1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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"
45 STATISTIC(NumInstRemoved
, "Number of instructions removed");
46 STATISTIC(NumDeadBlocks
, "Number of basic blocks unreachable");
48 STATISTIC(IPNumInstRemoved
, "Number ofinstructions removed by IPSCCP");
49 STATISTIC(IPNumDeadBlocks
, "Number of basic blocks unreachable by IPSCCP");
50 STATISTIC(IPNumArgsElimed
,"Number of arguments constant propagated by IPSCCP");
51 STATISTIC(IPNumGlobalConst
, "Number of globals found to be constant by IPSCCP");
54 /// LatticeVal class - This class represents the different lattice values that
55 /// an LLVM value may occupy. It is a simple class with value semantics.
57 class VISIBILITY_HIDDEN LatticeVal
{
59 /// undefined - This LLVM Value has no known value yet.
62 /// constant - This LLVM Value has a specific constant value.
65 /// forcedconstant - This LLVM Value was thought to be undef until
66 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
67 /// with another (different) constant, it goes to overdefined, instead of
71 /// overdefined - This instruction is not known to be constant, and we know
74 } LatticeValue
; // The current lattice position
76 Constant
*ConstantVal
; // If Constant value, the current value
78 inline LatticeVal() : LatticeValue(undefined
), ConstantVal(0) {}
80 // markOverdefined - Return true if this is a new status to be in...
81 inline bool markOverdefined() {
82 if (LatticeValue
!= overdefined
) {
83 LatticeValue
= overdefined
;
89 // markConstant - Return true if this is a new status for us.
90 inline bool markConstant(Constant
*V
) {
91 if (LatticeValue
!= constant
) {
92 if (LatticeValue
== undefined
) {
93 LatticeValue
= constant
;
94 assert(V
&& "Marking constant with NULL");
97 assert(LatticeValue
== forcedconstant
&&
98 "Cannot move from overdefined to constant!");
99 // Stay at forcedconstant if the constant is the same.
100 if (V
== ConstantVal
) return false;
102 // Otherwise, we go to overdefined. Assumptions made based on the
103 // forced value are possibly wrong. Assuming this is another constant
104 // could expose a contradiction.
105 LatticeValue
= overdefined
;
109 assert(ConstantVal
== V
&& "Marking constant with different value");
114 inline void markForcedConstant(Constant
*V
) {
115 assert(LatticeValue
== undefined
&& "Can't force a defined value!");
116 LatticeValue
= forcedconstant
;
120 inline bool isUndefined() const { return LatticeValue
== undefined
; }
121 inline bool isConstant() const {
122 return LatticeValue
== constant
|| LatticeValue
== forcedconstant
;
124 inline bool isOverdefined() const { return LatticeValue
== overdefined
; }
126 inline Constant
*getConstant() const {
127 assert(isConstant() && "Cannot get the constant of a non-constant!");
132 //===----------------------------------------------------------------------===//
134 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
135 /// Constant Propagation.
137 class SCCPSolver
: public InstVisitor
<SCCPSolver
> {
138 SmallSet
<BasicBlock
*, 16> BBExecutable
;// The basic blocks that are executable
139 std::map
<Value
*, LatticeVal
> ValueState
; // The state each value is in.
141 /// GlobalValue - If we are tracking any values for the contents of a global
142 /// variable, we keep a mapping from the constant accessor to the element of
143 /// the global, to the currently known value. If the value becomes
144 /// overdefined, it's entry is simply removed from this map.
145 DenseMap
<GlobalVariable
*, LatticeVal
> TrackedGlobals
;
147 /// TrackedFunctionRetVals - If we are tracking arguments into and the return
148 /// value out of a function, it will have an entry in this map, indicating
149 /// what the known return value for the function is.
150 DenseMap
<Function
*, LatticeVal
> TrackedFunctionRetVals
;
152 // The reason for two worklists is that overdefined is the lowest state
153 // on the lattice, and moving things to overdefined as fast as possible
154 // makes SCCP converge much faster.
155 // By having a separate worklist, we accomplish this because everything
156 // possibly overdefined will become overdefined at the soonest possible
158 std::vector
<Value
*> OverdefinedInstWorkList
;
159 std::vector
<Value
*> InstWorkList
;
162 std::vector
<BasicBlock
*> BBWorkList
; // The BasicBlock work list
164 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
165 /// overdefined, despite the fact that the PHI node is overdefined.
166 std::multimap
<PHINode
*, Instruction
*> UsersOfOverdefinedPHIs
;
168 /// KnownFeasibleEdges - Entries in this set are edges which have already had
169 /// PHI nodes retriggered.
170 typedef std::pair
<BasicBlock
*,BasicBlock
*> Edge
;
171 std::set
<Edge
> KnownFeasibleEdges
;
174 /// MarkBlockExecutable - This method can be used by clients to mark all of
175 /// the blocks that are known to be intrinsically live in the processed unit.
176 void MarkBlockExecutable(BasicBlock
*BB
) {
177 DOUT
<< "Marking Block Executable: " << BB
->getName() << "\n";
178 BBExecutable
.insert(BB
); // Basic block is executable!
179 BBWorkList
.push_back(BB
); // Add the block to the work list!
182 /// TrackValueOfGlobalVariable - Clients can use this method to
183 /// inform the SCCPSolver that it should track loads and stores to the
184 /// specified global variable if it can. This is only legal to call if
185 /// performing Interprocedural SCCP.
186 void TrackValueOfGlobalVariable(GlobalVariable
*GV
) {
187 const Type
*ElTy
= GV
->getType()->getElementType();
188 if (ElTy
->isFirstClassType()) {
189 LatticeVal
&IV
= TrackedGlobals
[GV
];
190 if (!isa
<UndefValue
>(GV
->getInitializer()))
191 IV
.markConstant(GV
->getInitializer());
195 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
196 /// and out of the specified function (which cannot have its address taken),
197 /// this method must be called.
198 void AddTrackedFunction(Function
*F
) {
199 assert(F
->hasInternalLinkage() && "Can only track internal functions!");
200 // Add an entry, F -> undef.
201 TrackedFunctionRetVals
[F
];
204 /// Solve - Solve for constants and executable blocks.
208 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
209 /// that branches on undef values cannot reach any of their successors.
210 /// However, this is not a safe assumption. After we solve dataflow, this
211 /// method should be use to handle this. If this returns true, the solver
213 bool ResolvedUndefsIn(Function
&F
);
215 /// getExecutableBlocks - Once we have solved for constants, return the set of
216 /// blocks that is known to be executable.
217 SmallSet
<BasicBlock
*, 16> &getExecutableBlocks() {
221 /// getValueMapping - Once we have solved for constants, return the mapping of
222 /// LLVM values to LatticeVals.
223 std::map
<Value
*, LatticeVal
> &getValueMapping() {
227 /// getTrackedFunctionRetVals - Get the inferred return value map.
229 const DenseMap
<Function
*, LatticeVal
> &getTrackedFunctionRetVals() {
230 return TrackedFunctionRetVals
;
233 /// getTrackedGlobals - Get and return the set of inferred initializers for
234 /// global variables.
235 const DenseMap
<GlobalVariable
*, LatticeVal
> &getTrackedGlobals() {
236 return TrackedGlobals
;
239 inline void markOverdefined(Value
*V
) {
240 markOverdefined(ValueState
[V
], V
);
244 // markConstant - Make a value be marked as "constant". If the value
245 // is not already a constant, add it to the instruction work list so that
246 // the users of the instruction are updated later.
248 inline void markConstant(LatticeVal
&IV
, Value
*V
, Constant
*C
) {
249 if (IV
.markConstant(C
)) {
250 DOUT
<< "markConstant: " << *C
<< ": " << *V
;
251 InstWorkList
.push_back(V
);
255 inline void markForcedConstant(LatticeVal
&IV
, Value
*V
, Constant
*C
) {
256 IV
.markForcedConstant(C
);
257 DOUT
<< "markForcedConstant: " << *C
<< ": " << *V
;
258 InstWorkList
.push_back(V
);
261 inline void markConstant(Value
*V
, Constant
*C
) {
262 markConstant(ValueState
[V
], V
, C
);
265 // markOverdefined - Make a value be marked as "overdefined". If the
266 // value is not already overdefined, add it to the overdefined instruction
267 // work list so that the users of the instruction are updated later.
269 inline void markOverdefined(LatticeVal
&IV
, Value
*V
) {
270 if (IV
.markOverdefined()) {
271 DEBUG(DOUT
<< "markOverdefined: ";
272 if (Function
*F
= dyn_cast
<Function
>(V
))
273 DOUT
<< "Function '" << F
->getName() << "'\n";
276 // Only instructions go on the work list
277 OverdefinedInstWorkList
.push_back(V
);
281 inline void mergeInValue(LatticeVal
&IV
, Value
*V
, LatticeVal
&MergeWithV
) {
282 if (IV
.isOverdefined() || MergeWithV
.isUndefined())
284 if (MergeWithV
.isOverdefined())
285 markOverdefined(IV
, V
);
286 else if (IV
.isUndefined())
287 markConstant(IV
, V
, MergeWithV
.getConstant());
288 else if (IV
.getConstant() != MergeWithV
.getConstant())
289 markOverdefined(IV
, V
);
292 inline void mergeInValue(Value
*V
, LatticeVal
&MergeWithV
) {
293 return mergeInValue(ValueState
[V
], V
, MergeWithV
);
297 // getValueState - Return the LatticeVal object that corresponds to the value.
298 // This function is necessary because not all values should start out in the
299 // underdefined state... Argument's should be overdefined, and
300 // constants should be marked as constants. If a value is not known to be an
301 // Instruction object, then use this accessor to get its value from the map.
303 inline LatticeVal
&getValueState(Value
*V
) {
304 std::map
<Value
*, LatticeVal
>::iterator I
= ValueState
.find(V
);
305 if (I
!= ValueState
.end()) return I
->second
; // Common case, in the map
307 if (Constant
*C
= dyn_cast
<Constant
>(V
)) {
308 if (isa
<UndefValue
>(V
)) {
309 // Nothing to do, remain undefined.
311 LatticeVal
&LV
= ValueState
[C
];
312 LV
.markConstant(C
); // Constants are constant
316 // All others are underdefined by default...
317 return ValueState
[V
];
320 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
321 // work list if it is not already executable...
323 void markEdgeExecutable(BasicBlock
*Source
, BasicBlock
*Dest
) {
324 if (!KnownFeasibleEdges
.insert(Edge(Source
, Dest
)).second
)
325 return; // This edge is already known to be executable!
327 if (BBExecutable
.count(Dest
)) {
328 DOUT
<< "Marking Edge Executable: " << Source
->getName()
329 << " -> " << Dest
->getName() << "\n";
331 // The destination is already executable, but we just made an edge
332 // feasible that wasn't before. Revisit the PHI nodes in the block
333 // because they have potentially new operands.
334 for (BasicBlock::iterator I
= Dest
->begin(); isa
<PHINode
>(I
); ++I
)
335 visitPHINode(*cast
<PHINode
>(I
));
338 MarkBlockExecutable(Dest
);
342 // getFeasibleSuccessors - Return a vector of booleans to indicate which
343 // successors are reachable from a given terminator instruction.
345 void getFeasibleSuccessors(TerminatorInst
&TI
, SmallVector
<bool, 16> &Succs
);
347 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
348 // block to the 'To' basic block is currently feasible...
350 bool isEdgeFeasible(BasicBlock
*From
, BasicBlock
*To
);
352 // OperandChangedState - This method is invoked on all of the users of an
353 // instruction that was just changed state somehow.... Based on this
354 // information, we need to update the specified user of this instruction.
356 void OperandChangedState(User
*U
) {
357 // Only instructions use other variable values!
358 Instruction
&I
= cast
<Instruction
>(*U
);
359 if (BBExecutable
.count(I
.getParent())) // Inst is executable?
364 friend class InstVisitor
<SCCPSolver
>;
366 // visit implementations - Something changed in this instruction... Either an
367 // operand made a transition, or the instruction is newly executable. Change
368 // the value type of I to reflect these changes if appropriate.
370 void visitPHINode(PHINode
&I
);
373 void visitReturnInst(ReturnInst
&I
);
374 void visitTerminatorInst(TerminatorInst
&TI
);
376 void visitCastInst(CastInst
&I
);
377 void visitSelectInst(SelectInst
&I
);
378 void visitBinaryOperator(Instruction
&I
);
379 void visitCmpInst(CmpInst
&I
);
380 void visitExtractElementInst(ExtractElementInst
&I
);
381 void visitInsertElementInst(InsertElementInst
&I
);
382 void visitShuffleVectorInst(ShuffleVectorInst
&I
);
384 // Instructions that cannot be folded away...
385 void visitStoreInst (Instruction
&I
);
386 void visitLoadInst (LoadInst
&I
);
387 void visitGetElementPtrInst(GetElementPtrInst
&I
);
388 void visitCallInst (CallInst
&I
) { visitCallSite(CallSite::get(&I
)); }
389 void visitInvokeInst (InvokeInst
&II
) {
390 visitCallSite(CallSite::get(&II
));
391 visitTerminatorInst(II
);
393 void visitCallSite (CallSite CS
);
394 void visitUnwindInst (TerminatorInst
&I
) { /*returns void*/ }
395 void visitUnreachableInst(TerminatorInst
&I
) { /*returns void*/ }
396 void visitAllocationInst(Instruction
&I
) { markOverdefined(&I
); }
397 void visitVANextInst (Instruction
&I
) { markOverdefined(&I
); }
398 void visitVAArgInst (Instruction
&I
) { markOverdefined(&I
); }
399 void visitFreeInst (Instruction
&I
) { /*returns void*/ }
401 void visitInstruction(Instruction
&I
) {
402 // If a new instruction is added to LLVM that we don't handle...
403 cerr
<< "SCCP: Don't know how to handle: " << I
;
404 markOverdefined(&I
); // Just in case
408 } // end anonymous namespace
411 // getFeasibleSuccessors - Return a vector of booleans to indicate which
412 // successors are reachable from a given terminator instruction.
414 void SCCPSolver::getFeasibleSuccessors(TerminatorInst
&TI
,
415 SmallVector
<bool, 16> &Succs
) {
416 Succs
.resize(TI
.getNumSuccessors());
417 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(&TI
)) {
418 if (BI
->isUnconditional()) {
421 LatticeVal
&BCValue
= getValueState(BI
->getCondition());
422 if (BCValue
.isOverdefined() ||
423 (BCValue
.isConstant() && !isa
<ConstantInt
>(BCValue
.getConstant()))) {
424 // Overdefined condition variables, and branches on unfoldable constant
425 // conditions, mean the branch could go either way.
426 Succs
[0] = Succs
[1] = true;
427 } else if (BCValue
.isConstant()) {
428 // Constant condition variables mean the branch can only go a single way
429 Succs
[BCValue
.getConstant() == ConstantInt::getFalse()] = true;
432 } else if (isa
<InvokeInst
>(&TI
)) {
433 // Invoke instructions successors are always executable.
434 Succs
[0] = Succs
[1] = true;
435 } else if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(&TI
)) {
436 LatticeVal
&SCValue
= getValueState(SI
->getCondition());
437 if (SCValue
.isOverdefined() || // Overdefined condition?
438 (SCValue
.isConstant() && !isa
<ConstantInt
>(SCValue
.getConstant()))) {
439 // All destinations are executable!
440 Succs
.assign(TI
.getNumSuccessors(), true);
441 } else if (SCValue
.isConstant()) {
442 Constant
*CPV
= SCValue
.getConstant();
443 // Make sure to skip the "default value" which isn't a value
444 for (unsigned i
= 1, E
= SI
->getNumSuccessors(); i
!= E
; ++i
) {
445 if (SI
->getSuccessorValue(i
) == CPV
) {// Found the right branch...
451 // Constant value not equal to any of the branches... must execute
452 // default branch then...
456 assert(0 && "SCCP: Don't know how to handle this terminator!");
461 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
462 // block to the 'To' basic block is currently feasible...
464 bool SCCPSolver::isEdgeFeasible(BasicBlock
*From
, BasicBlock
*To
) {
465 assert(BBExecutable
.count(To
) && "Dest should always be alive!");
467 // Make sure the source basic block is executable!!
468 if (!BBExecutable
.count(From
)) return false;
470 // Check to make sure this edge itself is actually feasible now...
471 TerminatorInst
*TI
= From
->getTerminator();
472 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(TI
)) {
473 if (BI
->isUnconditional())
476 LatticeVal
&BCValue
= getValueState(BI
->getCondition());
477 if (BCValue
.isOverdefined()) {
478 // Overdefined condition variables mean the branch could go either way.
480 } else if (BCValue
.isConstant()) {
481 // Not branching on an evaluatable constant?
482 if (!isa
<ConstantInt
>(BCValue
.getConstant())) return true;
484 // Constant condition variables mean the branch can only go a single way
485 return BI
->getSuccessor(BCValue
.getConstant() ==
486 ConstantInt::getFalse()) == To
;
490 } else if (isa
<InvokeInst
>(TI
)) {
491 // Invoke instructions successors are always executable.
493 } else if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(TI
)) {
494 LatticeVal
&SCValue
= getValueState(SI
->getCondition());
495 if (SCValue
.isOverdefined()) { // Overdefined condition?
496 // All destinations are executable!
498 } else if (SCValue
.isConstant()) {
499 Constant
*CPV
= SCValue
.getConstant();
500 if (!isa
<ConstantInt
>(CPV
))
501 return true; // not a foldable constant?
503 // Make sure to skip the "default value" which isn't a value
504 for (unsigned i
= 1, E
= SI
->getNumSuccessors(); i
!= E
; ++i
)
505 if (SI
->getSuccessorValue(i
) == CPV
) // Found the taken branch...
506 return SI
->getSuccessor(i
) == To
;
508 // Constant value not equal to any of the branches... must execute
509 // default branch then...
510 return SI
->getDefaultDest() == To
;
514 cerr
<< "Unknown terminator instruction: " << *TI
;
519 // visit Implementations - Something changed in this instruction... Either an
520 // operand made a transition, or the instruction is newly executable. Change
521 // the value type of I to reflect these changes if appropriate. This method
522 // makes sure to do the following actions:
524 // 1. If a phi node merges two constants in, and has conflicting value coming
525 // from different branches, or if the PHI node merges in an overdefined
526 // value, then the PHI node becomes overdefined.
527 // 2. If a phi node merges only constants in, and they all agree on value, the
528 // PHI node becomes a constant value equal to that.
529 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
530 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
531 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
532 // 6. If a conditional branch has a value that is constant, make the selected
533 // destination executable
534 // 7. If a conditional branch has a value that is overdefined, make all
535 // successors executable.
537 void SCCPSolver::visitPHINode(PHINode
&PN
) {
538 LatticeVal
&PNIV
= getValueState(&PN
);
539 if (PNIV
.isOverdefined()) {
540 // There may be instructions using this PHI node that are not overdefined
541 // themselves. If so, make sure that they know that the PHI node operand
543 std::multimap
<PHINode
*, Instruction
*>::iterator I
, E
;
544 tie(I
, E
) = UsersOfOverdefinedPHIs
.equal_range(&PN
);
546 SmallVector
<Instruction
*, 16> Users
;
547 for (; I
!= E
; ++I
) Users
.push_back(I
->second
);
548 while (!Users
.empty()) {
553 return; // Quick exit
556 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
557 // and slow us down a lot. Just mark them overdefined.
558 if (PN
.getNumIncomingValues() > 64) {
559 markOverdefined(PNIV
, &PN
);
563 // Look at all of the executable operands of the PHI node. If any of them
564 // are overdefined, the PHI becomes overdefined as well. If they are all
565 // constant, and they agree with each other, the PHI becomes the identical
566 // constant. If they are constant and don't agree, the PHI is overdefined.
567 // If there are no executable operands, the PHI remains undefined.
569 Constant
*OperandVal
= 0;
570 for (unsigned i
= 0, e
= PN
.getNumIncomingValues(); i
!= e
; ++i
) {
571 LatticeVal
&IV
= getValueState(PN
.getIncomingValue(i
));
572 if (IV
.isUndefined()) continue; // Doesn't influence PHI node.
574 if (isEdgeFeasible(PN
.getIncomingBlock(i
), PN
.getParent())) {
575 if (IV
.isOverdefined()) { // PHI node becomes overdefined!
576 markOverdefined(PNIV
, &PN
);
580 if (OperandVal
== 0) { // Grab the first value...
581 OperandVal
= IV
.getConstant();
582 } else { // Another value is being merged in!
583 // There is already a reachable operand. If we conflict with it,
584 // then the PHI node becomes overdefined. If we agree with it, we
587 // Check to see if there are two different constants merging...
588 if (IV
.getConstant() != OperandVal
) {
589 // Yes there is. This means the PHI node is not constant.
590 // You must be overdefined poor PHI.
592 markOverdefined(PNIV
, &PN
); // The PHI node now becomes overdefined
593 return; // I'm done analyzing you
599 // If we exited the loop, this means that the PHI node only has constant
600 // arguments that agree with each other(and OperandVal is the constant) or
601 // OperandVal is null because there are no defined incoming arguments. If
602 // this is the case, the PHI remains undefined.
605 markConstant(PNIV
, &PN
, OperandVal
); // Acquire operand value
608 void SCCPSolver::visitReturnInst(ReturnInst
&I
) {
609 if (I
.getNumOperands() == 0) return; // Ret void
611 // If we are tracking the return value of this function, merge it in.
612 Function
*F
= I
.getParent()->getParent();
613 if (F
->hasInternalLinkage() && !TrackedFunctionRetVals
.empty()) {
614 DenseMap
<Function
*, LatticeVal
>::iterator TFRVI
=
615 TrackedFunctionRetVals
.find(F
);
616 if (TFRVI
!= TrackedFunctionRetVals
.end() &&
617 !TFRVI
->second
.isOverdefined()) {
618 LatticeVal
&IV
= getValueState(I
.getOperand(0));
619 mergeInValue(TFRVI
->second
, F
, IV
);
625 void SCCPSolver::visitTerminatorInst(TerminatorInst
&TI
) {
626 SmallVector
<bool, 16> SuccFeasible
;
627 getFeasibleSuccessors(TI
, SuccFeasible
);
629 BasicBlock
*BB
= TI
.getParent();
631 // Mark all feasible successors executable...
632 for (unsigned i
= 0, e
= SuccFeasible
.size(); i
!= e
; ++i
)
634 markEdgeExecutable(BB
, TI
.getSuccessor(i
));
637 void SCCPSolver::visitCastInst(CastInst
&I
) {
638 Value
*V
= I
.getOperand(0);
639 LatticeVal
&VState
= getValueState(V
);
640 if (VState
.isOverdefined()) // Inherit overdefinedness of operand
642 else if (VState
.isConstant()) // Propagate constant value
643 markConstant(&I
, ConstantExpr::getCast(I
.getOpcode(),
644 VState
.getConstant(), I
.getType()));
647 void SCCPSolver::visitSelectInst(SelectInst
&I
) {
648 LatticeVal
&CondValue
= getValueState(I
.getCondition());
649 if (CondValue
.isUndefined())
651 if (CondValue
.isConstant()) {
652 if (ConstantInt
*CondCB
= dyn_cast
<ConstantInt
>(CondValue
.getConstant())){
653 mergeInValue(&I
, getValueState(CondCB
->getZExtValue() ? I
.getTrueValue()
654 : I
.getFalseValue()));
659 // Otherwise, the condition is overdefined or a constant we can't evaluate.
660 // See if we can produce something better than overdefined based on the T/F
662 LatticeVal
&TVal
= getValueState(I
.getTrueValue());
663 LatticeVal
&FVal
= getValueState(I
.getFalseValue());
665 // select ?, C, C -> C.
666 if (TVal
.isConstant() && FVal
.isConstant() &&
667 TVal
.getConstant() == FVal
.getConstant()) {
668 markConstant(&I
, FVal
.getConstant());
672 if (TVal
.isUndefined()) { // select ?, undef, X -> X.
673 mergeInValue(&I
, FVal
);
674 } else if (FVal
.isUndefined()) { // select ?, X, undef -> X.
675 mergeInValue(&I
, TVal
);
681 // Handle BinaryOperators and Shift Instructions...
682 void SCCPSolver::visitBinaryOperator(Instruction
&I
) {
683 LatticeVal
&IV
= ValueState
[&I
];
684 if (IV
.isOverdefined()) return;
686 LatticeVal
&V1State
= getValueState(I
.getOperand(0));
687 LatticeVal
&V2State
= getValueState(I
.getOperand(1));
689 if (V1State
.isOverdefined() || V2State
.isOverdefined()) {
690 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
691 // operand is overdefined.
692 if (I
.getOpcode() == Instruction::And
|| I
.getOpcode() == Instruction::Or
) {
693 LatticeVal
*NonOverdefVal
= 0;
694 if (!V1State
.isOverdefined()) {
695 NonOverdefVal
= &V1State
;
696 } else if (!V2State
.isOverdefined()) {
697 NonOverdefVal
= &V2State
;
701 if (NonOverdefVal
->isUndefined()) {
702 // Could annihilate value.
703 if (I
.getOpcode() == Instruction::And
)
704 markConstant(IV
, &I
, Constant::getNullValue(I
.getType()));
705 else if (const VectorType
*PT
= dyn_cast
<VectorType
>(I
.getType()))
706 markConstant(IV
, &I
, ConstantVector::getAllOnesValue(PT
));
708 markConstant(IV
, &I
, ConstantInt::getAllOnesValue(I
.getType()));
711 if (I
.getOpcode() == Instruction::And
) {
712 if (NonOverdefVal
->getConstant()->isNullValue()) {
713 markConstant(IV
, &I
, NonOverdefVal
->getConstant());
714 return; // X and 0 = 0
717 if (ConstantInt
*CI
=
718 dyn_cast
<ConstantInt
>(NonOverdefVal
->getConstant()))
719 if (CI
->isAllOnesValue()) {
720 markConstant(IV
, &I
, NonOverdefVal
->getConstant());
721 return; // X or -1 = -1
729 // If both operands are PHI nodes, it is possible that this instruction has
730 // a constant value, despite the fact that the PHI node doesn't. Check for
731 // this condition now.
732 if (PHINode
*PN1
= dyn_cast
<PHINode
>(I
.getOperand(0)))
733 if (PHINode
*PN2
= dyn_cast
<PHINode
>(I
.getOperand(1)))
734 if (PN1
->getParent() == PN2
->getParent()) {
735 // Since the two PHI nodes are in the same basic block, they must have
736 // entries for the same predecessors. Walk the predecessor list, and
737 // if all of the incoming values are constants, and the result of
738 // evaluating this expression with all incoming value pairs is the
739 // same, then this expression is a constant even though the PHI node
740 // is not a constant!
742 for (unsigned i
= 0, e
= PN1
->getNumIncomingValues(); i
!= e
; ++i
) {
743 LatticeVal
&In1
= getValueState(PN1
->getIncomingValue(i
));
744 BasicBlock
*InBlock
= PN1
->getIncomingBlock(i
);
746 getValueState(PN2
->getIncomingValueForBlock(InBlock
));
748 if (In1
.isOverdefined() || In2
.isOverdefined()) {
749 Result
.markOverdefined();
750 break; // Cannot fold this operation over the PHI nodes!
751 } else if (In1
.isConstant() && In2
.isConstant()) {
752 Constant
*V
= ConstantExpr::get(I
.getOpcode(), In1
.getConstant(),
754 if (Result
.isUndefined())
755 Result
.markConstant(V
);
756 else if (Result
.isConstant() && Result
.getConstant() != V
) {
757 Result
.markOverdefined();
763 // If we found a constant value here, then we know the instruction is
764 // constant despite the fact that the PHI nodes are overdefined.
765 if (Result
.isConstant()) {
766 markConstant(IV
, &I
, Result
.getConstant());
767 // Remember that this instruction is virtually using the PHI node
769 UsersOfOverdefinedPHIs
.insert(std::make_pair(PN1
, &I
));
770 UsersOfOverdefinedPHIs
.insert(std::make_pair(PN2
, &I
));
772 } else if (Result
.isUndefined()) {
776 // Okay, this really is overdefined now. Since we might have
777 // speculatively thought that this was not overdefined before, and
778 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
779 // make sure to clean out any entries that we put there, for
781 std::multimap
<PHINode
*, Instruction
*>::iterator It
, E
;
782 tie(It
, E
) = UsersOfOverdefinedPHIs
.equal_range(PN1
);
784 if (It
->second
== &I
) {
785 UsersOfOverdefinedPHIs
.erase(It
++);
789 tie(It
, E
) = UsersOfOverdefinedPHIs
.equal_range(PN2
);
791 if (It
->second
== &I
) {
792 UsersOfOverdefinedPHIs
.erase(It
++);
798 markOverdefined(IV
, &I
);
799 } else if (V1State
.isConstant() && V2State
.isConstant()) {
800 markConstant(IV
, &I
, ConstantExpr::get(I
.getOpcode(), V1State
.getConstant(),
801 V2State
.getConstant()));
805 // Handle ICmpInst instruction...
806 void SCCPSolver::visitCmpInst(CmpInst
&I
) {
807 LatticeVal
&IV
= ValueState
[&I
];
808 if (IV
.isOverdefined()) return;
810 LatticeVal
&V1State
= getValueState(I
.getOperand(0));
811 LatticeVal
&V2State
= getValueState(I
.getOperand(1));
813 if (V1State
.isOverdefined() || V2State
.isOverdefined()) {
814 // If both operands are PHI nodes, it is possible that this instruction has
815 // a constant value, despite the fact that the PHI node doesn't. Check for
816 // this condition now.
817 if (PHINode
*PN1
= dyn_cast
<PHINode
>(I
.getOperand(0)))
818 if (PHINode
*PN2
= dyn_cast
<PHINode
>(I
.getOperand(1)))
819 if (PN1
->getParent() == PN2
->getParent()) {
820 // Since the two PHI nodes are in the same basic block, they must have
821 // entries for the same predecessors. Walk the predecessor list, and
822 // if all of the incoming values are constants, and the result of
823 // evaluating this expression with all incoming value pairs is the
824 // same, then this expression is a constant even though the PHI node
825 // is not a constant!
827 for (unsigned i
= 0, e
= PN1
->getNumIncomingValues(); i
!= e
; ++i
) {
828 LatticeVal
&In1
= getValueState(PN1
->getIncomingValue(i
));
829 BasicBlock
*InBlock
= PN1
->getIncomingBlock(i
);
831 getValueState(PN2
->getIncomingValueForBlock(InBlock
));
833 if (In1
.isOverdefined() || In2
.isOverdefined()) {
834 Result
.markOverdefined();
835 break; // Cannot fold this operation over the PHI nodes!
836 } else if (In1
.isConstant() && In2
.isConstant()) {
837 Constant
*V
= ConstantExpr::getCompare(I
.getPredicate(),
840 if (Result
.isUndefined())
841 Result
.markConstant(V
);
842 else if (Result
.isConstant() && Result
.getConstant() != V
) {
843 Result
.markOverdefined();
849 // If we found a constant value here, then we know the instruction is
850 // constant despite the fact that the PHI nodes are overdefined.
851 if (Result
.isConstant()) {
852 markConstant(IV
, &I
, Result
.getConstant());
853 // Remember that this instruction is virtually using the PHI node
855 UsersOfOverdefinedPHIs
.insert(std::make_pair(PN1
, &I
));
856 UsersOfOverdefinedPHIs
.insert(std::make_pair(PN2
, &I
));
858 } else if (Result
.isUndefined()) {
862 // Okay, this really is overdefined now. Since we might have
863 // speculatively thought that this was not overdefined before, and
864 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
865 // make sure to clean out any entries that we put there, for
867 std::multimap
<PHINode
*, Instruction
*>::iterator It
, E
;
868 tie(It
, E
) = UsersOfOverdefinedPHIs
.equal_range(PN1
);
870 if (It
->second
== &I
) {
871 UsersOfOverdefinedPHIs
.erase(It
++);
875 tie(It
, E
) = UsersOfOverdefinedPHIs
.equal_range(PN2
);
877 if (It
->second
== &I
) {
878 UsersOfOverdefinedPHIs
.erase(It
++);
884 markOverdefined(IV
, &I
);
885 } else if (V1State
.isConstant() && V2State
.isConstant()) {
886 markConstant(IV
, &I
, ConstantExpr::getCompare(I
.getPredicate(),
887 V1State
.getConstant(),
888 V2State
.getConstant()));
892 void SCCPSolver::visitExtractElementInst(ExtractElementInst
&I
) {
893 // FIXME : SCCP does not handle vectors properly.
898 LatticeVal
&ValState
= getValueState(I
.getOperand(0));
899 LatticeVal
&IdxState
= getValueState(I
.getOperand(1));
901 if (ValState
.isOverdefined() || IdxState
.isOverdefined())
903 else if(ValState
.isConstant() && IdxState
.isConstant())
904 markConstant(&I
, ConstantExpr::getExtractElement(ValState
.getConstant(),
905 IdxState
.getConstant()));
909 void SCCPSolver::visitInsertElementInst(InsertElementInst
&I
) {
910 // FIXME : SCCP does not handle vectors properly.
914 LatticeVal
&ValState
= getValueState(I
.getOperand(0));
915 LatticeVal
&EltState
= getValueState(I
.getOperand(1));
916 LatticeVal
&IdxState
= getValueState(I
.getOperand(2));
918 if (ValState
.isOverdefined() || EltState
.isOverdefined() ||
919 IdxState
.isOverdefined())
921 else if(ValState
.isConstant() && EltState
.isConstant() &&
922 IdxState
.isConstant())
923 markConstant(&I
, ConstantExpr::getInsertElement(ValState
.getConstant(),
924 EltState
.getConstant(),
925 IdxState
.getConstant()));
926 else if (ValState
.isUndefined() && EltState
.isConstant() &&
927 IdxState
.isConstant())
928 markConstant(&I
,ConstantExpr::getInsertElement(UndefValue::get(I
.getType()),
929 EltState
.getConstant(),
930 IdxState
.getConstant()));
934 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst
&I
) {
935 // FIXME : SCCP does not handle vectors properly.
939 LatticeVal
&V1State
= getValueState(I
.getOperand(0));
940 LatticeVal
&V2State
= getValueState(I
.getOperand(1));
941 LatticeVal
&MaskState
= getValueState(I
.getOperand(2));
943 if (MaskState
.isUndefined() ||
944 (V1State
.isUndefined() && V2State
.isUndefined()))
945 return; // Undefined output if mask or both inputs undefined.
947 if (V1State
.isOverdefined() || V2State
.isOverdefined() ||
948 MaskState
.isOverdefined()) {
951 // A mix of constant/undef inputs.
952 Constant
*V1
= V1State
.isConstant() ?
953 V1State
.getConstant() : UndefValue::get(I
.getType());
954 Constant
*V2
= V2State
.isConstant() ?
955 V2State
.getConstant() : UndefValue::get(I
.getType());
956 Constant
*Mask
= MaskState
.isConstant() ?
957 MaskState
.getConstant() : UndefValue::get(I
.getOperand(2)->getType());
958 markConstant(&I
, ConstantExpr::getShuffleVector(V1
, V2
, Mask
));
963 // Handle getelementptr instructions... if all operands are constants then we
964 // can turn this into a getelementptr ConstantExpr.
966 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst
&I
) {
967 LatticeVal
&IV
= ValueState
[&I
];
968 if (IV
.isOverdefined()) return;
970 SmallVector
<Constant
*, 8> Operands
;
971 Operands
.reserve(I
.getNumOperands());
973 for (unsigned i
= 0, e
= I
.getNumOperands(); i
!= e
; ++i
) {
974 LatticeVal
&State
= getValueState(I
.getOperand(i
));
975 if (State
.isUndefined())
976 return; // Operands are not resolved yet...
977 else if (State
.isOverdefined()) {
978 markOverdefined(IV
, &I
);
981 assert(State
.isConstant() && "Unknown state!");
982 Operands
.push_back(State
.getConstant());
985 Constant
*Ptr
= Operands
[0];
986 Operands
.erase(Operands
.begin()); // Erase the pointer from idx list...
988 markConstant(IV
, &I
, ConstantExpr::getGetElementPtr(Ptr
, &Operands
[0],
992 void SCCPSolver::visitStoreInst(Instruction
&SI
) {
993 if (TrackedGlobals
.empty() || !isa
<GlobalVariable
>(SI
.getOperand(1)))
995 GlobalVariable
*GV
= cast
<GlobalVariable
>(SI
.getOperand(1));
996 DenseMap
<GlobalVariable
*, LatticeVal
>::iterator I
= TrackedGlobals
.find(GV
);
997 if (I
== TrackedGlobals
.end() || I
->second
.isOverdefined()) return;
999 // Get the value we are storing into the global.
1000 LatticeVal
&PtrVal
= getValueState(SI
.getOperand(0));
1002 mergeInValue(I
->second
, GV
, PtrVal
);
1003 if (I
->second
.isOverdefined())
1004 TrackedGlobals
.erase(I
); // No need to keep tracking this!
1008 // Handle load instructions. If the operand is a constant pointer to a constant
1009 // global, we can replace the load with the loaded constant value!
1010 void SCCPSolver::visitLoadInst(LoadInst
&I
) {
1011 LatticeVal
&IV
= ValueState
[&I
];
1012 if (IV
.isOverdefined()) return;
1014 LatticeVal
&PtrVal
= getValueState(I
.getOperand(0));
1015 if (PtrVal
.isUndefined()) return; // The pointer is not resolved yet!
1016 if (PtrVal
.isConstant() && !I
.isVolatile()) {
1017 Value
*Ptr
= PtrVal
.getConstant();
1018 if (isa
<ConstantPointerNull
>(Ptr
)) {
1019 // load null -> null
1020 markConstant(IV
, &I
, Constant::getNullValue(I
.getType()));
1024 // Transform load (constant global) into the value loaded.
1025 if (GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(Ptr
)) {
1026 if (GV
->isConstant()) {
1027 if (!GV
->isDeclaration()) {
1028 markConstant(IV
, &I
, GV
->getInitializer());
1031 } else if (!TrackedGlobals
.empty()) {
1032 // If we are tracking this global, merge in the known value for it.
1033 DenseMap
<GlobalVariable
*, LatticeVal
>::iterator It
=
1034 TrackedGlobals
.find(GV
);
1035 if (It
!= TrackedGlobals
.end()) {
1036 mergeInValue(IV
, &I
, It
->second
);
1042 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1043 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(Ptr
))
1044 if (CE
->getOpcode() == Instruction::GetElementPtr
)
1045 if (GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(CE
->getOperand(0)))
1046 if (GV
->isConstant() && !GV
->isDeclaration())
1048 ConstantFoldLoadThroughGEPConstantExpr(GV
->getInitializer(), CE
)) {
1049 markConstant(IV
, &I
, V
);
1054 // Otherwise we cannot say for certain what value this load will produce.
1056 markOverdefined(IV
, &I
);
1059 void SCCPSolver::visitCallSite(CallSite CS
) {
1060 Function
*F
= CS
.getCalledFunction();
1062 // If we are tracking this function, we must make sure to bind arguments as
1064 DenseMap
<Function
*, LatticeVal
>::iterator TFRVI
=TrackedFunctionRetVals
.end();
1065 if (F
&& F
->hasInternalLinkage())
1066 TFRVI
= TrackedFunctionRetVals
.find(F
);
1068 if (TFRVI
!= TrackedFunctionRetVals
.end()) {
1069 // If this is the first call to the function hit, mark its entry block
1071 if (!BBExecutable
.count(F
->begin()))
1072 MarkBlockExecutable(F
->begin());
1074 CallSite::arg_iterator CAI
= CS
.arg_begin();
1075 for (Function::arg_iterator AI
= F
->arg_begin(), E
= F
->arg_end();
1076 AI
!= E
; ++AI
, ++CAI
) {
1077 LatticeVal
&IV
= ValueState
[AI
];
1078 if (!IV
.isOverdefined())
1079 mergeInValue(IV
, AI
, getValueState(*CAI
));
1082 Instruction
*I
= CS
.getInstruction();
1083 if (I
->getType() == Type::VoidTy
) return;
1085 LatticeVal
&IV
= ValueState
[I
];
1086 if (IV
.isOverdefined()) return;
1088 // Propagate the return value of the function to the value of the instruction.
1089 if (TFRVI
!= TrackedFunctionRetVals
.end()) {
1090 mergeInValue(IV
, I
, TFRVI
->second
);
1094 if (F
== 0 || !F
->isDeclaration() || !canConstantFoldCallTo(F
)) {
1095 markOverdefined(IV
, I
);
1099 SmallVector
<Constant
*, 8> Operands
;
1100 Operands
.reserve(I
->getNumOperands()-1);
1102 for (CallSite::arg_iterator AI
= CS
.arg_begin(), E
= CS
.arg_end();
1104 LatticeVal
&State
= getValueState(*AI
);
1105 if (State
.isUndefined())
1106 return; // Operands are not resolved yet...
1107 else if (State
.isOverdefined()) {
1108 markOverdefined(IV
, I
);
1111 assert(State
.isConstant() && "Unknown state!");
1112 Operands
.push_back(State
.getConstant());
1115 if (Constant
*C
= ConstantFoldCall(F
, &Operands
[0], Operands
.size()))
1116 markConstant(IV
, I
, C
);
1118 markOverdefined(IV
, I
);
1122 void SCCPSolver::Solve() {
1123 // Process the work lists until they are empty!
1124 while (!BBWorkList
.empty() || !InstWorkList
.empty() ||
1125 !OverdefinedInstWorkList
.empty()) {
1126 // Process the instruction work list...
1127 while (!OverdefinedInstWorkList
.empty()) {
1128 Value
*I
= OverdefinedInstWorkList
.back();
1129 OverdefinedInstWorkList
.pop_back();
1131 DOUT
<< "\nPopped off OI-WL: " << *I
;
1133 // "I" got into the work list because it either made the transition from
1134 // bottom to constant
1136 // Anything on this worklist that is overdefined need not be visited
1137 // since all of its users will have already been marked as overdefined
1138 // Update all of the users of this instruction's value...
1140 for (Value::use_iterator UI
= I
->use_begin(), E
= I
->use_end();
1142 OperandChangedState(*UI
);
1144 // Process the instruction work list...
1145 while (!InstWorkList
.empty()) {
1146 Value
*I
= InstWorkList
.back();
1147 InstWorkList
.pop_back();
1149 DOUT
<< "\nPopped off I-WL: " << *I
;
1151 // "I" got into the work list because it either made the transition from
1152 // bottom to constant
1154 // Anything on this worklist that is overdefined need not be visited
1155 // since all of its users will have already been marked as overdefined.
1156 // Update all of the users of this instruction's value...
1158 if (!getValueState(I
).isOverdefined())
1159 for (Value::use_iterator UI
= I
->use_begin(), E
= I
->use_end();
1161 OperandChangedState(*UI
);
1164 // Process the basic block work list...
1165 while (!BBWorkList
.empty()) {
1166 BasicBlock
*BB
= BBWorkList
.back();
1167 BBWorkList
.pop_back();
1169 DOUT
<< "\nPopped off BBWL: " << *BB
;
1171 // Notify all instructions in this basic block that they are newly
1178 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1179 /// that branches on undef values cannot reach any of their successors.
1180 /// However, this is not a safe assumption. After we solve dataflow, this
1181 /// method should be use to handle this. If this returns true, the solver
1182 /// should be rerun.
1184 /// This method handles this by finding an unresolved branch and marking it one
1185 /// of the edges from the block as being feasible, even though the condition
1186 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1187 /// CFG and only slightly pessimizes the analysis results (by marking one,
1188 /// potentially infeasible, edge feasible). This cannot usefully modify the
1189 /// constraints on the condition of the branch, as that would impact other users
1192 /// This scan also checks for values that use undefs, whose results are actually
1193 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1194 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1195 /// even if X isn't defined.
1196 bool SCCPSolver::ResolvedUndefsIn(Function
&F
) {
1197 for (Function::iterator BB
= F
.begin(), E
= F
.end(); BB
!= E
; ++BB
) {
1198 if (!BBExecutable
.count(BB
))
1201 for (BasicBlock::iterator I
= BB
->begin(), E
= BB
->end(); I
!= E
; ++I
) {
1202 // Look for instructions which produce undef values.
1203 if (I
->getType() == Type::VoidTy
) continue;
1205 LatticeVal
&LV
= getValueState(I
);
1206 if (!LV
.isUndefined()) continue;
1208 // Get the lattice values of the first two operands for use below.
1209 LatticeVal
&Op0LV
= getValueState(I
->getOperand(0));
1211 if (I
->getNumOperands() == 2) {
1212 // If this is a two-operand instruction, and if both operands are
1213 // undefs, the result stays undef.
1214 Op1LV
= getValueState(I
->getOperand(1));
1215 if (Op0LV
.isUndefined() && Op1LV
.isUndefined())
1219 // If this is an instructions whose result is defined even if the input is
1220 // not fully defined, propagate the information.
1221 const Type
*ITy
= I
->getType();
1222 switch (I
->getOpcode()) {
1223 default: break; // Leave the instruction as an undef.
1224 case Instruction::ZExt
:
1225 // After a zero extend, we know the top part is zero. SExt doesn't have
1226 // to be handled here, because we don't know whether the top part is 1's
1228 assert(Op0LV
.isUndefined());
1229 markForcedConstant(LV
, I
, Constant::getNullValue(ITy
));
1231 case Instruction::Mul
:
1232 case Instruction::And
:
1233 // undef * X -> 0. X could be zero.
1234 // undef & X -> 0. X could be zero.
1235 markForcedConstant(LV
, I
, Constant::getNullValue(ITy
));
1238 case Instruction::Or
:
1239 // undef | X -> -1. X could be -1.
1240 if (const VectorType
*PTy
= dyn_cast
<VectorType
>(ITy
))
1241 markForcedConstant(LV
, I
, ConstantVector::getAllOnesValue(PTy
));
1243 markForcedConstant(LV
, I
, ConstantInt::getAllOnesValue(ITy
));
1246 case Instruction::SDiv
:
1247 case Instruction::UDiv
:
1248 case Instruction::SRem
:
1249 case Instruction::URem
:
1250 // X / undef -> undef. No change.
1251 // X % undef -> undef. No change.
1252 if (Op1LV
.isUndefined()) break;
1254 // undef / X -> 0. X could be maxint.
1255 // undef % X -> 0. X could be 1.
1256 markForcedConstant(LV
, I
, Constant::getNullValue(ITy
));
1259 case Instruction::AShr
:
1260 // undef >>s X -> undef. No change.
1261 if (Op0LV
.isUndefined()) break;
1263 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1264 if (Op0LV
.isConstant())
1265 markForcedConstant(LV
, I
, Op0LV
.getConstant());
1267 markOverdefined(LV
, I
);
1269 case Instruction::LShr
:
1270 case Instruction::Shl
:
1271 // undef >> X -> undef. No change.
1272 // undef << X -> undef. No change.
1273 if (Op0LV
.isUndefined()) break;
1275 // X >> undef -> 0. X could be 0.
1276 // X << undef -> 0. X could be 0.
1277 markForcedConstant(LV
, I
, Constant::getNullValue(ITy
));
1279 case Instruction::Select
:
1280 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1281 if (Op0LV
.isUndefined()) {
1282 if (!Op1LV
.isConstant()) // Pick the constant one if there is any.
1283 Op1LV
= getValueState(I
->getOperand(2));
1284 } else if (Op1LV
.isUndefined()) {
1285 // c ? undef : undef -> undef. No change.
1286 Op1LV
= getValueState(I
->getOperand(2));
1287 if (Op1LV
.isUndefined())
1289 // Otherwise, c ? undef : x -> x.
1291 // Leave Op1LV as Operand(1)'s LatticeValue.
1294 if (Op1LV
.isConstant())
1295 markForcedConstant(LV
, I
, Op1LV
.getConstant());
1297 markOverdefined(LV
, I
);
1302 TerminatorInst
*TI
= BB
->getTerminator();
1303 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(TI
)) {
1304 if (!BI
->isConditional()) continue;
1305 if (!getValueState(BI
->getCondition()).isUndefined())
1307 } else if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(TI
)) {
1308 if (!getValueState(SI
->getCondition()).isUndefined())
1314 // If the edge to the first successor isn't thought to be feasible yet, mark
1316 if (KnownFeasibleEdges
.count(Edge(BB
, TI
->getSuccessor(0))))
1319 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1320 // and return. This will make other blocks reachable, which will allow new
1321 // values to be discovered and existing ones to be moved in the lattice.
1322 markEdgeExecutable(BB
, TI
->getSuccessor(0));
1331 //===--------------------------------------------------------------------===//
1333 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1334 /// Sparse Conditional Constant Propagator.
1336 struct VISIBILITY_HIDDEN SCCP
: public FunctionPass
{
1337 static char ID
; // Pass identification, replacement for typeid
1338 SCCP() : FunctionPass((intptr_t)&ID
) {}
1340 // runOnFunction - Run the Sparse Conditional Constant Propagation
1341 // algorithm, and return true if the function was modified.
1343 bool runOnFunction(Function
&F
);
1345 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
1346 AU
.setPreservesCFG();
1351 RegisterPass
<SCCP
> X("sccp", "Sparse Conditional Constant Propagation");
1352 } // end anonymous namespace
1355 // createSCCPPass - This is the public interface to this file...
1356 FunctionPass
*llvm::createSCCPPass() {
1361 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1362 // and return true if the function was modified.
1364 bool SCCP::runOnFunction(Function
&F
) {
1365 DOUT
<< "SCCP on function '" << F
.getName() << "'\n";
1368 // Mark the first block of the function as being executable.
1369 Solver
.MarkBlockExecutable(F
.begin());
1371 // Mark all arguments to the function as being overdefined.
1372 for (Function::arg_iterator AI
= F
.arg_begin(), E
= F
.arg_end(); AI
!= E
;++AI
)
1373 Solver
.markOverdefined(AI
);
1375 // Solve for constants.
1376 bool ResolvedUndefs
= true;
1377 while (ResolvedUndefs
) {
1379 DOUT
<< "RESOLVING UNDEFs\n";
1380 ResolvedUndefs
= Solver
.ResolvedUndefsIn(F
);
1383 bool MadeChanges
= false;
1385 // If we decided that there are basic blocks that are dead in this function,
1386 // delete their contents now. Note that we cannot actually delete the blocks,
1387 // as we cannot modify the CFG of the function.
1389 SmallSet
<BasicBlock
*, 16> &ExecutableBBs
= Solver
.getExecutableBlocks();
1390 SmallVector
<Instruction
*, 32> Insts
;
1391 std::map
<Value
*, LatticeVal
> &Values
= Solver
.getValueMapping();
1393 for (Function::iterator BB
= F
.begin(), E
= F
.end(); BB
!= E
; ++BB
)
1394 if (!ExecutableBBs
.count(BB
)) {
1395 DOUT
<< " BasicBlock Dead:" << *BB
;
1398 // Delete the instructions backwards, as it has a reduced likelihood of
1399 // having to update as many def-use and use-def chains.
1400 for (BasicBlock::iterator I
= BB
->begin(), E
= BB
->getTerminator();
1403 while (!Insts
.empty()) {
1404 Instruction
*I
= Insts
.back();
1406 if (!I
->use_empty())
1407 I
->replaceAllUsesWith(UndefValue::get(I
->getType()));
1408 BB
->getInstList().erase(I
);
1413 // Iterate over all of the instructions in a function, replacing them with
1414 // constants if we have found them to be of constant values.
1416 for (BasicBlock::iterator BI
= BB
->begin(), E
= BB
->end(); BI
!= E
; ) {
1417 Instruction
*Inst
= BI
++;
1418 if (Inst
->getType() != Type::VoidTy
) {
1419 LatticeVal
&IV
= Values
[Inst
];
1420 if ((IV
.isConstant() || IV
.isUndefined()) &&
1421 !isa
<TerminatorInst
>(Inst
)) {
1422 Constant
*Const
= IV
.isConstant()
1423 ? IV
.getConstant() : UndefValue::get(Inst
->getType());
1424 DOUT
<< " Constant: " << *Const
<< " = " << *Inst
;
1426 // Replaces all of the uses of a variable with uses of the constant.
1427 Inst
->replaceAllUsesWith(Const
);
1429 // Delete the instruction.
1430 BB
->getInstList().erase(Inst
);
1432 // Hey, we just changed something!
1444 //===--------------------------------------------------------------------===//
1446 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1447 /// Constant Propagation.
1449 struct VISIBILITY_HIDDEN IPSCCP
: public ModulePass
{
1451 IPSCCP() : ModulePass((intptr_t)&ID
) {}
1452 bool runOnModule(Module
&M
);
1455 char IPSCCP::ID
= 0;
1456 RegisterPass
<IPSCCP
>
1457 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1458 } // end anonymous namespace
1460 // createIPSCCPPass - This is the public interface to this file...
1461 ModulePass
*llvm::createIPSCCPPass() {
1462 return new IPSCCP();
1466 static bool AddressIsTaken(GlobalValue
*GV
) {
1467 // Delete any dead constantexpr klingons.
1468 GV
->removeDeadConstantUsers();
1470 for (Value::use_iterator UI
= GV
->use_begin(), E
= GV
->use_end();
1472 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(*UI
)) {
1473 if (SI
->getOperand(0) == GV
|| SI
->isVolatile())
1474 return true; // Storing addr of GV.
1475 } else if (isa
<InvokeInst
>(*UI
) || isa
<CallInst
>(*UI
)) {
1476 // Make sure we are calling the function, not passing the address.
1477 CallSite CS
= CallSite::get(cast
<Instruction
>(*UI
));
1478 for (CallSite::arg_iterator AI
= CS
.arg_begin(),
1479 E
= CS
.arg_end(); AI
!= E
; ++AI
)
1482 } else if (LoadInst
*LI
= dyn_cast
<LoadInst
>(*UI
)) {
1483 if (LI
->isVolatile())
1491 bool IPSCCP::runOnModule(Module
&M
) {
1494 // Loop over all functions, marking arguments to those with their addresses
1495 // taken or that are external as overdefined.
1497 for (Module::iterator F
= M
.begin(), E
= M
.end(); F
!= E
; ++F
)
1498 if (!F
->hasInternalLinkage() || AddressIsTaken(F
)) {
1499 if (!F
->isDeclaration())
1500 Solver
.MarkBlockExecutable(F
->begin());
1501 for (Function::arg_iterator AI
= F
->arg_begin(), E
= F
->arg_end();
1503 Solver
.markOverdefined(AI
);
1505 Solver
.AddTrackedFunction(F
);
1508 // Loop over global variables. We inform the solver about any internal global
1509 // variables that do not have their 'addresses taken'. If they don't have
1510 // their addresses taken, we can propagate constants through them.
1511 for (Module::global_iterator G
= M
.global_begin(), E
= M
.global_end();
1513 if (!G
->isConstant() && G
->hasInternalLinkage() && !AddressIsTaken(G
))
1514 Solver
.TrackValueOfGlobalVariable(G
);
1516 // Solve for constants.
1517 bool ResolvedUndefs
= true;
1518 while (ResolvedUndefs
) {
1521 DOUT
<< "RESOLVING UNDEFS\n";
1522 ResolvedUndefs
= false;
1523 for (Module::iterator F
= M
.begin(), E
= M
.end(); F
!= E
; ++F
)
1524 ResolvedUndefs
|= Solver
.ResolvedUndefsIn(*F
);
1527 bool MadeChanges
= false;
1529 // Iterate over all of the instructions in the module, replacing them with
1530 // constants if we have found them to be of constant values.
1532 SmallSet
<BasicBlock
*, 16> &ExecutableBBs
= Solver
.getExecutableBlocks();
1533 SmallVector
<Instruction
*, 32> Insts
;
1534 SmallVector
<BasicBlock
*, 32> BlocksToErase
;
1535 std::map
<Value
*, LatticeVal
> &Values
= Solver
.getValueMapping();
1537 for (Module::iterator F
= M
.begin(), E
= M
.end(); F
!= E
; ++F
) {
1538 for (Function::arg_iterator AI
= F
->arg_begin(), E
= F
->arg_end();
1540 if (!AI
->use_empty()) {
1541 LatticeVal
&IV
= Values
[AI
];
1542 if (IV
.isConstant() || IV
.isUndefined()) {
1543 Constant
*CST
= IV
.isConstant() ?
1544 IV
.getConstant() : UndefValue::get(AI
->getType());
1545 DOUT
<< "*** Arg " << *AI
<< " = " << *CST
<<"\n";
1547 // Replaces all of the uses of a variable with uses of the
1549 AI
->replaceAllUsesWith(CST
);
1554 for (Function::iterator BB
= F
->begin(), E
= F
->end(); BB
!= E
; ++BB
)
1555 if (!ExecutableBBs
.count(BB
)) {
1556 DOUT
<< " BasicBlock Dead:" << *BB
;
1559 // Delete the instructions backwards, as it has a reduced likelihood of
1560 // having to update as many def-use and use-def chains.
1561 TerminatorInst
*TI
= BB
->getTerminator();
1562 for (BasicBlock::iterator I
= BB
->begin(), E
= TI
; I
!= E
; ++I
)
1565 while (!Insts
.empty()) {
1566 Instruction
*I
= Insts
.back();
1568 if (!I
->use_empty())
1569 I
->replaceAllUsesWith(UndefValue::get(I
->getType()));
1570 BB
->getInstList().erase(I
);
1575 for (unsigned i
= 0, e
= TI
->getNumSuccessors(); i
!= e
; ++i
) {
1576 BasicBlock
*Succ
= TI
->getSuccessor(i
);
1577 if (!Succ
->empty() && isa
<PHINode
>(Succ
->begin()))
1578 TI
->getSuccessor(i
)->removePredecessor(BB
);
1580 if (!TI
->use_empty())
1581 TI
->replaceAllUsesWith(UndefValue::get(TI
->getType()));
1582 BB
->getInstList().erase(TI
);
1584 if (&*BB
!= &F
->front())
1585 BlocksToErase
.push_back(BB
);
1587 new UnreachableInst(BB
);
1590 for (BasicBlock::iterator BI
= BB
->begin(), E
= BB
->end(); BI
!= E
; ) {
1591 Instruction
*Inst
= BI
++;
1592 if (Inst
->getType() != Type::VoidTy
) {
1593 LatticeVal
&IV
= Values
[Inst
];
1594 if (IV
.isConstant() || IV
.isUndefined() &&
1595 !isa
<TerminatorInst
>(Inst
)) {
1596 Constant
*Const
= IV
.isConstant()
1597 ? IV
.getConstant() : UndefValue::get(Inst
->getType());
1598 DOUT
<< " Constant: " << *Const
<< " = " << *Inst
;
1600 // Replaces all of the uses of a variable with uses of the
1602 Inst
->replaceAllUsesWith(Const
);
1604 // Delete the instruction.
1605 if (!isa
<TerminatorInst
>(Inst
) && !isa
<CallInst
>(Inst
))
1606 BB
->getInstList().erase(Inst
);
1608 // Hey, we just changed something!
1616 // Now that all instructions in the function are constant folded, erase dead
1617 // blocks, because we can now use ConstantFoldTerminator to get rid of
1619 for (unsigned i
= 0, e
= BlocksToErase
.size(); i
!= e
; ++i
) {
1620 // If there are any PHI nodes in this successor, drop entries for BB now.
1621 BasicBlock
*DeadBB
= BlocksToErase
[i
];
1622 while (!DeadBB
->use_empty()) {
1623 Instruction
*I
= cast
<Instruction
>(DeadBB
->use_back());
1624 bool Folded
= ConstantFoldTerminator(I
->getParent());
1626 // The constant folder may not have been able to fold the terminator
1627 // if this is a branch or switch on undef. Fold it manually as a
1628 // branch to the first successor.
1629 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(I
)) {
1630 assert(BI
->isConditional() && isa
<UndefValue
>(BI
->getCondition()) &&
1631 "Branch should be foldable!");
1632 } else if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(I
)) {
1633 assert(isa
<UndefValue
>(SI
->getCondition()) && "Switch should fold");
1635 assert(0 && "Didn't fold away reference to block!");
1638 // Make this an uncond branch to the first successor.
1639 TerminatorInst
*TI
= I
->getParent()->getTerminator();
1640 new BranchInst(TI
->getSuccessor(0), TI
);
1642 // Remove entries in successor phi nodes to remove edges.
1643 for (unsigned i
= 1, e
= TI
->getNumSuccessors(); i
!= e
; ++i
)
1644 TI
->getSuccessor(i
)->removePredecessor(TI
->getParent());
1646 // Remove the old terminator.
1647 TI
->eraseFromParent();
1651 // Finally, delete the basic block.
1652 F
->getBasicBlockList().erase(DeadBB
);
1654 BlocksToErase
.clear();
1657 // If we inferred constant or undef return values for a function, we replaced
1658 // all call uses with the inferred value. This means we don't need to bother
1659 // actually returning anything from the function. Replace all return
1660 // instructions with return undef.
1661 const DenseMap
<Function
*, LatticeVal
> &RV
=Solver
.getTrackedFunctionRetVals();
1662 for (DenseMap
<Function
*, LatticeVal
>::const_iterator I
= RV
.begin(),
1663 E
= RV
.end(); I
!= E
; ++I
)
1664 if (!I
->second
.isOverdefined() &&
1665 I
->first
->getReturnType() != Type::VoidTy
) {
1666 Function
*F
= I
->first
;
1667 for (Function::iterator BB
= F
->begin(), E
= F
->end(); BB
!= E
; ++BB
)
1668 if (ReturnInst
*RI
= dyn_cast
<ReturnInst
>(BB
->getTerminator()))
1669 if (!isa
<UndefValue
>(RI
->getOperand(0)))
1670 RI
->setOperand(0, UndefValue::get(F
->getReturnType()));
1673 // If we infered constant or undef values for globals variables, we can delete
1674 // the global and any stores that remain to it.
1675 const DenseMap
<GlobalVariable
*, LatticeVal
> &TG
= Solver
.getTrackedGlobals();
1676 for (DenseMap
<GlobalVariable
*, LatticeVal
>::const_iterator I
= TG
.begin(),
1677 E
= TG
.end(); I
!= E
; ++I
) {
1678 GlobalVariable
*GV
= I
->first
;
1679 assert(!I
->second
.isOverdefined() &&
1680 "Overdefined values should have been taken out of the map!");
1681 DOUT
<< "Found that GV '" << GV
->getName()<< "' is constant!\n";
1682 while (!GV
->use_empty()) {
1683 StoreInst
*SI
= cast
<StoreInst
>(GV
->use_back());
1684 SI
->eraseFromParent();
1686 M
.getGlobalList().erase(GV
);