83#ifdef EXPENSIVE_CHECKS
89#define DEBUG_TYPE "dfa-jump-threading"
91STATISTIC(NumTransforms,
"Number of transformations done");
93STATISTIC(NumPaths,
"Number of individual paths threaded");
96class SelectInstToUnfold {
103 SelectInst *getInst() {
return SI; }
104 PHINode *getUse() {
return SIUse; }
106 explicit operator bool()
const {
return SI && SIUse; }
109class DFAJumpThreading {
111 DFAJumpThreading(
const ScalarOptions &Opts, AssumptionCache *AC,
112 DomTreeUpdater *DTU, LoopInfo *LI, TargetTransformInfo *TTI,
113 OptimizationRemarkEmitter *ORE)
114 : Opts(Opts), AC(AC), DTU(DTU), LI(LI), TTI(TTI), ORE(ORE) {}
124 while (!
Stack.empty()) {
125 SelectInstToUnfold SIToUnfold =
Stack.pop_back_val();
127 std::vector<SelectInstToUnfold> NewSIsToUnfold;
128 std::vector<BasicBlock *> NewBBs;
129 unfold(DTU, LI, SIToUnfold, &NewSIsToUnfold, &NewBBs);
136 static void unfold(DomTreeUpdater *DTU, LoopInfo *LI,
137 SelectInstToUnfold SIToUnfold,
138 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
139 std::vector<BasicBlock *> *NewBBs);
141 const ScalarOptions &Opts;
145 TargetTransformInfo *TTI;
146 OptimizationRemarkEmitter *ORE;
158 SelectInstToUnfold SIToUnfold,
159 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
160 std::vector<BasicBlock *> *NewBBs) {
161 SelectInst *
SI = SIToUnfold.getInst();
162 PHINode *SIUse = SIToUnfold.getUse();
167 if (UncondBrInst *StartBlockTerm =
172 SI->getContext(), Twine(
SI->getName(),
".si.unfold.false"),
174 NewBBs->push_back(NewBlock);
180 StartBlockTerm->getDebugLoc(),
SI->getDebugLoc());
183 DTU->
applyUpdates({{DominatorTree::Insert, NewBlock, EndBlock}});
190 Value *SIOp1 =
SI->getTrueValue();
191 Value *SIOp2 =
SI->getFalseValue();
194 Twine(SIOp2->
getName(),
".si.unfold.phi"),
199 for (PHINode &Phi : EndBlock->
phis()) {
202 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlock);
211 Twine(
SI->getName(),
".si.unfold.phi"),
214 if (
Pred != StartBlock &&
Pred != NewBlock)
225 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, SIUse));
227 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, NewPhi));
230 StartBlockTerm->eraseFromParent();
233 BI->setDebugLoc(SelectBranchLoc);
234 BI->setMetadata(LLVMContext::MD_prof,
235 SI->getMetadata(LLVMContext::MD_prof));
236 DTU->
applyUpdates({{DominatorTree::Insert, StartBlock, NewBlock}});
240 SI->getContext(), Twine(
SI->getName(),
".si.unfold.true"),
243 SI->getContext(), Twine(
SI->getName(),
".si.unfold.false"),
246 NewBBs->push_back(NewBlockT);
247 NewBBs->push_back(NewBlockF);
275 BI->setDebugLoc(SelectLoc);
276 BI->setMetadata(LLVMContext::MD_prof,
277 SI->getMetadata(LLVMContext::MD_prof));
278 DTU->
applyUpdates({{DominatorTree::Insert, NewBlockT, NewBlockF},
279 {DominatorTree::Insert, NewBlockT, EndBlock},
280 {DominatorTree::Insert, NewBlockF, EndBlock}});
295 NewSIsToUnfold->push_back(SelectInstToUnfold(TrueSI, NewPhiT));
297 NewSIsToUnfold->push_back(SelectInstToUnfold(FalseSi, NewPhiF));
304 for (PHINode &Phi : EndBlock->
phis()) {
307 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlockT);
308 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlockF);
309 Phi.removeIncomingValue(StartBlock);
315 unsigned SuccNum = CondBr->
getSuccessor(1) == EndBlock ? 1 : 0;
317 DTU->
applyUpdates({{DominatorTree::Delete, StartBlock, EndBlock},
318 {DominatorTree::Insert, StartBlock, NewBlockT}});
323 for (BasicBlock *NewBB : *NewBBs)
324 L->addBasicBlockToLoop(NewBB, *LI);
328 assert(
SI->use_empty() &&
"Select must be dead now");
329 SI->eraseFromParent();
356 OS <<
"< " <<
llvm::join(BBNames,
", ") <<
" >";
365struct ThreadingPath {
367 APInt getExitValue()
const {
return ExitVal; }
368 void setExitValue(
const ConstantInt *
V) { ExitVal =
V->getValue(); }
369 void setExitValue(
const APInt &
V) { ExitVal =
V; }
372 const BasicBlock *getDeterminatorBB()
const {
return DBB; }
373 void setDeterminator(
const BasicBlock *BB) { DBB = BB; }
376 const PathType &getPath()
const {
return Path; }
377 void setPath(
const PathType &NewPath) { Path = NewPath; }
378 void push_back(BasicBlock *BB) { Path.push_back(BB); }
379 void push_front(BasicBlock *BB) { Path.push_front(BB); }
380 void appendExcludingFirst(
const PathType &OtherPath) {
384 void print(raw_ostream &OS)
const {
395inline raw_ostream &
operator<<(raw_ostream &OS,
const ThreadingPath &TPath) {
402 MainSwitch(
const ScalarOptions &Opts, SwitchInst *SI, LoopInfo *LI,
403 OptimizationRemarkEmitter *ORE)
409 return OptimizationRemarkMissed(
DEBUG_TYPE,
"SwitchNotPredictable", SI)
410 <<
"Switch instruction is not predictable.";
415 virtual ~MainSwitch() =
default;
417 SwitchInst *getInstr()
const {
return Instr; }
427 bool isCandidate(
const SwitchInst *SI,
const ScalarOptions &Opts) {
428 std::deque<std::pair<Value *, BasicBlock *>> Q;
429 SmallPtrSet<Value *, 16> SeenValues;
432 Value *SICond =
SI->getCondition();
442 addToQueue(SICond,
nullptr, Q, SeenValues);
445 Value *Current = Q.front().first;
446 BasicBlock *CurrentIncomingBB = Q.front().second;
450 for (BasicBlock *IncomingBB :
Phi->blocks()) {
451 Value *Incoming =
Phi->getIncomingValueForBlock(IncomingBB);
452 addToQueue(Incoming, IncomingBB, Q, SeenValues);
456 if (!isValidSelectInst(SelI))
458 addToQueue(SelI->getTrueValue(), CurrentIncomingBB, Q, SeenValues);
459 addToQueue(SelI->getFalseValue(), CurrentIncomingBB, Q, SeenValues);
462 SelectInsts.push_back(SelectInstToUnfold(SelI, SelIUse));
477 if (Opts.dfa_early_exit_heuristic &&
480 <<
"\tExiting early due to unpredictability heuristic.\n");
491 void addToQueue(
Value *Val, BasicBlock *BB,
492 std::deque<std::pair<Value *, BasicBlock *>> &Q,
493 SmallPtrSet<Value *, 16> &SeenValues) {
494 if (SeenValues.
insert(Val).second)
495 Q.push_back({Val, BB});
498 bool isValidSelectInst(SelectInst *SI) {
499 if (!
SI->hasOneUse())
524 for (SelectInstToUnfold SIToUnfold : SelectInsts) {
525 SelectInst *PrevSI = SIToUnfold.getInst();
535 SwitchInst *Instr =
nullptr;
539struct AllSwitchPaths {
540 AllSwitchPaths(
const ScalarOptions &Opts,
const MainSwitch *MSwitch,
541 OptimizationRemarkEmitter *ORE, LoopInfo *LI,
Loop *L)
542 : Opts(Opts), Switch(MSwitch->getInstr()),
543 SwitchBlock(Switch->
getParent()), ORE(ORE), LI(LI), SwitchOuterLoop(
L) {
546 std::vector<ThreadingPath> &getThreadingPaths() {
return TPaths; }
547 unsigned getNumThreadingPaths() {
return TPaths.size(); }
548 SwitchInst *getSwitchInst() {
return Switch; }
549 BasicBlock *getSwitchBlock() {
return SwitchBlock; }
559 typedef DenseMap<const BasicBlock *, const PHINode *> StateDefMap;
560 std::vector<ThreadingPath> getPathsFromStateDefMap(StateDefMap &StateDef,
563 unsigned PathsLimit) {
564 std::vector<ThreadingPath> Res;
565 auto *PhiBB =
Phi->getParent();
569 for (
auto *IncomingBB :
Phi->blocks()) {
570 if (Res.size() >= PathsLimit)
572 if (!UniqueBlocks.
insert(IncomingBB).second)
574 if (!SwitchOuterLoop->
contains(IncomingBB))
577 Value *IncomingValue =
Phi->getIncomingValueForBlock(IncomingBB);
581 if (PhiBB == SwitchBlock &&
584 ThreadingPath NewPath;
585 NewPath.setDeterminator(PhiBB);
586 NewPath.setExitValue(
C);
588 if (IncomingBB != SwitchBlock) {
592 NewPath.push_back(IncomingBB);
594 NewPath.push_back(PhiBB);
595 Res.push_back(NewPath);
599 if (VB.
contains(IncomingBB) || IncomingBB == SwitchBlock)
605 auto *IncomingPhiDefBB = IncomingPhi->getParent();
606 if (!StateDef.contains(IncomingPhiDefBB))
610 if (IncomingPhiDefBB == IncomingBB) {
611 assert(PathsLimit > Res.size());
612 std::vector<ThreadingPath> PredPaths = getPathsFromStateDefMap(
613 StateDef, IncomingPhi, VB, PathsLimit - Res.size());
614 for (ThreadingPath &Path : PredPaths) {
615 Path.push_back(PhiBB);
616 Res.push_back(std::move(Path));
626 assert(PathsLimit > Res.size());
627 auto InterPathLimit = PathsLimit - Res.size();
628 IntermediatePaths = paths(IncomingPhiDefBB, IncomingBB, VB,
630 if (IntermediatePaths.empty())
633 assert(InterPathLimit >= IntermediatePaths.size());
634 auto PredPathLimit = InterPathLimit / IntermediatePaths.size();
635 std::vector<ThreadingPath> PredPaths =
636 getPathsFromStateDefMap(StateDef, IncomingPhi, VB, PredPathLimit);
637 for (
const ThreadingPath &Path : PredPaths) {
638 for (
const PathType &IPath : IntermediatePaths) {
639 ThreadingPath NewPath(Path);
640 NewPath.appendExcludingFirst(IPath);
641 NewPath.push_back(PhiBB);
642 Res.push_back(NewPath);
651 unsigned PathDepth,
unsigned PathsLimit) {
655 if (PathDepth > Opts.dfa_max_path_length) {
657 return OptimizationRemarkAnalysis(
DEBUG_TYPE,
"MaxPathLengthReached",
659 <<
"Exploration stopped after visiting MaxPathLength="
660 <<
ore::NV(
"MaxPathLength", Opts.dfa_max_path_length)
667 if (++NumVisited > Opts.dfa_max_num_visited_paths)
677 SmallPtrSet<BasicBlock *, 4> Successors;
679 if (Res.size() >= PathsLimit)
681 if (!Successors.
insert(Succ).second)
686 Res.push_back({BB, ToBB});
696 if (Succ == CurrLoop->getHeader())
702 assert(PathsLimit > Res.size());
704 paths(Succ, ToBB, Visited, PathDepth + 1, PathsLimit - Res.size());
719 StateDefMap getStateDefMap()
const {
721 DenseSet<const BasicBlock *> MultipleDefBBs;
723 assert(FirstDef &&
"The first definition must be a phi.");
726 Stack.push_back(FirstDef);
727 SmallPtrSet<Value *, 16> SeenValues;
729 while (!
Stack.empty()) {
730 PHINode *CurPhi =
Stack.pop_back_val();
733 auto [
_,
Inserted] = Res.try_emplace(CurDefBlock, CurPhi);
735 MultipleDefBBs.
insert(CurDefBlock);
737 SeenValues.
insert(CurPhi);
739 for (BasicBlock *IncomingBB : CurPhi->
blocks()) {
740 PHINode *IncomingPhi =
744 bool IsOutsideLoops = !SwitchOuterLoop->
contains(IncomingBB);
745 if (SeenValues.
contains(IncomingPhi) || IsOutsideLoops)
748 Stack.push_back(IncomingPhi);
758 for (
auto *BB : MultipleDefBBs) {
759 LLVM_DEBUG(
dbgs() <<
"Not a state-defining block: Multiple defs in "
768 StateDefMap StateDef = getStateDefMap();
769 if (StateDef.empty()) {
771 return OptimizationRemarkMissed(
DEBUG_TYPE,
"SwitchNotPredictable",
773 <<
"Switch instruction is not predictable.";
779 auto *SwitchPhiDefBB = SwitchPhi->getParent();
782 std::vector<ThreadingPath> PathsToPhiDef = getPathsFromStateDefMap(
783 StateDef, SwitchPhi, VB, Opts.dfa_max_num_paths);
784 if (SwitchPhiDefBB == SwitchBlock || PathsToPhiDef.empty()) {
785 TPaths = std::move(PathsToPhiDef);
789 assert(Opts.dfa_max_num_paths >= PathsToPhiDef.size() &&
790 !PathsToPhiDef.empty());
791 auto PathsLimit = Opts.dfa_max_num_paths / PathsToPhiDef.size();
794 paths(SwitchPhiDefBB, SwitchBlock, VB, 1, PathsLimit);
795 if (PathsToSwitchBB.empty())
798 std::vector<ThreadingPath> TempList;
799 for (
const ThreadingPath &Path : PathsToPhiDef) {
800 SmallPtrSet<BasicBlock *, 32> PathSet(
Path.getPath().begin(),
801 Path.getPath().end());
802 for (
const PathType &PathToSw : PathsToSwitchBB) {
804 [&](
const BasicBlock *BB) {
return PathSet.contains(BB); }))
806 ThreadingPath PathCopy(Path);
807 PathCopy.appendExcludingFirst(PathToSw);
808 TempList.push_back(PathCopy);
811 TPaths = std::move(TempList);
816 BasicBlock *getNextCaseSuccessor(
const APInt &NextState) {
818 if (CaseValToDest.empty()) {
819 for (
auto Case : Switch->
cases()) {
820 APInt CaseVal = Case.getCaseValue()->getValue();
821 CaseValToDest[CaseVal] = Case.getCaseSuccessor();
825 auto SuccIt = CaseValToDest.find(NextState);
833 SmallDenseMap<BasicBlock *, APInt> DestToState;
834 for (ThreadingPath &Path : TPaths) {
835 APInt NextState =
Path.getExitValue();
836 BasicBlock *Dest = getNextCaseSuccessor(NextState);
840 if (NextState != StateIt->second) {
841 LLVM_DEBUG(
dbgs() <<
"Next state in " << Path <<
" is equivalent to "
842 << StateIt->second <<
"\n");
843 Path.setExitValue(StateIt->second);
848 const ScalarOptions &Opts;
849 unsigned NumVisited = 0;
852 OptimizationRemarkEmitter *ORE;
853 std::vector<ThreadingPath> TPaths;
854 DenseMap<APInt, BasicBlock *> CaseValToDest;
856 Loop *SwitchOuterLoop;
860 TransformDFA(
const ScalarOptions &Opts, AllSwitchPaths *SwitchPaths,
861 DomTreeUpdater *DTU, AssumptionCache *AC,
862 TargetTransformInfo *
TTI, OptimizationRemarkEmitter *ORE,
863 SmallPtrSet<const Value *, 32> EphValues)
864 : Opts(Opts), SwitchPaths(SwitchPaths), DTU(DTU), AC(AC),
TTI(
TTI),
865 ORE(ORE), EphValues(EphValues) {}
868 if (isLegalAndProfitableToTransform()) {
869 createAllExitPaths();
881 bool isLegalAndProfitableToTransform() {
884 SwitchInst *
Switch = SwitchPaths->getSwitchInst();
887 if (
Switch->getNumSuccessors() <= 1)
893 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
895 APInt NextState = TPath.getExitValue();
896 const BasicBlock *Determinator = TPath.getDeterminatorBB();
899 BasicBlock *BB = SwitchPaths->getSwitchBlock();
900 BasicBlock *VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
902 Metrics.analyzeBasicBlock(BB, *
TTI, EphValues);
903 NumClonedInst += BB->
size();
904 DuplicateMap[BB].push_back({BB, NextState});
909 if (PathBBs.front() == Determinator)
914 auto DetIt =
llvm::find(PathBBs, Determinator);
915 for (
auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
917 VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
920 Metrics.analyzeBasicBlock(BB, *
TTI, EphValues);
921 NumClonedInst += BB->
size();
922 DuplicateMap[BB].push_back({BB, NextState});
926 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
927 <<
"non-duplicatable instructions.\n");
929 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NonDuplicatableInst",
931 <<
"Contains non-duplicatable instructions.";
937 if (
Metrics.Convergence != ConvergenceKind::None) {
938 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
939 <<
"convergent instructions.\n");
941 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ConvergentInst", Switch)
942 <<
"Contains convergent instructions.";
947 if (!
Metrics.NumInsts.isValid()) {
948 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
949 <<
"instructions with invalid cost.\n");
951 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ConvergentInst", Switch)
952 <<
"Contains instructions with invalid cost.";
963 for (
auto *BB : DuplicateMap.
keys()) {
964 NumOrigInst += BB->
size();
968 if (!DuplicateMap.
count(Succ) && Succ->getSinglePredecessor())
972 if (
double(NumClonedInst) /
double(NumOrigInst) >
973 Opts.dfa_max_cloned_rate) {
974 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, too much "
975 "instructions wll be cloned\n");
977 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotProfitable", Switch)
978 <<
"Too much instructions will be cloned.";
987 if (NumOuterUseBlock > Opts.dfa_max_out_use_blocks) {
988 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, too much "
989 "blocks with outer uses\n");
991 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotProfitable", Switch)
992 <<
"Too much blocks with outer uses.";
999 unsigned JumpTableSize = 0;
1002 if (JumpTableSize == 0) {
1006 unsigned CondBranches =
1007 APInt(32,
Switch->getNumSuccessors()).ceilLogBase2();
1008 assert(CondBranches > 0 &&
1009 "The threaded switch must have multiple branches");
1010 DuplicationCost =
Metrics.NumInsts / CondBranches;
1018 DuplicationCost =
Metrics.NumInsts / JumpTableSize;
1021 LLVM_DEBUG(
dbgs() <<
"\nDFA Jump Threading: Cost to jump thread block "
1022 << SwitchPaths->getSwitchBlock()->getName()
1023 <<
" is: " << DuplicationCost <<
"\n\n");
1025 if (DuplicationCost > Opts.dfa_cost_threshold) {
1026 LLVM_DEBUG(
dbgs() <<
"Not jump threading, duplication cost exceeds the "
1027 <<
"cost threshold.\n");
1029 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotProfitable", Switch)
1030 <<
"Duplication cost exceeds the cost threshold (cost="
1031 <<
ore::NV(
"Cost", DuplicationCost) <<
", threshold="
1032 <<
ore::NV(
"Threshold", Opts.dfa_cost_threshold) <<
").";
1038 return OptimizationRemark(
DEBUG_TYPE,
"JumpThreaded", Switch)
1039 <<
"Switch statement jump-threaded.";
1046 void createAllExitPaths() {
1048 BasicBlock *SwitchBlock = SwitchPaths->getSwitchBlock();
1049 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
1053 TPath.push_front(SwitchBlock);
1060 SmallSetVector<BasicBlock *, 16> BlocksToClean;
1063 for (
const ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
1064 createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, DTU);
1070 for (
const ThreadingPath &TPath : SwitchPaths->getThreadingPaths())
1071 updateLastSuccessor(TPath, DuplicateMap, DTU);
1077 for (BasicBlock *BB : BlocksToClean)
1087 void createExitPath(
DefMap &NewDefs,
const ThreadingPath &Path,
1089 SmallSetVector<BasicBlock *, 16> &BlocksToClean,
1090 DomTreeUpdater *DTU) {
1091 APInt NextState =
Path.getExitValue();
1096 if (PathBBs.front() == Determinator)
1097 PathBBs.pop_front();
1099 auto DetIt =
llvm::find(PathBBs, Determinator);
1102 BasicBlock *PrevBB = PathBBs.size() == 1 ? *DetIt : *std::prev(DetIt);
1103 for (
auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
1105 BlocksToClean.
insert(BB);
1109 BasicBlock *NextBB = getClonedBB(BB, NextState, DuplicateMap);
1111 updatePredecessor(PrevBB, BB, NextBB, DTU);
1117 BasicBlock *NewBB = cloneBlockAndUpdatePredecessor(
1118 BB, PrevBB, NextState, DuplicateMap, NewDefs, DTU);
1119 DuplicateMap[BB].push_back({NewBB, NextState});
1120 BlocksToClean.
insert(NewBB);
1132 SSAUpdaterBulk SSAUpdate;
1133 SmallVector<Use *, 16> UsesToRename;
1135 for (
const auto &KV : NewDefs) {
1138 std::vector<Instruction *> Cloned = KV.second;
1142 for (Use &U :
I->uses()) {
1145 if (UserPN->getIncomingBlock(U) == BB)
1147 }
else if (
User->getParent() == BB) {
1156 if (UsesToRename.
empty())
1164 unsigned VarNum = SSAUpdate.
AddVariable(
I->getName(),
I->getType());
1166 for (Instruction *New : Cloned)
1169 while (!UsesToRename.
empty())
1183 static BasicBlock *getNextCaseSuccessor(SwitchInst *Switch,
1184 const APInt &NextState) {
1186 for (
auto Case :
Switch->cases()) {
1187 if (Case.getCaseValue()->getValue() == NextState) {
1188 NextCase = Case.getCaseSuccessor();
1193 NextCase =
Switch->getDefaultDest();
1201 BasicBlock *cloneBlockAndUpdatePredecessor(BasicBlock *BB, BasicBlock *PrevBB,
1202 const APInt &NextState,
1205 DomTreeUpdater *DTU) {
1219 for (Instruction &
I : *NewBB) {
1231 updateSuccessorPhis(BB, NewBB, NextState, VMap, DuplicateMap);
1232 updatePredecessor(PrevBB, BB, NewBB, DTU);
1233 updateDefMap(NewDefs, VMap);
1236 SmallPtrSet<BasicBlock *, 4> SuccSet;
1238 if (SuccSet.
insert(SuccBB).second)
1239 DTU->
applyUpdates({{DominatorTree::Insert, NewBB, SuccBB}});
1249 void updateSuccessorPhis(BasicBlock *BB, BasicBlock *ClonedBB,
1252 std::vector<BasicBlock *> BlocksToUpdate;
1256 if (BB == SwitchPaths->getSwitchBlock()) {
1257 SwitchInst *
Switch = SwitchPaths->getSwitchInst();
1258 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1259 BlocksToUpdate.push_back(NextCase);
1260 BasicBlock *ClonedSucc = getClonedBB(NextCase, NextState, DuplicateMap);
1262 BlocksToUpdate.push_back(ClonedSucc);
1267 BlocksToUpdate.push_back(Succ);
1272 BasicBlock *ClonedSucc = getClonedBB(Succ, NextState, DuplicateMap);
1274 BlocksToUpdate.push_back(ClonedSucc);
1281 for (BasicBlock *Succ : BlocksToUpdate) {
1282 for (PHINode &Phi : Succ->phis()) {
1283 Value *Incoming =
Phi.getIncomingValueForBlock(BB);
1286 Phi.addIncoming(Incoming, ClonedBB);
1289 Value *ClonedVal = VMap[Incoming];
1291 Phi.addIncoming(ClonedVal, ClonedBB);
1293 Phi.addIncoming(Incoming, ClonedBB);
1301 void updatePredecessor(BasicBlock *PrevBB, BasicBlock *OldBB,
1302 BasicBlock *NewBB, DomTreeUpdater *DTU) {
1305 if (!isPredecessor(OldBB, PrevBB))
1315 DTU->
applyUpdates({{DominatorTree::Delete, PrevBB, OldBB},
1316 {DominatorTree::Insert, PrevBB, NewBB}});
1325 for (
auto Entry : VMap) {
1328 if (!Inst || !
Entry.second ||
1336 NewDefsVector.
push_back({Inst, Cloned});
1340 sort(NewDefsVector, [](
const auto &
LHS,
const auto &
RHS) {
1341 if (
LHS.first ==
RHS.first)
1342 return LHS.second->comesBefore(
RHS.second);
1343 return LHS.first->comesBefore(
RHS.first);
1346 for (
const auto &KV : NewDefsVector)
1347 NewDefs[KV.first].push_back(KV.second);
1355 void updateLastSuccessor(
const ThreadingPath &TPath,
1357 DomTreeUpdater *DTU) {
1358 APInt NextState = TPath.getExitValue();
1360 BasicBlock *LastBlock = getClonedBB(BB, NextState, DuplicateMap);
1367 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1369 std::vector<DominatorTree::UpdateType> DTUpdates;
1370 SmallPtrSet<BasicBlock *, 4> SuccSet;
1371 for (BasicBlock *Succ :
successors(LastBlock)) {
1372 if (Succ != NextCase && SuccSet.
insert(Succ).second)
1373 DTUpdates.push_back({DominatorTree::Delete, LastBlock, Succ});
1377 Switch->eraseFromParent();
1385 void cleanPhiNodes(BasicBlock *BB) {
1390 PN.eraseFromParent();
1396 for (PHINode &Phi : BB->
phis())
1397 Phi.removeIncomingValueIf([&](
unsigned Index) {
1399 return !isPredecessor(BB, IncomingBB);
1405 BasicBlock *getClonedBB(BasicBlock *BB,
const APInt &NextState,
1411 auto It =
llvm::find_if(ClonedBBs, [NextState](
const ClonedBlock &
C) {
1412 return C.State == NextState;
1414 return It != ClonedBBs.end() ? (*It).BB :
nullptr;
1418 bool isPredecessor(BasicBlock *BB, BasicBlock *IncomingBB) {
1422 const ScalarOptions &Opts;
1423 AllSwitchPaths *SwitchPaths;
1424 DomTreeUpdater *DTU;
1425 AssumptionCache *AC;
1426 TargetTransformInfo *
TTI;
1427 OptimizationRemarkEmitter *ORE;
1428 SmallPtrSet<const Value *, 32> EphValues;
1432bool DFAJumpThreading::run(
Function &
F) {
1433 LLVM_DEBUG(
dbgs() <<
"\nDFA Jump threading: " <<
F.getName() <<
"\n");
1435 if (
F.hasOptSize()) {
1436 LLVM_DEBUG(
dbgs() <<
"Skipping due to the 'minsize' attribute\n");
1440 if (Opts.dfa_jump_view_cfg_before)
1444 bool MadeChanges =
false;
1445 LoopInfoBroken =
false;
1447 for (BasicBlock &BB :
F) {
1453 <<
" is a candidate\n");
1454 MainSwitch
Switch(Opts, SI, LI, ORE);
1456 if (!
Switch.getInstr()) {
1458 <<
"candidate for jump threading\n");
1463 <<
"candidate for jump threading\n");
1466 unfoldSelectInstrs(
Switch.getSelectInsts());
1467 if (!
Switch.getSelectInsts().empty())
1470 AllSwitchPaths SwitchPaths(Opts, &Switch, ORE, LI,
1474 if (SwitchPaths.getNumThreadingPaths() > 0) {
1491 SmallPtrSet<const Value *, 32> EphValues;
1492 if (ThreadableLoops.
size() > 0)
1495 for (AllSwitchPaths SwitchPaths : ThreadableLoops) {
1496 TransformDFA Transform(Opts, &SwitchPaths, DTU, AC,
TTI, ORE, EphValues);
1497 if (Transform.run())
1498 MadeChanges = LoopInfoBroken =
true;
1503#ifdef EXPENSIVE_CHECKS
1509 "Failed to maintain validity of domtree!");
1525 DFAJumpThreading ThreadImpl(Opts, &AC, &DTU, &LI, &
TTI, &ORE);
1526 if (!ThreadImpl.run(
F))
1531 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)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static void updateSSA(DominatorTree &DT, CallBrInst *CBR, CallInst *Intrinsic, SSAUpdater &SSAUpdate)
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
uint64_t IntrinsicInst * II
This file implements a set that has insertion order iteration characteristics.
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 LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
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 BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
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 this loop.
const LoopT * getOutermostLoop() const
Get the outermost loop in which this loop is contained.
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
void insert_range(Range &&R)
bool insert(const value_type &X)
Insert a new element into the SetVector.
bool erase(PtrType Ptr)
Remove pointer from the set.
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.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
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.
std::pair< iterator, bool > insert(const ValueT &V)
const ParentTy * getParent() const
This class implements an extremely fast bulk output stream that can only output to a stream.
@ BasicBlock
Various leaf nodes.
@ 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.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
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)
const ScalarOptions & getScalarOptions(const LLVMContext &C)
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
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...
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
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.
LLVM_ABI void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
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.
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.
LLVM_ABI void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
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).
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Integrate with the new Pass Manager.