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