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