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(nullptr, 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 nullptr;
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)
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) {
00498     markAnythingOverdefined(&I);
00499   }
00500   void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
00501   void visitAllocaInst    (Instruction &I) { markOverdefined(&I); }
00502   void visitVAArgInst     (Instruction &I) { markAnythingOverdefined(&I); }
00503 
00504   void visitInstruction(Instruction &I) {
00505     // If a new instruction is added to LLVM that we don't handle.
00506     dbgs() << "SCCP: Don't know how to handle: " << I << '\n';
00507     markAnythingOverdefined(&I);   // Just in case
00508   }
00509 };
00510 
00511 } // end anonymous namespace
00512 
00513 
00514 // getFeasibleSuccessors - Return a vector of booleans to indicate which
00515 // successors are reachable from a given terminator instruction.
00516 //
00517 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
00518                                        SmallVectorImpl<bool> &Succs) {
00519   Succs.resize(TI.getNumSuccessors());
00520   if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
00521     if (BI->isUnconditional()) {
00522       Succs[0] = true;
00523       return;
00524     }
00525 
00526     LatticeVal BCValue = getValueState(BI->getCondition());
00527     ConstantInt *CI = BCValue.getConstantInt();
00528     if (!CI) {
00529       // Overdefined condition variables, and branches on unfoldable constant
00530       // conditions, mean the branch could go either way.
00531       if (!BCValue.isUndefined())
00532         Succs[0] = Succs[1] = true;
00533       return;
00534     }
00535 
00536     // Constant condition variables mean the branch can only go a single way.
00537     Succs[CI->isZero()] = true;
00538     return;
00539   }
00540 
00541   if (isa<InvokeInst>(TI)) {
00542     // Invoke instructions successors are always executable.
00543     Succs[0] = Succs[1] = true;
00544     return;
00545   }
00546 
00547   if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
00548     if (!SI->getNumCases()) {
00549       Succs[0] = true;
00550       return;
00551     }
00552     LatticeVal SCValue = getValueState(SI->getCondition());
00553     ConstantInt *CI = SCValue.getConstantInt();
00554 
00555     if (!CI) {   // Overdefined or undefined condition?
00556       // All destinations are executable!
00557       if (!SCValue.isUndefined())
00558         Succs.assign(TI.getNumSuccessors(), true);
00559       return;
00560     }
00561 
00562     Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
00563     return;
00564   }
00565 
00566   // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
00567   if (isa<IndirectBrInst>(&TI)) {
00568     // Just mark all destinations executable!
00569     Succs.assign(TI.getNumSuccessors(), true);
00570     return;
00571   }
00572 
00573 #ifndef NDEBUG
00574   dbgs() << "Unknown terminator instruction: " << TI << '\n';
00575 #endif
00576   llvm_unreachable("SCCP: Don't know how to handle this terminator!");
00577 }
00578 
00579 
00580 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
00581 // block to the 'To' basic block is currently feasible.
00582 //
00583 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
00584   assert(BBExecutable.count(To) && "Dest should always be alive!");
00585 
00586   // Make sure the source basic block is executable!!
00587   if (!BBExecutable.count(From)) return false;
00588 
00589   // Check to make sure this edge itself is actually feasible now.
00590   TerminatorInst *TI = From->getTerminator();
00591   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
00592     if (BI->isUnconditional())
00593       return true;
00594 
00595     LatticeVal BCValue = getValueState(BI->getCondition());
00596 
00597     // Overdefined condition variables mean the branch could go either way,
00598     // undef conditions mean that neither edge is feasible yet.
00599     ConstantInt *CI = BCValue.getConstantInt();
00600     if (!CI)
00601       return !BCValue.isUndefined();
00602 
00603     // Constant condition variables mean the branch can only go a single way.
00604     return BI->getSuccessor(CI->isZero()) == To;
00605   }
00606 
00607   // Invoke instructions successors are always executable.
00608   if (isa<InvokeInst>(TI))
00609     return true;
00610 
00611   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00612     if (SI->getNumCases() < 1)
00613       return true;
00614 
00615     LatticeVal SCValue = getValueState(SI->getCondition());
00616     ConstantInt *CI = SCValue.getConstantInt();
00617 
00618     if (!CI)
00619       return !SCValue.isUndefined();
00620 
00621     return SI->findCaseValue(CI).getCaseSuccessor() == To;
00622   }
00623 
00624   // Just mark all destinations executable!
00625   // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
00626   if (isa<IndirectBrInst>(TI))
00627     return true;
00628 
00629 #ifndef NDEBUG
00630   dbgs() << "Unknown terminator instruction: " << *TI << '\n';
00631 #endif
00632   llvm_unreachable(nullptr);
00633 }
00634 
00635 // visit Implementations - Something changed in this instruction, either an
00636 // operand made a transition, or the instruction is newly executable.  Change
00637 // the value type of I to reflect these changes if appropriate.  This method
00638 // makes sure to do the following actions:
00639 //
00640 // 1. If a phi node merges two constants in, and has conflicting value coming
00641 //    from different branches, or if the PHI node merges in an overdefined
00642 //    value, then the PHI node becomes overdefined.
00643 // 2. If a phi node merges only constants in, and they all agree on value, the
00644 //    PHI node becomes a constant value equal to that.
00645 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
00646 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
00647 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
00648 // 6. If a conditional branch has a value that is constant, make the selected
00649 //    destination executable
00650 // 7. If a conditional branch has a value that is overdefined, make all
00651 //    successors executable.
00652 //
00653 void SCCPSolver::visitPHINode(PHINode &PN) {
00654   // If this PN returns a struct, just mark the result overdefined.
00655   // TODO: We could do a lot better than this if code actually uses this.
00656   if (PN.getType()->isStructTy())
00657     return markAnythingOverdefined(&PN);
00658 
00659   if (getValueState(&PN).isOverdefined())
00660     return;  // Quick exit
00661 
00662   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
00663   // and slow us down a lot.  Just mark them overdefined.
00664   if (PN.getNumIncomingValues() > 64)
00665     return markOverdefined(&PN);
00666 
00667   // Look at all of the executable operands of the PHI node.  If any of them
00668   // are overdefined, the PHI becomes overdefined as well.  If they are all
00669   // constant, and they agree with each other, the PHI becomes the identical
00670   // constant.  If they are constant and don't agree, the PHI is overdefined.
00671   // If there are no executable operands, the PHI remains undefined.
00672   //
00673   Constant *OperandVal = nullptr;
00674   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
00675     LatticeVal IV = getValueState(PN.getIncomingValue(i));
00676     if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
00677 
00678     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
00679       continue;
00680 
00681     if (IV.isOverdefined())    // PHI node becomes overdefined!
00682       return markOverdefined(&PN);
00683 
00684     if (!OperandVal) {   // Grab the first value.
00685       OperandVal = IV.getConstant();
00686       continue;
00687     }
00688 
00689     // There is already a reachable operand.  If we conflict with it,
00690     // then the PHI node becomes overdefined.  If we agree with it, we
00691     // can continue on.
00692 
00693     // Check to see if there are two different constants merging, if so, the PHI
00694     // node is overdefined.
00695     if (IV.getConstant() != OperandVal)
00696       return markOverdefined(&PN);
00697   }
00698 
00699   // If we exited the loop, this means that the PHI node only has constant
00700   // arguments that agree with each other(and OperandVal is the constant) or
00701   // OperandVal is null because there are no defined incoming arguments.  If
00702   // this is the case, the PHI remains undefined.
00703   //
00704   if (OperandVal)
00705     markConstant(&PN, OperandVal);      // Acquire operand value
00706 }
00707 
00708 void SCCPSolver::visitReturnInst(ReturnInst &I) {
00709   if (I.getNumOperands() == 0) return;  // ret void
00710 
00711   Function *F = I.getParent()->getParent();
00712   Value *ResultOp = I.getOperand(0);
00713 
00714   // If we are tracking the return value of this function, merge it in.
00715   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
00716     DenseMap<Function*, LatticeVal>::iterator TFRVI =
00717       TrackedRetVals.find(F);
00718     if (TFRVI != TrackedRetVals.end()) {
00719       mergeInValue(TFRVI->second, F, getValueState(ResultOp));
00720       return;
00721     }
00722   }
00723 
00724   // Handle functions that return multiple values.
00725   if (!TrackedMultipleRetVals.empty()) {
00726     if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
00727       if (MRVFunctionsTracked.count(F))
00728         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
00729           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
00730                        getStructValueState(ResultOp, i));
00731 
00732   }
00733 }
00734 
00735 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
00736   SmallVector<bool, 16> SuccFeasible;
00737   getFeasibleSuccessors(TI, SuccFeasible);
00738 
00739   BasicBlock *BB = TI.getParent();
00740 
00741   // Mark all feasible successors executable.
00742   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
00743     if (SuccFeasible[i])
00744       markEdgeExecutable(BB, TI.getSuccessor(i));
00745 }
00746 
00747 void SCCPSolver::visitCastInst(CastInst &I) {
00748   LatticeVal OpSt = getValueState(I.getOperand(0));
00749   if (OpSt.isOverdefined())          // Inherit overdefinedness of operand
00750     markOverdefined(&I);
00751   else if (OpSt.isConstant())        // Propagate constant value
00752     markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
00753                                            OpSt.getConstant(), I.getType()));
00754 }
00755 
00756 
00757 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
00758   // If this returns a struct, mark all elements over defined, we don't track
00759   // structs in structs.
00760   if (EVI.getType()->isStructTy())
00761     return markAnythingOverdefined(&EVI);
00762 
00763   // If this is extracting from more than one level of struct, we don't know.
00764   if (EVI.getNumIndices() != 1)
00765     return markOverdefined(&EVI);
00766 
00767   Value *AggVal = EVI.getAggregateOperand();
00768   if (AggVal->getType()->isStructTy()) {
00769     unsigned i = *EVI.idx_begin();
00770     LatticeVal EltVal = getStructValueState(AggVal, i);
00771     mergeInValue(getValueState(&EVI), &EVI, EltVal);
00772   } else {
00773     // Otherwise, must be extracting from an array.
00774     return markOverdefined(&EVI);
00775   }
00776 }
00777 
00778 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
00779   StructType *STy = dyn_cast<StructType>(IVI.getType());
00780   if (!STy)
00781     return markOverdefined(&IVI);
00782 
00783   // If this has more than one index, we can't handle it, drive all results to
00784   // undef.
00785   if (IVI.getNumIndices() != 1)
00786     return markAnythingOverdefined(&IVI);
00787 
00788   Value *Aggr = IVI.getAggregateOperand();
00789   unsigned Idx = *IVI.idx_begin();
00790 
00791   // Compute the result based on what we're inserting.
00792   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00793     // This passes through all values that aren't the inserted element.
00794     if (i != Idx) {
00795       LatticeVal EltVal = getStructValueState(Aggr, i);
00796       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
00797       continue;
00798     }
00799 
00800     Value *Val = IVI.getInsertedValueOperand();
00801     if (Val->getType()->isStructTy())
00802       // We don't track structs in structs.
00803       markOverdefined(getStructValueState(&IVI, i), &IVI);
00804     else {
00805       LatticeVal InVal = getValueState(Val);
00806       mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
00807     }
00808   }
00809 }
00810 
00811 void SCCPSolver::visitSelectInst(SelectInst &I) {
00812   // If this select returns a struct, just mark the result overdefined.
00813   // TODO: We could do a lot better than this if code actually uses this.
00814   if (I.getType()->isStructTy())
00815     return markAnythingOverdefined(&I);
00816 
00817   LatticeVal CondValue = getValueState(I.getCondition());
00818   if (CondValue.isUndefined())
00819     return;
00820 
00821   if (ConstantInt *CondCB = CondValue.getConstantInt()) {
00822     Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
00823     mergeInValue(&I, getValueState(OpVal));
00824     return;
00825   }
00826 
00827   // Otherwise, the condition is overdefined or a constant we can't evaluate.
00828   // See if we can produce something better than overdefined based on the T/F
00829   // value.
00830   LatticeVal TVal = getValueState(I.getTrueValue());
00831   LatticeVal FVal = getValueState(I.getFalseValue());
00832 
00833   // select ?, C, C -> C.
00834   if (TVal.isConstant() && FVal.isConstant() &&
00835       TVal.getConstant() == FVal.getConstant())
00836     return markConstant(&I, FVal.getConstant());
00837 
00838   if (TVal.isUndefined())   // select ?, undef, X -> X.
00839     return mergeInValue(&I, FVal);
00840   if (FVal.isUndefined())   // select ?, X, undef -> X.
00841     return mergeInValue(&I, TVal);
00842   markOverdefined(&I);
00843 }
00844 
00845 // Handle Binary Operators.
00846 void SCCPSolver::visitBinaryOperator(Instruction &I) {
00847   LatticeVal V1State = getValueState(I.getOperand(0));
00848   LatticeVal V2State = getValueState(I.getOperand(1));
00849 
00850   LatticeVal &IV = ValueState[&I];
00851   if (IV.isOverdefined()) return;
00852 
00853   if (V1State.isConstant() && V2State.isConstant())
00854     return markConstant(IV, &I,
00855                         ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
00856                                           V2State.getConstant()));
00857 
00858   // If something is undef, wait for it to resolve.
00859   if (!V1State.isOverdefined() && !V2State.isOverdefined())
00860     return;
00861 
00862   // Otherwise, one of our operands is overdefined.  Try to produce something
00863   // better than overdefined with some tricks.
00864 
00865   // If this is an AND or OR with 0 or -1, it doesn't matter that the other
00866   // operand is overdefined.
00867   if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
00868     LatticeVal *NonOverdefVal = nullptr;
00869     if (!V1State.isOverdefined())
00870       NonOverdefVal = &V1State;
00871     else if (!V2State.isOverdefined())
00872       NonOverdefVal = &V2State;
00873 
00874     if (NonOverdefVal) {
00875       if (NonOverdefVal->isUndefined()) {
00876         // Could annihilate value.
00877         if (I.getOpcode() == Instruction::And)
00878           markConstant(IV, &I, Constant::getNullValue(I.getType()));
00879         else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
00880           markConstant(IV, &I, Constant::getAllOnesValue(PT));
00881         else
00882           markConstant(IV, &I,
00883                        Constant::getAllOnesValue(I.getType()));
00884         return;
00885       }
00886 
00887       if (I.getOpcode() == Instruction::And) {
00888         // X and 0 = 0
00889         if (NonOverdefVal->getConstant()->isNullValue())
00890           return markConstant(IV, &I, NonOverdefVal->getConstant());
00891       } else {
00892         if (ConstantInt *CI = NonOverdefVal->getConstantInt())
00893           if (CI->isAllOnesValue())     // X or -1 = -1
00894             return markConstant(IV, &I, NonOverdefVal->getConstant());
00895       }
00896     }
00897   }
00898 
00899 
00900   markOverdefined(&I);
00901 }
00902 
00903 // Handle ICmpInst instruction.
00904 void SCCPSolver::visitCmpInst(CmpInst &I) {
00905   LatticeVal V1State = getValueState(I.getOperand(0));
00906   LatticeVal V2State = getValueState(I.getOperand(1));
00907 
00908   LatticeVal &IV = ValueState[&I];
00909   if (IV.isOverdefined()) return;
00910 
00911   if (V1State.isConstant() && V2State.isConstant())
00912     return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
00913                                                          V1State.getConstant(),
00914                                                         V2State.getConstant()));
00915 
00916   // If operands are still undefined, wait for it to resolve.
00917   if (!V1State.isOverdefined() && !V2State.isOverdefined())
00918     return;
00919 
00920   markOverdefined(&I);
00921 }
00922 
00923 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
00924   // TODO : SCCP does not handle vectors properly.
00925   return markOverdefined(&I);
00926 
00927 #if 0
00928   LatticeVal &ValState = getValueState(I.getOperand(0));
00929   LatticeVal &IdxState = getValueState(I.getOperand(1));
00930 
00931   if (ValState.isOverdefined() || IdxState.isOverdefined())
00932     markOverdefined(&I);
00933   else if(ValState.isConstant() && IdxState.isConstant())
00934     markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
00935                                                      IdxState.getConstant()));
00936 #endif
00937 }
00938 
00939 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
00940   // TODO : SCCP does not handle vectors properly.
00941   return markOverdefined(&I);
00942 #if 0
00943   LatticeVal &ValState = getValueState(I.getOperand(0));
00944   LatticeVal &EltState = getValueState(I.getOperand(1));
00945   LatticeVal &IdxState = getValueState(I.getOperand(2));
00946 
00947   if (ValState.isOverdefined() || EltState.isOverdefined() ||
00948       IdxState.isOverdefined())
00949     markOverdefined(&I);
00950   else if(ValState.isConstant() && EltState.isConstant() &&
00951           IdxState.isConstant())
00952     markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
00953                                                     EltState.getConstant(),
00954                                                     IdxState.getConstant()));
00955   else if (ValState.isUndefined() && EltState.isConstant() &&
00956            IdxState.isConstant())
00957     markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
00958                                                    EltState.getConstant(),
00959                                                    IdxState.getConstant()));
00960 #endif
00961 }
00962 
00963 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
00964   // TODO : SCCP does not handle vectors properly.
00965   return markOverdefined(&I);
00966 #if 0
00967   LatticeVal &V1State   = getValueState(I.getOperand(0));
00968   LatticeVal &V2State   = getValueState(I.getOperand(1));
00969   LatticeVal &MaskState = getValueState(I.getOperand(2));
00970 
00971   if (MaskState.isUndefined() ||
00972       (V1State.isUndefined() && V2State.isUndefined()))
00973     return;  // Undefined output if mask or both inputs undefined.
00974 
00975   if (V1State.isOverdefined() || V2State.isOverdefined() ||
00976       MaskState.isOverdefined()) {
00977     markOverdefined(&I);
00978   } else {
00979     // A mix of constant/undef inputs.
00980     Constant *V1 = V1State.isConstant() ?
00981         V1State.getConstant() : UndefValue::get(I.getType());
00982     Constant *V2 = V2State.isConstant() ?
00983         V2State.getConstant() : UndefValue::get(I.getType());
00984     Constant *Mask = MaskState.isConstant() ?
00985       MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
00986     markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
00987   }
00988 #endif
00989 }
00990 
00991 // Handle getelementptr instructions.  If all operands are constants then we
00992 // can turn this into a getelementptr ConstantExpr.
00993 //
00994 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
00995   if (ValueState[&I].isOverdefined()) return;
00996 
00997   SmallVector<Constant*, 8> Operands;
00998   Operands.reserve(I.getNumOperands());
00999 
01000   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
01001     LatticeVal State = getValueState(I.getOperand(i));
01002     if (State.isUndefined())
01003       return;  // Operands are not resolved yet.
01004 
01005     if (State.isOverdefined())
01006       return markOverdefined(&I);
01007 
01008     assert(State.isConstant() && "Unknown state!");
01009     Operands.push_back(State.getConstant());
01010   }
01011 
01012   Constant *Ptr = Operands[0];
01013   ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
01014   markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
01015 }
01016 
01017 void SCCPSolver::visitStoreInst(StoreInst &SI) {
01018   // If this store is of a struct, ignore it.
01019   if (SI.getOperand(0)->getType()->isStructTy())
01020     return;
01021 
01022   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
01023     return;
01024 
01025   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
01026   DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
01027   if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
01028 
01029   // Get the value we are storing into the global, then merge it.
01030   mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
01031   if (I->second.isOverdefined())
01032     TrackedGlobals.erase(I);      // No need to keep tracking this!
01033 }
01034 
01035 
01036 // Handle load instructions.  If the operand is a constant pointer to a constant
01037 // global, we can replace the load with the loaded constant value!
01038 void SCCPSolver::visitLoadInst(LoadInst &I) {
01039   // If this load is of a struct, just mark the result overdefined.
01040   if (I.getType()->isStructTy())
01041     return markAnythingOverdefined(&I);
01042 
01043   LatticeVal PtrVal = getValueState(I.getOperand(0));
01044   if (PtrVal.isUndefined()) return;   // The pointer is not resolved yet!
01045 
01046   LatticeVal &IV = ValueState[&I];
01047   if (IV.isOverdefined()) return;
01048 
01049   if (!PtrVal.isConstant() || I.isVolatile())
01050     return markOverdefined(IV, &I);
01051 
01052   Constant *Ptr = PtrVal.getConstant();
01053 
01054   // load null -> null
01055   if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
01056     return markConstant(IV, &I, Constant::getNullValue(I.getType()));
01057 
01058   // Transform load (constant global) into the value loaded.
01059   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
01060     if (!TrackedGlobals.empty()) {
01061       // If we are tracking this global, merge in the known value for it.
01062       DenseMap<GlobalVariable*, LatticeVal>::iterator It =
01063         TrackedGlobals.find(GV);
01064       if (It != TrackedGlobals.end()) {
01065         mergeInValue(IV, &I, It->second);
01066         return;
01067       }
01068     }
01069   }
01070 
01071   // Transform load from a constant into a constant if possible.
01072   if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, DL))
01073     return markConstant(IV, &I, C);
01074 
01075   // Otherwise we cannot say for certain what value this load will produce.
01076   // Bail out.
01077   markOverdefined(IV, &I);
01078 }
01079 
01080 void SCCPSolver::visitCallSite(CallSite CS) {
01081   Function *F = CS.getCalledFunction();
01082   Instruction *I = CS.getInstruction();
01083 
01084   // The common case is that we aren't tracking the callee, either because we
01085   // are not doing interprocedural analysis or the callee is indirect, or is
01086   // external.  Handle these cases first.
01087   if (!F || F->isDeclaration()) {
01088 CallOverdefined:
01089     // Void return and not tracking callee, just bail.
01090     if (I->getType()->isVoidTy()) return;
01091 
01092     // Otherwise, if we have a single return value case, and if the function is
01093     // a declaration, maybe we can constant fold it.
01094     if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
01095         canConstantFoldCallTo(F)) {
01096 
01097       SmallVector<Constant*, 8> Operands;
01098       for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
01099            AI != E; ++AI) {
01100         LatticeVal State = getValueState(*AI);
01101 
01102         if (State.isUndefined())
01103           return;  // Operands are not resolved yet.
01104         if (State.isOverdefined())
01105           return markOverdefined(I);
01106         assert(State.isConstant() && "Unknown state!");
01107         Operands.push_back(State.getConstant());
01108       }
01109 
01110       // If we can constant fold this, mark the result of the call as a
01111       // constant.
01112       if (Constant *C = ConstantFoldCall(F, Operands, TLI))
01113         return markConstant(I, C);
01114     }
01115 
01116     // Otherwise, we don't know anything about this call, mark it overdefined.
01117     return markAnythingOverdefined(I);
01118   }
01119 
01120   // If this is a local function that doesn't have its address taken, mark its
01121   // entry block executable and merge in the actual arguments to the call into
01122   // the formal arguments of the function.
01123   if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
01124     MarkBlockExecutable(F->begin());
01125 
01126     // Propagate information from this call site into the callee.
01127     CallSite::arg_iterator CAI = CS.arg_begin();
01128     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
01129          AI != E; ++AI, ++CAI) {
01130       // If this argument is byval, and if the function is not readonly, there
01131       // will be an implicit copy formed of the input aggregate.
01132       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
01133         markOverdefined(AI);
01134         continue;
01135       }
01136 
01137       if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
01138         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
01139           LatticeVal CallArg = getStructValueState(*CAI, i);
01140           mergeInValue(getStructValueState(AI, i), AI, CallArg);
01141         }
01142       } else {
01143         mergeInValue(AI, getValueState(*CAI));
01144       }
01145     }
01146   }
01147 
01148   // If this is a single/zero retval case, see if we're tracking the function.
01149   if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
01150     if (!MRVFunctionsTracked.count(F))
01151       goto CallOverdefined;  // Not tracking this callee.
01152 
01153     // If we are tracking this callee, propagate the result of the function
01154     // into this call site.
01155     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
01156       mergeInValue(getStructValueState(I, i), I,
01157                    TrackedMultipleRetVals[std::make_pair(F, i)]);
01158   } else {
01159     DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
01160     if (TFRVI == TrackedRetVals.end())
01161       goto CallOverdefined;  // Not tracking this callee.
01162 
01163     // If so, propagate the return value of the callee into this call result.
01164     mergeInValue(I, TFRVI->second);
01165   }
01166 }
01167 
01168 void SCCPSolver::Solve() {
01169   // Process the work lists until they are empty!
01170   while (!BBWorkList.empty() || !InstWorkList.empty() ||
01171          !OverdefinedInstWorkList.empty()) {
01172     // Process the overdefined instruction's work list first, which drives other
01173     // things to overdefined more quickly.
01174     while (!OverdefinedInstWorkList.empty()) {
01175       Value *I = OverdefinedInstWorkList.pop_back_val();
01176 
01177       DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
01178 
01179       // "I" got into the work list because it either made the transition from
01180       // bottom to constant, or to overdefined.
01181       //
01182       // Anything on this worklist that is overdefined need not be visited
01183       // since all of its users will have already been marked as overdefined
01184       // Update all of the users of this instruction's value.
01185       //
01186       for (User *U : I->users())
01187         if (Instruction *UI = dyn_cast<Instruction>(U))
01188           OperandChangedState(UI);
01189     }
01190 
01191     // Process the instruction work list.
01192     while (!InstWorkList.empty()) {
01193       Value *I = InstWorkList.pop_back_val();
01194 
01195       DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
01196 
01197       // "I" got into the work list because it made the transition from undef to
01198       // constant.
01199       //
01200       // Anything on this worklist that is overdefined need not be visited
01201       // since all of its users will have already been marked as overdefined.
01202       // Update all of the users of this instruction's value.
01203       //
01204       if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
01205         for (User *U : I->users())
01206           if (Instruction *UI = dyn_cast<Instruction>(U))
01207             OperandChangedState(UI);
01208     }
01209 
01210     // Process the basic block work list.
01211     while (!BBWorkList.empty()) {
01212       BasicBlock *BB = BBWorkList.back();
01213       BBWorkList.pop_back();
01214 
01215       DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
01216 
01217       // Notify all instructions in this basic block that they are newly
01218       // executable.
01219       visit(BB);
01220     }
01221   }
01222 }
01223 
01224 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
01225 /// that branches on undef values cannot reach any of their successors.
01226 /// However, this is not a safe assumption.  After we solve dataflow, this
01227 /// method should be use to handle this.  If this returns true, the solver
01228 /// should be rerun.
01229 ///
01230 /// This method handles this by finding an unresolved branch and marking it one
01231 /// of the edges from the block as being feasible, even though the condition
01232 /// doesn't say it would otherwise be.  This allows SCCP to find the rest of the
01233 /// CFG and only slightly pessimizes the analysis results (by marking one,
01234 /// potentially infeasible, edge feasible).  This cannot usefully modify the
01235 /// constraints on the condition of the branch, as that would impact other users
01236 /// of the value.
01237 ///
01238 /// This scan also checks for values that use undefs, whose results are actually
01239 /// defined.  For example, 'zext i8 undef to i32' should produce all zeros
01240 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
01241 /// even if X isn't defined.
01242 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
01243   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
01244     if (!BBExecutable.count(BB))
01245       continue;
01246 
01247     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
01248       // Look for instructions which produce undef values.
01249       if (I->getType()->isVoidTy()) continue;
01250 
01251       if (StructType *STy = dyn_cast<StructType>(I->getType())) {
01252         // Only a few things that can be structs matter for undef.
01253 
01254         // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
01255         if (CallSite CS = CallSite(I))
01256           if (Function *F = CS.getCalledFunction())
01257             if (MRVFunctionsTracked.count(F))
01258               continue;
01259 
01260         // extractvalue and insertvalue don't need to be marked; they are
01261         // tracked as precisely as their operands.
01262         if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
01263           continue;
01264 
01265         // Send the results of everything else to overdefined.  We could be
01266         // more precise than this but it isn't worth bothering.
01267         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
01268           LatticeVal &LV = getStructValueState(I, i);
01269           if (LV.isUndefined())
01270             markOverdefined(LV, I);
01271         }
01272         continue;
01273       }
01274 
01275       LatticeVal &LV = getValueState(I);
01276       if (!LV.isUndefined()) continue;
01277 
01278       // extractvalue is safe; check here because the argument is a struct.
01279       if (isa<ExtractValueInst>(I))
01280         continue;
01281 
01282       // Compute the operand LatticeVals, for convenience below.
01283       // Anything taking a struct is conservatively assumed to require
01284       // overdefined markings.
01285       if (I->getOperand(0)->getType()->isStructTy()) {
01286         markOverdefined(I);
01287         return true;
01288       }
01289       LatticeVal Op0LV = getValueState(I->getOperand(0));
01290       LatticeVal Op1LV;
01291       if (I->getNumOperands() == 2) {
01292         if (I->getOperand(1)->getType()->isStructTy()) {
01293           markOverdefined(I);
01294           return true;
01295         }
01296 
01297         Op1LV = getValueState(I->getOperand(1));
01298       }
01299       // If this is an instructions whose result is defined even if the input is
01300       // not fully defined, propagate the information.
01301       Type *ITy = I->getType();
01302       switch (I->getOpcode()) {
01303       case Instruction::Add:
01304       case Instruction::Sub:
01305       case Instruction::Trunc:
01306       case Instruction::FPTrunc:
01307       case Instruction::BitCast:
01308         break; // Any undef -> undef
01309       case Instruction::FSub:
01310       case Instruction::FAdd:
01311       case Instruction::FMul:
01312       case Instruction::FDiv:
01313       case Instruction::FRem:
01314         // Floating-point binary operation: be conservative.
01315         if (Op0LV.isUndefined() && Op1LV.isUndefined())
01316           markForcedConstant(I, Constant::getNullValue(ITy));
01317         else
01318           markOverdefined(I);
01319         return true;
01320       case Instruction::ZExt:
01321       case Instruction::SExt:
01322       case Instruction::FPToUI:
01323       case Instruction::FPToSI:
01324       case Instruction::FPExt:
01325       case Instruction::PtrToInt:
01326       case Instruction::IntToPtr:
01327       case Instruction::SIToFP:
01328       case Instruction::UIToFP:
01329         // undef -> 0; some outputs are impossible
01330         markForcedConstant(I, Constant::getNullValue(ITy));
01331         return true;
01332       case Instruction::Mul:
01333       case Instruction::And:
01334         // Both operands undef -> undef
01335         if (Op0LV.isUndefined() && Op1LV.isUndefined())
01336           break;
01337         // undef * X -> 0.   X could be zero.
01338         // undef & X -> 0.   X could be zero.
01339         markForcedConstant(I, Constant::getNullValue(ITy));
01340         return true;
01341 
01342       case Instruction::Or:
01343         // Both operands undef -> undef
01344         if (Op0LV.isUndefined() && Op1LV.isUndefined())
01345           break;
01346         // undef | X -> -1.   X could be -1.
01347         markForcedConstant(I, Constant::getAllOnesValue(ITy));
01348         return true;
01349 
01350       case Instruction::Xor:
01351         // undef ^ undef -> 0; strictly speaking, this is not strictly
01352         // necessary, but we try to be nice to people who expect this
01353         // behavior in simple cases
01354         if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
01355           markForcedConstant(I, Constant::getNullValue(ITy));
01356           return true;
01357         }
01358         // undef ^ X -> undef
01359         break;
01360 
01361       case Instruction::SDiv:
01362       case Instruction::UDiv:
01363       case Instruction::SRem:
01364       case Instruction::URem:
01365         // X / undef -> undef.  No change.
01366         // X % undef -> undef.  No change.
01367         if (Op1LV.isUndefined()) break;
01368 
01369         // undef / X -> 0.   X could be maxint.
01370         // undef % X -> 0.   X could be 1.
01371         markForcedConstant(I, Constant::getNullValue(ITy));
01372         return true;
01373 
01374       case Instruction::AShr:
01375         // X >>a undef -> undef.
01376         if (Op1LV.isUndefined()) break;
01377 
01378         // undef >>a X -> all ones
01379         markForcedConstant(I, Constant::getAllOnesValue(ITy));
01380         return true;
01381       case Instruction::LShr:
01382       case Instruction::Shl:
01383         // X << undef -> undef.
01384         // X >> undef -> undef.
01385         if (Op1LV.isUndefined()) break;
01386 
01387         // undef << X -> 0
01388         // undef >> X -> 0
01389         markForcedConstant(I, Constant::getNullValue(ITy));
01390         return true;
01391       case Instruction::Select:
01392         Op1LV = getValueState(I->getOperand(1));
01393         // undef ? X : Y  -> X or Y.  There could be commonality between X/Y.
01394         if (Op0LV.isUndefined()) {
01395           if (!Op1LV.isConstant())  // Pick the constant one if there is any.
01396             Op1LV = getValueState(I->getOperand(2));
01397         } else if (Op1LV.isUndefined()) {
01398           // c ? undef : undef -> undef.  No change.
01399           Op1LV = getValueState(I->getOperand(2));
01400           if (Op1LV.isUndefined())
01401             break;
01402           // Otherwise, c ? undef : x -> x.
01403         } else {
01404           // Leave Op1LV as Operand(1)'s LatticeValue.
01405         }
01406 
01407         if (Op1LV.isConstant())
01408           markForcedConstant(I, Op1LV.getConstant());
01409         else
01410           markOverdefined(I);
01411         return true;
01412       case Instruction::Load:
01413         // A load here means one of two things: a load of undef from a global,
01414         // a load from an unknown pointer.  Either way, having it return undef
01415         // is okay.
01416         break;
01417       case Instruction::ICmp:
01418         // X == undef -> undef.  Other comparisons get more complicated.
01419         if (cast<ICmpInst>(I)->isEquality())
01420           break;
01421         markOverdefined(I);
01422         return true;
01423       case Instruction::Call:
01424       case Instruction::Invoke: {
01425         // There are two reasons a call can have an undef result
01426         // 1. It could be tracked.
01427         // 2. It could be constant-foldable.
01428         // Because of the way we solve return values, tracked calls must
01429         // never be marked overdefined in ResolvedUndefsIn.
01430         if (Function *F = CallSite(I).getCalledFunction())
01431           if (TrackedRetVals.count(F))
01432             break;
01433 
01434         // If the call is constant-foldable, we mark it overdefined because
01435         // we do not know what return values are valid.
01436         markOverdefined(I);
01437         return true;
01438       }
01439       default:
01440         // If we don't know what should happen here, conservatively mark it
01441         // overdefined.
01442         markOverdefined(I);
01443         return true;
01444       }
01445     }
01446 
01447     // Check to see if we have a branch or switch on an undefined value.  If so
01448     // we force the branch to go one way or the other to make the successor
01449     // values live.  It doesn't really matter which way we force it.
01450     TerminatorInst *TI = BB->getTerminator();
01451     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
01452       if (!BI->isConditional()) continue;
01453       if (!getValueState(BI->getCondition()).isUndefined())
01454         continue;
01455 
01456       // If the input to SCCP is actually branch on undef, fix the undef to
01457       // false.
01458       if (isa<UndefValue>(BI->getCondition())) {
01459         BI->setCondition(ConstantInt::getFalse(BI->getContext()));
01460         markEdgeExecutable(BB, TI->getSuccessor(1));
01461         return true;
01462       }
01463 
01464       // Otherwise, it is a branch on a symbolic value which is currently
01465       // considered to be undef.  Handle this by forcing the input value to the
01466       // branch to false.
01467       markForcedConstant(BI->getCondition(),
01468                          ConstantInt::getFalse(TI->getContext()));
01469       return true;
01470     }
01471 
01472     if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
01473       if (!SI->getNumCases())
01474         continue;
01475       if (!getValueState(SI->getCondition()).isUndefined())
01476         continue;
01477 
01478       // If the input to SCCP is actually switch on undef, fix the undef to
01479       // the first constant.
01480       if (isa<UndefValue>(SI->getCondition())) {
01481         SI->setCondition(SI->case_begin().getCaseValue());
01482         markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
01483         return true;
01484       }
01485 
01486       markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
01487       return true;
01488     }
01489   }
01490 
01491   return false;
01492 }
01493 
01494 
01495 namespace {
01496   //===--------------------------------------------------------------------===//
01497   //
01498   /// SCCP Class - This class uses the SCCPSolver to implement a per-function
01499   /// Sparse Conditional Constant Propagator.
01500   ///
01501   struct SCCP : public FunctionPass {
01502     void getAnalysisUsage(AnalysisUsage &AU) const override {
01503       AU.addRequired<TargetLibraryInfo>();
01504     }
01505     static char ID; // Pass identification, replacement for typeid
01506     SCCP() : FunctionPass(ID) {
01507       initializeSCCPPass(*PassRegistry::getPassRegistry());
01508     }
01509 
01510     // runOnFunction - Run the Sparse Conditional Constant Propagation
01511     // algorithm, and return true if the function was modified.
01512     //
01513     bool runOnFunction(Function &F) override;
01514   };
01515 } // end anonymous namespace
01516 
01517 char SCCP::ID = 0;
01518 INITIALIZE_PASS(SCCP, "sccp",
01519                 "Sparse Conditional Constant Propagation", false, false)
01520 
01521 // createSCCPPass - This is the public interface to this file.
01522 FunctionPass *llvm::createSCCPPass() {
01523   return new SCCP();
01524 }
01525 
01526 static void DeleteInstructionInBlock(BasicBlock *BB) {
01527   DEBUG(dbgs() << "  BasicBlock Dead:" << *BB);
01528   ++NumDeadBlocks;
01529 
01530   // Check to see if there are non-terminating instructions to delete.
01531   if (isa<TerminatorInst>(BB->begin()))
01532     return;
01533 
01534   // Delete the instructions backwards, as it has a reduced likelihood of having
01535   // to update as many def-use and use-def chains.
01536   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
01537   while (EndInst != BB->begin()) {
01538     // Delete the next to last instruction.
01539     BasicBlock::iterator I = EndInst;
01540     Instruction *Inst = --I;
01541     if (!Inst->use_empty())
01542       Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
01543     if (isa<LandingPadInst>(Inst)) {
01544       EndInst = Inst;
01545       continue;
01546     }
01547     BB->getInstList().erase(Inst);
01548     ++NumInstRemoved;
01549   }
01550 }
01551 
01552 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
01553 // and return true if the function was modified.
01554 //
01555 bool SCCP::runOnFunction(Function &F) {
01556   if (skipOptnoneFunction(F))
01557     return false;
01558 
01559   DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
01560   const DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01561   const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
01562   const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
01563   SCCPSolver Solver(DL, TLI);
01564 
01565   // Mark the first block of the function as being executable.
01566   Solver.MarkBlockExecutable(F.begin());
01567 
01568   // Mark all arguments to the function as being overdefined.
01569   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
01570     Solver.markAnythingOverdefined(AI);
01571 
01572   // Solve for constants.
01573   bool ResolvedUndefs = true;
01574   while (ResolvedUndefs) {
01575     Solver.Solve();
01576     DEBUG(dbgs() << "RESOLVING UNDEFs\n");
01577     ResolvedUndefs = Solver.ResolvedUndefsIn(F);
01578   }
01579 
01580   bool MadeChanges = false;
01581 
01582   // If we decided that there are basic blocks that are dead in this function,
01583   // delete their contents now.  Note that we cannot actually delete the blocks,
01584   // as we cannot modify the CFG of the function.
01585 
01586   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
01587     if (!Solver.isBlockExecutable(BB)) {
01588       DeleteInstructionInBlock(BB);
01589       MadeChanges = true;
01590       continue;
01591     }
01592 
01593     // Iterate over all of the instructions in a function, replacing them with
01594     // constants if we have found them to be of constant values.
01595     //
01596     for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
01597       Instruction *Inst = BI++;
01598       if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
01599         continue;
01600 
01601       // TODO: Reconstruct structs from their elements.
01602       if (Inst->getType()->isStructTy())
01603         continue;
01604 
01605       LatticeVal IV = Solver.getLatticeValueFor(Inst);
01606       if (IV.isOverdefined())
01607         continue;
01608 
01609       Constant *Const = IV.isConstant()
01610         ? IV.getConstant() : UndefValue::get(Inst->getType());
01611       DEBUG(dbgs() << "  Constant: " << *Const << " = " << *Inst << '\n');
01612 
01613       // Replaces all of the uses of a variable with uses of the constant.
01614       Inst->replaceAllUsesWith(Const);
01615 
01616       // Delete the instruction.
01617       Inst->eraseFromParent();
01618 
01619       // Hey, we just changed something!
01620       MadeChanges = true;
01621       ++NumInstRemoved;
01622     }
01623   }
01624 
01625   return MadeChanges;
01626 }
01627 
01628 namespace {
01629   //===--------------------------------------------------------------------===//
01630   //
01631   /// IPSCCP Class - This class implements interprocedural Sparse Conditional
01632   /// Constant Propagation.
01633   ///
01634   struct IPSCCP : public ModulePass {
01635     void getAnalysisUsage(AnalysisUsage &AU) const override {
01636       AU.addRequired<TargetLibraryInfo>();
01637     }
01638     static char ID;
01639     IPSCCP() : ModulePass(ID) {
01640       initializeIPSCCPPass(*PassRegistry::getPassRegistry());
01641     }
01642     bool runOnModule(Module &M) override;
01643   };
01644 } // end anonymous namespace
01645 
01646 char IPSCCP::ID = 0;
01647 INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
01648                 "Interprocedural Sparse Conditional Constant Propagation",
01649                 false, false)
01650 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
01651 INITIALIZE_PASS_END(IPSCCP, "ipsccp",
01652                 "Interprocedural Sparse Conditional Constant Propagation",
01653                 false, false)
01654 
01655 // createIPSCCPPass - This is the public interface to this file.
01656 ModulePass *llvm::createIPSCCPPass() {
01657   return new IPSCCP();
01658 }
01659 
01660 
01661 static bool AddressIsTaken(const GlobalValue *GV) {
01662   // Delete any dead constantexpr klingons.
01663   GV->removeDeadConstantUsers();
01664 
01665   for (const Use &U : GV->uses()) {
01666     const User *UR = U.getUser();
01667     if (const StoreInst *SI = dyn_cast<StoreInst>(UR)) {
01668       if (SI->getOperand(0) == GV || SI->isVolatile())
01669         return true;  // Storing addr of GV.
01670     } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
01671       // Make sure we are calling the function, not passing the address.
01672       ImmutableCallSite CS(cast<Instruction>(UR));
01673       if (!CS.isCallee(&U))
01674         return true;
01675     } else if (const LoadInst *LI = dyn_cast<LoadInst>(UR)) {
01676       if (LI->isVolatile())
01677         return true;
01678     } else if (isa<BlockAddress>(UR)) {
01679       // blockaddress doesn't take the address of the function, it takes addr
01680       // of label.
01681     } else {
01682       return true;
01683     }
01684   }
01685   return false;
01686 }
01687 
01688 bool IPSCCP::runOnModule(Module &M) {
01689   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01690   const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
01691   const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
01692   SCCPSolver Solver(DL, TLI);
01693 
01694   // AddressTakenFunctions - This set keeps track of the address-taken functions
01695   // that are in the input.  As IPSCCP runs through and simplifies code,
01696   // functions that were address taken can end up losing their
01697   // address-taken-ness.  Because of this, we keep track of their addresses from
01698   // the first pass so we can use them for the later simplification pass.
01699   SmallPtrSet<Function*, 32> AddressTakenFunctions;
01700 
01701   // Loop over all functions, marking arguments to those with their addresses
01702   // taken or that are external as overdefined.
01703   //
01704   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
01705     if (F->isDeclaration())
01706       continue;
01707 
01708     // If this is a strong or ODR definition of this function, then we can
01709     // propagate information about its result into callsites of it.
01710     if (!F->mayBeOverridden())
01711       Solver.AddTrackedFunction(F);
01712 
01713     // If this function only has direct calls that we can see, we can track its
01714     // arguments and return value aggressively, and can assume it is not called
01715     // unless we see evidence to the contrary.
01716     if (F->hasLocalLinkage()) {
01717       if (AddressIsTaken(F))
01718         AddressTakenFunctions.insert(F);
01719       else {
01720         Solver.AddArgumentTrackedFunction(F);
01721         continue;
01722       }
01723     }
01724 
01725     // Assume the function is called.
01726     Solver.MarkBlockExecutable(F->begin());
01727 
01728     // Assume nothing about the incoming arguments.
01729     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
01730          AI != E; ++AI)
01731       Solver.markAnythingOverdefined(AI);
01732   }
01733 
01734   // Loop over global variables.  We inform the solver about any internal global
01735   // variables that do not have their 'addresses taken'.  If they don't have
01736   // their addresses taken, we can propagate constants through them.
01737   for (Module::global_iterator G = M.global_begin(), E = M.global_end();
01738        G != E; ++G)
01739     if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
01740       Solver.TrackValueOfGlobalVariable(G);
01741 
01742   // Solve for constants.
01743   bool ResolvedUndefs = true;
01744   while (ResolvedUndefs) {
01745     Solver.Solve();
01746 
01747     DEBUG(dbgs() << "RESOLVING UNDEFS\n");
01748     ResolvedUndefs = false;
01749     for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
01750       ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
01751   }
01752 
01753   bool MadeChanges = false;
01754 
01755   // Iterate over all of the instructions in the module, replacing them with
01756   // constants if we have found them to be of constant values.
01757   //
01758   SmallVector<BasicBlock*, 512> BlocksToErase;
01759 
01760   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
01761     if (Solver.isBlockExecutable(F->begin())) {
01762       for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
01763            AI != E; ++AI) {
01764         if (AI->use_empty() || AI->getType()->isStructTy()) continue;
01765 
01766         // TODO: Could use getStructLatticeValueFor to find out if the entire
01767         // result is a constant and replace it entirely if so.
01768 
01769         LatticeVal IV = Solver.getLatticeValueFor(AI);
01770         if (IV.isOverdefined()) continue;
01771 
01772         Constant *CST = IV.isConstant() ?
01773         IV.getConstant() : UndefValue::get(AI->getType());
01774         DEBUG(dbgs() << "***  Arg " << *AI << " = " << *CST <<"\n");
01775 
01776         // Replaces all of the uses of a variable with uses of the
01777         // constant.
01778         AI->replaceAllUsesWith(CST);
01779         ++IPNumArgsElimed;
01780       }
01781     }
01782 
01783     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
01784       if (!Solver.isBlockExecutable(BB)) {
01785         DeleteInstructionInBlock(BB);
01786         MadeChanges = true;
01787 
01788         TerminatorInst *TI = BB->getTerminator();
01789         for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
01790           BasicBlock *Succ = TI->getSuccessor(i);
01791           if (!Succ->empty() && isa<PHINode>(Succ->begin()))
01792             TI->getSuccessor(i)->removePredecessor(BB);
01793         }
01794         if (!TI->use_empty())
01795           TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
01796         TI->eraseFromParent();
01797 
01798         if (&*BB != &F->front())
01799           BlocksToErase.push_back(BB);
01800         else
01801           new UnreachableInst(M.getContext(), BB);
01802         continue;
01803       }
01804 
01805       for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
01806         Instruction *Inst = BI++;
01807         if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
01808           continue;
01809 
01810         // TODO: Could use getStructLatticeValueFor to find out if the entire
01811         // result is a constant and replace it entirely if so.
01812 
01813         LatticeVal IV = Solver.getLatticeValueFor(Inst);
01814         if (IV.isOverdefined())
01815           continue;
01816 
01817         Constant *Const = IV.isConstant()
01818           ? IV.getConstant() : UndefValue::get(Inst->getType());
01819         DEBUG(dbgs() << "  Constant: " << *Const << " = " << *Inst << '\n');
01820 
01821         // Replaces all of the uses of a variable with uses of the
01822         // constant.
01823         Inst->replaceAllUsesWith(Const);
01824 
01825         // Delete the instruction.
01826         if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
01827           Inst->eraseFromParent();
01828 
01829         // Hey, we just changed something!
01830         MadeChanges = true;
01831         ++IPNumInstRemoved;
01832       }
01833     }
01834 
01835     // Now that all instructions in the function are constant folded, erase dead
01836     // blocks, because we can now use ConstantFoldTerminator to get rid of
01837     // in-edges.
01838     for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
01839       // If there are any PHI nodes in this successor, drop entries for BB now.
01840       BasicBlock *DeadBB = BlocksToErase[i];
01841       for (Value::user_iterator UI = DeadBB->user_begin(),
01842                                 UE = DeadBB->user_end();
01843            UI != UE;) {
01844         // Grab the user and then increment the iterator early, as the user
01845         // will be deleted. Step past all adjacent uses from the same user.
01846         Instruction *I = dyn_cast<Instruction>(*UI);
01847         do { ++UI; } while (UI != UE && *UI == I);
01848 
01849         // Ignore blockaddress users; BasicBlock's dtor will handle them.
01850         if (!I) continue;
01851 
01852         bool Folded = ConstantFoldTerminator(I->getParent());
01853         if (!Folded) {
01854           // The constant folder may not have been able to fold the terminator
01855           // if this is a branch or switch on undef.  Fold it manually as a
01856           // branch to the first successor.
01857 #ifndef NDEBUG
01858           if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
01859             assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
01860                    "Branch should be foldable!");
01861           } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
01862             assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
01863           } else {
01864             llvm_unreachable("Didn't fold away reference to block!");
01865           }
01866 #endif
01867 
01868           // Make this an uncond branch to the first successor.
01869           TerminatorInst *TI = I->getParent()->getTerminator();
01870           BranchInst::Create(TI->getSuccessor(0), TI);
01871 
01872           // Remove entries in successor phi nodes to remove edges.
01873           for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
01874             TI->getSuccessor(i)->removePredecessor(TI->getParent());
01875 
01876           // Remove the old terminator.
01877           TI->eraseFromParent();
01878         }
01879       }
01880 
01881       // Finally, delete the basic block.
01882       F->getBasicBlockList().erase(DeadBB);
01883     }
01884     BlocksToErase.clear();
01885   }
01886 
01887   // If we inferred constant or undef return values for a function, we replaced
01888   // all call uses with the inferred value.  This means we don't need to bother
01889   // actually returning anything from the function.  Replace all return
01890   // instructions with return undef.
01891   //
01892   // Do this in two stages: first identify the functions we should process, then
01893   // actually zap their returns.  This is important because we can only do this
01894   // if the address of the function isn't taken.  In cases where a return is the
01895   // last use of a function, the order of processing functions would affect
01896   // whether other functions are optimizable.
01897   SmallVector<ReturnInst*, 8> ReturnsToZap;
01898 
01899   // TODO: Process multiple value ret instructions also.
01900   const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
01901   for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
01902        E = RV.end(); I != E; ++I) {
01903     Function *F = I->first;
01904     if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
01905       continue;
01906 
01907     // We can only do this if we know that nothing else can call the function.
01908     if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
01909       continue;
01910 
01911     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
01912       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
01913         if (!isa<UndefValue>(RI->getOperand(0)))
01914           ReturnsToZap.push_back(RI);
01915   }
01916 
01917   // Zap all returns which we've identified as zap to change.
01918   for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
01919     Function *F = ReturnsToZap[i]->getParent()->getParent();
01920     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
01921   }
01922 
01923   // If we inferred constant or undef values for globals variables, we can
01924   // delete the global and any stores that remain to it.
01925   const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
01926   for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
01927          E = TG.end(); I != E; ++I) {
01928     GlobalVariable *GV = I->first;
01929     assert(!I->second.isOverdefined() &&
01930            "Overdefined values should have been taken out of the map!");
01931     DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
01932     while (!GV->use_empty()) {
01933       StoreInst *SI = cast<StoreInst>(GV->user_back());
01934       SI->eraseFromParent();
01935     }
01936     M.getGlobalList().erase(GV);
01937     ++IPNumGlobalConst;
01938   }
01939 
01940   return MadeChanges;
01941 }