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
19 // * This pass has a habit of making definitions be dead. It is a good idea
20 // to to run a DCE pass sometime after running this pass.
22 //===----------------------------------------------------------------------===//
24 #define DEBUG_TYPE "sccp"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/Transforms/IPO.h"
27 #include "llvm/Constants.h"
28 #include "llvm/DerivedTypes.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Analysis/ConstantFolding.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include "llvm/Support/CallSite.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/InstVisitor.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/SmallSet.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(IPNumDeadBlocks , "Number of basic blocks unreachable 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.
59 class VISIBILITY_HIDDEN LatticeVal {
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
76 } LatticeValue; // The current lattice position
78 Constant *ConstantVal; // If Constant value, the current value
80 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
82 // markOverdefined - Return true if this is a new status to be in...
83 inline bool markOverdefined() {
84 if (LatticeValue != overdefined) {
85 LatticeValue = overdefined;
91 // markConstant - Return true if this is a new status for us.
92 inline bool markConstant(Constant *V) {
93 if (LatticeValue != constant) {
94 if (LatticeValue == undefined) {
95 LatticeValue = constant;
96 assert(V && "Marking constant with NULL");
99 assert(LatticeValue == forcedconstant &&
100 "Cannot move from overdefined to constant!");
101 // Stay at forcedconstant if the constant is the same.
102 if (V == ConstantVal) return false;
104 // Otherwise, we go to overdefined. Assumptions made based on the
105 // forced value are possibly wrong. Assuming this is another constant
106 // could expose a contradiction.
107 LatticeValue = overdefined;
111 assert(ConstantVal == V && "Marking constant with different value");
116 inline void markForcedConstant(Constant *V) {
117 assert(LatticeValue == undefined && "Can't force a defined value!");
118 LatticeValue = forcedconstant;
122 inline bool isUndefined() const { return LatticeValue == undefined; }
123 inline bool isConstant() const {
124 return LatticeValue == constant || LatticeValue == forcedconstant;
126 inline bool isOverdefined() const { return LatticeValue == overdefined; }
128 inline Constant *getConstant() const {
129 assert(isConstant() && "Cannot get the constant of a non-constant!");
134 //===----------------------------------------------------------------------===//
136 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
137 /// Constant Propagation.
139 class SCCPSolver : public InstVisitor<SCCPSolver> {
140 SmallSet<BasicBlock*, 16> BBExecutable;// The basic blocks that are executable
141 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
143 /// GlobalValue - If we are tracking any values for the contents of a global
144 /// variable, we keep a mapping from the constant accessor to the element of
145 /// the global, to the currently known value. If the value becomes
146 /// overdefined, it's entry is simply removed from this map.
147 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
149 /// TrackedRetVals - If we are tracking arguments into and the return
150 /// value out of a function, it will have an entry in this map, indicating
151 /// what the known return value for the function is.
152 DenseMap<Function*, LatticeVal> TrackedRetVals;
154 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
155 /// that return multiple values.
156 std::map<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
158 // The reason for two worklists is that overdefined is the lowest state
159 // on the lattice, and moving things to overdefined as fast as possible
160 // makes SCCP converge much faster.
161 // By having a separate worklist, we accomplish this because everything
162 // possibly overdefined will become overdefined at the soonest possible
164 std::vector<Value*> OverdefinedInstWorkList;
165 std::vector<Value*> InstWorkList;
168 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
170 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
171 /// overdefined, despite the fact that the PHI node is overdefined.
172 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
174 /// KnownFeasibleEdges - Entries in this set are edges which have already had
175 /// PHI nodes retriggered.
176 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
177 std::set<Edge> KnownFeasibleEdges;
180 /// MarkBlockExecutable - This method can be used by clients to mark all of
181 /// the blocks that are known to be intrinsically live in the processed unit.
182 void MarkBlockExecutable(BasicBlock *BB) {
183 DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n";
184 BBExecutable.insert(BB); // Basic block is executable!
185 BBWorkList.push_back(BB); // Add the block to the work list!
188 /// TrackValueOfGlobalVariable - Clients can use this method to
189 /// inform the SCCPSolver that it should track loads and stores to the
190 /// specified global variable if it can. This is only legal to call if
191 /// performing Interprocedural SCCP.
192 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
193 const Type *ElTy = GV->getType()->getElementType();
194 if (ElTy->isFirstClassType()) {
195 LatticeVal &IV = TrackedGlobals[GV];
196 if (!isa<UndefValue>(GV->getInitializer()))
197 IV.markConstant(GV->getInitializer());
201 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
202 /// and out of the specified function (which cannot have its address taken),
203 /// this method must be called.
204 void AddTrackedFunction(Function *F) {
205 assert(F->hasInternalLinkage() && "Can only track internal functions!");
206 // Add an entry, F -> undef.
207 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
208 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
209 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
212 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
215 /// Solve - Solve for constants and executable blocks.
219 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
220 /// that branches on undef values cannot reach any of their successors.
221 /// However, this is not a safe assumption. After we solve dataflow, this
222 /// method should be use to handle this. If this returns true, the solver
224 bool ResolvedUndefsIn(Function &F);
226 /// getExecutableBlocks - Once we have solved for constants, return the set of
227 /// blocks that is known to be executable.
228 SmallSet<BasicBlock*, 16> &getExecutableBlocks() {
232 /// getValueMapping - Once we have solved for constants, return the mapping of
233 /// LLVM values to LatticeVals.
234 std::map<Value*, LatticeVal> &getValueMapping() {
238 /// getTrackedRetVals - Get the inferred return value map.
240 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
241 return TrackedRetVals;
244 /// getTrackedGlobals - Get and return the set of inferred initializers for
245 /// global variables.
246 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
247 return TrackedGlobals;
250 inline void markOverdefined(Value *V) {
251 markOverdefined(ValueState[V], V);
255 // markConstant - Make a value be marked as "constant". If the value
256 // is not already a constant, add it to the instruction work list so that
257 // the users of the instruction are updated later.
259 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
260 if (IV.markConstant(C)) {
261 DOUT << "markConstant: " << *C << ": " << *V;
262 InstWorkList.push_back(V);
266 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
267 IV.markForcedConstant(C);
268 DOUT << "markForcedConstant: " << *C << ": " << *V;
269 InstWorkList.push_back(V);
272 inline void markConstant(Value *V, Constant *C) {
273 markConstant(ValueState[V], V, C);
276 // markOverdefined - Make a value be marked as "overdefined". If the
277 // value is not already overdefined, add it to the overdefined instruction
278 // work list so that the users of the instruction are updated later.
279 inline void markOverdefined(LatticeVal &IV, Value *V) {
280 if (IV.markOverdefined()) {
281 DEBUG(DOUT << "markOverdefined: ";
282 if (Function *F = dyn_cast<Function>(V))
283 DOUT << "Function '" << F->getName() << "'\n";
286 // Only instructions go on the work list
287 OverdefinedInstWorkList.push_back(V);
291 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
292 if (IV.isOverdefined() || MergeWithV.isUndefined())
294 if (MergeWithV.isOverdefined())
295 markOverdefined(IV, V);
296 else if (IV.isUndefined())
297 markConstant(IV, V, MergeWithV.getConstant());
298 else if (IV.getConstant() != MergeWithV.getConstant())
299 markOverdefined(IV, V);
302 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
303 return mergeInValue(ValueState[V], V, MergeWithV);
307 // getValueState - Return the LatticeVal object that corresponds to the value.
308 // This function is necessary because not all values should start out in the
309 // underdefined state... Argument's should be overdefined, and
310 // constants should be marked as constants. If a value is not known to be an
311 // Instruction object, then use this accessor to get its value from the map.
313 inline LatticeVal &getValueState(Value *V) {
314 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
315 if (I != ValueState.end()) return I->second; // Common case, in the map
317 if (Constant *C = dyn_cast<Constant>(V)) {
318 if (isa<UndefValue>(V)) {
319 // Nothing to do, remain undefined.
321 LatticeVal &LV = ValueState[C];
322 LV.markConstant(C); // Constants are constant
326 // All others are underdefined by default...
327 return ValueState[V];
330 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
331 // work list if it is not already executable...
333 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
334 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
335 return; // This edge is already known to be executable!
337 if (BBExecutable.count(Dest)) {
338 DOUT << "Marking Edge Executable: " << Source->getNameStart()
339 << " -> " << Dest->getNameStart() << "\n";
341 // The destination is already executable, but we just made an edge
342 // feasible that wasn't before. Revisit the PHI nodes in the block
343 // because they have potentially new operands.
344 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
345 visitPHINode(*cast<PHINode>(I));
348 MarkBlockExecutable(Dest);
352 // getFeasibleSuccessors - Return a vector of booleans to indicate which
353 // successors are reachable from a given terminator instruction.
355 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
357 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
358 // block to the 'To' basic block is currently feasible...
360 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
362 // OperandChangedState - This method is invoked on all of the users of an
363 // instruction that was just changed state somehow.... Based on this
364 // information, we need to update the specified user of this instruction.
366 void OperandChangedState(User *U) {
367 // Only instructions use other variable values!
368 Instruction &I = cast<Instruction>(*U);
369 if (BBExecutable.count(I.getParent())) // Inst is executable?
374 friend class InstVisitor<SCCPSolver>;
376 // visit implementations - Something changed in this instruction... Either an
377 // operand made a transition, or the instruction is newly executable. Change
378 // the value type of I to reflect these changes if appropriate.
380 void visitPHINode(PHINode &I);
383 void visitReturnInst(ReturnInst &I);
384 void visitTerminatorInst(TerminatorInst &TI);
386 void visitCastInst(CastInst &I);
387 void visitGetResultInst(GetResultInst &GRI);
388 void visitSelectInst(SelectInst &I);
389 void visitBinaryOperator(Instruction &I);
390 void visitCmpInst(CmpInst &I);
391 void visitExtractElementInst(ExtractElementInst &I);
392 void visitInsertElementInst(InsertElementInst &I);
393 void visitShuffleVectorInst(ShuffleVectorInst &I);
394 void visitExtractValueInst(ExtractValueInst &EVI);
395 void visitInsertValueInst(InsertValueInst &IVI);
397 // Instructions that cannot be folded away...
398 void visitStoreInst (Instruction &I);
399 void visitLoadInst (LoadInst &I);
400 void visitGetElementPtrInst(GetElementPtrInst &I);
401 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
402 void visitInvokeInst (InvokeInst &II) {
403 visitCallSite(CallSite::get(&II));
404 visitTerminatorInst(II);
406 void visitCallSite (CallSite CS);
407 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
408 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
409 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
410 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
411 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
412 void visitFreeInst (Instruction &I) { /*returns void*/ }
414 void visitInstruction(Instruction &I) {
415 // If a new instruction is added to LLVM that we don't handle...
416 cerr << "SCCP: Don't know how to handle: " << I;
417 markOverdefined(&I); // Just in case
421 } // end anonymous namespace
424 // getFeasibleSuccessors - Return a vector of booleans to indicate which
425 // successors are reachable from a given terminator instruction.
427 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
428 SmallVector<bool, 16> &Succs) {
429 Succs.resize(TI.getNumSuccessors());
430 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
431 if (BI->isUnconditional()) {
434 LatticeVal &BCValue = getValueState(BI->getCondition());
435 if (BCValue.isOverdefined() ||
436 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
437 // Overdefined condition variables, and branches on unfoldable constant
438 // conditions, mean the branch could go either way.
439 Succs[0] = Succs[1] = true;
440 } else if (BCValue.isConstant()) {
441 // Constant condition variables mean the branch can only go a single way
442 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
445 } else if (isa<InvokeInst>(&TI)) {
446 // Invoke instructions successors are always executable.
447 Succs[0] = Succs[1] = true;
448 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
449 LatticeVal &SCValue = getValueState(SI->getCondition());
450 if (SCValue.isOverdefined() || // Overdefined condition?
451 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
452 // All destinations are executable!
453 Succs.assign(TI.getNumSuccessors(), true);
454 } else if (SCValue.isConstant())
455 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
457 assert(0 && "SCCP: Don't know how to handle this terminator!");
462 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
463 // block to the 'To' basic block is currently feasible...
465 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
466 assert(BBExecutable.count(To) && "Dest should always be alive!");
468 // Make sure the source basic block is executable!!
469 if (!BBExecutable.count(From)) return false;
471 // Check to make sure this edge itself is actually feasible now...
472 TerminatorInst *TI = From->getTerminator();
473 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
474 if (BI->isUnconditional())
477 LatticeVal &BCValue = getValueState(BI->getCondition());
478 if (BCValue.isOverdefined()) {
479 // Overdefined condition variables mean the branch could go either way.
481 } else if (BCValue.isConstant()) {
482 // Not branching on an evaluatable constant?
483 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
485 // Constant condition variables mean the branch can only go a single way
486 return BI->getSuccessor(BCValue.getConstant() ==
487 ConstantInt::getFalse()) == To;
491 } else if (isa<InvokeInst>(TI)) {
492 // Invoke instructions successors are always executable.
494 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
495 LatticeVal &SCValue = getValueState(SI->getCondition());
496 if (SCValue.isOverdefined()) { // Overdefined condition?
497 // All destinations are executable!
499 } else if (SCValue.isConstant()) {
500 Constant *CPV = SCValue.getConstant();
501 if (!isa<ConstantInt>(CPV))
502 return true; // not a foldable constant?
504 // Make sure to skip the "default value" which isn't a value
505 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
506 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
507 return SI->getSuccessor(i) == To;
509 // Constant value not equal to any of the branches... must execute
510 // default branch then...
511 return SI->getDefaultDest() == To;
515 cerr << "Unknown terminator instruction: " << *TI;
520 // visit Implementations - Something changed in this instruction... Either an
521 // operand made a transition, or the instruction is newly executable. Change
522 // the value type of I to reflect these changes if appropriate. This method
523 // makes sure to do the following actions:
525 // 1. If a phi node merges two constants in, and has conflicting value coming
526 // from different branches, or if the PHI node merges in an overdefined
527 // value, then the PHI node becomes overdefined.
528 // 2. If a phi node merges only constants in, and they all agree on value, the
529 // PHI node becomes a constant value equal to that.
530 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
531 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
532 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
533 // 6. If a conditional branch has a value that is constant, make the selected
534 // destination executable
535 // 7. If a conditional branch has a value that is overdefined, make all
536 // successors executable.
538 void SCCPSolver::visitPHINode(PHINode &PN) {
539 LatticeVal &PNIV = getValueState(&PN);
540 if (PNIV.isOverdefined()) {
541 // There may be instructions using this PHI node that are not overdefined
542 // themselves. If so, make sure that they know that the PHI node operand
544 std::multimap<PHINode*, Instruction*>::iterator I, E;
545 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
547 SmallVector<Instruction*, 16> Users;
548 for (; I != E; ++I) Users.push_back(I->second);
549 while (!Users.empty()) {
554 return; // Quick exit
557 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
558 // and slow us down a lot. Just mark them overdefined.
559 if (PN.getNumIncomingValues() > 64) {
560 markOverdefined(PNIV, &PN);
564 // Look at all of the executable operands of the PHI node. If any of them
565 // are overdefined, the PHI becomes overdefined as well. If they are all
566 // constant, and they agree with each other, the PHI becomes the identical
567 // constant. If they are constant and don't agree, the PHI is overdefined.
568 // If there are no executable operands, the PHI remains undefined.
570 Constant *OperandVal = 0;
571 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
572 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
573 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
575 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
576 if (IV.isOverdefined()) { // PHI node becomes overdefined!
577 markOverdefined(PNIV, &PN);
581 if (OperandVal == 0) { // Grab the first value...
582 OperandVal = IV.getConstant();
583 } else { // Another value is being merged in!
584 // There is already a reachable operand. If we conflict with it,
585 // then the PHI node becomes overdefined. If we agree with it, we
588 // Check to see if there are two different constants merging...
589 if (IV.getConstant() != OperandVal) {
590 // Yes there is. This means the PHI node is not constant.
591 // You must be overdefined poor PHI.
593 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
594 return; // I'm done analyzing you
600 // If we exited the loop, this means that the PHI node only has constant
601 // arguments that agree with each other(and OperandVal is the constant) or
602 // OperandVal is null because there are no defined incoming arguments. If
603 // this is the case, the PHI remains undefined.
606 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
609 void SCCPSolver::visitReturnInst(ReturnInst &I) {
610 if (I.getNumOperands() == 0) return; // Ret void
612 Function *F = I.getParent()->getParent();
613 // If we are tracking the return value of this function, merge it in.
614 if (!F->hasInternalLinkage())
617 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
618 DenseMap<Function*, LatticeVal>::iterator TFRVI =
619 TrackedRetVals.find(F);
620 if (TFRVI != TrackedRetVals.end() &&
621 !TFRVI->second.isOverdefined()) {
622 LatticeVal &IV = getValueState(I.getOperand(0));
623 mergeInValue(TFRVI->second, F, IV);
628 // Handle functions that return multiple values.
629 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
630 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
631 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
632 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
633 if (It == TrackedMultipleRetVals.end()) break;
634 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
636 } else if (!TrackedMultipleRetVals.empty() &&
637 I.getNumOperands() == 1 &&
638 isa<StructType>(I.getOperand(0)->getType())) {
639 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
641 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
642 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
643 if (It == TrackedMultipleRetVals.end()) break;
644 Value *Val = FindInsertedValue(I.getOperand(0), i);
645 mergeInValue(It->second, F, getValueState(Val));
650 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
651 SmallVector<bool, 16> SuccFeasible;
652 getFeasibleSuccessors(TI, SuccFeasible);
654 BasicBlock *BB = TI.getParent();
656 // Mark all feasible successors executable...
657 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
659 markEdgeExecutable(BB, TI.getSuccessor(i));
662 void SCCPSolver::visitCastInst(CastInst &I) {
663 Value *V = I.getOperand(0);
664 LatticeVal &VState = getValueState(V);
665 if (VState.isOverdefined()) // Inherit overdefinedness of operand
667 else if (VState.isConstant()) // Propagate constant value
668 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
669 VState.getConstant(), I.getType()));
672 void SCCPSolver::visitGetResultInst(GetResultInst &GRI) {
673 Value *Aggr = GRI.getOperand(0);
675 // If the operand to the getresult is an undef, the result is undef.
676 if (isa<UndefValue>(Aggr))
680 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
681 F = CI->getCalledFunction();
683 F = cast<InvokeInst>(Aggr)->getCalledFunction();
685 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
687 if (F == 0 || TrackedMultipleRetVals.empty()) {
688 markOverdefined(&GRI);
692 // See if we are tracking the result of the callee.
693 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
694 It = TrackedMultipleRetVals.find(std::make_pair(F, GRI.getIndex()));
696 // If not tracking this function (for example, it is a declaration) just move
698 if (It == TrackedMultipleRetVals.end()) {
699 markOverdefined(&GRI);
703 // Otherwise, the value will be merged in here as a result of CallSite
707 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
708 Value *Aggr = EVI.getOperand(0);
710 // If the operand to the getresult is an undef, the result is undef.
711 if (isa<UndefValue>(Aggr))
714 // Currently only handle single-index extractvalues.
715 if (EVI.getNumIndices() != 1) {
716 markOverdefined(&EVI);
721 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
722 F = CI->getCalledFunction();
723 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
724 F = II->getCalledFunction();
726 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
728 if (F == 0 || TrackedMultipleRetVals.empty()) {
729 markOverdefined(&EVI);
733 // See if we are tracking the result of the callee.
734 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
735 It = TrackedMultipleRetVals.find(std::make_pair(F, *EVI.idx_begin()));
737 // If not tracking this function (for example, it is a declaration) just move
739 if (It == TrackedMultipleRetVals.end()) {
740 markOverdefined(&EVI);
744 // Otherwise, the value will be merged in here as a result of CallSite
748 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
749 Value *Aggr = IVI.getOperand(0);
750 Value *Val = IVI.getOperand(1);
752 // If the operand to the getresult is an undef, the result is undef.
753 if (isa<UndefValue>(Aggr))
756 // Currently only handle single-index insertvalues.
757 if (IVI.getNumIndices() != 1) {
758 markOverdefined(&IVI);
762 // See if we are tracking the result of the callee.
763 Function *F = IVI.getParent()->getParent();
764 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
765 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
767 // Merge in the inserted member value.
768 if (It != TrackedMultipleRetVals.end())
769 mergeInValue(It->second, F, getValueState(Val));
771 // Mark the aggregate result of the IVI overdefined; any tracking that we do will
772 // be done on the individual member values.
773 markOverdefined(&IVI);
776 void SCCPSolver::visitSelectInst(SelectInst &I) {
777 LatticeVal &CondValue = getValueState(I.getCondition());
778 if (CondValue.isUndefined())
780 if (CondValue.isConstant()) {
781 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
782 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
783 : I.getFalseValue()));
788 // Otherwise, the condition is overdefined or a constant we can't evaluate.
789 // See if we can produce something better than overdefined based on the T/F
791 LatticeVal &TVal = getValueState(I.getTrueValue());
792 LatticeVal &FVal = getValueState(I.getFalseValue());
794 // select ?, C, C -> C.
795 if (TVal.isConstant() && FVal.isConstant() &&
796 TVal.getConstant() == FVal.getConstant()) {
797 markConstant(&I, FVal.getConstant());
801 if (TVal.isUndefined()) { // select ?, undef, X -> X.
802 mergeInValue(&I, FVal);
803 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
804 mergeInValue(&I, TVal);
810 // Handle BinaryOperators and Shift Instructions...
811 void SCCPSolver::visitBinaryOperator(Instruction &I) {
812 LatticeVal &IV = ValueState[&I];
813 if (IV.isOverdefined()) return;
815 LatticeVal &V1State = getValueState(I.getOperand(0));
816 LatticeVal &V2State = getValueState(I.getOperand(1));
818 if (V1State.isOverdefined() || V2State.isOverdefined()) {
819 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
820 // operand is overdefined.
821 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
822 LatticeVal *NonOverdefVal = 0;
823 if (!V1State.isOverdefined()) {
824 NonOverdefVal = &V1State;
825 } else if (!V2State.isOverdefined()) {
826 NonOverdefVal = &V2State;
830 if (NonOverdefVal->isUndefined()) {
831 // Could annihilate value.
832 if (I.getOpcode() == Instruction::And)
833 markConstant(IV, &I, Constant::getNullValue(I.getType()));
834 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
835 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
837 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
840 if (I.getOpcode() == Instruction::And) {
841 if (NonOverdefVal->getConstant()->isNullValue()) {
842 markConstant(IV, &I, NonOverdefVal->getConstant());
843 return; // X and 0 = 0
846 if (ConstantInt *CI =
847 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
848 if (CI->isAllOnesValue()) {
849 markConstant(IV, &I, NonOverdefVal->getConstant());
850 return; // X or -1 = -1
858 // If both operands are PHI nodes, it is possible that this instruction has
859 // a constant value, despite the fact that the PHI node doesn't. Check for
860 // this condition now.
861 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
862 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
863 if (PN1->getParent() == PN2->getParent()) {
864 // Since the two PHI nodes are in the same basic block, they must have
865 // entries for the same predecessors. Walk the predecessor list, and
866 // if all of the incoming values are constants, and the result of
867 // evaluating this expression with all incoming value pairs is the
868 // same, then this expression is a constant even though the PHI node
869 // is not a constant!
871 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
872 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
873 BasicBlock *InBlock = PN1->getIncomingBlock(i);
875 getValueState(PN2->getIncomingValueForBlock(InBlock));
877 if (In1.isOverdefined() || In2.isOverdefined()) {
878 Result.markOverdefined();
879 break; // Cannot fold this operation over the PHI nodes!
880 } else if (In1.isConstant() && In2.isConstant()) {
881 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
883 if (Result.isUndefined())
884 Result.markConstant(V);
885 else if (Result.isConstant() && Result.getConstant() != V) {
886 Result.markOverdefined();
892 // If we found a constant value here, then we know the instruction is
893 // constant despite the fact that the PHI nodes are overdefined.
894 if (Result.isConstant()) {
895 markConstant(IV, &I, Result.getConstant());
896 // Remember that this instruction is virtually using the PHI node
898 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
899 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
901 } else if (Result.isUndefined()) {
905 // Okay, this really is overdefined now. Since we might have
906 // speculatively thought that this was not overdefined before, and
907 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
908 // make sure to clean out any entries that we put there, for
910 std::multimap<PHINode*, Instruction*>::iterator It, E;
911 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
913 if (It->second == &I) {
914 UsersOfOverdefinedPHIs.erase(It++);
918 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
920 if (It->second == &I) {
921 UsersOfOverdefinedPHIs.erase(It++);
927 markOverdefined(IV, &I);
928 } else if (V1State.isConstant() && V2State.isConstant()) {
929 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
930 V2State.getConstant()));
934 // Handle ICmpInst instruction...
935 void SCCPSolver::visitCmpInst(CmpInst &I) {
936 LatticeVal &IV = ValueState[&I];
937 if (IV.isOverdefined()) return;
939 LatticeVal &V1State = getValueState(I.getOperand(0));
940 LatticeVal &V2State = getValueState(I.getOperand(1));
942 if (V1State.isOverdefined() || V2State.isOverdefined()) {
943 // If both operands are PHI nodes, it is possible that this instruction has
944 // a constant value, despite the fact that the PHI node doesn't. Check for
945 // this condition now.
946 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
947 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
948 if (PN1->getParent() == PN2->getParent()) {
949 // Since the two PHI nodes are in the same basic block, they must have
950 // entries for the same predecessors. Walk the predecessor list, and
951 // if all of the incoming values are constants, and the result of
952 // evaluating this expression with all incoming value pairs is the
953 // same, then this expression is a constant even though the PHI node
954 // is not a constant!
956 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
957 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
958 BasicBlock *InBlock = PN1->getIncomingBlock(i);
960 getValueState(PN2->getIncomingValueForBlock(InBlock));
962 if (In1.isOverdefined() || In2.isOverdefined()) {
963 Result.markOverdefined();
964 break; // Cannot fold this operation over the PHI nodes!
965 } else if (In1.isConstant() && In2.isConstant()) {
966 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
969 if (Result.isUndefined())
970 Result.markConstant(V);
971 else if (Result.isConstant() && Result.getConstant() != V) {
972 Result.markOverdefined();
978 // If we found a constant value here, then we know the instruction is
979 // constant despite the fact that the PHI nodes are overdefined.
980 if (Result.isConstant()) {
981 markConstant(IV, &I, Result.getConstant());
982 // Remember that this instruction is virtually using the PHI node
984 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
985 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
987 } else if (Result.isUndefined()) {
991 // Okay, this really is overdefined now. Since we might have
992 // speculatively thought that this was not overdefined before, and
993 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
994 // make sure to clean out any entries that we put there, for
996 std::multimap<PHINode*, Instruction*>::iterator It, E;
997 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
999 if (It->second == &I) {
1000 UsersOfOverdefinedPHIs.erase(It++);
1004 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
1006 if (It->second == &I) {
1007 UsersOfOverdefinedPHIs.erase(It++);
1013 markOverdefined(IV, &I);
1014 } else if (V1State.isConstant() && V2State.isConstant()) {
1015 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
1016 V1State.getConstant(),
1017 V2State.getConstant()));
1021 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1022 // FIXME : SCCP does not handle vectors properly.
1023 markOverdefined(&I);
1027 LatticeVal &ValState = getValueState(I.getOperand(0));
1028 LatticeVal &IdxState = getValueState(I.getOperand(1));
1030 if (ValState.isOverdefined() || IdxState.isOverdefined())
1031 markOverdefined(&I);
1032 else if(ValState.isConstant() && IdxState.isConstant())
1033 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1034 IdxState.getConstant()));
1038 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1039 // FIXME : SCCP does not handle vectors properly.
1040 markOverdefined(&I);
1043 LatticeVal &ValState = getValueState(I.getOperand(0));
1044 LatticeVal &EltState = getValueState(I.getOperand(1));
1045 LatticeVal &IdxState = getValueState(I.getOperand(2));
1047 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1048 IdxState.isOverdefined())
1049 markOverdefined(&I);
1050 else if(ValState.isConstant() && EltState.isConstant() &&
1051 IdxState.isConstant())
1052 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1053 EltState.getConstant(),
1054 IdxState.getConstant()));
1055 else if (ValState.isUndefined() && EltState.isConstant() &&
1056 IdxState.isConstant())
1057 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1058 EltState.getConstant(),
1059 IdxState.getConstant()));
1063 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1064 // FIXME : SCCP does not handle vectors properly.
1065 markOverdefined(&I);
1068 LatticeVal &V1State = getValueState(I.getOperand(0));
1069 LatticeVal &V2State = getValueState(I.getOperand(1));
1070 LatticeVal &MaskState = getValueState(I.getOperand(2));
1072 if (MaskState.isUndefined() ||
1073 (V1State.isUndefined() && V2State.isUndefined()))
1074 return; // Undefined output if mask or both inputs undefined.
1076 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1077 MaskState.isOverdefined()) {
1078 markOverdefined(&I);
1080 // A mix of constant/undef inputs.
1081 Constant *V1 = V1State.isConstant() ?
1082 V1State.getConstant() : UndefValue::get(I.getType());
1083 Constant *V2 = V2State.isConstant() ?
1084 V2State.getConstant() : UndefValue::get(I.getType());
1085 Constant *Mask = MaskState.isConstant() ?
1086 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1087 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1092 // Handle getelementptr instructions... if all operands are constants then we
1093 // can turn this into a getelementptr ConstantExpr.
1095 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1096 LatticeVal &IV = ValueState[&I];
1097 if (IV.isOverdefined()) return;
1099 SmallVector<Constant*, 8> Operands;
1100 Operands.reserve(I.getNumOperands());
1102 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1103 LatticeVal &State = getValueState(I.getOperand(i));
1104 if (State.isUndefined())
1105 return; // Operands are not resolved yet...
1106 else if (State.isOverdefined()) {
1107 markOverdefined(IV, &I);
1110 assert(State.isConstant() && "Unknown state!");
1111 Operands.push_back(State.getConstant());
1114 Constant *Ptr = Operands[0];
1115 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1117 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1121 void SCCPSolver::visitStoreInst(Instruction &SI) {
1122 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1124 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1125 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1126 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1128 // Get the value we are storing into the global.
1129 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1131 mergeInValue(I->second, GV, PtrVal);
1132 if (I->second.isOverdefined())
1133 TrackedGlobals.erase(I); // No need to keep tracking this!
1137 // Handle load instructions. If the operand is a constant pointer to a constant
1138 // global, we can replace the load with the loaded constant value!
1139 void SCCPSolver::visitLoadInst(LoadInst &I) {
1140 LatticeVal &IV = ValueState[&I];
1141 if (IV.isOverdefined()) return;
1143 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1144 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1145 if (PtrVal.isConstant() && !I.isVolatile()) {
1146 Value *Ptr = PtrVal.getConstant();
1147 // TODO: Consider a target hook for valid address spaces for this xform.
1148 if (isa<ConstantPointerNull>(Ptr) &&
1149 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
1150 // load null -> null
1151 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1155 // Transform load (constant global) into the value loaded.
1156 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1157 if (GV->isConstant()) {
1158 if (!GV->isDeclaration()) {
1159 markConstant(IV, &I, GV->getInitializer());
1162 } else if (!TrackedGlobals.empty()) {
1163 // If we are tracking this global, merge in the known value for it.
1164 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1165 TrackedGlobals.find(GV);
1166 if (It != TrackedGlobals.end()) {
1167 mergeInValue(IV, &I, It->second);
1173 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1174 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1175 if (CE->getOpcode() == Instruction::GetElementPtr)
1176 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
1177 if (GV->isConstant() && !GV->isDeclaration())
1179 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
1180 markConstant(IV, &I, V);
1185 // Otherwise we cannot say for certain what value this load will produce.
1187 markOverdefined(IV, &I);
1190 void SCCPSolver::visitCallSite(CallSite CS) {
1191 Function *F = CS.getCalledFunction();
1192 Instruction *I = CS.getInstruction();
1194 // The common case is that we aren't tracking the callee, either because we
1195 // are not doing interprocedural analysis or the callee is indirect, or is
1196 // external. Handle these cases first.
1197 if (F == 0 || !F->hasInternalLinkage()) {
1199 // Void return and not tracking callee, just bail.
1200 if (I->getType() == Type::VoidTy) return;
1202 // Otherwise, if we have a single return value case, and if the function is
1203 // a declaration, maybe we can constant fold it.
1204 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1205 canConstantFoldCallTo(F)) {
1207 SmallVector<Constant*, 8> Operands;
1208 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1210 LatticeVal &State = getValueState(*AI);
1211 if (State.isUndefined())
1212 return; // Operands are not resolved yet.
1213 else if (State.isOverdefined()) {
1217 assert(State.isConstant() && "Unknown state!");
1218 Operands.push_back(State.getConstant());
1221 // If we can constant fold this, mark the result of the call as a
1223 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size())) {
1229 // Otherwise, we don't know anything about this call, mark it overdefined.
1234 // If this is a single/zero retval case, see if we're tracking the function.
1235 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1236 if (TFRVI != TrackedRetVals.end()) {
1237 // If so, propagate the return value of the callee into this call result.
1238 mergeInValue(I, TFRVI->second);
1239 } else if (isa<StructType>(I->getType())) {
1240 // Check to see if we're tracking this callee, if not, handle it in the
1241 // common path above.
1242 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
1243 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
1244 if (TMRVI == TrackedMultipleRetVals.end())
1245 goto CallOverdefined;
1247 // If we are tracking this callee, propagate the return values of the call
1248 // into this call site. We do this by walking all the uses. Single-index
1249 // ExtractValueInst uses can be tracked; anything more complicated is
1250 // currently handled conservatively.
1251 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1253 if (GetResultInst *GRI = dyn_cast<GetResultInst>(*UI)) {
1255 TrackedMultipleRetVals[std::make_pair(F, GRI->getIndex())]);
1258 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1259 if (EVI->getNumIndices() == 1) {
1261 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
1265 // The aggregate value is used in a way not handled here. Assume nothing.
1266 markOverdefined(*UI);
1269 // Otherwise we're not tracking this callee, so handle it in the
1270 // common path above.
1271 goto CallOverdefined;
1274 // Finally, if this is the first call to the function hit, mark its entry
1275 // block executable.
1276 if (!BBExecutable.count(F->begin()))
1277 MarkBlockExecutable(F->begin());
1279 // Propagate information from this call site into the callee.
1280 CallSite::arg_iterator CAI = CS.arg_begin();
1281 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1282 AI != E; ++AI, ++CAI) {
1283 LatticeVal &IV = ValueState[AI];
1284 if (!IV.isOverdefined())
1285 mergeInValue(IV, AI, getValueState(*CAI));
1290 void SCCPSolver::Solve() {
1291 // Process the work lists until they are empty!
1292 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1293 !OverdefinedInstWorkList.empty()) {
1294 // Process the instruction work list...
1295 while (!OverdefinedInstWorkList.empty()) {
1296 Value *I = OverdefinedInstWorkList.back();
1297 OverdefinedInstWorkList.pop_back();
1299 DOUT << "\nPopped off OI-WL: " << *I;
1301 // "I" got into the work list because it either made the transition from
1302 // bottom to constant
1304 // Anything on this worklist that is overdefined need not be visited
1305 // since all of its users will have already been marked as overdefined
1306 // Update all of the users of this instruction's value...
1308 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1310 OperandChangedState(*UI);
1312 // Process the instruction work list...
1313 while (!InstWorkList.empty()) {
1314 Value *I = InstWorkList.back();
1315 InstWorkList.pop_back();
1317 DOUT << "\nPopped off I-WL: " << *I;
1319 // "I" got into the work list because it either made the transition from
1320 // bottom to constant
1322 // Anything on this worklist that is overdefined need not be visited
1323 // since all of its users will have already been marked as overdefined.
1324 // Update all of the users of this instruction's value...
1326 if (!getValueState(I).isOverdefined())
1327 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1329 OperandChangedState(*UI);
1332 // Process the basic block work list...
1333 while (!BBWorkList.empty()) {
1334 BasicBlock *BB = BBWorkList.back();
1335 BBWorkList.pop_back();
1337 DOUT << "\nPopped off BBWL: " << *BB;
1339 // Notify all instructions in this basic block that they are newly
1346 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1347 /// that branches on undef values cannot reach any of their successors.
1348 /// However, this is not a safe assumption. After we solve dataflow, this
1349 /// method should be use to handle this. If this returns true, the solver
1350 /// should be rerun.
1352 /// This method handles this by finding an unresolved branch and marking it one
1353 /// of the edges from the block as being feasible, even though the condition
1354 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1355 /// CFG and only slightly pessimizes the analysis results (by marking one,
1356 /// potentially infeasible, edge feasible). This cannot usefully modify the
1357 /// constraints on the condition of the branch, as that would impact other users
1360 /// This scan also checks for values that use undefs, whose results are actually
1361 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1362 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1363 /// even if X isn't defined.
1364 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1365 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1366 if (!BBExecutable.count(BB))
1369 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1370 // Look for instructions which produce undef values.
1371 if (I->getType() == Type::VoidTy) continue;
1373 LatticeVal &LV = getValueState(I);
1374 if (!LV.isUndefined()) continue;
1376 // Get the lattice values of the first two operands for use below.
1377 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1379 if (I->getNumOperands() == 2) {
1380 // If this is a two-operand instruction, and if both operands are
1381 // undefs, the result stays undef.
1382 Op1LV = getValueState(I->getOperand(1));
1383 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1387 // If this is an instructions whose result is defined even if the input is
1388 // not fully defined, propagate the information.
1389 const Type *ITy = I->getType();
1390 switch (I->getOpcode()) {
1391 default: break; // Leave the instruction as an undef.
1392 case Instruction::ZExt:
1393 // After a zero extend, we know the top part is zero. SExt doesn't have
1394 // to be handled here, because we don't know whether the top part is 1's
1396 assert(Op0LV.isUndefined());
1397 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1399 case Instruction::Mul:
1400 case Instruction::And:
1401 // undef * X -> 0. X could be zero.
1402 // undef & X -> 0. X could be zero.
1403 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1406 case Instruction::Or:
1407 // undef | X -> -1. X could be -1.
1408 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1409 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
1411 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1414 case Instruction::SDiv:
1415 case Instruction::UDiv:
1416 case Instruction::SRem:
1417 case Instruction::URem:
1418 // X / undef -> undef. No change.
1419 // X % undef -> undef. No change.
1420 if (Op1LV.isUndefined()) break;
1422 // undef / X -> 0. X could be maxint.
1423 // undef % X -> 0. X could be 1.
1424 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1427 case Instruction::AShr:
1428 // undef >>s X -> undef. No change.
1429 if (Op0LV.isUndefined()) break;
1431 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1432 if (Op0LV.isConstant())
1433 markForcedConstant(LV, I, Op0LV.getConstant());
1435 markOverdefined(LV, I);
1437 case Instruction::LShr:
1438 case Instruction::Shl:
1439 // undef >> X -> undef. No change.
1440 // undef << X -> undef. No change.
1441 if (Op0LV.isUndefined()) break;
1443 // X >> undef -> 0. X could be 0.
1444 // X << undef -> 0. X could be 0.
1445 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1447 case Instruction::Select:
1448 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1449 if (Op0LV.isUndefined()) {
1450 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1451 Op1LV = getValueState(I->getOperand(2));
1452 } else if (Op1LV.isUndefined()) {
1453 // c ? undef : undef -> undef. No change.
1454 Op1LV = getValueState(I->getOperand(2));
1455 if (Op1LV.isUndefined())
1457 // Otherwise, c ? undef : x -> x.
1459 // Leave Op1LV as Operand(1)'s LatticeValue.
1462 if (Op1LV.isConstant())
1463 markForcedConstant(LV, I, Op1LV.getConstant());
1465 markOverdefined(LV, I);
1467 case Instruction::Call:
1468 // If a call has an undef result, it is because it is constant foldable
1469 // but one of the inputs was undef. Just force the result to
1471 markOverdefined(LV, I);
1476 TerminatorInst *TI = BB->getTerminator();
1477 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1478 if (!BI->isConditional()) continue;
1479 if (!getValueState(BI->getCondition()).isUndefined())
1481 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1482 if (SI->getNumSuccessors()<2) // no cases
1484 if (!getValueState(SI->getCondition()).isUndefined())
1490 // If the edge to the second successor isn't thought to be feasible yet,
1491 // mark it so now. We pick the second one so that this goes to some
1492 // enumerated value in a switch instead of going to the default destination.
1493 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
1496 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1497 // and return. This will make other blocks reachable, which will allow new
1498 // values to be discovered and existing ones to be moved in the lattice.
1499 markEdgeExecutable(BB, TI->getSuccessor(1));
1501 // This must be a conditional branch of switch on undef. At this point,
1502 // force the old terminator to branch to the first successor. This is
1503 // required because we are now influencing the dataflow of the function with
1504 // the assumption that this edge is taken. If we leave the branch condition
1505 // as undef, then further analysis could think the undef went another way
1506 // leading to an inconsistent set of conclusions.
1507 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1508 BI->setCondition(ConstantInt::getFalse());
1510 SwitchInst *SI = cast<SwitchInst>(TI);
1511 SI->setCondition(SI->getCaseValue(1));
1522 //===--------------------------------------------------------------------===//
1524 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1525 /// Sparse Conditional Constant Propagator.
1527 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
1528 static char ID; // Pass identification, replacement for typeid
1529 SCCP() : FunctionPass((intptr_t)&ID) {}
1531 // runOnFunction - Run the Sparse Conditional Constant Propagation
1532 // algorithm, and return true if the function was modified.
1534 bool runOnFunction(Function &F);
1536 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1537 AU.setPreservesCFG();
1540 } // end anonymous namespace
1543 static RegisterPass<SCCP>
1544 X("sccp", "Sparse Conditional Constant Propagation");
1546 // createSCCPPass - This is the public interface to this file...
1547 FunctionPass *llvm::createSCCPPass() {
1552 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1553 // and return true if the function was modified.
1555 bool SCCP::runOnFunction(Function &F) {
1556 DOUT << "SCCP on function '" << F.getNameStart() << "'\n";
1559 // Mark the first block of the function as being executable.
1560 Solver.MarkBlockExecutable(F.begin());
1562 // Mark all arguments to the function as being overdefined.
1563 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1564 Solver.markOverdefined(AI);
1566 // Solve for constants.
1567 bool ResolvedUndefs = true;
1568 while (ResolvedUndefs) {
1570 DOUT << "RESOLVING UNDEFs\n";
1571 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1574 bool MadeChanges = false;
1576 // If we decided that there are basic blocks that are dead in this function,
1577 // delete their contents now. Note that we cannot actually delete the blocks,
1578 // as we cannot modify the CFG of the function.
1580 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
1581 SmallVector<Instruction*, 32> Insts;
1582 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1584 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1585 if (!ExecutableBBs.count(BB)) {
1586 DOUT << " BasicBlock Dead:" << *BB;
1589 // Delete the instructions backwards, as it has a reduced likelihood of
1590 // having to update as many def-use and use-def chains.
1591 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1594 while (!Insts.empty()) {
1595 Instruction *I = Insts.back();
1597 if (!I->use_empty())
1598 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1599 BB->getInstList().erase(I);
1604 // Iterate over all of the instructions in a function, replacing them with
1605 // constants if we have found them to be of constant values.
1607 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1608 Instruction *Inst = BI++;
1609 if (Inst->getType() == Type::VoidTy ||
1610 isa<StructType>(Inst->getType()) ||
1611 isa<TerminatorInst>(Inst))
1614 LatticeVal &IV = Values[Inst];
1615 if (!IV.isConstant() && !IV.isUndefined())
1618 Constant *Const = IV.isConstant()
1619 ? IV.getConstant() : UndefValue::get(Inst->getType());
1620 DOUT << " Constant: " << *Const << " = " << *Inst;
1622 // Replaces all of the uses of a variable with uses of the constant.
1623 Inst->replaceAllUsesWith(Const);
1625 // Delete the instruction.
1626 Inst->eraseFromParent();
1628 // Hey, we just changed something!
1638 //===--------------------------------------------------------------------===//
1640 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1641 /// Constant Propagation.
1643 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
1645 IPSCCP() : ModulePass((intptr_t)&ID) {}
1646 bool runOnModule(Module &M);
1648 } // end anonymous namespace
1650 char IPSCCP::ID = 0;
1651 static RegisterPass<IPSCCP>
1652 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1654 // createIPSCCPPass - This is the public interface to this file...
1655 ModulePass *llvm::createIPSCCPPass() {
1656 return new IPSCCP();
1660 static bool AddressIsTaken(GlobalValue *GV) {
1661 // Delete any dead constantexpr klingons.
1662 GV->removeDeadConstantUsers();
1664 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1666 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1667 if (SI->getOperand(0) == GV || SI->isVolatile())
1668 return true; // Storing addr of GV.
1669 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1670 // Make sure we are calling the function, not passing the address.
1671 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1672 for (CallSite::arg_iterator AI = CS.arg_begin(),
1673 E = CS.arg_end(); AI != E; ++AI)
1676 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1677 if (LI->isVolatile())
1685 bool IPSCCP::runOnModule(Module &M) {
1688 // Loop over all functions, marking arguments to those with their addresses
1689 // taken or that are external as overdefined.
1691 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1692 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1693 if (!F->isDeclaration())
1694 Solver.MarkBlockExecutable(F->begin());
1695 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1697 Solver.markOverdefined(AI);
1699 Solver.AddTrackedFunction(F);
1702 // Loop over global variables. We inform the solver about any internal global
1703 // variables that do not have their 'addresses taken'. If they don't have
1704 // their addresses taken, we can propagate constants through them.
1705 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1707 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1708 Solver.TrackValueOfGlobalVariable(G);
1710 // Solve for constants.
1711 bool ResolvedUndefs = true;
1712 while (ResolvedUndefs) {
1715 DOUT << "RESOLVING UNDEFS\n";
1716 ResolvedUndefs = false;
1717 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1718 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1721 bool MadeChanges = false;
1723 // Iterate over all of the instructions in the module, replacing them with
1724 // constants if we have found them to be of constant values.
1726 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
1727 SmallVector<Instruction*, 32> Insts;
1728 SmallVector<BasicBlock*, 32> BlocksToErase;
1729 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1731 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1732 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1734 if (!AI->use_empty()) {
1735 LatticeVal &IV = Values[AI];
1736 if (IV.isConstant() || IV.isUndefined()) {
1737 Constant *CST = IV.isConstant() ?
1738 IV.getConstant() : UndefValue::get(AI->getType());
1739 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
1741 // Replaces all of the uses of a variable with uses of the
1743 AI->replaceAllUsesWith(CST);
1748 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1749 if (!ExecutableBBs.count(BB)) {
1750 DOUT << " BasicBlock Dead:" << *BB;
1753 // Delete the instructions backwards, as it has a reduced likelihood of
1754 // having to update as many def-use and use-def chains.
1755 TerminatorInst *TI = BB->getTerminator();
1756 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1759 while (!Insts.empty()) {
1760 Instruction *I = Insts.back();
1762 if (!I->use_empty())
1763 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1764 BB->getInstList().erase(I);
1769 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1770 BasicBlock *Succ = TI->getSuccessor(i);
1771 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1772 TI->getSuccessor(i)->removePredecessor(BB);
1774 if (!TI->use_empty())
1775 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1776 BB->getInstList().erase(TI);
1778 if (&*BB != &F->front())
1779 BlocksToErase.push_back(BB);
1781 new UnreachableInst(BB);
1784 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1785 Instruction *Inst = BI++;
1786 if (Inst->getType() == Type::VoidTy ||
1787 isa<StructType>(Inst->getType()) ||
1788 isa<TerminatorInst>(Inst))
1791 LatticeVal &IV = Values[Inst];
1792 if (!IV.isConstant() && !IV.isUndefined())
1795 Constant *Const = IV.isConstant()
1796 ? IV.getConstant() : UndefValue::get(Inst->getType());
1797 DOUT << " Constant: " << *Const << " = " << *Inst;
1799 // Replaces all of the uses of a variable with uses of the
1801 Inst->replaceAllUsesWith(Const);
1803 // Delete the instruction.
1804 if (!isa<CallInst>(Inst))
1805 Inst->eraseFromParent();
1807 // Hey, we just changed something!
1813 // Now that all instructions in the function are constant folded, erase dead
1814 // blocks, because we can now use ConstantFoldTerminator to get rid of
1816 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1817 // If there are any PHI nodes in this successor, drop entries for BB now.
1818 BasicBlock *DeadBB = BlocksToErase[i];
1819 while (!DeadBB->use_empty()) {
1820 Instruction *I = cast<Instruction>(DeadBB->use_back());
1821 bool Folded = ConstantFoldTerminator(I->getParent());
1823 // The constant folder may not have been able to fold the terminator
1824 // if this is a branch or switch on undef. Fold it manually as a
1825 // branch to the first successor.
1826 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1827 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1828 "Branch should be foldable!");
1829 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1830 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1832 assert(0 && "Didn't fold away reference to block!");
1835 // Make this an uncond branch to the first successor.
1836 TerminatorInst *TI = I->getParent()->getTerminator();
1837 BranchInst::Create(TI->getSuccessor(0), TI);
1839 // Remove entries in successor phi nodes to remove edges.
1840 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1841 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1843 // Remove the old terminator.
1844 TI->eraseFromParent();
1848 // Finally, delete the basic block.
1849 F->getBasicBlockList().erase(DeadBB);
1851 BlocksToErase.clear();
1854 // If we inferred constant or undef return values for a function, we replaced
1855 // all call uses with the inferred value. This means we don't need to bother
1856 // actually returning anything from the function. Replace all return
1857 // instructions with return undef.
1858 // TODO: Process multiple value ret instructions also.
1859 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1860 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1861 E = RV.end(); I != E; ++I)
1862 if (!I->second.isOverdefined() &&
1863 I->first->getReturnType() != Type::VoidTy) {
1864 Function *F = I->first;
1865 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1866 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1867 if (!isa<UndefValue>(RI->getOperand(0)))
1868 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1871 // If we infered constant or undef values for globals variables, we can delete
1872 // the global and any stores that remain to it.
1873 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1874 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1875 E = TG.end(); I != E; ++I) {
1876 GlobalVariable *GV = I->first;
1877 assert(!I->second.isOverdefined() &&
1878 "Overdefined values should have been taken out of the map!");
1879 DOUT << "Found that GV '" << GV->getNameStart() << "' is constant!\n";
1880 while (!GV->use_empty()) {
1881 StoreInst *SI = cast<StoreInst>(GV->use_back());
1882 SI->eraseFromParent();
1884 M.getGlobalList().erase(GV);