47 #define DEBUG_TYPE "sccp"
49 STATISTIC(NumInstRemoved,
"Number of instructions removed");
50 STATISTIC(NumDeadBlocks ,
"Number of basic blocks unreachable");
52 STATISTIC(IPNumInstRemoved,
"Number of instructions removed by IPSCCP");
53 STATISTIC(IPNumArgsElimed ,
"Number of arguments constant propagated by IPSCCP");
54 STATISTIC(IPNumGlobalConst,
"Number of globals found to be constant by IPSCCP");
83 LatticeValueTy getLatticeValue()
const {
88 LatticeVal() : Val(nullptr, unknown) {}
90 bool isUnknown()
const {
return getLatticeValue() == unknown; }
92 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
94 bool isOverdefined()
const {
return getLatticeValue() == overdefined; }
98 return Val.getPointer();
102 bool markOverdefined() {
106 Val.setInt(overdefined);
112 if (getLatticeValue() == constant) {
113 assert(getConstant() == V &&
"Marking constant with different value");
118 Val.setInt(constant);
119 assert(V &&
"Marking constant with NULL");
122 assert(getLatticeValue() == forcedconstant &&
123 "Cannot move from overdefined to constant!");
125 if (V == getConstant())
return false;
130 Val.setInt(overdefined);
151 void markForcedConstant(
Constant *V) {
152 assert(isUnknown() &&
"Can't force a defined value!");
153 Val.setInt(forcedconstant);
167 class SCCPSolver :
public InstVisitor<SCCPSolver> {
217 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
221 : DL(DL), TLI(tli) {}
228 if (!BBExecutable.insert(BB).second)
231 BBWorkList.push_back(BB);
242 LatticeVal &IV = TrackedGlobals[GV];
254 MRVFunctionsTracked.insert(F);
255 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
256 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
259 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
262 void AddArgumentTrackedFunction(
Function *F) {
263 TrackingIncomingArguments.insert(F);
277 bool isBlockExecutable(
BasicBlock *BB)
const {
278 return BBExecutable.count(BB);
281 std::vector<LatticeVal> getStructLatticeValueFor(
Value *V)
const {
282 std::vector<LatticeVal> StructValues;
284 assert(STy &&
"getStructLatticeValueFor() can be called only on structs");
285 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
286 auto I = StructValueState.find(std::make_pair(V, i));
287 assert(
I != StructValueState.end() &&
"Value not in valuemap!");
288 StructValues.push_back(
I->second);
293 LatticeVal getLatticeValueFor(
Value *V)
const {
295 assert(I != ValueState.
end() &&
"V is not in valuemap!");
302 return TrackedRetVals;
308 return TrackedGlobals;
314 return MRVFunctionsTracked;
319 void markOverdefined(
Value *V) {
320 if (
auto *STy = dyn_cast<StructType>(V->
getType()))
321 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
322 markOverdefined(getStructValueState(V, i), V);
324 markOverdefined(ValueState[V], V);
332 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
333 assert(It != TrackedMultipleRetVals.end());
334 LatticeVal LV = It->second;
335 if (LV.isOverdefined())
343 void pushToWorkList(LatticeVal &IV,
Value *V) {
344 if (IV.isOverdefined())
345 return OverdefinedInstWorkList.push_back(V);
346 InstWorkList.push_back(V);
354 if (!IV.markConstant(C))
return;
355 DEBUG(
dbgs() <<
"markConstant: " << *C <<
": " << *V <<
'\n');
356 pushToWorkList(IV, V);
361 markConstant(ValueState[V], V, C);
366 LatticeVal &IV = ValueState[V];
367 IV.markForcedConstant(C);
368 DEBUG(
dbgs() <<
"markForcedConstant: " << *C <<
": " << *V <<
'\n');
369 pushToWorkList(IV, V);
376 void markOverdefined(LatticeVal &IV,
Value *V) {
377 if (!IV.markOverdefined())
return;
380 if (
auto *F = dyn_cast<Function>(V))
383 dbgs() << *V <<
'\n');
385 pushToWorkList(IV, V);
388 void mergeInValue(LatticeVal &IV,
Value *V, LatticeVal MergeWithV) {
389 if (IV.isOverdefined() || MergeWithV.isUnknown())
391 if (MergeWithV.isOverdefined())
392 return markOverdefined(IV, V);
394 return markConstant(IV, V, MergeWithV.getConstant());
395 if (IV.getConstant() != MergeWithV.getConstant())
396 return markOverdefined(IV, V);
399 void mergeInValue(
Value *V, LatticeVal MergeWithV) {
401 "non-structs should use markConstant");
402 mergeInValue(ValueState[V], V, MergeWithV);
409 LatticeVal &getValueState(
Value *V) {
412 std::pair<DenseMap<Value*, LatticeVal>::iterator,
bool> I =
413 ValueState.
insert(std::make_pair(V, LatticeVal()));
414 LatticeVal &LV = I.first->second;
419 if (
auto *C = dyn_cast<Constant>(V)) {
421 if (!isa<UndefValue>(V))
432 LatticeVal &getStructValueState(
Value *V,
unsigned i) {
434 assert(i < cast<StructType>(V->
getType())->getNumElements() &&
435 "Invalid element #");
437 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
438 bool> I = StructValueState.insert(
439 std::make_pair(std::make_pair(V, i), LatticeVal()));
440 LatticeVal &LV = I.first->second;
445 if (
auto *C = dyn_cast<Constant>(V)) {
449 LV.markOverdefined();
450 else if (isa<UndefValue>(Elt))
453 LV.markConstant(Elt);
464 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
467 if (!MarkBlockExecutable(Dest)) {
472 <<
" -> " << Dest->
getName() <<
'\n');
519 markOverdefined(&CPI);
520 visitTerminatorInst(CPI);
532 visitTerminatorInst(II);
541 DEBUG(
dbgs() <<
"SCCP: Don't know how to handle: " << I <<
'\n');
555 if (
auto *BI = dyn_cast<BranchInst>(&TI)) {
556 if (BI->isUnconditional()) {
561 LatticeVal BCValue = getValueState(BI->getCondition());
566 if (!BCValue.isUnknown())
567 Succs[0] = Succs[1] =
true;
572 Succs[CI->isZero()] =
true;
582 if (
auto *
SI = dyn_cast<SwitchInst>(&TI)) {
583 if (!
SI->getNumCases()) {
587 LatticeVal SCValue = getValueState(
SI->getCondition());
592 if (!SCValue.isUnknown())
597 Succs[
SI->findCaseValue(CI)->getSuccessorIndex()] =
true;
603 if (
auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
605 LatticeVal IBRValue = getValueState(IBR->getAddress());
609 if (!IBRValue.isUnknown())
616 "Block address of a different function ?");
617 for (
unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
619 if (IBR->getDestination(i) ==
T) {
630 DEBUG(
dbgs() <<
"Unknown terminator instruction: " << TI <<
'\n');
639 assert(BBExecutable.count(To) &&
"Dest should always be alive!");
642 if (!BBExecutable.count(From))
return false;
646 if (
auto *BI = dyn_cast<BranchInst>(TI)) {
647 if (BI->isUnconditional())
650 LatticeVal BCValue = getValueState(BI->getCondition());
656 return !BCValue.isUnknown();
659 return BI->getSuccessor(CI->isZero()) == To;
666 if (
auto *
SI = dyn_cast<SwitchInst>(TI)) {
667 if (
SI->getNumCases() < 1)
670 LatticeVal SCValue = getValueState(
SI->getCondition());
674 return !SCValue.isUnknown();
676 return SI->findCaseValue(CI)->getCaseSuccessor() == To;
681 if (
auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
682 LatticeVal IBRValue = getValueState(IBR->getAddress());
686 return !IBRValue.isUnknown();
689 return Addr->getBasicBlock() == To;
692 DEBUG(
dbgs() <<
"Unknown terminator instruction: " << *TI <<
'\n');
714 void SCCPSolver::visitPHINode(
PHINode &PN) {
718 return markOverdefined(&PN);
720 if (getValueState(&PN).isOverdefined())
726 return markOverdefined(&PN);
737 if (IV.isUnknown())
continue;
742 if (IV.isOverdefined())
743 return markOverdefined(&PN);
746 OperandVal = IV.getConstant();
756 if (IV.getConstant() != OperandVal)
757 return markOverdefined(&PN);
766 markConstant(&PN, OperandVal);
769 void SCCPSolver::visitReturnInst(
ReturnInst &I) {
778 TrackedRetVals.
find(F);
779 if (TFRVI != TrackedRetVals.
end()) {
780 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
786 if (!TrackedMultipleRetVals.empty()) {
787 if (
auto *STy = dyn_cast<StructType>(ResultOp->
getType()))
788 if (MRVFunctionsTracked.count(F))
790 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)],
F,
791 getStructValueState(ResultOp, i));
798 getFeasibleSuccessors(TI, SuccFeasible);
803 for (
unsigned i = 0, e = SuccFeasible.
size(); i != e; ++i)
808 void SCCPSolver::visitCastInst(
CastInst &I) {
809 LatticeVal OpSt = getValueState(I.
getOperand(0));
810 if (OpSt.isOverdefined())
812 else if (OpSt.isConstant()) {
816 if (isa<UndefValue>(C))
828 return markOverdefined(&EVI);
832 return markOverdefined(&EVI);
837 LatticeVal EltVal = getStructValueState(AggVal, i);
838 mergeInValue(getValueState(&EVI), &EVI, EltVal);
841 return markOverdefined(&EVI);
848 return markOverdefined(&IVI);
853 return markOverdefined(&IVI);
862 LatticeVal EltVal = getStructValueState(Aggr, i);
863 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
870 markOverdefined(getStructValueState(&IVI, i), &IVI);
872 LatticeVal InVal = getValueState(Val);
873 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
878 void SCCPSolver::visitSelectInst(
SelectInst &I) {
882 return markOverdefined(&I);
885 if (CondValue.isUnknown())
888 if (
ConstantInt *CondCB = CondValue.getConstantInt()) {
890 mergeInValue(&I, getValueState(OpVal));
901 if (TVal.isConstant() && FVal.isConstant() &&
902 TVal.getConstant() == FVal.getConstant())
903 return markConstant(&I, FVal.getConstant());
905 if (TVal.isUnknown())
906 return mergeInValue(&I, FVal);
907 if (FVal.isUnknown())
908 return mergeInValue(&I, TVal);
913 void SCCPSolver::visitBinaryOperator(
Instruction &I) {
914 LatticeVal V1State = getValueState(I.
getOperand(0));
915 LatticeVal V2State = getValueState(I.
getOperand(1));
917 LatticeVal &IV = ValueState[&
I];
918 if (IV.isOverdefined())
return;
920 if (V1State.isConstant() && V2State.isConstant()) {
922 V2State.getConstant());
924 if (isa<UndefValue>(C))
926 return markConstant(IV, &I, C);
930 if (!V1State.isOverdefined() && !V2State.isOverdefined())
938 if (V1State.isConstant() && V1State.getConstant()->isNullValue())
939 return markConstant(IV, &I, V1State.getConstant());
947 LatticeVal *NonOverdefVal =
nullptr;
948 if (!V1State.isOverdefined())
949 NonOverdefVal = &V1State;
950 else if (!V2State.isOverdefined())
951 NonOverdefVal = &V2State;
954 if (NonOverdefVal->isUnknown())
961 if (NonOverdefVal->getConstant()->isNullValue())
962 return markConstant(IV, &I, NonOverdefVal->getConstant());
965 if (
ConstantInt *CI = NonOverdefVal->getConstantInt())
966 if (CI->isMinusOne())
967 return markConstant(IV, &I, NonOverdefVal->getConstant());
977 void SCCPSolver::visitCmpInst(
CmpInst &I) {
978 LatticeVal V1State = getValueState(I.
getOperand(0));
979 LatticeVal V2State = getValueState(I.
getOperand(1));
981 LatticeVal &IV = ValueState[&
I];
982 if (IV.isOverdefined())
return;
984 if (V1State.isConstant() && V2State.isConstant()) {
986 I.
getPredicate(), V1State.getConstant(), V2State.getConstant());
987 if (isa<UndefValue>(C))
989 return markConstant(IV, &I, C);
993 if (!V1State.isOverdefined() && !V2State.isOverdefined())
1003 if (ValueState[&I].isOverdefined())
return;
1009 LatticeVal State = getValueState(I.
getOperand(i));
1010 if (State.isUnknown())
1013 if (State.isOverdefined())
1014 return markOverdefined(&I);
1016 assert(State.isConstant() &&
"Unknown state!");
1017 Operands.
push_back(State.getConstant());
1024 if (isa<UndefValue>(C))
1026 markConstant(&I, C);
1034 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.
getOperand(1)))
1039 if (I == TrackedGlobals.end() || I->second.isOverdefined())
return;
1042 mergeInValue(I->second, GV, getValueState(SI.
getOperand(0)));
1043 if (I->second.isOverdefined())
1044 TrackedGlobals.erase(I);
1050 void SCCPSolver::visitLoadInst(
LoadInst &I) {
1053 return markOverdefined(&I);
1055 LatticeVal PtrVal = getValueState(I.
getOperand(0));
1056 if (PtrVal.isUnknown())
return;
1058 LatticeVal &IV = ValueState[&
I];
1059 if (IV.isOverdefined())
return;
1062 return markOverdefined(IV, &I);
1064 Constant *Ptr = PtrVal.getConstant();
1071 if (
auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1072 if (!TrackedGlobals.empty()) {
1075 TrackedGlobals.
find(GV);
1076 if (It != TrackedGlobals.
end()) {
1077 mergeInValue(IV, &I, It->second);
1085 if (isa<UndefValue>(C))
1087 return markConstant(IV, &I, C);
1092 markOverdefined(IV, &I);
1095 void SCCPSolver::visitCallSite(
CallSite CS) {
1115 LatticeVal State = getValueState(*AI);
1117 if (State.isUnknown())
1119 if (State.isOverdefined())
1120 return markOverdefined(I);
1121 assert(State.isConstant() &&
"Unknown state!");
1122 Operands.
push_back(State.getConstant());
1125 if (getValueState(I).isOverdefined())
1132 if (isa<UndefValue>(C))
1134 return markConstant(I, C);
1139 return markOverdefined(I);
1145 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1146 MarkBlockExecutable(&F->
front());
1151 AI !=
E; ++AI, ++CAI) {
1155 markOverdefined(&*AI);
1159 if (
auto *STy = dyn_cast<StructType>(AI->getType())) {
1161 LatticeVal
CallArg = getStructValueState(*CAI, i);
1162 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
1165 mergeInValue(&*AI, getValueState(*CAI));
1172 if (!MRVFunctionsTracked.count(F))
1173 goto CallOverdefined;
1178 mergeInValue(getStructValueState(I, i),
I,
1179 TrackedMultipleRetVals[std::make_pair(F, i)]);
1182 if (TFRVI == TrackedRetVals.
end())
1183 goto CallOverdefined;
1186 mergeInValue(I, TFRVI->second);
1190 void SCCPSolver::Solve() {
1192 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1193 !OverdefinedInstWorkList.empty()) {
1196 while (!OverdefinedInstWorkList.empty()) {
1197 Value *I = OverdefinedInstWorkList.pop_back_val();
1199 DEBUG(
dbgs() <<
"\nPopped off OI-WL: " << *I <<
'\n');
1209 if (
auto *UI = dyn_cast<Instruction>(U))
1210 OperandChangedState(UI);
1214 while (!InstWorkList.empty()) {
1215 Value *I = InstWorkList.pop_back_val();
1217 DEBUG(
dbgs() <<
"\nPopped off I-WL: " << *I <<
'\n');
1228 if (
auto *UI = dyn_cast<Instruction>(U))
1229 OperandChangedState(UI);
1233 while (!BBWorkList.empty()) {
1235 BBWorkList.pop_back();
1237 DEBUG(
dbgs() <<
"\nPopped off BBWL: " << *BB <<
'\n');
1264 bool SCCPSolver::ResolvedUndefsIn(
Function &F) {
1266 if (!BBExecutable.count(&BB))
1273 if (
auto *STy = dyn_cast<StructType>(I.
getType())) {
1279 if (MRVFunctionsTracked.count(F))
1284 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(
I))
1290 LatticeVal &LV = getStructValueState(&I, i);
1292 markOverdefined(LV, &I);
1297 LatticeVal &LV = getValueState(&I);
1298 if (!LV.isUnknown())
continue;
1301 if (isa<ExtractValueInst>(I))
1308 markOverdefined(&I);
1311 LatticeVal Op0LV = getValueState(I.getOperand(0));
1313 if (I.getNumOperands() == 2) {
1315 markOverdefined(&I);
1319 Op1LV = getValueState(I.getOperand(1));
1324 switch (I.getOpcode()) {
1326 case Instruction::Sub:
1327 case Instruction::Trunc:
1328 case Instruction::FPTrunc:
1329 case Instruction::BitCast:
1331 case Instruction::FSub:
1332 case Instruction::FAdd:
1333 case Instruction::FMul:
1334 case Instruction::FDiv:
1335 case Instruction::FRem:
1337 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1340 markOverdefined(&I);
1342 case Instruction::ZExt:
1343 case Instruction::SExt:
1344 case Instruction::FPToUI:
1345 case Instruction::FPToSI:
1346 case Instruction::FPExt:
1347 case Instruction::PtrToInt:
1348 case Instruction::IntToPtr:
1349 case Instruction::SIToFP:
1350 case Instruction::UIToFP:
1354 case Instruction::Mul:
1355 case Instruction::And:
1357 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1364 case Instruction::Or:
1366 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1372 case Instruction::Xor:
1376 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
1383 case Instruction::SDiv:
1384 case Instruction::UDiv:
1385 case Instruction::SRem:
1386 case Instruction::URem:
1389 if (Op1LV.isUnknown())
break;
1393 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1401 case Instruction::AShr:
1403 if (Op1LV.isUnknown())
break;
1406 if (Op1LV.isConstant()) {
1407 if (
auto *ShiftAmt = Op1LV.getConstantInt())
1408 if (ShiftAmt->getLimitedValue() >=
1409 ShiftAmt->getType()->getScalarSizeInBits())
1416 case Instruction::LShr:
1417 case Instruction::Shl:
1420 if (Op1LV.isUnknown())
break;
1423 if (Op1LV.isConstant()) {
1424 if (
auto *ShiftAmt = Op1LV.getConstantInt())
1425 if (ShiftAmt->getLimitedValue() >=
1426 ShiftAmt->getType()->getScalarSizeInBits())
1435 Op1LV = getValueState(I.getOperand(1));
1437 if (Op0LV.isUnknown()) {
1438 if (!Op1LV.isConstant())
1439 Op1LV = getValueState(I.getOperand(2));
1440 }
else if (Op1LV.isUnknown()) {
1442 Op1LV = getValueState(I.getOperand(2));
1443 if (Op1LV.isUnknown())
1450 if (Op1LV.isConstant())
1451 markForcedConstant(&I, Op1LV.getConstant());
1453 markOverdefined(&I);
1460 case Instruction::ICmp:
1462 if (cast<ICmpInst>(&I)->isEquality())
1464 markOverdefined(&I);
1467 case Instruction::Invoke: {
1474 if (TrackedRetVals.count(F))
1479 markOverdefined(&I);
1485 markOverdefined(&I);
1494 if (
auto *BI = dyn_cast<BranchInst>(TI)) {
1495 if (!BI->isConditional())
continue;
1496 if (!getValueState(BI->getCondition()).isUnknown())
1501 if (isa<UndefValue>(BI->getCondition())) {
1510 markForcedConstant(BI->getCondition(),
1515 if (
auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1518 if (IBR->getNumSuccessors() < 1)
1521 if (!getValueState(IBR->getAddress()).isUnknown())
1526 if (isa<UndefValue>(IBR->getAddress())) {
1528 markEdgeExecutable(&BB, IBR->getSuccessor(0));
1535 markForcedConstant(IBR->getAddress(),
1540 if (
auto *SI = dyn_cast<SwitchInst>(TI)) {
1541 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
1546 if (isa<UndefValue>(SI->getCondition())) {
1547 SI->setCondition(SI->case_begin()->getCaseValue());
1548 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
1552 markForcedConstant(SI->getCondition(), SI->case_begin()->getCaseValue());
1563 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
1564 if (
any_of(IVs, [](
const LatticeVal &LV) {
return LV.isOverdefined(); }))
1566 std::vector<Constant *> ConstVals;
1568 for (
unsigned i = 0, e =
ST->getNumElements(); i != e; ++i) {
1569 LatticeVal V = IVs[i];
1570 ConstVals.push_back(V.isConstant()
1576 LatticeVal IV = Solver.getLatticeValueFor(V);
1577 if (IV.isOverdefined())
1581 assert(Const &&
"Constant is nullptr here!");
1582 DEBUG(
dbgs() <<
" Constant: " << *Const <<
" = " << *V <<
'\n');
1595 SCCPSolver Solver(DL, TLI);
1598 Solver.MarkBlockExecutable(&F.
front());
1602 Solver.markOverdefined(&AI);
1605 bool ResolvedUndefs =
true;
1606 while (ResolvedUndefs) {
1609 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1612 bool MadeChanges =
false;
1619 if (!Solver.isBlockExecutable(&BB)) {
1620 DEBUG(
dbgs() <<
" BasicBlock Dead:" << BB);
1681 bool runOnFunction(
Function &F)
override {
1682 if (skipFunction(F))
1686 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1694 "Sparse Conditional Constant Propagation",
false,
false)
1706 for (
const Use &U : GV->
uses()) {
1707 const User *UR = U.getUser();
1708 if (
const auto *SI = dyn_cast<StoreInst>(UR)) {
1711 }
else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
1716 }
else if (
const auto *LI = dyn_cast<LoadInst>(UR)) {
1717 if (LI->isVolatile())
1719 }
else if (isa<BlockAddress>(UR)) {
1737 if (
auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1738 if (!isa<UndefValue>(RI->getOperand(0)))
1744 SCCPSolver Solver(DL, TLI);
1766 Solver.AddTrackedFunction(&F);
1773 AddressTakenFunctions.
insert(&F);
1776 Solver.AddArgumentTrackedFunction(&F);
1782 Solver.MarkBlockExecutable(&F.
front());
1786 Solver.markOverdefined(&AI);
1793 if (!
G.isConstant() &&
G.hasLocalLinkage() &&
1795 Solver.TrackValueOfGlobalVariable(&
G);
1798 bool ResolvedUndefs =
true;
1799 while (ResolvedUndefs) {
1803 ResolvedUndefs =
false;
1805 ResolvedUndefs |= Solver.ResolvedUndefsIn(F);
1808 bool MadeChanges =
false;
1819 if (Solver.isBlockExecutable(&F.
front()))
1826 if (!Solver.isBlockExecutable(&*BB)) {
1827 DEBUG(
dbgs() <<
" BasicBlock Dead:" << *BB);
1835 if (&*BB != &F.
front())
1845 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1857 for (
unsigned i = 0, e = BlocksToErase.
size(); i != e; ++i) {
1866 do { ++UI; }
while (UI != UE && *UI == I);
1873 "Expect TermInst on constantint or blockaddress to be folded");
1880 BlocksToErase.
clear();
1896 for (
const auto &I : RV) {
1903 for (
const auto &F : Solver.getMRVFunctionsTracked()) {
1905 "The return type should be a struct");
1907 if (Solver.isStructLatticeConstant(F, STy))
1912 for (
unsigned i = 0, e = ReturnsToZap.
size(); i != e; ++i) {
1913 Function *F = ReturnsToZap[i]->getParent()->getParent();
1921 E = TG.
end(); I !=
E; ++
I) {
1923 assert(!I->second.isOverdefined() &&
1924 "Overdefined values should have been taken out of the map!");
1930 M.getGlobalList().
erase(GV);
1959 bool runOnModule(
Module &M)
override {
1964 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1976 "Interprocedural Sparse Conditional Constant Propagation",
Legacy wrapper pass to provide the GlobalsAAResult object.
Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
Return a value (possibly void), from a function.
User::op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
This class is the base class for the comparison instructions.
INITIALIZE_PASS_BEGIN(SCCPLegacyPass,"sccp","Sparse Conditional Constant Propagation", false, false) INITIALIZE_PASS_END(SCCPLegacyPass
iterator_range< use_iterator > uses()
static bool isConstant(const MachineInstr &MI)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static bool runIPSCCP(Module &M, const DataLayout &DL, const TargetLibraryInfo *TLI)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
Base class for instruction visitors.
Value * getAggregateOperand()
const Instruction & back() const
Type * getSourceElementType() const
STATISTIC(NumFunctions,"Total number of functions")
iterator erase(iterator where)
bool isVolatile() const
Return true if this is a store to a volatile memory location.
This is the interface for a simple mod/ref and alias analysis over globals.
bool onlyReadsMemory() const
Determine if the function does not access or only reads memory.
A Module instance is used to store all the information related to an LLVM module. ...
An instruction for ordering other memory operations.
static bool AddressIsTaken(const GlobalValue *GV)
Implements a dense probed hash-table based set.
unsigned getNumOperands() const
Type * getValueType() const
This class represents a function call, abstracting a target machine's calling convention.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
ModulePass * createIPSCCPPass()
createIPSCCPPass - This pass propagates constants from call sites into the bodies of functions...
bool hasExactDefinition() const
Return true if this global has an exact defintion.
unsigned getNumIndices() const
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
An instruction for reading from memory.
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
static bool runSCCP(Function &F, const DataLayout &DL, const TargetLibraryInfo *TLI)
void reserve(size_type N)
unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap, bool PreserveLCSSA=false)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Constant * ConstantFoldCall(ImmutableCallSite CS, Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
The address of a basic block.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
This class represents the LLVM 'select' instruction.
This is the base class for all instructions that perform data casts.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
void initializeSCCPLegacyPassPass(PassRegistry &)
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
FunctionPass * createSCCPPass()
void assign(size_type NumElts, const T &Elt)
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible. ...
Value * getInsertedValueOperand()
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
iterator find(const_arg_type_t< KeyT > Val)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Type * getReturnType() const
Returns the type of the ret val.
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
LLVM Basic Block Representation.
PointerIntPair - This class implements a pair of a pointer and small integer.
The instances of the Type class are immutable: once they are created, they are never changed...
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
This is an important base class in LLVM.
const Value * getCondition() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Analysis pass providing a never-invalidated alias analysis result.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
Predicate getPredicate() const
Return the predicate for this instruction.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, const DataLayout &DL)
ConstantFoldLoadFromConstPtr - Return the value that a load from C would produce if it is constant an...
static Constant * getAllOnesValue(Type *Ty)
Get the all ones value.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
LLVMContext & getContext() const
All values hold a context through their type.
const Value * getTrueValue() const
Sparse Conditional Constant Propagation
idx_iterator idx_begin() const
Iterator for intrusive lists based on ilist_node.
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V)
Sparse Conditional Constant false
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
InstrTy * getInstruction() const
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
Provides information about what library functions are available for the current target.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than it's terminator and any present EH pad instruct...
static const Function * getCalledFunction(const Value *V, bool LookThroughBitCast, bool &IsNoBuiltin)
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
static void findReturnsToZap(Function &F, SmallPtrSet< Function *, 32 > &AddressTakenFunctions, SmallVector< ReturnInst *, 8 > &ReturnsToZap)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
iterator_range< user_iterator > users()
llvm_unreachable("Unknown RegBank!")
bool isStructTy() const
True if this is an instance of StructType.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
void initializeIPSCCPLegacyPassPass(PassRegistry &)
Establish a view to a call site for examination.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
user_iterator_impl< User > user_iterator
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
bool hasLocalLinkage() const
Analysis pass providing the TargetLibraryInfo.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
const BasicBlock & front() const
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool canConstantFoldCallTo(ImmutableCallSite CS, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function...
bool isExceptional() const
const Value * getFalseValue() const
A container for analyses that lazily runs them and caches their results.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
unsigned getNumElements() const
Random access to the elements.
const BasicBlock * getParent() const
iterator_range< arg_iterator > args()
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
bool isVoidTy() const
Return true if this is 'void'.
This instruction inserts a struct field of array element value into an aggregate value.