LLVM 19.0.0git
DFAJumpThreading.cpp
Go to the documentation of this file.
1//===- DFAJumpThreading.cpp - Threads a switch statement inside a loop ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Transform each threading path to effectively jump thread the DFA. For
10// example, the CFG below could be transformed as follows, where the cloned
11// blocks unconditionally branch to the next correct case based on what is
12// identified in the analysis.
13//
14// sw.bb sw.bb
15// / | \ / | \
16// case1 case2 case3 case1 case2 case3
17// \ | / | | |
18// determinator det.2 det.3 det.1
19// br sw.bb / | \
20// sw.bb.2 sw.bb.3 sw.bb.1
21// br case2 br case3 br case1ยง
22//
23// Definitions and Terminology:
24//
25// * Threading path:
26// a list of basic blocks, the exit state, and the block that determines
27// the next state, for which the following notation will be used:
28// < path of BBs that form a cycle > [ state, determinator ]
29//
30// * Predictable switch:
31// The switch variable is always a known constant so that all conditional
32// jumps based on switch variable can be converted to unconditional jump.
33//
34// * Determinator:
35// The basic block that determines the next state of the DFA.
36//
37// Representing the optimization in C-like pseudocode: the code pattern on the
38// left could functionally be transformed to the right pattern if the switch
39// condition is predictable.
40//
41// X = A goto A
42// for (...) A:
43// switch (X) ...
44// case A goto B
45// X = B B:
46// case B ...
47// X = C goto C
48//
49// The pass first checks that switch variable X is decided by the control flow
50// path taken in the loop; for example, in case B, the next value of X is
51// decided to be C. It then enumerates through all paths in the loop and labels
52// the basic blocks where the next state is decided.
53//
54// Using this information it creates new paths that unconditionally branch to
55// the next case. This involves cloning code, so it only gets triggered if the
56// amount of code duplicated is below a threshold.
57//
58//===----------------------------------------------------------------------===//
59
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/DenseMap.h"
63#include "llvm/ADT/SmallSet.h"
64#include "llvm/ADT/Statistic.h"
71#include "llvm/IR/CFG.h"
72#include "llvm/IR/Constants.h"
75#include "llvm/Support/Debug.h"
79#include <algorithm>
80#include <deque>
81
82#ifdef EXPENSIVE_CHECKS
83#include "llvm/IR/Verifier.h"
84#endif
85
86using namespace llvm;
87
88#define DEBUG_TYPE "dfa-jump-threading"
89
90STATISTIC(NumTransforms, "Number of transformations done");
91STATISTIC(NumCloned, "Number of blocks cloned");
92STATISTIC(NumPaths, "Number of individual paths threaded");
93
94static cl::opt<bool>
95 ClViewCfgBefore("dfa-jump-view-cfg-before",
96 cl::desc("View the CFG before DFA Jump Threading"),
97 cl::Hidden, cl::init(false));
98
100 "dfa-early-exit-heuristic",
101 cl::desc("Exit early if an unpredictable value come from the same loop"),
102 cl::Hidden, cl::init(true));
103
105 "dfa-max-path-length",
106 cl::desc("Max number of blocks searched to find a threading path"),
107 cl::Hidden, cl::init(20));
108
110 MaxNumPaths("dfa-max-num-paths",
111 cl::desc("Max number of paths enumerated around a switch"),
112 cl::Hidden, cl::init(200));
113
115 CostThreshold("dfa-cost-threshold",
116 cl::desc("Maximum cost accepted for the transformation"),
117 cl::Hidden, cl::init(50));
118
119namespace {
120
121class SelectInstToUnfold {
122 SelectInst *SI;
123 PHINode *SIUse;
124
125public:
126 SelectInstToUnfold(SelectInst *SI, PHINode *SIUse) : SI(SI), SIUse(SIUse) {}
127
128 SelectInst *getInst() { return SI; }
129 PHINode *getUse() { return SIUse; }
130
131 explicit operator bool() const { return SI && SIUse; }
132};
133
134void unfold(DomTreeUpdater *DTU, LoopInfo *LI, SelectInstToUnfold SIToUnfold,
135 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
136 std::vector<BasicBlock *> *NewBBs);
137
138class DFAJumpThreading {
139public:
140 DFAJumpThreading(AssumptionCache *AC, DominatorTree *DT, LoopInfo *LI,
142 : AC(AC), DT(DT), LI(LI), TTI(TTI), ORE(ORE) {}
143
144 bool run(Function &F);
145 bool LoopInfoBroken;
146
147private:
148 void
149 unfoldSelectInstrs(DominatorTree *DT,
150 const SmallVector<SelectInstToUnfold, 4> &SelectInsts) {
151 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
153 for (SelectInstToUnfold SIToUnfold : SelectInsts)
154 Stack.push_back(SIToUnfold);
155
156 while (!Stack.empty()) {
157 SelectInstToUnfold SIToUnfold = Stack.pop_back_val();
158
159 std::vector<SelectInstToUnfold> NewSIsToUnfold;
160 std::vector<BasicBlock *> NewBBs;
161 unfold(&DTU, LI, SIToUnfold, &NewSIsToUnfold, &NewBBs);
162
163 // Put newly discovered select instructions into the work list.
164 for (const SelectInstToUnfold &NewSIToUnfold : NewSIsToUnfold)
165 Stack.push_back(NewSIToUnfold);
166 }
167 }
168
169 AssumptionCache *AC;
170 DominatorTree *DT;
171 LoopInfo *LI;
174};
175
176} // end anonymous namespace
177
178namespace {
179
180/// Create a new basic block and sink \p SIToSink into it.
181void createBasicBlockAndSinkSelectInst(
182 DomTreeUpdater *DTU, SelectInst *SI, PHINode *SIUse, SelectInst *SIToSink,
183 BasicBlock *EndBlock, StringRef NewBBName, BasicBlock **NewBlock,
184 BranchInst **NewBranch, std::vector<SelectInstToUnfold> *NewSIsToUnfold,
185 std::vector<BasicBlock *> *NewBBs) {
186 assert(SIToSink->hasOneUse());
187 assert(NewBlock);
188 assert(NewBranch);
189 *NewBlock = BasicBlock::Create(SI->getContext(), NewBBName,
190 EndBlock->getParent(), EndBlock);
191 NewBBs->push_back(*NewBlock);
192 *NewBranch = BranchInst::Create(EndBlock, *NewBlock);
193 SIToSink->moveBefore(*NewBranch);
194 NewSIsToUnfold->push_back(SelectInstToUnfold(SIToSink, SIUse));
195 DTU->applyUpdates({{DominatorTree::Insert, *NewBlock, EndBlock}});
196}
197
198/// Unfold the select instruction held in \p SIToUnfold by replacing it with
199/// control flow.
200///
201/// Put newly discovered select instructions into \p NewSIsToUnfold. Put newly
202/// created basic blocks into \p NewBBs.
203///
204/// TODO: merge it with CodeGenPrepare::optimizeSelectInst() if possible.
205void unfold(DomTreeUpdater *DTU, LoopInfo *LI, SelectInstToUnfold SIToUnfold,
206 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
207 std::vector<BasicBlock *> *NewBBs) {
208 SelectInst *SI = SIToUnfold.getInst();
209 PHINode *SIUse = SIToUnfold.getUse();
210 BasicBlock *StartBlock = SI->getParent();
211 BasicBlock *EndBlock = SIUse->getParent();
212 BranchInst *StartBlockTerm =
213 dyn_cast<BranchInst>(StartBlock->getTerminator());
214
215 assert(StartBlockTerm && StartBlockTerm->isUnconditional());
216 assert(SI->hasOneUse());
217
218 // These are the new basic blocks for the conditional branch.
219 // At least one will become an actual new basic block.
220 BasicBlock *TrueBlock = nullptr;
221 BasicBlock *FalseBlock = nullptr;
222 BranchInst *TrueBranch = nullptr;
223 BranchInst *FalseBranch = nullptr;
224
225 // Sink select instructions to be able to unfold them later.
226 if (SelectInst *SIOp = dyn_cast<SelectInst>(SI->getTrueValue())) {
227 createBasicBlockAndSinkSelectInst(DTU, SI, SIUse, SIOp, EndBlock,
228 "si.unfold.true", &TrueBlock, &TrueBranch,
229 NewSIsToUnfold, NewBBs);
230 }
231 if (SelectInst *SIOp = dyn_cast<SelectInst>(SI->getFalseValue())) {
232 createBasicBlockAndSinkSelectInst(DTU, SI, SIUse, SIOp, EndBlock,
233 "si.unfold.false", &FalseBlock,
234 &FalseBranch, NewSIsToUnfold, NewBBs);
235 }
236
237 // If there was nothing to sink, then arbitrarily choose the 'false' side
238 // for a new input value to the PHI.
239 if (!TrueBlock && !FalseBlock) {
240 FalseBlock = BasicBlock::Create(SI->getContext(), "si.unfold.false",
241 EndBlock->getParent(), EndBlock);
242 NewBBs->push_back(FalseBlock);
243 BranchInst::Create(EndBlock, FalseBlock);
244 DTU->applyUpdates({{DominatorTree::Insert, FalseBlock, EndBlock}});
245 }
246
247 // Insert the real conditional branch based on the original condition.
248 // If we did not create a new block for one of the 'true' or 'false' paths
249 // of the condition, it means that side of the branch goes to the end block
250 // directly and the path originates from the start block from the point of
251 // view of the new PHI.
252 BasicBlock *TT = EndBlock;
253 BasicBlock *FT = EndBlock;
254 if (TrueBlock && FalseBlock) {
255 // A diamond.
256 TT = TrueBlock;
257 FT = FalseBlock;
258
259 // Update the phi node of SI.
260 SIUse->addIncoming(SI->getTrueValue(), TrueBlock);
261 SIUse->addIncoming(SI->getFalseValue(), FalseBlock);
262
263 // Update any other PHI nodes in EndBlock.
264 for (PHINode &Phi : EndBlock->phis()) {
265 if (&Phi != SIUse) {
266 Value *OrigValue = Phi.getIncomingValueForBlock(StartBlock);
267 Phi.addIncoming(OrigValue, TrueBlock);
268 Phi.addIncoming(OrigValue, FalseBlock);
269 }
270
271 // Remove incoming place of original StartBlock, which comes in a indirect
272 // way (through TrueBlock and FalseBlock) now.
273 Phi.removeIncomingValue(StartBlock, /* DeletePHIIfEmpty = */ false);
274 }
275 } else {
276 BasicBlock *NewBlock = nullptr;
277 Value *SIOp1 = SI->getTrueValue();
278 Value *SIOp2 = SI->getFalseValue();
279
280 // A triangle pointing right.
281 if (!TrueBlock) {
282 NewBlock = FalseBlock;
283 FT = FalseBlock;
284 }
285 // A triangle pointing left.
286 else {
287 NewBlock = TrueBlock;
288 TT = TrueBlock;
289 std::swap(SIOp1, SIOp2);
290 }
291
292 // Update the phi node of SI.
293 for (unsigned Idx = 0; Idx < SIUse->getNumIncomingValues(); ++Idx) {
294 if (SIUse->getIncomingBlock(Idx) == StartBlock)
295 SIUse->setIncomingValue(Idx, SIOp1);
296 }
297 SIUse->addIncoming(SIOp2, NewBlock);
298
299 // Update any other PHI nodes in EndBlock.
300 for (auto II = EndBlock->begin(); PHINode *Phi = dyn_cast<PHINode>(II);
301 ++II) {
302 if (Phi != SIUse)
303 Phi->addIncoming(Phi->getIncomingValueForBlock(StartBlock), NewBlock);
304 }
305 }
306 StartBlockTerm->eraseFromParent();
307 BranchInst::Create(TT, FT, SI->getCondition(), StartBlock);
308 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, TT},
309 {DominatorTree::Insert, StartBlock, FT}});
310
311 // Preserve loop info
312 if (Loop *L = LI->getLoopFor(SI->getParent())) {
313 for (BasicBlock *NewBB : *NewBBs)
314 L->addBasicBlockToLoop(NewBB, *LI);
315 }
316
317 // The select is now dead.
318 assert(SI->use_empty() && "Select must be dead now");
319 SI->eraseFromParent();
320}
321
322struct ClonedBlock {
323 BasicBlock *BB;
324 APInt State; ///< \p State corresponds to the next value of a switch stmnt.
325};
326
327typedef std::deque<BasicBlock *> PathType;
328typedef std::vector<PathType> PathsType;
329typedef SmallPtrSet<const BasicBlock *, 8> VisitedBlocks;
330typedef std::vector<ClonedBlock> CloneList;
331
332// This data structure keeps track of all blocks that have been cloned. If two
333// different ThreadingPaths clone the same block for a certain state it should
334// be reused, and it can be looked up in this map.
335typedef DenseMap<BasicBlock *, CloneList> DuplicateBlockMap;
336
337// This map keeps track of all the new definitions for an instruction. This
338// information is needed when restoring SSA form after cloning blocks.
340
341inline raw_ostream &operator<<(raw_ostream &OS, const PathType &Path) {
342 OS << "< ";
343 for (const BasicBlock *BB : Path) {
344 std::string BBName;
345 if (BB->hasName())
346 raw_string_ostream(BBName) << BB->getName();
347 else
348 raw_string_ostream(BBName) << BB;
349 OS << BBName << " ";
350 }
351 OS << ">";
352 return OS;
353}
354
355/// ThreadingPath is a path in the control flow of a loop that can be threaded
356/// by cloning necessary basic blocks and replacing conditional branches with
357/// unconditional ones. A threading path includes a list of basic blocks, the
358/// exit state, and the block that determines the next state.
359struct ThreadingPath {
360 /// Exit value is DFA's exit state for the given path.
361 APInt getExitValue() const { return ExitVal; }
362 void setExitValue(const ConstantInt *V) {
363 ExitVal = V->getValue();
364 IsExitValSet = true;
365 }
366 bool isExitValueSet() const { return IsExitValSet; }
367
368 /// Determinator is the basic block that determines the next state of the DFA.
369 const BasicBlock *getDeterminatorBB() const { return DBB; }
370 void setDeterminator(const BasicBlock *BB) { DBB = BB; }
371
372 /// Path is a list of basic blocks.
373 const PathType &getPath() const { return Path; }
374 void setPath(const PathType &NewPath) { Path = NewPath; }
375
376 void print(raw_ostream &OS) const {
377 OS << Path << " [ " << ExitVal << ", " << DBB->getName() << " ]";
378 }
379
380private:
381 PathType Path;
382 APInt ExitVal;
383 const BasicBlock *DBB = nullptr;
384 bool IsExitValSet = false;
385};
386
387#ifndef NDEBUG
388inline raw_ostream &operator<<(raw_ostream &OS, const ThreadingPath &TPath) {
389 TPath.print(OS);
390 return OS;
391}
392#endif
393
394struct MainSwitch {
395 MainSwitch(SwitchInst *SI, LoopInfo *LI, OptimizationRemarkEmitter *ORE)
396 : LI(LI) {
397 if (isCandidate(SI)) {
398 Instr = SI;
399 } else {
400 ORE->emit([&]() {
401 return OptimizationRemarkMissed(DEBUG_TYPE, "SwitchNotPredictable", SI)
402 << "Switch instruction is not predictable.";
403 });
404 }
405 }
406
407 virtual ~MainSwitch() = default;
408
409 SwitchInst *getInstr() const { return Instr; }
410 const SmallVector<SelectInstToUnfold, 4> getSelectInsts() {
411 return SelectInsts;
412 }
413
414private:
415 /// Do a use-def chain traversal starting from the switch condition to see if
416 /// \p SI is a potential condidate.
417 ///
418 /// Also, collect select instructions to unfold.
419 bool isCandidate(const SwitchInst *SI) {
420 std::deque<std::pair<Value *, BasicBlock *>> Q;
421 SmallSet<Value *, 16> SeenValues;
422 SelectInsts.clear();
423
424 Value *SICond = SI->getCondition();
425 LLVM_DEBUG(dbgs() << "\tSICond: " << *SICond << "\n");
426 if (!isa<PHINode>(SICond))
427 return false;
428
429 // The switch must be in a loop.
430 const Loop *L = LI->getLoopFor(SI->getParent());
431 if (!L)
432 return false;
433
434 addToQueue(SICond, nullptr, Q, SeenValues);
435
436 while (!Q.empty()) {
437 Value *Current = Q.front().first;
438 BasicBlock *CurrentIncomingBB = Q.front().second;
439 Q.pop_front();
440
441 if (auto *Phi = dyn_cast<PHINode>(Current)) {
442 for (BasicBlock *IncomingBB : Phi->blocks()) {
443 Value *Incoming = Phi->getIncomingValueForBlock(IncomingBB);
444 addToQueue(Incoming, IncomingBB, Q, SeenValues);
445 }
446 LLVM_DEBUG(dbgs() << "\tphi: " << *Phi << "\n");
447 } else if (SelectInst *SelI = dyn_cast<SelectInst>(Current)) {
448 if (!isValidSelectInst(SelI))
449 return false;
450 addToQueue(SelI->getTrueValue(), CurrentIncomingBB, Q, SeenValues);
451 addToQueue(SelI->getFalseValue(), CurrentIncomingBB, Q, SeenValues);
452 LLVM_DEBUG(dbgs() << "\tselect: " << *SelI << "\n");
453 if (auto *SelIUse = dyn_cast<PHINode>(SelI->user_back()))
454 SelectInsts.push_back(SelectInstToUnfold(SelI, SelIUse));
455 } else if (isa<Constant>(Current)) {
456 LLVM_DEBUG(dbgs() << "\tconst: " << *Current << "\n");
457 continue;
458 } else {
459 LLVM_DEBUG(dbgs() << "\tother: " << *Current << "\n");
460 // Allow unpredictable values. The hope is that those will be the
461 // initial switch values that can be ignored (they will hit the
462 // unthreaded switch) but this assumption will get checked later after
463 // paths have been enumerated (in function getStateDefMap).
464
465 // If the unpredictable value comes from the same inner loop it is
466 // likely that it will also be on the enumerated paths, causing us to
467 // exit after we have enumerated all the paths. This heuristic save
468 // compile time because a search for all the paths can become expensive.
469 if (EarlyExitHeuristic &&
470 L->contains(LI->getLoopFor(CurrentIncomingBB))) {
472 << "\tExiting early due to unpredictability heuristic.\n");
473 return false;
474 }
475
476 continue;
477 }
478 }
479
480 return true;
481 }
482
483 void addToQueue(Value *Val, BasicBlock *BB,
484 std::deque<std::pair<Value *, BasicBlock *>> &Q,
485 SmallSet<Value *, 16> &SeenValues) {
486 if (SeenValues.contains(Val))
487 return;
488 Q.push_back({Val, BB});
489 SeenValues.insert(Val);
490 }
491
492 bool isValidSelectInst(SelectInst *SI) {
493 if (!SI->hasOneUse())
494 return false;
495
496 Instruction *SIUse = dyn_cast<Instruction>(SI->user_back());
497 // The use of the select inst should be either a phi or another select.
498 if (!SIUse && !(isa<PHINode>(SIUse) || isa<SelectInst>(SIUse)))
499 return false;
500
501 BasicBlock *SIBB = SI->getParent();
502
503 // Currently, we can only expand select instructions in basic blocks with
504 // one successor.
505 BranchInst *SITerm = dyn_cast<BranchInst>(SIBB->getTerminator());
506 if (!SITerm || !SITerm->isUnconditional())
507 return false;
508
509 // Only fold the select coming from directly where it is defined.
510 PHINode *PHIUser = dyn_cast<PHINode>(SIUse);
511 if (PHIUser && PHIUser->getIncomingBlock(*SI->use_begin()) != SIBB)
512 return false;
513
514 // If select will not be sunk during unfolding, and it is in the same basic
515 // block as another state defining select, then cannot unfold both.
516 for (SelectInstToUnfold SIToUnfold : SelectInsts) {
517 SelectInst *PrevSI = SIToUnfold.getInst();
518 if (PrevSI->getTrueValue() != SI && PrevSI->getFalseValue() != SI &&
519 PrevSI->getParent() == SI->getParent())
520 return false;
521 }
522
523 return true;
524 }
525
526 LoopInfo *LI;
527 SwitchInst *Instr = nullptr;
529};
530
531struct AllSwitchPaths {
532 AllSwitchPaths(const MainSwitch *MSwitch, OptimizationRemarkEmitter *ORE,
533 LoopInfo *LI)
534 : Switch(MSwitch->getInstr()), SwitchBlock(Switch->getParent()), ORE(ORE),
535 LI(LI) {}
536
537 std::vector<ThreadingPath> &getThreadingPaths() { return TPaths; }
538 unsigned getNumThreadingPaths() { return TPaths.size(); }
539 SwitchInst *getSwitchInst() { return Switch; }
540 BasicBlock *getSwitchBlock() { return SwitchBlock; }
541
542 void run() {
543 VisitedBlocks Visited;
544 PathsType LoopPaths = paths(SwitchBlock, Visited, /* PathDepth = */ 1);
545 StateDefMap StateDef = getStateDefMap(LoopPaths);
546
547 if (StateDef.empty()) {
548 ORE->emit([&]() {
549 return OptimizationRemarkMissed(DEBUG_TYPE, "SwitchNotPredictable",
550 Switch)
551 << "Switch instruction is not predictable.";
552 });
553 return;
554 }
555
556 for (const PathType &Path : LoopPaths) {
557 ThreadingPath TPath;
558
559 const BasicBlock *PrevBB = Path.back();
560 for (const BasicBlock *BB : Path) {
561 if (StateDef.contains(BB)) {
562 const PHINode *Phi = dyn_cast<PHINode>(StateDef[BB]);
563 assert(Phi && "Expected a state-defining instr to be a phi node.");
564
565 const Value *V = Phi->getIncomingValueForBlock(PrevBB);
566 if (const ConstantInt *C = dyn_cast<const ConstantInt>(V)) {
567 TPath.setExitValue(C);
568 TPath.setDeterminator(BB);
569 TPath.setPath(Path);
570 }
571 }
572
573 // Switch block is the determinator, this is the final exit value.
574 if (TPath.isExitValueSet() && BB == Path.front())
575 break;
576
577 PrevBB = BB;
578 }
579
580 if (TPath.isExitValueSet() && isSupported(TPath))
581 TPaths.push_back(TPath);
582 }
583 }
584
585private:
586 // Value: an instruction that defines a switch state;
587 // Key: the parent basic block of that instruction.
589
590 PathsType paths(BasicBlock *BB, VisitedBlocks &Visited,
591 unsigned PathDepth) const {
592 PathsType Res;
593
594 // Stop exploring paths after visiting MaxPathLength blocks
595 if (PathDepth > MaxPathLength) {
596 ORE->emit([&]() {
597 return OptimizationRemarkAnalysis(DEBUG_TYPE, "MaxPathLengthReached",
598 Switch)
599 << "Exploration stopped after visiting MaxPathLength="
600 << ore::NV("MaxPathLength", MaxPathLength) << " blocks.";
601 });
602 return Res;
603 }
604
605 Visited.insert(BB);
606
607 // Stop if we have reached the BB out of loop, since its successors have no
608 // impact on the DFA.
609 // TODO: Do we need to stop exploring if BB is the outer loop of the switch?
610 if (!LI->getLoopFor(BB))
611 return Res;
612
613 // Some blocks have multiple edges to the same successor, and this set
614 // is used to prevent a duplicate path from being generated
615 SmallSet<BasicBlock *, 4> Successors;
616 for (BasicBlock *Succ : successors(BB)) {
617 if (!Successors.insert(Succ).second)
618 continue;
619
620 // Found a cycle through the SwitchBlock
621 if (Succ == SwitchBlock) {
622 Res.push_back({BB});
623 continue;
624 }
625
626 // We have encountered a cycle, do not get caught in it
627 if (Visited.contains(Succ))
628 continue;
629
630 PathsType SuccPaths = paths(Succ, Visited, PathDepth + 1);
631 for (const PathType &Path : SuccPaths) {
632 PathType NewPath(Path);
633 NewPath.push_front(BB);
634 Res.push_back(NewPath);
635 if (Res.size() >= MaxNumPaths) {
636 return Res;
637 }
638 }
639 }
640 // This block could now be visited again from a different predecessor. Note
641 // that this will result in exponential runtime. Subpaths could possibly be
642 // cached but it takes a lot of memory to store them.
643 Visited.erase(BB);
644 return Res;
645 }
646
647 /// Walk the use-def chain and collect all the state-defining instructions.
648 ///
649 /// Return an empty map if unpredictable values encountered inside the basic
650 /// blocks of \p LoopPaths.
651 StateDefMap getStateDefMap(const PathsType &LoopPaths) const {
652 StateDefMap Res;
653
654 // Basic blocks belonging to any of the loops around the switch statement.
656 for (const PathType &Path : LoopPaths) {
657 for (BasicBlock *BB : Path)
658 LoopBBs.insert(BB);
659 }
660
661 Value *FirstDef = Switch->getOperand(0);
662
663 assert(isa<PHINode>(FirstDef) && "The first definition must be a phi.");
664
666 Stack.push_back(dyn_cast<PHINode>(FirstDef));
667 SmallSet<Value *, 16> SeenValues;
668
669 while (!Stack.empty()) {
670 PHINode *CurPhi = Stack.pop_back_val();
671
672 Res[CurPhi->getParent()] = CurPhi;
673 SeenValues.insert(CurPhi);
674
675 for (BasicBlock *IncomingBB : CurPhi->blocks()) {
676 Value *Incoming = CurPhi->getIncomingValueForBlock(IncomingBB);
677 bool IsOutsideLoops = LoopBBs.count(IncomingBB) == 0;
678 if (Incoming == FirstDef || isa<ConstantInt>(Incoming) ||
679 SeenValues.contains(Incoming) || IsOutsideLoops) {
680 continue;
681 }
682
683 // Any unpredictable value inside the loops means we must bail out.
684 if (!isa<PHINode>(Incoming))
685 return StateDefMap();
686
687 Stack.push_back(cast<PHINode>(Incoming));
688 }
689 }
690
691 return Res;
692 }
693
694 /// The determinator BB should precede the switch-defining BB.
695 ///
696 /// Otherwise, it is possible that the state defined in the determinator block
697 /// defines the state for the next iteration of the loop, rather than for the
698 /// current one.
699 ///
700 /// Currently supported paths:
701 /// \code
702 /// < switch bb1 determ def > [ 42, determ ]
703 /// < switch_and_def bb1 determ > [ 42, determ ]
704 /// < switch_and_def_and_determ bb1 > [ 42, switch_and_def_and_determ ]
705 /// \endcode
706 ///
707 /// Unsupported paths:
708 /// \code
709 /// < switch bb1 def determ > [ 43, determ ]
710 /// < switch_and_determ bb1 def > [ 43, switch_and_determ ]
711 /// \endcode
712 bool isSupported(const ThreadingPath &TPath) {
713 Instruction *SwitchCondI = dyn_cast<Instruction>(Switch->getCondition());
714 assert(SwitchCondI);
715 if (!SwitchCondI)
716 return false;
717
718 const BasicBlock *SwitchCondDefBB = SwitchCondI->getParent();
719 const BasicBlock *SwitchCondUseBB = Switch->getParent();
720 const BasicBlock *DeterminatorBB = TPath.getDeterminatorBB();
721
722 assert(
723 SwitchCondUseBB == TPath.getPath().front() &&
724 "The first BB in a threading path should have the switch instruction");
725 if (SwitchCondUseBB != TPath.getPath().front())
726 return false;
727
728 // Make DeterminatorBB the first element in Path.
729 PathType Path = TPath.getPath();
730 auto ItDet = llvm::find(Path, DeterminatorBB);
731 std::rotate(Path.begin(), ItDet, Path.end());
732
733 bool IsDetBBSeen = false;
734 bool IsDefBBSeen = false;
735 bool IsUseBBSeen = false;
736 for (BasicBlock *BB : Path) {
737 if (BB == DeterminatorBB)
738 IsDetBBSeen = true;
739 if (BB == SwitchCondDefBB)
740 IsDefBBSeen = true;
741 if (BB == SwitchCondUseBB)
742 IsUseBBSeen = true;
743 if (IsDetBBSeen && IsUseBBSeen && !IsDefBBSeen)
744 return false;
745 }
746
747 return true;
748 }
749
751 BasicBlock *SwitchBlock;
753 std::vector<ThreadingPath> TPaths;
754 LoopInfo *LI;
755};
756
757struct TransformDFA {
758 TransformDFA(AllSwitchPaths *SwitchPaths, DominatorTree *DT,
762 : SwitchPaths(SwitchPaths), DT(DT), AC(AC), TTI(TTI), ORE(ORE),
763 EphValues(EphValues) {}
764
765 void run() {
766 if (isLegalAndProfitableToTransform()) {
767 createAllExitPaths();
768 NumTransforms++;
769 }
770 }
771
772private:
773 /// This function performs both a legality check and profitability check at
774 /// the same time since it is convenient to do so. It iterates through all
775 /// blocks that will be cloned, and keeps track of the duplication cost. It
776 /// also returns false if it is illegal to clone some required block.
777 bool isLegalAndProfitableToTransform() {
779 SwitchInst *Switch = SwitchPaths->getSwitchInst();
780
781 // Don't thread switch without multiple successors.
782 if (Switch->getNumSuccessors() <= 1)
783 return false;
784
785 // Note that DuplicateBlockMap is not being used as intended here. It is
786 // just being used to ensure (BB, State) pairs are only counted once.
787 DuplicateBlockMap DuplicateMap;
788
789 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
790 PathType PathBBs = TPath.getPath();
791 APInt NextState = TPath.getExitValue();
792 const BasicBlock *Determinator = TPath.getDeterminatorBB();
793
794 // Update Metrics for the Switch block, this is always cloned
795 BasicBlock *BB = SwitchPaths->getSwitchBlock();
796 BasicBlock *VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
797 if (!VisitedBB) {
798 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
799 DuplicateMap[BB].push_back({BB, NextState});
800 }
801
802 // If the Switch block is the Determinator, then we can continue since
803 // this is the only block that is cloned and we already counted for it.
804 if (PathBBs.front() == Determinator)
805 continue;
806
807 // Otherwise update Metrics for all blocks that will be cloned. If any
808 // block is already cloned and would be reused, don't double count it.
809 auto DetIt = llvm::find(PathBBs, Determinator);
810 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
811 BB = *BBIt;
812 VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
813 if (VisitedBB)
814 continue;
815 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
816 DuplicateMap[BB].push_back({BB, NextState});
817 }
818
819 if (Metrics.notDuplicatable) {
820 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
821 << "non-duplicatable instructions.\n");
822 ORE->emit([&]() {
823 return OptimizationRemarkMissed(DEBUG_TYPE, "NonDuplicatableInst",
824 Switch)
825 << "Contains non-duplicatable instructions.";
826 });
827 return false;
828 }
829
830 if (Metrics.convergent) {
831 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
832 << "convergent instructions.\n");
833 ORE->emit([&]() {
834 return OptimizationRemarkMissed(DEBUG_TYPE, "ConvergentInst", Switch)
835 << "Contains convergent instructions.";
836 });
837 return false;
838 }
839
840 if (!Metrics.NumInsts.isValid()) {
841 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
842 << "instructions with invalid cost.\n");
843 ORE->emit([&]() {
844 return OptimizationRemarkMissed(DEBUG_TYPE, "ConvergentInst", Switch)
845 << "Contains instructions with invalid cost.";
846 });
847 return false;
848 }
849 }
850
851 InstructionCost DuplicationCost = 0;
852
853 unsigned JumpTableSize = 0;
854 TTI->getEstimatedNumberOfCaseClusters(*Switch, JumpTableSize, nullptr,
855 nullptr);
856 if (JumpTableSize == 0) {
857 // Factor in the number of conditional branches reduced from jump
858 // threading. Assume that lowering the switch block is implemented by
859 // using binary search, hence the LogBase2().
860 unsigned CondBranches =
861 APInt(32, Switch->getNumSuccessors()).ceilLogBase2();
862 assert(CondBranches > 0 &&
863 "The threaded switch must have multiple branches");
864 DuplicationCost = Metrics.NumInsts / CondBranches;
865 } else {
866 // Compared with jump tables, the DFA optimizer removes an indirect branch
867 // on each loop iteration, thus making branch prediction more precise. The
868 // more branch targets there are, the more likely it is for the branch
869 // predictor to make a mistake, and the more benefit there is in the DFA
870 // optimizer. Thus, the more branch targets there are, the lower is the
871 // cost of the DFA opt.
872 DuplicationCost = Metrics.NumInsts / JumpTableSize;
873 }
874
875 LLVM_DEBUG(dbgs() << "\nDFA Jump Threading: Cost to jump thread block "
876 << SwitchPaths->getSwitchBlock()->getName()
877 << " is: " << DuplicationCost << "\n\n");
878
879 if (DuplicationCost > CostThreshold) {
880 LLVM_DEBUG(dbgs() << "Not jump threading, duplication cost exceeds the "
881 << "cost threshold.\n");
882 ORE->emit([&]() {
883 return OptimizationRemarkMissed(DEBUG_TYPE, "NotProfitable", Switch)
884 << "Duplication cost exceeds the cost threshold (cost="
885 << ore::NV("Cost", DuplicationCost)
886 << ", threshold=" << ore::NV("Threshold", CostThreshold) << ").";
887 });
888 return false;
889 }
890
891 ORE->emit([&]() {
892 return OptimizationRemark(DEBUG_TYPE, "JumpThreaded", Switch)
893 << "Switch statement jump-threaded.";
894 });
895
896 return true;
897 }
898
899 /// Transform each threading path to effectively jump thread the DFA.
900 void createAllExitPaths() {
901 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager);
902
903 // Move the switch block to the end of the path, since it will be duplicated
904 BasicBlock *SwitchBlock = SwitchPaths->getSwitchBlock();
905 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
906 LLVM_DEBUG(dbgs() << TPath << "\n");
907 PathType NewPath(TPath.getPath());
908 NewPath.push_back(SwitchBlock);
909 TPath.setPath(NewPath);
910 }
911
912 // Transform the ThreadingPaths and keep track of the cloned values
913 DuplicateBlockMap DuplicateMap;
914 DefMap NewDefs;
915
916 SmallSet<BasicBlock *, 16> BlocksToClean;
917 for (BasicBlock *BB : successors(SwitchBlock))
918 BlocksToClean.insert(BB);
919
920 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
921 createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, &DTU);
922 NumPaths++;
923 }
924
925 // After all paths are cloned, now update the last successor of the cloned
926 // path so it skips over the switch statement
927 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths())
928 updateLastSuccessor(TPath, DuplicateMap, &DTU);
929
930 // For each instruction that was cloned and used outside, update its uses
931 updateSSA(NewDefs);
932
933 // Clean PHI Nodes for the newly created blocks
934 for (BasicBlock *BB : BlocksToClean)
935 cleanPhiNodes(BB);
936 }
937
938 /// For a specific ThreadingPath \p Path, create an exit path starting from
939 /// the determinator block.
940 ///
941 /// To remember the correct destination, we have to duplicate blocks
942 /// corresponding to each state. Also update the terminating instruction of
943 /// the predecessors, and phis in the successor blocks.
944 void createExitPath(DefMap &NewDefs, ThreadingPath &Path,
945 DuplicateBlockMap &DuplicateMap,
946 SmallSet<BasicBlock *, 16> &BlocksToClean,
947 DomTreeUpdater *DTU) {
948 APInt NextState = Path.getExitValue();
949 const BasicBlock *Determinator = Path.getDeterminatorBB();
950 PathType PathBBs = Path.getPath();
951
952 // Don't select the placeholder block in front
953 if (PathBBs.front() == Determinator)
954 PathBBs.pop_front();
955
956 auto DetIt = llvm::find(PathBBs, Determinator);
957 // When there is only one BB in PathBBs, the determinator takes itself as a
958 // direct predecessor.
959 BasicBlock *PrevBB = PathBBs.size() == 1 ? *DetIt : *std::prev(DetIt);
960 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
961 BasicBlock *BB = *BBIt;
962 BlocksToClean.insert(BB);
963
964 // We already cloned BB for this NextState, now just update the branch
965 // and continue.
966 BasicBlock *NextBB = getClonedBB(BB, NextState, DuplicateMap);
967 if (NextBB) {
968 updatePredecessor(PrevBB, BB, NextBB, DTU);
969 PrevBB = NextBB;
970 continue;
971 }
972
973 // Clone the BB and update the successor of Prev to jump to the new block
974 BasicBlock *NewBB = cloneBlockAndUpdatePredecessor(
975 BB, PrevBB, NextState, DuplicateMap, NewDefs, DTU);
976 DuplicateMap[BB].push_back({NewBB, NextState});
977 BlocksToClean.insert(NewBB);
978 PrevBB = NewBB;
979 }
980 }
981
982 /// Restore SSA form after cloning blocks.
983 ///
984 /// Each cloned block creates new defs for a variable, and the uses need to be
985 /// updated to reflect this. The uses may be replaced with a cloned value, or
986 /// some derived phi instruction. Note that all uses of a value defined in the
987 /// same block were already remapped when cloning the block.
988 void updateSSA(DefMap &NewDefs) {
989 SSAUpdaterBulk SSAUpdate;
990 SmallVector<Use *, 16> UsesToRename;
991
992 for (const auto &KV : NewDefs) {
993 Instruction *I = KV.first;
994 BasicBlock *BB = I->getParent();
995 std::vector<Instruction *> Cloned = KV.second;
996
997 // Scan all uses of this instruction to see if it is used outside of its
998 // block, and if so, record them in UsesToRename.
999 for (Use &U : I->uses()) {
1000 Instruction *User = cast<Instruction>(U.getUser());
1001 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1002 if (UserPN->getIncomingBlock(U) == BB)
1003 continue;
1004 } else if (User->getParent() == BB) {
1005 continue;
1006 }
1007
1008 UsesToRename.push_back(&U);
1009 }
1010
1011 // If there are no uses outside the block, we're done with this
1012 // instruction.
1013 if (UsesToRename.empty())
1014 continue;
1015 LLVM_DEBUG(dbgs() << "DFA-JT: Renaming non-local uses of: " << *I
1016 << "\n");
1017
1018 // We found a use of I outside of BB. Rename all uses of I that are
1019 // outside its block to be uses of the appropriate PHI node etc. See
1020 // ValuesInBlocks with the values we know.
1021 unsigned VarNum = SSAUpdate.AddVariable(I->getName(), I->getType());
1022 SSAUpdate.AddAvailableValue(VarNum, BB, I);
1023 for (Instruction *New : Cloned)
1024 SSAUpdate.AddAvailableValue(VarNum, New->getParent(), New);
1025
1026 while (!UsesToRename.empty())
1027 SSAUpdate.AddUse(VarNum, UsesToRename.pop_back_val());
1028
1029 LLVM_DEBUG(dbgs() << "\n");
1030 }
1031 // SSAUpdater handles phi placement and renaming uses with the appropriate
1032 // value.
1033 SSAUpdate.RewriteAllUses(DT);
1034 }
1035
1036 /// Clones a basic block, and adds it to the CFG.
1037 ///
1038 /// This function also includes updating phi nodes in the successors of the
1039 /// BB, and remapping uses that were defined locally in the cloned BB.
1040 BasicBlock *cloneBlockAndUpdatePredecessor(BasicBlock *BB, BasicBlock *PrevBB,
1041 const APInt &NextState,
1042 DuplicateBlockMap &DuplicateMap,
1043 DefMap &NewDefs,
1044 DomTreeUpdater *DTU) {
1045 ValueToValueMapTy VMap;
1046 BasicBlock *NewBB = CloneBasicBlock(
1047 BB, VMap, ".jt" + std::to_string(NextState.getLimitedValue()),
1048 BB->getParent());
1049 NewBB->moveAfter(BB);
1050 NumCloned++;
1051
1052 for (Instruction &I : *NewBB) {
1053 // Do not remap operands of PHINode in case a definition in BB is an
1054 // incoming value to a phi in the same block. This incoming value will
1055 // be renamed later while restoring SSA.
1056 if (isa<PHINode>(&I))
1057 continue;
1058 RemapInstruction(&I, VMap,
1060 if (AssumeInst *II = dyn_cast<AssumeInst>(&I))
1061 AC->registerAssumption(II);
1062 }
1063
1064 updateSuccessorPhis(BB, NewBB, NextState, VMap, DuplicateMap);
1065 updatePredecessor(PrevBB, BB, NewBB, DTU);
1066 updateDefMap(NewDefs, VMap);
1067
1068 // Add all successors to the DominatorTree
1070 for (auto *SuccBB : successors(NewBB)) {
1071 if (SuccSet.insert(SuccBB).second)
1072 DTU->applyUpdates({{DominatorTree::Insert, NewBB, SuccBB}});
1073 }
1074 SuccSet.clear();
1075 return NewBB;
1076 }
1077
1078 /// Update the phi nodes in BB's successors.
1079 ///
1080 /// This means creating a new incoming value from NewBB with the new
1081 /// instruction wherever there is an incoming value from BB.
1082 void updateSuccessorPhis(BasicBlock *BB, BasicBlock *ClonedBB,
1083 const APInt &NextState, ValueToValueMapTy &VMap,
1084 DuplicateBlockMap &DuplicateMap) {
1085 std::vector<BasicBlock *> BlocksToUpdate;
1086
1087 // If BB is the last block in the path, we can simply update the one case
1088 // successor that will be reached.
1089 if (BB == SwitchPaths->getSwitchBlock()) {
1090 SwitchInst *Switch = SwitchPaths->getSwitchInst();
1091 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1092 BlocksToUpdate.push_back(NextCase);
1093 BasicBlock *ClonedSucc = getClonedBB(NextCase, NextState, DuplicateMap);
1094 if (ClonedSucc)
1095 BlocksToUpdate.push_back(ClonedSucc);
1096 }
1097 // Otherwise update phis in all successors.
1098 else {
1099 for (BasicBlock *Succ : successors(BB)) {
1100 BlocksToUpdate.push_back(Succ);
1101
1102 // Check if a successor has already been cloned for the particular exit
1103 // value. In this case if a successor was already cloned, the phi nodes
1104 // in the cloned block should be updated directly.
1105 BasicBlock *ClonedSucc = getClonedBB(Succ, NextState, DuplicateMap);
1106 if (ClonedSucc)
1107 BlocksToUpdate.push_back(ClonedSucc);
1108 }
1109 }
1110
1111 // If there is a phi with an incoming value from BB, create a new incoming
1112 // value for the new predecessor ClonedBB. The value will either be the same
1113 // value from BB or a cloned value.
1114 for (BasicBlock *Succ : BlocksToUpdate) {
1115 for (auto II = Succ->begin(); PHINode *Phi = dyn_cast<PHINode>(II);
1116 ++II) {
1117 Value *Incoming = Phi->getIncomingValueForBlock(BB);
1118 if (Incoming) {
1119 if (isa<Constant>(Incoming)) {
1120 Phi->addIncoming(Incoming, ClonedBB);
1121 continue;
1122 }
1123 Value *ClonedVal = VMap[Incoming];
1124 if (ClonedVal)
1125 Phi->addIncoming(ClonedVal, ClonedBB);
1126 else
1127 Phi->addIncoming(Incoming, ClonedBB);
1128 }
1129 }
1130 }
1131 }
1132
1133 /// Sets the successor of PrevBB to be NewBB instead of OldBB. Note that all
1134 /// other successors are kept as well.
1135 void updatePredecessor(BasicBlock *PrevBB, BasicBlock *OldBB,
1136 BasicBlock *NewBB, DomTreeUpdater *DTU) {
1137 // When a path is reused, there is a chance that predecessors were already
1138 // updated before. Check if the predecessor needs to be updated first.
1139 if (!isPredecessor(OldBB, PrevBB))
1140 return;
1141
1142 Instruction *PrevTerm = PrevBB->getTerminator();
1143 for (unsigned Idx = 0; Idx < PrevTerm->getNumSuccessors(); Idx++) {
1144 if (PrevTerm->getSuccessor(Idx) == OldBB) {
1145 OldBB->removePredecessor(PrevBB, /* KeepOneInputPHIs = */ true);
1146 PrevTerm->setSuccessor(Idx, NewBB);
1147 }
1148 }
1149 DTU->applyUpdates({{DominatorTree::Delete, PrevBB, OldBB},
1150 {DominatorTree::Insert, PrevBB, NewBB}});
1151 }
1152
1153 /// Add new value mappings to the DefMap to keep track of all new definitions
1154 /// for a particular instruction. These will be used while updating SSA form.
1155 void updateDefMap(DefMap &NewDefs, ValueToValueMapTy &VMap) {
1157 NewDefsVector.reserve(VMap.size());
1158
1159 for (auto Entry : VMap) {
1160 Instruction *Inst =
1161 dyn_cast<Instruction>(const_cast<Value *>(Entry.first));
1162 if (!Inst || !Entry.second || isa<BranchInst>(Inst) ||
1163 isa<SwitchInst>(Inst)) {
1164 continue;
1165 }
1166
1167 Instruction *Cloned = dyn_cast<Instruction>(Entry.second);
1168 if (!Cloned)
1169 continue;
1170
1171 NewDefsVector.push_back({Inst, Cloned});
1172 }
1173
1174 // Sort the defs to get deterministic insertion order into NewDefs.
1175 sort(NewDefsVector, [](const auto &LHS, const auto &RHS) {
1176 if (LHS.first == RHS.first)
1177 return LHS.second->comesBefore(RHS.second);
1178 return LHS.first->comesBefore(RHS.first);
1179 });
1180
1181 for (const auto &KV : NewDefsVector)
1182 NewDefs[KV.first].push_back(KV.second);
1183 }
1184
1185 /// Update the last branch of a particular cloned path to point to the correct
1186 /// case successor.
1187 ///
1188 /// Note that this is an optional step and would have been done in later
1189 /// optimizations, but it makes the CFG significantly easier to work with.
1190 void updateLastSuccessor(ThreadingPath &TPath,
1191 DuplicateBlockMap &DuplicateMap,
1192 DomTreeUpdater *DTU) {
1193 APInt NextState = TPath.getExitValue();
1194 BasicBlock *BB = TPath.getPath().back();
1195 BasicBlock *LastBlock = getClonedBB(BB, NextState, DuplicateMap);
1196
1197 // Note multiple paths can end at the same block so check that it is not
1198 // updated yet
1199 if (!isa<SwitchInst>(LastBlock->getTerminator()))
1200 return;
1201 SwitchInst *Switch = cast<SwitchInst>(LastBlock->getTerminator());
1202 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1203
1204 std::vector<DominatorTree::UpdateType> DTUpdates;
1206 for (BasicBlock *Succ : successors(LastBlock)) {
1207 if (Succ != NextCase && SuccSet.insert(Succ).second)
1208 DTUpdates.push_back({DominatorTree::Delete, LastBlock, Succ});
1209 }
1210
1211 Switch->eraseFromParent();
1212 BranchInst::Create(NextCase, LastBlock);
1213
1214 DTU->applyUpdates(DTUpdates);
1215 }
1216
1217 /// After cloning blocks, some of the phi nodes have extra incoming values
1218 /// that are no longer used. This function removes them.
1219 void cleanPhiNodes(BasicBlock *BB) {
1220 // If BB is no longer reachable, remove any remaining phi nodes
1221 if (pred_empty(BB)) {
1222 std::vector<PHINode *> PhiToRemove;
1223 for (auto II = BB->begin(); PHINode *Phi = dyn_cast<PHINode>(II); ++II) {
1224 PhiToRemove.push_back(Phi);
1225 }
1226 for (PHINode *PN : PhiToRemove) {
1227 PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
1228 PN->eraseFromParent();
1229 }
1230 return;
1231 }
1232
1233 // Remove any incoming values that come from an invalid predecessor
1234 for (auto II = BB->begin(); PHINode *Phi = dyn_cast<PHINode>(II); ++II) {
1235 std::vector<BasicBlock *> BlocksToRemove;
1236 for (BasicBlock *IncomingBB : Phi->blocks()) {
1237 if (!isPredecessor(BB, IncomingBB))
1238 BlocksToRemove.push_back(IncomingBB);
1239 }
1240 for (BasicBlock *BB : BlocksToRemove)
1241 Phi->removeIncomingValue(BB);
1242 }
1243 }
1244
1245 /// Checks if BB was already cloned for a particular next state value. If it
1246 /// was then it returns this cloned block, and otherwise null.
1247 BasicBlock *getClonedBB(BasicBlock *BB, const APInt &NextState,
1248 DuplicateBlockMap &DuplicateMap) {
1249 CloneList ClonedBBs = DuplicateMap[BB];
1250
1251 // Find an entry in the CloneList with this NextState. If it exists then
1252 // return the corresponding BB
1253 auto It = llvm::find_if(ClonedBBs, [NextState](const ClonedBlock &C) {
1254 return C.State == NextState;
1255 });
1256 return It != ClonedBBs.end() ? (*It).BB : nullptr;
1257 }
1258
1259 /// Helper to get the successor corresponding to a particular case value for
1260 /// a switch statement.
1261 BasicBlock *getNextCaseSuccessor(SwitchInst *Switch, const APInt &NextState) {
1262 BasicBlock *NextCase = nullptr;
1263 for (auto Case : Switch->cases()) {
1264 if (Case.getCaseValue()->getValue() == NextState) {
1265 NextCase = Case.getCaseSuccessor();
1266 break;
1267 }
1268 }
1269 if (!NextCase)
1270 NextCase = Switch->getDefaultDest();
1271 return NextCase;
1272 }
1273
1274 /// Returns true if IncomingBB is a predecessor of BB.
1275 bool isPredecessor(BasicBlock *BB, BasicBlock *IncomingBB) {
1276 return llvm::is_contained(predecessors(BB), IncomingBB);
1277 }
1278
1279 AllSwitchPaths *SwitchPaths;
1280 DominatorTree *DT;
1281 AssumptionCache *AC;
1285 std::vector<ThreadingPath> TPaths;
1286};
1287
1288bool DFAJumpThreading::run(Function &F) {
1289 LLVM_DEBUG(dbgs() << "\nDFA Jump threading: " << F.getName() << "\n");
1290
1291 if (F.hasOptSize()) {
1292 LLVM_DEBUG(dbgs() << "Skipping due to the 'minsize' attribute\n");
1293 return false;
1294 }
1295
1296 if (ClViewCfgBefore)
1297 F.viewCFG();
1298
1299 SmallVector<AllSwitchPaths, 2> ThreadableLoops;
1300 bool MadeChanges = false;
1301 LoopInfoBroken = false;
1302
1303 for (BasicBlock &BB : F) {
1304 auto *SI = dyn_cast<SwitchInst>(BB.getTerminator());
1305 if (!SI)
1306 continue;
1307
1308 LLVM_DEBUG(dbgs() << "\nCheck if SwitchInst in BB " << BB.getName()
1309 << " is a candidate\n");
1310 MainSwitch Switch(SI, LI, ORE);
1311
1312 if (!Switch.getInstr())
1313 continue;
1314
1315 LLVM_DEBUG(dbgs() << "\nSwitchInst in BB " << BB.getName() << " is a "
1316 << "candidate for jump threading\n");
1317 LLVM_DEBUG(SI->dump());
1318
1319 unfoldSelectInstrs(DT, Switch.getSelectInsts());
1320 if (!Switch.getSelectInsts().empty())
1321 MadeChanges = true;
1322
1323 AllSwitchPaths SwitchPaths(&Switch, ORE, LI);
1324 SwitchPaths.run();
1325
1326 if (SwitchPaths.getNumThreadingPaths() > 0) {
1327 ThreadableLoops.push_back(SwitchPaths);
1328
1329 // For the time being limit this optimization to occurring once in a
1330 // function since it can change the CFG significantly. This is not a
1331 // strict requirement but it can cause buggy behavior if there is an
1332 // overlap of blocks in different opportunities. There is a lot of room to
1333 // experiment with catching more opportunities here.
1334 // NOTE: To release this contraint, we must handle LoopInfo invalidation
1335 break;
1336 }
1337 }
1338
1339#ifdef NDEBUG
1340 LI->verify(*DT);
1341#endif
1342
1344 if (ThreadableLoops.size() > 0)
1345 CodeMetrics::collectEphemeralValues(&F, AC, EphValues);
1346
1347 for (AllSwitchPaths SwitchPaths : ThreadableLoops) {
1348 TransformDFA Transform(&SwitchPaths, DT, AC, TTI, ORE, EphValues);
1349 Transform.run();
1350 MadeChanges = true;
1351 LoopInfoBroken = true;
1352 }
1353
1354#ifdef EXPENSIVE_CHECKS
1355 assert(DT->verify(DominatorTree::VerificationLevel::Full));
1356 verifyFunction(F, &dbgs());
1357#endif
1358
1359 return MadeChanges;
1360}
1361
1362} // end anonymous namespace
1363
1364/// Integrate with the new Pass Manager
1369 LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
1372 DFAJumpThreading ThreadImpl(&AC, &DT, &LI, &TTI, &ORE);
1373 if (!ThreadImpl.run(F))
1374 return PreservedAnalyses::all();
1375
1378 if (!ThreadImpl.LoopInfoBroken)
1379 PA.preserve<LoopAnalysis>();
1380 return PA;
1381}
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...
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< 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))
#define DEBUG_TYPE
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
Machine Trace Metrics
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:76
unsigned ceilLogBase2() const
Definition: APInt.h:1706
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.
Definition: APInt.h:453
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:473
This represents the llvm.assume intrinsic.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:430
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:499
const Instruction & front() const
Definition: BasicBlock.h:453
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:199
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
Definition: BasicBlock.cpp:284
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:206
size_t size() const
Definition: BasicBlock.h:451
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...
Definition: BasicBlock.h:221
const Instruction & back() const
Definition: BasicBlock.h:455
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Definition: BasicBlock.cpp:509
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, BasicBlock::iterator InsertBefore)
bool isUnconditional() const
This is the shared class of boolean and integer constants.
Definition: Constants.h:80
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
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.
Definition: Dominators.h:162
unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const BasicBlock * getParent() const
Definition: Instruction.h:152
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:566
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.
Definition: LoopInfo.h:44
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1827
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
void preserve()
Mark an analysis as preserved.
Definition: Analysis.h:129
Helper class for SSA formation on a set of values defined in multiple blocks.
unsigned AddVariable(StringRef Name, Type *Ty)
Add a new variable to the SSA rewriter.
void AddAvailableValue(unsigned Var, BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
void RewriteAllUses(DominatorTree *DT, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Perform all the necessary updates, including new PHI-nodes insertion and the requested uses update.
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
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:360
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
void clear()
Definition: SmallSet.h:218
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition: SmallSet.h:236
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:179
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
void reserve(size_type N)
Definition: SmallVector.h:676
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Multiway switch.
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) const
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
size_type size() const
Definition: ValueMap.h:140
LLVM Value Representation.
Definition: Value.h:74
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:660
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
@ 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.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< InstrNode * > Instr
Definition: RDFGraph.h:389
NodeAddr< PhiNode * > Phi
Definition: RDFGraph.h:390
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1742
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
Definition: Verifier.cpp:7062
auto successors(const MachineBasicBlock *BB)
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition: ValueMapper.h:94
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition: ValueMapper.h:76
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
Definition: ValueMapper.h:264
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:293
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1749
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1879
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:118
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
Utility to calculate the size and a few similar metrics for a set of basic blocks.
Definition: CodeMetrics.h:31
static 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).
Definition: CodeMetrics.cpp:70
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Integrate with the new Pass Manager.
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...