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