81#ifdef EXPENSIVE_CHECKS
87#define DEBUG_TYPE "dfa-jump-threading"
89STATISTIC(NumTransforms,
"Number of transformations done");
91STATISTIC(NumPaths,
"Number of individual paths threaded");
96 cl::desc(
"View the CFG before DFA Jump Threading"),
100 "dfa-early-exit-heuristic",
101 cl::desc(
"Exit early if an unpredictable value come from the same loop"),
105 "dfa-max-path-length",
106 cl::desc(
"Max number of blocks searched to find a threading path"),
110 "dfa-max-num-visited-paths",
112 "Max number of blocks visited while enumerating paths around a switch"),
117 cl::desc(
"Max number of paths enumerated around a switch"),
122 cl::desc(
"Maximum cost accepted for the transformation"),
130 "dfa-max-cloned-rate",
132 "Maximum cloned instructions rate accepted for the transformation"),
136class SelectInstToUnfold {
143 SelectInst *getInst() {
return SI; }
144 PHINode *getUse() {
return SIUse; }
146 explicit operator bool()
const {
return SI && SIUse; }
149class DFAJumpThreading {
151 DFAJumpThreading(AssumptionCache *AC, DomTreeUpdater *DTU, LoopInfo *LI,
152 TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE)
153 : AC(AC), DTU(DTU), LI(LI), TTI(TTI), ORE(ORE) {}
155 bool run(Function &
F);
163 while (!
Stack.empty()) {
164 SelectInstToUnfold SIToUnfold =
Stack.pop_back_val();
166 std::vector<SelectInstToUnfold> NewSIsToUnfold;
167 std::vector<BasicBlock *> NewBBs;
168 unfold(DTU, LI, SIToUnfold, &NewSIsToUnfold, &NewBBs);
175 static void unfold(DomTreeUpdater *DTU, LoopInfo *LI,
176 SelectInstToUnfold SIToUnfold,
177 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
178 std::vector<BasicBlock *> *NewBBs);
183 TargetTransformInfo *TTI;
184 OptimizationRemarkEmitter *ORE;
196 SelectInstToUnfold SIToUnfold,
197 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
198 std::vector<BasicBlock *> *NewBBs) {
199 SelectInst *
SI = SIToUnfold.getInst();
200 PHINode *SIUse = SIToUnfold.getUse();
204 BranchInst *StartBlockTerm =
212 SI->getContext(), Twine(
SI->getName(),
".si.unfold.false"),
214 NewBBs->push_back(NewBlock);
216 DTU->
applyUpdates({{DominatorTree::Insert, NewBlock, EndBlock}});
223 Value *SIOp1 =
SI->getTrueValue();
224 Value *SIOp2 =
SI->getFalseValue();
227 Twine(SIOp2->
getName(),
".si.unfold.phi"),
232 for (PHINode &Phi : EndBlock->
phis()) {
235 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlock);
244 Twine(
SI->getName(),
".si.unfold.phi"),
247 if (Pred != StartBlock && Pred != NewBlock)
258 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, SIUse));
260 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, NewPhi));
267 BI->setMetadata(LLVMContext::MD_prof,
268 SI->getMetadata(LLVMContext::MD_prof));
269 DTU->
applyUpdates({{DominatorTree::Insert, StartBlock, NewBlock}});
273 SI->getContext(), Twine(
SI->getName(),
".si.unfold.true"),
276 SI->getContext(), Twine(
SI->getName(),
".si.unfold.false"),
279 NewBBs->push_back(NewBlockT);
280 NewBBs->push_back(NewBlockF);
305 BI->setMetadata(LLVMContext::MD_prof,
306 SI->getMetadata(LLVMContext::MD_prof));
307 DTU->
applyUpdates({{DominatorTree::Insert, NewBlockT, NewBlockF},
308 {DominatorTree::Insert, NewBlockT, EndBlock},
309 {DominatorTree::Insert, NewBlockF, EndBlock}});
324 NewSIsToUnfold->push_back(SelectInstToUnfold(TrueSI, NewPhiT));
326 NewSIsToUnfold->push_back(SelectInstToUnfold(FalseSi, NewPhiF));
333 for (PHINode &Phi : EndBlock->
phis()) {
336 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlockT);
337 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlockF);
338 Phi.removeIncomingValue(StartBlock);
343 unsigned SuccNum = StartBlockTerm->
getSuccessor(1) == EndBlock ? 1 : 0;
345 DTU->
applyUpdates({{DominatorTree::Delete, StartBlock, EndBlock},
346 {DominatorTree::Insert, StartBlock, NewBlockT}});
351 for (BasicBlock *NewBB : *NewBBs)
352 L->addBasicBlockToLoop(NewBB, *LI);
356 assert(
SI->use_empty() &&
"Select must be dead now");
357 SI->eraseFromParent();
384 OS <<
"< " <<
llvm::join(BBNames,
", ") <<
" >";
393struct ThreadingPath {
395 APInt getExitValue()
const {
return ExitVal; }
396 void setExitValue(
const ConstantInt *V) {
397 ExitVal =
V->getValue();
400 void setExitValue(
const APInt &V) {
404 bool isExitValueSet()
const {
return IsExitValSet; }
407 const BasicBlock *getDeterminatorBB()
const {
return DBB; }
408 void setDeterminator(
const BasicBlock *BB) { DBB = BB; }
411 const PathType &getPath()
const {
return Path; }
412 void setPath(
const PathType &NewPath) { Path = NewPath; }
413 void push_back(BasicBlock *BB) { Path.push_back(BB); }
414 void push_front(BasicBlock *BB) { Path.push_front(BB); }
415 void appendExcludingFirst(
const PathType &OtherPath) {
419 void print(raw_ostream &OS)
const {
427 bool IsExitValSet =
false;
431inline raw_ostream &
operator<<(raw_ostream &OS,
const ThreadingPath &TPath) {
438 MainSwitch(SwitchInst *SI, LoopInfo *LI, OptimizationRemarkEmitter *ORE)
444 return OptimizationRemarkMissed(
DEBUG_TYPE,
"SwitchNotPredictable", SI)
445 <<
"Switch instruction is not predictable.";
450 virtual ~MainSwitch() =
default;
452 SwitchInst *getInstr()
const {
return Instr; }
463 std::deque<std::pair<Value *, BasicBlock *>> Q;
464 SmallPtrSet<Value *, 16> SeenValues;
467 Value *SICond =
SI->getCondition();
477 addToQueue(SICond,
nullptr, Q, SeenValues);
480 Value *Current = Q.front().first;
481 BasicBlock *CurrentIncomingBB = Q.front().second;
485 for (BasicBlock *IncomingBB :
Phi->blocks()) {
486 Value *Incoming =
Phi->getIncomingValueForBlock(IncomingBB);
487 addToQueue(Incoming, IncomingBB, Q, SeenValues);
491 if (!isValidSelectInst(SelI))
493 addToQueue(SelI->getTrueValue(), CurrentIncomingBB, Q, SeenValues);
494 addToQueue(SelI->getFalseValue(), CurrentIncomingBB, Q, SeenValues);
497 SelectInsts.push_back(SelectInstToUnfold(SelI, SelIUse));
515 <<
"\tExiting early due to unpredictability heuristic.\n");
526 void addToQueue(
Value *Val, BasicBlock *BB,
527 std::deque<std::pair<Value *, BasicBlock *>> &Q,
528 SmallPtrSet<Value *, 16> &SeenValues) {
529 if (SeenValues.
insert(Val).second)
530 Q.push_back({Val, BB});
533 bool isValidSelectInst(SelectInst *SI) {
534 if (!
SI->hasOneUse())
559 for (SelectInstToUnfold SIToUnfold : SelectInsts) {
560 SelectInst *PrevSI = SIToUnfold.getInst();
570 SwitchInst *Instr =
nullptr;
574struct AllSwitchPaths {
575 AllSwitchPaths(
const MainSwitch *MSwitch, OptimizationRemarkEmitter *ORE,
576 LoopInfo *LI, Loop *L)
577 : Switch(MSwitch->getInstr()), SwitchBlock(Switch->
getParent()), ORE(ORE),
578 LI(LI), SwitchOuterLoop(
L) {}
580 std::vector<ThreadingPath> &getThreadingPaths() {
return TPaths; }
581 unsigned getNumThreadingPaths() {
return TPaths.size(); }
582 SwitchInst *getSwitchInst() {
return Switch; }
583 BasicBlock *getSwitchBlock() {
return SwitchBlock; }
593 typedef DenseMap<const BasicBlock *, const PHINode *> StateDefMap;
594 std::vector<ThreadingPath> getPathsFromStateDefMap(StateDefMap &StateDef,
597 unsigned PathsLimit) {
598 std::vector<ThreadingPath> Res;
599 auto *PhiBB =
Phi->getParent();
603 for (
auto *IncomingBB :
Phi->blocks()) {
604 if (Res.size() >= PathsLimit)
606 if (!UniqueBlocks.
insert(IncomingBB).second)
608 if (!SwitchOuterLoop->
contains(IncomingBB))
611 Value *IncomingValue =
Phi->getIncomingValueForBlock(IncomingBB);
615 if (PhiBB == SwitchBlock &&
618 ThreadingPath NewPath;
619 NewPath.setDeterminator(PhiBB);
620 NewPath.setExitValue(
C);
622 if (IncomingBB != SwitchBlock)
623 NewPath.push_back(IncomingBB);
624 NewPath.push_back(PhiBB);
625 Res.push_back(NewPath);
629 if (VB.
contains(IncomingBB) || IncomingBB == SwitchBlock)
635 auto *IncomingPhiDefBB = IncomingPhi->getParent();
636 if (!StateDef.contains(IncomingPhiDefBB))
640 if (IncomingPhiDefBB == IncomingBB) {
641 assert(PathsLimit > Res.size());
642 std::vector<ThreadingPath> PredPaths = getPathsFromStateDefMap(
643 StateDef, IncomingPhi, VB, PathsLimit - Res.size());
644 for (ThreadingPath &Path : PredPaths) {
645 Path.push_back(PhiBB);
646 Res.push_back(std::move(Path));
656 assert(PathsLimit > Res.size());
657 auto InterPathLimit = PathsLimit - Res.size();
658 IntermediatePaths = paths(IncomingPhiDefBB, IncomingBB, VB,
660 if (IntermediatePaths.empty())
663 assert(InterPathLimit >= IntermediatePaths.size());
664 auto PredPathLimit = InterPathLimit / IntermediatePaths.size();
665 std::vector<ThreadingPath> PredPaths =
666 getPathsFromStateDefMap(StateDef, IncomingPhi, VB, PredPathLimit);
667 for (
const ThreadingPath &Path : PredPaths) {
668 for (
const PathType &IPath : IntermediatePaths) {
669 ThreadingPath NewPath(Path);
670 NewPath.appendExcludingFirst(IPath);
671 NewPath.push_back(PhiBB);
672 Res.push_back(NewPath);
681 unsigned PathDepth,
unsigned PathsLimit) {
687 return OptimizationRemarkAnalysis(
DEBUG_TYPE,
"MaxPathLengthReached",
689 <<
"Exploration stopped after visiting MaxPathLength="
706 SmallPtrSet<BasicBlock *, 4> Successors;
708 if (Res.size() >= PathsLimit)
710 if (!Successors.
insert(Succ).second)
715 Res.push_back({BB, ToBB});
725 if (Succ == CurrLoop->getHeader())
731 assert(PathsLimit > Res.size());
733 paths(Succ, ToBB, Visited, PathDepth + 1, PathsLimit - Res.size());
748 StateDefMap getStateDefMap()
const {
751 assert(FirstDef &&
"The first definition must be a phi.");
754 Stack.push_back(FirstDef);
755 SmallPtrSet<Value *, 16> SeenValues;
757 while (!
Stack.empty()) {
758 PHINode *CurPhi =
Stack.pop_back_val();
761 SeenValues.
insert(CurPhi);
763 for (BasicBlock *IncomingBB : CurPhi->
blocks()) {
764 PHINode *IncomingPhi =
768 bool IsOutsideLoops = !SwitchOuterLoop->
contains(IncomingBB);
769 if (SeenValues.
contains(IncomingPhi) || IsOutsideLoops)
772 Stack.push_back(IncomingPhi);
781 StateDefMap StateDef = getStateDefMap();
782 if (StateDef.empty()) {
784 return OptimizationRemarkMissed(
DEBUG_TYPE,
"SwitchNotPredictable",
786 <<
"Switch instruction is not predictable.";
792 auto *SwitchPhiDefBB = SwitchPhi->getParent();
795 std::vector<ThreadingPath> PathsToPhiDef =
796 getPathsFromStateDefMap(StateDef, SwitchPhi, VB,
MaxNumPaths);
797 if (SwitchPhiDefBB == SwitchBlock || PathsToPhiDef.empty()) {
798 TPaths = std::move(PathsToPhiDef);
803 auto PathsLimit =
MaxNumPaths / PathsToPhiDef.size();
806 paths(SwitchPhiDefBB, SwitchBlock, VB, 1, PathsLimit);
807 if (PathsToSwitchBB.empty())
810 std::vector<ThreadingPath> TempList;
811 for (
const ThreadingPath &Path : PathsToPhiDef) {
812 for (
const PathType &PathToSw : PathsToSwitchBB) {
813 ThreadingPath PathCopy(Path);
814 PathCopy.appendExcludingFirst(PathToSw);
815 TempList.push_back(PathCopy);
818 TPaths = std::move(TempList);
823 BasicBlock *getNextCaseSuccessor(
const APInt &NextState) {
825 if (CaseValToDest.empty()) {
826 for (
auto Case : Switch->
cases()) {
827 APInt CaseVal = Case.getCaseValue()->getValue();
828 CaseValToDest[CaseVal] = Case.getCaseSuccessor();
832 auto SuccIt = CaseValToDest.find(NextState);
840 SmallDenseMap<BasicBlock *, APInt> DestToState;
841 for (ThreadingPath &Path : TPaths) {
842 APInt NextState =
Path.getExitValue();
843 BasicBlock *Dest = getNextCaseSuccessor(NextState);
847 if (NextState != StateIt->second) {
848 LLVM_DEBUG(
dbgs() <<
"Next state in " << Path <<
" is equivalent to "
849 << StateIt->second <<
"\n");
850 Path.setExitValue(StateIt->second);
855 unsigned NumVisited = 0;
858 OptimizationRemarkEmitter *ORE;
859 std::vector<ThreadingPath> TPaths;
860 DenseMap<APInt, BasicBlock *> CaseValToDest;
862 Loop *SwitchOuterLoop;
866 TransformDFA(AllSwitchPaths *SwitchPaths, DomTreeUpdater *DTU,
867 AssumptionCache *AC, TargetTransformInfo *
TTI,
868 OptimizationRemarkEmitter *ORE,
869 SmallPtrSet<const Value *, 32> EphValues)
870 : SwitchPaths(SwitchPaths), DTU(DTU), AC(AC),
TTI(
TTI), ORE(ORE),
871 EphValues(EphValues) {}
874 if (isLegalAndProfitableToTransform()) {
875 createAllExitPaths();
887 bool isLegalAndProfitableToTransform() {
889 uint64_t NumClonedInst = 0;
890 SwitchInst *
Switch = SwitchPaths->getSwitchInst();
893 if (
Switch->getNumSuccessors() <= 1)
899 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
901 APInt NextState = TPath.getExitValue();
902 const BasicBlock *Determinator = TPath.getDeterminatorBB();
905 BasicBlock *BB = SwitchPaths->getSwitchBlock();
906 BasicBlock *VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
908 Metrics.analyzeBasicBlock(BB, *
TTI, EphValues);
910 DuplicateMap[BB].push_back({BB, NextState});
915 if (PathBBs.front() == Determinator)
920 auto DetIt =
llvm::find(PathBBs, Determinator);
921 for (
auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
923 VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
926 Metrics.analyzeBasicBlock(BB, *
TTI, EphValues);
928 DuplicateMap[BB].push_back({BB, NextState});
932 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
933 <<
"non-duplicatable instructions.\n");
935 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NonDuplicatableInst",
937 <<
"Contains non-duplicatable instructions.";
943 if (
Metrics.Convergence != ConvergenceKind::None) {
944 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
945 <<
"convergent instructions.\n");
947 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ConvergentInst", Switch)
948 <<
"Contains convergent instructions.";
953 if (!
Metrics.NumInsts.isValid()) {
954 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
955 <<
"instructions with invalid cost.\n");
957 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ConvergentInst", Switch)
958 <<
"Contains instructions with invalid cost.";
967 uint64_t NumOrigInst = 0;
968 for (
auto *BB : DuplicateMap.
keys())
970 if (
double(NumClonedInst) /
double(NumOrigInst) >
MaxClonedRate) {
971 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, too much "
972 "instructions wll be cloned\n");
974 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotProfitable", Switch)
975 <<
"Too much instructions will be cloned.";
982 unsigned JumpTableSize = 0;
985 if (JumpTableSize == 0) {
989 unsigned CondBranches =
990 APInt(32,
Switch->getNumSuccessors()).ceilLogBase2();
991 assert(CondBranches > 0 &&
992 "The threaded switch must have multiple branches");
993 DuplicationCost =
Metrics.NumInsts / CondBranches;
1001 DuplicationCost =
Metrics.NumInsts / JumpTableSize;
1004 LLVM_DEBUG(
dbgs() <<
"\nDFA Jump Threading: Cost to jump thread block "
1005 << SwitchPaths->getSwitchBlock()->getName()
1006 <<
" is: " << DuplicationCost <<
"\n\n");
1009 LLVM_DEBUG(
dbgs() <<
"Not jump threading, duplication cost exceeds the "
1010 <<
"cost threshold.\n");
1012 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotProfitable", Switch)
1013 <<
"Duplication cost exceeds the cost threshold (cost="
1014 <<
ore::NV(
"Cost", DuplicationCost)
1021 return OptimizationRemark(
DEBUG_TYPE,
"JumpThreaded", Switch)
1022 <<
"Switch statement jump-threaded.";
1029 void createAllExitPaths() {
1031 BasicBlock *SwitchBlock = SwitchPaths->getSwitchBlock();
1032 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
1036 TPath.push_front(SwitchBlock);
1043 SmallPtrSet<BasicBlock *, 16> BlocksToClean;
1046 for (
const ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
1047 createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, DTU);
1053 for (
const ThreadingPath &TPath : SwitchPaths->getThreadingPaths())
1054 updateLastSuccessor(TPath, DuplicateMap, DTU);
1060 for (BasicBlock *BB : BlocksToClean)
1070 void createExitPath(
DefMap &NewDefs,
const ThreadingPath &Path,
1072 SmallPtrSet<BasicBlock *, 16> &BlocksToClean,
1073 DomTreeUpdater *DTU) {
1074 APInt NextState =
Path.getExitValue();
1079 if (PathBBs.front() == Determinator)
1080 PathBBs.pop_front();
1082 auto DetIt =
llvm::find(PathBBs, Determinator);
1085 BasicBlock *PrevBB = PathBBs.size() == 1 ? *DetIt : *std::prev(DetIt);
1086 for (
auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
1088 BlocksToClean.
insert(BB);
1092 BasicBlock *NextBB = getClonedBB(BB, NextState, DuplicateMap);
1094 updatePredecessor(PrevBB, BB, NextBB, DTU);
1100 BasicBlock *NewBB = cloneBlockAndUpdatePredecessor(
1101 BB, PrevBB, NextState, DuplicateMap, NewDefs, DTU);
1102 DuplicateMap[BB].push_back({NewBB, NextState});
1103 BlocksToClean.
insert(NewBB);
1114 void updateSSA(
DefMap &NewDefs) {
1115 SSAUpdaterBulk SSAUpdate;
1116 SmallVector<Use *, 16> UsesToRename;
1118 for (
const auto &KV : NewDefs) {
1121 std::vector<Instruction *> Cloned = KV.second;
1125 for (Use &U :
I->uses()) {
1128 if (UserPN->getIncomingBlock(U) == BB)
1130 }
else if (
User->getParent() == BB) {
1139 if (UsesToRename.
empty())
1147 unsigned VarNum = SSAUpdate.
AddVariable(
I->getName(),
I->getType());
1149 for (Instruction *New : Cloned)
1152 while (!UsesToRename.
empty())
1166 static BasicBlock *getNextCaseSuccessor(SwitchInst *Switch,
1167 const APInt &NextState) {
1169 for (
auto Case :
Switch->cases()) {
1170 if (Case.getCaseValue()->getValue() == NextState) {
1171 NextCase = Case.getCaseSuccessor();
1176 NextCase =
Switch->getDefaultDest();
1184 BasicBlock *cloneBlockAndUpdatePredecessor(BasicBlock *BB, BasicBlock *PrevBB,
1185 const APInt &NextState,
1188 DomTreeUpdater *DTU) {
1196 for (Instruction &
I : *NewBB) {
1208 updateSuccessorPhis(BB, NewBB, NextState, VMap, DuplicateMap);
1209 updatePredecessor(PrevBB, BB, NewBB, DTU);
1210 updateDefMap(NewDefs, VMap);
1213 SmallPtrSet<BasicBlock *, 4> SuccSet;
1215 if (SuccSet.
insert(SuccBB).second)
1216 DTU->
applyUpdates({{DominatorTree::Insert, NewBB, SuccBB}});
1226 void updateSuccessorPhis(BasicBlock *BB, BasicBlock *ClonedBB,
1229 std::vector<BasicBlock *> BlocksToUpdate;
1233 if (BB == SwitchPaths->getSwitchBlock()) {
1234 SwitchInst *
Switch = SwitchPaths->getSwitchInst();
1235 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1236 BlocksToUpdate.push_back(NextCase);
1237 BasicBlock *ClonedSucc = getClonedBB(NextCase, NextState, DuplicateMap);
1239 BlocksToUpdate.push_back(ClonedSucc);
1244 BlocksToUpdate.push_back(Succ);
1249 BasicBlock *ClonedSucc = getClonedBB(Succ, NextState, DuplicateMap);
1251 BlocksToUpdate.push_back(ClonedSucc);
1258 for (BasicBlock *Succ : BlocksToUpdate) {
1259 for (PHINode &Phi : Succ->phis()) {
1260 Value *Incoming =
Phi.getIncomingValueForBlock(BB);
1263 Phi.addIncoming(Incoming, ClonedBB);
1266 Value *ClonedVal = VMap[Incoming];
1268 Phi.addIncoming(ClonedVal, ClonedBB);
1270 Phi.addIncoming(Incoming, ClonedBB);
1278 void updatePredecessor(BasicBlock *PrevBB, BasicBlock *OldBB,
1279 BasicBlock *NewBB, DomTreeUpdater *DTU) {
1282 if (!isPredecessor(OldBB, PrevBB))
1292 DTU->
applyUpdates({{DominatorTree::Delete, PrevBB, OldBB},
1293 {DominatorTree::Insert, PrevBB, NewBB}});
1302 for (
auto Entry : VMap) {
1314 NewDefsVector.
push_back({Inst, Cloned});
1318 sort(NewDefsVector, [](
const auto &
LHS,
const auto &
RHS) {
1319 if (
LHS.first ==
RHS.first)
1320 return LHS.second->comesBefore(
RHS.second);
1321 return LHS.first->comesBefore(
RHS.first);
1324 for (
const auto &KV : NewDefsVector)
1325 NewDefs[KV.first].push_back(KV.second);
1333 void updateLastSuccessor(
const ThreadingPath &TPath,
1335 DomTreeUpdater *DTU) {
1336 APInt NextState = TPath.getExitValue();
1338 BasicBlock *LastBlock = getClonedBB(BB, NextState, DuplicateMap);
1345 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1347 std::vector<DominatorTree::UpdateType> DTUpdates;
1348 SmallPtrSet<BasicBlock *, 4> SuccSet;
1349 for (BasicBlock *Succ :
successors(LastBlock)) {
1350 if (Succ != NextCase && SuccSet.
insert(Succ).second)
1351 DTUpdates.push_back({DominatorTree::Delete, LastBlock, Succ});
1354 Switch->eraseFromParent();
1362 void cleanPhiNodes(BasicBlock *BB) {
1367 PN.eraseFromParent();
1373 for (PHINode &Phi : BB->
phis())
1374 Phi.removeIncomingValueIf([&](
unsigned Index) {
1376 return !isPredecessor(BB, IncomingBB);
1382 BasicBlock *getClonedBB(BasicBlock *BB,
const APInt &NextState,
1388 auto It =
llvm::find_if(ClonedBBs, [NextState](
const ClonedBlock &
C) {
1389 return C.State == NextState;
1391 return It != ClonedBBs.end() ? (*It).BB :
nullptr;
1395 bool isPredecessor(BasicBlock *BB, BasicBlock *IncomingBB) {
1399 AllSwitchPaths *SwitchPaths;
1400 DomTreeUpdater *DTU;
1401 AssumptionCache *AC;
1402 TargetTransformInfo *
TTI;
1403 OptimizationRemarkEmitter *ORE;
1404 SmallPtrSet<const Value *, 32> EphValues;
1405 std::vector<ThreadingPath> TPaths;
1409bool DFAJumpThreading::run(Function &
F) {
1410 LLVM_DEBUG(
dbgs() <<
"\nDFA Jump threading: " <<
F.getName() <<
"\n");
1412 if (
F.hasOptSize()) {
1413 LLVM_DEBUG(
dbgs() <<
"Skipping due to the 'minsize' attribute\n");
1421 bool MadeChanges =
false;
1422 LoopInfoBroken =
false;
1424 for (BasicBlock &BB :
F) {
1430 <<
" is a candidate\n");
1431 MainSwitch
Switch(SI, LI, ORE);
1433 if (!
Switch.getInstr()) {
1435 <<
"candidate for jump threading\n");
1440 <<
"candidate for jump threading\n");
1443 unfoldSelectInstrs(
Switch.getSelectInsts());
1444 if (!
Switch.getSelectInsts().empty())
1447 AllSwitchPaths SwitchPaths(&Switch, ORE, LI,
1451 if (SwitchPaths.getNumThreadingPaths() > 0) {
1468 SmallPtrSet<const Value *, 32> EphValues;
1469 if (ThreadableLoops.
size() > 0)
1472 for (AllSwitchPaths SwitchPaths : ThreadableLoops) {
1473 TransformDFA Transform(&SwitchPaths, DTU, AC,
TTI, ORE, EphValues);
1474 if (Transform.run())
1475 MadeChanges = LoopInfoBroken =
true;
1480#ifdef EXPENSIVE_CHECKS
1486 "Failed to maintain validity of domtree!");
1501 DFAJumpThreading ThreadImpl(&AC, &DTU, &LI, &
TTI, &ORE);
1502 if (!ThreadImpl.run(
F))
1507 if (!ThreadImpl.LoopInfoBroken)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static const Function * getParent(const Value *V)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
std::deque< BasicBlock * > PathType
std::vector< PathType > PathsType
MapVector< Instruction *, std::vector< Instruction * > > DefMap
std::vector< ClonedBlock > CloneList
DenseMap< BasicBlock *, CloneList > DuplicateBlockMap
static cl::opt< double > MaxClonedRate("dfa-max-cloned-rate", cl::desc("Maximum cloned instructions rate accepted for the transformation"), cl::Hidden, cl::init(7.5))
This file defines the DenseMap class.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
uint64_t IntrinsicInst * II
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI filter_iterator< BasicBlock::const_iterator, std::function< bool(constInstruction &)> >::difference_type sizeWithoutDebug() const
Return the size of the basic block ignoring debug instructions.
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...
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Analysis pass which computes a DominatorTree.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
Analysis pass that exposes the LoopInfo for a function.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
const LoopT * getOutermostLoop() const
Get the outermost loop in which this loop is contained.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This class implements a map that also provides access to all stored values in a deterministic order.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
LLVM_ABI unsigned AddVariable(StringRef Name, Type *Ty)
Add a new variable to the SSA rewriter.
LLVM_ABI void AddAvailableValue(unsigned Var, BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
LLVM_ABI void RewriteAllUses(DominatorTree *DT, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Perform all the necessary updates, including new PHI-nodes insertion and the requested uses update.
LLVM_ABI void AddUse(unsigned Var, Use *U)
Record a use of the symbolic value.
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getTrueValue() const
bool erase(PtrType Ptr)
Remove pointer from the set.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(size_type N)
void push_back(const T &Elt)
BasicBlock * getDefaultDest() const
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
Analysis pass providing the TargetTransformInfo.
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Value * getOperand(unsigned i) const
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI std::string getNameOrAsOperand() const
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
const ParentTy * getParent() const
This class implements an extremely fast bulk output stream that can only output to a stream.
@ C
The default llvm calling convention, compatible with C.
@ BasicBlock
Various leaf nodes.
initializer< Ty > init(const Ty &Val)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< PhiNode * > Phi
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
FunctionAddr VTableAddr Value
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
static cl::opt< unsigned > MaxNumPaths("dfa-max-num-paths", cl::desc("Max number of paths enumerated around a switch"), cl::Hidden, cl::init(200))
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto pred_size(const MachineBasicBlock *BB)
static cl::opt< bool > ClViewCfgBefore("dfa-jump-view-cfg-before", cl::desc("View the CFG before DFA Jump Threading"), cl::Hidden, cl::init(false))
auto map_range(ContainerTy &&C, FuncTy F)
void sort(IteratorTy Start, IteratorTy End)
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
static cl::opt< unsigned > MaxNumVisitiedPaths("dfa-max-num-visited-paths", cl::desc("Max number of blocks visited while enumerating paths around a switch"), cl::Hidden, cl::init(2500))
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
static cl::opt< bool > EarlyExitHeuristic("dfa-early-exit-heuristic", cl::desc("Exit early if an unpredictable value come from the same loop"), cl::Hidden, cl::init(true))
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI bool VerifyDomInfo
Enables verification of dominator trees.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
static cl::opt< unsigned > MaxPathLength("dfa-max-path-length", cl::desc("Max number of blocks searched to find a threading path"), cl::Hidden, cl::init(20))
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
cl::opt< bool > ProfcheckDisableMetadataFixes("profcheck-disable-metadata-fixes", cl::Hidden, cl::init(false), cl::desc("Disable metadata propagation fixes discovered through Issue #147390"))
bool pred_empty(const BasicBlock *BB)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
static cl::opt< unsigned > CostThreshold("dfa-cost-threshold", cl::desc("Maximum cost accepted for the transformation"), cl::Hidden, cl::init(50))
static LLVM_ABI void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Integrate with the new Pass Manager.