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 assert(SI->hasOneUse());
194 // The select may come indirectly, instead of from where it is defined.
195 BasicBlock *StartBlock = SIUse->getIncomingBlock(*SI->use_begin());
196 BranchInst *StartBlockTerm =
197 dyn_cast<BranchInst>(StartBlock->getTerminator());
198 assert(StartBlockTerm);
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(StartBlock)) {
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 // TODO: We have dealt with the select coming indirectly now. This
537 // constraint can be relaxed.
538 PHINode *PHIUser = dyn_cast<PHINode>(SIUse);
539 if (PHIUser && PHIUser->getIncomingBlock(*SI->use_begin()) != SIBB)
540 return false;
541
542 // If select will not be sunk during unfolding, and it is in the same basic
543 // block as another state defining select, then cannot unfold both.
544 for (SelectInstToUnfold SIToUnfold : SelectInsts) {
545 SelectInst *PrevSI = SIToUnfold.getInst();
546 if (PrevSI->getTrueValue() != SI && PrevSI->getFalseValue() != SI &&
547 PrevSI->getParent() == SI->getParent())
548 return false;
549 }
550
551 return true;
552 }
553
554 LoopInfo *LI;
555 SwitchInst *Instr = nullptr;
557};
558
559struct AllSwitchPaths {
560 AllSwitchPaths(const MainSwitch *MSwitch, OptimizationRemarkEmitter *ORE,
561 LoopInfo *LI, Loop *L)
562 : Switch(MSwitch->getInstr()), SwitchBlock(Switch->getParent()), ORE(ORE),
563 LI(LI), SwitchOuterLoop(L) {}
564
565 std::vector<ThreadingPath> &getThreadingPaths() { return TPaths; }
566 unsigned getNumThreadingPaths() { return TPaths.size(); }
567 SwitchInst *getSwitchInst() { return Switch; }
568 BasicBlock *getSwitchBlock() { return SwitchBlock; }
569
570 void run() {
571 StateDefMap StateDef = getStateDefMap();
572 if (StateDef.empty()) {
573 ORE->emit([&]() {
574 return OptimizationRemarkMissed(DEBUG_TYPE, "SwitchNotPredictable",
575 Switch)
576 << "Switch instruction is not predictable.";
577 });
578 return;
579 }
580
581 auto *SwitchPhi = cast<PHINode>(Switch->getOperand(0));
582 auto *SwitchPhiDefBB = SwitchPhi->getParent();
583 VisitedBlocks VB;
584 // Get paths from the determinator BBs to SwitchPhiDefBB
585 std::vector<ThreadingPath> PathsToPhiDef =
586 getPathsFromStateDefMap(StateDef, SwitchPhi, VB, MaxNumPaths);
587 if (SwitchPhiDefBB == SwitchBlock || PathsToPhiDef.empty()) {
588 TPaths = std::move(PathsToPhiDef);
589 return;
590 }
591
592 assert(MaxNumPaths >= PathsToPhiDef.size() && !PathsToPhiDef.empty());
593 auto PathsLimit = MaxNumPaths / PathsToPhiDef.size();
594 // Find and append paths from SwitchPhiDefBB to SwitchBlock.
595 PathsType PathsToSwitchBB =
596 paths(SwitchPhiDefBB, SwitchBlock, VB, /* PathDepth = */ 1, PathsLimit);
597 if (PathsToSwitchBB.empty())
598 return;
599
600 std::vector<ThreadingPath> TempList;
601 for (const ThreadingPath &Path : PathsToPhiDef) {
602 for (const PathType &PathToSw : PathsToSwitchBB) {
603 ThreadingPath PathCopy(Path);
604 PathCopy.appendExcludingFirst(PathToSw);
605 TempList.push_back(PathCopy);
606 }
607 }
608 TPaths = std::move(TempList);
609 }
610
611private:
612 // Value: an instruction that defines a switch state;
613 // Key: the parent basic block of that instruction.
614 typedef DenseMap<const BasicBlock *, const PHINode *> StateDefMap;
615 std::vector<ThreadingPath> getPathsFromStateDefMap(StateDefMap &StateDef,
616 PHINode *Phi,
617 VisitedBlocks &VB,
618 unsigned PathsLimit) {
619 std::vector<ThreadingPath> Res;
620 auto *PhiBB = Phi->getParent();
621 VB.insert(PhiBB);
622
623 VisitedBlocks UniqueBlocks;
624 for (auto *IncomingBB : Phi->blocks()) {
625 if (Res.size() >= PathsLimit)
626 break;
627 if (!UniqueBlocks.insert(IncomingBB).second)
628 continue;
629 if (!SwitchOuterLoop->contains(IncomingBB))
630 continue;
631
632 Value *IncomingValue = Phi->getIncomingValueForBlock(IncomingBB);
633 // We found the determinator. This is the start of our path.
634 if (auto *C = dyn_cast<ConstantInt>(IncomingValue)) {
635 // SwitchBlock is the determinator, unsupported unless its also the def.
636 if (PhiBB == SwitchBlock &&
637 SwitchBlock != cast<PHINode>(Switch->getOperand(0))->getParent())
638 continue;
639 ThreadingPath NewPath;
640 NewPath.setDeterminator(PhiBB);
641 NewPath.setExitValue(C);
642 // Don't add SwitchBlock at the start, this is handled later.
643 if (IncomingBB != SwitchBlock)
644 NewPath.push_back(IncomingBB);
645 NewPath.push_back(PhiBB);
646 Res.push_back(NewPath);
647 continue;
648 }
649 // Don't get into a cycle.
650 if (VB.contains(IncomingBB) || IncomingBB == SwitchBlock)
651 continue;
652 // Recurse up the PHI chain.
653 auto *IncomingPhi = dyn_cast<PHINode>(IncomingValue);
654 if (!IncomingPhi)
655 continue;
656 auto *IncomingPhiDefBB = IncomingPhi->getParent();
657 if (!StateDef.contains(IncomingPhiDefBB))
658 continue;
659
660 // Direct predecessor, just add to the path.
661 if (IncomingPhiDefBB == IncomingBB) {
662 assert(PathsLimit > Res.size());
663 std::vector<ThreadingPath> PredPaths = getPathsFromStateDefMap(
664 StateDef, IncomingPhi, VB, PathsLimit - Res.size());
665 for (ThreadingPath &Path : PredPaths) {
666 Path.push_back(PhiBB);
667 Res.push_back(std::move(Path));
668 }
669 continue;
670 }
671 // Not a direct predecessor, find intermediate paths to append to the
672 // existing path.
673 if (VB.contains(IncomingPhiDefBB))
674 continue;
675
676 PathsType IntermediatePaths;
677 assert(PathsLimit > Res.size());
678 auto InterPathLimit = PathsLimit - Res.size();
679 IntermediatePaths = paths(IncomingPhiDefBB, IncomingBB, VB,
680 /* PathDepth = */ 1, InterPathLimit);
681 if (IntermediatePaths.empty())
682 continue;
683
684 assert(InterPathLimit >= IntermediatePaths.size());
685 auto PredPathLimit = InterPathLimit / IntermediatePaths.size();
686 std::vector<ThreadingPath> PredPaths =
687 getPathsFromStateDefMap(StateDef, IncomingPhi, VB, PredPathLimit);
688 for (const ThreadingPath &Path : PredPaths) {
689 for (const PathType &IPath : IntermediatePaths) {
690 ThreadingPath NewPath(Path);
691 NewPath.appendExcludingFirst(IPath);
692 NewPath.push_back(PhiBB);
693 Res.push_back(NewPath);
694 }
695 }
696 }
697 VB.erase(PhiBB);
698 return Res;
699 }
700
701 PathsType paths(BasicBlock *BB, BasicBlock *ToBB, VisitedBlocks &Visited,
702 unsigned PathDepth, unsigned PathsLimit) {
703 PathsType Res;
704
705 // Stop exploring paths after visiting MaxPathLength blocks
706 if (PathDepth > MaxPathLength) {
707 ORE->emit([&]() {
708 return OptimizationRemarkAnalysis(DEBUG_TYPE, "MaxPathLengthReached",
709 Switch)
710 << "Exploration stopped after visiting MaxPathLength="
711 << ore::NV("MaxPathLength", MaxPathLength) << " blocks.";
712 });
713 return Res;
714 }
715
716 Visited.insert(BB);
717 if (++NumVisited > MaxNumVisitiedPaths)
718 return Res;
719
720 // Stop if we have reached the BB out of loop, since its successors have no
721 // impact on the DFA.
722 if (!SwitchOuterLoop->contains(BB))
723 return Res;
724
725 // Some blocks have multiple edges to the same successor, and this set
726 // is used to prevent a duplicate path from being generated
727 SmallPtrSet<BasicBlock *, 4> Successors;
728 for (BasicBlock *Succ : successors(BB)) {
729 if (Res.size() >= PathsLimit)
730 break;
731 if (!Successors.insert(Succ).second)
732 continue;
733
734 // Found a cycle through the final block.
735 if (Succ == ToBB) {
736 Res.push_back({BB, ToBB});
737 continue;
738 }
739
740 // We have encountered a cycle, do not get caught in it
741 if (Visited.contains(Succ))
742 continue;
743
744 auto *CurrLoop = LI->getLoopFor(BB);
745 // Unlikely to be beneficial.
746 if (Succ == CurrLoop->getHeader())
747 continue;
748 // Skip for now, revisit this condition later to see the impact on
749 // coverage and compile time.
750 if (LI->getLoopFor(Succ) != CurrLoop)
751 continue;
752 assert(PathsLimit > Res.size());
753 PathsType SuccPaths =
754 paths(Succ, ToBB, Visited, PathDepth + 1, PathsLimit - Res.size());
755 for (PathType &Path : SuccPaths) {
756 Path.push_front(BB);
757 Res.push_back(Path);
758 }
759 }
760 // This block could now be visited again from a different predecessor. Note
761 // that this will result in exponential runtime. Subpaths could possibly be
762 // cached but it takes a lot of memory to store them.
763 Visited.erase(BB);
764 return Res;
765 }
766
767 /// Walk the use-def chain and collect all the state-defining blocks and the
768 /// PHI nodes in those blocks that define the state.
769 StateDefMap getStateDefMap() const {
770 StateDefMap Res;
771 PHINode *FirstDef = dyn_cast<PHINode>(Switch->getOperand(0));
772 assert(FirstDef && "The first definition must be a phi.");
773
775 Stack.push_back(FirstDef);
776 SmallPtrSet<Value *, 16> SeenValues;
777
778 while (!Stack.empty()) {
779 PHINode *CurPhi = Stack.pop_back_val();
780
781 Res[CurPhi->getParent()] = CurPhi;
782 SeenValues.insert(CurPhi);
783
784 for (BasicBlock *IncomingBB : CurPhi->blocks()) {
785 PHINode *IncomingPhi =
786 dyn_cast<PHINode>(CurPhi->getIncomingValueForBlock(IncomingBB));
787 if (!IncomingPhi)
788 continue;
789 bool IsOutsideLoops = !SwitchOuterLoop->contains(IncomingBB);
790 if (SeenValues.contains(IncomingPhi) || IsOutsideLoops)
791 continue;
792
793 Stack.push_back(IncomingPhi);
794 }
795 }
796
797 return Res;
798 }
799
800 unsigned NumVisited = 0;
801 SwitchInst *Switch;
802 BasicBlock *SwitchBlock;
803 OptimizationRemarkEmitter *ORE;
804 std::vector<ThreadingPath> TPaths;
805 LoopInfo *LI;
806 Loop *SwitchOuterLoop;
807};
808
809struct TransformDFA {
810 TransformDFA(AllSwitchPaths *SwitchPaths, DominatorTree *DT,
811 AssumptionCache *AC, TargetTransformInfo *TTI,
812 OptimizationRemarkEmitter *ORE,
813 SmallPtrSet<const Value *, 32> EphValues)
814 : SwitchPaths(SwitchPaths), DT(DT), AC(AC), TTI(TTI), ORE(ORE),
815 EphValues(EphValues) {}
816
817 void run() {
818 if (isLegalAndProfitableToTransform()) {
819 createAllExitPaths();
820 NumTransforms++;
821 }
822 }
823
824private:
825 /// This function performs both a legality check and profitability check at
826 /// the same time since it is convenient to do so. It iterates through all
827 /// blocks that will be cloned, and keeps track of the duplication cost. It
828 /// also returns false if it is illegal to clone some required block.
829 bool isLegalAndProfitableToTransform() {
830 CodeMetrics Metrics;
831 SwitchInst *Switch = SwitchPaths->getSwitchInst();
832
833 // Don't thread switch without multiple successors.
834 if (Switch->getNumSuccessors() <= 1)
835 return false;
836
837 // Note that DuplicateBlockMap is not being used as intended here. It is
838 // just being used to ensure (BB, State) pairs are only counted once.
839 DuplicateBlockMap DuplicateMap;
840
841 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
842 PathType PathBBs = TPath.getPath();
843 APInt NextState = TPath.getExitValue();
844 const BasicBlock *Determinator = TPath.getDeterminatorBB();
845
846 // Update Metrics for the Switch block, this is always cloned
847 BasicBlock *BB = SwitchPaths->getSwitchBlock();
848 BasicBlock *VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
849 if (!VisitedBB) {
850 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
851 DuplicateMap[BB].push_back({BB, NextState});
852 }
853
854 // If the Switch block is the Determinator, then we can continue since
855 // this is the only block that is cloned and we already counted for it.
856 if (PathBBs.front() == Determinator)
857 continue;
858
859 // Otherwise update Metrics for all blocks that will be cloned. If any
860 // block is already cloned and would be reused, don't double count it.
861 auto DetIt = llvm::find(PathBBs, Determinator);
862 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
863 BB = *BBIt;
864 VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
865 if (VisitedBB)
866 continue;
867 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
868 DuplicateMap[BB].push_back({BB, NextState});
869 }
870
871 if (Metrics.notDuplicatable) {
872 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
873 << "non-duplicatable instructions.\n");
874 ORE->emit([&]() {
875 return OptimizationRemarkMissed(DEBUG_TYPE, "NonDuplicatableInst",
876 Switch)
877 << "Contains non-duplicatable instructions.";
878 });
879 return false;
880 }
881
882 // FIXME: Allow jump threading with controlled convergence.
883 if (Metrics.Convergence != ConvergenceKind::None) {
884 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
885 << "convergent instructions.\n");
886 ORE->emit([&]() {
887 return OptimizationRemarkMissed(DEBUG_TYPE, "ConvergentInst", Switch)
888 << "Contains convergent instructions.";
889 });
890 return false;
891 }
892
893 if (!Metrics.NumInsts.isValid()) {
894 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains "
895 << "instructions with invalid cost.\n");
896 ORE->emit([&]() {
897 return OptimizationRemarkMissed(DEBUG_TYPE, "ConvergentInst", Switch)
898 << "Contains instructions with invalid cost.";
899 });
900 return false;
901 }
902 }
903
904 InstructionCost DuplicationCost = 0;
905
906 unsigned JumpTableSize = 0;
907 TTI->getEstimatedNumberOfCaseClusters(*Switch, JumpTableSize, nullptr,
908 nullptr);
909 if (JumpTableSize == 0) {
910 // Factor in the number of conditional branches reduced from jump
911 // threading. Assume that lowering the switch block is implemented by
912 // using binary search, hence the LogBase2().
913 unsigned CondBranches =
914 APInt(32, Switch->getNumSuccessors()).ceilLogBase2();
915 assert(CondBranches > 0 &&
916 "The threaded switch must have multiple branches");
917 DuplicationCost = Metrics.NumInsts / CondBranches;
918 } else {
919 // Compared with jump tables, the DFA optimizer removes an indirect branch
920 // on each loop iteration, thus making branch prediction more precise. The
921 // more branch targets there are, the more likely it is for the branch
922 // predictor to make a mistake, and the more benefit there is in the DFA
923 // optimizer. Thus, the more branch targets there are, the lower is the
924 // cost of the DFA opt.
925 DuplicationCost = Metrics.NumInsts / JumpTableSize;
926 }
927
928 LLVM_DEBUG(dbgs() << "\nDFA Jump Threading: Cost to jump thread block "
929 << SwitchPaths->getSwitchBlock()->getName()
930 << " is: " << DuplicationCost << "\n\n");
931
932 if (DuplicationCost > CostThreshold) {
933 LLVM_DEBUG(dbgs() << "Not jump threading, duplication cost exceeds the "
934 << "cost threshold.\n");
935 ORE->emit([&]() {
936 return OptimizationRemarkMissed(DEBUG_TYPE, "NotProfitable", Switch)
937 << "Duplication cost exceeds the cost threshold (cost="
938 << ore::NV("Cost", DuplicationCost)
939 << ", threshold=" << ore::NV("Threshold", CostThreshold) << ").";
940 });
941 return false;
942 }
943
944 ORE->emit([&]() {
945 return OptimizationRemark(DEBUG_TYPE, "JumpThreaded", Switch)
946 << "Switch statement jump-threaded.";
947 });
948
949 return true;
950 }
951
952 /// Transform each threading path to effectively jump thread the DFA.
953 void createAllExitPaths() {
954 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager);
955
956 // Move the switch block to the end of the path, since it will be duplicated
957 BasicBlock *SwitchBlock = SwitchPaths->getSwitchBlock();
958 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
959 LLVM_DEBUG(dbgs() << TPath << "\n");
960 // TODO: Fix exit path creation logic so that we dont need this
961 // placeholder.
962 TPath.push_front(SwitchBlock);
963 }
964
965 // Transform the ThreadingPaths and keep track of the cloned values
966 DuplicateBlockMap DuplicateMap;
967 DefMap NewDefs;
968
969 SmallPtrSet<BasicBlock *, 16> BlocksToClean;
970 BlocksToClean.insert_range(successors(SwitchBlock));
971
972 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
973 createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, &DTU);
974 NumPaths++;
975 }
976
977 // After all paths are cloned, now update the last successor of the cloned
978 // path so it skips over the switch statement
979 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths())
980 updateLastSuccessor(TPath, DuplicateMap, &DTU);
981
982 // For each instruction that was cloned and used outside, update its uses
983 updateSSA(NewDefs);
984
985 // Clean PHI Nodes for the newly created blocks
986 for (BasicBlock *BB : BlocksToClean)
987 cleanPhiNodes(BB);
988 }
989
990 /// For a specific ThreadingPath \p Path, create an exit path starting from
991 /// the determinator block.
992 ///
993 /// To remember the correct destination, we have to duplicate blocks
994 /// corresponding to each state. Also update the terminating instruction of
995 /// the predecessors, and phis in the successor blocks.
996 void createExitPath(DefMap &NewDefs, ThreadingPath &Path,
997 DuplicateBlockMap &DuplicateMap,
998 SmallPtrSet<BasicBlock *, 16> &BlocksToClean,
999 DomTreeUpdater *DTU) {
1000 APInt NextState = Path.getExitValue();
1001 const BasicBlock *Determinator = Path.getDeterminatorBB();
1002 PathType PathBBs = Path.getPath();
1003
1004 // Don't select the placeholder block in front
1005 if (PathBBs.front() == Determinator)
1006 PathBBs.pop_front();
1007
1008 auto DetIt = llvm::find(PathBBs, Determinator);
1009 // When there is only one BB in PathBBs, the determinator takes itself as a
1010 // direct predecessor.
1011 BasicBlock *PrevBB = PathBBs.size() == 1 ? *DetIt : *std::prev(DetIt);
1012 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
1013 BasicBlock *BB = *BBIt;
1014 BlocksToClean.insert(BB);
1015
1016 // We already cloned BB for this NextState, now just update the branch
1017 // and continue.
1018 BasicBlock *NextBB = getClonedBB(BB, NextState, DuplicateMap);
1019 if (NextBB) {
1020 updatePredecessor(PrevBB, BB, NextBB, DTU);
1021 PrevBB = NextBB;
1022 continue;
1023 }
1024
1025 // Clone the BB and update the successor of Prev to jump to the new block
1026 BasicBlock *NewBB = cloneBlockAndUpdatePredecessor(
1027 BB, PrevBB, NextState, DuplicateMap, NewDefs, DTU);
1028 DuplicateMap[BB].push_back({NewBB, NextState});
1029 BlocksToClean.insert(NewBB);
1030 PrevBB = NewBB;
1031 }
1032 }
1033
1034 /// Restore SSA form after cloning blocks.
1035 ///
1036 /// Each cloned block creates new defs for a variable, and the uses need to be
1037 /// updated to reflect this. The uses may be replaced with a cloned value, or
1038 /// some derived phi instruction. Note that all uses of a value defined in the
1039 /// same block were already remapped when cloning the block.
1040 void updateSSA(DefMap &NewDefs) {
1041 SSAUpdaterBulk SSAUpdate;
1042 SmallVector<Use *, 16> UsesToRename;
1043
1044 for (const auto &KV : NewDefs) {
1045 Instruction *I = KV.first;
1046 BasicBlock *BB = I->getParent();
1047 std::vector<Instruction *> Cloned = KV.second;
1048
1049 // Scan all uses of this instruction to see if it is used outside of its
1050 // block, and if so, record them in UsesToRename.
1051 for (Use &U : I->uses()) {
1052 Instruction *User = cast<Instruction>(U.getUser());
1053 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1054 if (UserPN->getIncomingBlock(U) == BB)
1055 continue;
1056 } else if (User->getParent() == BB) {
1057 continue;
1058 }
1059
1060 UsesToRename.push_back(&U);
1061 }
1062
1063 // If there are no uses outside the block, we're done with this
1064 // instruction.
1065 if (UsesToRename.empty())
1066 continue;
1067 LLVM_DEBUG(dbgs() << "DFA-JT: Renaming non-local uses of: " << *I
1068 << "\n");
1069
1070 // We found a use of I outside of BB. Rename all uses of I that are
1071 // outside its block to be uses of the appropriate PHI node etc. See
1072 // ValuesInBlocks with the values we know.
1073 unsigned VarNum = SSAUpdate.AddVariable(I->getName(), I->getType());
1074 SSAUpdate.AddAvailableValue(VarNum, BB, I);
1075 for (Instruction *New : Cloned)
1076 SSAUpdate.AddAvailableValue(VarNum, New->getParent(), New);
1077
1078 while (!UsesToRename.empty())
1079 SSAUpdate.AddUse(VarNum, UsesToRename.pop_back_val());
1080
1081 LLVM_DEBUG(dbgs() << "\n");
1082 }
1083 // SSAUpdater handles phi placement and renaming uses with the appropriate
1084 // value.
1085 SSAUpdate.RewriteAllUses(DT);
1086 }
1087
1088 /// Clones a basic block, and adds it to the CFG.
1089 ///
1090 /// This function also includes updating phi nodes in the successors of the
1091 /// BB, and remapping uses that were defined locally in the cloned BB.
1092 BasicBlock *cloneBlockAndUpdatePredecessor(BasicBlock *BB, BasicBlock *PrevBB,
1093 const APInt &NextState,
1094 DuplicateBlockMap &DuplicateMap,
1095 DefMap &NewDefs,
1096 DomTreeUpdater *DTU) {
1097 ValueToValueMapTy VMap;
1098 BasicBlock *NewBB = CloneBasicBlock(
1099 BB, VMap, ".jt" + std::to_string(NextState.getLimitedValue()),
1100 BB->getParent());
1101 NewBB->moveAfter(BB);
1102 NumCloned++;
1103
1104 for (Instruction &I : *NewBB) {
1105 // Do not remap operands of PHINode in case a definition in BB is an
1106 // incoming value to a phi in the same block. This incoming value will
1107 // be renamed later while restoring SSA.
1108 if (isa<PHINode>(&I))
1109 continue;
1110 RemapInstruction(&I, VMap,
1112 if (AssumeInst *II = dyn_cast<AssumeInst>(&I))
1113 AC->registerAssumption(II);
1114 }
1115
1116 updateSuccessorPhis(BB, NewBB, NextState, VMap, DuplicateMap);
1117 updatePredecessor(PrevBB, BB, NewBB, DTU);
1118 updateDefMap(NewDefs, VMap);
1119
1120 // Add all successors to the DominatorTree
1121 SmallPtrSet<BasicBlock *, 4> SuccSet;
1122 for (auto *SuccBB : successors(NewBB)) {
1123 if (SuccSet.insert(SuccBB).second)
1124 DTU->applyUpdates({{DominatorTree::Insert, NewBB, SuccBB}});
1125 }
1126 SuccSet.clear();
1127 return NewBB;
1128 }
1129
1130 /// Update the phi nodes in BB's successors.
1131 ///
1132 /// This means creating a new incoming value from NewBB with the new
1133 /// instruction wherever there is an incoming value from BB.
1134 void updateSuccessorPhis(BasicBlock *BB, BasicBlock *ClonedBB,
1135 const APInt &NextState, ValueToValueMapTy &VMap,
1136 DuplicateBlockMap &DuplicateMap) {
1137 std::vector<BasicBlock *> BlocksToUpdate;
1138
1139 // If BB is the last block in the path, we can simply update the one case
1140 // successor that will be reached.
1141 if (BB == SwitchPaths->getSwitchBlock()) {
1142 SwitchInst *Switch = SwitchPaths->getSwitchInst();
1143 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1144 BlocksToUpdate.push_back(NextCase);
1145 BasicBlock *ClonedSucc = getClonedBB(NextCase, NextState, DuplicateMap);
1146 if (ClonedSucc)
1147 BlocksToUpdate.push_back(ClonedSucc);
1148 }
1149 // Otherwise update phis in all successors.
1150 else {
1151 for (BasicBlock *Succ : successors(BB)) {
1152 BlocksToUpdate.push_back(Succ);
1153
1154 // Check if a successor has already been cloned for the particular exit
1155 // value. In this case if a successor was already cloned, the phi nodes
1156 // in the cloned block should be updated directly.
1157 BasicBlock *ClonedSucc = getClonedBB(Succ, NextState, DuplicateMap);
1158 if (ClonedSucc)
1159 BlocksToUpdate.push_back(ClonedSucc);
1160 }
1161 }
1162
1163 // If there is a phi with an incoming value from BB, create a new incoming
1164 // value for the new predecessor ClonedBB. The value will either be the same
1165 // value from BB or a cloned value.
1166 for (BasicBlock *Succ : BlocksToUpdate) {
1167 for (auto II = Succ->begin(); PHINode *Phi = dyn_cast<PHINode>(II);
1168 ++II) {
1169 Value *Incoming = Phi->getIncomingValueForBlock(BB);
1170 if (Incoming) {
1171 if (isa<Constant>(Incoming)) {
1172 Phi->addIncoming(Incoming, ClonedBB);
1173 continue;
1174 }
1175 Value *ClonedVal = VMap[Incoming];
1176 if (ClonedVal)
1177 Phi->addIncoming(ClonedVal, ClonedBB);
1178 else
1179 Phi->addIncoming(Incoming, ClonedBB);
1180 }
1181 }
1182 }
1183 }
1184
1185 /// Sets the successor of PrevBB to be NewBB instead of OldBB. Note that all
1186 /// other successors are kept as well.
1187 void updatePredecessor(BasicBlock *PrevBB, BasicBlock *OldBB,
1188 BasicBlock *NewBB, DomTreeUpdater *DTU) {
1189 // When a path is reused, there is a chance that predecessors were already
1190 // updated before. Check if the predecessor needs to be updated first.
1191 if (!isPredecessor(OldBB, PrevBB))
1192 return;
1193
1194 Instruction *PrevTerm = PrevBB->getTerminator();
1195 for (unsigned Idx = 0; Idx < PrevTerm->getNumSuccessors(); Idx++) {
1196 if (PrevTerm->getSuccessor(Idx) == OldBB) {
1197 OldBB->removePredecessor(PrevBB, /* KeepOneInputPHIs = */ true);
1198 PrevTerm->setSuccessor(Idx, NewBB);
1199 }
1200 }
1201 DTU->applyUpdates({{DominatorTree::Delete, PrevBB, OldBB},
1202 {DominatorTree::Insert, PrevBB, NewBB}});
1203 }
1204
1205 /// Add new value mappings to the DefMap to keep track of all new definitions
1206 /// for a particular instruction. These will be used while updating SSA form.
1207 void updateDefMap(DefMap &NewDefs, ValueToValueMapTy &VMap) {
1209 NewDefsVector.reserve(VMap.size());
1210
1211 for (auto Entry : VMap) {
1212 Instruction *Inst =
1213 dyn_cast<Instruction>(const_cast<Value *>(Entry.first));
1214 if (!Inst || !Entry.second || isa<BranchInst>(Inst) ||
1215 isa<SwitchInst>(Inst)) {
1216 continue;
1217 }
1218
1219 Instruction *Cloned = dyn_cast<Instruction>(Entry.second);
1220 if (!Cloned)
1221 continue;
1222
1223 NewDefsVector.push_back({Inst, Cloned});
1224 }
1225
1226 // Sort the defs to get deterministic insertion order into NewDefs.
1227 sort(NewDefsVector, [](const auto &LHS, const auto &RHS) {
1228 if (LHS.first == RHS.first)
1229 return LHS.second->comesBefore(RHS.second);
1230 return LHS.first->comesBefore(RHS.first);
1231 });
1232
1233 for (const auto &KV : NewDefsVector)
1234 NewDefs[KV.first].push_back(KV.second);
1235 }
1236
1237 /// Update the last branch of a particular cloned path to point to the correct
1238 /// case successor.
1239 ///
1240 /// Note that this is an optional step and would have been done in later
1241 /// optimizations, but it makes the CFG significantly easier to work with.
1242 void updateLastSuccessor(ThreadingPath &TPath,
1243 DuplicateBlockMap &DuplicateMap,
1244 DomTreeUpdater *DTU) {
1245 APInt NextState = TPath.getExitValue();
1246 BasicBlock *BB = TPath.getPath().back();
1247 BasicBlock *LastBlock = getClonedBB(BB, NextState, DuplicateMap);
1248
1249 // Note multiple paths can end at the same block so check that it is not
1250 // updated yet
1251 if (!isa<SwitchInst>(LastBlock->getTerminator()))
1252 return;
1253 SwitchInst *Switch = cast<SwitchInst>(LastBlock->getTerminator());
1254 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1255
1256 std::vector<DominatorTree::UpdateType> DTUpdates;
1257 SmallPtrSet<BasicBlock *, 4> SuccSet;
1258 for (BasicBlock *Succ : successors(LastBlock)) {
1259 if (Succ != NextCase && SuccSet.insert(Succ).second)
1260 DTUpdates.push_back({DominatorTree::Delete, LastBlock, Succ});
1261 }
1262
1263 Switch->eraseFromParent();
1264 BranchInst::Create(NextCase, LastBlock);
1265
1266 DTU->applyUpdates(DTUpdates);
1267 }
1268
1269 /// After cloning blocks, some of the phi nodes have extra incoming values
1270 /// that are no longer used. This function removes them.
1271 void cleanPhiNodes(BasicBlock *BB) {
1272 // If BB is no longer reachable, remove any remaining phi nodes
1273 if (pred_empty(BB)) {
1274 std::vector<PHINode *> PhiToRemove;
1275 for (auto II = BB->begin(); PHINode *Phi = dyn_cast<PHINode>(II); ++II) {
1276 PhiToRemove.push_back(Phi);
1277 }
1278 for (PHINode *PN : PhiToRemove) {
1279 PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
1280 PN->eraseFromParent();
1281 }
1282 return;
1283 }
1284
1285 // Remove any incoming values that come from an invalid predecessor
1286 for (auto II = BB->begin(); PHINode *Phi = dyn_cast<PHINode>(II); ++II) {
1287 std::vector<BasicBlock *> BlocksToRemove;
1288 for (BasicBlock *IncomingBB : Phi->blocks()) {
1289 if (!isPredecessor(BB, IncomingBB))
1290 BlocksToRemove.push_back(IncomingBB);
1291 }
1292 for (BasicBlock *BB : BlocksToRemove)
1293 Phi->removeIncomingValue(BB);
1294 }
1295 }
1296
1297 /// Checks if BB was already cloned for a particular next state value. If it
1298 /// was then it returns this cloned block, and otherwise null.
1299 BasicBlock *getClonedBB(BasicBlock *BB, const APInt &NextState,
1300 DuplicateBlockMap &DuplicateMap) {
1301 CloneList ClonedBBs = DuplicateMap[BB];
1302
1303 // Find an entry in the CloneList with this NextState. If it exists then
1304 // return the corresponding BB
1305 auto It = llvm::find_if(ClonedBBs, [NextState](const ClonedBlock &C) {
1306 return C.State == NextState;
1307 });
1308 return It != ClonedBBs.end() ? (*It).BB : nullptr;
1309 }
1310
1311 /// Helper to get the successor corresponding to a particular case value for
1312 /// a switch statement.
1313 BasicBlock *getNextCaseSuccessor(SwitchInst *Switch, const APInt &NextState) {
1314 BasicBlock *NextCase = nullptr;
1315 for (auto Case : Switch->cases()) {
1316 if (Case.getCaseValue()->getValue() == NextState) {
1317 NextCase = Case.getCaseSuccessor();
1318 break;
1319 }
1320 }
1321 if (!NextCase)
1322 NextCase = Switch->getDefaultDest();
1323 return NextCase;
1324 }
1325
1326 /// Returns true if IncomingBB is a predecessor of BB.
1327 bool isPredecessor(BasicBlock *BB, BasicBlock *IncomingBB) {
1328 return llvm::is_contained(predecessors(BB), IncomingBB);
1329 }
1330
1331 AllSwitchPaths *SwitchPaths;
1332 DominatorTree *DT;
1333 AssumptionCache *AC;
1334 TargetTransformInfo *TTI;
1335 OptimizationRemarkEmitter *ORE;
1336 SmallPtrSet<const Value *, 32> EphValues;
1337 std::vector<ThreadingPath> TPaths;
1338};
1339
1340bool DFAJumpThreading::run(Function &F) {
1341 LLVM_DEBUG(dbgs() << "\nDFA Jump threading: " << F.getName() << "\n");
1342
1343 if (F.hasOptSize()) {
1344 LLVM_DEBUG(dbgs() << "Skipping due to the 'minsize' attribute\n");
1345 return false;
1346 }
1347
1348 if (ClViewCfgBefore)
1349 F.viewCFG();
1350
1351 SmallVector<AllSwitchPaths, 2> ThreadableLoops;
1352 bool MadeChanges = false;
1353 LoopInfoBroken = false;
1354
1355 for (BasicBlock &BB : F) {
1357 if (!SI)
1358 continue;
1359
1360 LLVM_DEBUG(dbgs() << "\nCheck if SwitchInst in BB " << BB.getName()
1361 << " is a candidate\n");
1362 MainSwitch Switch(SI, LI, ORE);
1363
1364 if (!Switch.getInstr()) {
1365 LLVM_DEBUG(dbgs() << "\nSwitchInst in BB " << BB.getName() << " is not a "
1366 << "candidate for jump threading\n");
1367 continue;
1368 }
1369
1370 LLVM_DEBUG(dbgs() << "\nSwitchInst in BB " << BB.getName() << " is a "
1371 << "candidate for jump threading\n");
1372 LLVM_DEBUG(SI->dump());
1373
1374 unfoldSelectInstrs(DT, Switch.getSelectInsts());
1375 if (!Switch.getSelectInsts().empty())
1376 MadeChanges = true;
1377
1378 AllSwitchPaths SwitchPaths(&Switch, ORE, LI,
1379 LI->getLoopFor(&BB)->getOutermostLoop());
1380 SwitchPaths.run();
1381
1382 if (SwitchPaths.getNumThreadingPaths() > 0) {
1383 ThreadableLoops.push_back(SwitchPaths);
1384
1385 // For the time being limit this optimization to occurring once in a
1386 // function since it can change the CFG significantly. This is not a
1387 // strict requirement but it can cause buggy behavior if there is an
1388 // overlap of blocks in different opportunities. There is a lot of room to
1389 // experiment with catching more opportunities here.
1390 // NOTE: To release this contraint, we must handle LoopInfo invalidation
1391 break;
1392 }
1393 }
1394
1395#ifdef NDEBUG
1396 LI->verify(*DT);
1397#endif
1398
1399 SmallPtrSet<const Value *, 32> EphValues;
1400 if (ThreadableLoops.size() > 0)
1401 CodeMetrics::collectEphemeralValues(&F, AC, EphValues);
1402
1403 for (AllSwitchPaths SwitchPaths : ThreadableLoops) {
1404 TransformDFA Transform(&SwitchPaths, DT, AC, TTI, ORE, EphValues);
1405 Transform.run();
1406 MadeChanges = true;
1407 LoopInfoBroken = true;
1408 }
1409
1410#ifdef EXPENSIVE_CHECKS
1411 assert(DT->verify(DominatorTree::VerificationLevel::Full));
1412 verifyFunction(F, &dbgs());
1413#endif
1414
1415 return MadeChanges;
1416}
1417
1418} // end anonymous namespace
1419
1420/// Integrate with the new Pass Manager
1425 LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
1428 DFAJumpThreading ThreadImpl(&AC, &DT, &LI, &TTI, &ORE);
1429 if (!ThreadImpl.run(F))
1430 return PreservedAnalyses::all();
1431
1434 if (!ThreadImpl.LoopInfoBroken)
1435 PA.preserve<LoopAnalysis>();
1436 return PA;
1437}
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:644
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:560
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.