xref: /llvm-project/llvm/lib/Transforms/Utils/SCCPSolver.cpp (revision b569ec6de6a0c57d6c4b675df7d7e3e28a9f4904)
1bbab9f98SSjoerd Meijer //===- SCCPSolver.cpp - SCCP Utility --------------------------- *- C++ -*-===//
2bbab9f98SSjoerd Meijer //
3bbab9f98SSjoerd Meijer // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4bbab9f98SSjoerd Meijer // See https://llvm.org/LICENSE.txt for license information.
5bbab9f98SSjoerd Meijer // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6bbab9f98SSjoerd Meijer //
7bbab9f98SSjoerd Meijer //===----------------------------------------------------------------------===//
8bbab9f98SSjoerd Meijer //
9bbab9f98SSjoerd Meijer // \file
10bbab9f98SSjoerd Meijer // This file implements the Sparse Conditional Constant Propagation (SCCP)
11bbab9f98SSjoerd Meijer // utility.
12bbab9f98SSjoerd Meijer //
13bbab9f98SSjoerd Meijer //===----------------------------------------------------------------------===//
14bbab9f98SSjoerd Meijer 
1539d29817SSjoerd Meijer #include "llvm/Transforms/Utils/SCCPSolver.h"
16aec3ec04SFlorian Mayer #include "llvm/ADT/SetVector.h"
17bbab9f98SSjoerd Meijer #include "llvm/Analysis/ConstantFolding.h"
18bbab9f98SSjoerd Meijer #include "llvm/Analysis/InstructionSimplify.h"
19a494ae43Sserge-sans-paille #include "llvm/Analysis/ValueLattice.h"
209ebaf4feSAlexandros Lamprineas #include "llvm/Analysis/ValueLatticeUtils.h"
21d37d4072SMikhail Gudim #include "llvm/Analysis/ValueTracking.h"
22a494ae43Sserge-sans-paille #include "llvm/IR/InstVisitor.h"
23bbab9f98SSjoerd Meijer #include "llvm/Support/Casting.h"
24bbab9f98SSjoerd Meijer #include "llvm/Support/Debug.h"
25bbab9f98SSjoerd Meijer #include "llvm/Support/ErrorHandling.h"
26bbab9f98SSjoerd Meijer #include "llvm/Support/raw_ostream.h"
279ebaf4feSAlexandros Lamprineas #include "llvm/Transforms/Utils/Local.h"
28bbab9f98SSjoerd Meijer #include <cassert>
29bbab9f98SSjoerd Meijer #include <utility>
30bbab9f98SSjoerd Meijer #include <vector>
31bbab9f98SSjoerd Meijer 
32bbab9f98SSjoerd Meijer using namespace llvm;
33bbab9f98SSjoerd Meijer 
34bbab9f98SSjoerd Meijer #define DEBUG_TYPE "sccp"
35bbab9f98SSjoerd Meijer 
36bbab9f98SSjoerd Meijer // The maximum number of range extensions allowed for operations requiring
37bbab9f98SSjoerd Meijer // widening.
38bbab9f98SSjoerd Meijer static const unsigned MaxNumRangeExtensions = 10;
39bbab9f98SSjoerd Meijer 
40bbab9f98SSjoerd Meijer /// Returns MergeOptions with MaxWidenSteps set to MaxNumRangeExtensions.
41bbab9f98SSjoerd Meijer static ValueLatticeElement::MergeOptions getMaxWidenStepsOpts() {
42bbab9f98SSjoerd Meijer   return ValueLatticeElement::MergeOptions().setMaxWidenSteps(
43bbab9f98SSjoerd Meijer       MaxNumRangeExtensions);
44bbab9f98SSjoerd Meijer }
45bbab9f98SSjoerd Meijer 
469ebaf4feSAlexandros Lamprineas namespace llvm {
47bbab9f98SSjoerd Meijer 
48a794b62cSFlorian Hahn bool SCCPSolver::isConstant(const ValueLatticeElement &LV) {
49bbab9f98SSjoerd Meijer   return LV.isConstant() ||
50bbab9f98SSjoerd Meijer          (LV.isConstantRange() && LV.getConstantRange().isSingleElement());
51bbab9f98SSjoerd Meijer }
52bbab9f98SSjoerd Meijer 
53a794b62cSFlorian Hahn bool SCCPSolver::isOverdefined(const ValueLatticeElement &LV) {
54a794b62cSFlorian Hahn   return !LV.isUnknownOrUndef() && !SCCPSolver::isConstant(LV);
55bbab9f98SSjoerd Meijer }
56bbab9f98SSjoerd Meijer 
57a794b62cSFlorian Hahn bool SCCPSolver::tryToReplaceWithConstant(Value *V) {
587ea597eaSAlexandros Lamprineas   Constant *Const = getConstantOrNull(V);
597ea597eaSAlexandros Lamprineas   if (!Const)
609ebaf4feSAlexandros Lamprineas     return false;
619ebaf4feSAlexandros Lamprineas   // Replacing `musttail` instructions with constant breaks `musttail` invariant
629ebaf4feSAlexandros Lamprineas   // unless the call itself can be removed.
639ebaf4feSAlexandros Lamprineas   // Calls with "clang.arc.attachedcall" implicitly use the return value and
649ebaf4feSAlexandros Lamprineas   // those uses cannot be updated with a constant.
659ebaf4feSAlexandros Lamprineas   CallBase *CB = dyn_cast<CallBase>(V);
66861caf9bShanbeom   if (CB && ((CB->isMustTailCall() && !wouldInstructionBeTriviallyDead(CB)) ||
679ebaf4feSAlexandros Lamprineas              CB->getOperandBundle(LLVMContext::OB_clang_arc_attachedcall))) {
689ebaf4feSAlexandros Lamprineas     Function *F = CB->getCalledFunction();
699ebaf4feSAlexandros Lamprineas 
709ebaf4feSAlexandros Lamprineas     // Don't zap returns of the callee
719ebaf4feSAlexandros Lamprineas     if (F)
72a794b62cSFlorian Hahn       addToMustPreserveReturnsInFunctions(F);
739ebaf4feSAlexandros Lamprineas 
749ebaf4feSAlexandros Lamprineas     LLVM_DEBUG(dbgs() << "  Can\'t treat the result of call " << *CB
759ebaf4feSAlexandros Lamprineas                       << " as a constant\n");
769ebaf4feSAlexandros Lamprineas     return false;
779ebaf4feSAlexandros Lamprineas   }
789ebaf4feSAlexandros Lamprineas 
799ebaf4feSAlexandros Lamprineas   LLVM_DEBUG(dbgs() << "  Constant: " << *Const << " = " << *V << '\n');
809ebaf4feSAlexandros Lamprineas 
819ebaf4feSAlexandros Lamprineas   // Replaces all of the uses of a variable with uses of the constant.
829ebaf4feSAlexandros Lamprineas   V->replaceAllUsesWith(Const);
839ebaf4feSAlexandros Lamprineas   return true;
849ebaf4feSAlexandros Lamprineas }
859ebaf4feSAlexandros Lamprineas 
86cdeaf5f2SFlorian Hahn /// Try to use \p Inst's value range from \p Solver to infer the NUW flag.
87cdeaf5f2SFlorian Hahn static bool refineInstruction(SCCPSolver &Solver,
8823ea58f3SVitaly Buka                               const SmallPtrSetImpl<Value *> &InsertedValues,
89cdeaf5f2SFlorian Hahn                               Instruction &Inst) {
90ed964304SYingwei Zheng   bool Changed = false;
9123ea58f3SVitaly Buka   auto GetRange = [&Solver, &InsertedValues](Value *Op) {
926b76c1e6SNikita Popov     if (auto *Const = dyn_cast<Constant>(Op))
936b76c1e6SNikita Popov       return Const->toConstantRange();
946b76c1e6SNikita Popov     if (InsertedValues.contains(Op)) {
95cdeaf5f2SFlorian Hahn       unsigned Bitwidth = Op->getType()->getScalarSizeInBits();
96cdeaf5f2SFlorian Hahn       return ConstantRange::getFull(Bitwidth);
97cdeaf5f2SFlorian Hahn     }
986b76c1e6SNikita Popov     return Solver.getLatticeValueFor(Op).asConstantRange(
996b76c1e6SNikita Popov         Op->getType(), /*UndefAllowed=*/false);
100cdeaf5f2SFlorian Hahn   };
101ed964304SYingwei Zheng 
102ed964304SYingwei Zheng   if (isa<OverflowingBinaryOperator>(Inst)) {
103b1822ef3SXChy     if (Inst.hasNoSignedWrap() && Inst.hasNoUnsignedWrap())
104b1822ef3SXChy       return false;
105b1822ef3SXChy 
106cdeaf5f2SFlorian Hahn     auto RangeA = GetRange(Inst.getOperand(0));
107cdeaf5f2SFlorian Hahn     auto RangeB = GetRange(Inst.getOperand(1));
108cdeaf5f2SFlorian Hahn     if (!Inst.hasNoUnsignedWrap()) {
109cdeaf5f2SFlorian Hahn       auto NUWRange = ConstantRange::makeGuaranteedNoWrapRegion(
1107d102133SFlorian Hahn           Instruction::BinaryOps(Inst.getOpcode()), RangeB,
1117d102133SFlorian Hahn           OverflowingBinaryOperator::NoUnsignedWrap);
112cdeaf5f2SFlorian Hahn       if (NUWRange.contains(RangeA)) {
113cdeaf5f2SFlorian Hahn         Inst.setHasNoUnsignedWrap();
11472121a20SFlorian Hahn         Changed = true;
11572121a20SFlorian Hahn       }
11672121a20SFlorian Hahn     }
11772121a20SFlorian Hahn     if (!Inst.hasNoSignedWrap()) {
11872121a20SFlorian Hahn       auto NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(
119ed964304SYingwei Zheng           Instruction::BinaryOps(Inst.getOpcode()), RangeB,
120ed964304SYingwei Zheng           OverflowingBinaryOperator::NoSignedWrap);
1214e607ec4SFlorian Hahn       if (NSWRange.contains(RangeA)) {
12272121a20SFlorian Hahn         Inst.setHasNoSignedWrap();
12372121a20SFlorian Hahn         Changed = true;
124cdeaf5f2SFlorian Hahn       }
125cdeaf5f2SFlorian Hahn     }
1266243395dSNoah Goldstein   } else if (isa<PossiblyNonNegInst>(Inst) && !Inst.hasNonNeg()) {
127ed964304SYingwei Zheng     auto Range = GetRange(Inst.getOperand(0));
128ed964304SYingwei Zheng     if (Range.isAllNonNegative()) {
129ed964304SYingwei Zheng       Inst.setNonNeg();
130ed964304SYingwei Zheng       Changed = true;
131ed964304SYingwei Zheng     }
132b1822ef3SXChy   } else if (TruncInst *TI = dyn_cast<TruncInst>(&Inst)) {
133b1822ef3SXChy     if (TI->hasNoSignedWrap() && TI->hasNoUnsignedWrap())
134b1822ef3SXChy       return false;
135b1822ef3SXChy 
136b1822ef3SXChy     auto Range = GetRange(Inst.getOperand(0));
137b1822ef3SXChy     uint64_t DestWidth = TI->getDestTy()->getScalarSizeInBits();
138b1822ef3SXChy     if (!TI->hasNoUnsignedWrap()) {
139b1822ef3SXChy       if (Range.getActiveBits() <= DestWidth) {
140b1822ef3SXChy         TI->setHasNoUnsignedWrap(true);
141b1822ef3SXChy         Changed = true;
142b1822ef3SXChy       }
143b1822ef3SXChy     }
144b1822ef3SXChy     if (!TI->hasNoSignedWrap()) {
145b1822ef3SXChy       if (Range.getMinSignedBits() <= DestWidth) {
146b1822ef3SXChy         TI->setHasNoSignedWrap(true);
147b1822ef3SXChy         Changed = true;
148b1822ef3SXChy       }
149b1822ef3SXChy     }
150*b569ec6dSNikita Popov   } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst)) {
151*b569ec6dSNikita Popov     if (GEP->hasNoUnsignedWrap() || !GEP->hasNoUnsignedSignedWrap())
152*b569ec6dSNikita Popov       return false;
153*b569ec6dSNikita Popov 
154*b569ec6dSNikita Popov     if (all_of(GEP->indices(),
155*b569ec6dSNikita Popov                [&](Value *V) { return GetRange(V).isAllNonNegative(); })) {
156*b569ec6dSNikita Popov       GEP->setNoWrapFlags(GEP->getNoWrapFlags() |
157*b569ec6dSNikita Popov                           GEPNoWrapFlags::noUnsignedWrap());
158*b569ec6dSNikita Popov       Changed = true;
159*b569ec6dSNikita Popov     }
160ed964304SYingwei Zheng   }
161cdeaf5f2SFlorian Hahn 
16272121a20SFlorian Hahn   return Changed;
163cdeaf5f2SFlorian Hahn }
164cdeaf5f2SFlorian Hahn 
165c9401f2eSDouglas Yung /// Try to replace signed instructions with their unsigned equivalent.
166c9401f2eSDouglas Yung static bool replaceSignedInst(SCCPSolver &Solver,
16723ea58f3SVitaly Buka                               SmallPtrSetImpl<Value *> &InsertedValues,
1689ebaf4feSAlexandros Lamprineas                               Instruction &Inst) {
1699ebaf4feSAlexandros Lamprineas   // Determine if a signed value is known to be >= 0.
1709ebaf4feSAlexandros Lamprineas   auto isNonNegative = [&Solver](Value *V) {
1719ebaf4feSAlexandros Lamprineas     // If this value was constant-folded, it may not have a solver entry.
1729ebaf4feSAlexandros Lamprineas     // Handle integers. Otherwise, return false.
1739ebaf4feSAlexandros Lamprineas     if (auto *C = dyn_cast<Constant>(V)) {
1749ebaf4feSAlexandros Lamprineas       auto *CInt = dyn_cast<ConstantInt>(C);
1759ebaf4feSAlexandros Lamprineas       return CInt && !CInt->isNegative();
1769ebaf4feSAlexandros Lamprineas     }
1779ebaf4feSAlexandros Lamprineas     const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
1789ebaf4feSAlexandros Lamprineas     return IV.isConstantRange(/*UndefAllowed=*/false) &&
1799ebaf4feSAlexandros Lamprineas            IV.getConstantRange().isAllNonNegative();
1809ebaf4feSAlexandros Lamprineas   };
1819ebaf4feSAlexandros Lamprineas 
1829ebaf4feSAlexandros Lamprineas   Instruction *NewInst = nullptr;
1839ebaf4feSAlexandros Lamprineas   switch (Inst.getOpcode()) {
1846243395dSNoah Goldstein   case Instruction::SIToFP:
1859ebaf4feSAlexandros Lamprineas   case Instruction::SExt: {
1866243395dSNoah Goldstein     // If the source value is not negative, this is a zext/uitofp.
1879ebaf4feSAlexandros Lamprineas     Value *Op0 = Inst.getOperand(0);
18823ea58f3SVitaly Buka     if (InsertedValues.count(Op0) || !isNonNegative(Op0))
1899ebaf4feSAlexandros Lamprineas       return false;
1906243395dSNoah Goldstein     NewInst = CastInst::Create(Inst.getOpcode() == Instruction::SExt
1916243395dSNoah Goldstein                                    ? Instruction::ZExt
1926243395dSNoah Goldstein                                    : Instruction::UIToFP,
1936243395dSNoah Goldstein                                Op0, Inst.getType(), "", Inst.getIterator());
194b1c59b51SCraig Topper     NewInst->setNonNeg();
1959ebaf4feSAlexandros Lamprineas     break;
1969ebaf4feSAlexandros Lamprineas   }
1979ebaf4feSAlexandros Lamprineas   case Instruction::AShr: {
1989ebaf4feSAlexandros Lamprineas     // If the shifted value is not negative, this is a logical shift right.
1999ebaf4feSAlexandros Lamprineas     Value *Op0 = Inst.getOperand(0);
20023ea58f3SVitaly Buka     if (InsertedValues.count(Op0) || !isNonNegative(Op0))
2019ebaf4feSAlexandros Lamprineas       return false;
2026b62a913SJeremy Morse     NewInst = BinaryOperator::CreateLShr(Op0, Inst.getOperand(1), "", Inst.getIterator());
203c3b9c36fSYingwei Zheng     NewInst->setIsExact(Inst.isExact());
2049ebaf4feSAlexandros Lamprineas     break;
2059ebaf4feSAlexandros Lamprineas   }
2069ebaf4feSAlexandros Lamprineas   case Instruction::SDiv:
2079ebaf4feSAlexandros Lamprineas   case Instruction::SRem: {
2089ebaf4feSAlexandros Lamprineas     // If both operands are not negative, this is the same as udiv/urem.
2099ebaf4feSAlexandros Lamprineas     Value *Op0 = Inst.getOperand(0), *Op1 = Inst.getOperand(1);
21023ea58f3SVitaly Buka     if (InsertedValues.count(Op0) || InsertedValues.count(Op1) ||
21123ea58f3SVitaly Buka         !isNonNegative(Op0) || !isNonNegative(Op1))
2129ebaf4feSAlexandros Lamprineas       return false;
2139ebaf4feSAlexandros Lamprineas     auto NewOpcode = Inst.getOpcode() == Instruction::SDiv ? Instruction::UDiv
2149ebaf4feSAlexandros Lamprineas                                                            : Instruction::URem;
2156b62a913SJeremy Morse     NewInst = BinaryOperator::Create(NewOpcode, Op0, Op1, "", Inst.getIterator());
216c3b9c36fSYingwei Zheng     if (Inst.getOpcode() == Instruction::SDiv)
217c3b9c36fSYingwei Zheng       NewInst->setIsExact(Inst.isExact());
2189ebaf4feSAlexandros Lamprineas     break;
2199ebaf4feSAlexandros Lamprineas   }
2209ebaf4feSAlexandros Lamprineas   default:
2219ebaf4feSAlexandros Lamprineas     return false;
2229ebaf4feSAlexandros Lamprineas   }
2239ebaf4feSAlexandros Lamprineas 
2249ebaf4feSAlexandros Lamprineas   // Wire up the new instruction and update state.
2259ebaf4feSAlexandros Lamprineas   assert(NewInst && "Expected replacement instruction");
2269ebaf4feSAlexandros Lamprineas   NewInst->takeName(&Inst);
22723ea58f3SVitaly Buka   InsertedValues.insert(NewInst);
2289ebaf4feSAlexandros Lamprineas   Inst.replaceAllUsesWith(NewInst);
22926af44b3SSudharsan Veeravalli   NewInst->setDebugLoc(Inst.getDebugLoc());
23023ea58f3SVitaly Buka   Solver.removeLatticeValueFor(&Inst);
2319ebaf4feSAlexandros Lamprineas   Inst.eraseFromParent();
2329ebaf4feSAlexandros Lamprineas   return true;
2339ebaf4feSAlexandros Lamprineas }
2349ebaf4feSAlexandros Lamprineas 
235a794b62cSFlorian Hahn bool SCCPSolver::simplifyInstsInBlock(BasicBlock &BB,
23623ea58f3SVitaly Buka                                       SmallPtrSetImpl<Value *> &InsertedValues,
2379ebaf4feSAlexandros Lamprineas                                       Statistic &InstRemovedStat,
2389ebaf4feSAlexandros Lamprineas                                       Statistic &InstReplacedStat) {
2399ebaf4feSAlexandros Lamprineas   bool MadeChanges = false;
2409ebaf4feSAlexandros Lamprineas   for (Instruction &Inst : make_early_inc_range(BB)) {
2419ebaf4feSAlexandros Lamprineas     if (Inst.getType()->isVoidTy())
2429ebaf4feSAlexandros Lamprineas       continue;
243a794b62cSFlorian Hahn     if (tryToReplaceWithConstant(&Inst)) {
244861caf9bShanbeom       if (wouldInstructionBeTriviallyDead(&Inst))
2459ebaf4feSAlexandros Lamprineas         Inst.eraseFromParent();
2469ebaf4feSAlexandros Lamprineas 
2479ebaf4feSAlexandros Lamprineas       MadeChanges = true;
2489ebaf4feSAlexandros Lamprineas       ++InstRemovedStat;
24923ea58f3SVitaly Buka     } else if (replaceSignedInst(*this, InsertedValues, Inst)) {
2509ebaf4feSAlexandros Lamprineas       MadeChanges = true;
2519ebaf4feSAlexandros Lamprineas       ++InstReplacedStat;
25223ea58f3SVitaly Buka     } else if (refineInstruction(*this, InsertedValues, Inst)) {
253cdeaf5f2SFlorian Hahn       MadeChanges = true;
2549ebaf4feSAlexandros Lamprineas     }
2559ebaf4feSAlexandros Lamprineas   }
2569ebaf4feSAlexandros Lamprineas   return MadeChanges;
2579ebaf4feSAlexandros Lamprineas }
2589ebaf4feSAlexandros Lamprineas 
259a794b62cSFlorian Hahn bool SCCPSolver::removeNonFeasibleEdges(BasicBlock *BB, DomTreeUpdater &DTU,
260a794b62cSFlorian Hahn                                         BasicBlock *&NewUnreachableBB) const {
2619ebaf4feSAlexandros Lamprineas   SmallPtrSet<BasicBlock *, 8> FeasibleSuccessors;
2629ebaf4feSAlexandros Lamprineas   bool HasNonFeasibleEdges = false;
2639ebaf4feSAlexandros Lamprineas   for (BasicBlock *Succ : successors(BB)) {
264a794b62cSFlorian Hahn     if (isEdgeFeasible(BB, Succ))
2659ebaf4feSAlexandros Lamprineas       FeasibleSuccessors.insert(Succ);
2669ebaf4feSAlexandros Lamprineas     else
2679ebaf4feSAlexandros Lamprineas       HasNonFeasibleEdges = true;
2689ebaf4feSAlexandros Lamprineas   }
2699ebaf4feSAlexandros Lamprineas 
2709ebaf4feSAlexandros Lamprineas   // All edges feasible, nothing to do.
2719ebaf4feSAlexandros Lamprineas   if (!HasNonFeasibleEdges)
2729ebaf4feSAlexandros Lamprineas     return false;
2739ebaf4feSAlexandros Lamprineas 
2749ebaf4feSAlexandros Lamprineas   // SCCP can only determine non-feasible edges for br, switch and indirectbr.
2759ebaf4feSAlexandros Lamprineas   Instruction *TI = BB->getTerminator();
2769ebaf4feSAlexandros Lamprineas   assert((isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
2779ebaf4feSAlexandros Lamprineas           isa<IndirectBrInst>(TI)) &&
2789ebaf4feSAlexandros Lamprineas          "Terminator must be a br, switch or indirectbr");
2799ebaf4feSAlexandros Lamprineas 
2809ebaf4feSAlexandros Lamprineas   if (FeasibleSuccessors.size() == 0) {
2819ebaf4feSAlexandros Lamprineas     // Branch on undef/poison, replace with unreachable.
2829ebaf4feSAlexandros Lamprineas     SmallPtrSet<BasicBlock *, 8> SeenSuccs;
2839ebaf4feSAlexandros Lamprineas     SmallVector<DominatorTree::UpdateType, 8> Updates;
2849ebaf4feSAlexandros Lamprineas     for (BasicBlock *Succ : successors(BB)) {
2859ebaf4feSAlexandros Lamprineas       Succ->removePredecessor(BB);
2869ebaf4feSAlexandros Lamprineas       if (SeenSuccs.insert(Succ).second)
2879ebaf4feSAlexandros Lamprineas         Updates.push_back({DominatorTree::Delete, BB, Succ});
2889ebaf4feSAlexandros Lamprineas     }
2899ebaf4feSAlexandros Lamprineas     TI->eraseFromParent();
2909ebaf4feSAlexandros Lamprineas     new UnreachableInst(BB->getContext(), BB);
2919ebaf4feSAlexandros Lamprineas     DTU.applyUpdatesPermissive(Updates);
2929ebaf4feSAlexandros Lamprineas   } else if (FeasibleSuccessors.size() == 1) {
2939ebaf4feSAlexandros Lamprineas     // Replace with an unconditional branch to the only feasible successor.
2949ebaf4feSAlexandros Lamprineas     BasicBlock *OnlyFeasibleSuccessor = *FeasibleSuccessors.begin();
2959ebaf4feSAlexandros Lamprineas     SmallVector<DominatorTree::UpdateType, 8> Updates;
2969ebaf4feSAlexandros Lamprineas     bool HaveSeenOnlyFeasibleSuccessor = false;
2979ebaf4feSAlexandros Lamprineas     for (BasicBlock *Succ : successors(BB)) {
2989ebaf4feSAlexandros Lamprineas       if (Succ == OnlyFeasibleSuccessor && !HaveSeenOnlyFeasibleSuccessor) {
2999ebaf4feSAlexandros Lamprineas         // Don't remove the edge to the only feasible successor the first time
3009ebaf4feSAlexandros Lamprineas         // we see it. We still do need to remove any multi-edges to it though.
3019ebaf4feSAlexandros Lamprineas         HaveSeenOnlyFeasibleSuccessor = true;
3029ebaf4feSAlexandros Lamprineas         continue;
3039ebaf4feSAlexandros Lamprineas       }
3049ebaf4feSAlexandros Lamprineas 
3059ebaf4feSAlexandros Lamprineas       Succ->removePredecessor(BB);
3069ebaf4feSAlexandros Lamprineas       Updates.push_back({DominatorTree::Delete, BB, Succ});
3079ebaf4feSAlexandros Lamprineas     }
3089ebaf4feSAlexandros Lamprineas 
30926af44b3SSudharsan Veeravalli     Instruction *BI = BranchInst::Create(OnlyFeasibleSuccessor, BB);
31026af44b3SSudharsan Veeravalli     BI->setDebugLoc(TI->getDebugLoc());
3119ebaf4feSAlexandros Lamprineas     TI->eraseFromParent();
3129ebaf4feSAlexandros Lamprineas     DTU.applyUpdatesPermissive(Updates);
3139ebaf4feSAlexandros Lamprineas   } else if (FeasibleSuccessors.size() > 1) {
3149ebaf4feSAlexandros Lamprineas     SwitchInstProfUpdateWrapper SI(*cast<SwitchInst>(TI));
3159ebaf4feSAlexandros Lamprineas     SmallVector<DominatorTree::UpdateType, 8> Updates;
3169ebaf4feSAlexandros Lamprineas 
3179ebaf4feSAlexandros Lamprineas     // If the default destination is unfeasible it will never be taken. Replace
3189ebaf4feSAlexandros Lamprineas     // it with a new block with a single Unreachable instruction.
3199ebaf4feSAlexandros Lamprineas     BasicBlock *DefaultDest = SI->getDefaultDest();
3209ebaf4feSAlexandros Lamprineas     if (!FeasibleSuccessors.contains(DefaultDest)) {
3219ebaf4feSAlexandros Lamprineas       if (!NewUnreachableBB) {
3229ebaf4feSAlexandros Lamprineas         NewUnreachableBB =
3239ebaf4feSAlexandros Lamprineas             BasicBlock::Create(DefaultDest->getContext(), "default.unreachable",
3249ebaf4feSAlexandros Lamprineas                                DefaultDest->getParent(), DefaultDest);
3259ebaf4feSAlexandros Lamprineas         new UnreachableInst(DefaultDest->getContext(), NewUnreachableBB);
3269ebaf4feSAlexandros Lamprineas       }
3279ebaf4feSAlexandros Lamprineas 
328d2180925SYingwei Zheng       DefaultDest->removePredecessor(BB);
3299ebaf4feSAlexandros Lamprineas       SI->setDefaultDest(NewUnreachableBB);
3309ebaf4feSAlexandros Lamprineas       Updates.push_back({DominatorTree::Delete, BB, DefaultDest});
3319ebaf4feSAlexandros Lamprineas       Updates.push_back({DominatorTree::Insert, BB, NewUnreachableBB});
3329ebaf4feSAlexandros Lamprineas     }
3339ebaf4feSAlexandros Lamprineas 
3349ebaf4feSAlexandros Lamprineas     for (auto CI = SI->case_begin(); CI != SI->case_end();) {
3359ebaf4feSAlexandros Lamprineas       if (FeasibleSuccessors.contains(CI->getCaseSuccessor())) {
3369ebaf4feSAlexandros Lamprineas         ++CI;
3379ebaf4feSAlexandros Lamprineas         continue;
3389ebaf4feSAlexandros Lamprineas       }
3399ebaf4feSAlexandros Lamprineas 
3409ebaf4feSAlexandros Lamprineas       BasicBlock *Succ = CI->getCaseSuccessor();
3419ebaf4feSAlexandros Lamprineas       Succ->removePredecessor(BB);
3429ebaf4feSAlexandros Lamprineas       Updates.push_back({DominatorTree::Delete, BB, Succ});
3439ebaf4feSAlexandros Lamprineas       SI.removeCase(CI);
3449ebaf4feSAlexandros Lamprineas       // Don't increment CI, as we removed a case.
3459ebaf4feSAlexandros Lamprineas     }
3469ebaf4feSAlexandros Lamprineas 
3479ebaf4feSAlexandros Lamprineas     DTU.applyUpdatesPermissive(Updates);
3489ebaf4feSAlexandros Lamprineas   } else {
3499ebaf4feSAlexandros Lamprineas     llvm_unreachable("Must have at least one feasible successor");
3509ebaf4feSAlexandros Lamprineas   }
3519ebaf4feSAlexandros Lamprineas   return true;
3529ebaf4feSAlexandros Lamprineas }
353bbab9f98SSjoerd Meijer 
354b7e51b4fSNikita Popov static void inferAttribute(Function *F, unsigned AttrIndex,
355b7e51b4fSNikita Popov                            const ValueLatticeElement &Val) {
356b7e51b4fSNikita Popov   // If there is a known constant range for the value, add range attribute.
357b7e51b4fSNikita Popov   if (Val.isConstantRange() && !Val.getConstantRange().isSingleElement()) {
358b7e51b4fSNikita Popov     // Do not add range attribute if the value may include undef.
359b7e51b4fSNikita Popov     if (Val.isConstantRangeIncludingUndef())
360b7e51b4fSNikita Popov       return;
36124fe1d4fSNikita Popov 
36224fe1d4fSNikita Popov     // Take the intersection of the existing attribute and the inferred range.
363b7e51b4fSNikita Popov     Attribute OldAttr = F->getAttributeAtIndex(AttrIndex, Attribute::Range);
364b7e51b4fSNikita Popov     ConstantRange CR = Val.getConstantRange();
365b7e51b4fSNikita Popov     if (OldAttr.isValid())
366b7e51b4fSNikita Popov       CR = CR.intersectWith(OldAttr.getRange());
367b7e51b4fSNikita Popov     F->addAttributeAtIndex(
368b7e51b4fSNikita Popov         AttrIndex, Attribute::get(F->getContext(), Attribute::Range, CR));
369b7e51b4fSNikita Popov     return;
37024fe1d4fSNikita Popov   }
371b7e51b4fSNikita Popov   // Infer nonnull attribute.
372b7e51b4fSNikita Popov   if (Val.isNotConstant() && Val.getNotConstant()->getType()->isPointerTy() &&
373b7e51b4fSNikita Popov       Val.getNotConstant()->isNullValue() &&
374b7e51b4fSNikita Popov       !F->hasAttributeAtIndex(AttrIndex, Attribute::NonNull)) {
375b7e51b4fSNikita Popov     F->addAttributeAtIndex(AttrIndex,
376b7e51b4fSNikita Popov                            Attribute::get(F->getContext(), Attribute::NonNull));
37724fe1d4fSNikita Popov   }
37824fe1d4fSNikita Popov }
379b7e51b4fSNikita Popov 
380b7e51b4fSNikita Popov void SCCPSolver::inferReturnAttributes() const {
381b7e51b4fSNikita Popov   for (const auto &[F, ReturnValue] : getTrackedRetVals())
382b7e51b4fSNikita Popov     inferAttribute(F, AttributeList::ReturnIndex, ReturnValue);
383b7e51b4fSNikita Popov }
384b7e51b4fSNikita Popov 
385b7e51b4fSNikita Popov void SCCPSolver::inferArgAttributes() const {
386b7e51b4fSNikita Popov   for (Function *F : getArgumentTrackedFunctions()) {
387b7e51b4fSNikita Popov     if (!isBlockExecutable(&F->front()))
388b7e51b4fSNikita Popov       continue;
389b7e51b4fSNikita Popov     for (Argument &A : F->args())
390b7e51b4fSNikita Popov       if (!A.getType()->isStructTy())
391b7e51b4fSNikita Popov         inferAttribute(F, AttributeList::FirstArgIndex + A.getArgNo(),
392b7e51b4fSNikita Popov                        getLatticeValueFor(&A));
393b7e51b4fSNikita Popov   }
39424fe1d4fSNikita Popov }
39524fe1d4fSNikita Popov 
396bbab9f98SSjoerd Meijer /// Helper class for SCCPSolver. This implements the instruction visitor and
397bbab9f98SSjoerd Meijer /// holds all the state.
398bbab9f98SSjoerd Meijer class SCCPInstVisitor : public InstVisitor<SCCPInstVisitor> {
399bbab9f98SSjoerd Meijer   const DataLayout &DL;
400bbab9f98SSjoerd Meijer   std::function<const TargetLibraryInfo &(Function &)> GetTLI;
401bbab9f98SSjoerd Meijer   SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable.
402bbab9f98SSjoerd Meijer   DenseMap<Value *, ValueLatticeElement>
403bbab9f98SSjoerd Meijer       ValueState; // The state each value is in.
404bbab9f98SSjoerd Meijer 
405bbab9f98SSjoerd Meijer   /// StructValueState - This maintains ValueState for values that have
406bbab9f98SSjoerd Meijer   /// StructType, for example for formal arguments, calls, insertelement, etc.
407bbab9f98SSjoerd Meijer   DenseMap<std::pair<Value *, unsigned>, ValueLatticeElement> StructValueState;
408bbab9f98SSjoerd Meijer 
409bbab9f98SSjoerd Meijer   /// GlobalValue - If we are tracking any values for the contents of a global
410bbab9f98SSjoerd Meijer   /// variable, we keep a mapping from the constant accessor to the element of
411bbab9f98SSjoerd Meijer   /// the global, to the currently known value.  If the value becomes
412bbab9f98SSjoerd Meijer   /// overdefined, it's entry is simply removed from this map.
413bbab9f98SSjoerd Meijer   DenseMap<GlobalVariable *, ValueLatticeElement> TrackedGlobals;
414bbab9f98SSjoerd Meijer 
415bbab9f98SSjoerd Meijer   /// TrackedRetVals - If we are tracking arguments into and the return
416bbab9f98SSjoerd Meijer   /// value out of a function, it will have an entry in this map, indicating
417bbab9f98SSjoerd Meijer   /// what the known return value for the function is.
418bbab9f98SSjoerd Meijer   MapVector<Function *, ValueLatticeElement> TrackedRetVals;
419bbab9f98SSjoerd Meijer 
420bbab9f98SSjoerd Meijer   /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
421bbab9f98SSjoerd Meijer   /// that return multiple values.
422bbab9f98SSjoerd Meijer   MapVector<std::pair<Function *, unsigned>, ValueLatticeElement>
423bbab9f98SSjoerd Meijer       TrackedMultipleRetVals;
424bbab9f98SSjoerd Meijer 
42554e5fb78SAlexandros Lamprineas   /// The set of values whose lattice has been invalidated.
42654e5fb78SAlexandros Lamprineas   /// Populated by resetLatticeValueFor(), cleared after resolving undefs.
42754e5fb78SAlexandros Lamprineas   DenseSet<Value *> Invalidated;
42854e5fb78SAlexandros Lamprineas 
429bbab9f98SSjoerd Meijer   /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
430bbab9f98SSjoerd Meijer   /// represented here for efficient lookup.
431bbab9f98SSjoerd Meijer   SmallPtrSet<Function *, 16> MRVFunctionsTracked;
432bbab9f98SSjoerd Meijer 
433bbab9f98SSjoerd Meijer   /// A list of functions whose return cannot be modified.
434bbab9f98SSjoerd Meijer   SmallPtrSet<Function *, 16> MustPreserveReturnsInFunctions;
435bbab9f98SSjoerd Meijer 
436bbab9f98SSjoerd Meijer   /// TrackingIncomingArguments - This is the set of functions for whose
437bbab9f98SSjoerd Meijer   /// arguments we make optimistic assumptions about and try to prove as
438bbab9f98SSjoerd Meijer   /// constants.
439bbab9f98SSjoerd Meijer   SmallPtrSet<Function *, 16> TrackingIncomingArguments;
440bbab9f98SSjoerd Meijer 
441bbab9f98SSjoerd Meijer   /// The reason for two worklists is that overdefined is the lowest state
442bbab9f98SSjoerd Meijer   /// on the lattice, and moving things to overdefined as fast as possible
443bbab9f98SSjoerd Meijer   /// makes SCCP converge much faster.
444bbab9f98SSjoerd Meijer   ///
445bbab9f98SSjoerd Meijer   /// By having a separate worklist, we accomplish this because everything
446bbab9f98SSjoerd Meijer   /// possibly overdefined will become overdefined at the soonest possible
447bbab9f98SSjoerd Meijer   /// point.
448bbab9f98SSjoerd Meijer   SmallVector<Value *, 64> OverdefinedInstWorkList;
449bbab9f98SSjoerd Meijer   SmallVector<Value *, 64> InstWorkList;
450bbab9f98SSjoerd Meijer 
451bbab9f98SSjoerd Meijer   // The BasicBlock work list
452bbab9f98SSjoerd Meijer   SmallVector<BasicBlock *, 64> BBWorkList;
453bbab9f98SSjoerd Meijer 
454bbab9f98SSjoerd Meijer   /// KnownFeasibleEdges - Entries in this set are edges which have already had
455bbab9f98SSjoerd Meijer   /// PHI nodes retriggered.
456bbab9f98SSjoerd Meijer   using Edge = std::pair<BasicBlock *, BasicBlock *>;
457bbab9f98SSjoerd Meijer   DenseSet<Edge> KnownFeasibleEdges;
458bbab9f98SSjoerd Meijer 
459b1f41685SAlexandros Lamprineas   DenseMap<Function *, std::unique_ptr<PredicateInfo>> FnPredicateInfo;
460b1f41685SAlexandros Lamprineas 
461aec3ec04SFlorian Mayer   DenseMap<Value *, SmallSetVector<User *, 2>> AdditionalUsers;
462bbab9f98SSjoerd Meijer 
463bbab9f98SSjoerd Meijer   LLVMContext &Ctx;
464bbab9f98SSjoerd Meijer 
465bbab9f98SSjoerd Meijer private:
466664b7a4cSNikita Popov   ConstantInt *getConstantInt(const ValueLatticeElement &IV, Type *Ty) const {
467664b7a4cSNikita Popov     return dyn_cast_or_null<ConstantInt>(getConstant(IV, Ty));
468bbab9f98SSjoerd Meijer   }
469bbab9f98SSjoerd Meijer 
470bbab9f98SSjoerd Meijer   // pushToWorkList - Helper for markConstant/markOverdefined
471bbab9f98SSjoerd Meijer   void pushToWorkList(ValueLatticeElement &IV, Value *V);
472bbab9f98SSjoerd Meijer 
473bbab9f98SSjoerd Meijer   // Helper to push \p V to the worklist, after updating it to \p IV. Also
474bbab9f98SSjoerd Meijer   // prints a debug message with the updated value.
475bbab9f98SSjoerd Meijer   void pushToWorkListMsg(ValueLatticeElement &IV, Value *V);
476bbab9f98SSjoerd Meijer 
477bbab9f98SSjoerd Meijer   // markConstant - Make a value be marked as "constant".  If the value
478bbab9f98SSjoerd Meijer   // is not already a constant, add it to the instruction work list so that
479bbab9f98SSjoerd Meijer   // the users of the instruction are updated later.
480bbab9f98SSjoerd Meijer   bool markConstant(ValueLatticeElement &IV, Value *V, Constant *C,
481bbab9f98SSjoerd Meijer                     bool MayIncludeUndef = false);
482bbab9f98SSjoerd Meijer 
483bbab9f98SSjoerd Meijer   bool markConstant(Value *V, Constant *C) {
484bbab9f98SSjoerd Meijer     assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
485bbab9f98SSjoerd Meijer     return markConstant(ValueState[V], V, C);
486bbab9f98SSjoerd Meijer   }
487bbab9f98SSjoerd Meijer 
4881cea5c21SNikita Popov   bool markNotConstant(ValueLatticeElement &IV, Value *V, Constant *C);
4891cea5c21SNikita Popov 
4901cea5c21SNikita Popov   bool markNotNull(ValueLatticeElement &IV, Value *V) {
4911cea5c21SNikita Popov     return markNotConstant(IV, V, Constant::getNullValue(V->getType()));
4921cea5c21SNikita Popov   }
4931cea5c21SNikita Popov 
494e7bc5372SAndreas Jonson   /// markConstantRange - Mark the object as constant range with \p CR. If the
495e7bc5372SAndreas Jonson   /// object is not a constant range with the range \p CR, add it to the
496e7bc5372SAndreas Jonson   /// instruction work list so that the users of the instruction are updated
497e7bc5372SAndreas Jonson   /// later.
498e7bc5372SAndreas Jonson   bool markConstantRange(ValueLatticeElement &IV, Value *V,
499e7bc5372SAndreas Jonson                          const ConstantRange &CR);
500e7bc5372SAndreas Jonson 
501bbab9f98SSjoerd Meijer   // markOverdefined - Make a value be marked as "overdefined". If the
502bbab9f98SSjoerd Meijer   // value is not already overdefined, add it to the overdefined instruction
503bbab9f98SSjoerd Meijer   // work list so that the users of the instruction are updated later.
504bbab9f98SSjoerd Meijer   bool markOverdefined(ValueLatticeElement &IV, Value *V);
505bbab9f98SSjoerd Meijer 
506bbab9f98SSjoerd Meijer   /// Merge \p MergeWithV into \p IV and push \p V to the worklist, if \p IV
507bbab9f98SSjoerd Meijer   /// changes.
508bbab9f98SSjoerd Meijer   bool mergeInValue(ValueLatticeElement &IV, Value *V,
509bbab9f98SSjoerd Meijer                     ValueLatticeElement MergeWithV,
510bbab9f98SSjoerd Meijer                     ValueLatticeElement::MergeOptions Opts = {
511bbab9f98SSjoerd Meijer                         /*MayIncludeUndef=*/false, /*CheckWiden=*/false});
512bbab9f98SSjoerd Meijer 
513bbab9f98SSjoerd Meijer   bool mergeInValue(Value *V, ValueLatticeElement MergeWithV,
514bbab9f98SSjoerd Meijer                     ValueLatticeElement::MergeOptions Opts = {
515bbab9f98SSjoerd Meijer                         /*MayIncludeUndef=*/false, /*CheckWiden=*/false}) {
516bbab9f98SSjoerd Meijer     assert(!V->getType()->isStructTy() &&
517bbab9f98SSjoerd Meijer            "non-structs should use markConstant");
518bbab9f98SSjoerd Meijer     return mergeInValue(ValueState[V], V, MergeWithV, Opts);
519bbab9f98SSjoerd Meijer   }
520bbab9f98SSjoerd Meijer 
521bbab9f98SSjoerd Meijer   /// getValueState - Return the ValueLatticeElement object that corresponds to
522bbab9f98SSjoerd Meijer   /// the value.  This function handles the case when the value hasn't been seen
523bbab9f98SSjoerd Meijer   /// yet by properly seeding constants etc.
524bbab9f98SSjoerd Meijer   ValueLatticeElement &getValueState(Value *V) {
525bbab9f98SSjoerd Meijer     assert(!V->getType()->isStructTy() && "Should use getStructValueState");
526bbab9f98SSjoerd Meijer 
527bbab9f98SSjoerd Meijer     auto I = ValueState.insert(std::make_pair(V, ValueLatticeElement()));
528bbab9f98SSjoerd Meijer     ValueLatticeElement &LV = I.first->second;
529bbab9f98SSjoerd Meijer 
530bbab9f98SSjoerd Meijer     if (!I.second)
531bbab9f98SSjoerd Meijer       return LV; // Common case, already in the map.
532bbab9f98SSjoerd Meijer 
533bbab9f98SSjoerd Meijer     if (auto *C = dyn_cast<Constant>(V))
534bbab9f98SSjoerd Meijer       LV.markConstant(C); // Constants are constant
535bbab9f98SSjoerd Meijer 
536bbab9f98SSjoerd Meijer     // All others are unknown by default.
537bbab9f98SSjoerd Meijer     return LV;
538bbab9f98SSjoerd Meijer   }
539bbab9f98SSjoerd Meijer 
540bbab9f98SSjoerd Meijer   /// getStructValueState - Return the ValueLatticeElement object that
541bbab9f98SSjoerd Meijer   /// corresponds to the value/field pair.  This function handles the case when
542bbab9f98SSjoerd Meijer   /// the value hasn't been seen yet by properly seeding constants etc.
543bbab9f98SSjoerd Meijer   ValueLatticeElement &getStructValueState(Value *V, unsigned i) {
544bbab9f98SSjoerd Meijer     assert(V->getType()->isStructTy() && "Should use getValueState");
545bbab9f98SSjoerd Meijer     assert(i < cast<StructType>(V->getType())->getNumElements() &&
546bbab9f98SSjoerd Meijer            "Invalid element #");
547bbab9f98SSjoerd Meijer 
548bbab9f98SSjoerd Meijer     auto I = StructValueState.insert(
549bbab9f98SSjoerd Meijer         std::make_pair(std::make_pair(V, i), ValueLatticeElement()));
550bbab9f98SSjoerd Meijer     ValueLatticeElement &LV = I.first->second;
551bbab9f98SSjoerd Meijer 
552bbab9f98SSjoerd Meijer     if (!I.second)
553bbab9f98SSjoerd Meijer       return LV; // Common case, already in the map.
554bbab9f98SSjoerd Meijer 
555bbab9f98SSjoerd Meijer     if (auto *C = dyn_cast<Constant>(V)) {
556bbab9f98SSjoerd Meijer       Constant *Elt = C->getAggregateElement(i);
557bbab9f98SSjoerd Meijer 
558bbab9f98SSjoerd Meijer       if (!Elt)
559bbab9f98SSjoerd Meijer         LV.markOverdefined(); // Unknown sort of constant.
560bbab9f98SSjoerd Meijer       else
561bbab9f98SSjoerd Meijer         LV.markConstant(Elt); // Constants are constant.
562bbab9f98SSjoerd Meijer     }
563bbab9f98SSjoerd Meijer 
564bbab9f98SSjoerd Meijer     // All others are underdefined by default.
565bbab9f98SSjoerd Meijer     return LV;
566bbab9f98SSjoerd Meijer   }
567bbab9f98SSjoerd Meijer 
56854e5fb78SAlexandros Lamprineas   /// Traverse the use-def chain of \p Call, marking itself and its users as
56954e5fb78SAlexandros Lamprineas   /// "unknown" on the way.
57054e5fb78SAlexandros Lamprineas   void invalidate(CallBase *Call) {
57154e5fb78SAlexandros Lamprineas     SmallVector<Instruction *, 64> ToInvalidate;
57254e5fb78SAlexandros Lamprineas     ToInvalidate.push_back(Call);
57354e5fb78SAlexandros Lamprineas 
57454e5fb78SAlexandros Lamprineas     while (!ToInvalidate.empty()) {
57554e5fb78SAlexandros Lamprineas       Instruction *Inst = ToInvalidate.pop_back_val();
57654e5fb78SAlexandros Lamprineas 
57754e5fb78SAlexandros Lamprineas       if (!Invalidated.insert(Inst).second)
57854e5fb78SAlexandros Lamprineas         continue;
57954e5fb78SAlexandros Lamprineas 
58054e5fb78SAlexandros Lamprineas       if (!BBExecutable.count(Inst->getParent()))
58154e5fb78SAlexandros Lamprineas         continue;
58254e5fb78SAlexandros Lamprineas 
58354e5fb78SAlexandros Lamprineas       Value *V = nullptr;
58454e5fb78SAlexandros Lamprineas       // For return instructions we need to invalidate the tracked returns map.
58554e5fb78SAlexandros Lamprineas       // Anything else has its lattice in the value map.
58654e5fb78SAlexandros Lamprineas       if (auto *RetInst = dyn_cast<ReturnInst>(Inst)) {
58754e5fb78SAlexandros Lamprineas         Function *F = RetInst->getParent()->getParent();
58854e5fb78SAlexandros Lamprineas         if (auto It = TrackedRetVals.find(F); It != TrackedRetVals.end()) {
58954e5fb78SAlexandros Lamprineas           It->second = ValueLatticeElement();
59054e5fb78SAlexandros Lamprineas           V = F;
59154e5fb78SAlexandros Lamprineas         } else if (MRVFunctionsTracked.count(F)) {
59254e5fb78SAlexandros Lamprineas           auto *STy = cast<StructType>(F->getReturnType());
59354e5fb78SAlexandros Lamprineas           for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I)
59454e5fb78SAlexandros Lamprineas             TrackedMultipleRetVals[{F, I}] = ValueLatticeElement();
59554e5fb78SAlexandros Lamprineas           V = F;
59654e5fb78SAlexandros Lamprineas         }
59754e5fb78SAlexandros Lamprineas       } else if (auto *STy = dyn_cast<StructType>(Inst->getType())) {
59854e5fb78SAlexandros Lamprineas         for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
59954e5fb78SAlexandros Lamprineas           if (auto It = StructValueState.find({Inst, I});
60054e5fb78SAlexandros Lamprineas               It != StructValueState.end()) {
60154e5fb78SAlexandros Lamprineas             It->second = ValueLatticeElement();
60254e5fb78SAlexandros Lamprineas             V = Inst;
60354e5fb78SAlexandros Lamprineas           }
60454e5fb78SAlexandros Lamprineas         }
60554e5fb78SAlexandros Lamprineas       } else if (auto It = ValueState.find(Inst); It != ValueState.end()) {
60654e5fb78SAlexandros Lamprineas         It->second = ValueLatticeElement();
60754e5fb78SAlexandros Lamprineas         V = Inst;
60854e5fb78SAlexandros Lamprineas       }
60954e5fb78SAlexandros Lamprineas 
61054e5fb78SAlexandros Lamprineas       if (V) {
61154e5fb78SAlexandros Lamprineas         LLVM_DEBUG(dbgs() << "Invalidated lattice for " << *V << "\n");
61254e5fb78SAlexandros Lamprineas 
61354e5fb78SAlexandros Lamprineas         for (User *U : V->users())
61454e5fb78SAlexandros Lamprineas           if (auto *UI = dyn_cast<Instruction>(U))
61554e5fb78SAlexandros Lamprineas             ToInvalidate.push_back(UI);
61654e5fb78SAlexandros Lamprineas 
61754e5fb78SAlexandros Lamprineas         auto It = AdditionalUsers.find(V);
61854e5fb78SAlexandros Lamprineas         if (It != AdditionalUsers.end())
61954e5fb78SAlexandros Lamprineas           for (User *U : It->second)
62054e5fb78SAlexandros Lamprineas             if (auto *UI = dyn_cast<Instruction>(U))
62154e5fb78SAlexandros Lamprineas               ToInvalidate.push_back(UI);
62254e5fb78SAlexandros Lamprineas       }
62354e5fb78SAlexandros Lamprineas     }
62454e5fb78SAlexandros Lamprineas   }
62554e5fb78SAlexandros Lamprineas 
626bbab9f98SSjoerd Meijer   /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
627bbab9f98SSjoerd Meijer   /// work list if it is not already executable.
628bbab9f98SSjoerd Meijer   bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest);
629bbab9f98SSjoerd Meijer 
630bbab9f98SSjoerd Meijer   // getFeasibleSuccessors - Return a vector of booleans to indicate which
631bbab9f98SSjoerd Meijer   // successors are reachable from a given terminator instruction.
632bbab9f98SSjoerd Meijer   void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs);
633bbab9f98SSjoerd Meijer 
634bbab9f98SSjoerd Meijer   // OperandChangedState - This method is invoked on all of the users of an
635bbab9f98SSjoerd Meijer   // instruction that was just changed state somehow.  Based on this
636bbab9f98SSjoerd Meijer   // information, we need to update the specified user of this instruction.
63739d29817SSjoerd Meijer   void operandChangedState(Instruction *I) {
638bbab9f98SSjoerd Meijer     if (BBExecutable.count(I->getParent())) // Inst is executable?
639bbab9f98SSjoerd Meijer       visit(*I);
640bbab9f98SSjoerd Meijer   }
641bbab9f98SSjoerd Meijer 
642bbab9f98SSjoerd Meijer   // Add U as additional user of V.
643e1d205a3SKazu Hirata   void addAdditionalUser(Value *V, User *U) { AdditionalUsers[V].insert(U); }
644bbab9f98SSjoerd Meijer 
645bbab9f98SSjoerd Meijer   // Mark I's users as changed, including AdditionalUsers.
646bbab9f98SSjoerd Meijer   void markUsersAsChanged(Value *I) {
647bbab9f98SSjoerd Meijer     // Functions include their arguments in the use-list. Changed function
648bbab9f98SSjoerd Meijer     // values mean that the result of the function changed. We only need to
649bbab9f98SSjoerd Meijer     // update the call sites with the new function result and do not have to
650bbab9f98SSjoerd Meijer     // propagate the call arguments.
651bbab9f98SSjoerd Meijer     if (isa<Function>(I)) {
652bbab9f98SSjoerd Meijer       for (User *U : I->users()) {
653bbab9f98SSjoerd Meijer         if (auto *CB = dyn_cast<CallBase>(U))
654bbab9f98SSjoerd Meijer           handleCallResult(*CB);
655bbab9f98SSjoerd Meijer       }
656bbab9f98SSjoerd Meijer     } else {
657bbab9f98SSjoerd Meijer       for (User *U : I->users())
658bbab9f98SSjoerd Meijer         if (auto *UI = dyn_cast<Instruction>(U))
65939d29817SSjoerd Meijer           operandChangedState(UI);
660bbab9f98SSjoerd Meijer     }
661bbab9f98SSjoerd Meijer 
662bbab9f98SSjoerd Meijer     auto Iter = AdditionalUsers.find(I);
663bbab9f98SSjoerd Meijer     if (Iter != AdditionalUsers.end()) {
664bbab9f98SSjoerd Meijer       // Copy additional users before notifying them of changes, because new
665bbab9f98SSjoerd Meijer       // users may be added, potentially invalidating the iterator.
666bbab9f98SSjoerd Meijer       SmallVector<Instruction *, 2> ToNotify;
667bbab9f98SSjoerd Meijer       for (User *U : Iter->second)
668bbab9f98SSjoerd Meijer         if (auto *UI = dyn_cast<Instruction>(U))
669bbab9f98SSjoerd Meijer           ToNotify.push_back(UI);
670bbab9f98SSjoerd Meijer       for (Instruction *UI : ToNotify)
67139d29817SSjoerd Meijer         operandChangedState(UI);
672bbab9f98SSjoerd Meijer     }
673bbab9f98SSjoerd Meijer   }
674bbab9f98SSjoerd Meijer   void handleCallOverdefined(CallBase &CB);
675bbab9f98SSjoerd Meijer   void handleCallResult(CallBase &CB);
676bbab9f98SSjoerd Meijer   void handleCallArguments(CallBase &CB);
677f101196dSNikita Popov   void handleExtractOfWithOverflow(ExtractValueInst &EVI,
678f101196dSNikita Popov                                    const WithOverflowInst *WO, unsigned Idx);
679bbab9f98SSjoerd Meijer 
680bbab9f98SSjoerd Meijer private:
681bbab9f98SSjoerd Meijer   friend class InstVisitor<SCCPInstVisitor>;
682bbab9f98SSjoerd Meijer 
683bbab9f98SSjoerd Meijer   // visit implementations - Something changed in this instruction.  Either an
684bbab9f98SSjoerd Meijer   // operand made a transition, or the instruction is newly executable.  Change
685bbab9f98SSjoerd Meijer   // the value type of I to reflect these changes if appropriate.
686bbab9f98SSjoerd Meijer   void visitPHINode(PHINode &I);
687bbab9f98SSjoerd Meijer 
688bbab9f98SSjoerd Meijer   // Terminators
689bbab9f98SSjoerd Meijer 
690bbab9f98SSjoerd Meijer   void visitReturnInst(ReturnInst &I);
691bbab9f98SSjoerd Meijer   void visitTerminator(Instruction &TI);
692bbab9f98SSjoerd Meijer 
693bbab9f98SSjoerd Meijer   void visitCastInst(CastInst &I);
694bbab9f98SSjoerd Meijer   void visitSelectInst(SelectInst &I);
695bbab9f98SSjoerd Meijer   void visitUnaryOperator(Instruction &I);
696d37d4072SMikhail Gudim   void visitFreezeInst(FreezeInst &I);
697bbab9f98SSjoerd Meijer   void visitBinaryOperator(Instruction &I);
698bbab9f98SSjoerd Meijer   void visitCmpInst(CmpInst &I);
699bbab9f98SSjoerd Meijer   void visitExtractValueInst(ExtractValueInst &EVI);
700bbab9f98SSjoerd Meijer   void visitInsertValueInst(InsertValueInst &IVI);
701bbab9f98SSjoerd Meijer 
702bbab9f98SSjoerd Meijer   void visitCatchSwitchInst(CatchSwitchInst &CPI) {
703bbab9f98SSjoerd Meijer     markOverdefined(&CPI);
704bbab9f98SSjoerd Meijer     visitTerminator(CPI);
705bbab9f98SSjoerd Meijer   }
706bbab9f98SSjoerd Meijer 
707bbab9f98SSjoerd Meijer   // Instructions that cannot be folded away.
708bbab9f98SSjoerd Meijer 
709bbab9f98SSjoerd Meijer   void visitStoreInst(StoreInst &I);
710bbab9f98SSjoerd Meijer   void visitLoadInst(LoadInst &I);
711bbab9f98SSjoerd Meijer   void visitGetElementPtrInst(GetElementPtrInst &I);
712657f26f0SNikita Popov   void visitAllocaInst(AllocaInst &AI);
713bbab9f98SSjoerd Meijer 
714bbab9f98SSjoerd Meijer   void visitInvokeInst(InvokeInst &II) {
715bbab9f98SSjoerd Meijer     visitCallBase(II);
716bbab9f98SSjoerd Meijer     visitTerminator(II);
717bbab9f98SSjoerd Meijer   }
718bbab9f98SSjoerd Meijer 
719bbab9f98SSjoerd Meijer   void visitCallBrInst(CallBrInst &CBI) {
720bbab9f98SSjoerd Meijer     visitCallBase(CBI);
721bbab9f98SSjoerd Meijer     visitTerminator(CBI);
722bbab9f98SSjoerd Meijer   }
723bbab9f98SSjoerd Meijer 
724bbab9f98SSjoerd Meijer   void visitCallBase(CallBase &CB);
725bbab9f98SSjoerd Meijer   void visitResumeInst(ResumeInst &I) { /*returns void*/
726bbab9f98SSjoerd Meijer   }
727bbab9f98SSjoerd Meijer   void visitUnreachableInst(UnreachableInst &I) { /*returns void*/
728bbab9f98SSjoerd Meijer   }
729bbab9f98SSjoerd Meijer   void visitFenceInst(FenceInst &I) { /*returns void*/
730bbab9f98SSjoerd Meijer   }
731bbab9f98SSjoerd Meijer 
732bbab9f98SSjoerd Meijer   void visitInstruction(Instruction &I);
733bbab9f98SSjoerd Meijer 
734bbab9f98SSjoerd Meijer public:
735b1f41685SAlexandros Lamprineas   void addPredicateInfo(Function &F, DominatorTree &DT, AssumptionCache &AC) {
736b1f41685SAlexandros Lamprineas     FnPredicateInfo.insert({&F, std::make_unique<PredicateInfo>(F, DT, AC)});
737bbab9f98SSjoerd Meijer   }
738bbab9f98SSjoerd Meijer 
739c4a0969bSSjoerd Meijer   void visitCallInst(CallInst &I) { visitCallBase(I); }
740c4a0969bSSjoerd Meijer 
74139d29817SSjoerd Meijer   bool markBlockExecutable(BasicBlock *BB);
742bbab9f98SSjoerd Meijer 
743bbab9f98SSjoerd Meijer   const PredicateBase *getPredicateInfoFor(Instruction *I) {
744b1f41685SAlexandros Lamprineas     auto It = FnPredicateInfo.find(I->getParent()->getParent());
745b1f41685SAlexandros Lamprineas     if (It == FnPredicateInfo.end())
746bbab9f98SSjoerd Meijer       return nullptr;
747b1f41685SAlexandros Lamprineas     return It->second->getPredicateInfoFor(I);
748bbab9f98SSjoerd Meijer   }
749bbab9f98SSjoerd Meijer 
750bbab9f98SSjoerd Meijer   SCCPInstVisitor(const DataLayout &DL,
751bbab9f98SSjoerd Meijer                   std::function<const TargetLibraryInfo &(Function &)> GetTLI,
752bbab9f98SSjoerd Meijer                   LLVMContext &Ctx)
753bbab9f98SSjoerd Meijer       : DL(DL), GetTLI(GetTLI), Ctx(Ctx) {}
754bbab9f98SSjoerd Meijer 
75539d29817SSjoerd Meijer   void trackValueOfGlobalVariable(GlobalVariable *GV) {
756bbab9f98SSjoerd Meijer     // We only track the contents of scalar globals.
757bbab9f98SSjoerd Meijer     if (GV->getValueType()->isSingleValueType()) {
758bbab9f98SSjoerd Meijer       ValueLatticeElement &IV = TrackedGlobals[GV];
759bbab9f98SSjoerd Meijer       IV.markConstant(GV->getInitializer());
760bbab9f98SSjoerd Meijer     }
761bbab9f98SSjoerd Meijer   }
762bbab9f98SSjoerd Meijer 
76339d29817SSjoerd Meijer   void addTrackedFunction(Function *F) {
764bbab9f98SSjoerd Meijer     // Add an entry, F -> undef.
765bbab9f98SSjoerd Meijer     if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
766bbab9f98SSjoerd Meijer       MRVFunctionsTracked.insert(F);
767bbab9f98SSjoerd Meijer       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
768bbab9f98SSjoerd Meijer         TrackedMultipleRetVals.insert(
769bbab9f98SSjoerd Meijer             std::make_pair(std::make_pair(F, i), ValueLatticeElement()));
770bbab9f98SSjoerd Meijer     } else if (!F->getReturnType()->isVoidTy())
771bbab9f98SSjoerd Meijer       TrackedRetVals.insert(std::make_pair(F, ValueLatticeElement()));
772bbab9f98SSjoerd Meijer   }
773bbab9f98SSjoerd Meijer 
774bbab9f98SSjoerd Meijer   void addToMustPreserveReturnsInFunctions(Function *F) {
775bbab9f98SSjoerd Meijer     MustPreserveReturnsInFunctions.insert(F);
776bbab9f98SSjoerd Meijer   }
777bbab9f98SSjoerd Meijer 
778bbab9f98SSjoerd Meijer   bool mustPreserveReturn(Function *F) {
779bbab9f98SSjoerd Meijer     return MustPreserveReturnsInFunctions.count(F);
780bbab9f98SSjoerd Meijer   }
781bbab9f98SSjoerd Meijer 
78239d29817SSjoerd Meijer   void addArgumentTrackedFunction(Function *F) {
783bbab9f98SSjoerd Meijer     TrackingIncomingArguments.insert(F);
784bbab9f98SSjoerd Meijer   }
785bbab9f98SSjoerd Meijer 
786bbab9f98SSjoerd Meijer   bool isArgumentTrackedFunction(Function *F) {
787bbab9f98SSjoerd Meijer     return TrackingIncomingArguments.count(F);
788bbab9f98SSjoerd Meijer   }
789bbab9f98SSjoerd Meijer 
790b7e51b4fSNikita Popov   const SmallPtrSetImpl<Function *> &getArgumentTrackedFunctions() const {
791b7e51b4fSNikita Popov     return TrackingIncomingArguments;
792b7e51b4fSNikita Popov   }
793b7e51b4fSNikita Popov 
79439d29817SSjoerd Meijer   void solve();
795bbab9f98SSjoerd Meijer 
79654e5fb78SAlexandros Lamprineas   bool resolvedUndef(Instruction &I);
79754e5fb78SAlexandros Lamprineas 
79839d29817SSjoerd Meijer   bool resolvedUndefsIn(Function &F);
799bbab9f98SSjoerd Meijer 
800bbab9f98SSjoerd Meijer   bool isBlockExecutable(BasicBlock *BB) const {
801bbab9f98SSjoerd Meijer     return BBExecutable.count(BB);
802bbab9f98SSjoerd Meijer   }
803bbab9f98SSjoerd Meijer 
804bbab9f98SSjoerd Meijer   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const;
805bbab9f98SSjoerd Meijer 
806bbab9f98SSjoerd Meijer   std::vector<ValueLatticeElement> getStructLatticeValueFor(Value *V) const {
807bbab9f98SSjoerd Meijer     std::vector<ValueLatticeElement> StructValues;
808bbab9f98SSjoerd Meijer     auto *STy = dyn_cast<StructType>(V->getType());
809bbab9f98SSjoerd Meijer     assert(STy && "getStructLatticeValueFor() can be called only on structs");
810bbab9f98SSjoerd Meijer     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
811bbab9f98SSjoerd Meijer       auto I = StructValueState.find(std::make_pair(V, i));
812bbab9f98SSjoerd Meijer       assert(I != StructValueState.end() && "Value not in valuemap!");
813bbab9f98SSjoerd Meijer       StructValues.push_back(I->second);
814bbab9f98SSjoerd Meijer     }
815bbab9f98SSjoerd Meijer     return StructValues;
816bbab9f98SSjoerd Meijer   }
817bbab9f98SSjoerd Meijer 
81823ea58f3SVitaly Buka   void removeLatticeValueFor(Value *V) { ValueState.erase(V); }
819bbab9f98SSjoerd Meijer 
82054e5fb78SAlexandros Lamprineas   /// Invalidate the Lattice Value of \p Call and its users after specializing
82154e5fb78SAlexandros Lamprineas   /// the call. Then recompute it.
82254e5fb78SAlexandros Lamprineas   void resetLatticeValueFor(CallBase *Call) {
82354e5fb78SAlexandros Lamprineas     // Calls to void returning functions do not need invalidation.
82454e5fb78SAlexandros Lamprineas     Function *F = Call->getCalledFunction();
82554e5fb78SAlexandros Lamprineas     (void)F;
82654e5fb78SAlexandros Lamprineas     assert(!F->getReturnType()->isVoidTy() &&
82754e5fb78SAlexandros Lamprineas            (TrackedRetVals.count(F) || MRVFunctionsTracked.count(F)) &&
82854e5fb78SAlexandros Lamprineas            "All non void specializations should be tracked");
82954e5fb78SAlexandros Lamprineas     invalidate(Call);
83054e5fb78SAlexandros Lamprineas     handleCallResult(*Call);
83154e5fb78SAlexandros Lamprineas   }
83254e5fb78SAlexandros Lamprineas 
833bbab9f98SSjoerd Meijer   const ValueLatticeElement &getLatticeValueFor(Value *V) const {
834bbab9f98SSjoerd Meijer     assert(!V->getType()->isStructTy() &&
835bbab9f98SSjoerd Meijer            "Should use getStructLatticeValueFor");
836bbab9f98SSjoerd Meijer     DenseMap<Value *, ValueLatticeElement>::const_iterator I =
837bbab9f98SSjoerd Meijer         ValueState.find(V);
838bbab9f98SSjoerd Meijer     assert(I != ValueState.end() &&
839bbab9f98SSjoerd Meijer            "V not found in ValueState nor Paramstate map!");
840bbab9f98SSjoerd Meijer     return I->second;
841bbab9f98SSjoerd Meijer   }
842bbab9f98SSjoerd Meijer 
843bbab9f98SSjoerd Meijer   const MapVector<Function *, ValueLatticeElement> &getTrackedRetVals() {
844bbab9f98SSjoerd Meijer     return TrackedRetVals;
845bbab9f98SSjoerd Meijer   }
846bbab9f98SSjoerd Meijer 
847bbab9f98SSjoerd Meijer   const DenseMap<GlobalVariable *, ValueLatticeElement> &getTrackedGlobals() {
848bbab9f98SSjoerd Meijer     return TrackedGlobals;
849bbab9f98SSjoerd Meijer   }
850bbab9f98SSjoerd Meijer 
851bbab9f98SSjoerd Meijer   const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
852bbab9f98SSjoerd Meijer     return MRVFunctionsTracked;
853bbab9f98SSjoerd Meijer   }
854bbab9f98SSjoerd Meijer 
855bbab9f98SSjoerd Meijer   void markOverdefined(Value *V) {
856bbab9f98SSjoerd Meijer     if (auto *STy = dyn_cast<StructType>(V->getType()))
857bbab9f98SSjoerd Meijer       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
858bbab9f98SSjoerd Meijer         markOverdefined(getStructValueState(V, i), V);
859bbab9f98SSjoerd Meijer     else
860bbab9f98SSjoerd Meijer       markOverdefined(ValueState[V], V);
861bbab9f98SSjoerd Meijer   }
862bbab9f98SSjoerd Meijer 
8637f59264dSNikita Popov   ValueLatticeElement getArgAttributeVL(Argument *A) {
8646b76c1e6SNikita Popov     if (A->getType()->isIntOrIntVectorTy()) {
8657f59264dSNikita Popov       if (std::optional<ConstantRange> Range = A->getRange())
8667f59264dSNikita Popov         return ValueLatticeElement::getRange(*Range);
867e7bc5372SAndreas Jonson     }
8687f59264dSNikita Popov     if (A->hasNonNullAttr())
8697f59264dSNikita Popov       return ValueLatticeElement::getNot(Constant::getNullValue(A->getType()));
8701cea5c21SNikita Popov     // Assume nothing about the incoming arguments without attributes.
8717f59264dSNikita Popov     return ValueLatticeElement::getOverdefined();
8727f59264dSNikita Popov   }
8737f59264dSNikita Popov 
8747f59264dSNikita Popov   void trackValueOfArgument(Argument *A) {
8757f59264dSNikita Popov     if (A->getType()->isStructTy())
8767f59264dSNikita Popov       return (void)markOverdefined(A);
8777f59264dSNikita Popov     mergeInValue(A, getArgAttributeVL(A));
878e7bc5372SAndreas Jonson   }
879e7bc5372SAndreas Jonson 
880bbab9f98SSjoerd Meijer   bool isStructLatticeConstant(Function *F, StructType *STy);
881bbab9f98SSjoerd Meijer 
882664b7a4cSNikita Popov   Constant *getConstant(const ValueLatticeElement &LV, Type *Ty) const;
883c4a0969bSSjoerd Meijer 
8847ea597eaSAlexandros Lamprineas   Constant *getConstantOrNull(Value *V) const;
8857ea597eaSAlexandros Lamprineas 
8867ea597eaSAlexandros Lamprineas   void setLatticeValueForSpecializationArguments(Function *F,
8878045bf9dSAlexandros Lamprineas                                        const SmallVectorImpl<ArgInfo> &Args);
888c4a0969bSSjoerd Meijer 
889c4a0969bSSjoerd Meijer   void markFunctionUnreachable(Function *F) {
890c4a0969bSSjoerd Meijer     for (auto &BB : *F)
891c4a0969bSSjoerd Meijer       BBExecutable.erase(&BB);
892c4a0969bSSjoerd Meijer   }
8938136a017SAlexandros Lamprineas 
8948136a017SAlexandros Lamprineas   void solveWhileResolvedUndefsIn(Module &M) {
8958136a017SAlexandros Lamprineas     bool ResolvedUndefs = true;
8968136a017SAlexandros Lamprineas     while (ResolvedUndefs) {
8978136a017SAlexandros Lamprineas       solve();
8988136a017SAlexandros Lamprineas       ResolvedUndefs = false;
8998136a017SAlexandros Lamprineas       for (Function &F : M)
9008136a017SAlexandros Lamprineas         ResolvedUndefs |= resolvedUndefsIn(F);
9018136a017SAlexandros Lamprineas     }
9028136a017SAlexandros Lamprineas   }
9038136a017SAlexandros Lamprineas 
9048136a017SAlexandros Lamprineas   void solveWhileResolvedUndefsIn(SmallVectorImpl<Function *> &WorkList) {
9058136a017SAlexandros Lamprineas     bool ResolvedUndefs = true;
9068136a017SAlexandros Lamprineas     while (ResolvedUndefs) {
9078136a017SAlexandros Lamprineas       solve();
9088136a017SAlexandros Lamprineas       ResolvedUndefs = false;
9098136a017SAlexandros Lamprineas       for (Function *F : WorkList)
9108136a017SAlexandros Lamprineas         ResolvedUndefs |= resolvedUndefsIn(*F);
9118136a017SAlexandros Lamprineas     }
9128136a017SAlexandros Lamprineas   }
91354e5fb78SAlexandros Lamprineas 
91454e5fb78SAlexandros Lamprineas   void solveWhileResolvedUndefs() {
91554e5fb78SAlexandros Lamprineas     bool ResolvedUndefs = true;
91654e5fb78SAlexandros Lamprineas     while (ResolvedUndefs) {
91754e5fb78SAlexandros Lamprineas       solve();
91854e5fb78SAlexandros Lamprineas       ResolvedUndefs = false;
91954e5fb78SAlexandros Lamprineas       for (Value *V : Invalidated)
92054e5fb78SAlexandros Lamprineas         if (auto *I = dyn_cast<Instruction>(V))
92154e5fb78SAlexandros Lamprineas           ResolvedUndefs |= resolvedUndef(*I);
92254e5fb78SAlexandros Lamprineas     }
92354e5fb78SAlexandros Lamprineas     Invalidated.clear();
92454e5fb78SAlexandros Lamprineas   }
925bbab9f98SSjoerd Meijer };
926bbab9f98SSjoerd Meijer 
927bbab9f98SSjoerd Meijer } // namespace llvm
928bbab9f98SSjoerd Meijer 
92939d29817SSjoerd Meijer bool SCCPInstVisitor::markBlockExecutable(BasicBlock *BB) {
930bbab9f98SSjoerd Meijer   if (!BBExecutable.insert(BB).second)
931bbab9f98SSjoerd Meijer     return false;
932bbab9f98SSjoerd Meijer   LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
933bbab9f98SSjoerd Meijer   BBWorkList.push_back(BB); // Add the block to the work list!
934bbab9f98SSjoerd Meijer   return true;
935bbab9f98SSjoerd Meijer }
936bbab9f98SSjoerd Meijer 
937bbab9f98SSjoerd Meijer void SCCPInstVisitor::pushToWorkList(ValueLatticeElement &IV, Value *V) {
938248b8534STamás Danyluk   if (IV.isOverdefined()) {
939248b8534STamás Danyluk     if (OverdefinedInstWorkList.empty() || OverdefinedInstWorkList.back() != V)
940248b8534STamás Danyluk       OverdefinedInstWorkList.push_back(V);
941248b8534STamás Danyluk     return;
942248b8534STamás Danyluk   }
943248b8534STamás Danyluk   if (InstWorkList.empty() || InstWorkList.back() != V)
944bbab9f98SSjoerd Meijer     InstWorkList.push_back(V);
945bbab9f98SSjoerd Meijer }
946bbab9f98SSjoerd Meijer 
947bbab9f98SSjoerd Meijer void SCCPInstVisitor::pushToWorkListMsg(ValueLatticeElement &IV, Value *V) {
948bbab9f98SSjoerd Meijer   LLVM_DEBUG(dbgs() << "updated " << IV << ": " << *V << '\n');
949bbab9f98SSjoerd Meijer   pushToWorkList(IV, V);
950bbab9f98SSjoerd Meijer }
951bbab9f98SSjoerd Meijer 
952bbab9f98SSjoerd Meijer bool SCCPInstVisitor::markConstant(ValueLatticeElement &IV, Value *V,
953bbab9f98SSjoerd Meijer                                    Constant *C, bool MayIncludeUndef) {
954bbab9f98SSjoerd Meijer   if (!IV.markConstant(C, MayIncludeUndef))
955bbab9f98SSjoerd Meijer     return false;
956bbab9f98SSjoerd Meijer   LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
957bbab9f98SSjoerd Meijer   pushToWorkList(IV, V);
958bbab9f98SSjoerd Meijer   return true;
959bbab9f98SSjoerd Meijer }
960bbab9f98SSjoerd Meijer 
9611cea5c21SNikita Popov bool SCCPInstVisitor::markNotConstant(ValueLatticeElement &IV, Value *V,
9621cea5c21SNikita Popov                                       Constant *C) {
9631cea5c21SNikita Popov   if (!IV.markNotConstant(C))
9641cea5c21SNikita Popov     return false;
9651cea5c21SNikita Popov   LLVM_DEBUG(dbgs() << "markNotConstant: " << *C << ": " << *V << '\n');
9661cea5c21SNikita Popov   pushToWorkList(IV, V);
9671cea5c21SNikita Popov   return true;
9681cea5c21SNikita Popov }
9691cea5c21SNikita Popov 
970e7bc5372SAndreas Jonson bool SCCPInstVisitor::markConstantRange(ValueLatticeElement &IV, Value *V,
971e7bc5372SAndreas Jonson                                         const ConstantRange &CR) {
972e7bc5372SAndreas Jonson   if (!IV.markConstantRange(CR))
973e7bc5372SAndreas Jonson     return false;
974e7bc5372SAndreas Jonson   LLVM_DEBUG(dbgs() << "markConstantRange: " << CR << ": " << *V << '\n');
975e7bc5372SAndreas Jonson   pushToWorkList(IV, V);
976e7bc5372SAndreas Jonson   return true;
977e7bc5372SAndreas Jonson }
978e7bc5372SAndreas Jonson 
979bbab9f98SSjoerd Meijer bool SCCPInstVisitor::markOverdefined(ValueLatticeElement &IV, Value *V) {
980bbab9f98SSjoerd Meijer   if (!IV.markOverdefined())
981bbab9f98SSjoerd Meijer     return false;
982bbab9f98SSjoerd Meijer 
983bbab9f98SSjoerd Meijer   LLVM_DEBUG(dbgs() << "markOverdefined: ";
984bbab9f98SSjoerd Meijer              if (auto *F = dyn_cast<Function>(V)) dbgs()
985bbab9f98SSjoerd Meijer              << "Function '" << F->getName() << "'\n";
986bbab9f98SSjoerd Meijer              else dbgs() << *V << '\n');
987bbab9f98SSjoerd Meijer   // Only instructions go on the work list
988bbab9f98SSjoerd Meijer   pushToWorkList(IV, V);
989bbab9f98SSjoerd Meijer   return true;
990bbab9f98SSjoerd Meijer }
991bbab9f98SSjoerd Meijer 
992bbab9f98SSjoerd Meijer bool SCCPInstVisitor::isStructLatticeConstant(Function *F, StructType *STy) {
993bbab9f98SSjoerd Meijer   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
994bbab9f98SSjoerd Meijer     const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
995bbab9f98SSjoerd Meijer     assert(It != TrackedMultipleRetVals.end());
996bbab9f98SSjoerd Meijer     ValueLatticeElement LV = It->second;
997a794b62cSFlorian Hahn     if (!SCCPSolver::isConstant(LV))
998bbab9f98SSjoerd Meijer       return false;
999bbab9f98SSjoerd Meijer   }
1000bbab9f98SSjoerd Meijer   return true;
1001bbab9f98SSjoerd Meijer }
1002bbab9f98SSjoerd Meijer 
1003664b7a4cSNikita Popov Constant *SCCPInstVisitor::getConstant(const ValueLatticeElement &LV,
1004664b7a4cSNikita Popov                                        Type *Ty) const {
1005664b7a4cSNikita Popov   if (LV.isConstant()) {
1006664b7a4cSNikita Popov     Constant *C = LV.getConstant();
1007664b7a4cSNikita Popov     assert(C->getType() == Ty && "Type mismatch");
1008664b7a4cSNikita Popov     return C;
1009664b7a4cSNikita Popov   }
1010bbab9f98SSjoerd Meijer 
1011bbab9f98SSjoerd Meijer   if (LV.isConstantRange()) {
101239d29817SSjoerd Meijer     const auto &CR = LV.getConstantRange();
1013bbab9f98SSjoerd Meijer     if (CR.getSingleElement())
1014664b7a4cSNikita Popov       return ConstantInt::get(Ty, *CR.getSingleElement());
1015bbab9f98SSjoerd Meijer   }
1016bbab9f98SSjoerd Meijer   return nullptr;
1017bbab9f98SSjoerd Meijer }
1018bbab9f98SSjoerd Meijer 
10197ea597eaSAlexandros Lamprineas Constant *SCCPInstVisitor::getConstantOrNull(Value *V) const {
10207ea597eaSAlexandros Lamprineas   Constant *Const = nullptr;
10217ea597eaSAlexandros Lamprineas   if (V->getType()->isStructTy()) {
10227ea597eaSAlexandros Lamprineas     std::vector<ValueLatticeElement> LVs = getStructLatticeValueFor(V);
10237ea597eaSAlexandros Lamprineas     if (any_of(LVs, SCCPSolver::isOverdefined))
10247ea597eaSAlexandros Lamprineas       return nullptr;
10257ea597eaSAlexandros Lamprineas     std::vector<Constant *> ConstVals;
10267ea597eaSAlexandros Lamprineas     auto *ST = cast<StructType>(V->getType());
10277ea597eaSAlexandros Lamprineas     for (unsigned I = 0, E = ST->getNumElements(); I != E; ++I) {
10287ea597eaSAlexandros Lamprineas       ValueLatticeElement LV = LVs[I];
10297ea597eaSAlexandros Lamprineas       ConstVals.push_back(SCCPSolver::isConstant(LV)
1030664b7a4cSNikita Popov                               ? getConstant(LV, ST->getElementType(I))
10317ea597eaSAlexandros Lamprineas                               : UndefValue::get(ST->getElementType(I)));
10327ea597eaSAlexandros Lamprineas     }
10337ea597eaSAlexandros Lamprineas     Const = ConstantStruct::get(ST, ConstVals);
10347ea597eaSAlexandros Lamprineas   } else {
10357ea597eaSAlexandros Lamprineas     const ValueLatticeElement &LV = getLatticeValueFor(V);
10367ea597eaSAlexandros Lamprineas     if (SCCPSolver::isOverdefined(LV))
10377ea597eaSAlexandros Lamprineas       return nullptr;
1038664b7a4cSNikita Popov     Const = SCCPSolver::isConstant(LV) ? getConstant(LV, V->getType())
10397ea597eaSAlexandros Lamprineas                                        : UndefValue::get(V->getType());
10407ea597eaSAlexandros Lamprineas   }
10417ea597eaSAlexandros Lamprineas   assert(Const && "Constant is nullptr here!");
10427ea597eaSAlexandros Lamprineas   return Const;
10437ea597eaSAlexandros Lamprineas }
10447ea597eaSAlexandros Lamprineas 
10457ea597eaSAlexandros Lamprineas void SCCPInstVisitor::setLatticeValueForSpecializationArguments(Function *F,
10467ea597eaSAlexandros Lamprineas                                         const SmallVectorImpl<ArgInfo> &Args) {
10478045bf9dSAlexandros Lamprineas   assert(!Args.empty() && "Specialization without arguments");
10488045bf9dSAlexandros Lamprineas   assert(F->arg_size() == Args[0].Formal->getParent()->arg_size() &&
1049c4a0969bSSjoerd Meijer          "Functions should have the same number of arguments");
1050c4a0969bSSjoerd Meijer 
10518045bf9dSAlexandros Lamprineas   auto Iter = Args.begin();
10527ea597eaSAlexandros Lamprineas   Function::arg_iterator NewArg = F->arg_begin();
10537ea597eaSAlexandros Lamprineas   Function::arg_iterator OldArg = Args[0].Formal->getParent()->arg_begin();
1054910eb988SAlexandros Lamprineas   for (auto End = F->arg_end(); NewArg != End; ++NewArg, ++OldArg) {
1055b803aee6SAlexandros Lamprineas 
1056b803aee6SAlexandros Lamprineas     LLVM_DEBUG(dbgs() << "SCCP: Marking argument "
1057b803aee6SAlexandros Lamprineas                       << NewArg->getNameOrAsOperand() << "\n");
1058b803aee6SAlexandros Lamprineas 
10597ea597eaSAlexandros Lamprineas     // Mark the argument constants in the new function
10607ea597eaSAlexandros Lamprineas     // or copy the lattice state over from the old function.
10617ea597eaSAlexandros Lamprineas     if (Iter != Args.end() && Iter->Formal == &*OldArg) {
10627ea597eaSAlexandros Lamprineas       if (auto *STy = dyn_cast<StructType>(NewArg->getType())) {
10637ea597eaSAlexandros Lamprineas         for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
10647ea597eaSAlexandros Lamprineas           ValueLatticeElement &NewValue = StructValueState[{&*NewArg, I}];
10657ea597eaSAlexandros Lamprineas           NewValue.markConstant(Iter->Actual->getAggregateElement(I));
10667ea597eaSAlexandros Lamprineas         }
10677ea597eaSAlexandros Lamprineas       } else {
10687ea597eaSAlexandros Lamprineas         ValueState[&*NewArg].markConstant(Iter->Actual);
10697ea597eaSAlexandros Lamprineas       }
10708045bf9dSAlexandros Lamprineas       ++Iter;
10717ea597eaSAlexandros Lamprineas     } else {
10727ea597eaSAlexandros Lamprineas       if (auto *STy = dyn_cast<StructType>(NewArg->getType())) {
10737ea597eaSAlexandros Lamprineas         for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
10747ea597eaSAlexandros Lamprineas           ValueLatticeElement &NewValue = StructValueState[{&*NewArg, I}];
10757ea597eaSAlexandros Lamprineas           NewValue = StructValueState[{&*OldArg, I}];
10767ea597eaSAlexandros Lamprineas         }
10777ea597eaSAlexandros Lamprineas       } else {
10787ea597eaSAlexandros Lamprineas         ValueLatticeElement &NewValue = ValueState[&*NewArg];
10797ea597eaSAlexandros Lamprineas         NewValue = ValueState[&*OldArg];
10807ea597eaSAlexandros Lamprineas       }
1081c4a0969bSSjoerd Meijer     }
1082c4a0969bSSjoerd Meijer   }
1083b803aee6SAlexandros Lamprineas }
1084c4a0969bSSjoerd Meijer 
1085bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitInstruction(Instruction &I) {
1086bbab9f98SSjoerd Meijer   // All the instructions we don't do any special handling for just
1087bbab9f98SSjoerd Meijer   // go to overdefined.
1088bbab9f98SSjoerd Meijer   LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
1089bbab9f98SSjoerd Meijer   markOverdefined(&I);
1090bbab9f98SSjoerd Meijer }
1091bbab9f98SSjoerd Meijer 
1092bbab9f98SSjoerd Meijer bool SCCPInstVisitor::mergeInValue(ValueLatticeElement &IV, Value *V,
1093bbab9f98SSjoerd Meijer                                    ValueLatticeElement MergeWithV,
1094bbab9f98SSjoerd Meijer                                    ValueLatticeElement::MergeOptions Opts) {
1095bbab9f98SSjoerd Meijer   if (IV.mergeIn(MergeWithV, Opts)) {
1096bbab9f98SSjoerd Meijer     pushToWorkList(IV, V);
1097bbab9f98SSjoerd Meijer     LLVM_DEBUG(dbgs() << "Merged " << MergeWithV << " into " << *V << " : "
1098bbab9f98SSjoerd Meijer                       << IV << "\n");
1099bbab9f98SSjoerd Meijer     return true;
1100bbab9f98SSjoerd Meijer   }
1101bbab9f98SSjoerd Meijer   return false;
1102bbab9f98SSjoerd Meijer }
1103bbab9f98SSjoerd Meijer 
1104bbab9f98SSjoerd Meijer bool SCCPInstVisitor::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
1105bbab9f98SSjoerd Meijer   if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
1106bbab9f98SSjoerd Meijer     return false; // This edge is already known to be executable!
1107bbab9f98SSjoerd Meijer 
110839d29817SSjoerd Meijer   if (!markBlockExecutable(Dest)) {
1109bbab9f98SSjoerd Meijer     // If the destination is already executable, we just made an *edge*
1110bbab9f98SSjoerd Meijer     // feasible that wasn't before.  Revisit the PHI nodes in the block
1111bbab9f98SSjoerd Meijer     // because they have potentially new operands.
1112bbab9f98SSjoerd Meijer     LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
1113bbab9f98SSjoerd Meijer                       << " -> " << Dest->getName() << '\n');
1114bbab9f98SSjoerd Meijer 
1115bbab9f98SSjoerd Meijer     for (PHINode &PN : Dest->phis())
1116bbab9f98SSjoerd Meijer       visitPHINode(PN);
1117bbab9f98SSjoerd Meijer   }
1118bbab9f98SSjoerd Meijer   return true;
1119bbab9f98SSjoerd Meijer }
1120bbab9f98SSjoerd Meijer 
1121bbab9f98SSjoerd Meijer // getFeasibleSuccessors - Return a vector of booleans to indicate which
1122bbab9f98SSjoerd Meijer // successors are reachable from a given terminator instruction.
1123bbab9f98SSjoerd Meijer void SCCPInstVisitor::getFeasibleSuccessors(Instruction &TI,
1124bbab9f98SSjoerd Meijer                                             SmallVectorImpl<bool> &Succs) {
1125bbab9f98SSjoerd Meijer   Succs.resize(TI.getNumSuccessors());
1126bbab9f98SSjoerd Meijer   if (auto *BI = dyn_cast<BranchInst>(&TI)) {
1127bbab9f98SSjoerd Meijer     if (BI->isUnconditional()) {
1128bbab9f98SSjoerd Meijer       Succs[0] = true;
1129bbab9f98SSjoerd Meijer       return;
1130bbab9f98SSjoerd Meijer     }
1131bbab9f98SSjoerd Meijer 
1132bbab9f98SSjoerd Meijer     ValueLatticeElement BCValue = getValueState(BI->getCondition());
1133664b7a4cSNikita Popov     ConstantInt *CI = getConstantInt(BCValue, BI->getCondition()->getType());
1134bbab9f98SSjoerd Meijer     if (!CI) {
1135bbab9f98SSjoerd Meijer       // Overdefined condition variables, and branches on unfoldable constant
1136bbab9f98SSjoerd Meijer       // conditions, mean the branch could go either way.
1137bbab9f98SSjoerd Meijer       if (!BCValue.isUnknownOrUndef())
1138bbab9f98SSjoerd Meijer         Succs[0] = Succs[1] = true;
1139bbab9f98SSjoerd Meijer       return;
1140bbab9f98SSjoerd Meijer     }
1141bbab9f98SSjoerd Meijer 
1142bbab9f98SSjoerd Meijer     // Constant condition variables mean the branch can only go a single way.
1143bbab9f98SSjoerd Meijer     Succs[CI->isZero()] = true;
1144bbab9f98SSjoerd Meijer     return;
1145bbab9f98SSjoerd Meijer   }
1146bbab9f98SSjoerd Meijer 
11474eafc9b6SNikita Popov   // We cannot analyze special terminators, so consider all successors
11484eafc9b6SNikita Popov   // executable.
11494eafc9b6SNikita Popov   if (TI.isSpecialTerminator()) {
1150bbab9f98SSjoerd Meijer     Succs.assign(TI.getNumSuccessors(), true);
1151bbab9f98SSjoerd Meijer     return;
1152bbab9f98SSjoerd Meijer   }
1153bbab9f98SSjoerd Meijer 
1154bbab9f98SSjoerd Meijer   if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
1155bbab9f98SSjoerd Meijer     if (!SI->getNumCases()) {
1156bbab9f98SSjoerd Meijer       Succs[0] = true;
1157bbab9f98SSjoerd Meijer       return;
1158bbab9f98SSjoerd Meijer     }
1159bbab9f98SSjoerd Meijer     const ValueLatticeElement &SCValue = getValueState(SI->getCondition());
1160664b7a4cSNikita Popov     if (ConstantInt *CI =
1161664b7a4cSNikita Popov             getConstantInt(SCValue, SI->getCondition()->getType())) {
1162bbab9f98SSjoerd Meijer       Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
1163bbab9f98SSjoerd Meijer       return;
1164bbab9f98SSjoerd Meijer     }
1165bbab9f98SSjoerd Meijer 
1166bbab9f98SSjoerd Meijer     // TODO: Switch on undef is UB. Stop passing false once the rest of LLVM
1167bbab9f98SSjoerd Meijer     // is ready.
1168bbab9f98SSjoerd Meijer     if (SCValue.isConstantRange(/*UndefAllowed=*/false)) {
1169bbab9f98SSjoerd Meijer       const ConstantRange &Range = SCValue.getConstantRange();
1170d2180925SYingwei Zheng       unsigned ReachableCaseCount = 0;
1171bbab9f98SSjoerd Meijer       for (const auto &Case : SI->cases()) {
1172bbab9f98SSjoerd Meijer         const APInt &CaseValue = Case.getCaseValue()->getValue();
1173d2180925SYingwei Zheng         if (Range.contains(CaseValue)) {
1174bbab9f98SSjoerd Meijer           Succs[Case.getSuccessorIndex()] = true;
1175d2180925SYingwei Zheng           ++ReachableCaseCount;
1176d2180925SYingwei Zheng         }
1177bbab9f98SSjoerd Meijer       }
1178bbab9f98SSjoerd Meijer 
1179d2180925SYingwei Zheng       Succs[SI->case_default()->getSuccessorIndex()] =
1180d2180925SYingwei Zheng           Range.isSizeLargerThan(ReachableCaseCount);
1181bbab9f98SSjoerd Meijer       return;
1182bbab9f98SSjoerd Meijer     }
1183bbab9f98SSjoerd Meijer 
1184bbab9f98SSjoerd Meijer     // Overdefined or unknown condition? All destinations are executable!
1185bbab9f98SSjoerd Meijer     if (!SCValue.isUnknownOrUndef())
1186bbab9f98SSjoerd Meijer       Succs.assign(TI.getNumSuccessors(), true);
1187bbab9f98SSjoerd Meijer     return;
1188bbab9f98SSjoerd Meijer   }
1189bbab9f98SSjoerd Meijer 
1190bbab9f98SSjoerd Meijer   // In case of indirect branch and its address is a blockaddress, we mark
1191bbab9f98SSjoerd Meijer   // the target as executable.
1192bbab9f98SSjoerd Meijer   if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
1193bbab9f98SSjoerd Meijer     // Casts are folded by visitCastInst.
1194bbab9f98SSjoerd Meijer     ValueLatticeElement IBRValue = getValueState(IBR->getAddress());
1195664b7a4cSNikita Popov     BlockAddress *Addr = dyn_cast_or_null<BlockAddress>(
1196664b7a4cSNikita Popov         getConstant(IBRValue, IBR->getAddress()->getType()));
1197bbab9f98SSjoerd Meijer     if (!Addr) { // Overdefined or unknown condition?
1198bbab9f98SSjoerd Meijer       // All destinations are executable!
1199bbab9f98SSjoerd Meijer       if (!IBRValue.isUnknownOrUndef())
1200bbab9f98SSjoerd Meijer         Succs.assign(TI.getNumSuccessors(), true);
1201bbab9f98SSjoerd Meijer       return;
1202bbab9f98SSjoerd Meijer     }
1203bbab9f98SSjoerd Meijer 
1204bbab9f98SSjoerd Meijer     BasicBlock *T = Addr->getBasicBlock();
1205bbab9f98SSjoerd Meijer     assert(Addr->getFunction() == T->getParent() &&
1206bbab9f98SSjoerd Meijer            "Block address of a different function ?");
1207bbab9f98SSjoerd Meijer     for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
1208bbab9f98SSjoerd Meijer       // This is the target.
1209bbab9f98SSjoerd Meijer       if (IBR->getDestination(i) == T) {
1210bbab9f98SSjoerd Meijer         Succs[i] = true;
1211bbab9f98SSjoerd Meijer         return;
1212bbab9f98SSjoerd Meijer       }
1213bbab9f98SSjoerd Meijer     }
1214bbab9f98SSjoerd Meijer 
1215bbab9f98SSjoerd Meijer     // If we didn't find our destination in the IBR successor list, then we
1216bbab9f98SSjoerd Meijer     // have undefined behavior. Its ok to assume no successor is executable.
1217bbab9f98SSjoerd Meijer     return;
1218bbab9f98SSjoerd Meijer   }
1219bbab9f98SSjoerd Meijer 
1220bbab9f98SSjoerd Meijer   LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
1221bbab9f98SSjoerd Meijer   llvm_unreachable("SCCP: Don't know how to handle this terminator!");
1222bbab9f98SSjoerd Meijer }
1223bbab9f98SSjoerd Meijer 
1224bbab9f98SSjoerd Meijer // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
1225bbab9f98SSjoerd Meijer // block to the 'To' basic block is currently feasible.
1226bbab9f98SSjoerd Meijer bool SCCPInstVisitor::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const {
1227bbab9f98SSjoerd Meijer   // Check if we've called markEdgeExecutable on the edge yet. (We could
1228bbab9f98SSjoerd Meijer   // be more aggressive and try to consider edges which haven't been marked
1229bbab9f98SSjoerd Meijer   // yet, but there isn't any need.)
1230bbab9f98SSjoerd Meijer   return KnownFeasibleEdges.count(Edge(From, To));
1231bbab9f98SSjoerd Meijer }
1232bbab9f98SSjoerd Meijer 
1233bbab9f98SSjoerd Meijer // visit Implementations - Something changed in this instruction, either an
1234bbab9f98SSjoerd Meijer // operand made a transition, or the instruction is newly executable.  Change
1235bbab9f98SSjoerd Meijer // the value type of I to reflect these changes if appropriate.  This method
1236bbab9f98SSjoerd Meijer // makes sure to do the following actions:
1237bbab9f98SSjoerd Meijer //
1238bbab9f98SSjoerd Meijer // 1. If a phi node merges two constants in, and has conflicting value coming
1239bbab9f98SSjoerd Meijer //    from different branches, or if the PHI node merges in an overdefined
1240bbab9f98SSjoerd Meijer //    value, then the PHI node becomes overdefined.
1241bbab9f98SSjoerd Meijer // 2. If a phi node merges only constants in, and they all agree on value, the
1242bbab9f98SSjoerd Meijer //    PHI node becomes a constant value equal to that.
1243bbab9f98SSjoerd Meijer // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
1244bbab9f98SSjoerd Meijer // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
1245bbab9f98SSjoerd Meijer // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
1246bbab9f98SSjoerd Meijer // 6. If a conditional branch has a value that is constant, make the selected
1247bbab9f98SSjoerd Meijer //    destination executable
1248bbab9f98SSjoerd Meijer // 7. If a conditional branch has a value that is overdefined, make all
1249bbab9f98SSjoerd Meijer //    successors executable.
1250bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitPHINode(PHINode &PN) {
1251bbab9f98SSjoerd Meijer   // If this PN returns a struct, just mark the result overdefined.
1252bbab9f98SSjoerd Meijer   // TODO: We could do a lot better than this if code actually uses this.
1253bbab9f98SSjoerd Meijer   if (PN.getType()->isStructTy())
1254bbab9f98SSjoerd Meijer     return (void)markOverdefined(&PN);
1255bbab9f98SSjoerd Meijer 
1256bbab9f98SSjoerd Meijer   if (getValueState(&PN).isOverdefined())
1257bbab9f98SSjoerd Meijer     return; // Quick exit
1258bbab9f98SSjoerd Meijer 
1259bbab9f98SSjoerd Meijer   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
1260bbab9f98SSjoerd Meijer   // and slow us down a lot.  Just mark them overdefined.
1261bbab9f98SSjoerd Meijer   if (PN.getNumIncomingValues() > 64)
1262bbab9f98SSjoerd Meijer     return (void)markOverdefined(&PN);
1263bbab9f98SSjoerd Meijer 
1264bbab9f98SSjoerd Meijer   unsigned NumActiveIncoming = 0;
1265bbab9f98SSjoerd Meijer 
1266bbab9f98SSjoerd Meijer   // Look at all of the executable operands of the PHI node.  If any of them
1267bbab9f98SSjoerd Meijer   // are overdefined, the PHI becomes overdefined as well.  If they are all
1268bbab9f98SSjoerd Meijer   // constant, and they agree with each other, the PHI becomes the identical
1269bbab9f98SSjoerd Meijer   // constant.  If they are constant and don't agree, the PHI is a constant
1270bbab9f98SSjoerd Meijer   // range. If there are no executable operands, the PHI remains unknown.
1271bbab9f98SSjoerd Meijer   ValueLatticeElement PhiState = getValueState(&PN);
1272bbab9f98SSjoerd Meijer   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1273bbab9f98SSjoerd Meijer     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
1274bbab9f98SSjoerd Meijer       continue;
1275bbab9f98SSjoerd Meijer 
1276bbab9f98SSjoerd Meijer     ValueLatticeElement IV = getValueState(PN.getIncomingValue(i));
1277bbab9f98SSjoerd Meijer     PhiState.mergeIn(IV);
1278bbab9f98SSjoerd Meijer     NumActiveIncoming++;
1279bbab9f98SSjoerd Meijer     if (PhiState.isOverdefined())
1280bbab9f98SSjoerd Meijer       break;
1281bbab9f98SSjoerd Meijer   }
1282bbab9f98SSjoerd Meijer 
1283bbab9f98SSjoerd Meijer   // We allow up to 1 range extension per active incoming value and one
1284bbab9f98SSjoerd Meijer   // additional extension. Note that we manually adjust the number of range
1285bbab9f98SSjoerd Meijer   // extensions to match the number of active incoming values. This helps to
1286bbab9f98SSjoerd Meijer   // limit multiple extensions caused by the same incoming value, if other
1287bbab9f98SSjoerd Meijer   // incoming values are equal.
1288bbab9f98SSjoerd Meijer   mergeInValue(&PN, PhiState,
1289bbab9f98SSjoerd Meijer                ValueLatticeElement::MergeOptions().setMaxWidenSteps(
1290bbab9f98SSjoerd Meijer                    NumActiveIncoming + 1));
1291bbab9f98SSjoerd Meijer   ValueLatticeElement &PhiStateRef = getValueState(&PN);
1292bbab9f98SSjoerd Meijer   PhiStateRef.setNumRangeExtensions(
1293bbab9f98SSjoerd Meijer       std::max(NumActiveIncoming, PhiStateRef.getNumRangeExtensions()));
1294bbab9f98SSjoerd Meijer }
1295bbab9f98SSjoerd Meijer 
1296bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitReturnInst(ReturnInst &I) {
1297bbab9f98SSjoerd Meijer   if (I.getNumOperands() == 0)
1298bbab9f98SSjoerd Meijer     return; // ret void
1299bbab9f98SSjoerd Meijer 
1300bbab9f98SSjoerd Meijer   Function *F = I.getParent()->getParent();
1301bbab9f98SSjoerd Meijer   Value *ResultOp = I.getOperand(0);
1302bbab9f98SSjoerd Meijer 
1303bbab9f98SSjoerd Meijer   // If we are tracking the return value of this function, merge it in.
1304bbab9f98SSjoerd Meijer   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
1305bbab9f98SSjoerd Meijer     auto TFRVI = TrackedRetVals.find(F);
1306bbab9f98SSjoerd Meijer     if (TFRVI != TrackedRetVals.end()) {
1307bbab9f98SSjoerd Meijer       mergeInValue(TFRVI->second, F, getValueState(ResultOp));
1308bbab9f98SSjoerd Meijer       return;
1309bbab9f98SSjoerd Meijer     }
1310bbab9f98SSjoerd Meijer   }
1311bbab9f98SSjoerd Meijer 
1312bbab9f98SSjoerd Meijer   // Handle functions that return multiple values.
1313bbab9f98SSjoerd Meijer   if (!TrackedMultipleRetVals.empty()) {
1314bbab9f98SSjoerd Meijer     if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
1315bbab9f98SSjoerd Meijer       if (MRVFunctionsTracked.count(F))
1316bbab9f98SSjoerd Meijer         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1317bbab9f98SSjoerd Meijer           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
1318bbab9f98SSjoerd Meijer                        getStructValueState(ResultOp, i));
1319bbab9f98SSjoerd Meijer   }
1320bbab9f98SSjoerd Meijer }
1321bbab9f98SSjoerd Meijer 
1322bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitTerminator(Instruction &TI) {
1323bbab9f98SSjoerd Meijer   SmallVector<bool, 16> SuccFeasible;
1324bbab9f98SSjoerd Meijer   getFeasibleSuccessors(TI, SuccFeasible);
1325bbab9f98SSjoerd Meijer 
1326bbab9f98SSjoerd Meijer   BasicBlock *BB = TI.getParent();
1327bbab9f98SSjoerd Meijer 
1328bbab9f98SSjoerd Meijer   // Mark all feasible successors executable.
1329bbab9f98SSjoerd Meijer   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
1330bbab9f98SSjoerd Meijer     if (SuccFeasible[i])
1331bbab9f98SSjoerd Meijer       markEdgeExecutable(BB, TI.getSuccessor(i));
1332bbab9f98SSjoerd Meijer }
1333bbab9f98SSjoerd Meijer 
1334bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitCastInst(CastInst &I) {
1335bbab9f98SSjoerd Meijer   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1336bbab9f98SSjoerd Meijer   // discover a concrete value later.
1337bbab9f98SSjoerd Meijer   if (ValueState[&I].isOverdefined())
1338bbab9f98SSjoerd Meijer     return;
1339bbab9f98SSjoerd Meijer 
1340bbab9f98SSjoerd Meijer   ValueLatticeElement OpSt = getValueState(I.getOperand(0));
1341ce4fa93dSAnton Afanasyev   if (OpSt.isUnknownOrUndef())
1342ce4fa93dSAnton Afanasyev     return;
1343ce4fa93dSAnton Afanasyev 
1344664b7a4cSNikita Popov   if (Constant *OpC = getConstant(OpSt, I.getOperand(0)->getType())) {
1345bbab9f98SSjoerd Meijer     // Fold the constant as we build.
13463b25407dSNikita Popov     if (Constant *C =
13473b25407dSNikita Popov             ConstantFoldCastOperand(I.getOpcode(), OpC, I.getType(), DL))
13483b25407dSNikita Popov       return (void)markConstant(&I, C);
13493b25407dSNikita Popov   }
13503b25407dSNikita Popov 
135112d6832dSNikita Popov   // Ignore bitcasts, as they may change the number of vector elements.
13526b76c1e6SNikita Popov   if (I.getDestTy()->isIntOrIntVectorTy() &&
13536b76c1e6SNikita Popov       I.getSrcTy()->isIntOrIntVectorTy() &&
135412d6832dSNikita Popov       I.getOpcode() != Instruction::BitCast) {
1355bbab9f98SSjoerd Meijer     auto &LV = getValueState(&I);
135627392a35SNikita Popov     ConstantRange OpRange =
13576b76c1e6SNikita Popov         OpSt.asConstantRange(I.getSrcTy(), /*UndefAllowed=*/false);
1358ce4fa93dSAnton Afanasyev 
1359bbab9f98SSjoerd Meijer     Type *DestTy = I.getDestTy();
1360bbab9f98SSjoerd Meijer     ConstantRange Res =
136112d6832dSNikita Popov         OpRange.castOp(I.getOpcode(), DestTy->getScalarSizeInBits());
1362bbab9f98SSjoerd Meijer     mergeInValue(LV, &I, ValueLatticeElement::getRange(Res));
1363ce4fa93dSAnton Afanasyev   } else
1364bbab9f98SSjoerd Meijer     markOverdefined(&I);
1365bbab9f98SSjoerd Meijer }
1366bbab9f98SSjoerd Meijer 
1367f101196dSNikita Popov void SCCPInstVisitor::handleExtractOfWithOverflow(ExtractValueInst &EVI,
1368f101196dSNikita Popov                                                   const WithOverflowInst *WO,
1369f101196dSNikita Popov                                                   unsigned Idx) {
1370f101196dSNikita Popov   Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
1371f101196dSNikita Popov   ValueLatticeElement L = getValueState(LHS);
1372f101196dSNikita Popov   ValueLatticeElement R = getValueState(RHS);
1373f101196dSNikita Popov   addAdditionalUser(LHS, &EVI);
1374f101196dSNikita Popov   addAdditionalUser(RHS, &EVI);
1375f101196dSNikita Popov   if (L.isUnknownOrUndef() || R.isUnknownOrUndef())
1376f101196dSNikita Popov     return; // Wait to resolve.
1377f101196dSNikita Popov 
1378f101196dSNikita Popov   Type *Ty = LHS->getType();
13796b76c1e6SNikita Popov   ConstantRange LR = L.asConstantRange(Ty, /*UndefAllowed=*/false);
13806b76c1e6SNikita Popov   ConstantRange RR = R.asConstantRange(Ty, /*UndefAllowed=*/false);
1381f101196dSNikita Popov   if (Idx == 0) {
1382f101196dSNikita Popov     ConstantRange Res = LR.binaryOp(WO->getBinaryOp(), RR);
1383f101196dSNikita Popov     mergeInValue(&EVI, ValueLatticeElement::getRange(Res));
1384f101196dSNikita Popov   } else {
1385f101196dSNikita Popov     assert(Idx == 1 && "Index can only be 0 or 1");
1386f101196dSNikita Popov     ConstantRange NWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1387f101196dSNikita Popov         WO->getBinaryOp(), RR, WO->getNoWrapKind());
1388f101196dSNikita Popov     if (NWRegion.contains(LR))
1389f101196dSNikita Popov       return (void)markConstant(&EVI, ConstantInt::getFalse(EVI.getType()));
1390f101196dSNikita Popov     markOverdefined(&EVI);
1391f101196dSNikita Popov   }
1392f101196dSNikita Popov }
1393f101196dSNikita Popov 
1394bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitExtractValueInst(ExtractValueInst &EVI) {
1395bbab9f98SSjoerd Meijer   // If this returns a struct, mark all elements over defined, we don't track
1396bbab9f98SSjoerd Meijer   // structs in structs.
1397bbab9f98SSjoerd Meijer   if (EVI.getType()->isStructTy())
1398bbab9f98SSjoerd Meijer     return (void)markOverdefined(&EVI);
1399bbab9f98SSjoerd Meijer 
140039d29817SSjoerd Meijer   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1401bbab9f98SSjoerd Meijer   // discover a concrete value later.
1402bbab9f98SSjoerd Meijer   if (ValueState[&EVI].isOverdefined())
1403bbab9f98SSjoerd Meijer     return (void)markOverdefined(&EVI);
1404bbab9f98SSjoerd Meijer 
1405bbab9f98SSjoerd Meijer   // If this is extracting from more than one level of struct, we don't know.
1406bbab9f98SSjoerd Meijer   if (EVI.getNumIndices() != 1)
1407bbab9f98SSjoerd Meijer     return (void)markOverdefined(&EVI);
1408bbab9f98SSjoerd Meijer 
1409bbab9f98SSjoerd Meijer   Value *AggVal = EVI.getAggregateOperand();
1410bbab9f98SSjoerd Meijer   if (AggVal->getType()->isStructTy()) {
1411bbab9f98SSjoerd Meijer     unsigned i = *EVI.idx_begin();
1412f101196dSNikita Popov     if (auto *WO = dyn_cast<WithOverflowInst>(AggVal))
1413f101196dSNikita Popov       return handleExtractOfWithOverflow(EVI, WO, i);
1414bbab9f98SSjoerd Meijer     ValueLatticeElement EltVal = getStructValueState(AggVal, i);
1415bbab9f98SSjoerd Meijer     mergeInValue(getValueState(&EVI), &EVI, EltVal);
1416bbab9f98SSjoerd Meijer   } else {
1417bbab9f98SSjoerd Meijer     // Otherwise, must be extracting from an array.
1418bbab9f98SSjoerd Meijer     return (void)markOverdefined(&EVI);
1419bbab9f98SSjoerd Meijer   }
1420bbab9f98SSjoerd Meijer }
1421bbab9f98SSjoerd Meijer 
1422bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitInsertValueInst(InsertValueInst &IVI) {
1423bbab9f98SSjoerd Meijer   auto *STy = dyn_cast<StructType>(IVI.getType());
1424bbab9f98SSjoerd Meijer   if (!STy)
1425bbab9f98SSjoerd Meijer     return (void)markOverdefined(&IVI);
1426bbab9f98SSjoerd Meijer 
142739d29817SSjoerd Meijer   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1428bbab9f98SSjoerd Meijer   // discover a concrete value later.
14290e24c32aSNikita Popov   if (ValueState[&IVI].isOverdefined())
1430bbab9f98SSjoerd Meijer     return (void)markOverdefined(&IVI);
1431bbab9f98SSjoerd Meijer 
1432bbab9f98SSjoerd Meijer   // If this has more than one index, we can't handle it, drive all results to
1433bbab9f98SSjoerd Meijer   // undef.
1434bbab9f98SSjoerd Meijer   if (IVI.getNumIndices() != 1)
1435bbab9f98SSjoerd Meijer     return (void)markOverdefined(&IVI);
1436bbab9f98SSjoerd Meijer 
1437bbab9f98SSjoerd Meijer   Value *Aggr = IVI.getAggregateOperand();
1438bbab9f98SSjoerd Meijer   unsigned Idx = *IVI.idx_begin();
1439bbab9f98SSjoerd Meijer 
1440bbab9f98SSjoerd Meijer   // Compute the result based on what we're inserting.
1441bbab9f98SSjoerd Meijer   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1442bbab9f98SSjoerd Meijer     // This passes through all values that aren't the inserted element.
1443bbab9f98SSjoerd Meijer     if (i != Idx) {
1444bbab9f98SSjoerd Meijer       ValueLatticeElement EltVal = getStructValueState(Aggr, i);
1445bbab9f98SSjoerd Meijer       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
1446bbab9f98SSjoerd Meijer       continue;
1447bbab9f98SSjoerd Meijer     }
1448bbab9f98SSjoerd Meijer 
1449bbab9f98SSjoerd Meijer     Value *Val = IVI.getInsertedValueOperand();
1450bbab9f98SSjoerd Meijer     if (Val->getType()->isStructTy())
1451bbab9f98SSjoerd Meijer       // We don't track structs in structs.
1452bbab9f98SSjoerd Meijer       markOverdefined(getStructValueState(&IVI, i), &IVI);
1453bbab9f98SSjoerd Meijer     else {
1454bbab9f98SSjoerd Meijer       ValueLatticeElement InVal = getValueState(Val);
1455bbab9f98SSjoerd Meijer       mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
1456bbab9f98SSjoerd Meijer     }
1457bbab9f98SSjoerd Meijer   }
1458bbab9f98SSjoerd Meijer }
1459bbab9f98SSjoerd Meijer 
1460bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitSelectInst(SelectInst &I) {
1461bbab9f98SSjoerd Meijer   // If this select returns a struct, just mark the result overdefined.
1462bbab9f98SSjoerd Meijer   // TODO: We could do a lot better than this if code actually uses this.
1463bbab9f98SSjoerd Meijer   if (I.getType()->isStructTy())
1464bbab9f98SSjoerd Meijer     return (void)markOverdefined(&I);
1465bbab9f98SSjoerd Meijer 
146639d29817SSjoerd Meijer   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1467bbab9f98SSjoerd Meijer   // discover a concrete value later.
1468bbab9f98SSjoerd Meijer   if (ValueState[&I].isOverdefined())
1469bbab9f98SSjoerd Meijer     return (void)markOverdefined(&I);
1470bbab9f98SSjoerd Meijer 
1471bbab9f98SSjoerd Meijer   ValueLatticeElement CondValue = getValueState(I.getCondition());
1472bbab9f98SSjoerd Meijer   if (CondValue.isUnknownOrUndef())
1473bbab9f98SSjoerd Meijer     return;
1474bbab9f98SSjoerd Meijer 
1475664b7a4cSNikita Popov   if (ConstantInt *CondCB =
1476664b7a4cSNikita Popov           getConstantInt(CondValue, I.getCondition()->getType())) {
1477bbab9f98SSjoerd Meijer     Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
1478bbab9f98SSjoerd Meijer     mergeInValue(&I, getValueState(OpVal));
1479bbab9f98SSjoerd Meijer     return;
1480bbab9f98SSjoerd Meijer   }
1481bbab9f98SSjoerd Meijer 
1482bbab9f98SSjoerd Meijer   // Otherwise, the condition is overdefined or a constant we can't evaluate.
1483bbab9f98SSjoerd Meijer   // See if we can produce something better than overdefined based on the T/F
1484bbab9f98SSjoerd Meijer   // value.
1485bbab9f98SSjoerd Meijer   ValueLatticeElement TVal = getValueState(I.getTrueValue());
1486bbab9f98SSjoerd Meijer   ValueLatticeElement FVal = getValueState(I.getFalseValue());
1487bbab9f98SSjoerd Meijer 
1488bbab9f98SSjoerd Meijer   bool Changed = ValueState[&I].mergeIn(TVal);
1489bbab9f98SSjoerd Meijer   Changed |= ValueState[&I].mergeIn(FVal);
1490bbab9f98SSjoerd Meijer   if (Changed)
1491bbab9f98SSjoerd Meijer     pushToWorkListMsg(ValueState[&I], &I);
1492bbab9f98SSjoerd Meijer }
1493bbab9f98SSjoerd Meijer 
1494bbab9f98SSjoerd Meijer // Handle Unary Operators.
1495bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitUnaryOperator(Instruction &I) {
1496bbab9f98SSjoerd Meijer   ValueLatticeElement V0State = getValueState(I.getOperand(0));
1497bbab9f98SSjoerd Meijer 
1498bbab9f98SSjoerd Meijer   ValueLatticeElement &IV = ValueState[&I];
149939d29817SSjoerd Meijer   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1500bbab9f98SSjoerd Meijer   // discover a concrete value later.
15010e24c32aSNikita Popov   if (IV.isOverdefined())
1502bbab9f98SSjoerd Meijer     return (void)markOverdefined(&I);
1503bbab9f98SSjoerd Meijer 
1504ebc54e0cSNikita Popov   // If something is unknown/undef, wait for it to resolve.
1505ebc54e0cSNikita Popov   if (V0State.isUnknownOrUndef())
1506ebc54e0cSNikita Popov     return;
1507ebc54e0cSNikita Popov 
1508a794b62cSFlorian Hahn   if (SCCPSolver::isConstant(V0State))
1509664b7a4cSNikita Popov     if (Constant *C = ConstantFoldUnaryOpOperand(
1510664b7a4cSNikita Popov             I.getOpcode(), getConstant(V0State, I.getType()), DL))
1511bbab9f98SSjoerd Meijer       return (void)markConstant(IV, &I, C);
1512bbab9f98SSjoerd Meijer 
1513bbab9f98SSjoerd Meijer   markOverdefined(&I);
1514bbab9f98SSjoerd Meijer }
1515bbab9f98SSjoerd Meijer 
1516d37d4072SMikhail Gudim void SCCPInstVisitor::visitFreezeInst(FreezeInst &I) {
1517d37d4072SMikhail Gudim   // If this freeze returns a struct, just mark the result overdefined.
1518d37d4072SMikhail Gudim   // TODO: We could do a lot better than this.
1519d37d4072SMikhail Gudim   if (I.getType()->isStructTy())
1520d37d4072SMikhail Gudim     return (void)markOverdefined(&I);
1521d37d4072SMikhail Gudim 
1522d37d4072SMikhail Gudim   ValueLatticeElement V0State = getValueState(I.getOperand(0));
1523d37d4072SMikhail Gudim   ValueLatticeElement &IV = ValueState[&I];
1524d37d4072SMikhail Gudim   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1525d37d4072SMikhail Gudim   // discover a concrete value later.
15260e24c32aSNikita Popov   if (IV.isOverdefined())
1527d37d4072SMikhail Gudim     return (void)markOverdefined(&I);
1528d37d4072SMikhail Gudim 
1529d37d4072SMikhail Gudim   // If something is unknown/undef, wait for it to resolve.
1530d37d4072SMikhail Gudim   if (V0State.isUnknownOrUndef())
1531d37d4072SMikhail Gudim     return;
1532d37d4072SMikhail Gudim 
1533d37d4072SMikhail Gudim   if (SCCPSolver::isConstant(V0State) &&
1534664b7a4cSNikita Popov       isGuaranteedNotToBeUndefOrPoison(getConstant(V0State, I.getType())))
1535664b7a4cSNikita Popov     return (void)markConstant(IV, &I, getConstant(V0State, I.getType()));
1536d37d4072SMikhail Gudim 
1537d37d4072SMikhail Gudim   markOverdefined(&I);
1538d37d4072SMikhail Gudim }
1539d37d4072SMikhail Gudim 
1540bbab9f98SSjoerd Meijer // Handle Binary Operators.
1541bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitBinaryOperator(Instruction &I) {
1542bbab9f98SSjoerd Meijer   ValueLatticeElement V1State = getValueState(I.getOperand(0));
1543bbab9f98SSjoerd Meijer   ValueLatticeElement V2State = getValueState(I.getOperand(1));
1544bbab9f98SSjoerd Meijer 
1545bbab9f98SSjoerd Meijer   ValueLatticeElement &IV = ValueState[&I];
1546bbab9f98SSjoerd Meijer   if (IV.isOverdefined())
1547bbab9f98SSjoerd Meijer     return;
1548bbab9f98SSjoerd Meijer 
1549bbab9f98SSjoerd Meijer   // If something is undef, wait for it to resolve.
1550bbab9f98SSjoerd Meijer   if (V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef())
1551bbab9f98SSjoerd Meijer     return;
1552bbab9f98SSjoerd Meijer 
1553bbab9f98SSjoerd Meijer   if (V1State.isOverdefined() && V2State.isOverdefined())
1554bbab9f98SSjoerd Meijer     return (void)markOverdefined(&I);
1555bbab9f98SSjoerd Meijer 
1556bbab9f98SSjoerd Meijer   // If either of the operands is a constant, try to fold it to a constant.
1557bbab9f98SSjoerd Meijer   // TODO: Use information from notconstant better.
1558bbab9f98SSjoerd Meijer   if ((V1State.isConstant() || V2State.isConstant())) {
1559664b7a4cSNikita Popov     Value *V1 = SCCPSolver::isConstant(V1State)
1560664b7a4cSNikita Popov                     ? getConstant(V1State, I.getOperand(0)->getType())
1561a794b62cSFlorian Hahn                     : I.getOperand(0);
1562664b7a4cSNikita Popov     Value *V2 = SCCPSolver::isConstant(V2State)
1563664b7a4cSNikita Popov                     ? getConstant(V2State, I.getOperand(1)->getType())
1564a794b62cSFlorian Hahn                     : I.getOperand(1);
1565e6fa09f4SThomas Hashem     Value *R = simplifyBinOp(I.getOpcode(), V1, V2, SimplifyQuery(DL, &I));
1566bbab9f98SSjoerd Meijer     auto *C = dyn_cast_or_null<Constant>(R);
1567bbab9f98SSjoerd Meijer     if (C) {
1568bbab9f98SSjoerd Meijer       // Conservatively assume that the result may be based on operands that may
1569bbab9f98SSjoerd Meijer       // be undef. Note that we use mergeInValue to combine the constant with
1570bbab9f98SSjoerd Meijer       // the existing lattice value for I, as different constants might be found
1571bbab9f98SSjoerd Meijer       // after one of the operands go to overdefined, e.g. due to one operand
1572bbab9f98SSjoerd Meijer       // being a special floating value.
1573bbab9f98SSjoerd Meijer       ValueLatticeElement NewV;
1574bbab9f98SSjoerd Meijer       NewV.markConstant(C, /*MayIncludeUndef=*/true);
1575bbab9f98SSjoerd Meijer       return (void)mergeInValue(&I, NewV);
1576bbab9f98SSjoerd Meijer     }
1577bbab9f98SSjoerd Meijer   }
1578bbab9f98SSjoerd Meijer 
1579bbab9f98SSjoerd Meijer   // Only use ranges for binary operators on integers.
15806b76c1e6SNikita Popov   if (!I.getType()->isIntOrIntVectorTy())
1581bbab9f98SSjoerd Meijer     return markOverdefined(&I);
1582bbab9f98SSjoerd Meijer 
1583bbab9f98SSjoerd Meijer   // Try to simplify to a constant range.
158427392a35SNikita Popov   ConstantRange A =
15856b76c1e6SNikita Popov       V1State.asConstantRange(I.getType(), /*UndefAllowed=*/false);
158627392a35SNikita Popov   ConstantRange B =
15876b76c1e6SNikita Popov       V2State.asConstantRange(I.getType(), /*UndefAllowed=*/false);
15886ae4fcfdSAntonio Frighetto 
15896ae4fcfdSAntonio Frighetto   auto *BO = cast<BinaryOperator>(&I);
15906ae4fcfdSAntonio Frighetto   ConstantRange R = ConstantRange::getEmpty(I.getType()->getScalarSizeInBits());
15916ae4fcfdSAntonio Frighetto   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO))
15926ae4fcfdSAntonio Frighetto     R = A.overflowingBinaryOp(BO->getOpcode(), B, OBO->getNoWrapKind());
15936ae4fcfdSAntonio Frighetto   else
15946ae4fcfdSAntonio Frighetto     R = A.binaryOp(BO->getOpcode(), B);
1595bbab9f98SSjoerd Meijer   mergeInValue(&I, ValueLatticeElement::getRange(R));
1596bbab9f98SSjoerd Meijer 
1597bbab9f98SSjoerd Meijer   // TODO: Currently we do not exploit special values that produce something
1598bbab9f98SSjoerd Meijer   // better than overdefined with an overdefined operand for vector or floating
1599bbab9f98SSjoerd Meijer   // point types, like and <4 x i32> overdefined, zeroinitializer.
1600bbab9f98SSjoerd Meijer }
1601bbab9f98SSjoerd Meijer 
1602bbab9f98SSjoerd Meijer // Handle ICmpInst instruction.
1603bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitCmpInst(CmpInst &I) {
1604bbab9f98SSjoerd Meijer   // Do not cache this lookup, getValueState calls later in the function might
1605bbab9f98SSjoerd Meijer   // invalidate the reference.
16060e24c32aSNikita Popov   if (ValueState[&I].isOverdefined())
1607bbab9f98SSjoerd Meijer     return (void)markOverdefined(&I);
1608bbab9f98SSjoerd Meijer 
1609bbab9f98SSjoerd Meijer   Value *Op1 = I.getOperand(0);
1610bbab9f98SSjoerd Meijer   Value *Op2 = I.getOperand(1);
1611bbab9f98SSjoerd Meijer 
1612bbab9f98SSjoerd Meijer   // For parameters, use ParamState which includes constant range info if
1613bbab9f98SSjoerd Meijer   // available.
1614bbab9f98SSjoerd Meijer   auto V1State = getValueState(Op1);
1615bbab9f98SSjoerd Meijer   auto V2State = getValueState(Op2);
1616bbab9f98SSjoerd Meijer 
1617134bda4bSNikita Popov   Constant *C = V1State.getCompare(I.getPredicate(), I.getType(), V2State, DL);
1618bbab9f98SSjoerd Meijer   if (C) {
1619bbab9f98SSjoerd Meijer     ValueLatticeElement CV;
1620bbab9f98SSjoerd Meijer     CV.markConstant(C);
1621bbab9f98SSjoerd Meijer     mergeInValue(&I, CV);
1622bbab9f98SSjoerd Meijer     return;
1623bbab9f98SSjoerd Meijer   }
1624bbab9f98SSjoerd Meijer 
1625bbab9f98SSjoerd Meijer   // If operands are still unknown, wait for it to resolve.
1626bbab9f98SSjoerd Meijer   if ((V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef()) &&
1627a794b62cSFlorian Hahn       !SCCPSolver::isConstant(ValueState[&I]))
1628bbab9f98SSjoerd Meijer     return;
1629bbab9f98SSjoerd Meijer 
1630bbab9f98SSjoerd Meijer   markOverdefined(&I);
1631bbab9f98SSjoerd Meijer }
1632bbab9f98SSjoerd Meijer 
1633bbab9f98SSjoerd Meijer // Handle getelementptr instructions.  If all operands are constants then we
1634bbab9f98SSjoerd Meijer // can turn this into a getelementptr ConstantExpr.
1635bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
16360e24c32aSNikita Popov   if (ValueState[&I].isOverdefined())
1637bbab9f98SSjoerd Meijer     return (void)markOverdefined(&I);
1638bbab9f98SSjoerd Meijer 
16391cea5c21SNikita Popov   const ValueLatticeElement &PtrState = getValueState(I.getPointerOperand());
16401cea5c21SNikita Popov   if (PtrState.isUnknownOrUndef())
16411cea5c21SNikita Popov     return;
16421cea5c21SNikita Popov 
16431cea5c21SNikita Popov   // gep inbounds/nuw of non-null is non-null.
16441cea5c21SNikita Popov   if (PtrState.isNotConstant() && PtrState.getNotConstant()->isNullValue()) {
16451cea5c21SNikita Popov     if (I.hasNoUnsignedWrap() ||
16461cea5c21SNikita Popov         (I.isInBounds() &&
16471cea5c21SNikita Popov          !NullPointerIsDefined(I.getFunction(), I.getAddressSpace())))
16481cea5c21SNikita Popov       return (void)markNotNull(ValueState[&I], &I);
16491cea5c21SNikita Popov     return (void)markOverdefined(&I);
16501cea5c21SNikita Popov   }
16511cea5c21SNikita Popov 
1652bbab9f98SSjoerd Meijer   SmallVector<Constant *, 8> Operands;
1653bbab9f98SSjoerd Meijer   Operands.reserve(I.getNumOperands());
1654bbab9f98SSjoerd Meijer 
1655bbab9f98SSjoerd Meijer   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1656bbab9f98SSjoerd Meijer     ValueLatticeElement State = getValueState(I.getOperand(i));
1657bbab9f98SSjoerd Meijer     if (State.isUnknownOrUndef())
1658bbab9f98SSjoerd Meijer       return; // Operands are not resolved yet.
1659bbab9f98SSjoerd Meijer 
1660664b7a4cSNikita Popov     if (Constant *C = getConstant(State, I.getOperand(i)->getType())) {
1661bbab9f98SSjoerd Meijer       Operands.push_back(C);
1662bbab9f98SSjoerd Meijer       continue;
1663bbab9f98SSjoerd Meijer     }
1664bbab9f98SSjoerd Meijer 
1665bbab9f98SSjoerd Meijer     return (void)markOverdefined(&I);
1666bbab9f98SSjoerd Meijer   }
1667bbab9f98SSjoerd Meijer 
166818423c7eSRahul Anand Radhakrishnan   if (Constant *C = ConstantFoldInstOperands(&I, Operands, DL))
1669bbab9f98SSjoerd Meijer     markConstant(&I, C);
16700797c184SNikita Popov   else
16710797c184SNikita Popov     markOverdefined(&I);
1672bbab9f98SSjoerd Meijer }
1673bbab9f98SSjoerd Meijer 
1674657f26f0SNikita Popov void SCCPInstVisitor::visitAllocaInst(AllocaInst &I) {
1675657f26f0SNikita Popov   if (!NullPointerIsDefined(I.getFunction(), I.getAddressSpace()))
1676657f26f0SNikita Popov     return (void)markNotNull(ValueState[&I], &I);
1677657f26f0SNikita Popov 
1678657f26f0SNikita Popov   markOverdefined(&I);
1679657f26f0SNikita Popov }
1680657f26f0SNikita Popov 
1681bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitStoreInst(StoreInst &SI) {
1682bbab9f98SSjoerd Meijer   // If this store is of a struct, ignore it.
1683bbab9f98SSjoerd Meijer   if (SI.getOperand(0)->getType()->isStructTy())
1684bbab9f98SSjoerd Meijer     return;
1685bbab9f98SSjoerd Meijer 
1686bbab9f98SSjoerd Meijer   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1687bbab9f98SSjoerd Meijer     return;
1688bbab9f98SSjoerd Meijer 
1689bbab9f98SSjoerd Meijer   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1690bbab9f98SSjoerd Meijer   auto I = TrackedGlobals.find(GV);
1691bbab9f98SSjoerd Meijer   if (I == TrackedGlobals.end())
1692bbab9f98SSjoerd Meijer     return;
1693bbab9f98SSjoerd Meijer 
1694bbab9f98SSjoerd Meijer   // Get the value we are storing into the global, then merge it.
1695bbab9f98SSjoerd Meijer   mergeInValue(I->second, GV, getValueState(SI.getOperand(0)),
1696bbab9f98SSjoerd Meijer                ValueLatticeElement::MergeOptions().setCheckWiden(false));
1697bbab9f98SSjoerd Meijer   if (I->second.isOverdefined())
1698bbab9f98SSjoerd Meijer     TrackedGlobals.erase(I); // No need to keep tracking this!
1699bbab9f98SSjoerd Meijer }
1700bbab9f98SSjoerd Meijer 
1701bbab9f98SSjoerd Meijer static ValueLatticeElement getValueFromMetadata(const Instruction *I) {
1702657f26f0SNikita Popov   if (const auto *CB = dyn_cast<CallBase>(I)) {
1703657f26f0SNikita Popov     if (CB->getType()->isIntOrIntVectorTy())
1704657f26f0SNikita Popov       if (std::optional<ConstantRange> Range = CB->getRange())
1705657f26f0SNikita Popov         return ValueLatticeElement::getRange(*Range);
1706657f26f0SNikita Popov     if (CB->getType()->isPointerTy() && CB->isReturnNonNull())
1707657f26f0SNikita Popov       return ValueLatticeElement::getNot(
1708657f26f0SNikita Popov           ConstantPointerNull::get(cast<PointerType>(I->getType())));
1709657f26f0SNikita Popov   }
1710657f26f0SNikita Popov 
1711657f26f0SNikita Popov   if (I->getType()->isIntOrIntVectorTy())
1712bbab9f98SSjoerd Meijer     if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range))
1713bbab9f98SSjoerd Meijer       return ValueLatticeElement::getRange(
1714bbab9f98SSjoerd Meijer           getConstantRangeFromMetadata(*Ranges));
1715bbab9f98SSjoerd Meijer   if (I->hasMetadata(LLVMContext::MD_nonnull))
1716bbab9f98SSjoerd Meijer     return ValueLatticeElement::getNot(
1717bbab9f98SSjoerd Meijer         ConstantPointerNull::get(cast<PointerType>(I->getType())));
1718657f26f0SNikita Popov 
1719bbab9f98SSjoerd Meijer   return ValueLatticeElement::getOverdefined();
1720bbab9f98SSjoerd Meijer }
1721bbab9f98SSjoerd Meijer 
1722bbab9f98SSjoerd Meijer // Handle load instructions.  If the operand is a constant pointer to a constant
1723bbab9f98SSjoerd Meijer // global, we can replace the load with the loaded constant value!
1724bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitLoadInst(LoadInst &I) {
1725bbab9f98SSjoerd Meijer   // If this load is of a struct or the load is volatile, just mark the result
1726bbab9f98SSjoerd Meijer   // as overdefined.
1727bbab9f98SSjoerd Meijer   if (I.getType()->isStructTy() || I.isVolatile())
1728bbab9f98SSjoerd Meijer     return (void)markOverdefined(&I);
1729bbab9f98SSjoerd Meijer 
173039d29817SSjoerd Meijer   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1731bbab9f98SSjoerd Meijer   // discover a concrete value later.
1732bbab9f98SSjoerd Meijer   if (ValueState[&I].isOverdefined())
1733bbab9f98SSjoerd Meijer     return (void)markOverdefined(&I);
1734bbab9f98SSjoerd Meijer 
1735bbab9f98SSjoerd Meijer   ValueLatticeElement PtrVal = getValueState(I.getOperand(0));
1736bbab9f98SSjoerd Meijer   if (PtrVal.isUnknownOrUndef())
1737bbab9f98SSjoerd Meijer     return; // The pointer is not resolved yet!
1738bbab9f98SSjoerd Meijer 
1739bbab9f98SSjoerd Meijer   ValueLatticeElement &IV = ValueState[&I];
1740bbab9f98SSjoerd Meijer 
1741a794b62cSFlorian Hahn   if (SCCPSolver::isConstant(PtrVal)) {
1742664b7a4cSNikita Popov     Constant *Ptr = getConstant(PtrVal, I.getOperand(0)->getType());
1743bbab9f98SSjoerd Meijer 
1744bbab9f98SSjoerd Meijer     // load null is undefined.
1745bbab9f98SSjoerd Meijer     if (isa<ConstantPointerNull>(Ptr)) {
1746bbab9f98SSjoerd Meijer       if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace()))
1747bbab9f98SSjoerd Meijer         return (void)markOverdefined(IV, &I);
1748bbab9f98SSjoerd Meijer       else
1749bbab9f98SSjoerd Meijer         return;
1750bbab9f98SSjoerd Meijer     }
1751bbab9f98SSjoerd Meijer 
1752bbab9f98SSjoerd Meijer     // Transform load (constant global) into the value loaded.
1753bbab9f98SSjoerd Meijer     if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1754bbab9f98SSjoerd Meijer       if (!TrackedGlobals.empty()) {
1755bbab9f98SSjoerd Meijer         // If we are tracking this global, merge in the known value for it.
1756bbab9f98SSjoerd Meijer         auto It = TrackedGlobals.find(GV);
1757bbab9f98SSjoerd Meijer         if (It != TrackedGlobals.end()) {
1758bbab9f98SSjoerd Meijer           mergeInValue(IV, &I, It->second, getMaxWidenStepsOpts());
1759bbab9f98SSjoerd Meijer           return;
1760bbab9f98SSjoerd Meijer         }
1761bbab9f98SSjoerd Meijer       }
1762bbab9f98SSjoerd Meijer     }
1763bbab9f98SSjoerd Meijer 
1764bbab9f98SSjoerd Meijer     // Transform load from a constant into a constant if possible.
17656db3edc8SNikita Popov     if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL))
1766bbab9f98SSjoerd Meijer       return (void)markConstant(IV, &I, C);
1767bbab9f98SSjoerd Meijer   }
1768bbab9f98SSjoerd Meijer 
1769bbab9f98SSjoerd Meijer   // Fall back to metadata.
1770bbab9f98SSjoerd Meijer   mergeInValue(&I, getValueFromMetadata(&I));
1771bbab9f98SSjoerd Meijer }
1772bbab9f98SSjoerd Meijer 
1773bbab9f98SSjoerd Meijer void SCCPInstVisitor::visitCallBase(CallBase &CB) {
1774bbab9f98SSjoerd Meijer   handleCallResult(CB);
1775bbab9f98SSjoerd Meijer   handleCallArguments(CB);
1776bbab9f98SSjoerd Meijer }
1777bbab9f98SSjoerd Meijer 
1778bbab9f98SSjoerd Meijer void SCCPInstVisitor::handleCallOverdefined(CallBase &CB) {
1779bbab9f98SSjoerd Meijer   Function *F = CB.getCalledFunction();
1780bbab9f98SSjoerd Meijer 
1781bbab9f98SSjoerd Meijer   // Void return and not tracking callee, just bail.
1782bbab9f98SSjoerd Meijer   if (CB.getType()->isVoidTy())
1783bbab9f98SSjoerd Meijer     return;
1784bbab9f98SSjoerd Meijer 
1785bbab9f98SSjoerd Meijer   // Always mark struct return as overdefined.
1786bbab9f98SSjoerd Meijer   if (CB.getType()->isStructTy())
1787bbab9f98SSjoerd Meijer     return (void)markOverdefined(&CB);
1788bbab9f98SSjoerd Meijer 
1789bbab9f98SSjoerd Meijer   // Otherwise, if we have a single return value case, and if the function is
1790bbab9f98SSjoerd Meijer   // a declaration, maybe we can constant fold it.
1791bbab9f98SSjoerd Meijer   if (F && F->isDeclaration() && canConstantFoldCallTo(&CB, F)) {
1792bbab9f98SSjoerd Meijer     SmallVector<Constant *, 8> Operands;
1793098e9351SKazu Hirata     for (const Use &A : CB.args()) {
1794098e9351SKazu Hirata       if (A.get()->getType()->isStructTy())
1795bbab9f98SSjoerd Meijer         return markOverdefined(&CB); // Can't handle struct args.
1796cfb88ee3SKevin P. Neal       if (A.get()->getType()->isMetadataTy())
1797cfb88ee3SKevin P. Neal         continue;                    // Carried in CB, not allowed in Operands.
1798098e9351SKazu Hirata       ValueLatticeElement State = getValueState(A);
1799bbab9f98SSjoerd Meijer 
1800bbab9f98SSjoerd Meijer       if (State.isUnknownOrUndef())
1801bbab9f98SSjoerd Meijer         return; // Operands are not resolved yet.
1802a794b62cSFlorian Hahn       if (SCCPSolver::isOverdefined(State))
1803bbab9f98SSjoerd Meijer         return (void)markOverdefined(&CB);
1804a794b62cSFlorian Hahn       assert(SCCPSolver::isConstant(State) && "Unknown state!");
1805664b7a4cSNikita Popov       Operands.push_back(getConstant(State, A->getType()));
1806bbab9f98SSjoerd Meijer     }
1807bbab9f98SSjoerd Meijer 
1808a794b62cSFlorian Hahn     if (SCCPSolver::isOverdefined(getValueState(&CB)))
1809bbab9f98SSjoerd Meijer       return (void)markOverdefined(&CB);
1810bbab9f98SSjoerd Meijer 
1811bbab9f98SSjoerd Meijer     // If we can constant fold this, mark the result of the call as a
1812bbab9f98SSjoerd Meijer     // constant.
18136db3edc8SNikita Popov     if (Constant *C = ConstantFoldCall(&CB, F, Operands, &GetTLI(*F)))
1814bbab9f98SSjoerd Meijer       return (void)markConstant(&CB, C);
1815bbab9f98SSjoerd Meijer   }
1816bbab9f98SSjoerd Meijer 
1817bbab9f98SSjoerd Meijer   // Fall back to metadata.
1818bbab9f98SSjoerd Meijer   mergeInValue(&CB, getValueFromMetadata(&CB));
1819bbab9f98SSjoerd Meijer }
1820bbab9f98SSjoerd Meijer 
1821bbab9f98SSjoerd Meijer void SCCPInstVisitor::handleCallArguments(CallBase &CB) {
1822bbab9f98SSjoerd Meijer   Function *F = CB.getCalledFunction();
1823bbab9f98SSjoerd Meijer   // If this is a local function that doesn't have its address taken, mark its
1824bbab9f98SSjoerd Meijer   // entry block executable and merge in the actual arguments to the call into
1825bbab9f98SSjoerd Meijer   // the formal arguments of the function.
182695570af6SMatt Arsenault   if (TrackingIncomingArguments.count(F)) {
182739d29817SSjoerd Meijer     markBlockExecutable(&F->front());
1828bbab9f98SSjoerd Meijer 
1829bbab9f98SSjoerd Meijer     // Propagate information from this call site into the callee.
1830bbab9f98SSjoerd Meijer     auto CAI = CB.arg_begin();
1831bbab9f98SSjoerd Meijer     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1832bbab9f98SSjoerd Meijer          ++AI, ++CAI) {
1833bbab9f98SSjoerd Meijer       // If this argument is byval, and if the function is not readonly, there
1834bbab9f98SSjoerd Meijer       // will be an implicit copy formed of the input aggregate.
1835bbab9f98SSjoerd Meijer       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1836bbab9f98SSjoerd Meijer         markOverdefined(&*AI);
1837bbab9f98SSjoerd Meijer         continue;
1838bbab9f98SSjoerd Meijer       }
1839bbab9f98SSjoerd Meijer 
1840bbab9f98SSjoerd Meijer       if (auto *STy = dyn_cast<StructType>(AI->getType())) {
1841bbab9f98SSjoerd Meijer         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1842bbab9f98SSjoerd Meijer           ValueLatticeElement CallArg = getStructValueState(*CAI, i);
1843bbab9f98SSjoerd Meijer           mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg,
1844bbab9f98SSjoerd Meijer                        getMaxWidenStepsOpts());
1845bbab9f98SSjoerd Meijer         }
1846bbab9f98SSjoerd Meijer       } else
18477f59264dSNikita Popov         mergeInValue(&*AI,
18487f59264dSNikita Popov                      getValueState(*CAI).intersect(getArgAttributeVL(&*AI)),
18497f59264dSNikita Popov                      getMaxWidenStepsOpts());
1850bbab9f98SSjoerd Meijer     }
1851bbab9f98SSjoerd Meijer   }
1852bbab9f98SSjoerd Meijer }
1853bbab9f98SSjoerd Meijer 
1854bbab9f98SSjoerd Meijer void SCCPInstVisitor::handleCallResult(CallBase &CB) {
1855bbab9f98SSjoerd Meijer   Function *F = CB.getCalledFunction();
1856bbab9f98SSjoerd Meijer 
1857bbab9f98SSjoerd Meijer   if (auto *II = dyn_cast<IntrinsicInst>(&CB)) {
1858bbab9f98SSjoerd Meijer     if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
1859bbab9f98SSjoerd Meijer       if (ValueState[&CB].isOverdefined())
1860bbab9f98SSjoerd Meijer         return;
1861bbab9f98SSjoerd Meijer 
1862bbab9f98SSjoerd Meijer       Value *CopyOf = CB.getOperand(0);
1863bbab9f98SSjoerd Meijer       ValueLatticeElement CopyOfVal = getValueState(CopyOf);
186439d29817SSjoerd Meijer       const auto *PI = getPredicateInfoFor(&CB);
1865bbab9f98SSjoerd Meijer       assert(PI && "Missing predicate info for ssa.copy");
1866bbab9f98SSjoerd Meijer 
1867c178ed33SFangrui Song       const std::optional<PredicateConstraint> &Constraint =
1868c178ed33SFangrui Song           PI->getConstraint();
1869bbab9f98SSjoerd Meijer       if (!Constraint) {
1870bbab9f98SSjoerd Meijer         mergeInValue(ValueState[&CB], &CB, CopyOfVal);
1871bbab9f98SSjoerd Meijer         return;
1872bbab9f98SSjoerd Meijer       }
1873bbab9f98SSjoerd Meijer 
1874bbab9f98SSjoerd Meijer       CmpInst::Predicate Pred = Constraint->Predicate;
1875bbab9f98SSjoerd Meijer       Value *OtherOp = Constraint->OtherOp;
1876bbab9f98SSjoerd Meijer 
1877bbab9f98SSjoerd Meijer       // Wait until OtherOp is resolved.
1878bbab9f98SSjoerd Meijer       if (getValueState(OtherOp).isUnknown()) {
1879bbab9f98SSjoerd Meijer         addAdditionalUser(OtherOp, &CB);
1880bbab9f98SSjoerd Meijer         return;
1881bbab9f98SSjoerd Meijer       }
1882bbab9f98SSjoerd Meijer 
1883bbab9f98SSjoerd Meijer       ValueLatticeElement CondVal = getValueState(OtherOp);
1884bbab9f98SSjoerd Meijer       ValueLatticeElement &IV = ValueState[&CB];
1885bbab9f98SSjoerd Meijer       if (CondVal.isConstantRange() || CopyOfVal.isConstantRange()) {
1886bbab9f98SSjoerd Meijer         auto ImposedCR =
1887bbab9f98SSjoerd Meijer             ConstantRange::getFull(DL.getTypeSizeInBits(CopyOf->getType()));
1888bbab9f98SSjoerd Meijer 
1889bbab9f98SSjoerd Meijer         // Get the range imposed by the condition.
1890bbab9f98SSjoerd Meijer         if (CondVal.isConstantRange())
1891bbab9f98SSjoerd Meijer           ImposedCR = ConstantRange::makeAllowedICmpRegion(
1892bbab9f98SSjoerd Meijer               Pred, CondVal.getConstantRange());
1893bbab9f98SSjoerd Meijer 
1894bbab9f98SSjoerd Meijer         // Combine range info for the original value with the new range from the
1895bbab9f98SSjoerd Meijer         // condition.
18966b76c1e6SNikita Popov         auto CopyOfCR = CopyOfVal.asConstantRange(CopyOf->getType(),
189727392a35SNikita Popov                                                   /*UndefAllowed=*/true);
18986b76c1e6SNikita Popov         // Treat an unresolved input like a full range.
18996b76c1e6SNikita Popov         if (CopyOfCR.isEmptySet())
19006b76c1e6SNikita Popov           CopyOfCR = ConstantRange::getFull(CopyOfCR.getBitWidth());
1901bbab9f98SSjoerd Meijer         auto NewCR = ImposedCR.intersectWith(CopyOfCR);
1902bbab9f98SSjoerd Meijer         // If the existing information is != x, do not use the information from
1903bbab9f98SSjoerd Meijer         // a chained predicate, as the != x information is more likely to be
1904bbab9f98SSjoerd Meijer         // helpful in practice.
1905bbab9f98SSjoerd Meijer         if (!CopyOfCR.contains(NewCR) && CopyOfCR.getSingleMissingElement())
1906bbab9f98SSjoerd Meijer           NewCR = CopyOfCR;
1907bbab9f98SSjoerd Meijer 
19087fa97b47SNikita Popov         // The new range is based on a branch condition. That guarantees that
19097fa97b47SNikita Popov         // neither of the compare operands can be undef in the branch targets,
19107fa97b47SNikita Popov         // unless we have conditions that are always true/false (e.g. icmp ule
19117fa97b47SNikita Popov         // i32, %a, i32_max). For the latter overdefined/empty range will be
19127fa97b47SNikita Popov         // inferred, but the branch will get folded accordingly anyways.
1913bbab9f98SSjoerd Meijer         addAdditionalUser(OtherOp, &CB);
19147fa97b47SNikita Popov         mergeInValue(
19157fa97b47SNikita Popov             IV, &CB,
19167fa97b47SNikita Popov             ValueLatticeElement::getRange(NewCR, /*MayIncludeUndef*/ false));
1917bbab9f98SSjoerd Meijer         return;
1918b0f78769Sluxufan       } else if (Pred == CmpInst::ICMP_EQ &&
1919b0f78769Sluxufan                  (CondVal.isConstant() || CondVal.isNotConstant())) {
1920bbab9f98SSjoerd Meijer         // For non-integer values or integer constant expressions, only
1921b0f78769Sluxufan         // propagate equal constants or not-constants.
1922bbab9f98SSjoerd Meijer         addAdditionalUser(OtherOp, &CB);
1923bbab9f98SSjoerd Meijer         mergeInValue(IV, &CB, CondVal);
1924bbab9f98SSjoerd Meijer         return;
19257fa97b47SNikita Popov       } else if (Pred == CmpInst::ICMP_NE && CondVal.isConstant()) {
1926bbab9f98SSjoerd Meijer         // Propagate inequalities.
1927bbab9f98SSjoerd Meijer         addAdditionalUser(OtherOp, &CB);
1928bbab9f98SSjoerd Meijer         mergeInValue(IV, &CB,
1929bbab9f98SSjoerd Meijer                      ValueLatticeElement::getNot(CondVal.getConstant()));
1930bbab9f98SSjoerd Meijer         return;
1931bbab9f98SSjoerd Meijer       }
1932bbab9f98SSjoerd Meijer 
1933bbab9f98SSjoerd Meijer       return (void)mergeInValue(IV, &CB, CopyOfVal);
1934bbab9f98SSjoerd Meijer     }
1935bbab9f98SSjoerd Meijer 
1936b396921dSHari Limaye     if (II->getIntrinsicID() == Intrinsic::vscale) {
1937b396921dSHari Limaye       unsigned BitWidth = CB.getType()->getScalarSizeInBits();
1938b396921dSHari Limaye       const ConstantRange Result = getVScaleRange(II->getFunction(), BitWidth);
1939b396921dSHari Limaye       return (void)mergeInValue(II, ValueLatticeElement::getRange(Result));
1940b396921dSHari Limaye     }
1941b396921dSHari Limaye 
1942bbab9f98SSjoerd Meijer     if (ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
1943bbab9f98SSjoerd Meijer       // Compute result range for intrinsics supported by ConstantRange.
1944bbab9f98SSjoerd Meijer       // Do this even if we don't know a range for all operands, as we may
1945bbab9f98SSjoerd Meijer       // still know something about the result range, e.g. of abs(x).
1946bbab9f98SSjoerd Meijer       SmallVector<ConstantRange, 2> OpRanges;
1947bbab9f98SSjoerd Meijer       for (Value *Op : II->args()) {
1948bbab9f98SSjoerd Meijer         const ValueLatticeElement &State = getValueState(Op);
194925d9fde2Sluxufan         if (State.isUnknownOrUndef())
195025d9fde2Sluxufan           return;
195127392a35SNikita Popov         OpRanges.push_back(
19526b76c1e6SNikita Popov             State.asConstantRange(Op->getType(), /*UndefAllowed=*/false));
1953bbab9f98SSjoerd Meijer       }
1954bbab9f98SSjoerd Meijer 
1955bbab9f98SSjoerd Meijer       ConstantRange Result =
1956bbab9f98SSjoerd Meijer           ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges);
1957bbab9f98SSjoerd Meijer       return (void)mergeInValue(II, ValueLatticeElement::getRange(Result));
1958bbab9f98SSjoerd Meijer     }
1959bbab9f98SSjoerd Meijer   }
1960bbab9f98SSjoerd Meijer 
1961bbab9f98SSjoerd Meijer   // The common case is that we aren't tracking the callee, either because we
1962bbab9f98SSjoerd Meijer   // are not doing interprocedural analysis or the callee is indirect, or is
1963bbab9f98SSjoerd Meijer   // external.  Handle these cases first.
1964bbab9f98SSjoerd Meijer   if (!F || F->isDeclaration())
1965bbab9f98SSjoerd Meijer     return handleCallOverdefined(CB);
1966bbab9f98SSjoerd Meijer 
1967bbab9f98SSjoerd Meijer   // If this is a single/zero retval case, see if we're tracking the function.
1968bbab9f98SSjoerd Meijer   if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
1969bbab9f98SSjoerd Meijer     if (!MRVFunctionsTracked.count(F))
1970bbab9f98SSjoerd Meijer       return handleCallOverdefined(CB); // Not tracking this callee.
1971bbab9f98SSjoerd Meijer 
1972bbab9f98SSjoerd Meijer     // If we are tracking this callee, propagate the result of the function
1973bbab9f98SSjoerd Meijer     // into this call site.
1974bbab9f98SSjoerd Meijer     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1975bbab9f98SSjoerd Meijer       mergeInValue(getStructValueState(&CB, i), &CB,
1976bbab9f98SSjoerd Meijer                    TrackedMultipleRetVals[std::make_pair(F, i)],
1977bbab9f98SSjoerd Meijer                    getMaxWidenStepsOpts());
1978bbab9f98SSjoerd Meijer   } else {
1979bbab9f98SSjoerd Meijer     auto TFRVI = TrackedRetVals.find(F);
1980bbab9f98SSjoerd Meijer     if (TFRVI == TrackedRetVals.end())
1981bbab9f98SSjoerd Meijer       return handleCallOverdefined(CB); // Not tracking this callee.
1982bbab9f98SSjoerd Meijer 
1983bbab9f98SSjoerd Meijer     // If so, propagate the return value of the callee into this call result.
1984bbab9f98SSjoerd Meijer     mergeInValue(&CB, TFRVI->second, getMaxWidenStepsOpts());
1985bbab9f98SSjoerd Meijer   }
1986bbab9f98SSjoerd Meijer }
1987bbab9f98SSjoerd Meijer 
198839d29817SSjoerd Meijer void SCCPInstVisitor::solve() {
1989bbab9f98SSjoerd Meijer   // Process the work lists until they are empty!
1990bbab9f98SSjoerd Meijer   while (!BBWorkList.empty() || !InstWorkList.empty() ||
1991bbab9f98SSjoerd Meijer          !OverdefinedInstWorkList.empty()) {
1992bbab9f98SSjoerd Meijer     // Process the overdefined instruction's work list first, which drives other
1993bbab9f98SSjoerd Meijer     // things to overdefined more quickly.
1994bbab9f98SSjoerd Meijer     while (!OverdefinedInstWorkList.empty()) {
1995bbab9f98SSjoerd Meijer       Value *I = OverdefinedInstWorkList.pop_back_val();
199654e5fb78SAlexandros Lamprineas       Invalidated.erase(I);
1997bbab9f98SSjoerd Meijer 
1998bbab9f98SSjoerd Meijer       LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1999bbab9f98SSjoerd Meijer 
2000bbab9f98SSjoerd Meijer       // "I" got into the work list because it either made the transition from
2001bbab9f98SSjoerd Meijer       // bottom to constant, or to overdefined.
2002bbab9f98SSjoerd Meijer       //
2003bbab9f98SSjoerd Meijer       // Anything on this worklist that is overdefined need not be visited
2004bbab9f98SSjoerd Meijer       // since all of its users will have already been marked as overdefined
2005bbab9f98SSjoerd Meijer       // Update all of the users of this instruction's value.
2006bbab9f98SSjoerd Meijer       //
2007bbab9f98SSjoerd Meijer       markUsersAsChanged(I);
2008bbab9f98SSjoerd Meijer     }
2009bbab9f98SSjoerd Meijer 
2010bbab9f98SSjoerd Meijer     // Process the instruction work list.
2011bbab9f98SSjoerd Meijer     while (!InstWorkList.empty()) {
2012bbab9f98SSjoerd Meijer       Value *I = InstWorkList.pop_back_val();
201354e5fb78SAlexandros Lamprineas       Invalidated.erase(I);
2014bbab9f98SSjoerd Meijer 
2015bbab9f98SSjoerd Meijer       LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
2016bbab9f98SSjoerd Meijer 
2017bbab9f98SSjoerd Meijer       // "I" got into the work list because it made the transition from undef to
2018bbab9f98SSjoerd Meijer       // constant.
2019bbab9f98SSjoerd Meijer       //
2020bbab9f98SSjoerd Meijer       // Anything on this worklist that is overdefined need not be visited
2021bbab9f98SSjoerd Meijer       // since all of its users will have already been marked as overdefined.
2022bbab9f98SSjoerd Meijer       // Update all of the users of this instruction's value.
2023bbab9f98SSjoerd Meijer       //
2024bbab9f98SSjoerd Meijer       if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
2025bbab9f98SSjoerd Meijer         markUsersAsChanged(I);
2026bbab9f98SSjoerd Meijer     }
2027bbab9f98SSjoerd Meijer 
2028bbab9f98SSjoerd Meijer     // Process the basic block work list.
2029bbab9f98SSjoerd Meijer     while (!BBWorkList.empty()) {
2030bbab9f98SSjoerd Meijer       BasicBlock *BB = BBWorkList.pop_back_val();
2031bbab9f98SSjoerd Meijer 
2032bbab9f98SSjoerd Meijer       LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
2033bbab9f98SSjoerd Meijer 
2034bbab9f98SSjoerd Meijer       // Notify all instructions in this basic block that they are newly
2035bbab9f98SSjoerd Meijer       // executable.
2036bbab9f98SSjoerd Meijer       visit(BB);
2037bbab9f98SSjoerd Meijer     }
2038bbab9f98SSjoerd Meijer   }
2039bbab9f98SSjoerd Meijer }
2040bbab9f98SSjoerd Meijer 
204154e5fb78SAlexandros Lamprineas bool SCCPInstVisitor::resolvedUndef(Instruction &I) {
204254e5fb78SAlexandros Lamprineas   // Look for instructions which produce undef values.
204354e5fb78SAlexandros Lamprineas   if (I.getType()->isVoidTy())
204454e5fb78SAlexandros Lamprineas     return false;
204554e5fb78SAlexandros Lamprineas 
204654e5fb78SAlexandros Lamprineas   if (auto *STy = dyn_cast<StructType>(I.getType())) {
204754e5fb78SAlexandros Lamprineas     // Only a few things that can be structs matter for undef.
204854e5fb78SAlexandros Lamprineas 
204954e5fb78SAlexandros Lamprineas     // Tracked calls must never be marked overdefined in resolvedUndefsIn.
205054e5fb78SAlexandros Lamprineas     if (auto *CB = dyn_cast<CallBase>(&I))
205154e5fb78SAlexandros Lamprineas       if (Function *F = CB->getCalledFunction())
205254e5fb78SAlexandros Lamprineas         if (MRVFunctionsTracked.count(F))
205354e5fb78SAlexandros Lamprineas           return false;
205454e5fb78SAlexandros Lamprineas 
205554e5fb78SAlexandros Lamprineas     // extractvalue and insertvalue don't need to be marked; they are
205654e5fb78SAlexandros Lamprineas     // tracked as precisely as their operands.
205754e5fb78SAlexandros Lamprineas     if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
205854e5fb78SAlexandros Lamprineas       return false;
205954e5fb78SAlexandros Lamprineas     // Send the results of everything else to overdefined.  We could be
206054e5fb78SAlexandros Lamprineas     // more precise than this but it isn't worth bothering.
206154e5fb78SAlexandros Lamprineas     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
206254e5fb78SAlexandros Lamprineas       ValueLatticeElement &LV = getStructValueState(&I, i);
206354e5fb78SAlexandros Lamprineas       if (LV.isUnknown()) {
206454e5fb78SAlexandros Lamprineas         markOverdefined(LV, &I);
206554e5fb78SAlexandros Lamprineas         return true;
206654e5fb78SAlexandros Lamprineas       }
206754e5fb78SAlexandros Lamprineas     }
206854e5fb78SAlexandros Lamprineas     return false;
206954e5fb78SAlexandros Lamprineas   }
207054e5fb78SAlexandros Lamprineas 
207154e5fb78SAlexandros Lamprineas   ValueLatticeElement &LV = getValueState(&I);
207254e5fb78SAlexandros Lamprineas   if (!LV.isUnknown())
207354e5fb78SAlexandros Lamprineas     return false;
207454e5fb78SAlexandros Lamprineas 
207554e5fb78SAlexandros Lamprineas   // There are two reasons a call can have an undef result
207654e5fb78SAlexandros Lamprineas   // 1. It could be tracked.
207754e5fb78SAlexandros Lamprineas   // 2. It could be constant-foldable.
207854e5fb78SAlexandros Lamprineas   // Because of the way we solve return values, tracked calls must
207954e5fb78SAlexandros Lamprineas   // never be marked overdefined in resolvedUndefsIn.
208054e5fb78SAlexandros Lamprineas   if (auto *CB = dyn_cast<CallBase>(&I))
208154e5fb78SAlexandros Lamprineas     if (Function *F = CB->getCalledFunction())
208254e5fb78SAlexandros Lamprineas       if (TrackedRetVals.count(F))
208354e5fb78SAlexandros Lamprineas         return false;
208454e5fb78SAlexandros Lamprineas 
208554e5fb78SAlexandros Lamprineas   if (isa<LoadInst>(I)) {
208654e5fb78SAlexandros Lamprineas     // A load here means one of two things: a load of undef from a global,
208754e5fb78SAlexandros Lamprineas     // a load from an unknown pointer.  Either way, having it return undef
208854e5fb78SAlexandros Lamprineas     // is okay.
208954e5fb78SAlexandros Lamprineas     return false;
209054e5fb78SAlexandros Lamprineas   }
209154e5fb78SAlexandros Lamprineas 
209254e5fb78SAlexandros Lamprineas   markOverdefined(&I);
209354e5fb78SAlexandros Lamprineas   return true;
209454e5fb78SAlexandros Lamprineas }
209554e5fb78SAlexandros Lamprineas 
20961f88d804SNikita Popov /// While solving the dataflow for a function, we don't compute a result for
20971f88d804SNikita Popov /// operations with an undef operand, to allow undef to be lowered to a
20981f88d804SNikita Popov /// constant later. For example, constant folding of "zext i8 undef to i16"
20991f88d804SNikita Popov /// would result in "i16 0", and if undef is later lowered to "i8 1", then the
21001f88d804SNikita Popov /// zext result would become "i16 1" and would result into an overdefined
21011f88d804SNikita Popov /// lattice value once merged with the previous result. Not computing the
21021f88d804SNikita Popov /// result of the zext (treating undef the same as unknown) allows us to handle
21031f88d804SNikita Popov /// a later undef->constant lowering more optimally.
2104bbab9f98SSjoerd Meijer ///
21051f88d804SNikita Popov /// However, if the operand remains undef when the solver returns, we do need
21061f88d804SNikita Popov /// to assign some result to the instruction (otherwise we would treat it as
21071f88d804SNikita Popov /// unreachable). For simplicity, we mark any instructions that are still
21089b994593SNikita Popov /// unknown as overdefined.
210939d29817SSjoerd Meijer bool SCCPInstVisitor::resolvedUndefsIn(Function &F) {
2110bbab9f98SSjoerd Meijer   bool MadeChange = false;
2111bbab9f98SSjoerd Meijer   for (BasicBlock &BB : F) {
2112bbab9f98SSjoerd Meijer     if (!BBExecutable.count(&BB))
2113bbab9f98SSjoerd Meijer       continue;
2114bbab9f98SSjoerd Meijer 
211554e5fb78SAlexandros Lamprineas     for (Instruction &I : BB)
211654e5fb78SAlexandros Lamprineas       MadeChange |= resolvedUndef(I);
2117bbab9f98SSjoerd Meijer   }
2118bbab9f98SSjoerd Meijer 
21198136a017SAlexandros Lamprineas   LLVM_DEBUG(if (MadeChange) dbgs()
21208136a017SAlexandros Lamprineas              << "\nResolved undefs in " << F.getName() << '\n');
21218136a017SAlexandros Lamprineas 
2122bbab9f98SSjoerd Meijer   return MadeChange;
2123bbab9f98SSjoerd Meijer }
2124bbab9f98SSjoerd Meijer 
2125bbab9f98SSjoerd Meijer //===----------------------------------------------------------------------===//
2126bbab9f98SSjoerd Meijer //
2127bbab9f98SSjoerd Meijer // SCCPSolver implementations
2128bbab9f98SSjoerd Meijer //
2129bbab9f98SSjoerd Meijer SCCPSolver::SCCPSolver(
2130bbab9f98SSjoerd Meijer     const DataLayout &DL,
2131bbab9f98SSjoerd Meijer     std::function<const TargetLibraryInfo &(Function &)> GetTLI,
2132bbab9f98SSjoerd Meijer     LLVMContext &Ctx)
2133bbab9f98SSjoerd Meijer     : Visitor(new SCCPInstVisitor(DL, std::move(GetTLI), Ctx)) {}
2134bbab9f98SSjoerd Meijer 
21353a3cb929SKazu Hirata SCCPSolver::~SCCPSolver() = default;
2136bbab9f98SSjoerd Meijer 
2137b1f41685SAlexandros Lamprineas void SCCPSolver::addPredicateInfo(Function &F, DominatorTree &DT,
2138b1f41685SAlexandros Lamprineas                                   AssumptionCache &AC) {
2139b1f41685SAlexandros Lamprineas   Visitor->addPredicateInfo(F, DT, AC);
2140bbab9f98SSjoerd Meijer }
2141bbab9f98SSjoerd Meijer 
214239d29817SSjoerd Meijer bool SCCPSolver::markBlockExecutable(BasicBlock *BB) {
214339d29817SSjoerd Meijer   return Visitor->markBlockExecutable(BB);
2144bbab9f98SSjoerd Meijer }
2145bbab9f98SSjoerd Meijer 
2146bbab9f98SSjoerd Meijer const PredicateBase *SCCPSolver::getPredicateInfoFor(Instruction *I) {
2147bbab9f98SSjoerd Meijer   return Visitor->getPredicateInfoFor(I);
2148bbab9f98SSjoerd Meijer }
2149bbab9f98SSjoerd Meijer 
215039d29817SSjoerd Meijer void SCCPSolver::trackValueOfGlobalVariable(GlobalVariable *GV) {
215139d29817SSjoerd Meijer   Visitor->trackValueOfGlobalVariable(GV);
2152bbab9f98SSjoerd Meijer }
2153bbab9f98SSjoerd Meijer 
215439d29817SSjoerd Meijer void SCCPSolver::addTrackedFunction(Function *F) {
215539d29817SSjoerd Meijer   Visitor->addTrackedFunction(F);
2156bbab9f98SSjoerd Meijer }
2157bbab9f98SSjoerd Meijer 
2158bbab9f98SSjoerd Meijer void SCCPSolver::addToMustPreserveReturnsInFunctions(Function *F) {
2159bbab9f98SSjoerd Meijer   Visitor->addToMustPreserveReturnsInFunctions(F);
2160bbab9f98SSjoerd Meijer }
2161bbab9f98SSjoerd Meijer 
2162bbab9f98SSjoerd Meijer bool SCCPSolver::mustPreserveReturn(Function *F) {
2163bbab9f98SSjoerd Meijer   return Visitor->mustPreserveReturn(F);
2164bbab9f98SSjoerd Meijer }
2165bbab9f98SSjoerd Meijer 
216639d29817SSjoerd Meijer void SCCPSolver::addArgumentTrackedFunction(Function *F) {
216739d29817SSjoerd Meijer   Visitor->addArgumentTrackedFunction(F);
2168bbab9f98SSjoerd Meijer }
2169bbab9f98SSjoerd Meijer 
2170bbab9f98SSjoerd Meijer bool SCCPSolver::isArgumentTrackedFunction(Function *F) {
2171bbab9f98SSjoerd Meijer   return Visitor->isArgumentTrackedFunction(F);
2172bbab9f98SSjoerd Meijer }
2173bbab9f98SSjoerd Meijer 
2174b7e51b4fSNikita Popov const SmallPtrSetImpl<Function *> &
2175b7e51b4fSNikita Popov SCCPSolver::getArgumentTrackedFunctions() const {
2176b7e51b4fSNikita Popov   return Visitor->getArgumentTrackedFunctions();
2177b7e51b4fSNikita Popov }
2178b7e51b4fSNikita Popov 
217939d29817SSjoerd Meijer void SCCPSolver::solve() { Visitor->solve(); }
2180bbab9f98SSjoerd Meijer 
218139d29817SSjoerd Meijer bool SCCPSolver::resolvedUndefsIn(Function &F) {
218239d29817SSjoerd Meijer   return Visitor->resolvedUndefsIn(F);
2183bbab9f98SSjoerd Meijer }
2184bbab9f98SSjoerd Meijer 
21858136a017SAlexandros Lamprineas void SCCPSolver::solveWhileResolvedUndefsIn(Module &M) {
21868136a017SAlexandros Lamprineas   Visitor->solveWhileResolvedUndefsIn(M);
21878136a017SAlexandros Lamprineas }
21888136a017SAlexandros Lamprineas 
21898136a017SAlexandros Lamprineas void
21908136a017SAlexandros Lamprineas SCCPSolver::solveWhileResolvedUndefsIn(SmallVectorImpl<Function *> &WorkList) {
21918136a017SAlexandros Lamprineas   Visitor->solveWhileResolvedUndefsIn(WorkList);
21928136a017SAlexandros Lamprineas }
21938136a017SAlexandros Lamprineas 
219454e5fb78SAlexandros Lamprineas void SCCPSolver::solveWhileResolvedUndefs() {
219554e5fb78SAlexandros Lamprineas   Visitor->solveWhileResolvedUndefs();
219654e5fb78SAlexandros Lamprineas }
219754e5fb78SAlexandros Lamprineas 
2198bbab9f98SSjoerd Meijer bool SCCPSolver::isBlockExecutable(BasicBlock *BB) const {
2199bbab9f98SSjoerd Meijer   return Visitor->isBlockExecutable(BB);
2200bbab9f98SSjoerd Meijer }
2201bbab9f98SSjoerd Meijer 
2202bbab9f98SSjoerd Meijer bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const {
2203bbab9f98SSjoerd Meijer   return Visitor->isEdgeFeasible(From, To);
2204bbab9f98SSjoerd Meijer }
2205bbab9f98SSjoerd Meijer 
2206bbab9f98SSjoerd Meijer std::vector<ValueLatticeElement>
2207bbab9f98SSjoerd Meijer SCCPSolver::getStructLatticeValueFor(Value *V) const {
2208bbab9f98SSjoerd Meijer   return Visitor->getStructLatticeValueFor(V);
2209bbab9f98SSjoerd Meijer }
2210bbab9f98SSjoerd Meijer 
221123ea58f3SVitaly Buka void SCCPSolver::removeLatticeValueFor(Value *V) {
221223ea58f3SVitaly Buka   return Visitor->removeLatticeValueFor(V);
2213bbab9f98SSjoerd Meijer }
2214bbab9f98SSjoerd Meijer 
221554e5fb78SAlexandros Lamprineas void SCCPSolver::resetLatticeValueFor(CallBase *Call) {
221654e5fb78SAlexandros Lamprineas   Visitor->resetLatticeValueFor(Call);
221754e5fb78SAlexandros Lamprineas }
221854e5fb78SAlexandros Lamprineas 
2219bbab9f98SSjoerd Meijer const ValueLatticeElement &SCCPSolver::getLatticeValueFor(Value *V) const {
2220bbab9f98SSjoerd Meijer   return Visitor->getLatticeValueFor(V);
2221bbab9f98SSjoerd Meijer }
2222bbab9f98SSjoerd Meijer 
2223bbab9f98SSjoerd Meijer const MapVector<Function *, ValueLatticeElement> &
222424fe1d4fSNikita Popov SCCPSolver::getTrackedRetVals() const {
2225bbab9f98SSjoerd Meijer   return Visitor->getTrackedRetVals();
2226bbab9f98SSjoerd Meijer }
2227bbab9f98SSjoerd Meijer 
2228bbab9f98SSjoerd Meijer const DenseMap<GlobalVariable *, ValueLatticeElement> &
2229bbab9f98SSjoerd Meijer SCCPSolver::getTrackedGlobals() {
2230bbab9f98SSjoerd Meijer   return Visitor->getTrackedGlobals();
2231bbab9f98SSjoerd Meijer }
2232bbab9f98SSjoerd Meijer 
2233bbab9f98SSjoerd Meijer const SmallPtrSet<Function *, 16> SCCPSolver::getMRVFunctionsTracked() {
2234bbab9f98SSjoerd Meijer   return Visitor->getMRVFunctionsTracked();
2235bbab9f98SSjoerd Meijer }
2236bbab9f98SSjoerd Meijer 
2237bbab9f98SSjoerd Meijer void SCCPSolver::markOverdefined(Value *V) { Visitor->markOverdefined(V); }
2238bbab9f98SSjoerd Meijer 
2239e7bc5372SAndreas Jonson void SCCPSolver::trackValueOfArgument(Argument *V) {
2240e7bc5372SAndreas Jonson   Visitor->trackValueOfArgument(V);
2241e7bc5372SAndreas Jonson }
2242e7bc5372SAndreas Jonson 
2243bbab9f98SSjoerd Meijer bool SCCPSolver::isStructLatticeConstant(Function *F, StructType *STy) {
2244bbab9f98SSjoerd Meijer   return Visitor->isStructLatticeConstant(F, STy);
2245bbab9f98SSjoerd Meijer }
2246bbab9f98SSjoerd Meijer 
2247664b7a4cSNikita Popov Constant *SCCPSolver::getConstant(const ValueLatticeElement &LV,
2248664b7a4cSNikita Popov                                   Type *Ty) const {
2249664b7a4cSNikita Popov   return Visitor->getConstant(LV, Ty);
2250bbab9f98SSjoerd Meijer }
2251c4a0969bSSjoerd Meijer 
22527ea597eaSAlexandros Lamprineas Constant *SCCPSolver::getConstantOrNull(Value *V) const {
22537ea597eaSAlexandros Lamprineas   return Visitor->getConstantOrNull(V);
22547ea597eaSAlexandros Lamprineas }
22557ea597eaSAlexandros Lamprineas 
22567ea597eaSAlexandros Lamprineas void SCCPSolver::setLatticeValueForSpecializationArguments(Function *F,
22577ea597eaSAlexandros Lamprineas                                    const SmallVectorImpl<ArgInfo> &Args) {
22587ea597eaSAlexandros Lamprineas   Visitor->setLatticeValueForSpecializationArguments(F, Args);
2259c4a0969bSSjoerd Meijer }
2260c4a0969bSSjoerd Meijer 
2261c4a0969bSSjoerd Meijer void SCCPSolver::markFunctionUnreachable(Function *F) {
2262c4a0969bSSjoerd Meijer   Visitor->markFunctionUnreachable(F);
2263c4a0969bSSjoerd Meijer }
2264c4a0969bSSjoerd Meijer 
2265c4a0969bSSjoerd Meijer void SCCPSolver::visit(Instruction *I) { Visitor->visit(I); }
2266c4a0969bSSjoerd Meijer 
2267c4a0969bSSjoerd Meijer void SCCPSolver::visitCall(CallInst &I) { Visitor->visitCall(I); }
2268