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/Transforms/Utils/Local.h"
33 #include "llvm/Support/CallSite.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/InstVisitor.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/STLExtras.h"
46 STATISTIC(NumInstRemoved, "Number of instructions removed");
47 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
50 STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
51 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
55 /// LatticeVal class - This class represents the different lattice values that
56 /// an LLVM value may occupy. It is a simple class with value semantics.
58 class VISIBILITY_HIDDEN LatticeVal {
60 /// undefined - This LLVM Value has no known value yet.
63 /// constant - This LLVM Value has a specific constant value.
66 /// forcedconstant - This LLVM Value was thought to be undef until
67 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
68 /// with another (different) constant, it goes to overdefined, instead of
72 /// overdefined - This instruction is not known to be constant, and we know
75 } LatticeValue; // The current lattice position
77 Constant *ConstantVal; // If Constant value, the current value
79 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
81 // markOverdefined - Return true if this is a new status to be in...
82 inline bool markOverdefined() {
83 if (LatticeValue != overdefined) {
84 LatticeValue = overdefined;
90 // markConstant - Return true if this is a new status for us.
91 inline bool markConstant(Constant *V) {
92 if (LatticeValue != constant) {
93 if (LatticeValue == undefined) {
94 LatticeValue = constant;
95 assert(V && "Marking constant with NULL");
98 assert(LatticeValue == forcedconstant &&
99 "Cannot move from overdefined to constant!");
100 // Stay at forcedconstant if the constant is the same.
101 if (V == ConstantVal) return false;
103 // Otherwise, we go to overdefined. Assumptions made based on the
104 // forced value are possibly wrong. Assuming this is another constant
105 // could expose a contradiction.
106 LatticeValue = overdefined;
110 assert(ConstantVal == V && "Marking constant with different value");
115 inline void markForcedConstant(Constant *V) {
116 assert(LatticeValue == undefined && "Can't force a defined value!");
117 LatticeValue = forcedconstant;
121 inline bool isUndefined() const { return LatticeValue == undefined; }
122 inline bool isConstant() const {
123 return LatticeValue == constant || LatticeValue == forcedconstant;
125 inline bool isOverdefined() const { return LatticeValue == overdefined; }
127 inline Constant *getConstant() const {
128 assert(isConstant() && "Cannot get the constant of a non-constant!");
133 //===----------------------------------------------------------------------===//
135 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
136 /// Constant Propagation.
138 class SCCPSolver : public InstVisitor<SCCPSolver> {
139 SmallSet<BasicBlock*, 16> BBExecutable;// The basic blocks that are executable
140 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
142 /// GlobalValue - If we are tracking any values for the contents of a global
143 /// variable, we keep a mapping from the constant accessor to the element of
144 /// the global, to the currently known value. If the value becomes
145 /// overdefined, it's entry is simply removed from this map.
146 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
148 /// TrackedRetVals - If we are tracking arguments into and the return
149 /// value out of a function, it will have an entry in this map, indicating
150 /// what the known return value for the function is.
151 DenseMap<Function*, LatticeVal> TrackedRetVals;
153 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
154 /// that return multiple values.
155 std::map<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
157 // The reason for two worklists is that overdefined is the lowest state
158 // on the lattice, and moving things to overdefined as fast as possible
159 // makes SCCP converge much faster.
160 // By having a separate worklist, we accomplish this because everything
161 // possibly overdefined will become overdefined at the soonest possible
163 std::vector<Value*> OverdefinedInstWorkList;
164 std::vector<Value*> InstWorkList;
167 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
169 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
170 /// overdefined, despite the fact that the PHI node is overdefined.
171 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
173 /// KnownFeasibleEdges - Entries in this set are edges which have already had
174 /// PHI nodes retriggered.
175 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
176 std::set<Edge> KnownFeasibleEdges;
179 /// MarkBlockExecutable - This method can be used by clients to mark all of
180 /// the blocks that are known to be intrinsically live in the processed unit.
181 void MarkBlockExecutable(BasicBlock *BB) {
182 DOUT << "Marking Block Executable: " << BB->getName() << "\n";
183 BBExecutable.insert(BB); // Basic block is executable!
184 BBWorkList.push_back(BB); // Add the block to the work list!
187 /// TrackValueOfGlobalVariable - Clients can use this method to
188 /// inform the SCCPSolver that it should track loads and stores to the
189 /// specified global variable if it can. This is only legal to call if
190 /// performing Interprocedural SCCP.
191 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
192 const Type *ElTy = GV->getType()->getElementType();
193 if (ElTy->isFirstClassType()) {
194 LatticeVal &IV = TrackedGlobals[GV];
195 if (!isa<UndefValue>(GV->getInitializer()))
196 IV.markConstant(GV->getInitializer());
200 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
201 /// and out of the specified function (which cannot have its address taken),
202 /// this method must be called.
203 void AddTrackedFunction(Function *F) {
204 assert(F->hasInternalLinkage() && "Can only track internal functions!");
205 // Add an entry, F -> undef.
206 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
207 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
208 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
211 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
214 /// Solve - Solve for constants and executable blocks.
218 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
219 /// that branches on undef values cannot reach any of their successors.
220 /// However, this is not a safe assumption. After we solve dataflow, this
221 /// method should be use to handle this. If this returns true, the solver
223 bool ResolvedUndefsIn(Function &F);
225 /// getExecutableBlocks - Once we have solved for constants, return the set of
226 /// blocks that is known to be executable.
227 SmallSet<BasicBlock*, 16> &getExecutableBlocks() {
231 /// getValueMapping - Once we have solved for constants, return the mapping of
232 /// LLVM values to LatticeVals.
233 std::map<Value*, LatticeVal> &getValueMapping() {
237 /// getTrackedRetVals - Get the inferred return value map.
239 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
240 return TrackedRetVals;
243 /// getTrackedGlobals - Get and return the set of inferred initializers for
244 /// global variables.
245 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
246 return TrackedGlobals;
249 inline void markOverdefined(Value *V) {
250 markOverdefined(ValueState[V], V);
254 // markConstant - Make a value be marked as "constant". If the value
255 // is not already a constant, add it to the instruction work list so that
256 // the users of the instruction are updated later.
258 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
259 if (IV.markConstant(C)) {
260 DOUT << "markConstant: " << *C << ": " << *V;
261 InstWorkList.push_back(V);
265 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
266 IV.markForcedConstant(C);
267 DOUT << "markForcedConstant: " << *C << ": " << *V;
268 InstWorkList.push_back(V);
271 inline void markConstant(Value *V, Constant *C) {
272 markConstant(ValueState[V], V, C);
275 // markOverdefined - Make a value be marked as "overdefined". If the
276 // value is not already overdefined, add it to the overdefined instruction
277 // work list so that the users of the instruction are updated later.
278 inline void markOverdefined(LatticeVal &IV, Value *V) {
279 if (IV.markOverdefined()) {
280 DEBUG(DOUT << "markOverdefined: ";
281 if (Function *F = dyn_cast<Function>(V))
282 DOUT << "Function '" << F->getName() << "'\n";
285 // Only instructions go on the work list
286 OverdefinedInstWorkList.push_back(V);
290 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
291 if (IV.isOverdefined() || MergeWithV.isUndefined())
293 if (MergeWithV.isOverdefined())
294 markOverdefined(IV, V);
295 else if (IV.isUndefined())
296 markConstant(IV, V, MergeWithV.getConstant());
297 else if (IV.getConstant() != MergeWithV.getConstant())
298 markOverdefined(IV, V);
301 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
302 return mergeInValue(ValueState[V], V, MergeWithV);
306 // getValueState - Return the LatticeVal object that corresponds to the value.
307 // This function is necessary because not all values should start out in the
308 // underdefined state... Argument's should be overdefined, and
309 // constants should be marked as constants. If a value is not known to be an
310 // Instruction object, then use this accessor to get its value from the map.
312 inline LatticeVal &getValueState(Value *V) {
313 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
314 if (I != ValueState.end()) return I->second; // Common case, in the map
316 if (Constant *C = dyn_cast<Constant>(V)) {
317 if (isa<UndefValue>(V)) {
318 // Nothing to do, remain undefined.
320 LatticeVal &LV = ValueState[C];
321 LV.markConstant(C); // Constants are constant
325 // All others are underdefined by default...
326 return ValueState[V];
329 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
330 // work list if it is not already executable...
332 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
333 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
334 return; // This edge is already known to be executable!
336 if (BBExecutable.count(Dest)) {
337 DOUT << "Marking Edge Executable: " << Source->getName()
338 << " -> " << Dest->getName() << "\n";
340 // The destination is already executable, but we just made an edge
341 // feasible that wasn't before. Revisit the PHI nodes in the block
342 // because they have potentially new operands.
343 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
344 visitPHINode(*cast<PHINode>(I));
347 MarkBlockExecutable(Dest);
351 // getFeasibleSuccessors - Return a vector of booleans to indicate which
352 // successors are reachable from a given terminator instruction.
354 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
356 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
357 // block to the 'To' basic block is currently feasible...
359 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
361 // OperandChangedState - This method is invoked on all of the users of an
362 // instruction that was just changed state somehow.... Based on this
363 // information, we need to update the specified user of this instruction.
365 void OperandChangedState(User *U) {
366 // Only instructions use other variable values!
367 Instruction &I = cast<Instruction>(*U);
368 if (BBExecutable.count(I.getParent())) // Inst is executable?
373 friend class InstVisitor<SCCPSolver>;
375 // visit implementations - Something changed in this instruction... Either an
376 // operand made a transition, or the instruction is newly executable. Change
377 // the value type of I to reflect these changes if appropriate.
379 void visitPHINode(PHINode &I);
382 void visitReturnInst(ReturnInst &I);
383 void visitTerminatorInst(TerminatorInst &TI);
385 void visitCastInst(CastInst &I);
386 void visitGetResultInst(GetResultInst &GRI);
387 void visitSelectInst(SelectInst &I);
388 void visitBinaryOperator(Instruction &I);
389 void visitCmpInst(CmpInst &I);
390 void visitExtractElementInst(ExtractElementInst &I);
391 void visitInsertElementInst(InsertElementInst &I);
392 void visitShuffleVectorInst(ShuffleVectorInst &I);
394 // Instructions that cannot be folded away...
395 void visitStoreInst (Instruction &I);
396 void visitLoadInst (LoadInst &I);
397 void visitGetElementPtrInst(GetElementPtrInst &I);
398 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
399 void visitInvokeInst (InvokeInst &II) {
400 visitCallSite(CallSite::get(&II));
401 visitTerminatorInst(II);
403 void visitCallSite (CallSite CS);
404 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
405 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
406 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
407 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
408 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
409 void visitFreeInst (Instruction &I) { /*returns void*/ }
411 void visitInstruction(Instruction &I) {
412 // If a new instruction is added to LLVM that we don't handle...
413 cerr << "SCCP: Don't know how to handle: " << I;
414 markOverdefined(&I); // Just in case
418 } // end anonymous namespace
421 // getFeasibleSuccessors - Return a vector of booleans to indicate which
422 // successors are reachable from a given terminator instruction.
424 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
425 SmallVector<bool, 16> &Succs) {
426 Succs.resize(TI.getNumSuccessors());
427 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
428 if (BI->isUnconditional()) {
431 LatticeVal &BCValue = getValueState(BI->getCondition());
432 if (BCValue.isOverdefined() ||
433 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
434 // Overdefined condition variables, and branches on unfoldable constant
435 // conditions, mean the branch could go either way.
436 Succs[0] = Succs[1] = true;
437 } else if (BCValue.isConstant()) {
438 // Constant condition variables mean the branch can only go a single way
439 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
442 } else if (isa<InvokeInst>(&TI)) {
443 // Invoke instructions successors are always executable.
444 Succs[0] = Succs[1] = true;
445 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
446 LatticeVal &SCValue = getValueState(SI->getCondition());
447 if (SCValue.isOverdefined() || // Overdefined condition?
448 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
449 // All destinations are executable!
450 Succs.assign(TI.getNumSuccessors(), true);
451 } else if (SCValue.isConstant()) {
452 Constant *CPV = SCValue.getConstant();
453 // Make sure to skip the "default value" which isn't a value
454 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
455 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
461 // Constant value not equal to any of the branches... must execute
462 // default branch then...
466 assert(0 && "SCCP: Don't know how to handle this terminator!");
471 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
472 // block to the 'To' basic block is currently feasible...
474 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
475 assert(BBExecutable.count(To) && "Dest should always be alive!");
477 // Make sure the source basic block is executable!!
478 if (!BBExecutable.count(From)) return false;
480 // Check to make sure this edge itself is actually feasible now...
481 TerminatorInst *TI = From->getTerminator();
482 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
483 if (BI->isUnconditional())
486 LatticeVal &BCValue = getValueState(BI->getCondition());
487 if (BCValue.isOverdefined()) {
488 // Overdefined condition variables mean the branch could go either way.
490 } else if (BCValue.isConstant()) {
491 // Not branching on an evaluatable constant?
492 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
494 // Constant condition variables mean the branch can only go a single way
495 return BI->getSuccessor(BCValue.getConstant() ==
496 ConstantInt::getFalse()) == To;
500 } else if (isa<InvokeInst>(TI)) {
501 // Invoke instructions successors are always executable.
503 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
504 LatticeVal &SCValue = getValueState(SI->getCondition());
505 if (SCValue.isOverdefined()) { // Overdefined condition?
506 // All destinations are executable!
508 } else if (SCValue.isConstant()) {
509 Constant *CPV = SCValue.getConstant();
510 if (!isa<ConstantInt>(CPV))
511 return true; // not a foldable constant?
513 // Make sure to skip the "default value" which isn't a value
514 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
515 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
516 return SI->getSuccessor(i) == To;
518 // Constant value not equal to any of the branches... must execute
519 // default branch then...
520 return SI->getDefaultDest() == To;
524 cerr << "Unknown terminator instruction: " << *TI;
529 // visit Implementations - Something changed in this instruction... Either an
530 // operand made a transition, or the instruction is newly executable. Change
531 // the value type of I to reflect these changes if appropriate. This method
532 // makes sure to do the following actions:
534 // 1. If a phi node merges two constants in, and has conflicting value coming
535 // from different branches, or if the PHI node merges in an overdefined
536 // value, then the PHI node becomes overdefined.
537 // 2. If a phi node merges only constants in, and they all agree on value, the
538 // PHI node becomes a constant value equal to that.
539 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
540 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
541 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
542 // 6. If a conditional branch has a value that is constant, make the selected
543 // destination executable
544 // 7. If a conditional branch has a value that is overdefined, make all
545 // successors executable.
547 void SCCPSolver::visitPHINode(PHINode &PN) {
548 LatticeVal &PNIV = getValueState(&PN);
549 if (PNIV.isOverdefined()) {
550 // There may be instructions using this PHI node that are not overdefined
551 // themselves. If so, make sure that they know that the PHI node operand
553 std::multimap<PHINode*, Instruction*>::iterator I, E;
554 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
556 SmallVector<Instruction*, 16> Users;
557 for (; I != E; ++I) Users.push_back(I->second);
558 while (!Users.empty()) {
563 return; // Quick exit
566 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
567 // and slow us down a lot. Just mark them overdefined.
568 if (PN.getNumIncomingValues() > 64) {
569 markOverdefined(PNIV, &PN);
573 // Look at all of the executable operands of the PHI node. If any of them
574 // are overdefined, the PHI becomes overdefined as well. If they are all
575 // constant, and they agree with each other, the PHI becomes the identical
576 // constant. If they are constant and don't agree, the PHI is overdefined.
577 // If there are no executable operands, the PHI remains undefined.
579 Constant *OperandVal = 0;
580 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
581 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
582 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
584 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
585 if (IV.isOverdefined()) { // PHI node becomes overdefined!
586 markOverdefined(PNIV, &PN);
590 if (OperandVal == 0) { // Grab the first value...
591 OperandVal = IV.getConstant();
592 } else { // Another value is being merged in!
593 // There is already a reachable operand. If we conflict with it,
594 // then the PHI node becomes overdefined. If we agree with it, we
597 // Check to see if there are two different constants merging...
598 if (IV.getConstant() != OperandVal) {
599 // Yes there is. This means the PHI node is not constant.
600 // You must be overdefined poor PHI.
602 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
603 return; // I'm done analyzing you
609 // If we exited the loop, this means that the PHI node only has constant
610 // arguments that agree with each other(and OperandVal is the constant) or
611 // OperandVal is null because there are no defined incoming arguments. If
612 // this is the case, the PHI remains undefined.
615 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
618 void SCCPSolver::visitReturnInst(ReturnInst &I) {
619 if (I.getNumOperands() == 0) return; // Ret void
621 Function *F = I.getParent()->getParent();
622 // If we are tracking the return value of this function, merge it in.
623 if (!F->hasInternalLinkage())
626 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
627 DenseMap<Function*, LatticeVal>::iterator TFRVI =
628 TrackedRetVals.find(F);
629 if (TFRVI != TrackedRetVals.end() &&
630 !TFRVI->second.isOverdefined()) {
631 LatticeVal &IV = getValueState(I.getOperand(0));
632 mergeInValue(TFRVI->second, F, IV);
637 // Handle functions that return multiple values.
638 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
639 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
640 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
641 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
642 if (It == TrackedMultipleRetVals.end()) break;
643 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
648 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
649 SmallVector<bool, 16> SuccFeasible;
650 getFeasibleSuccessors(TI, SuccFeasible);
652 BasicBlock *BB = TI.getParent();
654 // Mark all feasible successors executable...
655 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
657 markEdgeExecutable(BB, TI.getSuccessor(i));
660 void SCCPSolver::visitCastInst(CastInst &I) {
661 Value *V = I.getOperand(0);
662 LatticeVal &VState = getValueState(V);
663 if (VState.isOverdefined()) // Inherit overdefinedness of operand
665 else if (VState.isConstant()) // Propagate constant value
666 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
667 VState.getConstant(), I.getType()));
670 void SCCPSolver::visitGetResultInst(GetResultInst &GRI) {
671 Value *Aggr = GRI.getOperand(0);
673 // If the operand to the getresult is an undef, the result is undef.
674 if (isa<UndefValue>(Aggr))
678 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
679 F = CI->getCalledFunction();
681 F = cast<InvokeInst>(Aggr)->getCalledFunction();
683 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
685 if (F == 0 || TrackedMultipleRetVals.empty()) {
686 markOverdefined(&GRI);
690 // See if we are tracking the result of the callee.
691 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
692 It = TrackedMultipleRetVals.find(std::make_pair(F, GRI.getIndex()));
694 // If not tracking this function (for example, it is a declaration) just move
696 if (It == TrackedMultipleRetVals.end()) {
697 markOverdefined(&GRI);
701 // Otherwise, the value will be merged in here as a result of CallSite
705 void SCCPSolver::visitSelectInst(SelectInst &I) {
706 LatticeVal &CondValue = getValueState(I.getCondition());
707 if (CondValue.isUndefined())
709 if (CondValue.isConstant()) {
710 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
711 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
712 : I.getFalseValue()));
717 // Otherwise, the condition is overdefined or a constant we can't evaluate.
718 // See if we can produce something better than overdefined based on the T/F
720 LatticeVal &TVal = getValueState(I.getTrueValue());
721 LatticeVal &FVal = getValueState(I.getFalseValue());
723 // select ?, C, C -> C.
724 if (TVal.isConstant() && FVal.isConstant() &&
725 TVal.getConstant() == FVal.getConstant()) {
726 markConstant(&I, FVal.getConstant());
730 if (TVal.isUndefined()) { // select ?, undef, X -> X.
731 mergeInValue(&I, FVal);
732 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
733 mergeInValue(&I, TVal);
739 // Handle BinaryOperators and Shift Instructions...
740 void SCCPSolver::visitBinaryOperator(Instruction &I) {
741 LatticeVal &IV = ValueState[&I];
742 if (IV.isOverdefined()) return;
744 LatticeVal &V1State = getValueState(I.getOperand(0));
745 LatticeVal &V2State = getValueState(I.getOperand(1));
747 if (V1State.isOverdefined() || V2State.isOverdefined()) {
748 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
749 // operand is overdefined.
750 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
751 LatticeVal *NonOverdefVal = 0;
752 if (!V1State.isOverdefined()) {
753 NonOverdefVal = &V1State;
754 } else if (!V2State.isOverdefined()) {
755 NonOverdefVal = &V2State;
759 if (NonOverdefVal->isUndefined()) {
760 // Could annihilate value.
761 if (I.getOpcode() == Instruction::And)
762 markConstant(IV, &I, Constant::getNullValue(I.getType()));
763 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
764 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
766 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
769 if (I.getOpcode() == Instruction::And) {
770 if (NonOverdefVal->getConstant()->isNullValue()) {
771 markConstant(IV, &I, NonOverdefVal->getConstant());
772 return; // X and 0 = 0
775 if (ConstantInt *CI =
776 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
777 if (CI->isAllOnesValue()) {
778 markConstant(IV, &I, NonOverdefVal->getConstant());
779 return; // X or -1 = -1
787 // If both operands are PHI nodes, it is possible that this instruction has
788 // a constant value, despite the fact that the PHI node doesn't. Check for
789 // this condition now.
790 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
791 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
792 if (PN1->getParent() == PN2->getParent()) {
793 // Since the two PHI nodes are in the same basic block, they must have
794 // entries for the same predecessors. Walk the predecessor list, and
795 // if all of the incoming values are constants, and the result of
796 // evaluating this expression with all incoming value pairs is the
797 // same, then this expression is a constant even though the PHI node
798 // is not a constant!
800 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
801 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
802 BasicBlock *InBlock = PN1->getIncomingBlock(i);
804 getValueState(PN2->getIncomingValueForBlock(InBlock));
806 if (In1.isOverdefined() || In2.isOverdefined()) {
807 Result.markOverdefined();
808 break; // Cannot fold this operation over the PHI nodes!
809 } else if (In1.isConstant() && In2.isConstant()) {
810 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
812 if (Result.isUndefined())
813 Result.markConstant(V);
814 else if (Result.isConstant() && Result.getConstant() != V) {
815 Result.markOverdefined();
821 // If we found a constant value here, then we know the instruction is
822 // constant despite the fact that the PHI nodes are overdefined.
823 if (Result.isConstant()) {
824 markConstant(IV, &I, Result.getConstant());
825 // Remember that this instruction is virtually using the PHI node
827 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
828 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
830 } else if (Result.isUndefined()) {
834 // Okay, this really is overdefined now. Since we might have
835 // speculatively thought that this was not overdefined before, and
836 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
837 // make sure to clean out any entries that we put there, for
839 std::multimap<PHINode*, Instruction*>::iterator It, E;
840 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
842 if (It->second == &I) {
843 UsersOfOverdefinedPHIs.erase(It++);
847 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
849 if (It->second == &I) {
850 UsersOfOverdefinedPHIs.erase(It++);
856 markOverdefined(IV, &I);
857 } else if (V1State.isConstant() && V2State.isConstant()) {
858 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
859 V2State.getConstant()));
863 // Handle ICmpInst instruction...
864 void SCCPSolver::visitCmpInst(CmpInst &I) {
865 LatticeVal &IV = ValueState[&I];
866 if (IV.isOverdefined()) return;
868 LatticeVal &V1State = getValueState(I.getOperand(0));
869 LatticeVal &V2State = getValueState(I.getOperand(1));
871 if (V1State.isOverdefined() || V2State.isOverdefined()) {
872 // If both operands are PHI nodes, it is possible that this instruction has
873 // a constant value, despite the fact that the PHI node doesn't. Check for
874 // this condition now.
875 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
876 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
877 if (PN1->getParent() == PN2->getParent()) {
878 // Since the two PHI nodes are in the same basic block, they must have
879 // entries for the same predecessors. Walk the predecessor list, and
880 // if all of the incoming values are constants, and the result of
881 // evaluating this expression with all incoming value pairs is the
882 // same, then this expression is a constant even though the PHI node
883 // is not a constant!
885 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
886 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
887 BasicBlock *InBlock = PN1->getIncomingBlock(i);
889 getValueState(PN2->getIncomingValueForBlock(InBlock));
891 if (In1.isOverdefined() || In2.isOverdefined()) {
892 Result.markOverdefined();
893 break; // Cannot fold this operation over the PHI nodes!
894 } else if (In1.isConstant() && In2.isConstant()) {
895 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
898 if (Result.isUndefined())
899 Result.markConstant(V);
900 else if (Result.isConstant() && Result.getConstant() != V) {
901 Result.markOverdefined();
907 // If we found a constant value here, then we know the instruction is
908 // constant despite the fact that the PHI nodes are overdefined.
909 if (Result.isConstant()) {
910 markConstant(IV, &I, Result.getConstant());
911 // Remember that this instruction is virtually using the PHI node
913 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
914 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
916 } else if (Result.isUndefined()) {
920 // Okay, this really is overdefined now. Since we might have
921 // speculatively thought that this was not overdefined before, and
922 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
923 // make sure to clean out any entries that we put there, for
925 std::multimap<PHINode*, Instruction*>::iterator It, E;
926 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
928 if (It->second == &I) {
929 UsersOfOverdefinedPHIs.erase(It++);
933 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
935 if (It->second == &I) {
936 UsersOfOverdefinedPHIs.erase(It++);
942 markOverdefined(IV, &I);
943 } else if (V1State.isConstant() && V2State.isConstant()) {
944 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
945 V1State.getConstant(),
946 V2State.getConstant()));
950 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
951 // FIXME : SCCP does not handle vectors properly.
956 LatticeVal &ValState = getValueState(I.getOperand(0));
957 LatticeVal &IdxState = getValueState(I.getOperand(1));
959 if (ValState.isOverdefined() || IdxState.isOverdefined())
961 else if(ValState.isConstant() && IdxState.isConstant())
962 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
963 IdxState.getConstant()));
967 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
968 // FIXME : SCCP does not handle vectors properly.
972 LatticeVal &ValState = getValueState(I.getOperand(0));
973 LatticeVal &EltState = getValueState(I.getOperand(1));
974 LatticeVal &IdxState = getValueState(I.getOperand(2));
976 if (ValState.isOverdefined() || EltState.isOverdefined() ||
977 IdxState.isOverdefined())
979 else if(ValState.isConstant() && EltState.isConstant() &&
980 IdxState.isConstant())
981 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
982 EltState.getConstant(),
983 IdxState.getConstant()));
984 else if (ValState.isUndefined() && EltState.isConstant() &&
985 IdxState.isConstant())
986 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
987 EltState.getConstant(),
988 IdxState.getConstant()));
992 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
993 // FIXME : SCCP does not handle vectors properly.
997 LatticeVal &V1State = getValueState(I.getOperand(0));
998 LatticeVal &V2State = getValueState(I.getOperand(1));
999 LatticeVal &MaskState = getValueState(I.getOperand(2));
1001 if (MaskState.isUndefined() ||
1002 (V1State.isUndefined() && V2State.isUndefined()))
1003 return; // Undefined output if mask or both inputs undefined.
1005 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1006 MaskState.isOverdefined()) {
1007 markOverdefined(&I);
1009 // A mix of constant/undef inputs.
1010 Constant *V1 = V1State.isConstant() ?
1011 V1State.getConstant() : UndefValue::get(I.getType());
1012 Constant *V2 = V2State.isConstant() ?
1013 V2State.getConstant() : UndefValue::get(I.getType());
1014 Constant *Mask = MaskState.isConstant() ?
1015 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1016 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1021 // Handle getelementptr instructions... if all operands are constants then we
1022 // can turn this into a getelementptr ConstantExpr.
1024 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1025 LatticeVal &IV = ValueState[&I];
1026 if (IV.isOverdefined()) return;
1028 SmallVector<Constant*, 8> Operands;
1029 Operands.reserve(I.getNumOperands());
1031 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1032 LatticeVal &State = getValueState(I.getOperand(i));
1033 if (State.isUndefined())
1034 return; // Operands are not resolved yet...
1035 else if (State.isOverdefined()) {
1036 markOverdefined(IV, &I);
1039 assert(State.isConstant() && "Unknown state!");
1040 Operands.push_back(State.getConstant());
1043 Constant *Ptr = Operands[0];
1044 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1046 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1050 void SCCPSolver::visitStoreInst(Instruction &SI) {
1051 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1053 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1054 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1055 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1057 // Get the value we are storing into the global.
1058 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1060 mergeInValue(I->second, GV, PtrVal);
1061 if (I->second.isOverdefined())
1062 TrackedGlobals.erase(I); // No need to keep tracking this!
1066 // Handle load instructions. If the operand is a constant pointer to a constant
1067 // global, we can replace the load with the loaded constant value!
1068 void SCCPSolver::visitLoadInst(LoadInst &I) {
1069 LatticeVal &IV = ValueState[&I];
1070 if (IV.isOverdefined()) return;
1072 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1073 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1074 if (PtrVal.isConstant() && !I.isVolatile()) {
1075 Value *Ptr = PtrVal.getConstant();
1076 // TODO: Consider a target hook for valid address spaces for this xform.
1077 if (isa<ConstantPointerNull>(Ptr) &&
1078 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
1079 // load null -> null
1080 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1084 // Transform load (constant global) into the value loaded.
1085 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1086 if (GV->isConstant()) {
1087 if (!GV->isDeclaration()) {
1088 markConstant(IV, &I, GV->getInitializer());
1091 } else if (!TrackedGlobals.empty()) {
1092 // If we are tracking this global, merge in the known value for it.
1093 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1094 TrackedGlobals.find(GV);
1095 if (It != TrackedGlobals.end()) {
1096 mergeInValue(IV, &I, It->second);
1102 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1103 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1104 if (CE->getOpcode() == Instruction::GetElementPtr)
1105 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
1106 if (GV->isConstant() && !GV->isDeclaration())
1108 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
1109 markConstant(IV, &I, V);
1114 // Otherwise we cannot say for certain what value this load will produce.
1116 markOverdefined(IV, &I);
1119 void SCCPSolver::visitCallSite(CallSite CS) {
1120 Function *F = CS.getCalledFunction();
1121 Instruction *I = CS.getInstruction();
1123 // The common case is that we aren't tracking the callee, either because we
1124 // are not doing interprocedural analysis or the callee is indirect, or is
1125 // external. Handle these cases first.
1126 if (F == 0 || !F->hasInternalLinkage()) {
1128 // Void return and not tracking callee, just bail.
1129 if (I->getType() == Type::VoidTy) return;
1131 // Otherwise, if we have a single return value case, and if the function is
1132 // a declaration, maybe we can constant fold it.
1133 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1134 canConstantFoldCallTo(F)) {
1136 SmallVector<Constant*, 8> Operands;
1137 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1139 LatticeVal &State = getValueState(*AI);
1140 if (State.isUndefined())
1141 return; // Operands are not resolved yet.
1142 else if (State.isOverdefined()) {
1146 assert(State.isConstant() && "Unknown state!");
1147 Operands.push_back(State.getConstant());
1150 // If we can constant fold this, mark the result of the call as a
1152 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size())) {
1158 // Otherwise, we don't know anything about this call, mark it overdefined.
1163 // If this is a single/zero retval case, see if we're tracking the function.
1164 const StructType *RetSTy = dyn_cast<StructType>(I->getType());
1166 // Check to see if we're tracking this callee, if not, handle it in the
1167 // common path above.
1168 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1169 if (TFRVI == TrackedRetVals.end())
1170 goto CallOverdefined;
1172 // If so, propagate the return value of the callee into this call result.
1173 mergeInValue(I, TFRVI->second);
1175 // Check to see if we're tracking this callee, if not, handle it in the
1176 // common path above.
1177 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
1178 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
1179 if (TMRVI == TrackedMultipleRetVals.end())
1180 goto CallOverdefined;
1182 // If we are tracking this callee, propagate the return values of the call
1183 // into this call site. We do this by walking all the getresult uses.
1184 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1186 GetResultInst *GRI = cast<GetResultInst>(*UI);
1188 TrackedMultipleRetVals[std::make_pair(F, GRI->getIndex())]);
1192 // Finally, if this is the first call to the function hit, mark its entry
1193 // block executable.
1194 if (!BBExecutable.count(F->begin()))
1195 MarkBlockExecutable(F->begin());
1197 // Propagate information from this call site into the callee.
1198 CallSite::arg_iterator CAI = CS.arg_begin();
1199 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1200 AI != E; ++AI, ++CAI) {
1201 LatticeVal &IV = ValueState[AI];
1202 if (!IV.isOverdefined())
1203 mergeInValue(IV, AI, getValueState(*CAI));
1208 void SCCPSolver::Solve() {
1209 // Process the work lists until they are empty!
1210 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1211 !OverdefinedInstWorkList.empty()) {
1212 // Process the instruction work list...
1213 while (!OverdefinedInstWorkList.empty()) {
1214 Value *I = OverdefinedInstWorkList.back();
1215 OverdefinedInstWorkList.pop_back();
1217 DOUT << "\nPopped off OI-WL: " << *I;
1219 // "I" got into the work list because it either made the transition from
1220 // bottom to constant
1222 // Anything on this worklist that is overdefined need not be visited
1223 // since all of its users will have already been marked as overdefined
1224 // Update all of the users of this instruction's value...
1226 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1228 OperandChangedState(*UI);
1230 // Process the instruction work list...
1231 while (!InstWorkList.empty()) {
1232 Value *I = InstWorkList.back();
1233 InstWorkList.pop_back();
1235 DOUT << "\nPopped off I-WL: " << *I;
1237 // "I" got into the work list because it either made the transition from
1238 // bottom to constant
1240 // Anything on this worklist that is overdefined need not be visited
1241 // since all of its users will have already been marked as overdefined.
1242 // Update all of the users of this instruction's value...
1244 if (!getValueState(I).isOverdefined())
1245 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1247 OperandChangedState(*UI);
1250 // Process the basic block work list...
1251 while (!BBWorkList.empty()) {
1252 BasicBlock *BB = BBWorkList.back();
1253 BBWorkList.pop_back();
1255 DOUT << "\nPopped off BBWL: " << *BB;
1257 // Notify all instructions in this basic block that they are newly
1264 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1265 /// that branches on undef values cannot reach any of their successors.
1266 /// However, this is not a safe assumption. After we solve dataflow, this
1267 /// method should be use to handle this. If this returns true, the solver
1268 /// should be rerun.
1270 /// This method handles this by finding an unresolved branch and marking it one
1271 /// of the edges from the block as being feasible, even though the condition
1272 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1273 /// CFG and only slightly pessimizes the analysis results (by marking one,
1274 /// potentially infeasible, edge feasible). This cannot usefully modify the
1275 /// constraints on the condition of the branch, as that would impact other users
1278 /// This scan also checks for values that use undefs, whose results are actually
1279 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1280 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1281 /// even if X isn't defined.
1282 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1283 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1284 if (!BBExecutable.count(BB))
1287 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1288 // Look for instructions which produce undef values.
1289 if (I->getType() == Type::VoidTy) continue;
1291 LatticeVal &LV = getValueState(I);
1292 if (!LV.isUndefined()) continue;
1294 // Get the lattice values of the first two operands for use below.
1295 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1297 if (I->getNumOperands() == 2) {
1298 // If this is a two-operand instruction, and if both operands are
1299 // undefs, the result stays undef.
1300 Op1LV = getValueState(I->getOperand(1));
1301 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1305 // If this is an instructions whose result is defined even if the input is
1306 // not fully defined, propagate the information.
1307 const Type *ITy = I->getType();
1308 switch (I->getOpcode()) {
1309 default: break; // Leave the instruction as an undef.
1310 case Instruction::ZExt:
1311 // After a zero extend, we know the top part is zero. SExt doesn't have
1312 // to be handled here, because we don't know whether the top part is 1's
1314 assert(Op0LV.isUndefined());
1315 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1317 case Instruction::Mul:
1318 case Instruction::And:
1319 // undef * X -> 0. X could be zero.
1320 // undef & X -> 0. X could be zero.
1321 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1324 case Instruction::Or:
1325 // undef | X -> -1. X could be -1.
1326 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1327 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
1329 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1332 case Instruction::SDiv:
1333 case Instruction::UDiv:
1334 case Instruction::SRem:
1335 case Instruction::URem:
1336 // X / undef -> undef. No change.
1337 // X % undef -> undef. No change.
1338 if (Op1LV.isUndefined()) break;
1340 // undef / X -> 0. X could be maxint.
1341 // undef % X -> 0. X could be 1.
1342 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1345 case Instruction::AShr:
1346 // undef >>s X -> undef. No change.
1347 if (Op0LV.isUndefined()) break;
1349 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1350 if (Op0LV.isConstant())
1351 markForcedConstant(LV, I, Op0LV.getConstant());
1353 markOverdefined(LV, I);
1355 case Instruction::LShr:
1356 case Instruction::Shl:
1357 // undef >> X -> undef. No change.
1358 // undef << X -> undef. No change.
1359 if (Op0LV.isUndefined()) break;
1361 // X >> undef -> 0. X could be 0.
1362 // X << undef -> 0. X could be 0.
1363 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1365 case Instruction::Select:
1366 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1367 if (Op0LV.isUndefined()) {
1368 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1369 Op1LV = getValueState(I->getOperand(2));
1370 } else if (Op1LV.isUndefined()) {
1371 // c ? undef : undef -> undef. No change.
1372 Op1LV = getValueState(I->getOperand(2));
1373 if (Op1LV.isUndefined())
1375 // Otherwise, c ? undef : x -> x.
1377 // Leave Op1LV as Operand(1)'s LatticeValue.
1380 if (Op1LV.isConstant())
1381 markForcedConstant(LV, I, Op1LV.getConstant());
1383 markOverdefined(LV, I);
1388 TerminatorInst *TI = BB->getTerminator();
1389 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1390 if (!BI->isConditional()) continue;
1391 if (!getValueState(BI->getCondition()).isUndefined())
1393 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1394 if (!getValueState(SI->getCondition()).isUndefined())
1400 // If the edge to the second successor isn't thought to be feasible yet,
1401 // mark it so now. We pick the second one so that this goes to some
1402 // enumerated value in a switch instead of going to the default destination.
1403 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
1406 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1407 // and return. This will make other blocks reachable, which will allow new
1408 // values to be discovered and existing ones to be moved in the lattice.
1409 markEdgeExecutable(BB, TI->getSuccessor(1));
1411 // This must be a conditional branch of switch on undef. At this point,
1412 // force the old terminator to branch to the first successor. This is
1413 // required because we are now influencing the dataflow of the function with
1414 // the assumption that this edge is taken. If we leave the branch condition
1415 // as undef, then further analysis could think the undef went another way
1416 // leading to an inconsistent set of conclusions.
1417 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1418 BI->setCondition(ConstantInt::getFalse());
1420 SwitchInst *SI = cast<SwitchInst>(TI);
1421 SI->setCondition(SI->getCaseValue(1));
1432 //===--------------------------------------------------------------------===//
1434 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1435 /// Sparse Conditional Constant Propagator.
1437 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
1438 static char ID; // Pass identification, replacement for typeid
1439 SCCP() : FunctionPass((intptr_t)&ID) {}
1441 // runOnFunction - Run the Sparse Conditional Constant Propagation
1442 // algorithm, and return true if the function was modified.
1444 bool runOnFunction(Function &F);
1446 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1447 AU.setPreservesCFG();
1452 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
1453 } // end anonymous namespace
1456 // createSCCPPass - This is the public interface to this file...
1457 FunctionPass *llvm::createSCCPPass() {
1462 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1463 // and return true if the function was modified.
1465 bool SCCP::runOnFunction(Function &F) {
1466 DOUT << "SCCP on function '" << F.getName() << "'\n";
1469 // Mark the first block of the function as being executable.
1470 Solver.MarkBlockExecutable(F.begin());
1472 // Mark all arguments to the function as being overdefined.
1473 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1474 Solver.markOverdefined(AI);
1476 // Solve for constants.
1477 bool ResolvedUndefs = true;
1478 while (ResolvedUndefs) {
1480 DOUT << "RESOLVING UNDEFs\n";
1481 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1484 bool MadeChanges = false;
1486 // If we decided that there are basic blocks that are dead in this function,
1487 // delete their contents now. Note that we cannot actually delete the blocks,
1488 // as we cannot modify the CFG of the function.
1490 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
1491 SmallVector<Instruction*, 32> Insts;
1492 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1494 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1495 if (!ExecutableBBs.count(BB)) {
1496 DOUT << " BasicBlock Dead:" << *BB;
1499 // Delete the instructions backwards, as it has a reduced likelihood of
1500 // having to update as many def-use and use-def chains.
1501 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1504 while (!Insts.empty()) {
1505 Instruction *I = Insts.back();
1507 if (!I->use_empty())
1508 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1509 BB->getInstList().erase(I);
1514 // Iterate over all of the instructions in a function, replacing them with
1515 // constants if we have found them to be of constant values.
1517 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1518 Instruction *Inst = BI++;
1519 if (Inst->getType() == Type::VoidTy ||
1520 isa<TerminatorInst>(Inst))
1523 LatticeVal &IV = Values[Inst];
1524 if (!IV.isConstant() && !IV.isUndefined())
1527 Constant *Const = IV.isConstant()
1528 ? IV.getConstant() : UndefValue::get(Inst->getType());
1529 DOUT << " Constant: " << *Const << " = " << *Inst;
1531 // Replaces all of the uses of a variable with uses of the constant.
1532 Inst->replaceAllUsesWith(Const);
1534 // Delete the instruction.
1535 Inst->eraseFromParent();
1537 // Hey, we just changed something!
1547 //===--------------------------------------------------------------------===//
1549 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1550 /// Constant Propagation.
1552 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
1554 IPSCCP() : ModulePass((intptr_t)&ID) {}
1555 bool runOnModule(Module &M);
1558 char IPSCCP::ID = 0;
1559 RegisterPass<IPSCCP>
1560 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1561 } // end anonymous namespace
1563 // createIPSCCPPass - This is the public interface to this file...
1564 ModulePass *llvm::createIPSCCPPass() {
1565 return new IPSCCP();
1569 static bool AddressIsTaken(GlobalValue *GV) {
1570 // Delete any dead constantexpr klingons.
1571 GV->removeDeadConstantUsers();
1573 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1575 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1576 if (SI->getOperand(0) == GV || SI->isVolatile())
1577 return true; // Storing addr of GV.
1578 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1579 // Make sure we are calling the function, not passing the address.
1580 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1581 for (CallSite::arg_iterator AI = CS.arg_begin(),
1582 E = CS.arg_end(); AI != E; ++AI)
1585 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1586 if (LI->isVolatile())
1594 bool IPSCCP::runOnModule(Module &M) {
1597 // Loop over all functions, marking arguments to those with their addresses
1598 // taken or that are external as overdefined.
1600 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1601 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1602 if (!F->isDeclaration())
1603 Solver.MarkBlockExecutable(F->begin());
1604 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1606 Solver.markOverdefined(AI);
1608 Solver.AddTrackedFunction(F);
1611 // Loop over global variables. We inform the solver about any internal global
1612 // variables that do not have their 'addresses taken'. If they don't have
1613 // their addresses taken, we can propagate constants through them.
1614 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1616 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1617 Solver.TrackValueOfGlobalVariable(G);
1619 // Solve for constants.
1620 bool ResolvedUndefs = true;
1621 while (ResolvedUndefs) {
1624 DOUT << "RESOLVING UNDEFS\n";
1625 ResolvedUndefs = false;
1626 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1627 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1630 bool MadeChanges = false;
1632 // Iterate over all of the instructions in the module, replacing them with
1633 // constants if we have found them to be of constant values.
1635 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
1636 SmallVector<Instruction*, 32> Insts;
1637 SmallVector<BasicBlock*, 32> BlocksToErase;
1638 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1640 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1641 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1643 if (!AI->use_empty()) {
1644 LatticeVal &IV = Values[AI];
1645 if (IV.isConstant() || IV.isUndefined()) {
1646 Constant *CST = IV.isConstant() ?
1647 IV.getConstant() : UndefValue::get(AI->getType());
1648 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
1650 // Replaces all of the uses of a variable with uses of the
1652 AI->replaceAllUsesWith(CST);
1657 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1658 if (!ExecutableBBs.count(BB)) {
1659 DOUT << " BasicBlock Dead:" << *BB;
1662 // Delete the instructions backwards, as it has a reduced likelihood of
1663 // having to update as many def-use and use-def chains.
1664 TerminatorInst *TI = BB->getTerminator();
1665 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1668 while (!Insts.empty()) {
1669 Instruction *I = Insts.back();
1671 if (!I->use_empty())
1672 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1673 BB->getInstList().erase(I);
1678 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1679 BasicBlock *Succ = TI->getSuccessor(i);
1680 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1681 TI->getSuccessor(i)->removePredecessor(BB);
1683 if (!TI->use_empty())
1684 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1685 BB->getInstList().erase(TI);
1687 if (&*BB != &F->front())
1688 BlocksToErase.push_back(BB);
1690 new UnreachableInst(BB);
1693 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1694 Instruction *Inst = BI++;
1695 if (Inst->getType() != Type::VoidTy) {
1696 LatticeVal &IV = Values[Inst];
1697 if (IV.isConstant() ||
1698 (IV.isUndefined() && !isa<TerminatorInst>(Inst))) {
1699 Constant *Const = IV.isConstant()
1700 ? IV.getConstant() : UndefValue::get(Inst->getType());
1701 DOUT << " Constant: " << *Const << " = " << *Inst;
1703 // Replaces all of the uses of a variable with uses of the
1705 Inst->replaceAllUsesWith(Const);
1707 // Delete the instruction.
1708 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1709 BB->getInstList().erase(Inst);
1711 // Hey, we just changed something!
1719 // Now that all instructions in the function are constant folded, erase dead
1720 // blocks, because we can now use ConstantFoldTerminator to get rid of
1722 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1723 // If there are any PHI nodes in this successor, drop entries for BB now.
1724 BasicBlock *DeadBB = BlocksToErase[i];
1725 while (!DeadBB->use_empty()) {
1726 if (BasicBlock *PredBB = dyn_cast<BasicBlock>(DeadBB->use_back())) {
1727 PredBB->setUnwindDest(NULL);
1731 Instruction *I = cast<Instruction>(DeadBB->use_back());
1732 bool Folded = ConstantFoldTerminator(I->getParent());
1734 // The constant folder may not have been able to fold the terminator
1735 // if this is a branch or switch on undef. Fold it manually as a
1736 // branch to the first successor.
1737 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1738 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1739 "Branch should be foldable!");
1740 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1741 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1743 assert(0 && "Didn't fold away reference to block!");
1746 // Make this an uncond branch to the first successor.
1747 TerminatorInst *TI = I->getParent()->getTerminator();
1748 BranchInst::Create(TI->getSuccessor(0), TI);
1750 // Remove entries in successor phi nodes to remove edges.
1751 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1752 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1754 // Remove the old terminator.
1755 TI->eraseFromParent();
1759 // Finally, delete the basic block.
1760 F->getBasicBlockList().erase(DeadBB);
1762 BlocksToErase.clear();
1765 // If we inferred constant or undef return values for a function, we replaced
1766 // all call uses with the inferred value. This means we don't need to bother
1767 // actually returning anything from the function. Replace all return
1768 // instructions with return undef.
1769 // TODO: Process multiple value ret instructions also.
1770 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1771 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1772 E = RV.end(); I != E; ++I)
1773 if (!I->second.isOverdefined() &&
1774 I->first->getReturnType() != Type::VoidTy) {
1775 Function *F = I->first;
1776 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1777 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1778 if (!isa<UndefValue>(RI->getOperand(0)))
1779 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1782 // If we infered constant or undef values for globals variables, we can delete
1783 // the global and any stores that remain to it.
1784 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1785 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1786 E = TG.end(); I != E; ++I) {
1787 GlobalVariable *GV = I->first;
1788 assert(!I->second.isOverdefined() &&
1789 "Overdefined values should have been taken out of the map!");
1790 DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
1791 while (!GV->use_empty()) {
1792 StoreInst *SI = cast<StoreInst>(GV->use_back());
1793 SI->eraseFromParent();
1795 M.getGlobalList().erase(GV);