66 #define DEBUG_TYPE "sccp" 68 STATISTIC(NumInstRemoved,
"Number of instructions removed");
69 STATISTIC(NumDeadBlocks ,
"Number of basic blocks unreachable");
71 STATISTIC(IPNumInstRemoved,
"Number of instructions removed by IPSCCP");
72 STATISTIC(IPNumArgsElimed ,
"Number of arguments constant propagated by IPSCCP");
73 STATISTIC(IPNumGlobalConst,
"Number of globals found to be constant by IPSCCP");
103 LatticeValueTy getLatticeValue()
const {
108 LatticeVal() : Val(nullptr, unknown) {}
110 bool isUnknown()
const {
return getLatticeValue() == unknown; }
113 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
116 bool isOverdefined()
const {
return getLatticeValue() == overdefined; }
124 bool markOverdefined() {
134 if (getLatticeValue() == constant) {
135 assert(getConstant() == V &&
"Marking constant with different value");
141 assert(V &&
"Marking constant with NULL");
144 assert(getLatticeValue() == forcedconstant &&
145 "Cannot move from overdefined to constant!");
147 if (V == getConstant())
return false;
173 void markForcedConstant(
Constant *V) {
174 assert(isUnknown() &&
"Can't force a defined value!");
175 Val.
setInt(forcedconstant);
193 class SCCPSolver :
public InstVisitor<SCCPSolver> {
195 std::function<const TargetLibraryInfo &(Function &)> GetTLI;
248 using Edge = std::pair<BasicBlock *, BasicBlock *>;
256 AnalysisResults.
insert({&
F, std::move(A)});
261 if (A == AnalysisResults.
end())
263 return A->second.
PredInfo->getPredicateInfoFor(I);
267 auto A = AnalysisResults.
find(&F);
268 assert(A != AnalysisResults.
end() &&
"Need analysis results for function.");
274 : DL(DL), GetTLI(
std::move(GetTLI)) {}
281 if (!BBExecutable.
insert(BB).second)
295 LatticeVal &IV = TrackedGlobals[GV];
304 void AddTrackedFunction(
Function *F) {
307 MRVFunctionsTracked.
insert(F);
308 for (
unsigned i = 0,
e = STy->getNumElements(); i !=
e; ++i)
309 TrackedMultipleRetVals.
insert(std::make_pair(std::make_pair(F, i),
312 TrackedRetVals.
insert(std::make_pair(F, LatticeVal()));
317 void AddMustTailCallee(
Function *F) {
318 MustTailCallees.
insert(F);
323 bool isMustTailCallee(
Function *F) {
324 return MustTailCallees.
count(F);
327 void AddArgumentTrackedFunction(
Function *F) {
328 TrackingIncomingArguments.
insert(F);
333 bool isArgumentTrackedFunction(
Function *F) {
334 return TrackingIncomingArguments.
count(F);
347 bool isBlockExecutable(
BasicBlock *BB)
const {
348 return BBExecutable.
count(BB);
355 std::vector<LatticeVal> getStructLatticeValueFor(
Value *V)
const {
356 std::vector<LatticeVal> StructValues;
358 assert(STy &&
"getStructLatticeValueFor() can be called only on structs");
359 for (
unsigned i = 0,
e = STy->getNumElements(); i !=
e; ++i) {
360 auto I = StructValueState.
find(std::make_pair(V, i));
361 assert(I != StructValueState.
end() &&
"Value not in valuemap!");
362 StructValues.push_back(I->second);
367 const LatticeVal &getLatticeValueFor(
Value *V)
const {
369 "Should use getStructLatticeValueFor");
372 "V not found in ValueState nor Paramstate map!");
378 return TrackedRetVals;
384 return TrackedGlobals;
390 return MRVFunctionsTracked;
396 return MustTailCallees;
401 void markOverdefined(
Value *V) {
402 if (
auto *STy = dyn_cast<StructType>(V->
getType()))
403 for (
unsigned i = 0,
e = STy->getNumElements(); i !=
e; ++i)
404 markOverdefined(getStructValueState(V, i), V);
406 markOverdefined(ValueState[V], V);
414 const auto &It = TrackedMultipleRetVals.
find(std::make_pair(F, i));
415 assert(It != TrackedMultipleRetVals.
end());
416 LatticeVal LV = It->second;
417 if (LV.isOverdefined())
425 void pushToWorkList(LatticeVal &IV,
Value *V) {
426 if (IV.isOverdefined())
427 return OverdefinedInstWorkList.
push_back(V);
435 if (!IV.markConstant(C))
return false;
436 LLVM_DEBUG(
dbgs() <<
"markConstant: " << *C <<
": " << *V <<
'\n');
437 pushToWorkList(IV, V);
443 return markConstant(ValueState[V], V, C);
448 LatticeVal &IV = ValueState[V];
449 IV.markForcedConstant(C);
450 LLVM_DEBUG(
dbgs() <<
"markForcedConstant: " << *C <<
": " << *V <<
'\n');
451 pushToWorkList(IV, V);
457 bool markOverdefined(LatticeVal &IV,
Value *V) {
458 if (!IV.markOverdefined())
return false;
461 if (
auto *F = dyn_cast<Function>(V))
dbgs()
462 <<
"Function '" << F->
getName() <<
"'\n";
463 else dbgs() << *V <<
'\n');
465 pushToWorkList(IV, V);
469 bool mergeInValue(LatticeVal &IV,
Value *V, LatticeVal MergeWithV) {
470 if (IV.isOverdefined() || MergeWithV.isUnknown())
472 if (MergeWithV.isOverdefined())
473 return markOverdefined(IV, V);
475 return markConstant(IV, V, MergeWithV.getConstant());
476 if (IV.getConstant() != MergeWithV.getConstant())
477 return markOverdefined(IV, V);
481 bool mergeInValue(
Value *V, LatticeVal MergeWithV) {
483 "non-structs should use markConstant");
484 return mergeInValue(ValueState[V], V, MergeWithV);
490 LatticeVal &getValueState(
Value *V) {
493 std::pair<DenseMap<Value*, LatticeVal>::iterator,
bool> I =
494 ValueState.
insert(std::make_pair(V, LatticeVal()));
495 LatticeVal &LV = I.first->second;
500 if (
auto *C = dyn_cast<Constant>(V)) {
502 if (!isa<UndefValue>(V))
513 std::pair<DenseMap<Value*, ValueLatticeElement>::iterator,
bool>
517 LV = getValueState(V).toValueLattice();
525 LatticeVal &getStructValueState(
Value *V,
unsigned i) {
527 assert(i < cast<StructType>(V->
getType())->getNumElements() &&
528 "Invalid element #");
530 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
531 bool> I = StructValueState.
insert(
532 std::make_pair(std::make_pair(V, i), LatticeVal()));
533 LatticeVal &LV = I.first->second;
538 if (
auto *C = dyn_cast<Constant>(V)) {
542 LV.markOverdefined();
543 else if (isa<UndefValue>(Elt))
546 LV.markConstant(Elt);
556 if (!KnownFeasibleEdges.
insert(Edge(Source, Dest)).second)
559 if (!MarkBlockExecutable(Dest)) {
564 <<
" -> " << Dest->
getName() <<
'\n');
585 void addAdditionalUser(
Value *V,
User *U) {
586 auto Iter = AdditionalUsers.
insert({V, {}});
587 Iter.first->second.insert(U);
591 void markUsersAsChanged(
Value *I) {
593 if (
auto *UI = dyn_cast<Instruction>(U))
594 OperandChangedState(UI);
596 auto Iter = AdditionalUsers.
find(I);
597 if (Iter != AdditionalUsers.
end()) {
598 for (
User *U : Iter->second)
599 if (
auto *UI = dyn_cast<Instruction>(U))
600 OperandChangedState(UI);
626 markOverdefined(&CPI);
627 visitTerminator(CPI);
647 visitTerminator(CBI);
658 LLVM_DEBUG(
dbgs() <<
"SCCP: Don't know how to handle: " << I <<
'\n');
667 void SCCPSolver::getFeasibleSuccessors(
Instruction &TI,
670 if (
auto *BI = dyn_cast<BranchInst>(&TI)) {
671 if (BI->isUnconditional()) {
676 LatticeVal BCValue = getValueState(BI->getCondition());
681 if (!BCValue.isUnknown())
682 Succs[0] = Succs[1] =
true;
687 Succs[CI->isZero()] =
true;
697 if (
auto *
SI = dyn_cast<SwitchInst>(&TI)) {
698 if (!
SI->getNumCases()) {
702 LatticeVal SCValue = getValueState(
SI->getCondition());
707 if (!SCValue.isUnknown())
712 Succs[
SI->findCaseValue(CI)->getSuccessorIndex()] =
true;
718 if (
auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
720 LatticeVal IBRValue = getValueState(IBR->getAddress());
724 if (!IBRValue.isUnknown())
731 "Block address of a different function ?");
732 for (
unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
734 if (IBR->getDestination(i) ==
T) {
747 if (isa<CallBrInst>(&TI)) {
752 LLVM_DEBUG(
dbgs() <<
"Unknown terminator instruction: " << TI <<
'\n');
762 return KnownFeasibleEdges.
count(Edge(From, To));
782 void SCCPSolver::visitPHINode(
PHINode &PN) {
786 return (
void)markOverdefined(&PN);
788 if (getValueState(&PN).isOverdefined())
794 return (
void)markOverdefined(&PN);
804 if (IV.isUnknown())
continue;
809 if (IV.isOverdefined())
810 return (
void)markOverdefined(&PN);
813 OperandVal = IV.getConstant();
823 if (IV.getConstant() != OperandVal)
824 return (
void)markOverdefined(&PN);
832 markConstant(&PN, OperandVal);
835 void SCCPSolver::visitReturnInst(
ReturnInst &I) {
844 TrackedRetVals.
find(F);
845 if (TFRVI != TrackedRetVals.
end()) {
846 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
852 if (!TrackedMultipleRetVals.
empty()) {
853 if (
auto *STy = dyn_cast<StructType>(ResultOp->
getType()))
854 if (MRVFunctionsTracked.
count(F))
856 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)],
F,
857 getStructValueState(ResultOp, i));
861 void SCCPSolver::visitTerminator(
Instruction &TI) {
863 getFeasibleSuccessors(TI, SuccFeasible);
868 for (
unsigned i = 0,
e = SuccFeasible.
size(); i !=
e; ++i)
873 void SCCPSolver::visitCastInst(
CastInst &I) {
874 LatticeVal OpSt = getValueState(I.
getOperand(0));
875 if (OpSt.isOverdefined())
877 else if (OpSt.isConstant()) {
881 if (isa<UndefValue>(C))
892 return (
void)markOverdefined(&EVI);
896 return (
void)markOverdefined(&EVI);
901 LatticeVal EltVal = getStructValueState(AggVal, i);
902 mergeInValue(getValueState(&EVI), &EVI, EltVal);
905 return (
void)markOverdefined(&EVI);
912 return (
void)markOverdefined(&IVI);
917 return (
void)markOverdefined(&IVI);
926 LatticeVal EltVal = getStructValueState(Aggr, i);
927 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
934 markOverdefined(getStructValueState(&IVI, i), &IVI);
936 LatticeVal InVal = getValueState(Val);
937 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
942 void SCCPSolver::visitSelectInst(
SelectInst &I) {
946 return (
void)markOverdefined(&I);
949 if (CondValue.isUnknown())
952 if (
ConstantInt *CondCB = CondValue.getConstantInt()) {
954 mergeInValue(&I, getValueState(OpVal));
965 if (TVal.isConstant() && FVal.isConstant() &&
966 TVal.getConstant() == FVal.getConstant())
967 return (
void)markConstant(&I, FVal.getConstant());
969 if (TVal.isUnknown())
970 return (
void)mergeInValue(&I, FVal);
971 if (FVal.isUnknown())
972 return (
void)mergeInValue(&I, TVal);
977 void SCCPSolver::visitUnaryOperator(
Instruction &I) {
978 LatticeVal V0State = getValueState(I.
getOperand(0));
980 LatticeVal &IV = ValueState[&
I];
981 if (IV.isOverdefined())
return;
983 if (V0State.isConstant()) {
987 if (isa<UndefValue>(C))
989 return (
void)markConstant(IV, &I, C);
993 if (!V0State.isOverdefined())
1000 void SCCPSolver::visitBinaryOperator(
Instruction &I) {
1001 LatticeVal V1State = getValueState(I.
getOperand(0));
1002 LatticeVal V2State = getValueState(I.
getOperand(1));
1004 LatticeVal &IV = ValueState[&
I];
1005 if (IV.isOverdefined())
return;
1007 if (V1State.isConstant() && V2State.isConstant()) {
1009 V2State.getConstant());
1011 if (isa<UndefValue>(C))
1013 return (
void)markConstant(IV, &I, C);
1017 if (!V1State.isOverdefined() && !V2State.isOverdefined())
1025 if (V1State.isConstant() && V1State.getConstant()->isNullValue())
1026 return (
void)markConstant(IV, &I, V1State.getConstant());
1034 LatticeVal *NonOverdefVal =
nullptr;
1035 if (!V1State.isOverdefined())
1036 NonOverdefVal = &V1State;
1037 else if (!V2State.isOverdefined())
1038 NonOverdefVal = &V2State;
1040 if (NonOverdefVal) {
1041 if (NonOverdefVal->isUnknown())
1044 if (I.
getOpcode() == Instruction::And ||
1048 if (NonOverdefVal->getConstant()->isNullValue())
1049 return (
void)markConstant(IV, &I, NonOverdefVal->getConstant());
1052 if (
ConstantInt *CI = NonOverdefVal->getConstantInt())
1053 if (CI->isMinusOne())
1054 return (
void)markConstant(IV, &I, NonOverdefVal->getConstant());
1059 markOverdefined(&I);
1063 void SCCPSolver::visitCmpInst(
CmpInst &I) {
1066 if (ValueState[&I].isOverdefined())
return;
1073 auto V1Param = ParamState.
find(Op1);
1076 : getValueState(Op1).toValueLattice();
1078 auto V2Param = ParamState.
find(Op2);
1081 : getValueState(Op2).toValueLattice();
1085 if (isa<UndefValue>(C))
1089 mergeInValue(&I, CV);
1095 !ValueState[&
I].isConstant())
1098 markOverdefined(&I);
1104 if (ValueState[&I].isOverdefined())
return;
1110 LatticeVal State = getValueState(I.
getOperand(i));
1111 if (State.isUnknown())
1114 if (State.isOverdefined())
1115 return (
void)markOverdefined(&I);
1117 assert(State.isConstant() &&
"Unknown state!");
1118 Operands.
push_back(State.getConstant());
1125 if (isa<UndefValue>(C))
1127 markConstant(&I, C);
1140 if (I == TrackedGlobals.
end() || I->second.isOverdefined())
return;
1143 mergeInValue(I->second, GV, getValueState(SI.
getOperand(0)));
1144 if (I->second.isOverdefined())
1145 TrackedGlobals.
erase(I);
1150 void SCCPSolver::visitLoadInst(
LoadInst &I) {
1153 return (
void)markOverdefined(&I);
1155 LatticeVal PtrVal = getValueState(I.
getOperand(0));
1156 if (PtrVal.isUnknown())
return;
1158 LatticeVal &IV = ValueState[&
I];
1159 if (IV.isOverdefined())
return;
1162 return (
void)markOverdefined(IV, &I);
1164 Constant *Ptr = PtrVal.getConstant();
1167 if (isa<ConstantPointerNull>(Ptr)) {
1169 return (
void)markOverdefined(IV, &I);
1175 if (
auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1176 if (!TrackedGlobals.
empty()) {
1179 TrackedGlobals.
find(GV);
1180 if (It != TrackedGlobals.
end()) {
1181 mergeInValue(IV, &I, It->second);
1189 if (isa<UndefValue>(C))
1191 return (
void)markConstant(IV, &I, C);
1196 markOverdefined(IV, &I);
1199 void SCCPSolver::visitCallSite(
CallSite CS) {
1203 if (
auto *II = dyn_cast<IntrinsicInst>(I)) {
1204 if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
1205 if (ValueState[I].isOverdefined())
1208 auto *PI = getPredicateInfoFor(I);
1215 mergeInValue(ValueState[I], I, getValueState(CopyOf));
1219 Value *Cond = PBranch->Condition;
1224 mergeInValue(ValueState[I], I, getValueState(CopyOf));
1228 Value *CmpOp0 = Cmp->getOperand(0);
1229 Value *CmpOp1 = Cmp->getOperand(1);
1230 if (CopyOf != CmpOp0 && CopyOf != CmpOp1) {
1231 mergeInValue(ValueState[I], I, getValueState(CopyOf));
1235 if (CmpOp0 != CopyOf)
1238 LatticeVal OriginalVal = getValueState(CopyOf);
1239 LatticeVal EqVal = getValueState(CmpOp1);
1240 LatticeVal &IV = ValueState[
I];
1242 addAdditionalUser(CmpOp1, I);
1243 if (OriginalVal.isConstant())
1244 mergeInValue(IV, I, OriginalVal);
1246 mergeInValue(IV, I, EqVal);
1250 addAdditionalUser(CmpOp1, I);
1251 if (OriginalVal.isConstant())
1252 mergeInValue(IV, I, OriginalVal);
1254 mergeInValue(IV, I, EqVal);
1258 return (
void)mergeInValue(IV, I, getValueState(CopyOf));
1277 if (AI->get()->getType()->isStructTy())
1278 return markOverdefined(I);
1279 LatticeVal State = getValueState(*AI);
1281 if (State.isUnknown())
1283 if (State.isOverdefined())
1284 return (
void)markOverdefined(I);
1285 assert(State.isConstant() &&
"Unknown state!");
1286 Operands.
push_back(State.getConstant());
1289 if (getValueState(I).isOverdefined())
1295 Operands, &GetTLI(*F))) {
1297 if (isa<UndefValue>(C))
1299 return (
void)markConstant(I, C);
1304 return (
void)markOverdefined(I);
1310 if (!TrackingIncomingArguments.
empty() && TrackingIncomingArguments.
count(F)){
1311 MarkBlockExecutable(&F->
front());
1316 AI !=
E; ++AI, ++CAI) {
1320 markOverdefined(&*AI);
1324 if (
auto *STy = dyn_cast<StructType>(AI->getType())) {
1326 LatticeVal
CallArg = getStructValueState(*CAI, i);
1327 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
1332 LatticeVal ConcreteArgument = getValueState(*CAI);
1334 getParamState(&*AI).mergeIn(ConcreteArgument.toValueLattice(), DL);
1335 bool ValueChanged = mergeInValue(&*AI, ConcreteArgument);
1340 if (!ValueChanged && ParamChanged)
1341 pushToWorkList(ValueState[&*AI], &*AI);
1348 if (!MRVFunctionsTracked.
count(F))
1349 goto CallOverdefined;
1354 mergeInValue(getStructValueState(I, i),
I,
1355 TrackedMultipleRetVals[std::make_pair(F, i)]);
1358 if (TFRVI == TrackedRetVals.
end())
1359 goto CallOverdefined;
1362 mergeInValue(I, TFRVI->second);
1366 void SCCPSolver::Solve() {
1368 while (!BBWorkList.
empty() || !InstWorkList.
empty() ||
1369 !OverdefinedInstWorkList.
empty()) {
1372 while (!OverdefinedInstWorkList.
empty()) {
1384 markUsersAsChanged(I);
1388 while (!InstWorkList.
empty()) {
1401 markUsersAsChanged(I);
1405 while (!BBWorkList.
empty()) {
1436 bool SCCPSolver::ResolvedUndefsIn(
Function &F) {
1438 if (!BBExecutable.
count(&BB))
1445 if (
auto *STy = dyn_cast<StructType>(I.
getType())) {
1451 if (MRVFunctionsTracked.
count(F))
1456 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(
I))
1462 LatticeVal &LV = getStructValueState(&I, i);
1464 markOverdefined(LV, &I);
1469 LatticeVal &LV = getValueState(&I);
1470 if (!LV.isUnknown())
1480 if (TrackedRetVals.
count(F))
1485 markOverdefined(&I);
1490 if (isa<ExtractValueInst>(I))
1497 markOverdefined(&I);
1500 LatticeVal Op0LV = getValueState(I.getOperand(0));
1502 if (I.getNumOperands() == 2) {
1504 markOverdefined(&I);
1508 Op1LV = getValueState(I.getOperand(1));
1513 switch (I.getOpcode()) {
1515 case Instruction::Sub:
1516 case Instruction::Trunc:
1517 case Instruction::FPTrunc:
1518 case Instruction::BitCast:
1520 case Instruction::FSub:
1521 case Instruction::FAdd:
1522 case Instruction::FMul:
1523 case Instruction::FDiv:
1524 case Instruction::FRem:
1526 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1529 markOverdefined(&I);
1531 case Instruction::FNeg:
1533 case Instruction::ZExt:
1534 case Instruction::SExt:
1535 case Instruction::FPToUI:
1536 case Instruction::FPToSI:
1537 case Instruction::FPExt:
1538 case Instruction::PtrToInt:
1539 case Instruction::IntToPtr:
1540 case Instruction::SIToFP:
1541 case Instruction::UIToFP:
1545 case Instruction::Mul:
1546 case Instruction::And:
1548 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1554 case Instruction::Or:
1556 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1561 case Instruction::Xor:
1565 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
1571 case Instruction::SDiv:
1572 case Instruction::UDiv:
1573 case Instruction::SRem:
1574 case Instruction::URem:
1577 if (Op1LV.isUnknown())
break;
1581 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1588 case Instruction::AShr:
1590 if (Op1LV.isUnknown())
break;
1593 if (Op1LV.isConstant()) {
1594 if (
auto *ShiftAmt = Op1LV.getConstantInt())
1595 if (ShiftAmt->getLimitedValue() >=
1596 ShiftAmt->getType()->getScalarSizeInBits())
1603 case Instruction::LShr:
1604 case Instruction::Shl:
1607 if (Op1LV.isUnknown())
break;
1610 if (Op1LV.isConstant()) {
1611 if (
auto *ShiftAmt = Op1LV.getConstantInt())
1612 if (ShiftAmt->getLimitedValue() >=
1613 ShiftAmt->getType()->getScalarSizeInBits())
1622 Op1LV = getValueState(I.getOperand(1));
1624 if (Op0LV.isUnknown()) {
1625 if (!Op1LV.isConstant())
1626 Op1LV = getValueState(I.getOperand(2));
1627 }
else if (Op1LV.isUnknown()) {
1629 Op1LV = getValueState(I.getOperand(2));
1630 if (Op1LV.isUnknown())
1637 if (Op1LV.isConstant())
1638 markForcedConstant(&I, Op1LV.getConstant());
1640 markOverdefined(&I);
1647 case Instruction::ICmp:
1649 Op0LV = getValueState(I.getOperand(0));
1650 Op1LV = getValueState(I.getOperand(1));
1652 if ((Op0LV.isUnknown() || Op1LV.isUnknown()) &&
1653 cast<ICmpInst>(&I)->isEquality())
1655 markOverdefined(&I);
1658 case Instruction::Invoke:
1659 case Instruction::CallBr:
1664 markOverdefined(&I);
1673 if (
auto *BI = dyn_cast<BranchInst>(TI)) {
1674 if (!BI->isConditional())
continue;
1675 if (!getValueState(BI->getCondition()).isUnknown())
1680 if (isa<UndefValue>(BI->getCondition())) {
1691 if (markEdgeExecutable(&BB, DefaultSuccessor))
1697 if (
auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1700 if (IBR->getNumSuccessors() < 1)
1703 if (!getValueState(IBR->getAddress()).isUnknown())
1708 if (isa<UndefValue>(IBR->getAddress())) {
1710 markEdgeExecutable(&BB, IBR->getSuccessor(0));
1719 BasicBlock *DefaultSuccessor = IBR->getSuccessor(0);
1720 if (markEdgeExecutable(&BB, DefaultSuccessor))
1726 if (
auto *SI = dyn_cast<SwitchInst>(TI)) {
1727 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
1732 if (isa<UndefValue>(SI->getCondition())) {
1733 SI->setCondition(SI->case_begin()->getCaseValue());
1734 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
1742 BasicBlock *DefaultSuccessor = SI->case_begin()->getCaseSuccessor();
1743 if (markEdgeExecutable(&BB, DefaultSuccessor))
1756 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
1758 [](
const LatticeVal &LV) {
return LV.isOverdefined(); }))
1760 std::vector<Constant *> ConstVals;
1761 auto *
ST = cast<StructType>(V->
getType());
1762 for (
unsigned i = 0,
e =
ST->getNumElements(); i !=
e; ++i) {
1763 LatticeVal V = IVs[i];
1764 ConstVals.push_back(V.isConstant()
1770 const LatticeVal &IV = Solver.getLatticeValueFor(V);
1771 if (IV.isOverdefined())
1776 assert(Const &&
"Constant is nullptr here!");
1787 Solver.AddMustTailCallee(F);
1789 LLVM_DEBUG(
dbgs() <<
" Can\'t treat the result of musttail call : " << *CI
1790 <<
" as a constant\n");
1794 LLVM_DEBUG(
dbgs() <<
" Constant: " << *Const <<
" = " << *V <<
'\n');
1810 Solver.MarkBlockExecutable(&F.
front());
1814 Solver.markOverdefined(&AI);
1817 bool ResolvedUndefs =
true;
1818 while (ResolvedUndefs) {
1821 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1824 bool MadeChanges =
false;
1831 if (!Solver.isBlockExecutable(&BB)) {
1898 if (skipFunction(F))
1902 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1912 "Sparse Conditional Constant Propagation",
false,
false)
1922 SCCPSolver &Solver) {
1924 if (!Solver.isArgumentTrackedFunction(&F))
1929 if (Solver.isMustTailCallee(&F)) {
1931 <<
" due to present musttail call of it\n");
1937 [&Solver](
User *U) {
1938 if (isa<Instruction>(U) &&
1939 !Solver.isBlockExecutable(cast<Instruction>(U)->
getParent()))
1949 Solver.getStructLatticeValueFor(U),
1950 [](
const LatticeVal &LV) {
return !LV.isOverdefined(); });
1952 return !Solver.getLatticeValueFor(U).isOverdefined();
1954 "We can only zap functions where all live users have a concrete value");
1957 if (
CallInst *CI = BB.getTerminatingMustTailCall()) {
1958 LLVM_DEBUG(
dbgs() <<
"Can't zap return of the block due to present " 1959 <<
"musttail call : " << *CI <<
"\n");
1964 if (
auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1965 if (!isa<UndefValue>(RI->getOperand(0)))
1975 if (
SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1976 if (!isa<ConstantInt>(SI->getCondition())) {
1978 Dest = SI->case_begin()->getCaseSuccessor();
1979 C = SI->case_begin()->getCaseValue();
1981 }
else if (
BranchInst *BI = dyn_cast<BranchInst>(I)) {
1982 if (!isa<ConstantInt>(BI->getCondition())) {
1984 Dest = BI->getSuccessor(1);
1988 if (!isa<BlockAddress>(IBR->getAddress()->stripPointerCasts())) {
1990 Dest = IBR->getSuccessor(0);
1998 "Didn't find feasible edge?");
2009 SCCPSolver Solver(DL, GetTLI);
2014 if (F.isDeclaration())
2017 Solver.addAnalysis(F, getAnalysis(F));
2022 Solver.AddTrackedFunction(&F);
2027 Solver.AddArgumentTrackedFunction(&F);
2032 Solver.MarkBlockExecutable(&F.front());
2036 Solver.markOverdefined(&AI);
2043 G.removeDeadConstantUsers();
2045 Solver.TrackValueOfGlobalVariable(&
G);
2049 bool ResolvedUndefs =
true;
2051 while (ResolvedUndefs) {
2053 ResolvedUndefs =
false;
2055 if (Solver.ResolvedUndefsIn(F)) {
2059 ResolvedUndefs =
true;
2063 bool MadeChanges =
false;
2069 if (F.isDeclaration())
2074 if (Solver.isBlockExecutable(&F.front()))
2084 if (!Solver.isBlockExecutable(&*BB)) {
2090 if (&*BB != &F.front())
2119 if (!Solver.isBlockExecutable(&F.front()))
2130 UE = DeadBB->user_end();
2135 do { ++UI; }
while (UI != UE && *UI == I);
2148 "Expect TermInst on constantint or blockaddress to be folded");
2167 if (Solver.getPredicateInfoFor(Inst)) {
2168 if (
auto *II = dyn_cast<IntrinsicInst>(Inst)) {
2169 if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
2170 Value *
Op = II->getOperand(0);
2193 for (
const auto &I : RV) {
2200 for (
auto F : Solver.getMRVFunctionsTracked()) {
2201 assert(F->getReturnType()->isStructTy() &&
2202 "The return type should be a struct");
2203 StructType *STy = cast<StructType>(F->getReturnType());
2204 if (Solver.isStructLatticeConstant(F, STy))
2209 for (
unsigned i = 0,
e = ReturnsToZap.
size(); i !=
e; ++i) {
2210 Function *F = ReturnsToZap[i]->getParent()->getParent();
2218 E = TG.
end(); I !=
E; ++
I) {
2220 assert(!I->second.isOverdefined() &&
2221 "Overdefined values should have been taken out of the map!");
2223 <<
"' is constant!\n");
2228 M.getGlobalList().
erase(GV);
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.
bool onlyReadsMemory() const
Determine if the function does not access or only reads memory.
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
This class is the base class for the comparison instructions.
void setInt(IntType IntVal) LLVM_LVALUE_FUNCTION
static bool isConstant(const MachineInstr &MI)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
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()
Interprocedural Sparse Conditional Constant Propagation
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
iterator erase(iterator where)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
PointerTy getPointer() const
This is the interface for a simple mod/ref and alias analysis over globals.
unsigned getNumIndices() const
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
A Module instance is used to store all the information related to an LLVM module. ...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
An instruction for ordering other memory operations.
bool canTrackArgumentsInterprocedurally(Function *F)
Determine if the values of the given function's arguments can be tracked interprocedurally.
Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant *> Operands, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
Implements a dense probed hash-table based set.
unsigned getNumElements() const
Random access to the elements.
void push_back(const T &Elt)
bool isSafeToRemove() const
Return true if the instruction can be removed if the result is unused.
static ValueLatticeElement get(Constant *C)
This class represents a function call, abstracting a target machine's calling convention.
const Value * getTrueValue() const
An efficient, type-erasing, non-owning reference to a callable.
bool isTerminator() const
This class implements a map that also provides access to all stored values in a deterministic order...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
An instruction for reading from memory.
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void reserve(size_type N)
bool isMustTailCall() const
LLVMContext & getContext() const
Get the context in which this basic block lives.
static void findReturnsToZap(Function &F, SmallVector< ReturnInst *, 8 > &ReturnsToZap, SCCPSolver &Solver)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
std::unique_ptr< PredicateInfo > PredInfo
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
The address of a basic block.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
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.
void initializeSCCPLegacyPassPass(PassRegistry &)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static void forceIndeterminateEdge(Instruction *I, SCCPSolver &Solver)
FunctionPass * createSCCPPass()
mir Rename Register Operands
Type * getSourceElementType() const
Helper struct for bundling up the analysis results per function for IPSCCP.
void assign(size_type NumElts, const T &Elt)
InstrTy * getInstruction() const
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
Value * getInsertedValueOperand()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator find(const KeyT &Key)
bool isOverdefined() const
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
void setPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
iterator find(const_arg_type_t< KeyT > Val)
bool canTrackReturnsInterprocedurally(Function *F)
Determine if the values of the given function's returns can be tracked interprocedurally.
bool isVoidTy() const
Return true if this is 'void'.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static bool runOnFunction(Function &F, bool PostInlining)
bool erase(const KeyT &Val)
Type * getReturnType() const
Returns the type of the ret val.
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...
void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Conditional or Unconditional Branch instruction.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
This function has undefined behavior.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
Resume the propagation of an exception.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Indirect Branch Instruction.
std::pair< iterator, bool > insert(const ValueT &V)
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.
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.
FunctionPass class - This class is used to implement most global optimizations.
static Constant * get(StructType *T, ArrayRef< Constant *> V)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
const Function * getFunction() const
Return the function this instruction belongs to.
static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V)
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...
const Value * getCondition() const
static Constant * getAllOnesValue(Type *Ty)
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.
bool isExceptionalTerminator() const
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
This file implements the PredicateInfo analysis, which creates an Extended SSA form for operations us...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool runIPSCCP(Module &M, const DataLayout &DL, std::function< const TargetLibraryInfo &(Function &)> GetTLI, function_ref< AnalysisResultsForFn(Function &)> getAnalysis)
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function...
idx_iterator idx_begin() const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
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.
BlockVerifier::State From
INITIALIZE_PASS_BEGIN(IPSCCPLegacyPass, "ipsccp", "Interprocedural Sparse Conditional Constant Propagation", false, false) INITIALIZE_PASS_END(IPSCCPLegacyPass
Constant * getCompare(CmpInst::Predicate Pred, Type *Ty, const ValueLatticeElement &Other) const
Compares this symbolic value with Other using Pred and returns either true, false or undef constants...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
bool canTrackGlobalVariableInterprocedurally(GlobalVariable *GV)
Determine if the value maintained in the given global variable can be tracked interprocedurally.
size_type count(const KeyT &Key) const
LLVM_NODISCARD T pop_back_val()
void setPreservesCFG()
This function should be called by the pass, iff they do not:
unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than it's terminator and any present EH pad instruct...
typename VectorType::iterator iterator
User::op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
iterator_range< user_iterator > users()
Represents analyses that only rely on functions' control flow.
const Value * getFalseValue() const
Predicate getPredicate() const
Return the predicate for this instruction.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
user_iterator_impl< User > user_iterator
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
bool isUnconditional() const
LLVM_NODISCARD bool empty() const
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Analysis pass providing the TargetLibraryInfo.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
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.
static const Function * getParent(const Value *V)
print Print MemDeps of function
static ValueLatticeElement getOverdefined()
A container for analyses that lazily runs them and caches their results.
This header defines various interfaces for pass management in LLVM.
unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
static bool runSCCP(Function &F, const DataLayout &DL, const TargetLibraryInfo *TLI)
iterator_range< arg_iterator > args()
bool isStructTy() const
True if this is an instance of StructType.
const BasicBlock * getParent() const
This instruction inserts a struct field of array element value into an aggregate value.
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.