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 /// getBlockAddress - If this is a constant with a BlockAddress value, return
144 /// it, otherwise return null.
145 BlockAddress *getBlockAddress() const {
147 return dyn_cast<BlockAddress>(getConstant());
151 void markForcedConstant(Constant *V) {
152 assert(isUnknown() && "Can't force a defined value!");
153 Val.setInt(forcedconstant);
157 } // end anonymous namespace.
162 //===----------------------------------------------------------------------===//
164 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
165 /// Constant Propagation.
167 class SCCPSolver : public InstVisitor<SCCPSolver> {
168 const DataLayout &DL;
169 const TargetLibraryInfo *TLI;
170 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
171 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
173 /// StructValueState - This maintains ValueState for values that have
174 /// StructType, for example for formal arguments, calls, insertelement, etc.
176 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
178 /// GlobalValue - If we are tracking any values for the contents of a global
179 /// variable, we keep a mapping from the constant accessor to the element of
180 /// the global, to the currently known value. If the value becomes
181 /// overdefined, it's entry is simply removed from this map.
182 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
184 /// TrackedRetVals - If we are tracking arguments into and the return
185 /// value out of a function, it will have an entry in this map, indicating
186 /// what the known return value for the function is.
187 DenseMap<Function*, LatticeVal> TrackedRetVals;
189 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
190 /// that return multiple values.
191 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
193 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
194 /// represented here for efficient lookup.
195 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
197 /// TrackingIncomingArguments - This is the set of functions for whose
198 /// arguments we make optimistic assumptions about and try to prove as
200 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
202 /// The reason for two worklists is that overdefined is the lowest state
203 /// on the lattice, and moving things to overdefined as fast as possible
204 /// makes SCCP converge much faster.
206 /// By having a separate worklist, we accomplish this because everything
207 /// possibly overdefined will become overdefined at the soonest possible
209 SmallVector<Value*, 64> OverdefinedInstWorkList;
210 SmallVector<Value*, 64> InstWorkList;
213 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
215 /// KnownFeasibleEdges - Entries in this set are edges which have already had
216 /// PHI nodes retriggered.
217 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
218 DenseSet<Edge> KnownFeasibleEdges;
220 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
221 : DL(DL), TLI(tli) {}
223 /// MarkBlockExecutable - This method can be used by clients to mark all of
224 /// the blocks that are known to be intrinsically live in the processed unit.
226 /// This returns true if the block was not considered live before.
227 bool MarkBlockExecutable(BasicBlock *BB) {
228 if (!BBExecutable.insert(BB).second)
230 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
231 BBWorkList.push_back(BB); // Add the block to the work list!
235 /// TrackValueOfGlobalVariable - Clients can use this method to
236 /// inform the SCCPSolver that it should track loads and stores to the
237 /// specified global variable if it can. This is only legal to call if
238 /// performing Interprocedural SCCP.
239 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
240 // We only track the contents of scalar globals.
241 if (GV->getValueType()->isSingleValueType()) {
242 LatticeVal &IV = TrackedGlobals[GV];
243 if (!isa<UndefValue>(GV->getInitializer()))
244 IV.markConstant(GV->getInitializer());
248 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
249 /// and out of the specified function (which cannot have its address taken),
250 /// this method must be called.
251 void AddTrackedFunction(Function *F) {
252 // Add an entry, F -> undef.
253 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
254 MRVFunctionsTracked.insert(F);
255 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
256 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
259 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
262 void AddArgumentTrackedFunction(Function *F) {
263 TrackingIncomingArguments.insert(F);
266 /// Solve - Solve for constants and executable blocks.
270 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
271 /// that branches on undef values cannot reach any of their successors.
272 /// However, this is not a safe assumption. After we solve dataflow, this
273 /// method should be use to handle this. If this returns true, the solver
275 bool ResolvedUndefsIn(Function &F);
277 bool isBlockExecutable(BasicBlock *BB) const {
278 return BBExecutable.count(BB);
281 std::vector<LatticeVal> getStructLatticeValueFor(Value *V) const {
282 std::vector<LatticeVal> StructValues;
283 auto *STy = dyn_cast<StructType>(V->getType());
284 assert(STy && "getStructLatticeValueFor() can be called only on structs");
285 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
286 auto I = StructValueState.find(std::make_pair(V, i));
287 assert(I != StructValueState.end() && "Value not in valuemap!");
288 StructValues.push_back(I->second);
293 LatticeVal getLatticeValueFor(Value *V) const {
294 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
295 assert(I != ValueState.end() && "V is not in valuemap!");
299 /// getTrackedRetVals - Get the inferred return value map.
301 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
302 return TrackedRetVals;
305 /// getTrackedGlobals - Get and return the set of inferred initializers for
306 /// global variables.
307 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
308 return TrackedGlobals;
311 /// getMRVFunctionsTracked - Get the set of functions which return multiple
312 /// values tracked by the pass.
313 const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
314 return MRVFunctionsTracked;
317 /// markOverdefined - Mark the specified value overdefined. This
318 /// works with both scalars and structs.
319 void markOverdefined(Value *V) {
320 if (auto *STy = dyn_cast<StructType>(V->getType()))
321 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
322 markOverdefined(getStructValueState(V, i), V);
324 markOverdefined(ValueState[V], V);
327 // isStructLatticeConstant - Return true if all the lattice values
328 // corresponding to elements of the structure are not overdefined,
330 bool isStructLatticeConstant(Function *F, StructType *STy) {
331 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
332 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
333 assert(It != TrackedMultipleRetVals.end());
334 LatticeVal LV = It->second;
335 if (LV.isOverdefined())
342 // pushToWorkList - Helper for markConstant/markForcedConstant/markOverdefined
343 void pushToWorkList(LatticeVal &IV, Value *V) {
344 if (IV.isOverdefined())
345 return OverdefinedInstWorkList.push_back(V);
346 InstWorkList.push_back(V);
349 // markConstant - Make a value be marked as "constant". If the value
350 // is not already a constant, add it to the instruction work list so that
351 // the users of the instruction are updated later.
353 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
354 if (!IV.markConstant(C)) return;
355 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
356 pushToWorkList(IV, V);
359 void markConstant(Value *V, Constant *C) {
360 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
361 markConstant(ValueState[V], V, C);
364 void markForcedConstant(Value *V, Constant *C) {
365 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
366 LatticeVal &IV = ValueState[V];
367 IV.markForcedConstant(C);
368 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
369 pushToWorkList(IV, V);
373 // markOverdefined - Make a value be marked as "overdefined". If the
374 // value is not already overdefined, add it to the overdefined instruction
375 // work list so that the users of the instruction are updated later.
376 void markOverdefined(LatticeVal &IV, Value *V) {
377 if (!IV.markOverdefined()) return;
379 DEBUG(dbgs() << "markOverdefined: ";
380 if (auto *F = dyn_cast<Function>(V))
381 dbgs() << "Function '" << F->getName() << "'\n";
383 dbgs() << *V << '\n');
384 // Only instructions go on the work list
385 pushToWorkList(IV, V);
388 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
389 if (IV.isOverdefined() || MergeWithV.isUnknown())
391 if (MergeWithV.isOverdefined())
392 return markOverdefined(IV, V);
394 return markConstant(IV, V, MergeWithV.getConstant());
395 if (IV.getConstant() != MergeWithV.getConstant())
396 return markOverdefined(IV, V);
399 void mergeInValue(Value *V, LatticeVal MergeWithV) {
400 assert(!V->getType()->isStructTy() &&
401 "non-structs should use markConstant");
402 mergeInValue(ValueState[V], V, MergeWithV);
406 /// getValueState - Return the LatticeVal object that corresponds to the
407 /// value. This function handles the case when the value hasn't been seen yet
408 /// by properly seeding constants etc.
409 LatticeVal &getValueState(Value *V) {
410 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
412 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
413 ValueState.insert(std::make_pair(V, LatticeVal()));
414 LatticeVal &LV = I.first->second;
417 return LV; // Common case, already in the map.
419 if (auto *C = dyn_cast<Constant>(V)) {
420 // Undef values remain unknown.
421 if (!isa<UndefValue>(V))
422 LV.markConstant(C); // Constants are constant
425 // All others are underdefined by default.
429 /// getStructValueState - Return the LatticeVal object that corresponds to the
430 /// value/field pair. This function handles the case when the value hasn't
431 /// been seen yet by properly seeding constants etc.
432 LatticeVal &getStructValueState(Value *V, unsigned i) {
433 assert(V->getType()->isStructTy() && "Should use getValueState");
434 assert(i < cast<StructType>(V->getType())->getNumElements() &&
435 "Invalid element #");
437 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
438 bool> I = StructValueState.insert(
439 std::make_pair(std::make_pair(V, i), LatticeVal()));
440 LatticeVal &LV = I.first->second;
443 return LV; // Common case, already in the map.
445 if (auto *C = dyn_cast<Constant>(V)) {
446 Constant *Elt = C->getAggregateElement(i);
449 LV.markOverdefined(); // Unknown sort of constant.
450 else if (isa<UndefValue>(Elt))
451 ; // Undef values remain unknown.
453 LV.markConstant(Elt); // Constants are constant.
456 // All others are underdefined by default.
461 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
462 /// work list if it is not already executable.
463 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
464 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
465 return; // This edge is already known to be executable!
467 if (!MarkBlockExecutable(Dest)) {
468 // If the destination is already executable, we just made an *edge*
469 // feasible that wasn't before. Revisit the PHI nodes in the block
470 // because they have potentially new operands.
471 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
472 << " -> " << Dest->getName() << '\n');
475 for (BasicBlock::iterator I = Dest->begin();
476 (PN = dyn_cast<PHINode>(I)); ++I)
481 // getFeasibleSuccessors - Return a vector of booleans to indicate which
482 // successors are reachable from a given terminator instruction.
484 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
486 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
487 // block to the 'To' basic block is currently feasible.
489 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
491 // OperandChangedState - This method is invoked on all of the users of an
492 // instruction that was just changed state somehow. Based on this
493 // information, we need to update the specified user of this instruction.
495 void OperandChangedState(Instruction *I) {
496 if (BBExecutable.count(I->getParent())) // Inst is executable?
501 friend class InstVisitor<SCCPSolver>;
503 // visit implementations - Something changed in this instruction. Either an
504 // operand made a transition, or the instruction is newly executable. Change
505 // the value type of I to reflect these changes if appropriate.
506 void visitPHINode(PHINode &I);
509 void visitReturnInst(ReturnInst &I);
510 void visitTerminatorInst(TerminatorInst &TI);
512 void visitCastInst(CastInst &I);
513 void visitSelectInst(SelectInst &I);
514 void visitBinaryOperator(Instruction &I);
515 void visitCmpInst(CmpInst &I);
516 void visitExtractValueInst(ExtractValueInst &EVI);
517 void visitInsertValueInst(InsertValueInst &IVI);
518 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
519 markOverdefined(&CPI);
520 visitTerminatorInst(CPI);
523 // Instructions that cannot be folded away.
524 void visitStoreInst (StoreInst &I);
525 void visitLoadInst (LoadInst &I);
526 void visitGetElementPtrInst(GetElementPtrInst &I);
527 void visitCallInst (CallInst &I) {
530 void visitInvokeInst (InvokeInst &II) {
532 visitTerminatorInst(II);
534 void visitCallSite (CallSite CS);
535 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
536 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
537 void visitFenceInst (FenceInst &I) { /*returns void*/ }
538 void visitInstruction(Instruction &I) {
539 // All the instructions we don't do any special handling for just
540 // go to overdefined.
541 DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
546 } // end anonymous namespace
549 // getFeasibleSuccessors - Return a vector of booleans to indicate which
550 // successors are reachable from a given terminator instruction.
552 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
553 SmallVectorImpl<bool> &Succs) {
554 Succs.resize(TI.getNumSuccessors());
555 if (auto *BI = dyn_cast<BranchInst>(&TI)) {
556 if (BI->isUnconditional()) {
561 LatticeVal BCValue = getValueState(BI->getCondition());
562 ConstantInt *CI = BCValue.getConstantInt();
564 // Overdefined condition variables, and branches on unfoldable constant
565 // conditions, mean the branch could go either way.
566 if (!BCValue.isUnknown())
567 Succs[0] = Succs[1] = true;
571 // Constant condition variables mean the branch can only go a single way.
572 Succs[CI->isZero()] = true;
576 // Unwinding instructions successors are always executable.
577 if (TI.isExceptional()) {
578 Succs.assign(TI.getNumSuccessors(), true);
582 if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
583 if (!SI->getNumCases()) {
587 LatticeVal SCValue = getValueState(SI->getCondition());
588 ConstantInt *CI = SCValue.getConstantInt();
590 if (!CI) { // Overdefined or unknown condition?
591 // All destinations are executable!
592 if (!SCValue.isUnknown())
593 Succs.assign(TI.getNumSuccessors(), true);
597 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
601 // In case of indirect branch and its address is a blockaddress, we mark
602 // the target as executable.
603 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
604 // Casts are folded by visitCastInst.
605 LatticeVal IBRValue = getValueState(IBR->getAddress());
606 BlockAddress *Addr = IBRValue.getBlockAddress();
607 if (!Addr) { // Overdefined or unknown condition?
608 // All destinations are executable!
609 if (!IBRValue.isUnknown())
610 Succs.assign(TI.getNumSuccessors(), true);
614 BasicBlock* T = Addr->getBasicBlock();
615 assert(Addr->getFunction() == T->getParent() &&
616 "Block address of a different function ?");
617 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
618 // This is the target.
619 if (IBR->getDestination(i) == T) {
625 // If we didn't find our destination in the IBR successor list, then we
626 // have undefined behavior. Its ok to assume no successor is executable.
630 DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
631 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
635 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
636 // block to the 'To' basic block is currently feasible.
638 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
639 assert(BBExecutable.count(To) && "Dest should always be alive!");
641 // Make sure the source basic block is executable!!
642 if (!BBExecutable.count(From)) return false;
644 // Check to make sure this edge itself is actually feasible now.
645 TerminatorInst *TI = From->getTerminator();
646 if (auto *BI = dyn_cast<BranchInst>(TI)) {
647 if (BI->isUnconditional())
650 LatticeVal BCValue = getValueState(BI->getCondition());
652 // Overdefined condition variables mean the branch could go either way,
653 // undef conditions mean that neither edge is feasible yet.
654 ConstantInt *CI = BCValue.getConstantInt();
656 return !BCValue.isUnknown();
658 // Constant condition variables mean the branch can only go a single way.
659 return BI->getSuccessor(CI->isZero()) == To;
662 // Unwinding instructions successors are always executable.
663 if (TI->isExceptional())
666 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
667 if (SI->getNumCases() < 1)
670 LatticeVal SCValue = getValueState(SI->getCondition());
671 ConstantInt *CI = SCValue.getConstantInt();
674 return !SCValue.isUnknown();
676 return SI->findCaseValue(CI)->getCaseSuccessor() == To;
679 // In case of indirect branch and its address is a blockaddress, we mark
680 // the target as executable.
681 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
682 LatticeVal IBRValue = getValueState(IBR->getAddress());
683 BlockAddress *Addr = IBRValue.getBlockAddress();
686 return !IBRValue.isUnknown();
688 // At this point, the indirectbr is branching on a blockaddress.
689 return Addr->getBasicBlock() == To;
692 DEBUG(dbgs() << "Unknown terminator instruction: " << *TI << '\n');
693 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
696 // visit Implementations - Something changed in this instruction, either an
697 // operand made a transition, or the instruction is newly executable. Change
698 // the value type of I to reflect these changes if appropriate. This method
699 // makes sure to do the following actions:
701 // 1. If a phi node merges two constants in, and has conflicting value coming
702 // from different branches, or if the PHI node merges in an overdefined
703 // value, then the PHI node becomes overdefined.
704 // 2. If a phi node merges only constants in, and they all agree on value, the
705 // PHI node becomes a constant value equal to that.
706 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
707 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
708 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
709 // 6. If a conditional branch has a value that is constant, make the selected
710 // destination executable
711 // 7. If a conditional branch has a value that is overdefined, make all
712 // successors executable.
714 void SCCPSolver::visitPHINode(PHINode &PN) {
715 // If this PN returns a struct, just mark the result overdefined.
716 // TODO: We could do a lot better than this if code actually uses this.
717 if (PN.getType()->isStructTy())
718 return markOverdefined(&PN);
720 if (getValueState(&PN).isOverdefined())
721 return; // Quick exit
723 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
724 // and slow us down a lot. Just mark them overdefined.
725 if (PN.getNumIncomingValues() > 64)
726 return markOverdefined(&PN);
728 // Look at all of the executable operands of the PHI node. If any of them
729 // are overdefined, the PHI becomes overdefined as well. If they are all
730 // constant, and they agree with each other, the PHI becomes the identical
731 // constant. If they are constant and don't agree, the PHI is overdefined.
732 // If there are no executable operands, the PHI remains unknown.
734 Constant *OperandVal = nullptr;
735 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
736 LatticeVal IV = getValueState(PN.getIncomingValue(i));
737 if (IV.isUnknown()) continue; // Doesn't influence PHI node.
739 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
742 if (IV.isOverdefined()) // PHI node becomes overdefined!
743 return markOverdefined(&PN);
745 if (!OperandVal) { // Grab the first value.
746 OperandVal = IV.getConstant();
750 // There is already a reachable operand. If we conflict with it,
751 // then the PHI node becomes overdefined. If we agree with it, we
754 // Check to see if there are two different constants merging, if so, the PHI
755 // node is overdefined.
756 if (IV.getConstant() != OperandVal)
757 return markOverdefined(&PN);
760 // If we exited the loop, this means that the PHI node only has constant
761 // arguments that agree with each other(and OperandVal is the constant) or
762 // OperandVal is null because there are no defined incoming arguments. If
763 // this is the case, the PHI remains unknown.
766 markConstant(&PN, OperandVal); // Acquire operand value
769 void SCCPSolver::visitReturnInst(ReturnInst &I) {
770 if (I.getNumOperands() == 0) return; // ret void
772 Function *F = I.getParent()->getParent();
773 Value *ResultOp = I.getOperand(0);
775 // If we are tracking the return value of this function, merge it in.
776 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
777 DenseMap<Function*, LatticeVal>::iterator TFRVI =
778 TrackedRetVals.find(F);
779 if (TFRVI != TrackedRetVals.end()) {
780 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
785 // Handle functions that return multiple values.
786 if (!TrackedMultipleRetVals.empty()) {
787 if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
788 if (MRVFunctionsTracked.count(F))
789 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
790 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
791 getStructValueState(ResultOp, i));
796 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
797 SmallVector<bool, 16> SuccFeasible;
798 getFeasibleSuccessors(TI, SuccFeasible);
800 BasicBlock *BB = TI.getParent();
802 // Mark all feasible successors executable.
803 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
805 markEdgeExecutable(BB, TI.getSuccessor(i));
808 void SCCPSolver::visitCastInst(CastInst &I) {
809 LatticeVal OpSt = getValueState(I.getOperand(0));
810 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
812 else if (OpSt.isConstant()) {
813 // Fold the constant as we build.
814 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
816 if (isa<UndefValue>(C))
818 // Propagate constant value
824 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
825 // If this returns a struct, mark all elements over defined, we don't track
826 // structs in structs.
827 if (EVI.getType()->isStructTy())
828 return markOverdefined(&EVI);
830 // If this is extracting from more than one level of struct, we don't know.
831 if (EVI.getNumIndices() != 1)
832 return markOverdefined(&EVI);
834 Value *AggVal = EVI.getAggregateOperand();
835 if (AggVal->getType()->isStructTy()) {
836 unsigned i = *EVI.idx_begin();
837 LatticeVal EltVal = getStructValueState(AggVal, i);
838 mergeInValue(getValueState(&EVI), &EVI, EltVal);
840 // Otherwise, must be extracting from an array.
841 return markOverdefined(&EVI);
845 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
846 auto *STy = dyn_cast<StructType>(IVI.getType());
848 return markOverdefined(&IVI);
850 // If this has more than one index, we can't handle it, drive all results to
852 if (IVI.getNumIndices() != 1)
853 return markOverdefined(&IVI);
855 Value *Aggr = IVI.getAggregateOperand();
856 unsigned Idx = *IVI.idx_begin();
858 // Compute the result based on what we're inserting.
859 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
860 // This passes through all values that aren't the inserted element.
862 LatticeVal EltVal = getStructValueState(Aggr, i);
863 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
867 Value *Val = IVI.getInsertedValueOperand();
868 if (Val->getType()->isStructTy())
869 // We don't track structs in structs.
870 markOverdefined(getStructValueState(&IVI, i), &IVI);
872 LatticeVal InVal = getValueState(Val);
873 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
878 void SCCPSolver::visitSelectInst(SelectInst &I) {
879 // If this select returns a struct, just mark the result overdefined.
880 // TODO: We could do a lot better than this if code actually uses this.
881 if (I.getType()->isStructTy())
882 return markOverdefined(&I);
884 LatticeVal CondValue = getValueState(I.getCondition());
885 if (CondValue.isUnknown())
888 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
889 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
890 mergeInValue(&I, getValueState(OpVal));
894 // Otherwise, the condition is overdefined or a constant we can't evaluate.
895 // See if we can produce something better than overdefined based on the T/F
897 LatticeVal TVal = getValueState(I.getTrueValue());
898 LatticeVal FVal = getValueState(I.getFalseValue());
900 // select ?, C, C -> C.
901 if (TVal.isConstant() && FVal.isConstant() &&
902 TVal.getConstant() == FVal.getConstant())
903 return markConstant(&I, FVal.getConstant());
905 if (TVal.isUnknown()) // select ?, undef, X -> X.
906 return mergeInValue(&I, FVal);
907 if (FVal.isUnknown()) // select ?, X, undef -> X.
908 return mergeInValue(&I, TVal);
912 // Handle Binary Operators.
913 void SCCPSolver::visitBinaryOperator(Instruction &I) {
914 LatticeVal V1State = getValueState(I.getOperand(0));
915 LatticeVal V2State = getValueState(I.getOperand(1));
917 LatticeVal &IV = ValueState[&I];
918 if (IV.isOverdefined()) return;
920 if (V1State.isConstant() && V2State.isConstant()) {
921 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
922 V2State.getConstant());
924 if (isa<UndefValue>(C))
926 return markConstant(IV, &I, C);
929 // If something is undef, wait for it to resolve.
930 if (!V1State.isOverdefined() && !V2State.isOverdefined())
933 // Otherwise, one of our operands is overdefined. Try to produce something
934 // better than overdefined with some tricks.
935 // If this is 0 / Y, it doesn't matter that the second operand is
936 // overdefined, and we can replace it with zero.
937 if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv)
938 if (V1State.isConstant() && V1State.getConstant()->isNullValue())
939 return markConstant(IV, &I, V1State.getConstant());
944 // it doesn't matter that the other operand is overdefined.
945 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul ||
946 I.getOpcode() == Instruction::Or) {
947 LatticeVal *NonOverdefVal = nullptr;
948 if (!V1State.isOverdefined())
949 NonOverdefVal = &V1State;
950 else if (!V2State.isOverdefined())
951 NonOverdefVal = &V2State;
954 if (NonOverdefVal->isUnknown())
957 if (I.getOpcode() == Instruction::And ||
958 I.getOpcode() == Instruction::Mul) {
961 if (NonOverdefVal->getConstant()->isNullValue())
962 return markConstant(IV, &I, NonOverdefVal->getConstant());
965 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
966 if (CI->isMinusOne())
967 return markConstant(IV, &I, NonOverdefVal->getConstant());
976 // Handle ICmpInst instruction.
977 void SCCPSolver::visitCmpInst(CmpInst &I) {
978 LatticeVal V1State = getValueState(I.getOperand(0));
979 LatticeVal V2State = getValueState(I.getOperand(1));
981 LatticeVal &IV = ValueState[&I];
982 if (IV.isOverdefined()) return;
984 if (V1State.isConstant() && V2State.isConstant()) {
985 Constant *C = ConstantExpr::getCompare(
986 I.getPredicate(), V1State.getConstant(), V2State.getConstant());
987 if (isa<UndefValue>(C))
989 return markConstant(IV, &I, C);
992 // If operands are still unknown, wait for it to resolve.
993 if (!V1State.isOverdefined() && !V2State.isOverdefined())
999 // Handle getelementptr instructions. If all operands are constants then we
1000 // can turn this into a getelementptr ConstantExpr.
1002 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1003 if (ValueState[&I].isOverdefined()) return;
1005 SmallVector<Constant*, 8> Operands;
1006 Operands.reserve(I.getNumOperands());
1008 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1009 LatticeVal State = getValueState(I.getOperand(i));
1010 if (State.isUnknown())
1011 return; // Operands are not resolved yet.
1013 if (State.isOverdefined())
1014 return markOverdefined(&I);
1016 assert(State.isConstant() && "Unknown state!");
1017 Operands.push_back(State.getConstant());
1020 Constant *Ptr = Operands[0];
1021 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
1023 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1024 if (isa<UndefValue>(C))
1026 markConstant(&I, C);
1029 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1030 // If this store is of a struct, ignore it.
1031 if (SI.getOperand(0)->getType()->isStructTy())
1034 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1037 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1038 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1039 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1041 // Get the value we are storing into the global, then merge it.
1042 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1043 if (I->second.isOverdefined())
1044 TrackedGlobals.erase(I); // No need to keep tracking this!
1048 // Handle load instructions. If the operand is a constant pointer to a constant
1049 // global, we can replace the load with the loaded constant value!
1050 void SCCPSolver::visitLoadInst(LoadInst &I) {
1051 // If this load is of a struct, just mark the result overdefined.
1052 if (I.getType()->isStructTy())
1053 return markOverdefined(&I);
1055 LatticeVal PtrVal = getValueState(I.getOperand(0));
1056 if (PtrVal.isUnknown()) return; // The pointer is not resolved yet!
1058 LatticeVal &IV = ValueState[&I];
1059 if (IV.isOverdefined()) return;
1061 if (!PtrVal.isConstant() || I.isVolatile())
1062 return markOverdefined(IV, &I);
1064 Constant *Ptr = PtrVal.getConstant();
1066 // load null is undefined.
1067 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1070 // Transform load (constant global) into the value loaded.
1071 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1072 if (!TrackedGlobals.empty()) {
1073 // If we are tracking this global, merge in the known value for it.
1074 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1075 TrackedGlobals.find(GV);
1076 if (It != TrackedGlobals.end()) {
1077 mergeInValue(IV, &I, It->second);
1083 // Transform load from a constant into a constant if possible.
1084 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
1085 if (isa<UndefValue>(C))
1087 return markConstant(IV, &I, C);
1090 // Otherwise we cannot say for certain what value this load will produce.
1092 markOverdefined(IV, &I);
1095 void SCCPSolver::visitCallSite(CallSite CS) {
1096 Function *F = CS.getCalledFunction();
1097 Instruction *I = CS.getInstruction();
1099 // The common case is that we aren't tracking the callee, either because we
1100 // are not doing interprocedural analysis or the callee is indirect, or is
1101 // external. Handle these cases first.
1102 if (!F || F->isDeclaration()) {
1104 // Void return and not tracking callee, just bail.
1105 if (I->getType()->isVoidTy()) return;
1107 // Otherwise, if we have a single return value case, and if the function is
1108 // a declaration, maybe we can constant fold it.
1109 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1110 canConstantFoldCallTo(CS, F)) {
1112 SmallVector<Constant*, 8> Operands;
1113 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1115 LatticeVal State = getValueState(*AI);
1117 if (State.isUnknown())
1118 return; // Operands are not resolved yet.
1119 if (State.isOverdefined())
1120 return markOverdefined(I);
1121 assert(State.isConstant() && "Unknown state!");
1122 Operands.push_back(State.getConstant());
1125 if (getValueState(I).isOverdefined())
1128 // If we can constant fold this, mark the result of the call as a
1130 if (Constant *C = ConstantFoldCall(CS, F, Operands, TLI)) {
1132 if (isa<UndefValue>(C))
1134 return markConstant(I, C);
1138 // Otherwise, we don't know anything about this call, mark it overdefined.
1139 return markOverdefined(I);
1142 // If this is a local function that doesn't have its address taken, mark its
1143 // entry block executable and merge in the actual arguments to the call into
1144 // the formal arguments of the function.
1145 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1146 MarkBlockExecutable(&F->front());
1148 // Propagate information from this call site into the callee.
1149 CallSite::arg_iterator CAI = CS.arg_begin();
1150 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1151 AI != E; ++AI, ++CAI) {
1152 // If this argument is byval, and if the function is not readonly, there
1153 // will be an implicit copy formed of the input aggregate.
1154 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1155 markOverdefined(&*AI);
1159 if (auto *STy = dyn_cast<StructType>(AI->getType())) {
1160 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1161 LatticeVal CallArg = getStructValueState(*CAI, i);
1162 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
1165 mergeInValue(&*AI, getValueState(*CAI));
1170 // If this is a single/zero retval case, see if we're tracking the function.
1171 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
1172 if (!MRVFunctionsTracked.count(F))
1173 goto CallOverdefined; // Not tracking this callee.
1175 // If we are tracking this callee, propagate the result of the function
1176 // into this call site.
1177 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1178 mergeInValue(getStructValueState(I, i), I,
1179 TrackedMultipleRetVals[std::make_pair(F, i)]);
1181 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1182 if (TFRVI == TrackedRetVals.end())
1183 goto CallOverdefined; // Not tracking this callee.
1185 // If so, propagate the return value of the callee into this call result.
1186 mergeInValue(I, TFRVI->second);
1190 void SCCPSolver::Solve() {
1191 // Process the work lists until they are empty!
1192 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1193 !OverdefinedInstWorkList.empty()) {
1194 // Process the overdefined instruction's work list first, which drives other
1195 // things to overdefined more quickly.
1196 while (!OverdefinedInstWorkList.empty()) {
1197 Value *I = OverdefinedInstWorkList.pop_back_val();
1199 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1201 // "I" got into the work list because it either made the transition from
1202 // bottom to constant, or to overdefined.
1204 // Anything on this worklist that is overdefined need not be visited
1205 // since all of its users will have already been marked as overdefined
1206 // Update all of the users of this instruction's value.
1208 for (User *U : I->users())
1209 if (auto *UI = dyn_cast<Instruction>(U))
1210 OperandChangedState(UI);
1213 // Process the instruction work list.
1214 while (!InstWorkList.empty()) {
1215 Value *I = InstWorkList.pop_back_val();
1217 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1219 // "I" got into the work list because it made the transition from undef to
1222 // Anything on this worklist that is overdefined need not be visited
1223 // since all of its users will have already been marked as overdefined.
1224 // Update all of the users of this instruction's value.
1226 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1227 for (User *U : I->users())
1228 if (auto *UI = dyn_cast<Instruction>(U))
1229 OperandChangedState(UI);
1232 // Process the basic block work list.
1233 while (!BBWorkList.empty()) {
1234 BasicBlock *BB = BBWorkList.back();
1235 BBWorkList.pop_back();
1237 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1239 // Notify all instructions in this basic block that they are newly
1246 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1247 /// that branches on undef values cannot reach any of their successors.
1248 /// However, this is not a safe assumption. After we solve dataflow, this
1249 /// method should be use to handle this. If this returns true, the solver
1250 /// should be rerun.
1252 /// This method handles this by finding an unresolved branch and marking it one
1253 /// of the edges from the block as being feasible, even though the condition
1254 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1255 /// CFG and only slightly pessimizes the analysis results (by marking one,
1256 /// potentially infeasible, edge feasible). This cannot usefully modify the
1257 /// constraints on the condition of the branch, as that would impact other users
1260 /// This scan also checks for values that use undefs, whose results are actually
1261 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1262 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1263 /// even if X isn't defined.
1264 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1265 for (BasicBlock &BB : F) {
1266 if (!BBExecutable.count(&BB))
1269 for (Instruction &I : BB) {
1270 // Look for instructions which produce undef values.
1271 if (I.getType()->isVoidTy()) continue;
1273 if (auto *STy = dyn_cast<StructType>(I.getType())) {
1274 // Only a few things that can be structs matter for undef.
1276 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1277 if (CallSite CS = CallSite(&I))
1278 if (Function *F = CS.getCalledFunction())
1279 if (MRVFunctionsTracked.count(F))
1282 // extractvalue and insertvalue don't need to be marked; they are
1283 // tracked as precisely as their operands.
1284 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1287 // Send the results of everything else to overdefined. We could be
1288 // more precise than this but it isn't worth bothering.
1289 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1290 LatticeVal &LV = getStructValueState(&I, i);
1292 markOverdefined(LV, &I);
1297 LatticeVal &LV = getValueState(&I);
1298 if (!LV.isUnknown()) continue;
1300 // extractvalue is safe; check here because the argument is a struct.
1301 if (isa<ExtractValueInst>(I))
1304 // Compute the operand LatticeVals, for convenience below.
1305 // Anything taking a struct is conservatively assumed to require
1306 // overdefined markings.
1307 if (I.getOperand(0)->getType()->isStructTy()) {
1308 markOverdefined(&I);
1311 LatticeVal Op0LV = getValueState(I.getOperand(0));
1313 if (I.getNumOperands() == 2) {
1314 if (I.getOperand(1)->getType()->isStructTy()) {
1315 markOverdefined(&I);
1319 Op1LV = getValueState(I.getOperand(1));
1321 // If this is an instructions whose result is defined even if the input is
1322 // not fully defined, propagate the information.
1323 Type *ITy = I.getType();
1324 switch (I.getOpcode()) {
1325 case Instruction::Add:
1326 case Instruction::Sub:
1327 case Instruction::Trunc:
1328 case Instruction::FPTrunc:
1329 case Instruction::BitCast:
1330 break; // Any undef -> undef
1331 case Instruction::FSub:
1332 case Instruction::FAdd:
1333 case Instruction::FMul:
1334 case Instruction::FDiv:
1335 case Instruction::FRem:
1336 // Floating-point binary operation: be conservative.
1337 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1338 markForcedConstant(&I, Constant::getNullValue(ITy));
1340 markOverdefined(&I);
1342 case Instruction::ZExt:
1343 case Instruction::SExt:
1344 case Instruction::FPToUI:
1345 case Instruction::FPToSI:
1346 case Instruction::FPExt:
1347 case Instruction::PtrToInt:
1348 case Instruction::IntToPtr:
1349 case Instruction::SIToFP:
1350 case Instruction::UIToFP:
1351 // undef -> 0; some outputs are impossible
1352 markForcedConstant(&I, Constant::getNullValue(ITy));
1354 case Instruction::Mul:
1355 case Instruction::And:
1356 // Both operands undef -> undef
1357 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1359 // undef * X -> 0. X could be zero.
1360 // undef & X -> 0. X could be zero.
1361 markForcedConstant(&I, Constant::getNullValue(ITy));
1364 case Instruction::Or:
1365 // Both operands undef -> undef
1366 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1368 // undef | X -> -1. X could be -1.
1369 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
1372 case Instruction::Xor:
1373 // undef ^ undef -> 0; strictly speaking, this is not strictly
1374 // necessary, but we try to be nice to people who expect this
1375 // behavior in simple cases
1376 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
1377 markForcedConstant(&I, Constant::getNullValue(ITy));
1380 // undef ^ X -> undef
1383 case Instruction::SDiv:
1384 case Instruction::UDiv:
1385 case Instruction::SRem:
1386 case Instruction::URem:
1387 // X / undef -> undef. No change.
1388 // X % undef -> undef. No change.
1389 if (Op1LV.isUnknown()) break;
1391 // X / 0 -> undef. No change.
1392 // X % 0 -> undef. No change.
1393 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1396 // undef / X -> 0. X could be maxint.
1397 // undef % X -> 0. X could be 1.
1398 markForcedConstant(&I, Constant::getNullValue(ITy));
1401 case Instruction::AShr:
1402 // X >>a undef -> undef.
1403 if (Op1LV.isUnknown()) break;
1405 // Shifting by the bitwidth or more is undefined.
1406 if (Op1LV.isConstant()) {
1407 if (auto *ShiftAmt = Op1LV.getConstantInt())
1408 if (ShiftAmt->getLimitedValue() >=
1409 ShiftAmt->getType()->getScalarSizeInBits())
1414 markForcedConstant(&I, Constant::getNullValue(ITy));
1416 case Instruction::LShr:
1417 case Instruction::Shl:
1418 // X << undef -> undef.
1419 // X >> undef -> undef.
1420 if (Op1LV.isUnknown()) break;
1422 // Shifting by the bitwidth or more is undefined.
1423 if (Op1LV.isConstant()) {
1424 if (auto *ShiftAmt = Op1LV.getConstantInt())
1425 if (ShiftAmt->getLimitedValue() >=
1426 ShiftAmt->getType()->getScalarSizeInBits())
1432 markForcedConstant(&I, Constant::getNullValue(ITy));
1434 case Instruction::Select:
1435 Op1LV = getValueState(I.getOperand(1));
1436 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1437 if (Op0LV.isUnknown()) {
1438 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1439 Op1LV = getValueState(I.getOperand(2));
1440 } else if (Op1LV.isUnknown()) {
1441 // c ? undef : undef -> undef. No change.
1442 Op1LV = getValueState(I.getOperand(2));
1443 if (Op1LV.isUnknown())
1445 // Otherwise, c ? undef : x -> x.
1447 // Leave Op1LV as Operand(1)'s LatticeValue.
1450 if (Op1LV.isConstant())
1451 markForcedConstant(&I, Op1LV.getConstant());
1453 markOverdefined(&I);
1455 case Instruction::Load:
1456 // A load here means one of two things: a load of undef from a global,
1457 // a load from an unknown pointer. Either way, having it return undef
1460 case Instruction::ICmp:
1461 // X == undef -> undef. Other comparisons get more complicated.
1462 if (cast<ICmpInst>(&I)->isEquality())
1464 markOverdefined(&I);
1466 case Instruction::Call:
1467 case Instruction::Invoke: {
1468 // There are two reasons a call can have an undef result
1469 // 1. It could be tracked.
1470 // 2. It could be constant-foldable.
1471 // Because of the way we solve return values, tracked calls must
1472 // never be marked overdefined in ResolvedUndefsIn.
1473 if (Function *F = CallSite(&I).getCalledFunction())
1474 if (TrackedRetVals.count(F))
1477 // If the call is constant-foldable, we mark it overdefined because
1478 // we do not know what return values are valid.
1479 markOverdefined(&I);
1483 // If we don't know what should happen here, conservatively mark it
1485 markOverdefined(&I);
1490 // Check to see if we have a branch or switch on an undefined value. If so
1491 // we force the branch to go one way or the other to make the successor
1492 // values live. It doesn't really matter which way we force it.
1493 TerminatorInst *TI = BB.getTerminator();
1494 if (auto *BI = dyn_cast<BranchInst>(TI)) {
1495 if (!BI->isConditional()) continue;
1496 if (!getValueState(BI->getCondition()).isUnknown())
1499 // If the input to SCCP is actually branch on undef, fix the undef to
1501 if (isa<UndefValue>(BI->getCondition())) {
1502 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1503 markEdgeExecutable(&BB, TI->getSuccessor(1));
1507 // Otherwise, it is a branch on a symbolic value which is currently
1508 // considered to be undef. Handle this by forcing the input value to the
1510 markForcedConstant(BI->getCondition(),
1511 ConstantInt::getFalse(TI->getContext()));
1515 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1516 // Indirect branch with no successor ?. Its ok to assume it branches
1518 if (IBR->getNumSuccessors() < 1)
1521 if (!getValueState(IBR->getAddress()).isUnknown())
1524 // If the input to SCCP is actually branch on undef, fix the undef to
1525 // the first successor of the indirect branch.
1526 if (isa<UndefValue>(IBR->getAddress())) {
1527 IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
1528 markEdgeExecutable(&BB, IBR->getSuccessor(0));
1532 // Otherwise, it is a branch on a symbolic value which is currently
1533 // considered to be undef. Handle this by forcing the input value to the
1534 // branch to the first successor.
1535 markForcedConstant(IBR->getAddress(),
1536 BlockAddress::get(IBR->getSuccessor(0)));
1540 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1541 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
1544 // If the input to SCCP is actually switch on undef, fix the undef to
1545 // the first constant.
1546 if (isa<UndefValue>(SI->getCondition())) {
1547 SI->setCondition(SI->case_begin()->getCaseValue());
1548 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
1552 markForcedConstant(SI->getCondition(), SI->case_begin()->getCaseValue());
1560 static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
1561 Constant *Const = nullptr;
1562 if (V->getType()->isStructTy()) {
1563 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
1564 if (any_of(IVs, [](const LatticeVal &LV) { return LV.isOverdefined(); }))
1566 std::vector<Constant *> ConstVals;
1567 auto *ST = dyn_cast<StructType>(V->getType());
1568 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1569 LatticeVal V = IVs[i];
1570 ConstVals.push_back(V.isConstant()
1572 : UndefValue::get(ST->getElementType(i)));
1574 Const = ConstantStruct::get(ST, ConstVals);
1576 LatticeVal IV = Solver.getLatticeValueFor(V);
1577 if (IV.isOverdefined())
1579 Const = IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
1581 assert(Const && "Constant is nullptr here!");
1582 DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n');
1584 // Replaces all of the uses of a variable with uses of the constant.
1585 V->replaceAllUsesWith(Const);
1589 // runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
1590 // and return true if the function was modified.
1592 static bool runSCCP(Function &F, const DataLayout &DL,
1593 const TargetLibraryInfo *TLI) {
1594 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1595 SCCPSolver Solver(DL, TLI);
1597 // Mark the first block of the function as being executable.
1598 Solver.MarkBlockExecutable(&F.front());
1600 // Mark all arguments to the function as being overdefined.
1601 for (Argument &AI : F.args())
1602 Solver.markOverdefined(&AI);
1604 // Solve for constants.
1605 bool ResolvedUndefs = true;
1606 while (ResolvedUndefs) {
1608 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1609 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1612 bool MadeChanges = false;
1614 // If we decided that there are basic blocks that are dead in this function,
1615 // delete their contents now. Note that we cannot actually delete the blocks,
1616 // as we cannot modify the CFG of the function.
1618 for (BasicBlock &BB : F) {
1619 if (!Solver.isBlockExecutable(&BB)) {
1620 DEBUG(dbgs() << " BasicBlock Dead:" << BB);
1623 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
1629 // Iterate over all of the instructions in a function, replacing them with
1630 // constants if we have found them to be of constant values.
1632 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
1633 Instruction *Inst = &*BI++;
1634 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1637 if (tryToReplaceWithConstant(Solver, Inst)) {
1638 if (isInstructionTriviallyDead(Inst))
1639 Inst->eraseFromParent();
1640 // Hey, we just changed something!
1650 PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
1651 const DataLayout &DL = F.getParent()->getDataLayout();
1652 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1653 if (!runSCCP(F, DL, &TLI))
1654 return PreservedAnalyses::all();
1656 auto PA = PreservedAnalyses();
1657 PA.preserve<GlobalsAA>();
1662 //===--------------------------------------------------------------------===//
1664 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1665 /// Sparse Conditional Constant Propagator.
1667 class SCCPLegacyPass : public FunctionPass {
1669 void getAnalysisUsage(AnalysisUsage &AU) const override {
1670 AU.addRequired<TargetLibraryInfoWrapperPass>();
1671 AU.addPreserved<GlobalsAAWrapperPass>();
1673 static char ID; // Pass identification, replacement for typeid
1674 SCCPLegacyPass() : FunctionPass(ID) {
1675 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1678 // runOnFunction - Run the Sparse Conditional Constant Propagation
1679 // algorithm, and return true if the function was modified.
1681 bool runOnFunction(Function &F) override {
1682 if (skipFunction(F))
1684 const DataLayout &DL = F.getParent()->getDataLayout();
1685 const TargetLibraryInfo *TLI =
1686 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1687 return runSCCP(F, DL, TLI);
1690 } // end anonymous namespace
1692 char SCCPLegacyPass::ID = 0;
1693 INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1694 "Sparse Conditional Constant Propagation", false, false)
1695 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1696 INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1697 "Sparse Conditional Constant Propagation", false, false)
1699 // createSCCPPass - This is the public interface to this file.
1700 FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1702 static bool AddressIsTaken(const GlobalValue *GV) {
1703 // Delete any dead constantexpr klingons.
1704 GV->removeDeadConstantUsers();
1706 for (const Use &U : GV->uses()) {
1707 const User *UR = U.getUser();
1708 if (const auto *SI = dyn_cast<StoreInst>(UR)) {
1709 if (SI->getOperand(0) == GV || SI->isVolatile())
1710 return true; // Storing addr of GV.
1711 } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
1712 // Make sure we are calling the function, not passing the address.
1713 ImmutableCallSite CS(cast<Instruction>(UR));
1714 if (!CS.isCallee(&U))
1716 } else if (const auto *LI = dyn_cast<LoadInst>(UR)) {
1717 if (LI->isVolatile())
1719 } else if (isa<BlockAddress>(UR)) {
1720 // blockaddress doesn't take the address of the function, it takes addr
1729 static void findReturnsToZap(Function &F,
1730 SmallPtrSet<Function *, 32> &AddressTakenFunctions,
1731 SmallVector<ReturnInst *, 8> &ReturnsToZap) {
1732 // We can only do this if we know that nothing else can call the function.
1733 if (!F.hasLocalLinkage() || AddressTakenFunctions.count(&F))
1736 for (BasicBlock &BB : F)
1737 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1738 if (!isa<UndefValue>(RI->getOperand(0)))
1739 ReturnsToZap.push_back(RI);
1742 static bool runIPSCCP(Module &M, const DataLayout &DL,
1743 const TargetLibraryInfo *TLI) {
1744 SCCPSolver Solver(DL, TLI);
1746 // AddressTakenFunctions - This set keeps track of the address-taken functions
1747 // that are in the input. As IPSCCP runs through and simplifies code,
1748 // functions that were address taken can end up losing their
1749 // address-taken-ness. Because of this, we keep track of their addresses from
1750 // the first pass so we can use them for the later simplification pass.
1751 SmallPtrSet<Function*, 32> AddressTakenFunctions;
1753 // Loop over all functions, marking arguments to those with their addresses
1754 // taken or that are external as overdefined.
1756 for (Function &F : M) {
1757 if (F.isDeclaration())
1760 // If this is an exact definition of this function, then we can propagate
1761 // information about its result into callsites of it.
1762 // Don't touch naked functions. They may contain asm returning a
1763 // value we don't see, so we may end up interprocedurally propagating
1764 // the return value incorrectly.
1765 if (F.hasExactDefinition() && !F.hasFnAttribute(Attribute::Naked))
1766 Solver.AddTrackedFunction(&F);
1768 // If this function only has direct calls that we can see, we can track its
1769 // arguments and return value aggressively, and can assume it is not called
1770 // unless we see evidence to the contrary.
1771 if (F.hasLocalLinkage()) {
1772 if (F.hasAddressTaken()) {
1773 AddressTakenFunctions.insert(&F);
1776 Solver.AddArgumentTrackedFunction(&F);
1781 // Assume the function is called.
1782 Solver.MarkBlockExecutable(&F.front());
1784 // Assume nothing about the incoming arguments.
1785 for (Argument &AI : F.args())
1786 Solver.markOverdefined(&AI);
1789 // Loop over global variables. We inform the solver about any internal global
1790 // variables that do not have their 'addresses taken'. If they don't have
1791 // their addresses taken, we can propagate constants through them.
1792 for (GlobalVariable &G : M.globals())
1793 if (!G.isConstant() && G.hasLocalLinkage() &&
1794 G.hasDefinitiveInitializer() && !AddressIsTaken(&G))
1795 Solver.TrackValueOfGlobalVariable(&G);
1797 // Solve for constants.
1798 bool ResolvedUndefs = true;
1799 while (ResolvedUndefs) {
1802 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1803 ResolvedUndefs = false;
1804 for (Function &F : M)
1805 ResolvedUndefs |= Solver.ResolvedUndefsIn(F);
1808 bool MadeChanges = false;
1810 // Iterate over all of the instructions in the module, replacing them with
1811 // constants if we have found them to be of constant values.
1813 SmallVector<BasicBlock*, 512> BlocksToErase;
1815 for (Function &F : M) {
1816 if (F.isDeclaration())
1819 if (Solver.isBlockExecutable(&F.front()))
1820 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
1822 if (!AI->use_empty() && tryToReplaceWithConstant(Solver, &*AI))
1825 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1826 if (!Solver.isBlockExecutable(&*BB)) {
1827 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1831 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false);
1835 if (&*BB != &F.front())
1836 BlocksToErase.push_back(&*BB);
1840 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1841 Instruction *Inst = &*BI++;
1842 if (Inst->getType()->isVoidTy())
1844 if (tryToReplaceWithConstant(Solver, Inst)) {
1845 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1846 Inst->eraseFromParent();
1847 // Hey, we just changed something!
1854 // Now that all instructions in the function are constant folded, erase dead
1855 // blocks, because we can now use ConstantFoldTerminator to get rid of
1857 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1858 // If there are any PHI nodes in this successor, drop entries for BB now.
1859 BasicBlock *DeadBB = BlocksToErase[i];
1860 for (Value::user_iterator UI = DeadBB->user_begin(),
1861 UE = DeadBB->user_end();
1863 // Grab the user and then increment the iterator early, as the user
1864 // will be deleted. Step past all adjacent uses from the same user.
1865 auto *I = dyn_cast<Instruction>(*UI);
1866 do { ++UI; } while (UI != UE && *UI == I);
1868 // Ignore blockaddress users; BasicBlock's dtor will handle them.
1871 bool Folded = ConstantFoldTerminator(I->getParent());
1873 "Expect TermInst on constantint or blockaddress to be folded");
1877 // Finally, delete the basic block.
1878 F.getBasicBlockList().erase(DeadBB);
1880 BlocksToErase.clear();
1883 // If we inferred constant or undef return values for a function, we replaced
1884 // all call uses with the inferred value. This means we don't need to bother
1885 // actually returning anything from the function. Replace all return
1886 // instructions with return undef.
1888 // Do this in two stages: first identify the functions we should process, then
1889 // actually zap their returns. This is important because we can only do this
1890 // if the address of the function isn't taken. In cases where a return is the
1891 // last use of a function, the order of processing functions would affect
1892 // whether other functions are optimizable.
1893 SmallVector<ReturnInst*, 8> ReturnsToZap;
1895 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1896 for (const auto &I : RV) {
1897 Function *F = I.first;
1898 if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
1900 findReturnsToZap(*F, AddressTakenFunctions, ReturnsToZap);
1903 for (const auto &F : Solver.getMRVFunctionsTracked()) {
1904 assert(F->getReturnType()->isStructTy() &&
1905 "The return type should be a struct");
1906 StructType *STy = cast<StructType>(F->getReturnType());
1907 if (Solver.isStructLatticeConstant(F, STy))
1908 findReturnsToZap(*F, AddressTakenFunctions, ReturnsToZap);
1911 // Zap all returns which we've identified as zap to change.
1912 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1913 Function *F = ReturnsToZap[i]->getParent()->getParent();
1914 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1917 // If we inferred constant or undef values for globals variables, we can
1918 // delete the global and any stores that remain to it.
1919 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1920 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1921 E = TG.end(); I != E; ++I) {
1922 GlobalVariable *GV = I->first;
1923 assert(!I->second.isOverdefined() &&
1924 "Overdefined values should have been taken out of the map!");
1925 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1926 while (!GV->use_empty()) {
1927 StoreInst *SI = cast<StoreInst>(GV->user_back());
1928 SI->eraseFromParent();
1930 M.getGlobalList().erase(GV);
1937 PreservedAnalyses IPSCCPPass::run(Module &M, ModuleAnalysisManager &AM) {
1938 const DataLayout &DL = M.getDataLayout();
1939 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
1940 if (!runIPSCCP(M, DL, &TLI))
1941 return PreservedAnalyses::all();
1942 return PreservedAnalyses::none();
1946 //===--------------------------------------------------------------------===//
1948 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1949 /// Constant Propagation.
1951 class IPSCCPLegacyPass : public ModulePass {
1955 IPSCCPLegacyPass() : ModulePass(ID) {
1956 initializeIPSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1959 bool runOnModule(Module &M) override {
1962 const DataLayout &DL = M.getDataLayout();
1963 const TargetLibraryInfo *TLI =
1964 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1965 return runIPSCCP(M, DL, TLI);
1968 void getAnalysisUsage(AnalysisUsage &AU) const override {
1969 AU.addRequired<TargetLibraryInfoWrapperPass>();
1972 } // end anonymous namespace
1974 char IPSCCPLegacyPass::ID = 0;
1975 INITIALIZE_PASS_BEGIN(IPSCCPLegacyPass, "ipsccp",
1976 "Interprocedural Sparse Conditional Constant Propagation",
1978 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1979 INITIALIZE_PASS_END(IPSCCPLegacyPass, "ipsccp",
1980 "Interprocedural Sparse Conditional Constant Propagation",
1983 // createIPSCCPPass - This is the public interface to this file.
1984 ModulePass *llvm::createIPSCCPPass() { return new IPSCCPLegacyPass(); }