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/Target/TargetLibraryInfo.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/InstVisitor.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/DenseSet.h"
39 #include "llvm/ADT/PointerIntPair.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/STLExtras.h"
48 STATISTIC(NumInstRemoved, "Number of instructions removed");
49 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
51 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
52 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
53 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
56 /// LatticeVal class - This class represents the different lattice values that
57 /// an LLVM value may occupy. It is a simple class with value semantics.
61 /// undefined - This LLVM Value has no known value yet.
64 /// constant - This LLVM Value has a specific constant value.
67 /// forcedconstant - This LLVM Value was thought to be undef until
68 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
69 /// with another (different) constant, it goes to overdefined, instead of
73 /// overdefined - This instruction is not known to be constant, and we know
78 /// Val: This stores the current lattice value along with the Constant* for
79 /// the constant if this is a 'constant' or 'forcedconstant' value.
80 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
82 LatticeValueTy getLatticeValue() const {
87 LatticeVal() : Val(0, undefined) {}
89 bool isUndefined() const { return getLatticeValue() == undefined; }
90 bool isConstant() const {
91 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
93 bool isOverdefined() const { return getLatticeValue() == overdefined; }
95 Constant *getConstant() const {
96 assert(isConstant() && "Cannot get the constant of a non-constant!");
97 return Val.getPointer();
100 /// markOverdefined - Return true if this is a change in status.
101 bool markOverdefined() {
105 Val.setInt(overdefined);
109 /// markConstant - Return true if this is a change in status.
110 bool markConstant(Constant *V) {
111 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
112 assert(getConstant() == V && "Marking constant with different value");
117 Val.setInt(constant);
118 assert(V && "Marking constant with NULL");
121 assert(getLatticeValue() == forcedconstant &&
122 "Cannot move from overdefined to constant!");
123 // Stay at forcedconstant if the constant is the same.
124 if (V == getConstant()) return false;
126 // Otherwise, we go to overdefined. Assumptions made based on the
127 // forced value are possibly wrong. Assuming this is another constant
128 // could expose a contradiction.
129 Val.setInt(overdefined);
134 /// getConstantInt - If this is a constant with a ConstantInt value, return it
135 /// otherwise return null.
136 ConstantInt *getConstantInt() const {
138 return dyn_cast<ConstantInt>(getConstant());
142 void markForcedConstant(Constant *V) {
143 assert(isUndefined() && "Can't force a defined value!");
144 Val.setInt(forcedconstant);
148 } // end anonymous namespace.
153 //===----------------------------------------------------------------------===//
155 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
156 /// Constant Propagation.
158 class SCCPSolver : public InstVisitor<SCCPSolver> {
159 const TargetData *TD;
160 const TargetLibraryInfo *TLI;
161 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
162 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
164 /// StructValueState - This maintains ValueState for values that have
165 /// StructType, for example for formal arguments, calls, insertelement, etc.
167 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
169 /// GlobalValue - If we are tracking any values for the contents of a global
170 /// variable, we keep a mapping from the constant accessor to the element of
171 /// the global, to the currently known value. If the value becomes
172 /// overdefined, it's entry is simply removed from this map.
173 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
175 /// TrackedRetVals - If we are tracking arguments into and the return
176 /// value out of a function, it will have an entry in this map, indicating
177 /// what the known return value for the function is.
178 DenseMap<Function*, LatticeVal> TrackedRetVals;
180 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
181 /// that return multiple values.
182 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
184 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
185 /// represented here for efficient lookup.
186 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
188 /// TrackingIncomingArguments - This is the set of functions for whose
189 /// arguments we make optimistic assumptions about and try to prove as
191 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
193 /// The reason for two worklists is that overdefined is the lowest state
194 /// on the lattice, and moving things to overdefined as fast as possible
195 /// makes SCCP converge much faster.
197 /// By having a separate worklist, we accomplish this because everything
198 /// possibly overdefined will become overdefined at the soonest possible
200 SmallVector<Value*, 64> OverdefinedInstWorkList;
201 SmallVector<Value*, 64> InstWorkList;
204 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
206 /// KnownFeasibleEdges - Entries in this set are edges which have already had
207 /// PHI nodes retriggered.
208 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
209 DenseSet<Edge> KnownFeasibleEdges;
211 SCCPSolver(const TargetData *td, const TargetLibraryInfo *tli)
212 : TD(td), TLI(tli) {}
214 /// MarkBlockExecutable - This method can be used by clients to mark all of
215 /// the blocks that are known to be intrinsically live in the processed unit.
217 /// This returns true if the block was not considered live before.
218 bool MarkBlockExecutable(BasicBlock *BB) {
219 if (!BBExecutable.insert(BB)) return false;
220 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
221 BBWorkList.push_back(BB); // Add the block to the work list!
225 /// TrackValueOfGlobalVariable - Clients can use this method to
226 /// inform the SCCPSolver that it should track loads and stores to the
227 /// specified global variable if it can. This is only legal to call if
228 /// performing Interprocedural SCCP.
229 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
230 // We only track the contents of scalar globals.
231 if (GV->getType()->getElementType()->isSingleValueType()) {
232 LatticeVal &IV = TrackedGlobals[GV];
233 if (!isa<UndefValue>(GV->getInitializer()))
234 IV.markConstant(GV->getInitializer());
238 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
239 /// and out of the specified function (which cannot have its address taken),
240 /// this method must be called.
241 void AddTrackedFunction(Function *F) {
242 // Add an entry, F -> undef.
243 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
244 MRVFunctionsTracked.insert(F);
245 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
246 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
249 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
252 void AddArgumentTrackedFunction(Function *F) {
253 TrackingIncomingArguments.insert(F);
256 /// Solve - Solve for constants and executable blocks.
260 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
261 /// that branches on undef values cannot reach any of their successors.
262 /// However, this is not a safe assumption. After we solve dataflow, this
263 /// method should be use to handle this. If this returns true, the solver
265 bool ResolvedUndefsIn(Function &F);
267 bool isBlockExecutable(BasicBlock *BB) const {
268 return BBExecutable.count(BB);
271 LatticeVal getLatticeValueFor(Value *V) const {
272 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
273 assert(I != ValueState.end() && "V is not in valuemap!");
277 /*LatticeVal getStructLatticeValueFor(Value *V, unsigned i) const {
278 DenseMap<std::pair<Value*, unsigned>, LatticeVal>::const_iterator I =
279 StructValueState.find(std::make_pair(V, i));
280 assert(I != StructValueState.end() && "V is not in valuemap!");
284 /// getTrackedRetVals - Get the inferred return value map.
286 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
287 return TrackedRetVals;
290 /// getTrackedGlobals - Get and return the set of inferred initializers for
291 /// global variables.
292 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
293 return TrackedGlobals;
296 void markOverdefined(Value *V) {
297 assert(!V->getType()->isStructTy() && "Should use other method");
298 markOverdefined(ValueState[V], V);
301 /// markAnythingOverdefined - Mark the specified value overdefined. This
302 /// works with both scalars and structs.
303 void markAnythingOverdefined(Value *V) {
304 if (StructType *STy = dyn_cast<StructType>(V->getType()))
305 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
306 markOverdefined(getStructValueState(V, i), V);
312 // markConstant - Make a value be marked as "constant". If the value
313 // is not already a constant, add it to the instruction work list so that
314 // the users of the instruction are updated later.
316 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
317 if (!IV.markConstant(C)) return;
318 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
319 if (IV.isOverdefined())
320 OverdefinedInstWorkList.push_back(V);
322 InstWorkList.push_back(V);
325 void markConstant(Value *V, Constant *C) {
326 assert(!V->getType()->isStructTy() && "Should use other method");
327 markConstant(ValueState[V], V, C);
330 void markForcedConstant(Value *V, Constant *C) {
331 assert(!V->getType()->isStructTy() && "Should use other method");
332 LatticeVal &IV = ValueState[V];
333 IV.markForcedConstant(C);
334 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
335 if (IV.isOverdefined())
336 OverdefinedInstWorkList.push_back(V);
338 InstWorkList.push_back(V);
342 // markOverdefined - Make a value be marked as "overdefined". If the
343 // value is not already overdefined, add it to the overdefined instruction
344 // work list so that the users of the instruction are updated later.
345 void markOverdefined(LatticeVal &IV, Value *V) {
346 if (!IV.markOverdefined()) return;
348 DEBUG(dbgs() << "markOverdefined: ";
349 if (Function *F = dyn_cast<Function>(V))
350 dbgs() << "Function '" << F->getName() << "'\n";
352 dbgs() << *V << '\n');
353 // Only instructions go on the work list
354 OverdefinedInstWorkList.push_back(V);
357 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
358 if (IV.isOverdefined() || MergeWithV.isUndefined())
360 if (MergeWithV.isOverdefined())
361 markOverdefined(IV, V);
362 else if (IV.isUndefined())
363 markConstant(IV, V, MergeWithV.getConstant());
364 else if (IV.getConstant() != MergeWithV.getConstant())
365 markOverdefined(IV, V);
368 void mergeInValue(Value *V, LatticeVal MergeWithV) {
369 assert(!V->getType()->isStructTy() && "Should use other method");
370 mergeInValue(ValueState[V], V, MergeWithV);
374 /// getValueState - Return the LatticeVal object that corresponds to the
375 /// value. This function handles the case when the value hasn't been seen yet
376 /// by properly seeding constants etc.
377 LatticeVal &getValueState(Value *V) {
378 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
380 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
381 ValueState.insert(std::make_pair(V, LatticeVal()));
382 LatticeVal &LV = I.first->second;
385 return LV; // Common case, already in the map.
387 if (Constant *C = dyn_cast<Constant>(V)) {
388 // Undef values remain undefined.
389 if (!isa<UndefValue>(V))
390 LV.markConstant(C); // Constants are constant
393 // All others are underdefined by default.
397 /// getStructValueState - Return the LatticeVal object that corresponds to the
398 /// value/field pair. This function handles the case when the value hasn't
399 /// been seen yet by properly seeding constants etc.
400 LatticeVal &getStructValueState(Value *V, unsigned i) {
401 assert(V->getType()->isStructTy() && "Should use getValueState");
402 assert(i < cast<StructType>(V->getType())->getNumElements() &&
403 "Invalid element #");
405 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
406 bool> I = StructValueState.insert(
407 std::make_pair(std::make_pair(V, i), LatticeVal()));
408 LatticeVal &LV = I.first->second;
411 return LV; // Common case, already in the map.
413 if (Constant *C = dyn_cast<Constant>(V)) {
414 if (isa<UndefValue>(C))
415 ; // Undef values remain undefined.
416 else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C))
417 LV.markConstant(CS->getOperand(i)); // Constants are constant.
418 else if (isa<ConstantAggregateZero>(C)) {
419 Type *FieldTy = cast<StructType>(V->getType())->getElementType(i);
420 LV.markConstant(Constant::getNullValue(FieldTy));
422 LV.markOverdefined(); // Unknown sort of constant.
425 // All others are underdefined by default.
430 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
431 /// work list if it is not already executable.
432 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
433 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
434 return; // This edge is already known to be executable!
436 if (!MarkBlockExecutable(Dest)) {
437 // If the destination is already executable, we just made an *edge*
438 // feasible that wasn't before. Revisit the PHI nodes in the block
439 // because they have potentially new operands.
440 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
441 << " -> " << Dest->getName() << "\n");
444 for (BasicBlock::iterator I = Dest->begin();
445 (PN = dyn_cast<PHINode>(I)); ++I)
450 // getFeasibleSuccessors - Return a vector of booleans to indicate which
451 // successors are reachable from a given terminator instruction.
453 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
455 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
456 // block to the 'To' basic block is currently feasible.
458 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
460 // OperandChangedState - This method is invoked on all of the users of an
461 // instruction that was just changed state somehow. Based on this
462 // information, we need to update the specified user of this instruction.
464 void OperandChangedState(Instruction *I) {
465 if (BBExecutable.count(I->getParent())) // Inst is executable?
470 friend class InstVisitor<SCCPSolver>;
472 // visit implementations - Something changed in this instruction. Either an
473 // operand made a transition, or the instruction is newly executable. Change
474 // the value type of I to reflect these changes if appropriate.
475 void visitPHINode(PHINode &I);
478 void visitReturnInst(ReturnInst &I);
479 void visitTerminatorInst(TerminatorInst &TI);
481 void visitCastInst(CastInst &I);
482 void visitSelectInst(SelectInst &I);
483 void visitBinaryOperator(Instruction &I);
484 void visitCmpInst(CmpInst &I);
485 void visitExtractElementInst(ExtractElementInst &I);
486 void visitInsertElementInst(InsertElementInst &I);
487 void visitShuffleVectorInst(ShuffleVectorInst &I);
488 void visitExtractValueInst(ExtractValueInst &EVI);
489 void visitInsertValueInst(InsertValueInst &IVI);
490 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
492 // Instructions that cannot be folded away.
493 void visitStoreInst (StoreInst &I);
494 void visitLoadInst (LoadInst &I);
495 void visitGetElementPtrInst(GetElementPtrInst &I);
496 void visitCallInst (CallInst &I) {
499 void visitInvokeInst (InvokeInst &II) {
501 visitTerminatorInst(II);
503 void visitCallSite (CallSite CS);
504 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
505 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
506 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
507 void visitFenceInst (FenceInst &I) { /*returns void*/ }
508 void visitAtomicCmpXchgInst (AtomicCmpXchgInst &I) { markOverdefined(&I); }
509 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
510 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
511 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
513 void visitInstruction(Instruction &I) {
514 // If a new instruction is added to LLVM that we don't handle.
515 dbgs() << "SCCP: Don't know how to handle: " << I;
516 markAnythingOverdefined(&I); // Just in case
520 } // end anonymous namespace
523 // getFeasibleSuccessors - Return a vector of booleans to indicate which
524 // successors are reachable from a given terminator instruction.
526 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
527 SmallVector<bool, 16> &Succs) {
528 Succs.resize(TI.getNumSuccessors());
529 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
530 if (BI->isUnconditional()) {
535 LatticeVal BCValue = getValueState(BI->getCondition());
536 ConstantInt *CI = BCValue.getConstantInt();
538 // Overdefined condition variables, and branches on unfoldable constant
539 // conditions, mean the branch could go either way.
540 if (!BCValue.isUndefined())
541 Succs[0] = Succs[1] = true;
545 // Constant condition variables mean the branch can only go a single way.
546 Succs[CI->isZero()] = true;
550 if (isa<InvokeInst>(TI)) {
551 // Invoke instructions successors are always executable.
552 Succs[0] = Succs[1] = true;
556 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
557 if (TI.getNumSuccessors() < 2) {
561 LatticeVal SCValue = getValueState(SI->getCondition());
562 ConstantInt *CI = SCValue.getConstantInt();
564 if (CI == 0) { // Overdefined or undefined condition?
565 // All destinations are executable!
566 if (!SCValue.isUndefined())
567 Succs.assign(TI.getNumSuccessors(), true);
571 Succs[SI->findCaseValue(CI)] = true;
575 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
576 if (isa<IndirectBrInst>(&TI)) {
577 // Just mark all destinations executable!
578 Succs.assign(TI.getNumSuccessors(), true);
583 dbgs() << "Unknown terminator instruction: " << TI << '\n';
585 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
589 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
590 // block to the 'To' basic block is currently feasible.
592 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
593 assert(BBExecutable.count(To) && "Dest should always be alive!");
595 // Make sure the source basic block is executable!!
596 if (!BBExecutable.count(From)) return false;
598 // Check to make sure this edge itself is actually feasible now.
599 TerminatorInst *TI = From->getTerminator();
600 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
601 if (BI->isUnconditional())
604 LatticeVal BCValue = getValueState(BI->getCondition());
606 // Overdefined condition variables mean the branch could go either way,
607 // undef conditions mean that neither edge is feasible yet.
608 ConstantInt *CI = BCValue.getConstantInt();
610 return !BCValue.isUndefined();
612 // Constant condition variables mean the branch can only go a single way.
613 return BI->getSuccessor(CI->isZero()) == To;
616 // Invoke instructions successors are always executable.
617 if (isa<InvokeInst>(TI))
620 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
621 if (SI->getNumSuccessors() < 2)
624 LatticeVal SCValue = getValueState(SI->getCondition());
625 ConstantInt *CI = SCValue.getConstantInt();
628 return !SCValue.isUndefined();
630 // Make sure to skip the "default value" which isn't a value
631 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
632 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
633 return SI->getSuccessor(i) == To;
635 // If the constant value is not equal to any of the branches, we must
636 // execute default branch.
637 return SI->getDefaultDest() == To;
640 // Just mark all destinations executable!
641 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
642 if (isa<IndirectBrInst>(TI))
646 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
651 // visit Implementations - Something changed in this instruction, either an
652 // operand made a transition, or the instruction is newly executable. Change
653 // the value type of I to reflect these changes if appropriate. This method
654 // makes sure to do the following actions:
656 // 1. If a phi node merges two constants in, and has conflicting value coming
657 // from different branches, or if the PHI node merges in an overdefined
658 // value, then the PHI node becomes overdefined.
659 // 2. If a phi node merges only constants in, and they all agree on value, the
660 // PHI node becomes a constant value equal to that.
661 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
662 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
663 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
664 // 6. If a conditional branch has a value that is constant, make the selected
665 // destination executable
666 // 7. If a conditional branch has a value that is overdefined, make all
667 // successors executable.
669 void SCCPSolver::visitPHINode(PHINode &PN) {
670 // If this PN returns a struct, just mark the result overdefined.
671 // TODO: We could do a lot better than this if code actually uses this.
672 if (PN.getType()->isStructTy())
673 return markAnythingOverdefined(&PN);
675 if (getValueState(&PN).isOverdefined())
676 return; // Quick exit
678 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
679 // and slow us down a lot. Just mark them overdefined.
680 if (PN.getNumIncomingValues() > 64)
681 return markOverdefined(&PN);
683 // Look at all of the executable operands of the PHI node. If any of them
684 // are overdefined, the PHI becomes overdefined as well. If they are all
685 // constant, and they agree with each other, the PHI becomes the identical
686 // constant. If they are constant and don't agree, the PHI is overdefined.
687 // If there are no executable operands, the PHI remains undefined.
689 Constant *OperandVal = 0;
690 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
691 LatticeVal IV = getValueState(PN.getIncomingValue(i));
692 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
694 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
697 if (IV.isOverdefined()) // PHI node becomes overdefined!
698 return markOverdefined(&PN);
700 if (OperandVal == 0) { // Grab the first value.
701 OperandVal = IV.getConstant();
705 // There is already a reachable operand. If we conflict with it,
706 // then the PHI node becomes overdefined. If we agree with it, we
709 // Check to see if there are two different constants merging, if so, the PHI
710 // node is overdefined.
711 if (IV.getConstant() != OperandVal)
712 return markOverdefined(&PN);
715 // If we exited the loop, this means that the PHI node only has constant
716 // arguments that agree with each other(and OperandVal is the constant) or
717 // OperandVal is null because there are no defined incoming arguments. If
718 // this is the case, the PHI remains undefined.
721 markConstant(&PN, OperandVal); // Acquire operand value
727 void SCCPSolver::visitReturnInst(ReturnInst &I) {
728 if (I.getNumOperands() == 0) return; // ret void
730 Function *F = I.getParent()->getParent();
731 Value *ResultOp = I.getOperand(0);
733 // If we are tracking the return value of this function, merge it in.
734 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
735 DenseMap<Function*, LatticeVal>::iterator TFRVI =
736 TrackedRetVals.find(F);
737 if (TFRVI != TrackedRetVals.end()) {
738 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
743 // Handle functions that return multiple values.
744 if (!TrackedMultipleRetVals.empty()) {
745 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
746 if (MRVFunctionsTracked.count(F))
747 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
748 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
749 getStructValueState(ResultOp, i));
754 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
755 SmallVector<bool, 16> SuccFeasible;
756 getFeasibleSuccessors(TI, SuccFeasible);
758 BasicBlock *BB = TI.getParent();
760 // Mark all feasible successors executable.
761 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
763 markEdgeExecutable(BB, TI.getSuccessor(i));
766 void SCCPSolver::visitCastInst(CastInst &I) {
767 LatticeVal OpSt = getValueState(I.getOperand(0));
768 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
770 else if (OpSt.isConstant()) // Propagate constant value
771 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
772 OpSt.getConstant(), I.getType()));
776 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
777 // If this returns a struct, mark all elements over defined, we don't track
778 // structs in structs.
779 if (EVI.getType()->isStructTy())
780 return markAnythingOverdefined(&EVI);
782 // If this is extracting from more than one level of struct, we don't know.
783 if (EVI.getNumIndices() != 1)
784 return markOverdefined(&EVI);
786 Value *AggVal = EVI.getAggregateOperand();
787 if (AggVal->getType()->isStructTy()) {
788 unsigned i = *EVI.idx_begin();
789 LatticeVal EltVal = getStructValueState(AggVal, i);
790 mergeInValue(getValueState(&EVI), &EVI, EltVal);
792 // Otherwise, must be extracting from an array.
793 return markOverdefined(&EVI);
797 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
798 StructType *STy = dyn_cast<StructType>(IVI.getType());
800 return markOverdefined(&IVI);
802 // If this has more than one index, we can't handle it, drive all results to
804 if (IVI.getNumIndices() != 1)
805 return markAnythingOverdefined(&IVI);
807 Value *Aggr = IVI.getAggregateOperand();
808 unsigned Idx = *IVI.idx_begin();
810 // Compute the result based on what we're inserting.
811 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
812 // This passes through all values that aren't the inserted element.
814 LatticeVal EltVal = getStructValueState(Aggr, i);
815 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
819 Value *Val = IVI.getInsertedValueOperand();
820 if (Val->getType()->isStructTy())
821 // We don't track structs in structs.
822 markOverdefined(getStructValueState(&IVI, i), &IVI);
824 LatticeVal InVal = getValueState(Val);
825 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
830 void SCCPSolver::visitSelectInst(SelectInst &I) {
831 // If this select returns a struct, just mark the result overdefined.
832 // TODO: We could do a lot better than this if code actually uses this.
833 if (I.getType()->isStructTy())
834 return markAnythingOverdefined(&I);
836 LatticeVal CondValue = getValueState(I.getCondition());
837 if (CondValue.isUndefined())
840 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
841 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
842 mergeInValue(&I, getValueState(OpVal));
846 // Otherwise, the condition is overdefined or a constant we can't evaluate.
847 // See if we can produce something better than overdefined based on the T/F
849 LatticeVal TVal = getValueState(I.getTrueValue());
850 LatticeVal FVal = getValueState(I.getFalseValue());
852 // select ?, C, C -> C.
853 if (TVal.isConstant() && FVal.isConstant() &&
854 TVal.getConstant() == FVal.getConstant())
855 return markConstant(&I, FVal.getConstant());
857 if (TVal.isUndefined()) // select ?, undef, X -> X.
858 return mergeInValue(&I, FVal);
859 if (FVal.isUndefined()) // select ?, X, undef -> X.
860 return mergeInValue(&I, TVal);
864 // Handle Binary Operators.
865 void SCCPSolver::visitBinaryOperator(Instruction &I) {
866 LatticeVal V1State = getValueState(I.getOperand(0));
867 LatticeVal V2State = getValueState(I.getOperand(1));
869 LatticeVal &IV = ValueState[&I];
870 if (IV.isOverdefined()) return;
872 if (V1State.isConstant() && V2State.isConstant())
873 return markConstant(IV, &I,
874 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
875 V2State.getConstant()));
877 // If something is undef, wait for it to resolve.
878 if (!V1State.isOverdefined() && !V2State.isOverdefined())
881 // Otherwise, one of our operands is overdefined. Try to produce something
882 // better than overdefined with some tricks.
884 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
885 // operand is overdefined.
886 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
887 LatticeVal *NonOverdefVal = 0;
888 if (!V1State.isOverdefined())
889 NonOverdefVal = &V1State;
890 else if (!V2State.isOverdefined())
891 NonOverdefVal = &V2State;
894 if (NonOverdefVal->isUndefined()) {
895 // Could annihilate value.
896 if (I.getOpcode() == Instruction::And)
897 markConstant(IV, &I, Constant::getNullValue(I.getType()));
898 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
899 markConstant(IV, &I, Constant::getAllOnesValue(PT));
902 Constant::getAllOnesValue(I.getType()));
906 if (I.getOpcode() == Instruction::And) {
908 if (NonOverdefVal->getConstant()->isNullValue())
909 return markConstant(IV, &I, NonOverdefVal->getConstant());
911 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
912 if (CI->isAllOnesValue()) // X or -1 = -1
913 return markConstant(IV, &I, NonOverdefVal->getConstant());
922 // Handle ICmpInst instruction.
923 void SCCPSolver::visitCmpInst(CmpInst &I) {
924 LatticeVal V1State = getValueState(I.getOperand(0));
925 LatticeVal V2State = getValueState(I.getOperand(1));
927 LatticeVal &IV = ValueState[&I];
928 if (IV.isOverdefined()) return;
930 if (V1State.isConstant() && V2State.isConstant())
931 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
932 V1State.getConstant(),
933 V2State.getConstant()));
935 // If operands are still undefined, wait for it to resolve.
936 if (!V1State.isOverdefined() && !V2State.isOverdefined())
942 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
943 // TODO : SCCP does not handle vectors properly.
944 return markOverdefined(&I);
947 LatticeVal &ValState = getValueState(I.getOperand(0));
948 LatticeVal &IdxState = getValueState(I.getOperand(1));
950 if (ValState.isOverdefined() || IdxState.isOverdefined())
952 else if(ValState.isConstant() && IdxState.isConstant())
953 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
954 IdxState.getConstant()));
958 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
959 // TODO : SCCP does not handle vectors properly.
960 return markOverdefined(&I);
962 LatticeVal &ValState = getValueState(I.getOperand(0));
963 LatticeVal &EltState = getValueState(I.getOperand(1));
964 LatticeVal &IdxState = getValueState(I.getOperand(2));
966 if (ValState.isOverdefined() || EltState.isOverdefined() ||
967 IdxState.isOverdefined())
969 else if(ValState.isConstant() && EltState.isConstant() &&
970 IdxState.isConstant())
971 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
972 EltState.getConstant(),
973 IdxState.getConstant()));
974 else if (ValState.isUndefined() && EltState.isConstant() &&
975 IdxState.isConstant())
976 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
977 EltState.getConstant(),
978 IdxState.getConstant()));
982 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
983 // TODO : SCCP does not handle vectors properly.
984 return markOverdefined(&I);
986 LatticeVal &V1State = getValueState(I.getOperand(0));
987 LatticeVal &V2State = getValueState(I.getOperand(1));
988 LatticeVal &MaskState = getValueState(I.getOperand(2));
990 if (MaskState.isUndefined() ||
991 (V1State.isUndefined() && V2State.isUndefined()))
992 return; // Undefined output if mask or both inputs undefined.
994 if (V1State.isOverdefined() || V2State.isOverdefined() ||
995 MaskState.isOverdefined()) {
998 // A mix of constant/undef inputs.
999 Constant *V1 = V1State.isConstant() ?
1000 V1State.getConstant() : UndefValue::get(I.getType());
1001 Constant *V2 = V2State.isConstant() ?
1002 V2State.getConstant() : UndefValue::get(I.getType());
1003 Constant *Mask = MaskState.isConstant() ?
1004 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1005 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1010 // Handle getelementptr instructions. If all operands are constants then we
1011 // can turn this into a getelementptr ConstantExpr.
1013 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1014 if (ValueState[&I].isOverdefined()) return;
1016 SmallVector<Constant*, 8> Operands;
1017 Operands.reserve(I.getNumOperands());
1019 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1020 LatticeVal State = getValueState(I.getOperand(i));
1021 if (State.isUndefined())
1022 return; // Operands are not resolved yet.
1024 if (State.isOverdefined())
1025 return markOverdefined(&I);
1027 assert(State.isConstant() && "Unknown state!");
1028 Operands.push_back(State.getConstant());
1031 Constant *Ptr = Operands[0];
1032 ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
1033 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
1036 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1037 // If this store is of a struct, ignore it.
1038 if (SI.getOperand(0)->getType()->isStructTy())
1041 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1044 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1045 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1046 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1048 // Get the value we are storing into the global, then merge it.
1049 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1050 if (I->second.isOverdefined())
1051 TrackedGlobals.erase(I); // No need to keep tracking this!
1055 // Handle load instructions. If the operand is a constant pointer to a constant
1056 // global, we can replace the load with the loaded constant value!
1057 void SCCPSolver::visitLoadInst(LoadInst &I) {
1058 // If this load is of a struct, just mark the result overdefined.
1059 if (I.getType()->isStructTy())
1060 return markAnythingOverdefined(&I);
1062 LatticeVal PtrVal = getValueState(I.getOperand(0));
1063 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1065 LatticeVal &IV = ValueState[&I];
1066 if (IV.isOverdefined()) return;
1068 if (!PtrVal.isConstant() || I.isVolatile())
1069 return markOverdefined(IV, &I);
1071 Constant *Ptr = PtrVal.getConstant();
1073 // load null -> null
1074 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1075 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1077 // Transform load (constant global) into the value loaded.
1078 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1079 if (!TrackedGlobals.empty()) {
1080 // If we are tracking this global, merge in the known value for it.
1081 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1082 TrackedGlobals.find(GV);
1083 if (It != TrackedGlobals.end()) {
1084 mergeInValue(IV, &I, It->second);
1090 // Transform load from a constant into a constant if possible.
1091 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1092 return markConstant(IV, &I, C);
1094 // Otherwise we cannot say for certain what value this load will produce.
1096 markOverdefined(IV, &I);
1099 void SCCPSolver::visitCallSite(CallSite CS) {
1100 Function *F = CS.getCalledFunction();
1101 Instruction *I = CS.getInstruction();
1103 // The common case is that we aren't tracking the callee, either because we
1104 // are not doing interprocedural analysis or the callee is indirect, or is
1105 // external. Handle these cases first.
1106 if (F == 0 || F->isDeclaration()) {
1108 // Void return and not tracking callee, just bail.
1109 if (I->getType()->isVoidTy()) return;
1111 // Otherwise, if we have a single return value case, and if the function is
1112 // a declaration, maybe we can constant fold it.
1113 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1114 canConstantFoldCallTo(F)) {
1116 SmallVector<Constant*, 8> Operands;
1117 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1119 LatticeVal State = getValueState(*AI);
1121 if (State.isUndefined())
1122 return; // Operands are not resolved yet.
1123 if (State.isOverdefined())
1124 return markOverdefined(I);
1125 assert(State.isConstant() && "Unknown state!");
1126 Operands.push_back(State.getConstant());
1129 // If we can constant fold this, mark the result of the call as a
1131 if (Constant *C = ConstantFoldCall(F, Operands, TLI))
1132 return markConstant(I, C);
1135 // Otherwise, we don't know anything about this call, mark it overdefined.
1136 return markAnythingOverdefined(I);
1139 // If this is a local function that doesn't have its address taken, mark its
1140 // entry block executable and merge in the actual arguments to the call into
1141 // the formal arguments of the function.
1142 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1143 MarkBlockExecutable(F->begin());
1145 // Propagate information from this call site into the callee.
1146 CallSite::arg_iterator CAI = CS.arg_begin();
1147 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1148 AI != E; ++AI, ++CAI) {
1149 // If this argument is byval, and if the function is not readonly, there
1150 // will be an implicit copy formed of the input aggregate.
1151 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1152 markOverdefined(AI);
1156 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
1157 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1158 LatticeVal CallArg = getStructValueState(*CAI, i);
1159 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1162 mergeInValue(AI, getValueState(*CAI));
1167 // If this is a single/zero retval case, see if we're tracking the function.
1168 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
1169 if (!MRVFunctionsTracked.count(F))
1170 goto CallOverdefined; // Not tracking this callee.
1172 // If we are tracking this callee, propagate the result of the function
1173 // into this call site.
1174 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1175 mergeInValue(getStructValueState(I, i), I,
1176 TrackedMultipleRetVals[std::make_pair(F, i)]);
1178 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1179 if (TFRVI == TrackedRetVals.end())
1180 goto CallOverdefined; // Not tracking this callee.
1182 // If so, propagate the return value of the callee into this call result.
1183 mergeInValue(I, TFRVI->second);
1187 void SCCPSolver::Solve() {
1188 // Process the work lists until they are empty!
1189 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1190 !OverdefinedInstWorkList.empty()) {
1191 // Process the overdefined instruction's work list first, which drives other
1192 // things to overdefined more quickly.
1193 while (!OverdefinedInstWorkList.empty()) {
1194 Value *I = OverdefinedInstWorkList.pop_back_val();
1196 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1198 // "I" got into the work list because it either made the transition from
1199 // bottom to constant
1201 // Anything on this worklist that is overdefined need not be visited
1202 // since all of its users will have already been marked as overdefined
1203 // Update all of the users of this instruction's value.
1205 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1207 if (Instruction *I = dyn_cast<Instruction>(*UI))
1208 OperandChangedState(I);
1211 // Process the instruction work list.
1212 while (!InstWorkList.empty()) {
1213 Value *I = InstWorkList.pop_back_val();
1215 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1217 // "I" got into the work list because it made the transition from undef to
1220 // Anything on this worklist that is overdefined need not be visited
1221 // since all of its users will have already been marked as overdefined.
1222 // Update all of the users of this instruction's value.
1224 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1225 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1227 if (Instruction *I = dyn_cast<Instruction>(*UI))
1228 OperandChangedState(I);
1231 // Process the basic block work list.
1232 while (!BBWorkList.empty()) {
1233 BasicBlock *BB = BBWorkList.back();
1234 BBWorkList.pop_back();
1236 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1238 // Notify all instructions in this basic block that they are newly
1245 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1246 /// that branches on undef values cannot reach any of their successors.
1247 /// However, this is not a safe assumption. After we solve dataflow, this
1248 /// method should be use to handle this. If this returns true, the solver
1249 /// should be rerun.
1251 /// This method handles this by finding an unresolved branch and marking it one
1252 /// of the edges from the block as being feasible, even though the condition
1253 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1254 /// CFG and only slightly pessimizes the analysis results (by marking one,
1255 /// potentially infeasible, edge feasible). This cannot usefully modify the
1256 /// constraints on the condition of the branch, as that would impact other users
1259 /// This scan also checks for values that use undefs, whose results are actually
1260 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1261 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1262 /// even if X isn't defined.
1263 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1264 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1265 if (!BBExecutable.count(BB))
1268 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1269 // Look for instructions which produce undef values.
1270 if (I->getType()->isVoidTy()) continue;
1272 if (StructType *STy = dyn_cast<StructType>(I->getType())) {
1273 // Only a few things that can be structs matter for undef.
1275 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1276 if (CallSite CS = CallSite(I))
1277 if (Function *F = CS.getCalledFunction())
1278 if (MRVFunctionsTracked.count(F))
1281 // extractvalue and insertvalue don't need to be marked; they are
1282 // tracked as precisely as their operands.
1283 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1286 // Send the results of everything else to overdefined. We could be
1287 // more precise than this but it isn't worth bothering.
1288 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1289 LatticeVal &LV = getStructValueState(I, i);
1290 if (LV.isUndefined())
1291 markOverdefined(LV, I);
1296 LatticeVal &LV = getValueState(I);
1297 if (!LV.isUndefined()) continue;
1299 // extractvalue is safe; check here because the argument is a struct.
1300 if (isa<ExtractValueInst>(I))
1303 // Compute the operand LatticeVals, for convenience below.
1304 // Anything taking a struct is conservatively assumed to require
1305 // overdefined markings.
1306 if (I->getOperand(0)->getType()->isStructTy()) {
1310 LatticeVal Op0LV = getValueState(I->getOperand(0));
1312 if (I->getNumOperands() == 2) {
1313 if (I->getOperand(1)->getType()->isStructTy()) {
1318 Op1LV = getValueState(I->getOperand(1));
1320 // If this is an instructions whose result is defined even if the input is
1321 // not fully defined, propagate the information.
1322 Type *ITy = I->getType();
1323 switch (I->getOpcode()) {
1324 case Instruction::Add:
1325 case Instruction::Sub:
1326 case Instruction::Trunc:
1327 case Instruction::FPTrunc:
1328 case Instruction::BitCast:
1329 break; // Any undef -> undef
1330 case Instruction::FSub:
1331 case Instruction::FAdd:
1332 case Instruction::FMul:
1333 case Instruction::FDiv:
1334 case Instruction::FRem:
1335 // Floating-point binary operation: be conservative.
1336 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1337 markForcedConstant(I, Constant::getNullValue(ITy));
1341 case Instruction::ZExt:
1342 case Instruction::SExt:
1343 case Instruction::FPToUI:
1344 case Instruction::FPToSI:
1345 case Instruction::FPExt:
1346 case Instruction::PtrToInt:
1347 case Instruction::IntToPtr:
1348 case Instruction::SIToFP:
1349 case Instruction::UIToFP:
1350 // undef -> 0; some outputs are impossible
1351 markForcedConstant(I, Constant::getNullValue(ITy));
1353 case Instruction::Mul:
1354 case Instruction::And:
1355 // Both operands undef -> undef
1356 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1358 // undef * X -> 0. X could be zero.
1359 // undef & X -> 0. X could be zero.
1360 markForcedConstant(I, Constant::getNullValue(ITy));
1363 case Instruction::Or:
1364 // Both operands undef -> undef
1365 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1367 // undef | X -> -1. X could be -1.
1368 markForcedConstant(I, Constant::getAllOnesValue(ITy));
1371 case Instruction::Xor:
1372 // undef ^ undef -> 0; strictly speaking, this is not strictly
1373 // necessary, but we try to be nice to people who expect this
1374 // behavior in simple cases
1375 if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
1376 markForcedConstant(I, Constant::getNullValue(ITy));
1379 // undef ^ X -> undef
1382 case Instruction::SDiv:
1383 case Instruction::UDiv:
1384 case Instruction::SRem:
1385 case Instruction::URem:
1386 // X / undef -> undef. No change.
1387 // X % undef -> undef. No change.
1388 if (Op1LV.isUndefined()) break;
1390 // undef / X -> 0. X could be maxint.
1391 // undef % X -> 0. X could be 1.
1392 markForcedConstant(I, Constant::getNullValue(ITy));
1395 case Instruction::AShr:
1396 // X >>a undef -> undef.
1397 if (Op1LV.isUndefined()) break;
1399 // undef >>a X -> all ones
1400 markForcedConstant(I, Constant::getAllOnesValue(ITy));
1402 case Instruction::LShr:
1403 case Instruction::Shl:
1404 // X << undef -> undef.
1405 // X >> undef -> undef.
1406 if (Op1LV.isUndefined()) break;
1410 markForcedConstant(I, Constant::getNullValue(ITy));
1412 case Instruction::Select:
1413 Op1LV = getValueState(I->getOperand(1));
1414 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1415 if (Op0LV.isUndefined()) {
1416 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1417 Op1LV = getValueState(I->getOperand(2));
1418 } else if (Op1LV.isUndefined()) {
1419 // c ? undef : undef -> undef. No change.
1420 Op1LV = getValueState(I->getOperand(2));
1421 if (Op1LV.isUndefined())
1423 // Otherwise, c ? undef : x -> x.
1425 // Leave Op1LV as Operand(1)'s LatticeValue.
1428 if (Op1LV.isConstant())
1429 markForcedConstant(I, Op1LV.getConstant());
1433 case Instruction::Load:
1434 // A load here means one of two things: a load of undef from a global,
1435 // a load from an unknown pointer. Either way, having it return undef
1438 case Instruction::ICmp:
1439 // X == undef -> undef. Other comparisons get more complicated.
1440 if (cast<ICmpInst>(I)->isEquality())
1444 case Instruction::Call:
1445 case Instruction::Invoke: {
1446 // There are two reasons a call can have an undef result
1447 // 1. It could be tracked.
1448 // 2. It could be constant-foldable.
1449 // Because of the way we solve return values, tracked calls must
1450 // never be marked overdefined in ResolvedUndefsIn.
1451 if (Function *F = CallSite(I).getCalledFunction())
1452 if (TrackedRetVals.count(F))
1455 // If the call is constant-foldable, we mark it overdefined because
1456 // we do not know what return values are valid.
1461 // If we don't know what should happen here, conservatively mark it
1468 // Check to see if we have a branch or switch on an undefined value. If so
1469 // we force the branch to go one way or the other to make the successor
1470 // values live. It doesn't really matter which way we force it.
1471 TerminatorInst *TI = BB->getTerminator();
1472 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1473 if (!BI->isConditional()) continue;
1474 if (!getValueState(BI->getCondition()).isUndefined())
1477 // If the input to SCCP is actually branch on undef, fix the undef to
1479 if (isa<UndefValue>(BI->getCondition())) {
1480 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1481 markEdgeExecutable(BB, TI->getSuccessor(1));
1485 // Otherwise, it is a branch on a symbolic value which is currently
1486 // considered to be undef. Handle this by forcing the input value to the
1488 markForcedConstant(BI->getCondition(),
1489 ConstantInt::getFalse(TI->getContext()));
1493 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1494 if (SI->getNumSuccessors() < 2) // no cases
1496 if (!getValueState(SI->getCondition()).isUndefined())
1499 // If the input to SCCP is actually switch on undef, fix the undef to
1500 // the first constant.
1501 if (isa<UndefValue>(SI->getCondition())) {
1502 SI->setCondition(SI->getCaseValue(1));
1503 markEdgeExecutable(BB, TI->getSuccessor(1));
1507 markForcedConstant(SI->getCondition(), SI->getCaseValue(1));
1517 //===--------------------------------------------------------------------===//
1519 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1520 /// Sparse Conditional Constant Propagator.
1522 struct SCCP : public FunctionPass {
1523 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1524 AU.addRequired<TargetLibraryInfo>();
1526 static char ID; // Pass identification, replacement for typeid
1527 SCCP() : FunctionPass(ID) {
1528 initializeSCCPPass(*PassRegistry::getPassRegistry());
1531 // runOnFunction - Run the Sparse Conditional Constant Propagation
1532 // algorithm, and return true if the function was modified.
1534 bool runOnFunction(Function &F);
1536 } // end anonymous namespace
1539 INITIALIZE_PASS(SCCP, "sccp",
1540 "Sparse Conditional Constant Propagation", false, false)
1542 // createSCCPPass - This is the public interface to this file.
1543 FunctionPass *llvm::createSCCPPass() {
1547 static void DeleteInstructionInBlock(BasicBlock *BB) {
1548 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1551 // Check to see if there are non-terminating instructions to delete.
1552 if (isa<TerminatorInst>(BB->begin()))
1555 // Delete the instructions backwards, as it has a reduced likelihood of having
1556 // to update as many def-use and use-def chains.
1557 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1558 while (EndInst != BB->begin()) {
1559 // Delete the next to last instruction.
1560 BasicBlock::iterator I = EndInst;
1561 Instruction *Inst = --I;
1562 if (!Inst->use_empty())
1563 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1564 if (isa<LandingPadInst>(Inst)) {
1568 BB->getInstList().erase(Inst);
1573 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1574 // and return true if the function was modified.
1576 bool SCCP::runOnFunction(Function &F) {
1577 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1578 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1579 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1580 SCCPSolver Solver(TD, TLI);
1582 // Mark the first block of the function as being executable.
1583 Solver.MarkBlockExecutable(F.begin());
1585 // Mark all arguments to the function as being overdefined.
1586 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1587 Solver.markAnythingOverdefined(AI);
1589 // Solve for constants.
1590 bool ResolvedUndefs = true;
1591 while (ResolvedUndefs) {
1593 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1594 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1597 bool MadeChanges = false;
1599 // If we decided that there are basic blocks that are dead in this function,
1600 // delete their contents now. Note that we cannot actually delete the blocks,
1601 // as we cannot modify the CFG of the function.
1603 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1604 if (!Solver.isBlockExecutable(BB)) {
1605 DeleteInstructionInBlock(BB);
1610 // Iterate over all of the instructions in a function, replacing them with
1611 // constants if we have found them to be of constant values.
1613 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1614 Instruction *Inst = BI++;
1615 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1618 // TODO: Reconstruct structs from their elements.
1619 if (Inst->getType()->isStructTy())
1622 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1623 if (IV.isOverdefined())
1626 Constant *Const = IV.isConstant()
1627 ? IV.getConstant() : UndefValue::get(Inst->getType());
1628 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
1630 // Replaces all of the uses of a variable with uses of the constant.
1631 Inst->replaceAllUsesWith(Const);
1633 // Delete the instruction.
1634 Inst->eraseFromParent();
1636 // Hey, we just changed something!
1646 //===--------------------------------------------------------------------===//
1648 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1649 /// Constant Propagation.
1651 struct IPSCCP : public ModulePass {
1652 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1653 AU.addRequired<TargetLibraryInfo>();
1656 IPSCCP() : ModulePass(ID) {
1657 initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1659 bool runOnModule(Module &M);
1661 } // end anonymous namespace
1663 char IPSCCP::ID = 0;
1664 INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
1665 "Interprocedural Sparse Conditional Constant Propagation",
1667 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1668 INITIALIZE_PASS_END(IPSCCP, "ipsccp",
1669 "Interprocedural Sparse Conditional Constant Propagation",
1672 // createIPSCCPPass - This is the public interface to this file.
1673 ModulePass *llvm::createIPSCCPPass() {
1674 return new IPSCCP();
1678 static bool AddressIsTaken(const GlobalValue *GV) {
1679 // Delete any dead constantexpr klingons.
1680 GV->removeDeadConstantUsers();
1682 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1684 const User *U = *UI;
1685 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
1686 if (SI->getOperand(0) == GV || SI->isVolatile())
1687 return true; // Storing addr of GV.
1688 } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
1689 // Make sure we are calling the function, not passing the address.
1690 ImmutableCallSite CS(cast<Instruction>(U));
1691 if (!CS.isCallee(UI))
1693 } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
1694 if (LI->isVolatile())
1696 } else if (isa<BlockAddress>(U)) {
1697 // blockaddress doesn't take the address of the function, it takes addr
1706 bool IPSCCP::runOnModule(Module &M) {
1707 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1708 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1709 SCCPSolver Solver(TD, TLI);
1711 // AddressTakenFunctions - This set keeps track of the address-taken functions
1712 // that are in the input. As IPSCCP runs through and simplifies code,
1713 // functions that were address taken can end up losing their
1714 // address-taken-ness. Because of this, we keep track of their addresses from
1715 // the first pass so we can use them for the later simplification pass.
1716 SmallPtrSet<Function*, 32> AddressTakenFunctions;
1718 // Loop over all functions, marking arguments to those with their addresses
1719 // taken or that are external as overdefined.
1721 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1722 if (F->isDeclaration())
1725 // If this is a strong or ODR definition of this function, then we can
1726 // propagate information about its result into callsites of it.
1727 if (!F->mayBeOverridden())
1728 Solver.AddTrackedFunction(F);
1730 // If this function only has direct calls that we can see, we can track its
1731 // arguments and return value aggressively, and can assume it is not called
1732 // unless we see evidence to the contrary.
1733 if (F->hasLocalLinkage()) {
1734 if (AddressIsTaken(F))
1735 AddressTakenFunctions.insert(F);
1737 Solver.AddArgumentTrackedFunction(F);
1742 // Assume the function is called.
1743 Solver.MarkBlockExecutable(F->begin());
1745 // Assume nothing about the incoming arguments.
1746 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1748 Solver.markAnythingOverdefined(AI);
1751 // Loop over global variables. We inform the solver about any internal global
1752 // variables that do not have their 'addresses taken'. If they don't have
1753 // their addresses taken, we can propagate constants through them.
1754 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1756 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
1757 Solver.TrackValueOfGlobalVariable(G);
1759 // Solve for constants.
1760 bool ResolvedUndefs = true;
1761 while (ResolvedUndefs) {
1764 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1765 ResolvedUndefs = false;
1766 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1767 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1770 bool MadeChanges = false;
1772 // Iterate over all of the instructions in the module, replacing them with
1773 // constants if we have found them to be of constant values.
1775 SmallVector<BasicBlock*, 512> BlocksToErase;
1777 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1778 if (Solver.isBlockExecutable(F->begin())) {
1779 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1781 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
1783 // TODO: Could use getStructLatticeValueFor to find out if the entire
1784 // result is a constant and replace it entirely if so.
1786 LatticeVal IV = Solver.getLatticeValueFor(AI);
1787 if (IV.isOverdefined()) continue;
1789 Constant *CST = IV.isConstant() ?
1790 IV.getConstant() : UndefValue::get(AI->getType());
1791 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1793 // Replaces all of the uses of a variable with uses of the
1795 AI->replaceAllUsesWith(CST);
1800 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
1801 if (!Solver.isBlockExecutable(BB)) {
1802 DeleteInstructionInBlock(BB);
1805 TerminatorInst *TI = BB->getTerminator();
1806 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1807 BasicBlock *Succ = TI->getSuccessor(i);
1808 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1809 TI->getSuccessor(i)->removePredecessor(BB);
1811 if (!TI->use_empty())
1812 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1813 TI->eraseFromParent();
1815 if (&*BB != &F->front())
1816 BlocksToErase.push_back(BB);
1818 new UnreachableInst(M.getContext(), BB);
1822 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1823 Instruction *Inst = BI++;
1824 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
1827 // TODO: Could use getStructLatticeValueFor to find out if the entire
1828 // result is a constant and replace it entirely if so.
1830 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1831 if (IV.isOverdefined())
1834 Constant *Const = IV.isConstant()
1835 ? IV.getConstant() : UndefValue::get(Inst->getType());
1836 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
1838 // Replaces all of the uses of a variable with uses of the
1840 Inst->replaceAllUsesWith(Const);
1842 // Delete the instruction.
1843 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1844 Inst->eraseFromParent();
1846 // Hey, we just changed something!
1852 // Now that all instructions in the function are constant folded, erase dead
1853 // blocks, because we can now use ConstantFoldTerminator to get rid of
1855 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1856 // If there are any PHI nodes in this successor, drop entries for BB now.
1857 BasicBlock *DeadBB = BlocksToErase[i];
1858 for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1860 // Grab the user and then increment the iterator early, as the user
1861 // will be deleted. Step past all adjacent uses from the same user.
1862 Instruction *I = dyn_cast<Instruction>(*UI);
1863 do { ++UI; } while (UI != UE && *UI == I);
1865 // Ignore blockaddress users; BasicBlock's dtor will handle them.
1868 bool Folded = ConstantFoldTerminator(I->getParent());
1870 // The constant folder may not have been able to fold the terminator
1871 // if this is a branch or switch on undef. Fold it manually as a
1872 // branch to the first successor.
1874 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1875 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1876 "Branch should be foldable!");
1877 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1878 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1880 llvm_unreachable("Didn't fold away reference to block!");
1884 // Make this an uncond branch to the first successor.
1885 TerminatorInst *TI = I->getParent()->getTerminator();
1886 BranchInst::Create(TI->getSuccessor(0), TI);
1888 // Remove entries in successor phi nodes to remove edges.
1889 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1890 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1892 // Remove the old terminator.
1893 TI->eraseFromParent();
1897 // Finally, delete the basic block.
1898 F->getBasicBlockList().erase(DeadBB);
1900 BlocksToErase.clear();
1903 // If we inferred constant or undef return values for a function, we replaced
1904 // all call uses with the inferred value. This means we don't need to bother
1905 // actually returning anything from the function. Replace all return
1906 // instructions with return undef.
1908 // Do this in two stages: first identify the functions we should process, then
1909 // actually zap their returns. This is important because we can only do this
1910 // if the address of the function isn't taken. In cases where a return is the
1911 // last use of a function, the order of processing functions would affect
1912 // whether other functions are optimizable.
1913 SmallVector<ReturnInst*, 8> ReturnsToZap;
1915 // TODO: Process multiple value ret instructions also.
1916 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1917 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1918 E = RV.end(); I != E; ++I) {
1919 Function *F = I->first;
1920 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1923 // We can only do this if we know that nothing else can call the function.
1924 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
1927 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1928 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1929 if (!isa<UndefValue>(RI->getOperand(0)))
1930 ReturnsToZap.push_back(RI);
1933 // Zap all returns which we've identified as zap to change.
1934 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1935 Function *F = ReturnsToZap[i]->getParent()->getParent();
1936 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1939 // If we inferred constant or undef values for globals variables, we can delete
1940 // the global and any stores that remain to it.
1941 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1942 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1943 E = TG.end(); I != E; ++I) {
1944 GlobalVariable *GV = I->first;
1945 assert(!I->second.isOverdefined() &&
1946 "Overdefined values should have been taken out of the map!");
1947 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1948 while (!GV->use_empty()) {
1949 StoreInst *SI = cast<StoreInst>(GV->use_back());
1950 SI->eraseFromParent();
1952 M.getGlobalList().erase(GV);