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