80#ifdef EXPENSIVE_CHECKS
86#define DEBUG_TYPE "dfa-jump-threading"
88STATISTIC(NumTransforms,
"Number of transformations done");
90STATISTIC(NumPaths,
"Number of individual paths threaded");
94 cl::desc(
"View the CFG before DFA Jump Threading"),
98 "dfa-early-exit-heuristic",
99 cl::desc(
"Exit early if an unpredictable value come from the same loop"),
103 "dfa-max-path-length",
104 cl::desc(
"Max number of blocks searched to find a threading path"),
108 "dfa-max-num-visited-paths",
110 "Max number of blocks visited while enumerating paths around a switch"),
115 cl::desc(
"Max number of paths enumerated around a switch"),
120 cl::desc(
"Maximum cost accepted for the transformation"),
125class SelectInstToUnfold {
132 SelectInst *getInst() {
return SI; }
133 PHINode *getUse() {
return SIUse; }
135 explicit operator bool()
const {
return SI && SIUse; }
139 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
140 std::vector<BasicBlock *> *NewBBs);
142class DFAJumpThreading {
144 DFAJumpThreading(AssumptionCache *AC, DominatorTree *DT, LoopInfo *LI,
145 TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE)
146 : AC(AC), DT(DT), LI(LI), TTI(TTI), ORE(ORE) {}
148 bool run(Function &
F);
153 unfoldSelectInstrs(DominatorTree *DT,
155 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
158 while (!
Stack.empty()) {
159 SelectInstToUnfold SIToUnfold =
Stack.pop_back_val();
161 std::vector<SelectInstToUnfold> NewSIsToUnfold;
162 std::vector<BasicBlock *> NewBBs;
163 unfold(&DTU, LI, SIToUnfold, &NewSIsToUnfold, &NewBBs);
173 TargetTransformInfo *TTI;
174 OptimizationRemarkEmitter *ORE;
189 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
190 std::vector<BasicBlock *> *NewBBs) {
192 PHINode *SIUse = SIToUnfold.getUse();
204 SI->getContext(),
Twine(
SI->getName(),
".si.unfold.false"),
206 NewBBs->push_back(NewBlock);
215 Value *SIOp1 =
SI->getTrueValue();
216 Value *SIOp2 =
SI->getFalseValue();
227 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlock);
236 Twine(
SI->getName(),
".si.unfold.phi"),
239 if (Pred != StartBlock && Pred != NewBlock)
250 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, SIUse));
252 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, NewPhi));
262 SI->getContext(),
Twine(
SI->getName(),
".si.unfold.true"),
265 SI->getContext(),
Twine(
SI->getName(),
".si.unfold.false"),
268 NewBBs->push_back(NewBlockT);
269 NewBBs->push_back(NewBlockF);
309 NewSIsToUnfold->push_back(SelectInstToUnfold(TrueSI, NewPhiT));
311 NewSIsToUnfold->push_back(SelectInstToUnfold(FalseSi, NewPhiF));
321 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlockT);
322 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlockF);
323 Phi.removeIncomingValue(StartBlock);
328 unsigned SuccNum = StartBlockTerm->
getSuccessor(1) == EndBlock ? 1 : 0;
337 L->addBasicBlockToLoop(NewBB, *LI);
341 assert(
SI->use_empty() &&
"Select must be dead now");
342 SI->eraseFromParent();
350typedef std::deque<BasicBlock *> PathType;
351typedef std::vector<PathType> PathsType;
353typedef std::vector<ClonedBlock> CloneList;
382struct ThreadingPath {
384 APInt getExitValue()
const {
return ExitVal; }
385 void setExitValue(
const ConstantInt *V) {
386 ExitVal =
V->getValue();
389 bool isExitValueSet()
const {
return IsExitValSet; }
392 const BasicBlock *getDeterminatorBB()
const {
return DBB; }
393 void setDeterminator(
const BasicBlock *BB) { DBB = BB; }
396 const PathType &getPath()
const {
return Path; }
397 void setPath(
const PathType &NewPath) { Path = NewPath; }
398 void push_back(BasicBlock *BB) { Path.push_back(BB); }
399 void push_front(BasicBlock *BB) { Path.push_front(BB); }
400 void appendExcludingFirst(
const PathType &OtherPath) {
404 void print(raw_ostream &OS)
const {
405 OS << Path <<
" [ " << ExitVal <<
", " << DBB->getName() <<
" ]";
412 bool IsExitValSet =
false;
423 MainSwitch(SwitchInst *SI, LoopInfo *LI, OptimizationRemarkEmitter *ORE)
429 return OptimizationRemarkMissed(
DEBUG_TYPE,
"SwitchNotPredictable", SI)
430 <<
"Switch instruction is not predictable.";
435 virtual ~MainSwitch() =
default;
437 SwitchInst *getInstr()
const {
return Instr; }
448 std::deque<std::pair<Value *, BasicBlock *>> Q;
449 SmallPtrSet<Value *, 16> SeenValues;
452 Value *SICond =
SI->getCondition();
458 const Loop *
L = LI->getLoopFor(
SI->getParent());
462 addToQueue(SICond,
nullptr, Q, SeenValues);
465 Value *Current = Q.front().first;
466 BasicBlock *CurrentIncomingBB = Q.front().second;
470 for (BasicBlock *IncomingBB :
Phi->blocks()) {
471 Value *Incoming =
Phi->getIncomingValueForBlock(IncomingBB);
472 addToQueue(Incoming, IncomingBB, Q, SeenValues);
476 if (!isValidSelectInst(SelI))
478 addToQueue(SelI->getTrueValue(), CurrentIncomingBB, Q, SeenValues);
479 addToQueue(SelI->getFalseValue(), CurrentIncomingBB, Q, SeenValues);
482 SelectInsts.push_back(SelectInstToUnfold(SelI, SelIUse));
498 L->contains(LI->getLoopFor(CurrentIncomingBB))) {
500 <<
"\tExiting early due to unpredictability heuristic.\n");
511 void addToQueue(
Value *Val, BasicBlock *BB,
512 std::deque<std::pair<Value *, BasicBlock *>> &Q,
513 SmallPtrSet<Value *, 16> &SeenValues) {
514 if (SeenValues.
insert(Val).second)
515 Q.push_back({Val, BB});
518 bool isValidSelectInst(SelectInst *SI) {
519 if (!
SI->hasOneUse())
544 for (SelectInstToUnfold SIToUnfold : SelectInsts) {
545 SelectInst *PrevSI = SIToUnfold.getInst();
555 SwitchInst *Instr =
nullptr;
559struct AllSwitchPaths {
560 AllSwitchPaths(
const MainSwitch *MSwitch, OptimizationRemarkEmitter *ORE,
561 LoopInfo *LI, Loop *L)
562 : Switch(MSwitch->getInstr()), SwitchBlock(Switch->
getParent()), ORE(ORE),
563 LI(LI), SwitchOuterLoop(
L) {}
565 std::vector<ThreadingPath> &getThreadingPaths() {
return TPaths; }
566 unsigned getNumThreadingPaths() {
return TPaths.size(); }
567 SwitchInst *getSwitchInst() {
return Switch; }
568 BasicBlock *getSwitchBlock() {
return SwitchBlock; }
571 StateDefMap StateDef = getStateDefMap();
572 if (StateDef.empty()) {
574 return OptimizationRemarkMissed(
DEBUG_TYPE,
"SwitchNotPredictable",
576 <<
"Switch instruction is not predictable.";
582 auto *SwitchPhiDefBB = SwitchPhi->getParent();
585 std::vector<ThreadingPath> PathsToPhiDef =
586 getPathsFromStateDefMap(StateDef, SwitchPhi, VB,
MaxNumPaths);
587 if (SwitchPhiDefBB == SwitchBlock || PathsToPhiDef.empty()) {
588 TPaths = std::move(PathsToPhiDef);
593 auto PathsLimit =
MaxNumPaths / PathsToPhiDef.size();
595 PathsType PathsToSwitchBB =
596 paths(SwitchPhiDefBB, SwitchBlock, VB, 1, PathsLimit);
597 if (PathsToSwitchBB.empty())
600 std::vector<ThreadingPath> TempList;
601 for (
const ThreadingPath &Path : PathsToPhiDef) {
602 for (
const PathType &PathToSw : PathsToSwitchBB) {
603 ThreadingPath PathCopy(Path);
604 PathCopy.appendExcludingFirst(PathToSw);
605 TempList.push_back(PathCopy);
608 TPaths = std::move(TempList);
614 typedef DenseMap<const BasicBlock *, const PHINode *> StateDefMap;
615 std::vector<ThreadingPath> getPathsFromStateDefMap(StateDefMap &StateDef,
618 unsigned PathsLimit) {
619 std::vector<ThreadingPath> Res;
620 auto *PhiBB =
Phi->getParent();
623 VisitedBlocks UniqueBlocks;
624 for (
auto *IncomingBB :
Phi->blocks()) {
625 if (Res.size() >= PathsLimit)
627 if (!UniqueBlocks.insert(IncomingBB).second)
629 if (!SwitchOuterLoop->contains(IncomingBB))
632 Value *IncomingValue =
Phi->getIncomingValueForBlock(IncomingBB);
636 if (PhiBB == SwitchBlock &&
637 SwitchBlock !=
cast<PHINode>(Switch->getOperand(0))->getParent())
639 ThreadingPath NewPath;
640 NewPath.setDeterminator(PhiBB);
641 NewPath.setExitValue(
C);
643 if (IncomingBB != SwitchBlock)
644 NewPath.push_back(IncomingBB);
645 NewPath.push_back(PhiBB);
646 Res.push_back(NewPath);
650 if (VB.contains(IncomingBB) || IncomingBB == SwitchBlock)
656 auto *IncomingPhiDefBB = IncomingPhi->getParent();
657 if (!StateDef.contains(IncomingPhiDefBB))
661 if (IncomingPhiDefBB == IncomingBB) {
662 assert(PathsLimit > Res.size());
663 std::vector<ThreadingPath> PredPaths = getPathsFromStateDefMap(
664 StateDef, IncomingPhi, VB, PathsLimit - Res.size());
665 for (ThreadingPath &Path : PredPaths) {
666 Path.push_back(PhiBB);
667 Res.push_back(std::move(Path));
673 if (VB.contains(IncomingPhiDefBB))
676 PathsType IntermediatePaths;
677 assert(PathsLimit > Res.size());
678 auto InterPathLimit = PathsLimit - Res.size();
679 IntermediatePaths = paths(IncomingPhiDefBB, IncomingBB, VB,
681 if (IntermediatePaths.empty())
684 assert(InterPathLimit >= IntermediatePaths.size());
685 auto PredPathLimit = InterPathLimit / IntermediatePaths.size();
686 std::vector<ThreadingPath> PredPaths =
687 getPathsFromStateDefMap(StateDef, IncomingPhi, VB, PredPathLimit);
688 for (
const ThreadingPath &Path : PredPaths) {
689 for (
const PathType &IPath : IntermediatePaths) {
690 ThreadingPath NewPath(Path);
691 NewPath.appendExcludingFirst(IPath);
692 NewPath.push_back(PhiBB);
693 Res.push_back(NewPath);
701 PathsType paths(BasicBlock *BB, BasicBlock *ToBB, VisitedBlocks &Visited,
702 unsigned PathDepth,
unsigned PathsLimit) {
708 return OptimizationRemarkAnalysis(
DEBUG_TYPE,
"MaxPathLengthReached",
710 <<
"Exploration stopped after visiting MaxPathLength="
722 if (!SwitchOuterLoop->contains(BB))
727 SmallPtrSet<BasicBlock *, 4> Successors;
729 if (Res.size() >= PathsLimit)
731 if (!Successors.
insert(Succ).second)
736 Res.push_back({BB, ToBB});
741 if (Visited.contains(Succ))
744 auto *CurrLoop = LI->getLoopFor(BB);
746 if (Succ == CurrLoop->getHeader())
750 if (LI->getLoopFor(Succ) != CurrLoop)
752 assert(PathsLimit > Res.size());
753 PathsType SuccPaths =
754 paths(Succ, ToBB, Visited, PathDepth + 1, PathsLimit - Res.size());
755 for (PathType &Path : SuccPaths) {
769 StateDefMap getStateDefMap()
const {
772 assert(FirstDef &&
"The first definition must be a phi.");
775 Stack.push_back(FirstDef);
776 SmallPtrSet<Value *, 16> SeenValues;
778 while (!
Stack.empty()) {
779 PHINode *CurPhi =
Stack.pop_back_val();
782 SeenValues.
insert(CurPhi);
784 for (BasicBlock *IncomingBB : CurPhi->
blocks()) {
785 PHINode *IncomingPhi =
789 bool IsOutsideLoops = !SwitchOuterLoop->contains(IncomingBB);
790 if (SeenValues.
contains(IncomingPhi) || IsOutsideLoops)
793 Stack.push_back(IncomingPhi);
800 unsigned NumVisited = 0;
803 OptimizationRemarkEmitter *ORE;
804 std::vector<ThreadingPath> TPaths;
806 Loop *SwitchOuterLoop;
810 TransformDFA(AllSwitchPaths *SwitchPaths, DominatorTree *DT,
811 AssumptionCache *AC, TargetTransformInfo *TTI,
812 OptimizationRemarkEmitter *ORE,
813 SmallPtrSet<const Value *, 32> EphValues)
814 : SwitchPaths(SwitchPaths), DT(DT), AC(AC), TTI(TTI), ORE(ORE),
815 EphValues(EphValues) {}
818 if (isLegalAndProfitableToTransform()) {
819 createAllExitPaths();
829 bool isLegalAndProfitableToTransform() {
831 SwitchInst *
Switch = SwitchPaths->getSwitchInst();
834 if (
Switch->getNumSuccessors() <= 1)
839 DuplicateBlockMap DuplicateMap;
841 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
842 PathType PathBBs = TPath.getPath();
843 APInt NextState = TPath.getExitValue();
844 const BasicBlock *Determinator = TPath.getDeterminatorBB();
847 BasicBlock *BB = SwitchPaths->getSwitchBlock();
848 BasicBlock *VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
850 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
851 DuplicateMap[BB].push_back({BB, NextState});
856 if (PathBBs.front() == Determinator)
861 auto DetIt =
llvm::find(PathBBs, Determinator);
862 for (
auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
864 VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
867 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
868 DuplicateMap[BB].push_back({BB, NextState});
872 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
873 <<
"non-duplicatable instructions.\n");
875 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NonDuplicatableInst",
877 <<
"Contains non-duplicatable instructions.";
883 if (
Metrics.Convergence != ConvergenceKind::None) {
884 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
885 <<
"convergent instructions.\n");
887 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ConvergentInst", Switch)
888 <<
"Contains convergent instructions.";
893 if (!
Metrics.NumInsts.isValid()) {
894 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
895 <<
"instructions with invalid cost.\n");
897 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ConvergentInst", Switch)
898 <<
"Contains instructions with invalid cost.";
906 unsigned JumpTableSize = 0;
907 TTI->getEstimatedNumberOfCaseClusters(*Switch, JumpTableSize,
nullptr,
909 if (JumpTableSize == 0) {
913 unsigned CondBranches =
914 APInt(32,
Switch->getNumSuccessors()).ceilLogBase2();
915 assert(CondBranches > 0 &&
916 "The threaded switch must have multiple branches");
917 DuplicationCost =
Metrics.NumInsts / CondBranches;
925 DuplicationCost =
Metrics.NumInsts / JumpTableSize;
928 LLVM_DEBUG(
dbgs() <<
"\nDFA Jump Threading: Cost to jump thread block "
929 << SwitchPaths->getSwitchBlock()->getName()
930 <<
" is: " << DuplicationCost <<
"\n\n");
933 LLVM_DEBUG(
dbgs() <<
"Not jump threading, duplication cost exceeds the "
934 <<
"cost threshold.\n");
936 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotProfitable", Switch)
937 <<
"Duplication cost exceeds the cost threshold (cost="
938 <<
ore::NV(
"Cost", DuplicationCost)
945 return OptimizationRemark(
DEBUG_TYPE,
"JumpThreaded", Switch)
946 <<
"Switch statement jump-threaded.";
953 void createAllExitPaths() {
954 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager);
957 BasicBlock *SwitchBlock = SwitchPaths->getSwitchBlock();
958 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
962 TPath.push_front(SwitchBlock);
966 DuplicateBlockMap DuplicateMap;
969 SmallPtrSet<BasicBlock *, 16> BlocksToClean;
972 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
973 createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, &DTU);
979 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths())
980 updateLastSuccessor(TPath, DuplicateMap, &DTU);
986 for (BasicBlock *BB : BlocksToClean)
996 void createExitPath(DefMap &NewDefs, ThreadingPath &Path,
997 DuplicateBlockMap &DuplicateMap,
998 SmallPtrSet<BasicBlock *, 16> &BlocksToClean,
999 DomTreeUpdater *DTU) {
1000 APInt NextState =
Path.getExitValue();
1002 PathType PathBBs =
Path.getPath();
1005 if (PathBBs.front() == Determinator)
1006 PathBBs.pop_front();
1008 auto DetIt =
llvm::find(PathBBs, Determinator);
1011 BasicBlock *PrevBB = PathBBs.size() == 1 ? *DetIt : *std::prev(DetIt);
1012 for (
auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
1014 BlocksToClean.
insert(BB);
1018 BasicBlock *NextBB = getClonedBB(BB, NextState, DuplicateMap);
1020 updatePredecessor(PrevBB, BB, NextBB, DTU);
1026 BasicBlock *NewBB = cloneBlockAndUpdatePredecessor(
1027 BB, PrevBB, NextState, DuplicateMap, NewDefs, DTU);
1028 DuplicateMap[BB].push_back({NewBB, NextState});
1029 BlocksToClean.
insert(NewBB);
1040 void updateSSA(DefMap &NewDefs) {
1041 SSAUpdaterBulk SSAUpdate;
1042 SmallVector<Use *, 16> UsesToRename;
1044 for (
const auto &KV : NewDefs) {
1047 std::vector<Instruction *> Cloned = KV.second;
1051 for (Use &U :
I->uses()) {
1054 if (UserPN->getIncomingBlock(U) == BB)
1056 }
else if (
User->getParent() == BB) {
1065 if (UsesToRename.
empty())
1073 unsigned VarNum = SSAUpdate.
AddVariable(
I->getName(),
I->getType());
1075 for (Instruction *New : Cloned)
1078 while (!UsesToRename.
empty())
1092 BasicBlock *cloneBlockAndUpdatePredecessor(BasicBlock *BB, BasicBlock *PrevBB,
1093 const APInt &NextState,
1094 DuplicateBlockMap &DuplicateMap,
1096 DomTreeUpdater *DTU) {
1104 for (Instruction &
I : *NewBB) {
1113 AC->registerAssumption(
II);
1116 updateSuccessorPhis(BB, NewBB, NextState, VMap, DuplicateMap);
1117 updatePredecessor(PrevBB, BB, NewBB, DTU);
1118 updateDefMap(NewDefs, VMap);
1121 SmallPtrSet<BasicBlock *, 4> SuccSet;
1123 if (SuccSet.
insert(SuccBB).second)
1124 DTU->
applyUpdates({{DominatorTree::Insert, NewBB, SuccBB}});
1134 void updateSuccessorPhis(BasicBlock *BB, BasicBlock *ClonedBB,
1136 DuplicateBlockMap &DuplicateMap) {
1137 std::vector<BasicBlock *> BlocksToUpdate;
1141 if (BB == SwitchPaths->getSwitchBlock()) {
1142 SwitchInst *
Switch = SwitchPaths->getSwitchInst();
1143 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1144 BlocksToUpdate.push_back(NextCase);
1145 BasicBlock *ClonedSucc = getClonedBB(NextCase, NextState, DuplicateMap);
1147 BlocksToUpdate.push_back(ClonedSucc);
1152 BlocksToUpdate.push_back(Succ);
1157 BasicBlock *ClonedSucc = getClonedBB(Succ, NextState, DuplicateMap);
1159 BlocksToUpdate.push_back(ClonedSucc);
1166 for (BasicBlock *Succ : BlocksToUpdate) {
1169 Value *Incoming =
Phi->getIncomingValueForBlock(BB);
1172 Phi->addIncoming(Incoming, ClonedBB);
1175 Value *ClonedVal = VMap[Incoming];
1177 Phi->addIncoming(ClonedVal, ClonedBB);
1179 Phi->addIncoming(Incoming, ClonedBB);
1187 void updatePredecessor(BasicBlock *PrevBB, BasicBlock *OldBB,
1188 BasicBlock *NewBB, DomTreeUpdater *DTU) {
1191 if (!isPredecessor(OldBB, PrevBB))
1201 DTU->
applyUpdates({{DominatorTree::Delete, PrevBB, OldBB},
1202 {DominatorTree::Insert, PrevBB, NewBB}});
1211 for (
auto Entry : VMap) {
1223 NewDefsVector.
push_back({Inst, Cloned});
1227 sort(NewDefsVector, [](
const auto &
LHS,
const auto &
RHS) {
1228 if (
LHS.first ==
RHS.first)
1229 return LHS.second->comesBefore(
RHS.second);
1230 return LHS.first->comesBefore(
RHS.first);
1233 for (
const auto &KV : NewDefsVector)
1234 NewDefs[KV.first].push_back(KV.second);
1242 void updateLastSuccessor(ThreadingPath &TPath,
1243 DuplicateBlockMap &DuplicateMap,
1244 DomTreeUpdater *DTU) {
1245 APInt NextState = TPath.getExitValue();
1247 BasicBlock *LastBlock = getClonedBB(BB, NextState, DuplicateMap);
1254 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1256 std::vector<DominatorTree::UpdateType> DTUpdates;
1257 SmallPtrSet<BasicBlock *, 4> SuccSet;
1258 for (BasicBlock *Succ :
successors(LastBlock)) {
1259 if (Succ != NextCase && SuccSet.
insert(Succ).second)
1260 DTUpdates.push_back({DominatorTree::Delete, LastBlock, Succ});
1263 Switch->eraseFromParent();
1271 void cleanPhiNodes(BasicBlock *BB) {
1274 std::vector<PHINode *> PhiToRemove;
1276 PhiToRemove.push_back(Phi);
1278 for (PHINode *PN : PhiToRemove) {
1280 PN->eraseFromParent();
1287 std::vector<BasicBlock *> BlocksToRemove;
1288 for (BasicBlock *IncomingBB :
Phi->blocks()) {
1289 if (!isPredecessor(BB, IncomingBB))
1290 BlocksToRemove.push_back(IncomingBB);
1292 for (BasicBlock *BB : BlocksToRemove)
1293 Phi->removeIncomingValue(BB);
1299 BasicBlock *getClonedBB(BasicBlock *BB,
const APInt &NextState,
1300 DuplicateBlockMap &DuplicateMap) {
1301 CloneList ClonedBBs = DuplicateMap[BB];
1305 auto It =
llvm::find_if(ClonedBBs, [NextState](
const ClonedBlock &
C) {
1306 return C.State == NextState;
1308 return It != ClonedBBs.end() ? (*It).BB :
nullptr;
1313 BasicBlock *getNextCaseSuccessor(SwitchInst *Switch,
const APInt &NextState) {
1315 for (
auto Case :
Switch->cases()) {
1316 if (Case.getCaseValue()->getValue() == NextState) {
1317 NextCase = Case.getCaseSuccessor();
1322 NextCase =
Switch->getDefaultDest();
1327 bool isPredecessor(BasicBlock *BB, BasicBlock *IncomingBB) {
1331 AllSwitchPaths *SwitchPaths;
1333 AssumptionCache *AC;
1334 TargetTransformInfo *TTI;
1335 OptimizationRemarkEmitter *ORE;
1336 SmallPtrSet<const Value *, 32> EphValues;
1337 std::vector<ThreadingPath> TPaths;
1340bool DFAJumpThreading::run(
Function &
F) {
1341 LLVM_DEBUG(
dbgs() <<
"\nDFA Jump threading: " <<
F.getName() <<
"\n");
1343 if (
F.hasOptSize()) {
1344 LLVM_DEBUG(
dbgs() <<
"Skipping due to the 'minsize' attribute\n");
1352 bool MadeChanges =
false;
1353 LoopInfoBroken =
false;
1355 for (BasicBlock &BB :
F) {
1361 <<
" is a candidate\n");
1362 MainSwitch
Switch(SI, LI, ORE);
1364 if (!
Switch.getInstr()) {
1366 <<
"candidate for jump threading\n");
1371 <<
"candidate for jump threading\n");
1374 unfoldSelectInstrs(DT,
Switch.getSelectInsts());
1375 if (!
Switch.getSelectInsts().empty())
1378 AllSwitchPaths SwitchPaths(&Switch, ORE, LI,
1382 if (SwitchPaths.getNumThreadingPaths() > 0) {
1399 SmallPtrSet<const Value *, 32> EphValues;
1400 if (ThreadableLoops.
size() > 0)
1403 for (AllSwitchPaths SwitchPaths : ThreadableLoops) {
1404 TransformDFA Transform(&SwitchPaths, DT, AC,
TTI, ORE, EphValues);
1407 LoopInfoBroken =
true;
1410#ifdef EXPENSIVE_CHECKS
1411 assert(DT->
verify(DominatorTree::VerificationLevel::Full));
1428 DFAJumpThreading ThreadImpl(&AC, &DT, &LI, &
TTI, &ORE);
1429 if (!ThreadImpl.run(
F))
1434 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 const Function * getParent(const Value *V)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
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))
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))
static cl::opt< bool > ClViewCfgBefore("dfa-jump-view-cfg-before", cl::desc("View the CFG before DFA Jump Threading"), cl::Hidden, cl::init(false))
static cl::opt< unsigned > CostThreshold("dfa-cost-threshold", cl::desc("Maximum cost accepted for the transformation"), cl::Hidden, cl::init(50))
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))
static cl::opt< unsigned > MaxNumPaths("dfa-max-num-paths", cl::desc("Max number of paths enumerated around a switch"), cl::Hidden, cl::init(200))
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 Basic Block Representation.
iterator begin()
Instruction iterator methods.
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.
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.
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
Analysis pass which computes a DominatorTree.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
static constexpr UpdateKind Delete
static constexpr UpdateKind Insert
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
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.
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.
Represents a single loop in the control flow graph.
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
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)
Analysis pass providing the TargetTransformInfo.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
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.
A raw_ostream that writes to an std::string.
@ 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.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
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.
auto pred_size(const MachineBasicBlock *BB)
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...
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)
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.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
bool pred_empty(const BasicBlock *BB)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
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.