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 visitLandingPadInst(LandingPadInst &I) { markOverdefined(&I); }
519 void visitFuncletPadInst(FuncletPadInst &FPI) {
520 markOverdefined(&FPI);
522 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
523 markOverdefined(&CPI);
524 visitTerminatorInst(CPI);
527 // Instructions that cannot be folded away.
528 void visitStoreInst (StoreInst &I);
529 void visitLoadInst (LoadInst &I);
530 void visitGetElementPtrInst(GetElementPtrInst &I);
531 void visitCallInst (CallInst &I) {
534 void visitInvokeInst (InvokeInst &II) {
536 visitTerminatorInst(II);
538 void visitCallSite (CallSite CS);
539 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
540 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
541 void visitFenceInst (FenceInst &I) { /*returns void*/ }
542 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
545 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
546 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
547 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
549 void visitInstruction(Instruction &I) {
550 // If a new instruction is added to LLVM that we don't handle.
551 DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
552 markOverdefined(&I); // Just in case
556 } // end anonymous namespace
559 // getFeasibleSuccessors - Return a vector of booleans to indicate which
560 // successors are reachable from a given terminator instruction.
562 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
563 SmallVectorImpl<bool> &Succs) {
564 Succs.resize(TI.getNumSuccessors());
565 if (auto *BI = dyn_cast<BranchInst>(&TI)) {
566 if (BI->isUnconditional()) {
571 LatticeVal BCValue = getValueState(BI->getCondition());
572 ConstantInt *CI = BCValue.getConstantInt();
574 // Overdefined condition variables, and branches on unfoldable constant
575 // conditions, mean the branch could go either way.
576 if (!BCValue.isUnknown())
577 Succs[0] = Succs[1] = true;
581 // Constant condition variables mean the branch can only go a single way.
582 Succs[CI->isZero()] = true;
586 // Unwinding instructions successors are always executable.
587 if (TI.isExceptional()) {
588 Succs.assign(TI.getNumSuccessors(), true);
592 if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
593 if (!SI->getNumCases()) {
597 LatticeVal SCValue = getValueState(SI->getCondition());
598 ConstantInt *CI = SCValue.getConstantInt();
600 if (!CI) { // Overdefined or unknown condition?
601 // All destinations are executable!
602 if (!SCValue.isUnknown())
603 Succs.assign(TI.getNumSuccessors(), true);
607 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
611 // In case of indirect branch and its address is a blockaddress, we mark
612 // the target as executable.
613 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
614 // Casts are folded by visitCastInst.
615 LatticeVal IBRValue = getValueState(IBR->getAddress());
616 BlockAddress *Addr = IBRValue.getBlockAddress();
617 if (!Addr) { // Overdefined or unknown condition?
618 // All destinations are executable!
619 if (!IBRValue.isUnknown())
620 Succs.assign(TI.getNumSuccessors(), true);
624 BasicBlock* T = Addr->getBasicBlock();
625 assert(Addr->getFunction() == T->getParent() &&
626 "Block address of a different function ?");
627 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
628 // This is the target.
629 if (IBR->getDestination(i) == T) {
635 // If we didn't find our destination in the IBR successor list, then we
636 // have undefined behavior. Its ok to assume no successor is executable.
640 DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
641 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
645 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
646 // block to the 'To' basic block is currently feasible.
648 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
649 assert(BBExecutable.count(To) && "Dest should always be alive!");
651 // Make sure the source basic block is executable!!
652 if (!BBExecutable.count(From)) return false;
654 // Check to make sure this edge itself is actually feasible now.
655 TerminatorInst *TI = From->getTerminator();
656 if (auto *BI = dyn_cast<BranchInst>(TI)) {
657 if (BI->isUnconditional())
660 LatticeVal BCValue = getValueState(BI->getCondition());
662 // Overdefined condition variables mean the branch could go either way,
663 // undef conditions mean that neither edge is feasible yet.
664 ConstantInt *CI = BCValue.getConstantInt();
666 return !BCValue.isUnknown();
668 // Constant condition variables mean the branch can only go a single way.
669 return BI->getSuccessor(CI->isZero()) == To;
672 // Unwinding instructions successors are always executable.
673 if (TI->isExceptional())
676 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
677 if (SI->getNumCases() < 1)
680 LatticeVal SCValue = getValueState(SI->getCondition());
681 ConstantInt *CI = SCValue.getConstantInt();
684 return !SCValue.isUnknown();
686 return SI->findCaseValue(CI)->getCaseSuccessor() == To;
689 // In case of indirect branch and its address is a blockaddress, we mark
690 // the target as executable.
691 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
692 LatticeVal IBRValue = getValueState(IBR->getAddress());
693 BlockAddress *Addr = IBRValue.getBlockAddress();
696 return !IBRValue.isUnknown();
698 // At this point, the indirectbr is branching on a blockaddress.
699 return Addr->getBasicBlock() == To;
702 DEBUG(dbgs() << "Unknown terminator instruction: " << *TI << '\n');
703 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
706 // visit Implementations - Something changed in this instruction, either an
707 // operand made a transition, or the instruction is newly executable. Change
708 // the value type of I to reflect these changes if appropriate. This method
709 // makes sure to do the following actions:
711 // 1. If a phi node merges two constants in, and has conflicting value coming
712 // from different branches, or if the PHI node merges in an overdefined
713 // value, then the PHI node becomes overdefined.
714 // 2. If a phi node merges only constants in, and they all agree on value, the
715 // PHI node becomes a constant value equal to that.
716 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
717 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
718 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
719 // 6. If a conditional branch has a value that is constant, make the selected
720 // destination executable
721 // 7. If a conditional branch has a value that is overdefined, make all
722 // successors executable.
724 void SCCPSolver::visitPHINode(PHINode &PN) {
725 // If this PN returns a struct, just mark the result overdefined.
726 // TODO: We could do a lot better than this if code actually uses this.
727 if (PN.getType()->isStructTy())
728 return markOverdefined(&PN);
730 if (getValueState(&PN).isOverdefined())
731 return; // Quick exit
733 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
734 // and slow us down a lot. Just mark them overdefined.
735 if (PN.getNumIncomingValues() > 64)
736 return markOverdefined(&PN);
738 // Look at all of the executable operands of the PHI node. If any of them
739 // are overdefined, the PHI becomes overdefined as well. If they are all
740 // constant, and they agree with each other, the PHI becomes the identical
741 // constant. If they are constant and don't agree, the PHI is overdefined.
742 // If there are no executable operands, the PHI remains unknown.
744 Constant *OperandVal = nullptr;
745 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
746 LatticeVal IV = getValueState(PN.getIncomingValue(i));
747 if (IV.isUnknown()) continue; // Doesn't influence PHI node.
749 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
752 if (IV.isOverdefined()) // PHI node becomes overdefined!
753 return markOverdefined(&PN);
755 if (!OperandVal) { // Grab the first value.
756 OperandVal = IV.getConstant();
760 // There is already a reachable operand. If we conflict with it,
761 // then the PHI node becomes overdefined. If we agree with it, we
764 // Check to see if there are two different constants merging, if so, the PHI
765 // node is overdefined.
766 if (IV.getConstant() != OperandVal)
767 return markOverdefined(&PN);
770 // If we exited the loop, this means that the PHI node only has constant
771 // arguments that agree with each other(and OperandVal is the constant) or
772 // OperandVal is null because there are no defined incoming arguments. If
773 // this is the case, the PHI remains unknown.
776 markConstant(&PN, OperandVal); // Acquire operand value
779 void SCCPSolver::visitReturnInst(ReturnInst &I) {
780 if (I.getNumOperands() == 0) return; // ret void
782 Function *F = I.getParent()->getParent();
783 Value *ResultOp = I.getOperand(0);
785 // If we are tracking the return value of this function, merge it in.
786 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
787 DenseMap<Function*, LatticeVal>::iterator TFRVI =
788 TrackedRetVals.find(F);
789 if (TFRVI != TrackedRetVals.end()) {
790 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
795 // Handle functions that return multiple values.
796 if (!TrackedMultipleRetVals.empty()) {
797 if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
798 if (MRVFunctionsTracked.count(F))
799 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
800 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
801 getStructValueState(ResultOp, i));
806 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
807 SmallVector<bool, 16> SuccFeasible;
808 getFeasibleSuccessors(TI, SuccFeasible);
810 BasicBlock *BB = TI.getParent();
812 // Mark all feasible successors executable.
813 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
815 markEdgeExecutable(BB, TI.getSuccessor(i));
818 void SCCPSolver::visitCastInst(CastInst &I) {
819 LatticeVal OpSt = getValueState(I.getOperand(0));
820 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
822 else if (OpSt.isConstant()) {
823 // Fold the constant as we build.
824 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
826 if (isa<UndefValue>(C))
828 // Propagate constant value
834 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
835 // If this returns a struct, mark all elements over defined, we don't track
836 // structs in structs.
837 if (EVI.getType()->isStructTy())
838 return markOverdefined(&EVI);
840 // If this is extracting from more than one level of struct, we don't know.
841 if (EVI.getNumIndices() != 1)
842 return markOverdefined(&EVI);
844 Value *AggVal = EVI.getAggregateOperand();
845 if (AggVal->getType()->isStructTy()) {
846 unsigned i = *EVI.idx_begin();
847 LatticeVal EltVal = getStructValueState(AggVal, i);
848 mergeInValue(getValueState(&EVI), &EVI, EltVal);
850 // Otherwise, must be extracting from an array.
851 return markOverdefined(&EVI);
855 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
856 auto *STy = dyn_cast<StructType>(IVI.getType());
858 return markOverdefined(&IVI);
860 // If this has more than one index, we can't handle it, drive all results to
862 if (IVI.getNumIndices() != 1)
863 return markOverdefined(&IVI);
865 Value *Aggr = IVI.getAggregateOperand();
866 unsigned Idx = *IVI.idx_begin();
868 // Compute the result based on what we're inserting.
869 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
870 // This passes through all values that aren't the inserted element.
872 LatticeVal EltVal = getStructValueState(Aggr, i);
873 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
877 Value *Val = IVI.getInsertedValueOperand();
878 if (Val->getType()->isStructTy())
879 // We don't track structs in structs.
880 markOverdefined(getStructValueState(&IVI, i), &IVI);
882 LatticeVal InVal = getValueState(Val);
883 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
888 void SCCPSolver::visitSelectInst(SelectInst &I) {
889 // If this select returns a struct, just mark the result overdefined.
890 // TODO: We could do a lot better than this if code actually uses this.
891 if (I.getType()->isStructTy())
892 return markOverdefined(&I);
894 LatticeVal CondValue = getValueState(I.getCondition());
895 if (CondValue.isUnknown())
898 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
899 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
900 mergeInValue(&I, getValueState(OpVal));
904 // Otherwise, the condition is overdefined or a constant we can't evaluate.
905 // See if we can produce something better than overdefined based on the T/F
907 LatticeVal TVal = getValueState(I.getTrueValue());
908 LatticeVal FVal = getValueState(I.getFalseValue());
910 // select ?, C, C -> C.
911 if (TVal.isConstant() && FVal.isConstant() &&
912 TVal.getConstant() == FVal.getConstant())
913 return markConstant(&I, FVal.getConstant());
915 if (TVal.isUnknown()) // select ?, undef, X -> X.
916 return mergeInValue(&I, FVal);
917 if (FVal.isUnknown()) // select ?, X, undef -> X.
918 return mergeInValue(&I, TVal);
922 // Handle Binary Operators.
923 void SCCPSolver::visitBinaryOperator(Instruction &I) {
924 LatticeVal V1State = getValueState(I.getOperand(0));
925 LatticeVal V2State = getValueState(I.getOperand(1));
927 LatticeVal &IV = ValueState[&I];
928 if (IV.isOverdefined()) return;
930 if (V1State.isConstant() && V2State.isConstant()) {
931 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
932 V2State.getConstant());
934 if (isa<UndefValue>(C))
936 return markConstant(IV, &I, C);
939 // If something is undef, wait for it to resolve.
940 if (!V1State.isOverdefined() && !V2State.isOverdefined())
943 // Otherwise, one of our operands is overdefined. Try to produce something
944 // better than overdefined with some tricks.
945 // If this is 0 / Y, it doesn't matter that the second operand is
946 // overdefined, and we can replace it with zero.
947 if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv)
948 if (V1State.isConstant() && V1State.getConstant()->isNullValue())
949 return markConstant(IV, &I, V1State.getConstant());
954 // it doesn't matter that the other operand is overdefined.
955 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul ||
956 I.getOpcode() == Instruction::Or) {
957 LatticeVal *NonOverdefVal = nullptr;
958 if (!V1State.isOverdefined())
959 NonOverdefVal = &V1State;
960 else if (!V2State.isOverdefined())
961 NonOverdefVal = &V2State;
964 if (NonOverdefVal->isUnknown())
967 if (I.getOpcode() == Instruction::And ||
968 I.getOpcode() == Instruction::Mul) {
971 if (NonOverdefVal->getConstant()->isNullValue())
972 return markConstant(IV, &I, NonOverdefVal->getConstant());
975 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
976 if (CI->isAllOnesValue())
977 return markConstant(IV, &I, NonOverdefVal->getConstant());
986 // Handle ICmpInst instruction.
987 void SCCPSolver::visitCmpInst(CmpInst &I) {
988 LatticeVal V1State = getValueState(I.getOperand(0));
989 LatticeVal V2State = getValueState(I.getOperand(1));
991 LatticeVal &IV = ValueState[&I];
992 if (IV.isOverdefined()) return;
994 if (V1State.isConstant() && V2State.isConstant()) {
995 Constant *C = ConstantExpr::getCompare(
996 I.getPredicate(), V1State.getConstant(), V2State.getConstant());
997 if (isa<UndefValue>(C))
999 return markConstant(IV, &I, C);
1002 // If operands are still unknown, wait for it to resolve.
1003 if (!V1State.isOverdefined() && !V2State.isOverdefined())
1006 markOverdefined(&I);
1009 // Handle getelementptr instructions. If all operands are constants then we
1010 // can turn this into a getelementptr ConstantExpr.
1012 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1013 if (ValueState[&I].isOverdefined()) return;
1015 SmallVector<Constant*, 8> Operands;
1016 Operands.reserve(I.getNumOperands());
1018 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1019 LatticeVal State = getValueState(I.getOperand(i));
1020 if (State.isUnknown())
1021 return; // Operands are not resolved yet.
1023 if (State.isOverdefined())
1024 return markOverdefined(&I);
1026 assert(State.isConstant() && "Unknown state!");
1027 Operands.push_back(State.getConstant());
1030 Constant *Ptr = Operands[0];
1031 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
1033 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1034 if (isa<UndefValue>(C))
1036 markConstant(&I, C);
1039 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1040 // If this store is of a struct, ignore it.
1041 if (SI.getOperand(0)->getType()->isStructTy())
1044 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1047 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1048 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1049 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1051 // Get the value we are storing into the global, then merge it.
1052 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1053 if (I->second.isOverdefined())
1054 TrackedGlobals.erase(I); // No need to keep tracking this!
1058 // Handle load instructions. If the operand is a constant pointer to a constant
1059 // global, we can replace the load with the loaded constant value!
1060 void SCCPSolver::visitLoadInst(LoadInst &I) {
1061 // If this load is of a struct, just mark the result overdefined.
1062 if (I.getType()->isStructTy())
1063 return markOverdefined(&I);
1065 LatticeVal PtrVal = getValueState(I.getOperand(0));
1066 if (PtrVal.isUnknown()) return; // The pointer is not resolved yet!
1068 LatticeVal &IV = ValueState[&I];
1069 if (IV.isOverdefined()) return;
1071 if (!PtrVal.isConstant() || I.isVolatile())
1072 return markOverdefined(IV, &I);
1074 Constant *Ptr = PtrVal.getConstant();
1076 // load null is undefined.
1077 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1080 // Transform load (constant global) into the value loaded.
1081 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1082 if (!TrackedGlobals.empty()) {
1083 // If we are tracking this global, merge in the known value for it.
1084 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1085 TrackedGlobals.find(GV);
1086 if (It != TrackedGlobals.end()) {
1087 mergeInValue(IV, &I, It->second);
1093 // Transform load from a constant into a constant if possible.
1094 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
1095 if (isa<UndefValue>(C))
1097 return markConstant(IV, &I, C);
1100 // Otherwise we cannot say for certain what value this load will produce.
1102 markOverdefined(IV, &I);
1105 void SCCPSolver::visitCallSite(CallSite CS) {
1106 Function *F = CS.getCalledFunction();
1107 Instruction *I = CS.getInstruction();
1109 // The common case is that we aren't tracking the callee, either because we
1110 // are not doing interprocedural analysis or the callee is indirect, or is
1111 // external. Handle these cases first.
1112 if (!F || F->isDeclaration()) {
1114 // Void return and not tracking callee, just bail.
1115 if (I->getType()->isVoidTy()) return;
1117 // Otherwise, if we have a single return value case, and if the function is
1118 // a declaration, maybe we can constant fold it.
1119 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1120 canConstantFoldCallTo(F)) {
1122 SmallVector<Constant*, 8> Operands;
1123 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1125 LatticeVal State = getValueState(*AI);
1127 if (State.isUnknown())
1128 return; // Operands are not resolved yet.
1129 if (State.isOverdefined())
1130 return markOverdefined(I);
1131 assert(State.isConstant() && "Unknown state!");
1132 Operands.push_back(State.getConstant());
1135 if (getValueState(I).isOverdefined())
1138 // If we can constant fold this, mark the result of the call as a
1140 if (Constant *C = ConstantFoldCall(F, Operands, TLI)) {
1142 if (isa<UndefValue>(C))
1144 return markConstant(I, C);
1148 // Otherwise, we don't know anything about this call, mark it overdefined.
1149 return markOverdefined(I);
1152 // If this is a local function that doesn't have its address taken, mark its
1153 // entry block executable and merge in the actual arguments to the call into
1154 // the formal arguments of the function.
1155 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1156 MarkBlockExecutable(&F->front());
1158 // Propagate information from this call site into the callee.
1159 CallSite::arg_iterator CAI = CS.arg_begin();
1160 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1161 AI != E; ++AI, ++CAI) {
1162 // If this argument is byval, and if the function is not readonly, there
1163 // will be an implicit copy formed of the input aggregate.
1164 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1165 markOverdefined(&*AI);
1169 if (auto *STy = dyn_cast<StructType>(AI->getType())) {
1170 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1171 LatticeVal CallArg = getStructValueState(*CAI, i);
1172 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
1175 mergeInValue(&*AI, getValueState(*CAI));
1180 // If this is a single/zero retval case, see if we're tracking the function.
1181 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
1182 if (!MRVFunctionsTracked.count(F))
1183 goto CallOverdefined; // Not tracking this callee.
1185 // If we are tracking this callee, propagate the result of the function
1186 // into this call site.
1187 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1188 mergeInValue(getStructValueState(I, i), I,
1189 TrackedMultipleRetVals[std::make_pair(F, i)]);
1191 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1192 if (TFRVI == TrackedRetVals.end())
1193 goto CallOverdefined; // Not tracking this callee.
1195 // If so, propagate the return value of the callee into this call result.
1196 mergeInValue(I, TFRVI->second);
1200 void SCCPSolver::Solve() {
1201 // Process the work lists until they are empty!
1202 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1203 !OverdefinedInstWorkList.empty()) {
1204 // Process the overdefined instruction's work list first, which drives other
1205 // things to overdefined more quickly.
1206 while (!OverdefinedInstWorkList.empty()) {
1207 Value *I = OverdefinedInstWorkList.pop_back_val();
1209 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1211 // "I" got into the work list because it either made the transition from
1212 // bottom to constant, or to overdefined.
1214 // Anything on this worklist that is overdefined need not be visited
1215 // since all of its users will have already been marked as overdefined
1216 // Update all of the users of this instruction's value.
1218 for (User *U : I->users())
1219 if (auto *UI = dyn_cast<Instruction>(U))
1220 OperandChangedState(UI);
1223 // Process the instruction work list.
1224 while (!InstWorkList.empty()) {
1225 Value *I = InstWorkList.pop_back_val();
1227 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1229 // "I" got into the work list because it made the transition from undef to
1232 // Anything on this worklist that is overdefined need not be visited
1233 // since all of its users will have already been marked as overdefined.
1234 // Update all of the users of this instruction's value.
1236 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1237 for (User *U : I->users())
1238 if (auto *UI = dyn_cast<Instruction>(U))
1239 OperandChangedState(UI);
1242 // Process the basic block work list.
1243 while (!BBWorkList.empty()) {
1244 BasicBlock *BB = BBWorkList.back();
1245 BBWorkList.pop_back();
1247 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1249 // Notify all instructions in this basic block that they are newly
1256 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1257 /// that branches on undef values cannot reach any of their successors.
1258 /// However, this is not a safe assumption. After we solve dataflow, this
1259 /// method should be use to handle this. If this returns true, the solver
1260 /// should be rerun.
1262 /// This method handles this by finding an unresolved branch and marking it one
1263 /// of the edges from the block as being feasible, even though the condition
1264 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1265 /// CFG and only slightly pessimizes the analysis results (by marking one,
1266 /// potentially infeasible, edge feasible). This cannot usefully modify the
1267 /// constraints on the condition of the branch, as that would impact other users
1270 /// This scan also checks for values that use undefs, whose results are actually
1271 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1272 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1273 /// even if X isn't defined.
1274 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1275 for (BasicBlock &BB : F) {
1276 if (!BBExecutable.count(&BB))
1279 for (Instruction &I : BB) {
1280 // Look for instructions which produce undef values.
1281 if (I.getType()->isVoidTy()) continue;
1283 if (auto *STy = dyn_cast<StructType>(I.getType())) {
1284 // Only a few things that can be structs matter for undef.
1286 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1287 if (CallSite CS = CallSite(&I))
1288 if (Function *F = CS.getCalledFunction())
1289 if (MRVFunctionsTracked.count(F))
1292 // extractvalue and insertvalue don't need to be marked; they are
1293 // tracked as precisely as their operands.
1294 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1297 // Send the results of everything else to overdefined. We could be
1298 // more precise than this but it isn't worth bothering.
1299 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1300 LatticeVal &LV = getStructValueState(&I, i);
1302 markOverdefined(LV, &I);
1307 LatticeVal &LV = getValueState(&I);
1308 if (!LV.isUnknown()) continue;
1310 // extractvalue is safe; check here because the argument is a struct.
1311 if (isa<ExtractValueInst>(I))
1314 // Compute the operand LatticeVals, for convenience below.
1315 // Anything taking a struct is conservatively assumed to require
1316 // overdefined markings.
1317 if (I.getOperand(0)->getType()->isStructTy()) {
1318 markOverdefined(&I);
1321 LatticeVal Op0LV = getValueState(I.getOperand(0));
1323 if (I.getNumOperands() == 2) {
1324 if (I.getOperand(1)->getType()->isStructTy()) {
1325 markOverdefined(&I);
1329 Op1LV = getValueState(I.getOperand(1));
1331 // If this is an instructions whose result is defined even if the input is
1332 // not fully defined, propagate the information.
1333 Type *ITy = I.getType();
1334 switch (I.getOpcode()) {
1335 case Instruction::Add:
1336 case Instruction::Sub:
1337 case Instruction::Trunc:
1338 case Instruction::FPTrunc:
1339 case Instruction::BitCast:
1340 break; // Any undef -> undef
1341 case Instruction::FSub:
1342 case Instruction::FAdd:
1343 case Instruction::FMul:
1344 case Instruction::FDiv:
1345 case Instruction::FRem:
1346 // Floating-point binary operation: be conservative.
1347 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1348 markForcedConstant(&I, Constant::getNullValue(ITy));
1350 markOverdefined(&I);
1352 case Instruction::ZExt:
1353 case Instruction::SExt:
1354 case Instruction::FPToUI:
1355 case Instruction::FPToSI:
1356 case Instruction::FPExt:
1357 case Instruction::PtrToInt:
1358 case Instruction::IntToPtr:
1359 case Instruction::SIToFP:
1360 case Instruction::UIToFP:
1361 // undef -> 0; some outputs are impossible
1362 markForcedConstant(&I, Constant::getNullValue(ITy));
1364 case Instruction::Mul:
1365 case Instruction::And:
1366 // Both operands undef -> undef
1367 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1369 // undef * X -> 0. X could be zero.
1370 // undef & X -> 0. X could be zero.
1371 markForcedConstant(&I, Constant::getNullValue(ITy));
1374 case Instruction::Or:
1375 // Both operands undef -> undef
1376 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1378 // undef | X -> -1. X could be -1.
1379 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
1382 case Instruction::Xor:
1383 // undef ^ undef -> 0; strictly speaking, this is not strictly
1384 // necessary, but we try to be nice to people who expect this
1385 // behavior in simple cases
1386 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
1387 markForcedConstant(&I, Constant::getNullValue(ITy));
1390 // undef ^ X -> undef
1393 case Instruction::SDiv:
1394 case Instruction::UDiv:
1395 case Instruction::SRem:
1396 case Instruction::URem:
1397 // X / undef -> undef. No change.
1398 // X % undef -> undef. No change.
1399 if (Op1LV.isUnknown()) break;
1401 // X / 0 -> undef. No change.
1402 // X % 0 -> undef. No change.
1403 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1406 // undef / X -> 0. X could be maxint.
1407 // undef % X -> 0. X could be 1.
1408 markForcedConstant(&I, Constant::getNullValue(ITy));
1411 case Instruction::AShr:
1412 // X >>a undef -> undef.
1413 if (Op1LV.isUnknown()) break;
1415 // Shifting by the bitwidth or more is undefined.
1416 if (Op1LV.isConstant()) {
1417 if (auto *ShiftAmt = Op1LV.getConstantInt())
1418 if (ShiftAmt->getLimitedValue() >=
1419 ShiftAmt->getType()->getScalarSizeInBits())
1424 markForcedConstant(&I, Constant::getNullValue(ITy));
1426 case Instruction::LShr:
1427 case Instruction::Shl:
1428 // X << undef -> undef.
1429 // X >> undef -> undef.
1430 if (Op1LV.isUnknown()) break;
1432 // Shifting by the bitwidth or more is undefined.
1433 if (Op1LV.isConstant()) {
1434 if (auto *ShiftAmt = Op1LV.getConstantInt())
1435 if (ShiftAmt->getLimitedValue() >=
1436 ShiftAmt->getType()->getScalarSizeInBits())
1442 markForcedConstant(&I, Constant::getNullValue(ITy));
1444 case Instruction::Select:
1445 Op1LV = getValueState(I.getOperand(1));
1446 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1447 if (Op0LV.isUnknown()) {
1448 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1449 Op1LV = getValueState(I.getOperand(2));
1450 } else if (Op1LV.isUnknown()) {
1451 // c ? undef : undef -> undef. No change.
1452 Op1LV = getValueState(I.getOperand(2));
1453 if (Op1LV.isUnknown())
1455 // Otherwise, c ? undef : x -> x.
1457 // Leave Op1LV as Operand(1)'s LatticeValue.
1460 if (Op1LV.isConstant())
1461 markForcedConstant(&I, Op1LV.getConstant());
1463 markOverdefined(&I);
1465 case Instruction::Load:
1466 // A load here means one of two things: a load of undef from a global,
1467 // a load from an unknown pointer. Either way, having it return undef
1470 case Instruction::ICmp:
1471 // X == undef -> undef. Other comparisons get more complicated.
1472 if (cast<ICmpInst>(&I)->isEquality())
1474 markOverdefined(&I);
1476 case Instruction::Call:
1477 case Instruction::Invoke: {
1478 // There are two reasons a call can have an undef result
1479 // 1. It could be tracked.
1480 // 2. It could be constant-foldable.
1481 // Because of the way we solve return values, tracked calls must
1482 // never be marked overdefined in ResolvedUndefsIn.
1483 if (Function *F = CallSite(&I).getCalledFunction())
1484 if (TrackedRetVals.count(F))
1487 // If the call is constant-foldable, we mark it overdefined because
1488 // we do not know what return values are valid.
1489 markOverdefined(&I);
1493 // If we don't know what should happen here, conservatively mark it
1495 markOverdefined(&I);
1500 // Check to see if we have a branch or switch on an undefined value. If so
1501 // we force the branch to go one way or the other to make the successor
1502 // values live. It doesn't really matter which way we force it.
1503 TerminatorInst *TI = BB.getTerminator();
1504 if (auto *BI = dyn_cast<BranchInst>(TI)) {
1505 if (!BI->isConditional()) continue;
1506 if (!getValueState(BI->getCondition()).isUnknown())
1509 // If the input to SCCP is actually branch on undef, fix the undef to
1511 if (isa<UndefValue>(BI->getCondition())) {
1512 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1513 markEdgeExecutable(&BB, TI->getSuccessor(1));
1517 // Otherwise, it is a branch on a symbolic value which is currently
1518 // considered to be undef. Handle this by forcing the input value to the
1520 markForcedConstant(BI->getCondition(),
1521 ConstantInt::getFalse(TI->getContext()));
1525 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1526 // Indirect branch with no successor ?. Its ok to assume it branches
1528 if (IBR->getNumSuccessors() < 1)
1531 if (!getValueState(IBR->getAddress()).isUnknown())
1534 // If the input to SCCP is actually branch on undef, fix the undef to
1535 // the first successor of the indirect branch.
1536 if (isa<UndefValue>(IBR->getAddress())) {
1537 IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
1538 markEdgeExecutable(&BB, IBR->getSuccessor(0));
1542 // Otherwise, it is a branch on a symbolic value which is currently
1543 // considered to be undef. Handle this by forcing the input value to the
1544 // branch to the first successor.
1545 markForcedConstant(IBR->getAddress(),
1546 BlockAddress::get(IBR->getSuccessor(0)));
1550 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1551 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
1554 // If the input to SCCP is actually switch on undef, fix the undef to
1555 // the first constant.
1556 if (isa<UndefValue>(SI->getCondition())) {
1557 SI->setCondition(SI->case_begin()->getCaseValue());
1558 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
1562 markForcedConstant(SI->getCondition(), SI->case_begin()->getCaseValue());
1570 static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
1571 Constant *Const = nullptr;
1572 if (V->getType()->isStructTy()) {
1573 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
1574 if (any_of(IVs, [](const LatticeVal &LV) { return LV.isOverdefined(); }))
1576 std::vector<Constant *> ConstVals;
1577 auto *ST = dyn_cast<StructType>(V->getType());
1578 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1579 LatticeVal V = IVs[i];
1580 ConstVals.push_back(V.isConstant()
1582 : UndefValue::get(ST->getElementType(i)));
1584 Const = ConstantStruct::get(ST, ConstVals);
1586 LatticeVal IV = Solver.getLatticeValueFor(V);
1587 if (IV.isOverdefined())
1589 Const = IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
1591 assert(Const && "Constant is nullptr here!");
1592 DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n');
1594 // Replaces all of the uses of a variable with uses of the constant.
1595 V->replaceAllUsesWith(Const);
1599 // runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
1600 // and return true if the function was modified.
1602 static bool runSCCP(Function &F, const DataLayout &DL,
1603 const TargetLibraryInfo *TLI) {
1604 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1605 SCCPSolver Solver(DL, TLI);
1607 // Mark the first block of the function as being executable.
1608 Solver.MarkBlockExecutable(&F.front());
1610 // Mark all arguments to the function as being overdefined.
1611 for (Argument &AI : F.args())
1612 Solver.markOverdefined(&AI);
1614 // Solve for constants.
1615 bool ResolvedUndefs = true;
1616 while (ResolvedUndefs) {
1618 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1619 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1622 bool MadeChanges = false;
1624 // If we decided that there are basic blocks that are dead in this function,
1625 // delete their contents now. Note that we cannot actually delete the blocks,
1626 // as we cannot modify the CFG of the function.
1628 for (BasicBlock &BB : F) {
1629 if (!Solver.isBlockExecutable(&BB)) {
1630 DEBUG(dbgs() << " BasicBlock Dead:" << BB);
1633 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
1639 // Iterate over all of the instructions in a function, replacing them with
1640 // constants if we have found them to be of constant values.
1642 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
1643 Instruction *Inst = &*BI++;
1644 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1647 if (tryToReplaceWithConstant(Solver, Inst)) {
1648 if (isInstructionTriviallyDead(Inst))
1649 Inst->eraseFromParent();
1650 // Hey, we just changed something!
1660 PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
1661 const DataLayout &DL = F.getParent()->getDataLayout();
1662 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1663 if (!runSCCP(F, DL, &TLI))
1664 return PreservedAnalyses::all();
1666 auto PA = PreservedAnalyses();
1667 PA.preserve<GlobalsAA>();
1672 //===--------------------------------------------------------------------===//
1674 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1675 /// Sparse Conditional Constant Propagator.
1677 class SCCPLegacyPass : public FunctionPass {
1679 void getAnalysisUsage(AnalysisUsage &AU) const override {
1680 AU.addRequired<TargetLibraryInfoWrapperPass>();
1681 AU.addPreserved<GlobalsAAWrapperPass>();
1683 static char ID; // Pass identification, replacement for typeid
1684 SCCPLegacyPass() : FunctionPass(ID) {
1685 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1688 // runOnFunction - Run the Sparse Conditional Constant Propagation
1689 // algorithm, and return true if the function was modified.
1691 bool runOnFunction(Function &F) override {
1692 if (skipFunction(F))
1694 const DataLayout &DL = F.getParent()->getDataLayout();
1695 const TargetLibraryInfo *TLI =
1696 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1697 return runSCCP(F, DL, TLI);
1700 } // end anonymous namespace
1702 char SCCPLegacyPass::ID = 0;
1703 INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1704 "Sparse Conditional Constant Propagation", false, false)
1705 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1706 INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1707 "Sparse Conditional Constant Propagation", false, false)
1709 // createSCCPPass - This is the public interface to this file.
1710 FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1712 static bool AddressIsTaken(const GlobalValue *GV) {
1713 // Delete any dead constantexpr klingons.
1714 GV->removeDeadConstantUsers();
1716 for (const Use &U : GV->uses()) {
1717 const User *UR = U.getUser();
1718 if (const auto *SI = dyn_cast<StoreInst>(UR)) {
1719 if (SI->getOperand(0) == GV || SI->isVolatile())
1720 return true; // Storing addr of GV.
1721 } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
1722 // Make sure we are calling the function, not passing the address.
1723 ImmutableCallSite CS(cast<Instruction>(UR));
1724 if (!CS.isCallee(&U))
1726 } else if (const auto *LI = dyn_cast<LoadInst>(UR)) {
1727 if (LI->isVolatile())
1729 } else if (isa<BlockAddress>(UR)) {
1730 // blockaddress doesn't take the address of the function, it takes addr
1739 static void findReturnsToZap(Function &F,
1740 SmallPtrSet<Function *, 32> &AddressTakenFunctions,
1741 SmallVector<ReturnInst *, 8> &ReturnsToZap) {
1742 // We can only do this if we know that nothing else can call the function.
1743 if (!F.hasLocalLinkage() || AddressTakenFunctions.count(&F))
1746 for (BasicBlock &BB : F)
1747 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1748 if (!isa<UndefValue>(RI->getOperand(0)))
1749 ReturnsToZap.push_back(RI);
1752 static bool runIPSCCP(Module &M, const DataLayout &DL,
1753 const TargetLibraryInfo *TLI) {
1754 SCCPSolver Solver(DL, TLI);
1756 // AddressTakenFunctions - This set keeps track of the address-taken functions
1757 // that are in the input. As IPSCCP runs through and simplifies code,
1758 // functions that were address taken can end up losing their
1759 // address-taken-ness. Because of this, we keep track of their addresses from
1760 // the first pass so we can use them for the later simplification pass.
1761 SmallPtrSet<Function*, 32> AddressTakenFunctions;
1763 // Loop over all functions, marking arguments to those with their addresses
1764 // taken or that are external as overdefined.
1766 for (Function &F : M) {
1767 if (F.isDeclaration())
1770 // If this is an exact definition of this function, then we can propagate
1771 // information about its result into callsites of it.
1772 // Don't touch naked functions. They may contain asm returning a
1773 // value we don't see, so we may end up interprocedurally propagating
1774 // the return value incorrectly.
1775 if (F.hasExactDefinition() && !F.hasFnAttribute(Attribute::Naked))
1776 Solver.AddTrackedFunction(&F);
1778 // If this function only has direct calls that we can see, we can track its
1779 // arguments and return value aggressively, and can assume it is not called
1780 // unless we see evidence to the contrary.
1781 if (F.hasLocalLinkage()) {
1782 if (F.hasAddressTaken()) {
1783 AddressTakenFunctions.insert(&F);
1786 Solver.AddArgumentTrackedFunction(&F);
1791 // Assume the function is called.
1792 Solver.MarkBlockExecutable(&F.front());
1794 // Assume nothing about the incoming arguments.
1795 for (Argument &AI : F.args())
1796 Solver.markOverdefined(&AI);
1799 // Loop over global variables. We inform the solver about any internal global
1800 // variables that do not have their 'addresses taken'. If they don't have
1801 // their addresses taken, we can propagate constants through them.
1802 for (GlobalVariable &G : M.globals())
1803 if (!G.isConstant() && G.hasLocalLinkage() && !AddressIsTaken(&G))
1804 Solver.TrackValueOfGlobalVariable(&G);
1806 // Solve for constants.
1807 bool ResolvedUndefs = true;
1808 while (ResolvedUndefs) {
1811 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1812 ResolvedUndefs = false;
1813 for (Function &F : M)
1814 ResolvedUndefs |= Solver.ResolvedUndefsIn(F);
1817 bool MadeChanges = false;
1819 // Iterate over all of the instructions in the module, replacing them with
1820 // constants if we have found them to be of constant values.
1822 SmallVector<BasicBlock*, 512> BlocksToErase;
1824 for (Function &F : M) {
1825 if (F.isDeclaration())
1828 if (Solver.isBlockExecutable(&F.front())) {
1829 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
1831 if (AI->use_empty())
1833 if (tryToReplaceWithConstant(Solver, &*AI))
1838 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1839 if (!Solver.isBlockExecutable(&*BB)) {
1840 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1844 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false);
1848 if (&*BB != &F.front())
1849 BlocksToErase.push_back(&*BB);
1853 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1854 Instruction *Inst = &*BI++;
1855 if (Inst->getType()->isVoidTy())
1857 if (tryToReplaceWithConstant(Solver, Inst)) {
1858 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1859 Inst->eraseFromParent();
1860 // Hey, we just changed something!
1867 // Now that all instructions in the function are constant folded, erase dead
1868 // blocks, because we can now use ConstantFoldTerminator to get rid of
1870 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1871 // If there are any PHI nodes in this successor, drop entries for BB now.
1872 BasicBlock *DeadBB = BlocksToErase[i];
1873 for (Value::user_iterator UI = DeadBB->user_begin(),
1874 UE = DeadBB->user_end();
1876 // Grab the user and then increment the iterator early, as the user
1877 // will be deleted. Step past all adjacent uses from the same user.
1878 auto *I = dyn_cast<Instruction>(*UI);
1879 do { ++UI; } while (UI != UE && *UI == I);
1881 // Ignore blockaddress users; BasicBlock's dtor will handle them.
1884 bool Folded = ConstantFoldTerminator(I->getParent());
1886 "Expect TermInst on constantint or blockaddress to be folded");
1890 // Finally, delete the basic block.
1891 F.getBasicBlockList().erase(DeadBB);
1893 BlocksToErase.clear();
1896 // If we inferred constant or undef return values for a function, we replaced
1897 // all call uses with the inferred value. This means we don't need to bother
1898 // actually returning anything from the function. Replace all return
1899 // instructions with return undef.
1901 // Do this in two stages: first identify the functions we should process, then
1902 // actually zap their returns. This is important because we can only do this
1903 // if the address of the function isn't taken. In cases where a return is the
1904 // last use of a function, the order of processing functions would affect
1905 // whether other functions are optimizable.
1906 SmallVector<ReturnInst*, 8> ReturnsToZap;
1908 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1909 for (const auto &I : RV) {
1910 Function *F = I.first;
1911 if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
1913 findReturnsToZap(*F, AddressTakenFunctions, ReturnsToZap);
1916 for (const auto &F : Solver.getMRVFunctionsTracked()) {
1917 assert(F->getReturnType()->isStructTy() &&
1918 "The return type should be a struct");
1919 StructType *STy = cast<StructType>(F->getReturnType());
1920 if (Solver.isStructLatticeConstant(F, STy))
1921 findReturnsToZap(*F, AddressTakenFunctions, ReturnsToZap);
1924 // Zap all returns which we've identified as zap to change.
1925 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1926 Function *F = ReturnsToZap[i]->getParent()->getParent();
1927 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1930 // If we inferred constant or undef values for globals variables, we can
1931 // delete the global and any stores that remain to it.
1932 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1933 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1934 E = TG.end(); I != E; ++I) {
1935 GlobalVariable *GV = I->first;
1936 assert(!I->second.isOverdefined() &&
1937 "Overdefined values should have been taken out of the map!");
1938 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1939 while (!GV->use_empty()) {
1940 StoreInst *SI = cast<StoreInst>(GV->user_back());
1941 SI->eraseFromParent();
1943 M.getGlobalList().erase(GV);
1950 PreservedAnalyses IPSCCPPass::run(Module &M, ModuleAnalysisManager &AM) {
1951 const DataLayout &DL = M.getDataLayout();
1952 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
1953 if (!runIPSCCP(M, DL, &TLI))
1954 return PreservedAnalyses::all();
1955 return PreservedAnalyses::none();
1959 //===--------------------------------------------------------------------===//
1961 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1962 /// Constant Propagation.
1964 class IPSCCPLegacyPass : public ModulePass {
1968 IPSCCPLegacyPass() : ModulePass(ID) {
1969 initializeIPSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1972 bool runOnModule(Module &M) override {
1975 const DataLayout &DL = M.getDataLayout();
1976 const TargetLibraryInfo *TLI =
1977 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1978 return runIPSCCP(M, DL, TLI);
1981 void getAnalysisUsage(AnalysisUsage &AU) const override {
1982 AU.addRequired<TargetLibraryInfoWrapperPass>();
1985 } // end anonymous namespace
1987 char IPSCCPLegacyPass::ID = 0;
1988 INITIALIZE_PASS_BEGIN(IPSCCPLegacyPass, "ipsccp",
1989 "Interprocedural Sparse Conditional Constant Propagation",
1991 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1992 INITIALIZE_PASS_END(IPSCCPLegacyPass, "ipsccp",
1993 "Interprocedural Sparse Conditional Constant Propagation",
1996 // createIPSCCPPass - This is the public interface to this file.
1997 ModulePass *llvm::createIPSCCPPass() { return new IPSCCPLegacyPass(); }