1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements sparse conditional constant propagation and merging:
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
18 //===----------------------------------------------------------------------===//
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"
47 STATISTIC(NumInstRemoved, "Number of instructions removed");
48 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
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");
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.
60 /// undefined - This LLVM Value has no known value yet.
63 /// constant - This LLVM Value has a specific constant value.
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
72 /// overdefined - This instruction is not known to be constant, and we know
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;
81 LatticeValueTy getLatticeValue() const {
86 LatticeVal() : Val(0, undefined) {}
88 bool isUndefined() const { return getLatticeValue() == undefined; }
89 bool isConstant() const {
90 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
92 bool isOverdefined() const { return getLatticeValue() == overdefined; }
94 Constant *getConstant() const {
95 assert(isConstant() && "Cannot get the constant of a non-constant!");
96 return Val.getPointer();
99 /// markOverdefined - Return true if this is a change in status.
100 bool markOverdefined() {
104 Val.setInt(overdefined);
108 /// markConstant - Return true if this is a change in status.
109 bool markConstant(Constant *V) {
110 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
111 assert(getConstant() == V && "Marking constant with different value");
116 Val.setInt(constant);
117 assert(V && "Marking constant with NULL");
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;
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);
133 /// getConstantInt - If this is a constant with a ConstantInt value, return it
134 /// otherwise return null.
135 ConstantInt *getConstantInt() const {
137 return dyn_cast<ConstantInt>(getConstant());
141 void markForcedConstant(Constant *V) {
142 assert(isUndefined() && "Can't force a defined value!");
143 Val.setInt(forcedconstant);
147 } // end anonymous namespace.
152 //===----------------------------------------------------------------------===//
154 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
155 /// Constant Propagation.
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.
162 /// StructValueState - This maintains ValueState for values that have
163 /// StructType, for example for formal arguments, calls, insertelement, etc.
165 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
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;
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;
178 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
179 /// that return multiple values.
180 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
182 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
183 /// represented here for efficient lookup.
184 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
186 /// TrackingIncomingArguments - This is the set of functions for whose
187 /// arguments we make optimistic assumptions about and try to prove as
189 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
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.
195 /// By having a separate worklist, we accomplish this because everything
196 /// possibly overdefined will become overdefined at the soonest possible
198 SmallVector<Value*, 64> OverdefinedInstWorkList;
199 SmallVector<Value*, 64> InstWorkList;
202 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
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;
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;
213 SCCPSolver(const TargetData *td) : TD(td) {}
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.
218 /// This returns true if the block was not considered live before.
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!
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.
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());
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.
242 void AddTrackedFunction(Function *F) {
243 // Add an entry, F -> undef.
244 if (const 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),
250 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
253 void AddArgumentTrackedFunction(Function *F) {
254 TrackingIncomingArguments.insert(F);
257 /// Solve - Solve for constants and executable blocks.
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
266 bool ResolvedUndefsIn(Function &F);
268 bool isBlockExecutable(BasicBlock *BB) const {
269 return BBExecutable.count(BB);
272 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!");
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!");
285 /// getTrackedRetVals - Get the inferred return value map.
287 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
288 return TrackedRetVals;
291 /// getTrackedGlobals - Get and return the set of inferred initializers for
292 /// global variables.
293 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
294 return TrackedGlobals;
297 void markOverdefined(Value *V) {
298 assert(!V->getType()->isStructTy() && "Should use other method");
299 markOverdefined(ValueState[V], V);
302 /// markAnythingOverdefined - Mark the specified value overdefined. This
303 /// works with both scalars and structs.
304 void markAnythingOverdefined(Value *V) {
305 if (const StructType *STy = dyn_cast<StructType>(V->getType()))
306 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
307 markOverdefined(getStructValueState(V, i), V);
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.
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);
323 InstWorkList.push_back(V);
326 void markConstant(Value *V, Constant *C) {
327 assert(!V->getType()->isStructTy() && "Should use other method");
328 markConstant(ValueState[V], V, 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);
339 InstWorkList.push_back(V);
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.
346 void markOverdefined(LatticeVal &IV, Value *V) {
347 if (!IV.markOverdefined()) return;
349 DEBUG(dbgs() << "markOverdefined: ";
350 if (Function *F = dyn_cast<Function>(V))
351 dbgs() << "Function '" << F->getName() << "'\n";
353 dbgs() << *V << '\n');
354 // Only instructions go on the work list
355 OverdefinedInstWorkList.push_back(V);
358 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
359 if (IV.isOverdefined() || MergeWithV.isUndefined())
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);
369 void mergeInValue(Value *V, LatticeVal MergeWithV) {
370 assert(!V->getType()->isStructTy() && "Should use other method");
371 mergeInValue(ValueState[V], V, MergeWithV);
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.
378 LatticeVal &getValueState(Value *V) {
379 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
381 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
382 ValueState.insert(std::make_pair(V, LatticeVal()));
383 LatticeVal &LV = I.first->second;
386 return LV; // Common case, already in the map.
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
394 // All others are underdefined by default.
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.
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 #");
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;
412 return LV; // Common case, already in the map.
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 const Type *FieldTy = cast<StructType>(V->getType())->getElementType(i);
421 LV.markConstant(Constant::getNullValue(FieldTy));
423 LV.markOverdefined(); // Unknown sort of constant.
426 // All others are underdefined by default.
431 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
432 /// work list if it is not already executable.
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!
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");
445 for (BasicBlock::iterator I = Dest->begin();
446 (PN = dyn_cast<PHINode>(I)); ++I)
451 // getFeasibleSuccessors - Return a vector of booleans to indicate which
452 // successors are reachable from a given terminator instruction.
454 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
456 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
457 // block to the 'To' basic block is currently feasible.
459 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
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.
465 void OperandChangedState(Instruction *I) {
466 if (BBExecutable.count(I->getParent())) // Inst is executable?
470 /// RemoveFromOverdefinedPHIs - If I has any entries in the
471 /// UsersOfOverdefinedPHIs map for PN, remove them now.
472 void RemoveFromOverdefinedPHIs(Instruction *I, PHINode *PN) {
473 if (UsersOfOverdefinedPHIs.empty()) return;
474 std::multimap<PHINode*, Instruction*>::iterator It, E;
475 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN);
478 UsersOfOverdefinedPHIs.erase(It++);
485 friend class InstVisitor<SCCPSolver>;
487 // visit implementations - Something changed in this instruction. Either an
488 // operand made a transition, or the instruction is newly executable. Change
489 // the value type of I to reflect these changes if appropriate.
490 void visitPHINode(PHINode &I);
493 void visitReturnInst(ReturnInst &I);
494 void visitTerminatorInst(TerminatorInst &TI);
496 void visitCastInst(CastInst &I);
497 void visitSelectInst(SelectInst &I);
498 void visitBinaryOperator(Instruction &I);
499 void visitCmpInst(CmpInst &I);
500 void visitExtractElementInst(ExtractElementInst &I);
501 void visitInsertElementInst(InsertElementInst &I);
502 void visitShuffleVectorInst(ShuffleVectorInst &I);
503 void visitExtractValueInst(ExtractValueInst &EVI);
504 void visitInsertValueInst(InsertValueInst &IVI);
506 // Instructions that cannot be folded away.
507 void visitStoreInst (StoreInst &I);
508 void visitLoadInst (LoadInst &I);
509 void visitGetElementPtrInst(GetElementPtrInst &I);
510 void visitCallInst (CallInst &I) {
511 visitCallSite(CallSite::get(&I));
513 void visitInvokeInst (InvokeInst &II) {
514 visitCallSite(CallSite::get(&II));
515 visitTerminatorInst(II);
517 void visitCallSite (CallSite CS);
518 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
519 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
520 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
521 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
522 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
524 void visitInstruction(Instruction &I) {
525 // If a new instruction is added to LLVM that we don't handle.
526 dbgs() << "SCCP: Don't know how to handle: " << I;
527 markAnythingOverdefined(&I); // Just in case
531 } // end anonymous namespace
534 // getFeasibleSuccessors - Return a vector of booleans to indicate which
535 // successors are reachable from a given terminator instruction.
537 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
538 SmallVector<bool, 16> &Succs) {
539 Succs.resize(TI.getNumSuccessors());
540 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
541 if (BI->isUnconditional()) {
546 LatticeVal BCValue = getValueState(BI->getCondition());
547 ConstantInt *CI = BCValue.getConstantInt();
549 // Overdefined condition variables, and branches on unfoldable constant
550 // conditions, mean the branch could go either way.
551 if (!BCValue.isUndefined())
552 Succs[0] = Succs[1] = true;
556 // Constant condition variables mean the branch can only go a single way.
557 Succs[CI->isZero()] = true;
561 if (isa<InvokeInst>(TI)) {
562 // Invoke instructions successors are always executable.
563 Succs[0] = Succs[1] = true;
567 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
568 LatticeVal SCValue = getValueState(SI->getCondition());
569 ConstantInt *CI = SCValue.getConstantInt();
571 if (CI == 0) { // Overdefined or undefined condition?
572 // All destinations are executable!
573 if (!SCValue.isUndefined())
574 Succs.assign(TI.getNumSuccessors(), true);
578 Succs[SI->findCaseValue(CI)] = true;
582 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
583 if (isa<IndirectBrInst>(&TI)) {
584 // Just mark all destinations executable!
585 Succs.assign(TI.getNumSuccessors(), true);
590 dbgs() << "Unknown terminator instruction: " << TI << '\n';
592 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
596 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
597 // block to the 'To' basic block is currently feasible.
599 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
600 assert(BBExecutable.count(To) && "Dest should always be alive!");
602 // Make sure the source basic block is executable!!
603 if (!BBExecutable.count(From)) return false;
605 // Check to make sure this edge itself is actually feasible now.
606 TerminatorInst *TI = From->getTerminator();
607 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
608 if (BI->isUnconditional())
611 LatticeVal BCValue = getValueState(BI->getCondition());
613 // Overdefined condition variables mean the branch could go either way,
614 // undef conditions mean that neither edge is feasible yet.
615 ConstantInt *CI = BCValue.getConstantInt();
617 return !BCValue.isUndefined();
619 // Constant condition variables mean the branch can only go a single way.
620 return BI->getSuccessor(CI->isZero()) == To;
623 // Invoke instructions successors are always executable.
624 if (isa<InvokeInst>(TI))
627 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
628 LatticeVal SCValue = getValueState(SI->getCondition());
629 ConstantInt *CI = SCValue.getConstantInt();
632 return !SCValue.isUndefined();
634 // Make sure to skip the "default value" which isn't a value
635 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
636 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
637 return SI->getSuccessor(i) == To;
639 // If the constant value is not equal to any of the branches, we must
640 // execute default branch.
641 return SI->getDefaultDest() == To;
644 // Just mark all destinations executable!
645 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
646 if (isa<IndirectBrInst>(&TI))
650 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
655 // visit Implementations - Something changed in this instruction, either an
656 // operand made a transition, or the instruction is newly executable. Change
657 // the value type of I to reflect these changes if appropriate. This method
658 // makes sure to do the following actions:
660 // 1. If a phi node merges two constants in, and has conflicting value coming
661 // from different branches, or if the PHI node merges in an overdefined
662 // value, then the PHI node becomes overdefined.
663 // 2. If a phi node merges only constants in, and they all agree on value, the
664 // PHI node becomes a constant value equal to that.
665 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
666 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
667 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
668 // 6. If a conditional branch has a value that is constant, make the selected
669 // destination executable
670 // 7. If a conditional branch has a value that is overdefined, make all
671 // successors executable.
673 void SCCPSolver::visitPHINode(PHINode &PN) {
674 // If this PN returns a struct, just mark the result overdefined.
675 // TODO: We could do a lot better than this if code actually uses this.
676 if (PN.getType()->isStructTy())
677 return markAnythingOverdefined(&PN);
679 if (getValueState(&PN).isOverdefined()) {
680 // There may be instructions using this PHI node that are not overdefined
681 // themselves. If so, make sure that they know that the PHI node operand
683 std::multimap<PHINode*, Instruction*>::iterator I, E;
684 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
688 SmallVector<Instruction*, 16> Users;
690 Users.push_back(I->second);
691 while (!Users.empty())
692 visit(Users.pop_back_val());
693 return; // Quick exit
696 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
697 // and slow us down a lot. Just mark them overdefined.
698 if (PN.getNumIncomingValues() > 64)
699 return markOverdefined(&PN);
701 // Look at all of the executable operands of the PHI node. If any of them
702 // are overdefined, the PHI becomes overdefined as well. If they are all
703 // constant, and they agree with each other, the PHI becomes the identical
704 // constant. If they are constant and don't agree, the PHI is overdefined.
705 // If there are no executable operands, the PHI remains undefined.
707 Constant *OperandVal = 0;
708 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
709 LatticeVal IV = getValueState(PN.getIncomingValue(i));
710 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
712 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
715 if (IV.isOverdefined()) // PHI node becomes overdefined!
716 return markOverdefined(&PN);
718 if (OperandVal == 0) { // Grab the first value.
719 OperandVal = IV.getConstant();
723 // There is already a reachable operand. If we conflict with it,
724 // then the PHI node becomes overdefined. If we agree with it, we
727 // Check to see if there are two different constants merging, if so, the PHI
728 // node is overdefined.
729 if (IV.getConstant() != OperandVal)
730 return markOverdefined(&PN);
733 // If we exited the loop, this means that the PHI node only has constant
734 // arguments that agree with each other(and OperandVal is the constant) or
735 // OperandVal is null because there are no defined incoming arguments. If
736 // this is the case, the PHI remains undefined.
739 markConstant(&PN, OperandVal); // Acquire operand value
745 void SCCPSolver::visitReturnInst(ReturnInst &I) {
746 if (I.getNumOperands() == 0) return; // ret void
748 Function *F = I.getParent()->getParent();
749 Value *ResultOp = I.getOperand(0);
751 // If we are tracking the return value of this function, merge it in.
752 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
753 DenseMap<Function*, LatticeVal>::iterator TFRVI =
754 TrackedRetVals.find(F);
755 if (TFRVI != TrackedRetVals.end()) {
756 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
761 // Handle functions that return multiple values.
762 if (!TrackedMultipleRetVals.empty()) {
763 if (const StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
764 if (MRVFunctionsTracked.count(F))
765 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
766 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
767 getStructValueState(ResultOp, i));
772 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
773 SmallVector<bool, 16> SuccFeasible;
774 getFeasibleSuccessors(TI, SuccFeasible);
776 BasicBlock *BB = TI.getParent();
778 // Mark all feasible successors executable.
779 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
781 markEdgeExecutable(BB, TI.getSuccessor(i));
784 void SCCPSolver::visitCastInst(CastInst &I) {
785 LatticeVal OpSt = getValueState(I.getOperand(0));
786 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
788 else if (OpSt.isConstant()) // Propagate constant value
789 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
790 OpSt.getConstant(), I.getType()));
794 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
795 // If this returns a struct, mark all elements over defined, we don't track
796 // structs in structs.
797 if (EVI.getType()->isStructTy())
798 return markAnythingOverdefined(&EVI);
800 // If this is extracting from more than one level of struct, we don't know.
801 if (EVI.getNumIndices() != 1)
802 return markOverdefined(&EVI);
804 Value *AggVal = EVI.getAggregateOperand();
805 if (AggVal->getType()->isStructTy()) {
806 unsigned i = *EVI.idx_begin();
807 LatticeVal EltVal = getStructValueState(AggVal, i);
808 mergeInValue(getValueState(&EVI), &EVI, EltVal);
810 // Otherwise, must be extracting from an array.
811 return markOverdefined(&EVI);
815 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
816 const StructType *STy = dyn_cast<StructType>(IVI.getType());
818 return markOverdefined(&IVI);
820 // If this has more than one index, we can't handle it, drive all results to
822 if (IVI.getNumIndices() != 1)
823 return markAnythingOverdefined(&IVI);
825 Value *Aggr = IVI.getAggregateOperand();
826 unsigned Idx = *IVI.idx_begin();
828 // Compute the result based on what we're inserting.
829 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
830 // This passes through all values that aren't the inserted element.
832 LatticeVal EltVal = getStructValueState(Aggr, i);
833 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
837 Value *Val = IVI.getInsertedValueOperand();
838 if (Val->getType()->isStructTy())
839 // We don't track structs in structs.
840 markOverdefined(getStructValueState(&IVI, i), &IVI);
842 LatticeVal InVal = getValueState(Val);
843 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
848 void SCCPSolver::visitSelectInst(SelectInst &I) {
849 // If this select returns a struct, just mark the result overdefined.
850 // TODO: We could do a lot better than this if code actually uses this.
851 if (I.getType()->isStructTy())
852 return markAnythingOverdefined(&I);
854 LatticeVal CondValue = getValueState(I.getCondition());
855 if (CondValue.isUndefined())
858 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
859 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
860 mergeInValue(&I, getValueState(OpVal));
864 // Otherwise, the condition is overdefined or a constant we can't evaluate.
865 // See if we can produce something better than overdefined based on the T/F
867 LatticeVal TVal = getValueState(I.getTrueValue());
868 LatticeVal FVal = getValueState(I.getFalseValue());
870 // select ?, C, C -> C.
871 if (TVal.isConstant() && FVal.isConstant() &&
872 TVal.getConstant() == FVal.getConstant())
873 return markConstant(&I, FVal.getConstant());
875 if (TVal.isUndefined()) // select ?, undef, X -> X.
876 return mergeInValue(&I, FVal);
877 if (FVal.isUndefined()) // select ?, X, undef -> X.
878 return mergeInValue(&I, TVal);
882 // Handle Binary Operators.
883 void SCCPSolver::visitBinaryOperator(Instruction &I) {
884 LatticeVal V1State = getValueState(I.getOperand(0));
885 LatticeVal V2State = getValueState(I.getOperand(1));
887 LatticeVal &IV = ValueState[&I];
888 if (IV.isOverdefined()) return;
890 if (V1State.isConstant() && V2State.isConstant())
891 return markConstant(IV, &I,
892 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
893 V2State.getConstant()));
895 // If something is undef, wait for it to resolve.
896 if (!V1State.isOverdefined() && !V2State.isOverdefined())
899 // Otherwise, one of our operands is overdefined. Try to produce something
900 // better than overdefined with some tricks.
902 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
903 // operand is overdefined.
904 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
905 LatticeVal *NonOverdefVal = 0;
906 if (!V1State.isOverdefined())
907 NonOverdefVal = &V1State;
908 else if (!V2State.isOverdefined())
909 NonOverdefVal = &V2State;
912 if (NonOverdefVal->isUndefined()) {
913 // Could annihilate value.
914 if (I.getOpcode() == Instruction::And)
915 markConstant(IV, &I, Constant::getNullValue(I.getType()));
916 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
917 markConstant(IV, &I, Constant::getAllOnesValue(PT));
920 Constant::getAllOnesValue(I.getType()));
924 if (I.getOpcode() == Instruction::And) {
926 if (NonOverdefVal->getConstant()->isNullValue())
927 return markConstant(IV, &I, NonOverdefVal->getConstant());
929 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
930 if (CI->isAllOnesValue()) // X or -1 = -1
931 return markConstant(IV, &I, NonOverdefVal->getConstant());
937 // If both operands are PHI nodes, it is possible that this instruction has
938 // a constant value, despite the fact that the PHI node doesn't. Check for
939 // this condition now.
940 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
941 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
942 if (PN1->getParent() == PN2->getParent()) {
943 // Since the two PHI nodes are in the same basic block, they must have
944 // entries for the same predecessors. Walk the predecessor list, and
945 // if all of the incoming values are constants, and the result of
946 // evaluating this expression with all incoming value pairs is the
947 // same, then this expression is a constant even though the PHI node
948 // is not a constant!
950 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
951 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
952 BasicBlock *InBlock = PN1->getIncomingBlock(i);
953 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
955 if (In1.isOverdefined() || In2.isOverdefined()) {
956 Result.markOverdefined();
957 break; // Cannot fold this operation over the PHI nodes!
960 if (In1.isConstant() && In2.isConstant()) {
961 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
963 if (Result.isUndefined())
964 Result.markConstant(V);
965 else if (Result.isConstant() && Result.getConstant() != V) {
966 Result.markOverdefined();
972 // If we found a constant value here, then we know the instruction is
973 // constant despite the fact that the PHI nodes are overdefined.
974 if (Result.isConstant()) {
975 markConstant(IV, &I, Result.getConstant());
976 // Remember that this instruction is virtually using the PHI node
978 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
979 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
983 if (Result.isUndefined())
986 // Okay, this really is overdefined now. Since we might have
987 // speculatively thought that this was not overdefined before, and
988 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
989 // make sure to clean out any entries that we put there, for
991 RemoveFromOverdefinedPHIs(&I, PN1);
992 RemoveFromOverdefinedPHIs(&I, PN2);
998 // Handle ICmpInst instruction.
999 void SCCPSolver::visitCmpInst(CmpInst &I) {
1000 LatticeVal V1State = getValueState(I.getOperand(0));
1001 LatticeVal V2State = getValueState(I.getOperand(1));
1003 LatticeVal &IV = ValueState[&I];
1004 if (IV.isOverdefined()) return;
1006 if (V1State.isConstant() && V2State.isConstant())
1007 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
1008 V1State.getConstant(),
1009 V2State.getConstant()));
1011 // If operands are still undefined, wait for it to resolve.
1012 if (!V1State.isOverdefined() && !V2State.isOverdefined())
1015 // If something is overdefined, use some tricks to avoid ending up and over
1016 // defined if we can.
1018 // If both operands are PHI nodes, it is possible that this instruction has
1019 // a constant value, despite the fact that the PHI node doesn't. Check for
1020 // this condition now.
1021 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
1022 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
1023 if (PN1->getParent() == PN2->getParent()) {
1024 // Since the two PHI nodes are in the same basic block, they must have
1025 // entries for the same predecessors. Walk the predecessor list, and
1026 // if all of the incoming values are constants, and the result of
1027 // evaluating this expression with all incoming value pairs is the
1028 // same, then this expression is a constant even though the PHI node
1029 // is not a constant!
1031 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
1032 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
1033 BasicBlock *InBlock = PN1->getIncomingBlock(i);
1034 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
1036 if (In1.isOverdefined() || In2.isOverdefined()) {
1037 Result.markOverdefined();
1038 break; // Cannot fold this operation over the PHI nodes!
1041 if (In1.isConstant() && In2.isConstant()) {
1042 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
1045 if (Result.isUndefined())
1046 Result.markConstant(V);
1047 else if (Result.isConstant() && Result.getConstant() != V) {
1048 Result.markOverdefined();
1054 // If we found a constant value here, then we know the instruction is
1055 // constant despite the fact that the PHI nodes are overdefined.
1056 if (Result.isConstant()) {
1057 markConstant(&I, Result.getConstant());
1058 // Remember that this instruction is virtually using the PHI node
1060 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
1061 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
1065 if (Result.isUndefined())
1068 // Okay, this really is overdefined now. Since we might have
1069 // speculatively thought that this was not overdefined before, and
1070 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1071 // make sure to clean out any entries that we put there, for
1073 RemoveFromOverdefinedPHIs(&I, PN1);
1074 RemoveFromOverdefinedPHIs(&I, PN2);
1077 markOverdefined(&I);
1080 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1081 // TODO : SCCP does not handle vectors properly.
1082 return markOverdefined(&I);
1085 LatticeVal &ValState = getValueState(I.getOperand(0));
1086 LatticeVal &IdxState = getValueState(I.getOperand(1));
1088 if (ValState.isOverdefined() || IdxState.isOverdefined())
1089 markOverdefined(&I);
1090 else if(ValState.isConstant() && IdxState.isConstant())
1091 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1092 IdxState.getConstant()));
1096 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1097 // TODO : SCCP does not handle vectors properly.
1098 return markOverdefined(&I);
1100 LatticeVal &ValState = getValueState(I.getOperand(0));
1101 LatticeVal &EltState = getValueState(I.getOperand(1));
1102 LatticeVal &IdxState = getValueState(I.getOperand(2));
1104 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1105 IdxState.isOverdefined())
1106 markOverdefined(&I);
1107 else if(ValState.isConstant() && EltState.isConstant() &&
1108 IdxState.isConstant())
1109 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1110 EltState.getConstant(),
1111 IdxState.getConstant()));
1112 else if (ValState.isUndefined() && EltState.isConstant() &&
1113 IdxState.isConstant())
1114 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1115 EltState.getConstant(),
1116 IdxState.getConstant()));
1120 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1121 // TODO : SCCP does not handle vectors properly.
1122 return markOverdefined(&I);
1124 LatticeVal &V1State = getValueState(I.getOperand(0));
1125 LatticeVal &V2State = getValueState(I.getOperand(1));
1126 LatticeVal &MaskState = getValueState(I.getOperand(2));
1128 if (MaskState.isUndefined() ||
1129 (V1State.isUndefined() && V2State.isUndefined()))
1130 return; // Undefined output if mask or both inputs undefined.
1132 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1133 MaskState.isOverdefined()) {
1134 markOverdefined(&I);
1136 // A mix of constant/undef inputs.
1137 Constant *V1 = V1State.isConstant() ?
1138 V1State.getConstant() : UndefValue::get(I.getType());
1139 Constant *V2 = V2State.isConstant() ?
1140 V2State.getConstant() : UndefValue::get(I.getType());
1141 Constant *Mask = MaskState.isConstant() ?
1142 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1143 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1148 // Handle getelementptr instructions. If all operands are constants then we
1149 // can turn this into a getelementptr ConstantExpr.
1151 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1152 if (ValueState[&I].isOverdefined()) return;
1154 SmallVector<Constant*, 8> Operands;
1155 Operands.reserve(I.getNumOperands());
1157 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1158 LatticeVal State = getValueState(I.getOperand(i));
1159 if (State.isUndefined())
1160 return; // Operands are not resolved yet.
1162 if (State.isOverdefined())
1163 return markOverdefined(&I);
1165 assert(State.isConstant() && "Unknown state!");
1166 Operands.push_back(State.getConstant());
1169 Constant *Ptr = Operands[0];
1170 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0]+1,
1171 Operands.size()-1));
1174 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1175 // If this store is of a struct, ignore it.
1176 if (SI.getOperand(0)->getType()->isStructTy())
1179 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1182 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1183 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1184 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1186 // Get the value we are storing into the global, then merge it.
1187 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1188 if (I->second.isOverdefined())
1189 TrackedGlobals.erase(I); // No need to keep tracking this!
1193 // Handle load instructions. If the operand is a constant pointer to a constant
1194 // global, we can replace the load with the loaded constant value!
1195 void SCCPSolver::visitLoadInst(LoadInst &I) {
1196 // If this load is of a struct, just mark the result overdefined.
1197 if (I.getType()->isStructTy())
1198 return markAnythingOverdefined(&I);
1200 LatticeVal PtrVal = getValueState(I.getOperand(0));
1201 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1203 LatticeVal &IV = ValueState[&I];
1204 if (IV.isOverdefined()) return;
1206 if (!PtrVal.isConstant() || I.isVolatile())
1207 return markOverdefined(IV, &I);
1209 Constant *Ptr = PtrVal.getConstant();
1211 // load null -> null
1212 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1213 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1215 // Transform load (constant global) into the value loaded.
1216 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1217 if (!TrackedGlobals.empty()) {
1218 // If we are tracking this global, merge in the known value for it.
1219 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1220 TrackedGlobals.find(GV);
1221 if (It != TrackedGlobals.end()) {
1222 mergeInValue(IV, &I, It->second);
1228 // Transform load from a constant into a constant if possible.
1229 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1230 return markConstant(IV, &I, C);
1232 // Otherwise we cannot say for certain what value this load will produce.
1234 markOverdefined(IV, &I);
1237 void SCCPSolver::visitCallSite(CallSite CS) {
1238 Function *F = CS.getCalledFunction();
1239 Instruction *I = CS.getInstruction();
1241 // The common case is that we aren't tracking the callee, either because we
1242 // are not doing interprocedural analysis or the callee is indirect, or is
1243 // external. Handle these cases first.
1244 if (F == 0 || F->isDeclaration()) {
1246 // Void return and not tracking callee, just bail.
1247 if (I->getType()->isVoidTy()) return;
1249 // Otherwise, if we have a single return value case, and if the function is
1250 // a declaration, maybe we can constant fold it.
1251 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1252 canConstantFoldCallTo(F)) {
1254 SmallVector<Constant*, 8> Operands;
1255 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1257 LatticeVal State = getValueState(*AI);
1259 if (State.isUndefined())
1260 return; // Operands are not resolved yet.
1261 if (State.isOverdefined())
1262 return markOverdefined(I);
1263 assert(State.isConstant() && "Unknown state!");
1264 Operands.push_back(State.getConstant());
1267 // If we can constant fold this, mark the result of the call as a
1269 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1270 return markConstant(I, C);
1273 // Otherwise, we don't know anything about this call, mark it overdefined.
1274 return markAnythingOverdefined(I);
1277 // If this is a local function that doesn't have its address taken, mark its
1278 // entry block executable and merge in the actual arguments to the call into
1279 // the formal arguments of the function.
1280 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1281 MarkBlockExecutable(F->begin());
1283 // Propagate information from this call site into the callee.
1284 CallSite::arg_iterator CAI = CS.arg_begin();
1285 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1286 AI != E; ++AI, ++CAI) {
1287 // If this argument is byval, and if the function is not readonly, there
1288 // will be an implicit copy formed of the input aggregate.
1289 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1290 markOverdefined(AI);
1294 if (const StructType *STy = dyn_cast<StructType>(AI->getType())) {
1295 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1296 LatticeVal CallArg = getStructValueState(*CAI, i);
1297 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1300 mergeInValue(AI, getValueState(*CAI));
1305 // If this is a single/zero retval case, see if we're tracking the function.
1306 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
1307 if (!MRVFunctionsTracked.count(F))
1308 goto CallOverdefined; // Not tracking this callee.
1310 // If we are tracking this callee, propagate the result of the function
1311 // into this call site.
1312 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1313 mergeInValue(getStructValueState(I, i), I,
1314 TrackedMultipleRetVals[std::make_pair(F, i)]);
1316 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1317 if (TFRVI == TrackedRetVals.end())
1318 goto CallOverdefined; // Not tracking this callee.
1320 // If so, propagate the return value of the callee into this call result.
1321 mergeInValue(I, TFRVI->second);
1325 void SCCPSolver::Solve() {
1326 // Process the work lists until they are empty!
1327 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1328 !OverdefinedInstWorkList.empty()) {
1329 // Process the overdefined instruction's work list first, which drives other
1330 // things to overdefined more quickly.
1331 while (!OverdefinedInstWorkList.empty()) {
1332 Value *I = OverdefinedInstWorkList.pop_back_val();
1334 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1336 // "I" got into the work list because it either made the transition from
1337 // bottom to constant
1339 // Anything on this worklist that is overdefined need not be visited
1340 // since all of its users will have already been marked as overdefined
1341 // Update all of the users of this instruction's value.
1343 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1345 if (Instruction *I = dyn_cast<Instruction>(*UI))
1346 OperandChangedState(I);
1349 // Process the instruction work list.
1350 while (!InstWorkList.empty()) {
1351 Value *I = InstWorkList.pop_back_val();
1353 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1355 // "I" got into the work list because it made the transition from undef to
1358 // Anything on this worklist that is overdefined need not be visited
1359 // since all of its users will have already been marked as overdefined.
1360 // Update all of the users of this instruction's value.
1362 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1363 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1365 if (Instruction *I = dyn_cast<Instruction>(*UI))
1366 OperandChangedState(I);
1369 // Process the basic block work list.
1370 while (!BBWorkList.empty()) {
1371 BasicBlock *BB = BBWorkList.back();
1372 BBWorkList.pop_back();
1374 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1376 // Notify all instructions in this basic block that they are newly
1383 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1384 /// that branches on undef values cannot reach any of their successors.
1385 /// However, this is not a safe assumption. After we solve dataflow, this
1386 /// method should be use to handle this. If this returns true, the solver
1387 /// should be rerun.
1389 /// This method handles this by finding an unresolved branch and marking it one
1390 /// of the edges from the block as being feasible, even though the condition
1391 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1392 /// CFG and only slightly pessimizes the analysis results (by marking one,
1393 /// potentially infeasible, edge feasible). This cannot usefully modify the
1394 /// constraints on the condition of the branch, as that would impact other users
1397 /// This scan also checks for values that use undefs, whose results are actually
1398 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1399 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1400 /// even if X isn't defined.
1401 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1402 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1403 if (!BBExecutable.count(BB))
1406 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1407 // Look for instructions which produce undef values.
1408 if (I->getType()->isVoidTy()) continue;
1410 if (const StructType *STy = dyn_cast<StructType>(I->getType())) {
1411 // Only a few things that can be structs matter for undef. Just send
1412 // all their results to overdefined. We could be more precise than this
1413 // but it isn't worth bothering.
1414 if (isa<CallInst>(I) || isa<SelectInst>(I)) {
1415 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1416 LatticeVal &LV = getStructValueState(I, i);
1417 if (LV.isUndefined())
1418 markOverdefined(LV, I);
1424 LatticeVal &LV = getValueState(I);
1425 if (!LV.isUndefined()) continue;
1427 // No instructions using structs need disambiguation.
1428 if (I->getOperand(0)->getType()->isStructTy())
1431 // Get the lattice values of the first two operands for use below.
1432 LatticeVal Op0LV = getValueState(I->getOperand(0));
1434 if (I->getNumOperands() == 2) {
1435 // No instructions using structs need disambiguation.
1436 if (I->getOperand(1)->getType()->isStructTy())
1439 // If this is a two-operand instruction, and if both operands are
1440 // undefs, the result stays undef.
1441 Op1LV = getValueState(I->getOperand(1));
1442 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1446 // If this is an instructions whose result is defined even if the input is
1447 // not fully defined, propagate the information.
1448 const Type *ITy = I->getType();
1449 switch (I->getOpcode()) {
1450 default: break; // Leave the instruction as an undef.
1451 case Instruction::ZExt:
1452 // After a zero extend, we know the top part is zero. SExt doesn't have
1453 // to be handled here, because we don't know whether the top part is 1's
1455 markForcedConstant(I, Constant::getNullValue(ITy));
1457 case Instruction::Mul:
1458 case Instruction::And:
1459 // undef * X -> 0. X could be zero.
1460 // undef & X -> 0. X could be zero.
1461 markForcedConstant(I, Constant::getNullValue(ITy));
1464 case Instruction::Or:
1465 // undef | X -> -1. X could be -1.
1466 markForcedConstant(I, Constant::getAllOnesValue(ITy));
1469 case Instruction::SDiv:
1470 case Instruction::UDiv:
1471 case Instruction::SRem:
1472 case Instruction::URem:
1473 // X / undef -> undef. No change.
1474 // X % undef -> undef. No change.
1475 if (Op1LV.isUndefined()) break;
1477 // undef / X -> 0. X could be maxint.
1478 // undef % X -> 0. X could be 1.
1479 markForcedConstant(I, Constant::getNullValue(ITy));
1482 case Instruction::AShr:
1483 // undef >>s X -> undef. No change.
1484 if (Op0LV.isUndefined()) break;
1486 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1487 if (Op0LV.isConstant())
1488 markForcedConstant(I, Op0LV.getConstant());
1492 case Instruction::LShr:
1493 case Instruction::Shl:
1494 // undef >> X -> undef. No change.
1495 // undef << X -> undef. No change.
1496 if (Op0LV.isUndefined()) break;
1498 // X >> undef -> 0. X could be 0.
1499 // X << undef -> 0. X could be 0.
1500 markForcedConstant(I, Constant::getNullValue(ITy));
1502 case Instruction::Select:
1503 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1504 if (Op0LV.isUndefined()) {
1505 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1506 Op1LV = getValueState(I->getOperand(2));
1507 } else if (Op1LV.isUndefined()) {
1508 // c ? undef : undef -> undef. No change.
1509 Op1LV = getValueState(I->getOperand(2));
1510 if (Op1LV.isUndefined())
1512 // Otherwise, c ? undef : x -> x.
1514 // Leave Op1LV as Operand(1)'s LatticeValue.
1517 if (Op1LV.isConstant())
1518 markForcedConstant(I, Op1LV.getConstant());
1522 case Instruction::Call:
1523 // If a call has an undef result, it is because it is constant foldable
1524 // but one of the inputs was undef. Just force the result to
1531 // Check to see if we have a branch or switch on an undefined value. If so
1532 // we force the branch to go one way or the other to make the successor
1533 // values live. It doesn't really matter which way we force it.
1534 TerminatorInst *TI = BB->getTerminator();
1535 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1536 if (!BI->isConditional()) continue;
1537 if (!getValueState(BI->getCondition()).isUndefined())
1540 // If the input to SCCP is actually branch on undef, fix the undef to
1542 if (isa<UndefValue>(BI->getCondition())) {
1543 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1544 markEdgeExecutable(BB, TI->getSuccessor(1));
1548 // Otherwise, it is a branch on a symbolic value which is currently
1549 // considered to be undef. Handle this by forcing the input value to the
1551 markForcedConstant(BI->getCondition(),
1552 ConstantInt::getFalse(TI->getContext()));
1556 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1557 if (SI->getNumSuccessors() < 2) // no cases
1559 if (!getValueState(SI->getCondition()).isUndefined())
1562 // If the input to SCCP is actually switch on undef, fix the undef to
1563 // the first constant.
1564 if (isa<UndefValue>(SI->getCondition())) {
1565 SI->setCondition(SI->getCaseValue(1));
1566 markEdgeExecutable(BB, TI->getSuccessor(1));
1570 markForcedConstant(SI->getCondition(), SI->getCaseValue(1));
1580 //===--------------------------------------------------------------------===//
1582 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1583 /// Sparse Conditional Constant Propagator.
1585 struct SCCP : public FunctionPass {
1586 static char ID; // Pass identification, replacement for typeid
1587 SCCP() : FunctionPass(&ID) {}
1589 // runOnFunction - Run the Sparse Conditional Constant Propagation
1590 // algorithm, and return true if the function was modified.
1592 bool runOnFunction(Function &F);
1594 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1595 AU.setPreservesCFG();
1598 } // end anonymous namespace
1601 static RegisterPass<SCCP>
1602 X("sccp", "Sparse Conditional Constant Propagation");
1604 // createSCCPPass - This is the public interface to this file.
1605 FunctionPass *llvm::createSCCPPass() {
1609 static void DeleteInstructionInBlock(BasicBlock *BB) {
1610 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1613 // Delete the instructions backwards, as it has a reduced likelihood of
1614 // having to update as many def-use and use-def chains.
1615 while (!isa<TerminatorInst>(BB->begin())) {
1616 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1618 if (!I->use_empty())
1619 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1620 BB->getInstList().erase(I);
1625 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1626 // and return true if the function was modified.
1628 bool SCCP::runOnFunction(Function &F) {
1629 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1630 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
1632 // Mark the first block of the function as being executable.
1633 Solver.MarkBlockExecutable(F.begin());
1635 // Mark all arguments to the function as being overdefined.
1636 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1637 Solver.markAnythingOverdefined(AI);
1639 // Solve for constants.
1640 bool ResolvedUndefs = true;
1641 while (ResolvedUndefs) {
1643 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1644 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1647 bool MadeChanges = false;
1649 // If we decided that there are basic blocks that are dead in this function,
1650 // delete their contents now. Note that we cannot actually delete the blocks,
1651 // as we cannot modify the CFG of the function.
1653 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1654 if (!Solver.isBlockExecutable(BB)) {
1655 DeleteInstructionInBlock(BB);
1660 // Iterate over all of the instructions in a function, replacing them with
1661 // constants if we have found them to be of constant values.
1663 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1664 Instruction *Inst = BI++;
1665 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1668 // TODO: Reconstruct structs from their elements.
1669 if (Inst->getType()->isStructTy())
1672 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1673 if (IV.isOverdefined())
1676 Constant *Const = IV.isConstant()
1677 ? IV.getConstant() : UndefValue::get(Inst->getType());
1678 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
1680 // Replaces all of the uses of a variable with uses of the constant.
1681 Inst->replaceAllUsesWith(Const);
1683 // Delete the instruction.
1684 Inst->eraseFromParent();
1686 // Hey, we just changed something!
1696 //===--------------------------------------------------------------------===//
1698 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1699 /// Constant Propagation.
1701 struct IPSCCP : public ModulePass {
1703 IPSCCP() : ModulePass(&ID) {}
1704 bool runOnModule(Module &M);
1706 } // end anonymous namespace
1708 char IPSCCP::ID = 0;
1709 static RegisterPass<IPSCCP>
1710 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1712 // createIPSCCPPass - This is the public interface to this file.
1713 ModulePass *llvm::createIPSCCPPass() {
1714 return new IPSCCP();
1718 static bool AddressIsTaken(const GlobalValue *GV) {
1719 // Delete any dead constantexpr klingons.
1720 GV->removeDeadConstantUsers();
1722 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1724 const User *U = *UI;
1725 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
1726 if (SI->getOperand(0) == GV || SI->isVolatile())
1727 return true; // Storing addr of GV.
1728 } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
1729 // Make sure we are calling the function, not passing the address.
1730 ImmutableCallSite CS(cast<Instruction>(U));
1731 if (!CS.isCallee(UI))
1733 } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
1734 if (LI->isVolatile())
1736 } else if (isa<BlockAddress>(U)) {
1737 // blockaddress doesn't take the address of the function, it takes addr
1746 bool IPSCCP::runOnModule(Module &M) {
1747 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
1749 // Loop over all functions, marking arguments to those with their addresses
1750 // taken or that are external as overdefined.
1752 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1753 if (F->isDeclaration())
1756 // If this is a strong or ODR definition of this function, then we can
1757 // propagate information about its result into callsites of it.
1758 if (!F->mayBeOverridden())
1759 Solver.AddTrackedFunction(F);
1761 // If this function only has direct calls that we can see, we can track its
1762 // arguments and return value aggressively, and can assume it is not called
1763 // unless we see evidence to the contrary.
1764 if (F->hasLocalLinkage() && !AddressIsTaken(F)) {
1765 Solver.AddArgumentTrackedFunction(F);
1769 // Assume the function is called.
1770 Solver.MarkBlockExecutable(F->begin());
1772 // Assume nothing about the incoming arguments.
1773 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1775 Solver.markAnythingOverdefined(AI);
1778 // Loop over global variables. We inform the solver about any internal global
1779 // variables that do not have their 'addresses taken'. If they don't have
1780 // their addresses taken, we can propagate constants through them.
1781 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1783 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
1784 Solver.TrackValueOfGlobalVariable(G);
1786 // Solve for constants.
1787 bool ResolvedUndefs = true;
1788 while (ResolvedUndefs) {
1791 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1792 ResolvedUndefs = false;
1793 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1794 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1797 bool MadeChanges = false;
1799 // Iterate over all of the instructions in the module, replacing them with
1800 // constants if we have found them to be of constant values.
1802 SmallVector<BasicBlock*, 512> BlocksToErase;
1804 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1805 if (Solver.isBlockExecutable(F->begin())) {
1806 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1808 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
1810 // TODO: Could use getStructLatticeValueFor to find out if the entire
1811 // result is a constant and replace it entirely if so.
1813 LatticeVal IV = Solver.getLatticeValueFor(AI);
1814 if (IV.isOverdefined()) continue;
1816 Constant *CST = IV.isConstant() ?
1817 IV.getConstant() : UndefValue::get(AI->getType());
1818 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1820 // Replaces all of the uses of a variable with uses of the
1822 AI->replaceAllUsesWith(CST);
1827 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
1828 if (!Solver.isBlockExecutable(BB)) {
1829 DeleteInstructionInBlock(BB);
1832 TerminatorInst *TI = BB->getTerminator();
1833 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1834 BasicBlock *Succ = TI->getSuccessor(i);
1835 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1836 TI->getSuccessor(i)->removePredecessor(BB);
1838 if (!TI->use_empty())
1839 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1840 TI->eraseFromParent();
1842 if (&*BB != &F->front())
1843 BlocksToErase.push_back(BB);
1845 new UnreachableInst(M.getContext(), BB);
1849 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1850 Instruction *Inst = BI++;
1851 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
1854 // TODO: Could use getStructLatticeValueFor to find out if the entire
1855 // result is a constant and replace it entirely if so.
1857 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1858 if (IV.isOverdefined())
1861 Constant *Const = IV.isConstant()
1862 ? IV.getConstant() : UndefValue::get(Inst->getType());
1863 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
1865 // Replaces all of the uses of a variable with uses of the
1867 Inst->replaceAllUsesWith(Const);
1869 // Delete the instruction.
1870 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1871 Inst->eraseFromParent();
1873 // Hey, we just changed something!
1879 // Now that all instructions in the function are constant folded, erase dead
1880 // blocks, because we can now use ConstantFoldTerminator to get rid of
1882 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1883 // If there are any PHI nodes in this successor, drop entries for BB now.
1884 BasicBlock *DeadBB = BlocksToErase[i];
1885 for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1887 // Grab the user and then increment the iterator early, as the user
1888 // will be deleted. Step past all adjacent uses from the same user.
1889 Instruction *I = dyn_cast<Instruction>(*UI);
1890 do { ++UI; } while (UI != UE && *UI == I);
1892 // Ignore blockaddress users; BasicBlock's dtor will handle them.
1895 bool Folded = ConstantFoldTerminator(I->getParent());
1897 // The constant folder may not have been able to fold the terminator
1898 // if this is a branch or switch on undef. Fold it manually as a
1899 // branch to the first successor.
1901 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1902 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1903 "Branch should be foldable!");
1904 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1905 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1907 llvm_unreachable("Didn't fold away reference to block!");
1911 // Make this an uncond branch to the first successor.
1912 TerminatorInst *TI = I->getParent()->getTerminator();
1913 BranchInst::Create(TI->getSuccessor(0), TI);
1915 // Remove entries in successor phi nodes to remove edges.
1916 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1917 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1919 // Remove the old terminator.
1920 TI->eraseFromParent();
1924 // Finally, delete the basic block.
1925 F->getBasicBlockList().erase(DeadBB);
1927 BlocksToErase.clear();
1930 // If we inferred constant or undef return values for a function, we replaced
1931 // all call uses with the inferred value. This means we don't need to bother
1932 // actually returning anything from the function. Replace all return
1933 // instructions with return undef.
1935 // Do this in two stages: first identify the functions we should process, then
1936 // actually zap their returns. This is important because we can only do this
1937 // if the address of the function isn't taken. In cases where a return is the
1938 // last use of a function, the order of processing functions would affect
1939 // whether other functions are optimizable.
1940 SmallVector<ReturnInst*, 8> ReturnsToZap;
1942 // TODO: Process multiple value ret instructions also.
1943 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1944 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1945 E = RV.end(); I != E; ++I) {
1946 Function *F = I->first;
1947 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1950 // We can only do this if we know that nothing else can call the function.
1951 if (!F->hasLocalLinkage() || AddressIsTaken(F))
1954 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1955 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1956 if (!isa<UndefValue>(RI->getOperand(0)))
1957 ReturnsToZap.push_back(RI);
1960 // Zap all returns which we've identified as zap to change.
1961 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1962 Function *F = ReturnsToZap[i]->getParent()->getParent();
1963 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1966 // If we infered constant or undef values for globals variables, we can delete
1967 // the global and any stores that remain to it.
1968 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1969 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1970 E = TG.end(); I != E; ++I) {
1971 GlobalVariable *GV = I->first;
1972 assert(!I->second.isOverdefined() &&
1973 "Overdefined values should have been taken out of the map!");
1974 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1975 while (!GV->use_empty()) {
1976 StoreInst *SI = cast<StoreInst>(GV->use_back());
1977 SI->eraseFromParent();
1979 M.getGlobalList().erase(GV);