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