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 #include "llvm/Transforms/IPO/SCCP.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/PointerIntPair.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/Analysis/GlobalsModRef.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/InstVisitor.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/IPO.h"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/Transforms/Scalar/SCCP.h"
43 #include "llvm/Transforms/Utils/Local.h"
47 #define DEBUG_TYPE "sccp"
49 STATISTIC(NumInstRemoved, "Number of instructions removed");
50 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
52 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
53 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
54 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
57 /// LatticeVal class - This class represents the different lattice values that
58 /// an LLVM value may occupy. It is a simple class with value semantics.
62 /// unknown - This LLVM Value has no known value yet.
65 /// constant - This LLVM Value has a specific constant value.
68 /// forcedconstant - This LLVM Value was thought to be undef until
69 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
70 /// with another (different) constant, it goes to overdefined, instead of
74 /// overdefined - This instruction is not known to be constant, and we know
79 /// Val: This stores the current lattice value along with the Constant* for
80 /// the constant if this is a 'constant' or 'forcedconstant' value.
81 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
83 LatticeValueTy getLatticeValue() const {
88 LatticeVal() : Val(nullptr, unknown) {}
90 bool isUnknown() const { return getLatticeValue() == unknown; }
91 bool isConstant() const {
92 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
94 bool isOverdefined() const { return getLatticeValue() == overdefined; }
96 Constant *getConstant() const {
97 assert(isConstant() && "Cannot get the constant of a non-constant!");
98 return Val.getPointer();
101 /// markOverdefined - Return true if this is a change in status.
102 bool markOverdefined() {
106 Val.setInt(overdefined);
110 /// markConstant - Return true if this is a change in status.
111 bool markConstant(Constant *V) {
112 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
113 assert(getConstant() == V && "Marking constant with different value");
118 Val.setInt(constant);
119 assert(V && "Marking constant with NULL");
122 assert(getLatticeValue() == forcedconstant &&
123 "Cannot move from overdefined to constant!");
124 // Stay at forcedconstant if the constant is the same.
125 if (V == getConstant()) return false;
127 // Otherwise, we go to overdefined. Assumptions made based on the
128 // forced value are possibly wrong. Assuming this is another constant
129 // could expose a contradiction.
130 Val.setInt(overdefined);
135 /// getConstantInt - If this is a constant with a ConstantInt value, return it
136 /// otherwise return null.
137 ConstantInt *getConstantInt() const {
139 return dyn_cast<ConstantInt>(getConstant());
143 void markForcedConstant(Constant *V) {
144 assert(isUnknown() && "Can't force a defined value!");
145 Val.setInt(forcedconstant);
149 } // end anonymous namespace.
154 //===----------------------------------------------------------------------===//
156 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
157 /// Constant Propagation.
159 class SCCPSolver : public InstVisitor<SCCPSolver> {
160 const DataLayout &DL;
161 const TargetLibraryInfo *TLI;
162 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
163 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
165 /// StructValueState - This maintains ValueState for values that have
166 /// StructType, for example for formal arguments, calls, insertelement, etc.
168 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
170 /// GlobalValue - If we are tracking any values for the contents of a global
171 /// variable, we keep a mapping from the constant accessor to the element of
172 /// the global, to the currently known value. If the value becomes
173 /// overdefined, it's entry is simply removed from this map.
174 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
176 /// TrackedRetVals - If we are tracking arguments into and the return
177 /// value out of a function, it will have an entry in this map, indicating
178 /// what the known return value for the function is.
179 DenseMap<Function*, LatticeVal> TrackedRetVals;
181 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
182 /// that return multiple values.
183 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
185 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
186 /// represented here for efficient lookup.
187 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
189 /// TrackingIncomingArguments - This is the set of functions for whose
190 /// arguments we make optimistic assumptions about and try to prove as
192 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
194 /// The reason for two worklists is that overdefined is the lowest state
195 /// on the lattice, and moving things to overdefined as fast as possible
196 /// makes SCCP converge much faster.
198 /// By having a separate worklist, we accomplish this because everything
199 /// possibly overdefined will become overdefined at the soonest possible
201 SmallVector<Value*, 64> OverdefinedInstWorkList;
202 SmallVector<Value*, 64> InstWorkList;
205 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
207 /// KnownFeasibleEdges - Entries in this set are edges which have already had
208 /// PHI nodes retriggered.
209 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
210 DenseSet<Edge> KnownFeasibleEdges;
212 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
213 : DL(DL), TLI(tli) {}
215 /// MarkBlockExecutable - This method can be used by clients to mark all of
216 /// the blocks that are known to be intrinsically live in the processed unit.
218 /// This returns true if the block was not considered live before.
219 bool MarkBlockExecutable(BasicBlock *BB) {
220 if (!BBExecutable.insert(BB).second)
222 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
223 BBWorkList.push_back(BB); // Add the block to the work list!
227 /// TrackValueOfGlobalVariable - Clients can use this method to
228 /// inform the SCCPSolver that it should track loads and stores to the
229 /// specified global variable if it can. This is only legal to call if
230 /// performing Interprocedural SCCP.
231 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
232 // We only track the contents of scalar globals.
233 if (GV->getValueType()->isSingleValueType()) {
234 LatticeVal &IV = TrackedGlobals[GV];
235 if (!isa<UndefValue>(GV->getInitializer()))
236 IV.markConstant(GV->getInitializer());
240 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
241 /// and out of the specified function (which cannot have its address taken),
242 /// this method must be called.
243 void AddTrackedFunction(Function *F) {
244 // Add an entry, F -> undef.
245 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
246 MRVFunctionsTracked.insert(F);
247 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
248 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
251 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
254 void AddArgumentTrackedFunction(Function *F) {
255 TrackingIncomingArguments.insert(F);
258 /// Solve - Solve for constants and executable blocks.
262 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
263 /// that branches on undef values cannot reach any of their successors.
264 /// However, this is not a safe assumption. After we solve dataflow, this
265 /// method should be use to handle this. If this returns true, the solver
267 bool ResolvedUndefsIn(Function &F);
269 bool isBlockExecutable(BasicBlock *BB) const {
270 return BBExecutable.count(BB);
273 std::vector<LatticeVal> getStructLatticeValueFor(Value *V) const {
274 std::vector<LatticeVal> StructValues;
275 auto *STy = dyn_cast<StructType>(V->getType());
276 assert(STy && "getStructLatticeValueFor() can be called only on structs");
277 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
278 auto I = StructValueState.find(std::make_pair(V, i));
279 assert(I != StructValueState.end() && "Value not in valuemap!");
280 StructValues.push_back(I->second);
285 LatticeVal getLatticeValueFor(Value *V) const {
286 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
287 assert(I != ValueState.end() && "V is not in valuemap!");
291 /// getTrackedRetVals - Get the inferred return value map.
293 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
294 return TrackedRetVals;
297 /// getTrackedGlobals - Get and return the set of inferred initializers for
298 /// global variables.
299 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
300 return TrackedGlobals;
303 /// getMRVFunctionsTracked - Get the set of functions which return multiple
304 /// values tracked by the pass.
305 const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
306 return MRVFunctionsTracked;
309 void markOverdefined(Value *V) {
310 assert(!V->getType()->isStructTy() &&
311 "structs should use markAnythingOverdefined");
312 markOverdefined(ValueState[V], V);
315 /// markAnythingOverdefined - Mark the specified value overdefined. This
316 /// works with both scalars and structs.
317 void markAnythingOverdefined(Value *V) {
318 if (auto *STy = dyn_cast<StructType>(V->getType()))
319 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
320 markOverdefined(getStructValueState(V, i), V);
325 // isStructLatticeConstant - Return true if all the lattice values
326 // corresponding to elements of the structure are not overdefined,
328 bool isStructLatticeConstant(Function *F, StructType *STy) {
329 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
330 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
331 assert(It != TrackedMultipleRetVals.end());
332 LatticeVal LV = It->second;
333 if (LV.isOverdefined())
340 // pushToWorkList - Helper for markConstant/markForcedConstant/markOverdefined
341 void pushToWorkList(LatticeVal &IV, Value *V) {
342 if (IV.isOverdefined())
343 return OverdefinedInstWorkList.push_back(V);
344 InstWorkList.push_back(V);
347 // markConstant - Make a value be marked as "constant". If the value
348 // is not already a constant, add it to the instruction work list so that
349 // the users of the instruction are updated later.
351 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
352 if (!IV.markConstant(C)) return;
353 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
354 pushToWorkList(IV, V);
357 void markConstant(Value *V, Constant *C) {
358 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
359 markConstant(ValueState[V], V, C);
362 void markForcedConstant(Value *V, Constant *C) {
363 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
364 LatticeVal &IV = ValueState[V];
365 IV.markForcedConstant(C);
366 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
367 pushToWorkList(IV, V);
371 // markOverdefined - Make a value be marked as "overdefined". If the
372 // value is not already overdefined, add it to the overdefined instruction
373 // work list so that the users of the instruction are updated later.
374 void markOverdefined(LatticeVal &IV, Value *V) {
375 if (!IV.markOverdefined()) return;
377 DEBUG(dbgs() << "markOverdefined: ";
378 if (auto *F = dyn_cast<Function>(V))
379 dbgs() << "Function '" << F->getName() << "'\n";
381 dbgs() << *V << '\n');
382 // Only instructions go on the work list
383 pushToWorkList(IV, V);
386 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
387 if (IV.isOverdefined() || MergeWithV.isUnknown())
389 if (MergeWithV.isOverdefined())
390 return markOverdefined(IV, V);
392 return markConstant(IV, V, MergeWithV.getConstant());
393 if (IV.getConstant() != MergeWithV.getConstant())
394 return markOverdefined(IV, V);
397 void mergeInValue(Value *V, LatticeVal MergeWithV) {
398 assert(!V->getType()->isStructTy() &&
399 "non-structs should use markConstant");
400 mergeInValue(ValueState[V], V, MergeWithV);
404 /// getValueState - Return the LatticeVal object that corresponds to the
405 /// value. This function handles the case when the value hasn't been seen yet
406 /// by properly seeding constants etc.
407 LatticeVal &getValueState(Value *V) {
408 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
410 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
411 ValueState.insert(std::make_pair(V, LatticeVal()));
412 LatticeVal &LV = I.first->second;
415 return LV; // Common case, already in the map.
417 if (auto *C = dyn_cast<Constant>(V)) {
418 // Undef values remain unknown.
419 if (!isa<UndefValue>(V))
420 LV.markConstant(C); // Constants are constant
423 // All others are underdefined by default.
427 /// getStructValueState - Return the LatticeVal object that corresponds to the
428 /// value/field pair. This function handles the case when the value hasn't
429 /// been seen yet by properly seeding constants etc.
430 LatticeVal &getStructValueState(Value *V, unsigned i) {
431 assert(V->getType()->isStructTy() && "Should use getValueState");
432 assert(i < cast<StructType>(V->getType())->getNumElements() &&
433 "Invalid element #");
435 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
436 bool> I = StructValueState.insert(
437 std::make_pair(std::make_pair(V, i), LatticeVal()));
438 LatticeVal &LV = I.first->second;
441 return LV; // Common case, already in the map.
443 if (auto *C = dyn_cast<Constant>(V)) {
444 Constant *Elt = C->getAggregateElement(i);
447 LV.markOverdefined(); // Unknown sort of constant.
448 else if (isa<UndefValue>(Elt))
449 ; // Undef values remain unknown.
451 LV.markConstant(Elt); // Constants are constant.
454 // All others are underdefined by default.
459 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
460 /// work list if it is not already executable.
461 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
462 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
463 return; // This edge is already known to be executable!
465 if (!MarkBlockExecutable(Dest)) {
466 // If the destination is already executable, we just made an *edge*
467 // feasible that wasn't before. Revisit the PHI nodes in the block
468 // because they have potentially new operands.
469 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
470 << " -> " << Dest->getName() << '\n');
473 for (BasicBlock::iterator I = Dest->begin();
474 (PN = dyn_cast<PHINode>(I)); ++I)
479 // getFeasibleSuccessors - Return a vector of booleans to indicate which
480 // successors are reachable from a given terminator instruction.
482 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
484 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
485 // block to the 'To' basic block is currently feasible.
487 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
489 // OperandChangedState - This method is invoked on all of the users of an
490 // instruction that was just changed state somehow. Based on this
491 // information, we need to update the specified user of this instruction.
493 void OperandChangedState(Instruction *I) {
494 if (BBExecutable.count(I->getParent())) // Inst is executable?
499 friend class InstVisitor<SCCPSolver>;
501 // visit implementations - Something changed in this instruction. Either an
502 // operand made a transition, or the instruction is newly executable. Change
503 // the value type of I to reflect these changes if appropriate.
504 void visitPHINode(PHINode &I);
507 void visitReturnInst(ReturnInst &I);
508 void visitTerminatorInst(TerminatorInst &TI);
510 void visitCastInst(CastInst &I);
511 void visitSelectInst(SelectInst &I);
512 void visitBinaryOperator(Instruction &I);
513 void visitCmpInst(CmpInst &I);
514 void visitExtractElementInst(ExtractElementInst &I);
515 void visitInsertElementInst(InsertElementInst &I);
516 void visitShuffleVectorInst(ShuffleVectorInst &I);
517 void visitExtractValueInst(ExtractValueInst &EVI);
518 void visitInsertValueInst(InsertValueInst &IVI);
519 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
520 void visitFuncletPadInst(FuncletPadInst &FPI) {
521 markAnythingOverdefined(&FPI);
523 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
524 markAnythingOverdefined(&CPI);
525 visitTerminatorInst(CPI);
528 // Instructions that cannot be folded away.
529 void visitStoreInst (StoreInst &I);
530 void visitLoadInst (LoadInst &I);
531 void visitGetElementPtrInst(GetElementPtrInst &I);
532 void visitCallInst (CallInst &I) {
535 void visitInvokeInst (InvokeInst &II) {
537 visitTerminatorInst(II);
539 void visitCallSite (CallSite CS);
540 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
541 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
542 void visitFenceInst (FenceInst &I) { /*returns void*/ }
543 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
544 markAnythingOverdefined(&I);
546 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
547 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
548 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
550 void visitInstruction(Instruction &I) {
551 // If a new instruction is added to LLVM that we don't handle.
552 DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
553 markAnythingOverdefined(&I); // Just in case
557 } // end anonymous namespace
560 // getFeasibleSuccessors - Return a vector of booleans to indicate which
561 // successors are reachable from a given terminator instruction.
563 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
564 SmallVectorImpl<bool> &Succs) {
565 Succs.resize(TI.getNumSuccessors());
566 if (auto *BI = dyn_cast<BranchInst>(&TI)) {
567 if (BI->isUnconditional()) {
572 LatticeVal BCValue = getValueState(BI->getCondition());
573 ConstantInt *CI = BCValue.getConstantInt();
575 // Overdefined condition variables, and branches on unfoldable constant
576 // conditions, mean the branch could go either way.
577 if (!BCValue.isUnknown())
578 Succs[0] = Succs[1] = true;
582 // Constant condition variables mean the branch can only go a single way.
583 Succs[CI->isZero()] = true;
587 // Unwinding instructions successors are always executable.
588 if (TI.isExceptional()) {
589 Succs.assign(TI.getNumSuccessors(), true);
593 if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
594 if (!SI->getNumCases()) {
598 LatticeVal SCValue = getValueState(SI->getCondition());
599 ConstantInt *CI = SCValue.getConstantInt();
601 if (!CI) { // Overdefined or unknown condition?
602 // All destinations are executable!
603 if (!SCValue.isUnknown())
604 Succs.assign(TI.getNumSuccessors(), true);
608 Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
612 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
613 if (isa<IndirectBrInst>(&TI)) {
614 // Just mark all destinations executable!
615 Succs.assign(TI.getNumSuccessors(), true);
619 DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
620 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
624 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
625 // block to the 'To' basic block is currently feasible.
627 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
628 assert(BBExecutable.count(To) && "Dest should always be alive!");
630 // Make sure the source basic block is executable!!
631 if (!BBExecutable.count(From)) return false;
633 // Check to make sure this edge itself is actually feasible now.
634 TerminatorInst *TI = From->getTerminator();
635 if (auto *BI = dyn_cast<BranchInst>(TI)) {
636 if (BI->isUnconditional())
639 LatticeVal BCValue = getValueState(BI->getCondition());
641 // Overdefined condition variables mean the branch could go either way,
642 // undef conditions mean that neither edge is feasible yet.
643 ConstantInt *CI = BCValue.getConstantInt();
645 return !BCValue.isUnknown();
647 // Constant condition variables mean the branch can only go a single way.
648 return BI->getSuccessor(CI->isZero()) == To;
651 // Unwinding instructions successors are always executable.
652 if (TI->isExceptional())
655 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
656 if (SI->getNumCases() < 1)
659 LatticeVal SCValue = getValueState(SI->getCondition());
660 ConstantInt *CI = SCValue.getConstantInt();
663 return !SCValue.isUnknown();
665 return SI->findCaseValue(CI).getCaseSuccessor() == To;
668 // Just mark all destinations executable!
669 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
670 if (isa<IndirectBrInst>(TI))
673 DEBUG(dbgs() << "Unknown terminator instruction: " << *TI << '\n');
674 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
677 // visit Implementations - Something changed in this instruction, either an
678 // operand made a transition, or the instruction is newly executable. Change
679 // the value type of I to reflect these changes if appropriate. This method
680 // makes sure to do the following actions:
682 // 1. If a phi node merges two constants in, and has conflicting value coming
683 // from different branches, or if the PHI node merges in an overdefined
684 // value, then the PHI node becomes overdefined.
685 // 2. If a phi node merges only constants in, and they all agree on value, the
686 // PHI node becomes a constant value equal to that.
687 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
688 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
689 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
690 // 6. If a conditional branch has a value that is constant, make the selected
691 // destination executable
692 // 7. If a conditional branch has a value that is overdefined, make all
693 // successors executable.
695 void SCCPSolver::visitPHINode(PHINode &PN) {
696 // If this PN returns a struct, just mark the result overdefined.
697 // TODO: We could do a lot better than this if code actually uses this.
698 if (PN.getType()->isStructTy())
699 return markAnythingOverdefined(&PN);
701 if (getValueState(&PN).isOverdefined())
702 return; // Quick exit
704 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
705 // and slow us down a lot. Just mark them overdefined.
706 if (PN.getNumIncomingValues() > 64)
707 return markOverdefined(&PN);
709 // Look at all of the executable operands of the PHI node. If any of them
710 // are overdefined, the PHI becomes overdefined as well. If they are all
711 // constant, and they agree with each other, the PHI becomes the identical
712 // constant. If they are constant and don't agree, the PHI is overdefined.
713 // If there are no executable operands, the PHI remains unknown.
715 Constant *OperandVal = nullptr;
716 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
717 LatticeVal IV = getValueState(PN.getIncomingValue(i));
718 if (IV.isUnknown()) continue; // Doesn't influence PHI node.
720 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
723 if (IV.isOverdefined()) // PHI node becomes overdefined!
724 return markOverdefined(&PN);
726 if (!OperandVal) { // Grab the first value.
727 OperandVal = IV.getConstant();
731 // There is already a reachable operand. If we conflict with it,
732 // then the PHI node becomes overdefined. If we agree with it, we
735 // Check to see if there are two different constants merging, if so, the PHI
736 // node is overdefined.
737 if (IV.getConstant() != OperandVal)
738 return markOverdefined(&PN);
741 // If we exited the loop, this means that the PHI node only has constant
742 // arguments that agree with each other(and OperandVal is the constant) or
743 // OperandVal is null because there are no defined incoming arguments. If
744 // this is the case, the PHI remains unknown.
747 markConstant(&PN, OperandVal); // Acquire operand value
750 void SCCPSolver::visitReturnInst(ReturnInst &I) {
751 if (I.getNumOperands() == 0) return; // ret void
753 Function *F = I.getParent()->getParent();
754 Value *ResultOp = I.getOperand(0);
756 // If we are tracking the return value of this function, merge it in.
757 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
758 DenseMap<Function*, LatticeVal>::iterator TFRVI =
759 TrackedRetVals.find(F);
760 if (TFRVI != TrackedRetVals.end()) {
761 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
766 // Handle functions that return multiple values.
767 if (!TrackedMultipleRetVals.empty()) {
768 if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
769 if (MRVFunctionsTracked.count(F))
770 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
771 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
772 getStructValueState(ResultOp, i));
777 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
778 SmallVector<bool, 16> SuccFeasible;
779 getFeasibleSuccessors(TI, SuccFeasible);
781 BasicBlock *BB = TI.getParent();
783 // Mark all feasible successors executable.
784 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
786 markEdgeExecutable(BB, TI.getSuccessor(i));
789 void SCCPSolver::visitCastInst(CastInst &I) {
790 LatticeVal OpSt = getValueState(I.getOperand(0));
791 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
793 else if (OpSt.isConstant()) {
794 // Fold the constant as we build.
795 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
797 if (isa<UndefValue>(C))
799 // Propagate constant value
805 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
806 // If this returns a struct, mark all elements over defined, we don't track
807 // structs in structs.
808 if (EVI.getType()->isStructTy())
809 return markAnythingOverdefined(&EVI);
811 // If this is extracting from more than one level of struct, we don't know.
812 if (EVI.getNumIndices() != 1)
813 return markOverdefined(&EVI);
815 Value *AggVal = EVI.getAggregateOperand();
816 if (AggVal->getType()->isStructTy()) {
817 unsigned i = *EVI.idx_begin();
818 LatticeVal EltVal = getStructValueState(AggVal, i);
819 mergeInValue(getValueState(&EVI), &EVI, EltVal);
821 // Otherwise, must be extracting from an array.
822 return markOverdefined(&EVI);
826 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
827 auto *STy = dyn_cast<StructType>(IVI.getType());
829 return markOverdefined(&IVI);
831 // If this has more than one index, we can't handle it, drive all results to
833 if (IVI.getNumIndices() != 1)
834 return markAnythingOverdefined(&IVI);
836 Value *Aggr = IVI.getAggregateOperand();
837 unsigned Idx = *IVI.idx_begin();
839 // Compute the result based on what we're inserting.
840 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
841 // This passes through all values that aren't the inserted element.
843 LatticeVal EltVal = getStructValueState(Aggr, i);
844 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
848 Value *Val = IVI.getInsertedValueOperand();
849 if (Val->getType()->isStructTy())
850 // We don't track structs in structs.
851 markOverdefined(getStructValueState(&IVI, i), &IVI);
853 LatticeVal InVal = getValueState(Val);
854 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
859 void SCCPSolver::visitSelectInst(SelectInst &I) {
860 // If this select returns a struct, just mark the result overdefined.
861 // TODO: We could do a lot better than this if code actually uses this.
862 if (I.getType()->isStructTy())
863 return markAnythingOverdefined(&I);
865 LatticeVal CondValue = getValueState(I.getCondition());
866 if (CondValue.isUnknown())
869 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
870 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
871 mergeInValue(&I, getValueState(OpVal));
875 // Otherwise, the condition is overdefined or a constant we can't evaluate.
876 // See if we can produce something better than overdefined based on the T/F
878 LatticeVal TVal = getValueState(I.getTrueValue());
879 LatticeVal FVal = getValueState(I.getFalseValue());
881 // select ?, C, C -> C.
882 if (TVal.isConstant() && FVal.isConstant() &&
883 TVal.getConstant() == FVal.getConstant())
884 return markConstant(&I, FVal.getConstant());
886 if (TVal.isUnknown()) // select ?, undef, X -> X.
887 return mergeInValue(&I, FVal);
888 if (FVal.isUnknown()) // select ?, X, undef -> X.
889 return mergeInValue(&I, TVal);
893 // Handle Binary Operators.
894 void SCCPSolver::visitBinaryOperator(Instruction &I) {
895 LatticeVal V1State = getValueState(I.getOperand(0));
896 LatticeVal V2State = getValueState(I.getOperand(1));
898 LatticeVal &IV = ValueState[&I];
899 if (IV.isOverdefined()) return;
901 if (V1State.isConstant() && V2State.isConstant()) {
902 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
903 V2State.getConstant());
905 if (isa<UndefValue>(C))
907 return markConstant(IV, &I, C);
910 // If something is undef, wait for it to resolve.
911 if (!V1State.isOverdefined() && !V2State.isOverdefined())
914 // Otherwise, one of our operands is overdefined. Try to produce something
915 // better than overdefined with some tricks.
917 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
918 // operand is overdefined.
919 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul ||
920 I.getOpcode() == Instruction::Or) {
921 LatticeVal *NonOverdefVal = nullptr;
922 if (!V1State.isOverdefined())
923 NonOverdefVal = &V1State;
924 else if (!V2State.isOverdefined())
925 NonOverdefVal = &V2State;
928 if (NonOverdefVal->isUnknown())
931 if (I.getOpcode() == Instruction::And ||
932 I.getOpcode() == Instruction::Mul) {
935 if (NonOverdefVal->getConstant()->isNullValue())
936 return markConstant(IV, &I, NonOverdefVal->getConstant());
939 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
940 if (CI->isAllOnesValue())
941 return markConstant(IV, &I, NonOverdefVal->getConstant());
950 // Handle ICmpInst instruction.
951 void SCCPSolver::visitCmpInst(CmpInst &I) {
952 LatticeVal V1State = getValueState(I.getOperand(0));
953 LatticeVal V2State = getValueState(I.getOperand(1));
955 LatticeVal &IV = ValueState[&I];
956 if (IV.isOverdefined()) return;
958 if (V1State.isConstant() && V2State.isConstant()) {
959 Constant *C = ConstantExpr::getCompare(
960 I.getPredicate(), V1State.getConstant(), V2State.getConstant());
961 if (isa<UndefValue>(C))
963 return markConstant(IV, &I, C);
966 // If operands are still unknown, wait for it to resolve.
967 if (!V1State.isOverdefined() && !V2State.isOverdefined())
973 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
974 // TODO : SCCP does not handle vectors properly.
975 return markOverdefined(&I);
978 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
979 // TODO : SCCP does not handle vectors properly.
980 return markOverdefined(&I);
983 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
984 // TODO : SCCP does not handle vectors properly.
985 return markOverdefined(&I);
988 // Handle getelementptr instructions. If all operands are constants then we
989 // can turn this into a getelementptr ConstantExpr.
991 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
992 if (ValueState[&I].isOverdefined()) return;
994 SmallVector<Constant*, 8> Operands;
995 Operands.reserve(I.getNumOperands());
997 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
998 LatticeVal State = getValueState(I.getOperand(i));
999 if (State.isUnknown())
1000 return; // Operands are not resolved yet.
1002 if (State.isOverdefined())
1003 return markOverdefined(&I);
1005 assert(State.isConstant() && "Unknown state!");
1006 Operands.push_back(State.getConstant());
1009 Constant *Ptr = Operands[0];
1010 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
1012 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1013 if (isa<UndefValue>(C))
1015 markConstant(&I, C);
1018 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1019 // If this store is of a struct, ignore it.
1020 if (SI.getOperand(0)->getType()->isStructTy())
1023 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1026 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1027 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1028 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1030 // Get the value we are storing into the global, then merge it.
1031 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1032 if (I->second.isOverdefined())
1033 TrackedGlobals.erase(I); // No need to keep tracking this!
1037 // Handle load instructions. If the operand is a constant pointer to a constant
1038 // global, we can replace the load with the loaded constant value!
1039 void SCCPSolver::visitLoadInst(LoadInst &I) {
1040 // If this load is of a struct, just mark the result overdefined.
1041 if (I.getType()->isStructTy())
1042 return markAnythingOverdefined(&I);
1044 LatticeVal PtrVal = getValueState(I.getOperand(0));
1045 if (PtrVal.isUnknown()) return; // The pointer is not resolved yet!
1047 LatticeVal &IV = ValueState[&I];
1048 if (IV.isOverdefined()) return;
1050 if (!PtrVal.isConstant() || I.isVolatile())
1051 return markOverdefined(IV, &I);
1053 Constant *Ptr = PtrVal.getConstant();
1055 // load null is undefined.
1056 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1059 // Transform load (constant global) into the value loaded.
1060 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1061 if (!TrackedGlobals.empty()) {
1062 // If we are tracking this global, merge in the known value for it.
1063 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1064 TrackedGlobals.find(GV);
1065 if (It != TrackedGlobals.end()) {
1066 mergeInValue(IV, &I, It->second);
1072 // Transform load from a constant into a constant if possible.
1073 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
1074 if (isa<UndefValue>(C))
1076 return markConstant(IV, &I, C);
1079 // Otherwise we cannot say for certain what value this load will produce.
1081 markOverdefined(IV, &I);
1084 void SCCPSolver::visitCallSite(CallSite CS) {
1085 Function *F = CS.getCalledFunction();
1086 Instruction *I = CS.getInstruction();
1088 // The common case is that we aren't tracking the callee, either because we
1089 // are not doing interprocedural analysis or the callee is indirect, or is
1090 // external. Handle these cases first.
1091 if (!F || F->isDeclaration()) {
1093 // Void return and not tracking callee, just bail.
1094 if (I->getType()->isVoidTy()) return;
1096 // Otherwise, if we have a single return value case, and if the function is
1097 // a declaration, maybe we can constant fold it.
1098 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1099 canConstantFoldCallTo(F)) {
1101 SmallVector<Constant*, 8> Operands;
1102 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1104 LatticeVal State = getValueState(*AI);
1106 if (State.isUnknown())
1107 return; // Operands are not resolved yet.
1108 if (State.isOverdefined())
1109 return markOverdefined(I);
1110 assert(State.isConstant() && "Unknown state!");
1111 Operands.push_back(State.getConstant());
1114 if (getValueState(I).isOverdefined())
1117 // If we can constant fold this, mark the result of the call as a
1119 if (Constant *C = ConstantFoldCall(F, Operands, TLI)) {
1121 if (isa<UndefValue>(C))
1123 return markConstant(I, C);
1127 // Otherwise, we don't know anything about this call, mark it overdefined.
1128 return markAnythingOverdefined(I);
1131 // If this is a local function that doesn't have its address taken, mark its
1132 // entry block executable and merge in the actual arguments to the call into
1133 // the formal arguments of the function.
1134 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1135 MarkBlockExecutable(&F->front());
1137 // Propagate information from this call site into the callee.
1138 CallSite::arg_iterator CAI = CS.arg_begin();
1139 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1140 AI != E; ++AI, ++CAI) {
1141 // If this argument is byval, and if the function is not readonly, there
1142 // will be an implicit copy formed of the input aggregate.
1143 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1144 markOverdefined(&*AI);
1148 if (auto *STy = dyn_cast<StructType>(AI->getType())) {
1149 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1150 LatticeVal CallArg = getStructValueState(*CAI, i);
1151 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
1154 mergeInValue(&*AI, getValueState(*CAI));
1159 // If this is a single/zero retval case, see if we're tracking the function.
1160 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
1161 if (!MRVFunctionsTracked.count(F))
1162 goto CallOverdefined; // Not tracking this callee.
1164 // If we are tracking this callee, propagate the result of the function
1165 // into this call site.
1166 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1167 mergeInValue(getStructValueState(I, i), I,
1168 TrackedMultipleRetVals[std::make_pair(F, i)]);
1170 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1171 if (TFRVI == TrackedRetVals.end())
1172 goto CallOverdefined; // Not tracking this callee.
1174 // If so, propagate the return value of the callee into this call result.
1175 mergeInValue(I, TFRVI->second);
1179 void SCCPSolver::Solve() {
1180 // Process the work lists until they are empty!
1181 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1182 !OverdefinedInstWorkList.empty()) {
1183 // Process the overdefined instruction's work list first, which drives other
1184 // things to overdefined more quickly.
1185 while (!OverdefinedInstWorkList.empty()) {
1186 Value *I = OverdefinedInstWorkList.pop_back_val();
1188 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1190 // "I" got into the work list because it either made the transition from
1191 // bottom to constant, or to overdefined.
1193 // Anything on this worklist that is overdefined need not be visited
1194 // since all of its users will have already been marked as overdefined
1195 // Update all of the users of this instruction's value.
1197 for (User *U : I->users())
1198 if (auto *UI = dyn_cast<Instruction>(U))
1199 OperandChangedState(UI);
1202 // Process the instruction work list.
1203 while (!InstWorkList.empty()) {
1204 Value *I = InstWorkList.pop_back_val();
1206 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1208 // "I" got into the work list because it made the transition from undef to
1211 // Anything on this worklist that is overdefined need not be visited
1212 // since all of its users will have already been marked as overdefined.
1213 // Update all of the users of this instruction's value.
1215 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1216 for (User *U : I->users())
1217 if (auto *UI = dyn_cast<Instruction>(U))
1218 OperandChangedState(UI);
1221 // Process the basic block work list.
1222 while (!BBWorkList.empty()) {
1223 BasicBlock *BB = BBWorkList.back();
1224 BBWorkList.pop_back();
1226 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1228 // Notify all instructions in this basic block that they are newly
1235 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1236 /// that branches on undef values cannot reach any of their successors.
1237 /// However, this is not a safe assumption. After we solve dataflow, this
1238 /// method should be use to handle this. If this returns true, the solver
1239 /// should be rerun.
1241 /// This method handles this by finding an unresolved branch and marking it one
1242 /// of the edges from the block as being feasible, even though the condition
1243 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1244 /// CFG and only slightly pessimizes the analysis results (by marking one,
1245 /// potentially infeasible, edge feasible). This cannot usefully modify the
1246 /// constraints on the condition of the branch, as that would impact other users
1249 /// This scan also checks for values that use undefs, whose results are actually
1250 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1251 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1252 /// even if X isn't defined.
1253 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1254 for (BasicBlock &BB : F) {
1255 if (!BBExecutable.count(&BB))
1258 for (Instruction &I : BB) {
1259 // Look for instructions which produce undef values.
1260 if (I.getType()->isVoidTy()) continue;
1262 if (auto *STy = dyn_cast<StructType>(I.getType())) {
1263 // Only a few things that can be structs matter for undef.
1265 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1266 if (CallSite CS = CallSite(&I))
1267 if (Function *F = CS.getCalledFunction())
1268 if (MRVFunctionsTracked.count(F))
1271 // extractvalue and insertvalue don't need to be marked; they are
1272 // tracked as precisely as their operands.
1273 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1276 // Send the results of everything else to overdefined. We could be
1277 // more precise than this but it isn't worth bothering.
1278 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1279 LatticeVal &LV = getStructValueState(&I, i);
1281 markOverdefined(LV, &I);
1286 LatticeVal &LV = getValueState(&I);
1287 if (!LV.isUnknown()) continue;
1289 // extractvalue is safe; check here because the argument is a struct.
1290 if (isa<ExtractValueInst>(I))
1293 // Compute the operand LatticeVals, for convenience below.
1294 // Anything taking a struct is conservatively assumed to require
1295 // overdefined markings.
1296 if (I.getOperand(0)->getType()->isStructTy()) {
1297 markOverdefined(&I);
1300 LatticeVal Op0LV = getValueState(I.getOperand(0));
1302 if (I.getNumOperands() == 2) {
1303 if (I.getOperand(1)->getType()->isStructTy()) {
1304 markOverdefined(&I);
1308 Op1LV = getValueState(I.getOperand(1));
1310 // If this is an instructions whose result is defined even if the input is
1311 // not fully defined, propagate the information.
1312 Type *ITy = I.getType();
1313 switch (I.getOpcode()) {
1314 case Instruction::Add:
1315 case Instruction::Sub:
1316 case Instruction::Trunc:
1317 case Instruction::FPTrunc:
1318 case Instruction::BitCast:
1319 break; // Any undef -> undef
1320 case Instruction::FSub:
1321 case Instruction::FAdd:
1322 case Instruction::FMul:
1323 case Instruction::FDiv:
1324 case Instruction::FRem:
1325 // Floating-point binary operation: be conservative.
1326 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1327 markForcedConstant(&I, Constant::getNullValue(ITy));
1329 markOverdefined(&I);
1331 case Instruction::ZExt:
1332 case Instruction::SExt:
1333 case Instruction::FPToUI:
1334 case Instruction::FPToSI:
1335 case Instruction::FPExt:
1336 case Instruction::PtrToInt:
1337 case Instruction::IntToPtr:
1338 case Instruction::SIToFP:
1339 case Instruction::UIToFP:
1340 // undef -> 0; some outputs are impossible
1341 markForcedConstant(&I, Constant::getNullValue(ITy));
1343 case Instruction::Mul:
1344 case Instruction::And:
1345 // Both operands undef -> undef
1346 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1348 // undef * X -> 0. X could be zero.
1349 // undef & X -> 0. X could be zero.
1350 markForcedConstant(&I, Constant::getNullValue(ITy));
1353 case Instruction::Or:
1354 // Both operands undef -> undef
1355 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1357 // undef | X -> -1. X could be -1.
1358 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
1361 case Instruction::Xor:
1362 // undef ^ undef -> 0; strictly speaking, this is not strictly
1363 // necessary, but we try to be nice to people who expect this
1364 // behavior in simple cases
1365 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
1366 markForcedConstant(&I, Constant::getNullValue(ITy));
1369 // undef ^ X -> undef
1372 case Instruction::SDiv:
1373 case Instruction::UDiv:
1374 case Instruction::SRem:
1375 case Instruction::URem:
1376 // X / undef -> undef. No change.
1377 // X % undef -> undef. No change.
1378 if (Op1LV.isUnknown()) break;
1380 // X / 0 -> undef. No change.
1381 // X % 0 -> undef. No change.
1382 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1385 // undef / X -> 0. X could be maxint.
1386 // undef % X -> 0. X could be 1.
1387 markForcedConstant(&I, Constant::getNullValue(ITy));
1390 case Instruction::AShr:
1391 // X >>a undef -> undef.
1392 if (Op1LV.isUnknown()) break;
1394 // Shifting by the bitwidth or more is undefined.
1395 if (Op1LV.isConstant()) {
1396 if (auto *ShiftAmt = Op1LV.getConstantInt())
1397 if (ShiftAmt->getLimitedValue() >=
1398 ShiftAmt->getType()->getScalarSizeInBits())
1403 markForcedConstant(&I, Constant::getNullValue(ITy));
1405 case Instruction::LShr:
1406 case Instruction::Shl:
1407 // X << undef -> undef.
1408 // X >> undef -> undef.
1409 if (Op1LV.isUnknown()) break;
1411 // Shifting by the bitwidth or more is undefined.
1412 if (Op1LV.isConstant()) {
1413 if (auto *ShiftAmt = Op1LV.getConstantInt())
1414 if (ShiftAmt->getLimitedValue() >=
1415 ShiftAmt->getType()->getScalarSizeInBits())
1421 markForcedConstant(&I, Constant::getNullValue(ITy));
1423 case Instruction::Select:
1424 Op1LV = getValueState(I.getOperand(1));
1425 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1426 if (Op0LV.isUnknown()) {
1427 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1428 Op1LV = getValueState(I.getOperand(2));
1429 } else if (Op1LV.isUnknown()) {
1430 // c ? undef : undef -> undef. No change.
1431 Op1LV = getValueState(I.getOperand(2));
1432 if (Op1LV.isUnknown())
1434 // Otherwise, c ? undef : x -> x.
1436 // Leave Op1LV as Operand(1)'s LatticeValue.
1439 if (Op1LV.isConstant())
1440 markForcedConstant(&I, Op1LV.getConstant());
1442 markOverdefined(&I);
1444 case Instruction::Load:
1445 // A load here means one of two things: a load of undef from a global,
1446 // a load from an unknown pointer. Either way, having it return undef
1449 case Instruction::ICmp:
1450 // X == undef -> undef. Other comparisons get more complicated.
1451 if (cast<ICmpInst>(&I)->isEquality())
1453 markOverdefined(&I);
1455 case Instruction::Call:
1456 case Instruction::Invoke: {
1457 // There are two reasons a call can have an undef result
1458 // 1. It could be tracked.
1459 // 2. It could be constant-foldable.
1460 // Because of the way we solve return values, tracked calls must
1461 // never be marked overdefined in ResolvedUndefsIn.
1462 if (Function *F = CallSite(&I).getCalledFunction())
1463 if (TrackedRetVals.count(F))
1466 // If the call is constant-foldable, we mark it overdefined because
1467 // we do not know what return values are valid.
1468 markOverdefined(&I);
1472 // If we don't know what should happen here, conservatively mark it
1474 markOverdefined(&I);
1479 // Check to see if we have a branch or switch on an undefined value. If so
1480 // we force the branch to go one way or the other to make the successor
1481 // values live. It doesn't really matter which way we force it.
1482 TerminatorInst *TI = BB.getTerminator();
1483 if (auto *BI = dyn_cast<BranchInst>(TI)) {
1484 if (!BI->isConditional()) continue;
1485 if (!getValueState(BI->getCondition()).isUnknown())
1488 // If the input to SCCP is actually branch on undef, fix the undef to
1490 if (isa<UndefValue>(BI->getCondition())) {
1491 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1492 markEdgeExecutable(&BB, TI->getSuccessor(1));
1496 // Otherwise, it is a branch on a symbolic value which is currently
1497 // considered to be undef. Handle this by forcing the input value to the
1499 markForcedConstant(BI->getCondition(),
1500 ConstantInt::getFalse(TI->getContext()));
1504 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1505 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
1508 // If the input to SCCP is actually switch on undef, fix the undef to
1509 // the first constant.
1510 if (isa<UndefValue>(SI->getCondition())) {
1511 SI->setCondition(SI->case_begin().getCaseValue());
1512 markEdgeExecutable(&BB, SI->case_begin().getCaseSuccessor());
1516 markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
1524 static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
1525 Constant *Const = nullptr;
1526 if (V->getType()->isStructTy()) {
1527 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
1528 if (any_of(IVs, [](const LatticeVal &LV) { return LV.isOverdefined(); }))
1530 std::vector<Constant *> ConstVals;
1531 auto *ST = dyn_cast<StructType>(V->getType());
1532 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1533 LatticeVal V = IVs[i];
1534 ConstVals.push_back(V.isConstant()
1536 : UndefValue::get(ST->getElementType(i)));
1538 Const = ConstantStruct::get(ST, ConstVals);
1540 LatticeVal IV = Solver.getLatticeValueFor(V);
1541 if (IV.isOverdefined())
1543 Const = IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
1545 assert(Const && "Constant is nullptr here!");
1546 DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n');
1548 // Replaces all of the uses of a variable with uses of the constant.
1549 V->replaceAllUsesWith(Const);
1553 // runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
1554 // and return true if the function was modified.
1556 static bool runSCCP(Function &F, const DataLayout &DL,
1557 const TargetLibraryInfo *TLI) {
1558 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1559 SCCPSolver Solver(DL, TLI);
1561 // Mark the first block of the function as being executable.
1562 Solver.MarkBlockExecutable(&F.front());
1564 // Mark all arguments to the function as being overdefined.
1565 for (Argument &AI : F.args())
1566 Solver.markAnythingOverdefined(&AI);
1568 // Solve for constants.
1569 bool ResolvedUndefs = true;
1570 while (ResolvedUndefs) {
1572 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1573 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1576 bool MadeChanges = false;
1578 // If we decided that there are basic blocks that are dead in this function,
1579 // delete their contents now. Note that we cannot actually delete the blocks,
1580 // as we cannot modify the CFG of the function.
1582 for (BasicBlock &BB : F) {
1583 if (!Solver.isBlockExecutable(&BB)) {
1584 DEBUG(dbgs() << " BasicBlock Dead:" << BB);
1587 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
1593 // Iterate over all of the instructions in a function, replacing them with
1594 // constants if we have found them to be of constant values.
1596 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
1597 Instruction *Inst = &*BI++;
1598 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1601 if (tryToReplaceWithConstant(Solver, Inst)) {
1602 if (isInstructionTriviallyDead(Inst))
1603 Inst->eraseFromParent();
1604 // Hey, we just changed something!
1614 PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
1615 const DataLayout &DL = F.getParent()->getDataLayout();
1616 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1617 if (!runSCCP(F, DL, &TLI))
1618 return PreservedAnalyses::all();
1620 auto PA = PreservedAnalyses();
1621 PA.preserve<GlobalsAA>();
1626 //===--------------------------------------------------------------------===//
1628 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1629 /// Sparse Conditional Constant Propagator.
1631 class SCCPLegacyPass : public FunctionPass {
1633 void getAnalysisUsage(AnalysisUsage &AU) const override {
1634 AU.addRequired<TargetLibraryInfoWrapperPass>();
1635 AU.addPreserved<GlobalsAAWrapperPass>();
1637 static char ID; // Pass identification, replacement for typeid
1638 SCCPLegacyPass() : FunctionPass(ID) {
1639 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1642 // runOnFunction - Run the Sparse Conditional Constant Propagation
1643 // algorithm, and return true if the function was modified.
1645 bool runOnFunction(Function &F) override {
1646 if (skipFunction(F))
1648 const DataLayout &DL = F.getParent()->getDataLayout();
1649 const TargetLibraryInfo *TLI =
1650 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1651 return runSCCP(F, DL, TLI);
1654 } // end anonymous namespace
1656 char SCCPLegacyPass::ID = 0;
1657 INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1658 "Sparse Conditional Constant Propagation", false, false)
1659 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1660 INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1661 "Sparse Conditional Constant Propagation", false, false)
1663 // createSCCPPass - This is the public interface to this file.
1664 FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1666 static bool AddressIsTaken(const GlobalValue *GV) {
1667 // Delete any dead constantexpr klingons.
1668 GV->removeDeadConstantUsers();
1670 for (const Use &U : GV->uses()) {
1671 const User *UR = U.getUser();
1672 if (const auto *SI = dyn_cast<StoreInst>(UR)) {
1673 if (SI->getOperand(0) == GV || SI->isVolatile())
1674 return true; // Storing addr of GV.
1675 } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
1676 // Make sure we are calling the function, not passing the address.
1677 ImmutableCallSite CS(cast<Instruction>(UR));
1678 if (!CS.isCallee(&U))
1680 } else if (const auto *LI = dyn_cast<LoadInst>(UR)) {
1681 if (LI->isVolatile())
1683 } else if (isa<BlockAddress>(UR)) {
1684 // blockaddress doesn't take the address of the function, it takes addr
1693 static void findReturnsToZap(Function &F,
1694 SmallPtrSet<Function *, 32> &AddressTakenFunctions,
1695 SmallVector<ReturnInst *, 8> &ReturnsToZap) {
1696 // We can only do this if we know that nothing else can call the function.
1697 if (!F.hasLocalLinkage() || AddressTakenFunctions.count(&F))
1700 for (BasicBlock &BB : F)
1701 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1702 if (!isa<UndefValue>(RI->getOperand(0)))
1703 ReturnsToZap.push_back(RI);
1706 static bool runIPSCCP(Module &M, const DataLayout &DL,
1707 const TargetLibraryInfo *TLI) {
1708 SCCPSolver Solver(DL, TLI);
1710 // AddressTakenFunctions - This set keeps track of the address-taken functions
1711 // that are in the input. As IPSCCP runs through and simplifies code,
1712 // functions that were address taken can end up losing their
1713 // address-taken-ness. Because of this, we keep track of their addresses from
1714 // the first pass so we can use them for the later simplification pass.
1715 SmallPtrSet<Function*, 32> AddressTakenFunctions;
1717 // Loop over all functions, marking arguments to those with their addresses
1718 // taken or that are external as overdefined.
1720 for (Function &F : M) {
1721 if (F.isDeclaration())
1724 // If this is an exact definition of this function, then we can propagate
1725 // information about its result into callsites of it.
1726 if (F.hasExactDefinition())
1727 Solver.AddTrackedFunction(&F);
1729 // If this function only has direct calls that we can see, we can track its
1730 // arguments and return value aggressively, and can assume it is not called
1731 // unless we see evidence to the contrary.
1732 if (F.hasLocalLinkage()) {
1733 if (AddressIsTaken(&F))
1734 AddressTakenFunctions.insert(&F);
1736 Solver.AddArgumentTrackedFunction(&F);
1741 // Assume the function is called.
1742 Solver.MarkBlockExecutable(&F.front());
1744 // Assume nothing about the incoming arguments.
1745 for (Argument &AI : F.args())
1746 Solver.markAnythingOverdefined(&AI);
1749 // Loop over global variables. We inform the solver about any internal global
1750 // variables that do not have their 'addresses taken'. If they don't have
1751 // their addresses taken, we can propagate constants through them.
1752 for (GlobalVariable &G : M.globals())
1753 if (!G.isConstant() && G.hasLocalLinkage() && !AddressIsTaken(&G))
1754 Solver.TrackValueOfGlobalVariable(&G);
1756 // Solve for constants.
1757 bool ResolvedUndefs = true;
1758 while (ResolvedUndefs) {
1761 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1762 ResolvedUndefs = false;
1763 for (Function &F : M)
1764 ResolvedUndefs |= Solver.ResolvedUndefsIn(F);
1767 bool MadeChanges = false;
1769 // Iterate over all of the instructions in the module, replacing them with
1770 // constants if we have found them to be of constant values.
1772 SmallVector<BasicBlock*, 512> BlocksToErase;
1774 for (Function &F : M) {
1775 if (F.isDeclaration())
1778 if (Solver.isBlockExecutable(&F.front())) {
1779 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
1781 if (AI->use_empty())
1783 if (tryToReplaceWithConstant(Solver, &*AI))
1788 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1789 if (!Solver.isBlockExecutable(&*BB)) {
1790 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1794 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false);
1798 if (&*BB != &F.front())
1799 BlocksToErase.push_back(&*BB);
1803 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1804 Instruction *Inst = &*BI++;
1805 if (Inst->getType()->isVoidTy())
1807 if (tryToReplaceWithConstant(Solver, Inst)) {
1808 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1809 Inst->eraseFromParent();
1810 // Hey, we just changed something!
1817 // Now that all instructions in the function are constant folded, erase dead
1818 // blocks, because we can now use ConstantFoldTerminator to get rid of
1820 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1821 // If there are any PHI nodes in this successor, drop entries for BB now.
1822 BasicBlock *DeadBB = BlocksToErase[i];
1823 for (Value::user_iterator UI = DeadBB->user_begin(),
1824 UE = DeadBB->user_end();
1826 // Grab the user and then increment the iterator early, as the user
1827 // will be deleted. Step past all adjacent uses from the same user.
1828 auto *I = dyn_cast<Instruction>(*UI);
1829 do { ++UI; } while (UI != UE && *UI == I);
1831 // Ignore blockaddress users; BasicBlock's dtor will handle them.
1834 bool Folded = ConstantFoldTerminator(I->getParent());
1836 // The constant folder may not have been able to fold the terminator
1837 // if this is a branch or switch on undef. Fold it manually as a
1838 // branch to the first successor.
1840 if (auto *BI = dyn_cast<BranchInst>(I)) {
1841 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1842 "Branch should be foldable!");
1843 } else if (auto *SI = dyn_cast<SwitchInst>(I)) {
1844 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1846 llvm_unreachable("Didn't fold away reference to block!");
1850 // Make this an uncond branch to the first successor.
1851 TerminatorInst *TI = I->getParent()->getTerminator();
1852 BranchInst::Create(TI->getSuccessor(0), TI);
1854 // Remove entries in successor phi nodes to remove edges.
1855 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1856 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1858 // Remove the old terminator.
1859 TI->eraseFromParent();
1863 // Finally, delete the basic block.
1864 F.getBasicBlockList().erase(DeadBB);
1866 BlocksToErase.clear();
1869 // If we inferred constant or undef return values for a function, we replaced
1870 // all call uses with the inferred value. This means we don't need to bother
1871 // actually returning anything from the function. Replace all return
1872 // instructions with return undef.
1874 // Do this in two stages: first identify the functions we should process, then
1875 // actually zap their returns. This is important because we can only do this
1876 // if the address of the function isn't taken. In cases where a return is the
1877 // last use of a function, the order of processing functions would affect
1878 // whether other functions are optimizable.
1879 SmallVector<ReturnInst*, 8> ReturnsToZap;
1881 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1882 for (const auto &I : RV) {
1883 Function *F = I.first;
1884 if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
1886 findReturnsToZap(*F, AddressTakenFunctions, ReturnsToZap);
1889 for (const auto &F : Solver.getMRVFunctionsTracked()) {
1890 assert(F->getReturnType()->isStructTy() &&
1891 "The return type should be a struct");
1892 StructType *STy = cast<StructType>(F->getReturnType());
1893 if (Solver.isStructLatticeConstant(F, STy))
1894 findReturnsToZap(*F, AddressTakenFunctions, ReturnsToZap);
1897 // Zap all returns which we've identified as zap to change.
1898 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1899 Function *F = ReturnsToZap[i]->getParent()->getParent();
1900 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1903 // If we inferred constant or undef values for globals variables, we can
1904 // delete the global and any stores that remain to it.
1905 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1906 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1907 E = TG.end(); I != E; ++I) {
1908 GlobalVariable *GV = I->first;
1909 assert(!I->second.isOverdefined() &&
1910 "Overdefined values should have been taken out of the map!");
1911 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1912 while (!GV->use_empty()) {
1913 StoreInst *SI = cast<StoreInst>(GV->user_back());
1914 SI->eraseFromParent();
1916 M.getGlobalList().erase(GV);
1923 PreservedAnalyses IPSCCPPass::run(Module &M, ModuleAnalysisManager &AM) {
1924 const DataLayout &DL = M.getDataLayout();
1925 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
1926 if (!runIPSCCP(M, DL, &TLI))
1927 return PreservedAnalyses::all();
1928 return PreservedAnalyses::none();
1932 //===--------------------------------------------------------------------===//
1934 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1935 /// Constant Propagation.
1937 class IPSCCPLegacyPass : public ModulePass {
1941 IPSCCPLegacyPass() : ModulePass(ID) {
1942 initializeIPSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1945 bool runOnModule(Module &M) override {
1948 const DataLayout &DL = M.getDataLayout();
1949 const TargetLibraryInfo *TLI =
1950 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1951 return runIPSCCP(M, DL, TLI);
1954 void getAnalysisUsage(AnalysisUsage &AU) const override {
1955 AU.addRequired<TargetLibraryInfoWrapperPass>();
1958 } // end anonymous namespace
1960 char IPSCCPLegacyPass::ID = 0;
1961 INITIALIZE_PASS_BEGIN(IPSCCPLegacyPass, "ipsccp",
1962 "Interprocedural Sparse Conditional Constant Propagation",
1964 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1965 INITIALIZE_PASS_END(IPSCCPLegacyPass, "ipsccp",
1966 "Interprocedural Sparse Conditional Constant Propagation",
1969 // createIPSCCPPass - This is the public interface to this file.
1970 ModulePass *llvm::createIPSCCPPass() { return new IPSCCPLegacyPass(); }