1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements sparse conditional constant propagation and merging:
12 // Specifically, this:
13 // * Assumes values are constant unless proven otherwise
14 // * Assumes BasicBlocks are dead unless proven otherwise
15 // * Proves values to be constant, and replaces them with constants
16 // * Proves conditional branches to be unconditional
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "sccp"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Support/CallSite.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/InstVisitor.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/PointerIntPair.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/STLExtras.h"
47 STATISTIC(NumInstRemoved, "Number of instructions removed");
48 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
50 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
51 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
55 /// LatticeVal class - This class represents the different lattice values that
56 /// an LLVM value may occupy. It is a simple class with value semantics.
60 /// undefined - This LLVM Value has no known value yet.
63 /// constant - This LLVM Value has a specific constant value.
66 /// forcedconstant - This LLVM Value was thought to be undef until
67 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
68 /// with another (different) constant, it goes to overdefined, instead of
72 /// overdefined - This instruction is not known to be constant, and we know
77 /// Val: This stores the current lattice value along with the Constant* for
78 /// the constant if this is a 'constant' or 'forcedconstant' value.
79 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
81 LatticeValueTy getLatticeValue() const {
86 LatticeVal() : Val(0, undefined) {}
88 bool isUndefined() const { return getLatticeValue() == undefined; }
89 bool isConstant() const {
90 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
92 bool isOverdefined() const { return getLatticeValue() == overdefined; }
94 Constant *getConstant() const {
95 assert(isConstant() && "Cannot get the constant of a non-constant!");
96 return Val.getPointer();
99 /// markOverdefined - Return true if this is a change in status.
100 bool markOverdefined() {
104 Val.setInt(overdefined);
108 /// markConstant - Return true if this is a change in status.
109 bool markConstant(Constant *V) {
110 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
111 assert(getConstant() == V && "Marking constant with different value");
116 Val.setInt(constant);
117 assert(V && "Marking constant with NULL");
120 assert(getLatticeValue() == forcedconstant &&
121 "Cannot move from overdefined to constant!");
122 // Stay at forcedconstant if the constant is the same.
123 if (V == getConstant()) return false;
125 // Otherwise, we go to overdefined. Assumptions made based on the
126 // forced value are possibly wrong. Assuming this is another constant
127 // could expose a contradiction.
128 Val.setInt(overdefined);
133 /// getConstantInt - If this is a constant with a ConstantInt value, return it
134 /// otherwise return null.
135 ConstantInt *getConstantInt() const {
137 return dyn_cast<ConstantInt>(getConstant());
141 void markForcedConstant(Constant *V) {
142 assert(isUndefined() && "Can't force a defined value!");
143 Val.setInt(forcedconstant);
147 } // end anonymous namespace.
152 //===----------------------------------------------------------------------===//
154 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
155 /// Constant Propagation.
157 class SCCPSolver : public InstVisitor<SCCPSolver> {
158 const TargetData *TD;
159 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
160 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
162 /// StructValueState - This maintains ValueState for values that have
163 /// StructType, for example for formal arguments, calls, insertelement, etc.
165 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
167 /// GlobalValue - If we are tracking any values for the contents of a global
168 /// variable, we keep a mapping from the constant accessor to the element of
169 /// the global, to the currently known value. If the value becomes
170 /// overdefined, it's entry is simply removed from this map.
171 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
173 /// TrackedRetVals - If we are tracking arguments into and the return
174 /// value out of a function, it will have an entry in this map, indicating
175 /// what the known return value for the function is.
176 DenseMap<Function*, LatticeVal> TrackedRetVals;
178 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
179 /// that return multiple values.
180 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
182 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
183 /// represented here for efficient lookup.
184 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
186 /// TrackingIncomingArguments - This is the set of functions for whose
187 /// arguments we make optimistic assumptions about and try to prove as
189 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
191 /// The reason for two worklists is that overdefined is the lowest state
192 /// on the lattice, and moving things to overdefined as fast as possible
193 /// makes SCCP converge much faster.
195 /// By having a separate worklist, we accomplish this because everything
196 /// possibly overdefined will become overdefined at the soonest possible
198 SmallVector<Value*, 64> OverdefinedInstWorkList;
199 SmallVector<Value*, 64> InstWorkList;
202 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
204 /// KnownFeasibleEdges - Entries in this set are edges which have already had
205 /// PHI nodes retriggered.
206 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
207 DenseSet<Edge> KnownFeasibleEdges;
209 SCCPSolver(const TargetData *td) : TD(td) {}
211 /// MarkBlockExecutable - This method can be used by clients to mark all of
212 /// the blocks that are known to be intrinsically live in the processed unit.
214 /// This returns true if the block was not considered live before.
215 bool MarkBlockExecutable(BasicBlock *BB) {
216 if (!BBExecutable.insert(BB)) return false;
217 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
218 BBWorkList.push_back(BB); // Add the block to the work list!
222 /// TrackValueOfGlobalVariable - Clients can use this method to
223 /// inform the SCCPSolver that it should track loads and stores to the
224 /// specified global variable if it can. This is only legal to call if
225 /// performing Interprocedural SCCP.
226 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
227 // We only track the contents of scalar globals.
228 if (GV->getType()->getElementType()->isSingleValueType()) {
229 LatticeVal &IV = TrackedGlobals[GV];
230 if (!isa<UndefValue>(GV->getInitializer()))
231 IV.markConstant(GV->getInitializer());
235 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
236 /// and out of the specified function (which cannot have its address taken),
237 /// this method must be called.
238 void AddTrackedFunction(Function *F) {
239 // Add an entry, F -> undef.
240 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
241 MRVFunctionsTracked.insert(F);
242 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
243 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
246 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
249 void AddArgumentTrackedFunction(Function *F) {
250 TrackingIncomingArguments.insert(F);
253 /// Solve - Solve for constants and executable blocks.
257 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
258 /// that branches on undef values cannot reach any of their successors.
259 /// However, this is not a safe assumption. After we solve dataflow, this
260 /// method should be use to handle this. If this returns true, the solver
262 bool ResolvedUndefsIn(Function &F);
264 bool isBlockExecutable(BasicBlock *BB) const {
265 return BBExecutable.count(BB);
268 LatticeVal getLatticeValueFor(Value *V) const {
269 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
270 assert(I != ValueState.end() && "V is not in valuemap!");
274 /*LatticeVal getStructLatticeValueFor(Value *V, unsigned i) const {
275 DenseMap<std::pair<Value*, unsigned>, LatticeVal>::const_iterator I =
276 StructValueState.find(std::make_pair(V, i));
277 assert(I != StructValueState.end() && "V is not in valuemap!");
281 /// getTrackedRetVals - Get the inferred return value map.
283 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
284 return TrackedRetVals;
287 /// getTrackedGlobals - Get and return the set of inferred initializers for
288 /// global variables.
289 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
290 return TrackedGlobals;
293 void markOverdefined(Value *V) {
294 assert(!V->getType()->isStructTy() && "Should use other method");
295 markOverdefined(ValueState[V], V);
298 /// markAnythingOverdefined - Mark the specified value overdefined. This
299 /// works with both scalars and structs.
300 void markAnythingOverdefined(Value *V) {
301 if (StructType *STy = dyn_cast<StructType>(V->getType()))
302 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
303 markOverdefined(getStructValueState(V, i), V);
309 // markConstant - Make a value be marked as "constant". If the value
310 // is not already a constant, add it to the instruction work list so that
311 // the users of the instruction are updated later.
313 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
314 if (!IV.markConstant(C)) return;
315 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
316 if (IV.isOverdefined())
317 OverdefinedInstWorkList.push_back(V);
319 InstWorkList.push_back(V);
322 void markConstant(Value *V, Constant *C) {
323 assert(!V->getType()->isStructTy() && "Should use other method");
324 markConstant(ValueState[V], V, C);
327 void markForcedConstant(Value *V, Constant *C) {
328 assert(!V->getType()->isStructTy() && "Should use other method");
329 LatticeVal &IV = ValueState[V];
330 IV.markForcedConstant(C);
331 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
332 if (IV.isOverdefined())
333 OverdefinedInstWorkList.push_back(V);
335 InstWorkList.push_back(V);
339 // markOverdefined - Make a value be marked as "overdefined". If the
340 // value is not already overdefined, add it to the overdefined instruction
341 // work list so that the users of the instruction are updated later.
342 void markOverdefined(LatticeVal &IV, Value *V) {
343 if (!IV.markOverdefined()) return;
345 DEBUG(dbgs() << "markOverdefined: ";
346 if (Function *F = dyn_cast<Function>(V))
347 dbgs() << "Function '" << F->getName() << "'\n";
349 dbgs() << *V << '\n');
350 // Only instructions go on the work list
351 OverdefinedInstWorkList.push_back(V);
354 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
355 if (IV.isOverdefined() || MergeWithV.isUndefined())
357 if (MergeWithV.isOverdefined())
358 markOverdefined(IV, V);
359 else if (IV.isUndefined())
360 markConstant(IV, V, MergeWithV.getConstant());
361 else if (IV.getConstant() != MergeWithV.getConstant())
362 markOverdefined(IV, V);
365 void mergeInValue(Value *V, LatticeVal MergeWithV) {
366 assert(!V->getType()->isStructTy() && "Should use other method");
367 mergeInValue(ValueState[V], V, MergeWithV);
371 /// getValueState - Return the LatticeVal object that corresponds to the
372 /// value. This function handles the case when the value hasn't been seen yet
373 /// by properly seeding constants etc.
374 LatticeVal &getValueState(Value *V) {
375 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
377 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
378 ValueState.insert(std::make_pair(V, LatticeVal()));
379 LatticeVal &LV = I.first->second;
382 return LV; // Common case, already in the map.
384 if (Constant *C = dyn_cast<Constant>(V)) {
385 // Undef values remain undefined.
386 if (!isa<UndefValue>(V))
387 LV.markConstant(C); // Constants are constant
390 // All others are underdefined by default.
394 /// getStructValueState - Return the LatticeVal object that corresponds to the
395 /// value/field pair. This function handles the case when the value hasn't
396 /// been seen yet by properly seeding constants etc.
397 LatticeVal &getStructValueState(Value *V, unsigned i) {
398 assert(V->getType()->isStructTy() && "Should use getValueState");
399 assert(i < cast<StructType>(V->getType())->getNumElements() &&
400 "Invalid element #");
402 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
403 bool> I = StructValueState.insert(
404 std::make_pair(std::make_pair(V, i), LatticeVal()));
405 LatticeVal &LV = I.first->second;
408 return LV; // Common case, already in the map.
410 if (Constant *C = dyn_cast<Constant>(V)) {
411 if (isa<UndefValue>(C))
412 ; // Undef values remain undefined.
413 else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C))
414 LV.markConstant(CS->getOperand(i)); // Constants are constant.
415 else if (isa<ConstantAggregateZero>(C)) {
416 Type *FieldTy = cast<StructType>(V->getType())->getElementType(i);
417 LV.markConstant(Constant::getNullValue(FieldTy));
419 LV.markOverdefined(); // Unknown sort of constant.
422 // All others are underdefined by default.
427 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
428 /// work list if it is not already executable.
429 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
430 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
431 return; // This edge is already known to be executable!
433 if (!MarkBlockExecutable(Dest)) {
434 // If the destination is already executable, we just made an *edge*
435 // feasible that wasn't before. Revisit the PHI nodes in the block
436 // because they have potentially new operands.
437 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
438 << " -> " << Dest->getName() << "\n");
441 for (BasicBlock::iterator I = Dest->begin();
442 (PN = dyn_cast<PHINode>(I)); ++I)
447 // getFeasibleSuccessors - Return a vector of booleans to indicate which
448 // successors are reachable from a given terminator instruction.
450 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
452 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
453 // block to the 'To' basic block is currently feasible.
455 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
457 // OperandChangedState - This method is invoked on all of the users of an
458 // instruction that was just changed state somehow. Based on this
459 // information, we need to update the specified user of this instruction.
461 void OperandChangedState(Instruction *I) {
462 if (BBExecutable.count(I->getParent())) // Inst is executable?
467 friend class InstVisitor<SCCPSolver>;
469 // visit implementations - Something changed in this instruction. Either an
470 // operand made a transition, or the instruction is newly executable. Change
471 // the value type of I to reflect these changes if appropriate.
472 void visitPHINode(PHINode &I);
475 void visitReturnInst(ReturnInst &I);
476 void visitTerminatorInst(TerminatorInst &TI);
478 void visitCastInst(CastInst &I);
479 void visitSelectInst(SelectInst &I);
480 void visitBinaryOperator(Instruction &I);
481 void visitCmpInst(CmpInst &I);
482 void visitExtractElementInst(ExtractElementInst &I);
483 void visitInsertElementInst(InsertElementInst &I);
484 void visitShuffleVectorInst(ShuffleVectorInst &I);
485 void visitExtractValueInst(ExtractValueInst &EVI);
486 void visitInsertValueInst(InsertValueInst &IVI);
487 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
489 // Instructions that cannot be folded away.
490 void visitStoreInst (StoreInst &I);
491 void visitLoadInst (LoadInst &I);
492 void visitGetElementPtrInst(GetElementPtrInst &I);
493 void visitCallInst (CallInst &I) {
496 void visitInvokeInst (InvokeInst &II) {
498 visitTerminatorInst(II);
500 void visitCallSite (CallSite CS);
501 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
502 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
503 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
504 void visitFenceInst (FenceInst &I) { /*returns void*/ }
505 void visitAtomicCmpXchgInst (AtomicCmpXchgInst &I) { markOverdefined(&I); }
506 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
507 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
508 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
510 void visitInstruction(Instruction &I) {
511 // If a new instruction is added to LLVM that we don't handle.
512 dbgs() << "SCCP: Don't know how to handle: " << I;
513 markAnythingOverdefined(&I); // Just in case
517 } // end anonymous namespace
520 // getFeasibleSuccessors - Return a vector of booleans to indicate which
521 // successors are reachable from a given terminator instruction.
523 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
524 SmallVector<bool, 16> &Succs) {
525 Succs.resize(TI.getNumSuccessors());
526 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
527 if (BI->isUnconditional()) {
532 LatticeVal BCValue = getValueState(BI->getCondition());
533 ConstantInt *CI = BCValue.getConstantInt();
535 // Overdefined condition variables, and branches on unfoldable constant
536 // conditions, mean the branch could go either way.
537 if (!BCValue.isUndefined())
538 Succs[0] = Succs[1] = true;
542 // Constant condition variables mean the branch can only go a single way.
543 Succs[CI->isZero()] = true;
547 if (isa<InvokeInst>(TI)) {
548 // Invoke instructions successors are always executable.
549 Succs[0] = Succs[1] = true;
553 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
554 if (TI.getNumSuccessors() < 2) {
558 LatticeVal SCValue = getValueState(SI->getCondition());
559 ConstantInt *CI = SCValue.getConstantInt();
561 if (CI == 0) { // Overdefined or undefined condition?
562 // All destinations are executable!
563 if (!SCValue.isUndefined())
564 Succs.assign(TI.getNumSuccessors(), true);
568 Succs[SI->findCaseValue(CI)] = true;
572 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
573 if (isa<IndirectBrInst>(&TI)) {
574 // Just mark all destinations executable!
575 Succs.assign(TI.getNumSuccessors(), true);
580 dbgs() << "Unknown terminator instruction: " << TI << '\n';
582 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
586 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
587 // block to the 'To' basic block is currently feasible.
589 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
590 assert(BBExecutable.count(To) && "Dest should always be alive!");
592 // Make sure the source basic block is executable!!
593 if (!BBExecutable.count(From)) return false;
595 // Check to make sure this edge itself is actually feasible now.
596 TerminatorInst *TI = From->getTerminator();
597 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
598 if (BI->isUnconditional())
601 LatticeVal BCValue = getValueState(BI->getCondition());
603 // Overdefined condition variables mean the branch could go either way,
604 // undef conditions mean that neither edge is feasible yet.
605 ConstantInt *CI = BCValue.getConstantInt();
607 return !BCValue.isUndefined();
609 // Constant condition variables mean the branch can only go a single way.
610 return BI->getSuccessor(CI->isZero()) == To;
613 // Invoke instructions successors are always executable.
614 if (isa<InvokeInst>(TI))
617 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
618 if (SI->getNumSuccessors() < 2)
621 LatticeVal SCValue = getValueState(SI->getCondition());
622 ConstantInt *CI = SCValue.getConstantInt();
625 return !SCValue.isUndefined();
627 // Make sure to skip the "default value" which isn't a value
628 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
629 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
630 return SI->getSuccessor(i) == To;
632 // If the constant value is not equal to any of the branches, we must
633 // execute default branch.
634 return SI->getDefaultDest() == To;
637 // Just mark all destinations executable!
638 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
639 if (isa<IndirectBrInst>(TI))
643 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
648 // visit Implementations - Something changed in this instruction, either an
649 // operand made a transition, or the instruction is newly executable. Change
650 // the value type of I to reflect these changes if appropriate. This method
651 // makes sure to do the following actions:
653 // 1. If a phi node merges two constants in, and has conflicting value coming
654 // from different branches, or if the PHI node merges in an overdefined
655 // value, then the PHI node becomes overdefined.
656 // 2. If a phi node merges only constants in, and they all agree on value, the
657 // PHI node becomes a constant value equal to that.
658 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
659 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
660 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
661 // 6. If a conditional branch has a value that is constant, make the selected
662 // destination executable
663 // 7. If a conditional branch has a value that is overdefined, make all
664 // successors executable.
666 void SCCPSolver::visitPHINode(PHINode &PN) {
667 // If this PN returns a struct, just mark the result overdefined.
668 // TODO: We could do a lot better than this if code actually uses this.
669 if (PN.getType()->isStructTy())
670 return markAnythingOverdefined(&PN);
672 if (getValueState(&PN).isOverdefined())
673 return; // Quick exit
675 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
676 // and slow us down a lot. Just mark them overdefined.
677 if (PN.getNumIncomingValues() > 64)
678 return markOverdefined(&PN);
680 // Look at all of the executable operands of the PHI node. If any of them
681 // are overdefined, the PHI becomes overdefined as well. If they are all
682 // constant, and they agree with each other, the PHI becomes the identical
683 // constant. If they are constant and don't agree, the PHI is overdefined.
684 // If there are no executable operands, the PHI remains undefined.
686 Constant *OperandVal = 0;
687 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
688 LatticeVal IV = getValueState(PN.getIncomingValue(i));
689 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
691 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
694 if (IV.isOverdefined()) // PHI node becomes overdefined!
695 return markOverdefined(&PN);
697 if (OperandVal == 0) { // Grab the first value.
698 OperandVal = IV.getConstant();
702 // There is already a reachable operand. If we conflict with it,
703 // then the PHI node becomes overdefined. If we agree with it, we
706 // Check to see if there are two different constants merging, if so, the PHI
707 // node is overdefined.
708 if (IV.getConstant() != OperandVal)
709 return markOverdefined(&PN);
712 // If we exited the loop, this means that the PHI node only has constant
713 // arguments that agree with each other(and OperandVal is the constant) or
714 // OperandVal is null because there are no defined incoming arguments. If
715 // this is the case, the PHI remains undefined.
718 markConstant(&PN, OperandVal); // Acquire operand value
724 void SCCPSolver::visitReturnInst(ReturnInst &I) {
725 if (I.getNumOperands() == 0) return; // ret void
727 Function *F = I.getParent()->getParent();
728 Value *ResultOp = I.getOperand(0);
730 // If we are tracking the return value of this function, merge it in.
731 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
732 DenseMap<Function*, LatticeVal>::iterator TFRVI =
733 TrackedRetVals.find(F);
734 if (TFRVI != TrackedRetVals.end()) {
735 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
740 // Handle functions that return multiple values.
741 if (!TrackedMultipleRetVals.empty()) {
742 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
743 if (MRVFunctionsTracked.count(F))
744 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
745 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
746 getStructValueState(ResultOp, i));
751 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
752 SmallVector<bool, 16> SuccFeasible;
753 getFeasibleSuccessors(TI, SuccFeasible);
755 BasicBlock *BB = TI.getParent();
757 // Mark all feasible successors executable.
758 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
760 markEdgeExecutable(BB, TI.getSuccessor(i));
763 void SCCPSolver::visitCastInst(CastInst &I) {
764 LatticeVal OpSt = getValueState(I.getOperand(0));
765 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
767 else if (OpSt.isConstant()) // Propagate constant value
768 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
769 OpSt.getConstant(), I.getType()));
773 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
774 // If this returns a struct, mark all elements over defined, we don't track
775 // structs in structs.
776 if (EVI.getType()->isStructTy())
777 return markAnythingOverdefined(&EVI);
779 // If this is extracting from more than one level of struct, we don't know.
780 if (EVI.getNumIndices() != 1)
781 return markOverdefined(&EVI);
783 Value *AggVal = EVI.getAggregateOperand();
784 if (AggVal->getType()->isStructTy()) {
785 unsigned i = *EVI.idx_begin();
786 LatticeVal EltVal = getStructValueState(AggVal, i);
787 mergeInValue(getValueState(&EVI), &EVI, EltVal);
789 // Otherwise, must be extracting from an array.
790 return markOverdefined(&EVI);
794 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
795 StructType *STy = dyn_cast<StructType>(IVI.getType());
797 return markOverdefined(&IVI);
799 // If this has more than one index, we can't handle it, drive all results to
801 if (IVI.getNumIndices() != 1)
802 return markAnythingOverdefined(&IVI);
804 Value *Aggr = IVI.getAggregateOperand();
805 unsigned Idx = *IVI.idx_begin();
807 // Compute the result based on what we're inserting.
808 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
809 // This passes through all values that aren't the inserted element.
811 LatticeVal EltVal = getStructValueState(Aggr, i);
812 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
816 Value *Val = IVI.getInsertedValueOperand();
817 if (Val->getType()->isStructTy())
818 // We don't track structs in structs.
819 markOverdefined(getStructValueState(&IVI, i), &IVI);
821 LatticeVal InVal = getValueState(Val);
822 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
827 void SCCPSolver::visitSelectInst(SelectInst &I) {
828 // If this select returns a struct, just mark the result overdefined.
829 // TODO: We could do a lot better than this if code actually uses this.
830 if (I.getType()->isStructTy())
831 return markAnythingOverdefined(&I);
833 LatticeVal CondValue = getValueState(I.getCondition());
834 if (CondValue.isUndefined())
837 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
838 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
839 mergeInValue(&I, getValueState(OpVal));
843 // Otherwise, the condition is overdefined or a constant we can't evaluate.
844 // See if we can produce something better than overdefined based on the T/F
846 LatticeVal TVal = getValueState(I.getTrueValue());
847 LatticeVal FVal = getValueState(I.getFalseValue());
849 // select ?, C, C -> C.
850 if (TVal.isConstant() && FVal.isConstant() &&
851 TVal.getConstant() == FVal.getConstant())
852 return markConstant(&I, FVal.getConstant());
854 if (TVal.isUndefined()) // select ?, undef, X -> X.
855 return mergeInValue(&I, FVal);
856 if (FVal.isUndefined()) // select ?, X, undef -> X.
857 return mergeInValue(&I, TVal);
861 // Handle Binary Operators.
862 void SCCPSolver::visitBinaryOperator(Instruction &I) {
863 LatticeVal V1State = getValueState(I.getOperand(0));
864 LatticeVal V2State = getValueState(I.getOperand(1));
866 LatticeVal &IV = ValueState[&I];
867 if (IV.isOverdefined()) return;
869 if (V1State.isConstant() && V2State.isConstant())
870 return markConstant(IV, &I,
871 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
872 V2State.getConstant()));
874 // If something is undef, wait for it to resolve.
875 if (!V1State.isOverdefined() && !V2State.isOverdefined())
878 // Otherwise, one of our operands is overdefined. Try to produce something
879 // better than overdefined with some tricks.
881 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
882 // operand is overdefined.
883 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
884 LatticeVal *NonOverdefVal = 0;
885 if (!V1State.isOverdefined())
886 NonOverdefVal = &V1State;
887 else if (!V2State.isOverdefined())
888 NonOverdefVal = &V2State;
891 if (NonOverdefVal->isUndefined()) {
892 // Could annihilate value.
893 if (I.getOpcode() == Instruction::And)
894 markConstant(IV, &I, Constant::getNullValue(I.getType()));
895 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
896 markConstant(IV, &I, Constant::getAllOnesValue(PT));
899 Constant::getAllOnesValue(I.getType()));
903 if (I.getOpcode() == Instruction::And) {
905 if (NonOverdefVal->getConstant()->isNullValue())
906 return markConstant(IV, &I, NonOverdefVal->getConstant());
908 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
909 if (CI->isAllOnesValue()) // X or -1 = -1
910 return markConstant(IV, &I, NonOverdefVal->getConstant());
919 // Handle ICmpInst instruction.
920 void SCCPSolver::visitCmpInst(CmpInst &I) {
921 LatticeVal V1State = getValueState(I.getOperand(0));
922 LatticeVal V2State = getValueState(I.getOperand(1));
924 LatticeVal &IV = ValueState[&I];
925 if (IV.isOverdefined()) return;
927 if (V1State.isConstant() && V2State.isConstant())
928 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
929 V1State.getConstant(),
930 V2State.getConstant()));
932 // If operands are still undefined, wait for it to resolve.
933 if (!V1State.isOverdefined() && !V2State.isOverdefined())
939 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
940 // TODO : SCCP does not handle vectors properly.
941 return markOverdefined(&I);
944 LatticeVal &ValState = getValueState(I.getOperand(0));
945 LatticeVal &IdxState = getValueState(I.getOperand(1));
947 if (ValState.isOverdefined() || IdxState.isOverdefined())
949 else if(ValState.isConstant() && IdxState.isConstant())
950 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
951 IdxState.getConstant()));
955 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
956 // TODO : SCCP does not handle vectors properly.
957 return markOverdefined(&I);
959 LatticeVal &ValState = getValueState(I.getOperand(0));
960 LatticeVal &EltState = getValueState(I.getOperand(1));
961 LatticeVal &IdxState = getValueState(I.getOperand(2));
963 if (ValState.isOverdefined() || EltState.isOverdefined() ||
964 IdxState.isOverdefined())
966 else if(ValState.isConstant() && EltState.isConstant() &&
967 IdxState.isConstant())
968 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
969 EltState.getConstant(),
970 IdxState.getConstant()));
971 else if (ValState.isUndefined() && EltState.isConstant() &&
972 IdxState.isConstant())
973 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
974 EltState.getConstant(),
975 IdxState.getConstant()));
979 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
980 // TODO : SCCP does not handle vectors properly.
981 return markOverdefined(&I);
983 LatticeVal &V1State = getValueState(I.getOperand(0));
984 LatticeVal &V2State = getValueState(I.getOperand(1));
985 LatticeVal &MaskState = getValueState(I.getOperand(2));
987 if (MaskState.isUndefined() ||
988 (V1State.isUndefined() && V2State.isUndefined()))
989 return; // Undefined output if mask or both inputs undefined.
991 if (V1State.isOverdefined() || V2State.isOverdefined() ||
992 MaskState.isOverdefined()) {
995 // A mix of constant/undef inputs.
996 Constant *V1 = V1State.isConstant() ?
997 V1State.getConstant() : UndefValue::get(I.getType());
998 Constant *V2 = V2State.isConstant() ?
999 V2State.getConstant() : UndefValue::get(I.getType());
1000 Constant *Mask = MaskState.isConstant() ?
1001 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1002 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1007 // Handle getelementptr instructions. If all operands are constants then we
1008 // can turn this into a getelementptr ConstantExpr.
1010 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1011 if (ValueState[&I].isOverdefined()) return;
1013 SmallVector<Constant*, 8> Operands;
1014 Operands.reserve(I.getNumOperands());
1016 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1017 LatticeVal State = getValueState(I.getOperand(i));
1018 if (State.isUndefined())
1019 return; // Operands are not resolved yet.
1021 if (State.isOverdefined())
1022 return markOverdefined(&I);
1024 assert(State.isConstant() && "Unknown state!");
1025 Operands.push_back(State.getConstant());
1028 Constant *Ptr = Operands[0];
1029 ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
1030 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
1033 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1034 // If this store is of a struct, ignore it.
1035 if (SI.getOperand(0)->getType()->isStructTy())
1038 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1041 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1042 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1043 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1045 // Get the value we are storing into the global, then merge it.
1046 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1047 if (I->second.isOverdefined())
1048 TrackedGlobals.erase(I); // No need to keep tracking this!
1052 // Handle load instructions. If the operand is a constant pointer to a constant
1053 // global, we can replace the load with the loaded constant value!
1054 void SCCPSolver::visitLoadInst(LoadInst &I) {
1055 // If this load is of a struct, just mark the result overdefined.
1056 if (I.getType()->isStructTy())
1057 return markAnythingOverdefined(&I);
1059 LatticeVal PtrVal = getValueState(I.getOperand(0));
1060 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1062 LatticeVal &IV = ValueState[&I];
1063 if (IV.isOverdefined()) return;
1065 if (!PtrVal.isConstant() || I.isVolatile())
1066 return markOverdefined(IV, &I);
1068 Constant *Ptr = PtrVal.getConstant();
1070 // load null -> null
1071 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1072 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1074 // Transform load (constant global) into the value loaded.
1075 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1076 if (!TrackedGlobals.empty()) {
1077 // If we are tracking this global, merge in the known value for it.
1078 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1079 TrackedGlobals.find(GV);
1080 if (It != TrackedGlobals.end()) {
1081 mergeInValue(IV, &I, It->second);
1087 // Transform load from a constant into a constant if possible.
1088 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1089 return markConstant(IV, &I, C);
1091 // Otherwise we cannot say for certain what value this load will produce.
1093 markOverdefined(IV, &I);
1096 void SCCPSolver::visitCallSite(CallSite CS) {
1097 Function *F = CS.getCalledFunction();
1098 Instruction *I = CS.getInstruction();
1100 // The common case is that we aren't tracking the callee, either because we
1101 // are not doing interprocedural analysis or the callee is indirect, or is
1102 // external. Handle these cases first.
1103 if (F == 0 || F->isDeclaration()) {
1105 // Void return and not tracking callee, just bail.
1106 if (I->getType()->isVoidTy()) return;
1108 // Otherwise, if we have a single return value case, and if the function is
1109 // a declaration, maybe we can constant fold it.
1110 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1111 canConstantFoldCallTo(F)) {
1113 SmallVector<Constant*, 8> Operands;
1114 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1116 LatticeVal State = getValueState(*AI);
1118 if (State.isUndefined())
1119 return; // Operands are not resolved yet.
1120 if (State.isOverdefined())
1121 return markOverdefined(I);
1122 assert(State.isConstant() && "Unknown state!");
1123 Operands.push_back(State.getConstant());
1126 // If we can constant fold this, mark the result of the call as a
1128 if (Constant *C = ConstantFoldCall(F, Operands))
1129 return markConstant(I, C);
1132 // Otherwise, we don't know anything about this call, mark it overdefined.
1133 return markAnythingOverdefined(I);
1136 // If this is a local function that doesn't have its address taken, mark its
1137 // entry block executable and merge in the actual arguments to the call into
1138 // the formal arguments of the function.
1139 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1140 MarkBlockExecutable(F->begin());
1142 // Propagate information from this call site into the callee.
1143 CallSite::arg_iterator CAI = CS.arg_begin();
1144 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1145 AI != E; ++AI, ++CAI) {
1146 // If this argument is byval, and if the function is not readonly, there
1147 // will be an implicit copy formed of the input aggregate.
1148 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1149 markOverdefined(AI);
1153 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
1154 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1155 LatticeVal CallArg = getStructValueState(*CAI, i);
1156 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1159 mergeInValue(AI, getValueState(*CAI));
1164 // If this is a single/zero retval case, see if we're tracking the function.
1165 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
1166 if (!MRVFunctionsTracked.count(F))
1167 goto CallOverdefined; // Not tracking this callee.
1169 // If we are tracking this callee, propagate the result of the function
1170 // into this call site.
1171 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1172 mergeInValue(getStructValueState(I, i), I,
1173 TrackedMultipleRetVals[std::make_pair(F, i)]);
1175 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1176 if (TFRVI == TrackedRetVals.end())
1177 goto CallOverdefined; // Not tracking this callee.
1179 // If so, propagate the return value of the callee into this call result.
1180 mergeInValue(I, TFRVI->second);
1184 void SCCPSolver::Solve() {
1185 // Process the work lists until they are empty!
1186 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1187 !OverdefinedInstWorkList.empty()) {
1188 // Process the overdefined instruction's work list first, which drives other
1189 // things to overdefined more quickly.
1190 while (!OverdefinedInstWorkList.empty()) {
1191 Value *I = OverdefinedInstWorkList.pop_back_val();
1193 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1195 // "I" got into the work list because it either made the transition from
1196 // bottom to constant
1198 // Anything on this worklist that is overdefined need not be visited
1199 // since all of its users will have already been marked as overdefined
1200 // Update all of the users of this instruction's value.
1202 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1204 if (Instruction *I = dyn_cast<Instruction>(*UI))
1205 OperandChangedState(I);
1208 // Process the instruction work list.
1209 while (!InstWorkList.empty()) {
1210 Value *I = InstWorkList.pop_back_val();
1212 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1214 // "I" got into the work list because it made the transition from undef to
1217 // Anything on this worklist that is overdefined need not be visited
1218 // since all of its users will have already been marked as overdefined.
1219 // Update all of the users of this instruction's value.
1221 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1222 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1224 if (Instruction *I = dyn_cast<Instruction>(*UI))
1225 OperandChangedState(I);
1228 // Process the basic block work list.
1229 while (!BBWorkList.empty()) {
1230 BasicBlock *BB = BBWorkList.back();
1231 BBWorkList.pop_back();
1233 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1235 // Notify all instructions in this basic block that they are newly
1242 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1243 /// that branches on undef values cannot reach any of their successors.
1244 /// However, this is not a safe assumption. After we solve dataflow, this
1245 /// method should be use to handle this. If this returns true, the solver
1246 /// should be rerun.
1248 /// This method handles this by finding an unresolved branch and marking it one
1249 /// of the edges from the block as being feasible, even though the condition
1250 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1251 /// CFG and only slightly pessimizes the analysis results (by marking one,
1252 /// potentially infeasible, edge feasible). This cannot usefully modify the
1253 /// constraints on the condition of the branch, as that would impact other users
1256 /// This scan also checks for values that use undefs, whose results are actually
1257 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1258 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1259 /// even if X isn't defined.
1260 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1261 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1262 if (!BBExecutable.count(BB))
1265 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1266 // Look for instructions which produce undef values.
1267 if (I->getType()->isVoidTy()) continue;
1269 if (StructType *STy = dyn_cast<StructType>(I->getType())) {
1270 // Only a few things that can be structs matter for undef.
1272 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1273 if (CallSite CS = CallSite(I))
1274 if (Function *F = CS.getCalledFunction())
1275 if (MRVFunctionsTracked.count(F))
1278 // extractvalue and insertvalue don't need to be marked; they are
1279 // tracked as precisely as their operands.
1280 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1283 // Send the results of everything else to overdefined. We could be
1284 // more precise than this but it isn't worth bothering.
1285 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1286 LatticeVal &LV = getStructValueState(I, i);
1287 if (LV.isUndefined())
1288 markOverdefined(LV, I);
1293 LatticeVal &LV = getValueState(I);
1294 if (!LV.isUndefined()) continue;
1296 // extractvalue is safe; check here because the argument is a struct.
1297 if (isa<ExtractValueInst>(I))
1300 // Compute the operand LatticeVals, for convenience below.
1301 // Anything taking a struct is conservatively assumed to require
1302 // overdefined markings.
1303 if (I->getOperand(0)->getType()->isStructTy()) {
1307 LatticeVal Op0LV = getValueState(I->getOperand(0));
1309 if (I->getNumOperands() == 2) {
1310 if (I->getOperand(1)->getType()->isStructTy()) {
1315 Op1LV = getValueState(I->getOperand(1));
1317 // If this is an instructions whose result is defined even if the input is
1318 // not fully defined, propagate the information.
1319 Type *ITy = I->getType();
1320 switch (I->getOpcode()) {
1321 case Instruction::Add:
1322 case Instruction::Sub:
1323 case Instruction::Trunc:
1324 case Instruction::FPTrunc:
1325 case Instruction::BitCast:
1326 break; // Any undef -> undef
1327 case Instruction::FSub:
1328 case Instruction::FAdd:
1329 case Instruction::FMul:
1330 case Instruction::FDiv:
1331 case Instruction::FRem:
1332 // Floating-point binary operation: be conservative.
1333 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1334 markForcedConstant(I, Constant::getNullValue(ITy));
1338 case Instruction::ZExt:
1339 case Instruction::SExt:
1340 case Instruction::FPToUI:
1341 case Instruction::FPToSI:
1342 case Instruction::FPExt:
1343 case Instruction::PtrToInt:
1344 case Instruction::IntToPtr:
1345 case Instruction::SIToFP:
1346 case Instruction::UIToFP:
1347 // undef -> 0; some outputs are impossible
1348 markForcedConstant(I, Constant::getNullValue(ITy));
1350 case Instruction::Mul:
1351 case Instruction::And:
1352 // Both operands undef -> undef
1353 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1355 // undef * X -> 0. X could be zero.
1356 // undef & X -> 0. X could be zero.
1357 markForcedConstant(I, Constant::getNullValue(ITy));
1360 case Instruction::Or:
1361 // Both operands undef -> undef
1362 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1364 // undef | X -> -1. X could be -1.
1365 markForcedConstant(I, Constant::getAllOnesValue(ITy));
1368 case Instruction::Xor:
1369 // undef ^ undef -> 0; strictly speaking, this is not strictly
1370 // necessary, but we try to be nice to people who expect this
1371 // behavior in simple cases
1372 if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
1373 markForcedConstant(I, Constant::getNullValue(ITy));
1376 // undef ^ X -> undef
1379 case Instruction::SDiv:
1380 case Instruction::UDiv:
1381 case Instruction::SRem:
1382 case Instruction::URem:
1383 // X / undef -> undef. No change.
1384 // X % undef -> undef. No change.
1385 if (Op1LV.isUndefined()) break;
1387 // undef / X -> 0. X could be maxint.
1388 // undef % X -> 0. X could be 1.
1389 markForcedConstant(I, Constant::getNullValue(ITy));
1392 case Instruction::AShr:
1393 // X >>a undef -> undef.
1394 if (Op1LV.isUndefined()) break;
1396 // undef >>a X -> all ones
1397 markForcedConstant(I, Constant::getAllOnesValue(ITy));
1399 case Instruction::LShr:
1400 case Instruction::Shl:
1401 // X << undef -> undef.
1402 // X >> undef -> undef.
1403 if (Op1LV.isUndefined()) break;
1407 markForcedConstant(I, Constant::getNullValue(ITy));
1409 case Instruction::Select:
1410 Op1LV = getValueState(I->getOperand(1));
1411 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1412 if (Op0LV.isUndefined()) {
1413 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1414 Op1LV = getValueState(I->getOperand(2));
1415 } else if (Op1LV.isUndefined()) {
1416 // c ? undef : undef -> undef. No change.
1417 Op1LV = getValueState(I->getOperand(2));
1418 if (Op1LV.isUndefined())
1420 // Otherwise, c ? undef : x -> x.
1422 // Leave Op1LV as Operand(1)'s LatticeValue.
1425 if (Op1LV.isConstant())
1426 markForcedConstant(I, Op1LV.getConstant());
1430 case Instruction::Load:
1431 // A load here means one of two things: a load of undef from a global,
1432 // a load from an unknown pointer. Either way, having it return undef
1435 case Instruction::ICmp:
1436 // X == undef -> undef. Other comparisons get more complicated.
1437 if (cast<ICmpInst>(I)->isEquality())
1441 case Instruction::Call:
1442 case Instruction::Invoke: {
1443 // There are two reasons a call can have an undef result
1444 // 1. It could be tracked.
1445 // 2. It could be constant-foldable.
1446 // Because of the way we solve return values, tracked calls must
1447 // never be marked overdefined in ResolvedUndefsIn.
1448 if (Function *F = CallSite(I).getCalledFunction())
1449 if (TrackedRetVals.count(F))
1452 // If the call is constant-foldable, we mark it overdefined because
1453 // we do not know what return values are valid.
1458 // If we don't know what should happen here, conservatively mark it
1465 // Check to see if we have a branch or switch on an undefined value. If so
1466 // we force the branch to go one way or the other to make the successor
1467 // values live. It doesn't really matter which way we force it.
1468 TerminatorInst *TI = BB->getTerminator();
1469 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1470 if (!BI->isConditional()) continue;
1471 if (!getValueState(BI->getCondition()).isUndefined())
1474 // If the input to SCCP is actually branch on undef, fix the undef to
1476 if (isa<UndefValue>(BI->getCondition())) {
1477 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1478 markEdgeExecutable(BB, TI->getSuccessor(1));
1482 // Otherwise, it is a branch on a symbolic value which is currently
1483 // considered to be undef. Handle this by forcing the input value to the
1485 markForcedConstant(BI->getCondition(),
1486 ConstantInt::getFalse(TI->getContext()));
1490 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1491 if (SI->getNumSuccessors() < 2) // no cases
1493 if (!getValueState(SI->getCondition()).isUndefined())
1496 // If the input to SCCP is actually switch on undef, fix the undef to
1497 // the first constant.
1498 if (isa<UndefValue>(SI->getCondition())) {
1499 SI->setCondition(SI->getCaseValue(1));
1500 markEdgeExecutable(BB, TI->getSuccessor(1));
1504 markForcedConstant(SI->getCondition(), SI->getCaseValue(1));
1514 //===--------------------------------------------------------------------===//
1516 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1517 /// Sparse Conditional Constant Propagator.
1519 struct SCCP : public FunctionPass {
1520 static char ID; // Pass identification, replacement for typeid
1521 SCCP() : FunctionPass(ID) {
1522 initializeSCCPPass(*PassRegistry::getPassRegistry());
1525 // runOnFunction - Run the Sparse Conditional Constant Propagation
1526 // algorithm, and return true if the function was modified.
1528 bool runOnFunction(Function &F);
1530 } // end anonymous namespace
1533 INITIALIZE_PASS(SCCP, "sccp",
1534 "Sparse Conditional Constant Propagation", false, false)
1536 // createSCCPPass - This is the public interface to this file.
1537 FunctionPass *llvm::createSCCPPass() {
1541 static void DeleteInstructionInBlock(BasicBlock *BB) {
1542 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1545 // Check to see if there are non-terminating instructions to delete.
1546 if (isa<TerminatorInst>(BB->begin()))
1549 // Delete the instructions backwards, as it has a reduced likelihood of having
1550 // to update as many def-use and use-def chains.
1551 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1552 while (EndInst != BB->begin()) {
1553 // Delete the next to last instruction.
1554 BasicBlock::iterator I = EndInst;
1555 Instruction *Inst = --I;
1556 if (!Inst->use_empty())
1557 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1558 if (isa<LandingPadInst>(Inst)) {
1562 BB->getInstList().erase(Inst);
1567 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1568 // and return true if the function was modified.
1570 bool SCCP::runOnFunction(Function &F) {
1571 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1572 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
1574 // Mark the first block of the function as being executable.
1575 Solver.MarkBlockExecutable(F.begin());
1577 // Mark all arguments to the function as being overdefined.
1578 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1579 Solver.markAnythingOverdefined(AI);
1581 // Solve for constants.
1582 bool ResolvedUndefs = true;
1583 while (ResolvedUndefs) {
1585 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1586 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1589 bool MadeChanges = false;
1591 // If we decided that there are basic blocks that are dead in this function,
1592 // delete their contents now. Note that we cannot actually delete the blocks,
1593 // as we cannot modify the CFG of the function.
1595 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1596 if (!Solver.isBlockExecutable(BB)) {
1597 DeleteInstructionInBlock(BB);
1602 // Iterate over all of the instructions in a function, replacing them with
1603 // constants if we have found them to be of constant values.
1605 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1606 Instruction *Inst = BI++;
1607 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1610 // TODO: Reconstruct structs from their elements.
1611 if (Inst->getType()->isStructTy())
1614 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1615 if (IV.isOverdefined())
1618 Constant *Const = IV.isConstant()
1619 ? IV.getConstant() : UndefValue::get(Inst->getType());
1620 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
1622 // Replaces all of the uses of a variable with uses of the constant.
1623 Inst->replaceAllUsesWith(Const);
1625 // Delete the instruction.
1626 Inst->eraseFromParent();
1628 // Hey, we just changed something!
1638 //===--------------------------------------------------------------------===//
1640 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1641 /// Constant Propagation.
1643 struct IPSCCP : public ModulePass {
1645 IPSCCP() : ModulePass(ID) {
1646 initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1648 bool runOnModule(Module &M);
1650 } // end anonymous namespace
1652 char IPSCCP::ID = 0;
1653 INITIALIZE_PASS(IPSCCP, "ipsccp",
1654 "Interprocedural Sparse Conditional Constant Propagation",
1657 // createIPSCCPPass - This is the public interface to this file.
1658 ModulePass *llvm::createIPSCCPPass() {
1659 return new IPSCCP();
1663 static bool AddressIsTaken(const GlobalValue *GV) {
1664 // Delete any dead constantexpr klingons.
1665 GV->removeDeadConstantUsers();
1667 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1669 const User *U = *UI;
1670 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
1671 if (SI->getOperand(0) == GV || SI->isVolatile())
1672 return true; // Storing addr of GV.
1673 } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
1674 // Make sure we are calling the function, not passing the address.
1675 ImmutableCallSite CS(cast<Instruction>(U));
1676 if (!CS.isCallee(UI))
1678 } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
1679 if (LI->isVolatile())
1681 } else if (isa<BlockAddress>(U)) {
1682 // blockaddress doesn't take the address of the function, it takes addr
1691 bool IPSCCP::runOnModule(Module &M) {
1692 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
1694 // AddressTakenFunctions - This set keeps track of the address-taken functions
1695 // that are in the input. As IPSCCP runs through and simplifies code,
1696 // functions that were address taken can end up losing their
1697 // address-taken-ness. Because of this, we keep track of their addresses from
1698 // the first pass so we can use them for the later simplification pass.
1699 SmallPtrSet<Function*, 32> AddressTakenFunctions;
1701 // Loop over all functions, marking arguments to those with their addresses
1702 // taken or that are external as overdefined.
1704 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1705 if (F->isDeclaration())
1708 // If this is a strong or ODR definition of this function, then we can
1709 // propagate information about its result into callsites of it.
1710 if (!F->mayBeOverridden())
1711 Solver.AddTrackedFunction(F);
1713 // If this function only has direct calls that we can see, we can track its
1714 // arguments and return value aggressively, and can assume it is not called
1715 // unless we see evidence to the contrary.
1716 if (F->hasLocalLinkage()) {
1717 if (AddressIsTaken(F))
1718 AddressTakenFunctions.insert(F);
1720 Solver.AddArgumentTrackedFunction(F);
1725 // Assume the function is called.
1726 Solver.MarkBlockExecutable(F->begin());
1728 // Assume nothing about the incoming arguments.
1729 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1731 Solver.markAnythingOverdefined(AI);
1734 // Loop over global variables. We inform the solver about any internal global
1735 // variables that do not have their 'addresses taken'. If they don't have
1736 // their addresses taken, we can propagate constants through them.
1737 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1739 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
1740 Solver.TrackValueOfGlobalVariable(G);
1742 // Solve for constants.
1743 bool ResolvedUndefs = true;
1744 while (ResolvedUndefs) {
1747 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1748 ResolvedUndefs = false;
1749 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1750 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1753 bool MadeChanges = false;
1755 // Iterate over all of the instructions in the module, replacing them with
1756 // constants if we have found them to be of constant values.
1758 SmallVector<BasicBlock*, 512> BlocksToErase;
1760 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1761 if (Solver.isBlockExecutable(F->begin())) {
1762 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1764 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
1766 // TODO: Could use getStructLatticeValueFor to find out if the entire
1767 // result is a constant and replace it entirely if so.
1769 LatticeVal IV = Solver.getLatticeValueFor(AI);
1770 if (IV.isOverdefined()) continue;
1772 Constant *CST = IV.isConstant() ?
1773 IV.getConstant() : UndefValue::get(AI->getType());
1774 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1776 // Replaces all of the uses of a variable with uses of the
1778 AI->replaceAllUsesWith(CST);
1783 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
1784 if (!Solver.isBlockExecutable(BB)) {
1785 DeleteInstructionInBlock(BB);
1788 TerminatorInst *TI = BB->getTerminator();
1789 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1790 BasicBlock *Succ = TI->getSuccessor(i);
1791 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1792 TI->getSuccessor(i)->removePredecessor(BB);
1794 if (!TI->use_empty())
1795 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1796 TI->eraseFromParent();
1798 if (&*BB != &F->front())
1799 BlocksToErase.push_back(BB);
1801 new UnreachableInst(M.getContext(), BB);
1805 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1806 Instruction *Inst = BI++;
1807 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
1810 // TODO: Could use getStructLatticeValueFor to find out if the entire
1811 // result is a constant and replace it entirely if so.
1813 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1814 if (IV.isOverdefined())
1817 Constant *Const = IV.isConstant()
1818 ? IV.getConstant() : UndefValue::get(Inst->getType());
1819 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
1821 // Replaces all of the uses of a variable with uses of the
1823 Inst->replaceAllUsesWith(Const);
1825 // Delete the instruction.
1826 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1827 Inst->eraseFromParent();
1829 // Hey, we just changed something!
1835 // Now that all instructions in the function are constant folded, erase dead
1836 // blocks, because we can now use ConstantFoldTerminator to get rid of
1838 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1839 // If there are any PHI nodes in this successor, drop entries for BB now.
1840 BasicBlock *DeadBB = BlocksToErase[i];
1841 for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1843 // Grab the user and then increment the iterator early, as the user
1844 // will be deleted. Step past all adjacent uses from the same user.
1845 Instruction *I = dyn_cast<Instruction>(*UI);
1846 do { ++UI; } while (UI != UE && *UI == I);
1848 // Ignore blockaddress users; BasicBlock's dtor will handle them.
1851 bool Folded = ConstantFoldTerminator(I->getParent());
1853 // The constant folder may not have been able to fold the terminator
1854 // if this is a branch or switch on undef. Fold it manually as a
1855 // branch to the first successor.
1857 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1858 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1859 "Branch should be foldable!");
1860 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1861 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1863 llvm_unreachable("Didn't fold away reference to block!");
1867 // Make this an uncond branch to the first successor.
1868 TerminatorInst *TI = I->getParent()->getTerminator();
1869 BranchInst::Create(TI->getSuccessor(0), TI);
1871 // Remove entries in successor phi nodes to remove edges.
1872 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1873 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1875 // Remove the old terminator.
1876 TI->eraseFromParent();
1880 // Finally, delete the basic block.
1881 F->getBasicBlockList().erase(DeadBB);
1883 BlocksToErase.clear();
1886 // If we inferred constant or undef return values for a function, we replaced
1887 // all call uses with the inferred value. This means we don't need to bother
1888 // actually returning anything from the function. Replace all return
1889 // instructions with return undef.
1891 // Do this in two stages: first identify the functions we should process, then
1892 // actually zap their returns. This is important because we can only do this
1893 // if the address of the function isn't taken. In cases where a return is the
1894 // last use of a function, the order of processing functions would affect
1895 // whether other functions are optimizable.
1896 SmallVector<ReturnInst*, 8> ReturnsToZap;
1898 // TODO: Process multiple value ret instructions also.
1899 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1900 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1901 E = RV.end(); I != E; ++I) {
1902 Function *F = I->first;
1903 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1906 // We can only do this if we know that nothing else can call the function.
1907 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
1910 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1911 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1912 if (!isa<UndefValue>(RI->getOperand(0)))
1913 ReturnsToZap.push_back(RI);
1916 // Zap all returns which we've identified as zap to change.
1917 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1918 Function *F = ReturnsToZap[i]->getParent()->getParent();
1919 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1922 // If we inferred constant or undef values for globals variables, we can delete
1923 // the global and any stores that remain to it.
1924 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1925 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1926 E = TG.end(); I != E; ++I) {
1927 GlobalVariable *GV = I->first;
1928 assert(!I->second.isOverdefined() &&
1929 "Overdefined values should have been taken out of the map!");
1930 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1931 while (!GV->use_empty()) {
1932 StoreInst *SI = cast<StoreInst>(GV->use_back());
1933 SI->eraseFromParent();
1935 M.getGlobalList().erase(GV);