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