LLVM 24.0.0git
MustExecute.h
Go to the documentation of this file.
1//===- MustExecute.h - Is an instruction known to execute--------*- C++ -*-===//
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/// \file
9/// Contains a collection of routines for determining if a given instruction is
10/// guaranteed to execute if a given point in control flow is reached. The most
11/// common example is an instruction within a loop being provably executed if we
12/// branch to the header of it's containing loop.
13///
14/// There are two interfaces available to determine if an instruction is
15/// executed once a given point in the control flow is reached:
16/// 1) A loop-centric one derived from LoopSafetyInfo.
17/// 2) A "must be executed context"-based one implemented in the
18/// MustBeExecutedContextExplorer.
19/// Please refer to the class comments for more information.
20///
21//===----------------------------------------------------------------------===//
22
23#ifndef LLVM_ANALYSIS_MUSTEXECUTE_H
24#define LLVM_ANALYSIS_MUSTEXECUTE_H
25
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/DenseSet.h"
30#include "llvm/IR/PassManager.h"
32
33namespace llvm {
34
35namespace {
36template <typename T> using GetterTy = std::function<T *(const Function &F)>;
37}
38
39class BasicBlock;
40class DominatorTree;
41class Loop;
42class LoopInfo;
44class raw_ostream;
45
46/// Captures loop safety information.
47/// It keep information for loop blocks may throw exception or otherwise
48/// exit abnormally on any iteration of the loop which might actually execute
49/// at runtime. The primary way to consume this information is via
50/// isGuaranteedToExecute below, but some callers bailout or fallback to
51/// alternate reasoning if a loop contains any implicit control flow.
52/// NOTE: LoopSafetyInfo contains cached information regarding loops and their
53/// particular blocks. Cached information may not be valid after control flow
54/// changes.
56 // Used to update funclet bundle operands.
58
59 // Cache whether (the start of) this block is guaranteed to execute if the
60 // loop is entered.
61 mutable DenseMap<const BasicBlock *, bool> GuaranteedToExecute;
62
63 bool allLoopPathsLeadToBlockImpl(const BasicBlock *BB,
64 const DominatorTree *DT) const;
65
66protected:
67 const Loop *CurLoop;
68
69 /// Computes block colors.
71
72public:
73 /// Returns block colors map that is used to update funclet operand bundles.
75
76 /// Copy colors of block \p Old into the block \p New.
78
79 /// Returns true iff the block \p BB potentially may throw exception. It can
80 /// be false-positive in cases when we want to avoid complex analysis.
81 virtual bool blockMayThrow(const BasicBlock *BB) const = 0;
82
83 /// Returns true iff any block of the loop for which this info is contains an
84 /// instruction that may throw or otherwise exit abnormally.
85 virtual bool anyBlockMayThrow() const = 0;
86
87 /// Return true if we must reach the block \p BB under assumption that the
88 /// loop is entered.
90 const DominatorTree *DT) const;
91
92 /// Returns true if the instruction in a loop is guaranteed to execute at
93 /// least once (under the assumption that the loop is entered).
94 virtual bool isGuaranteedToExecute(const Instruction &Inst,
95 const DominatorTree *DT) const = 0;
96
98
99 virtual ~LoopSafetyInfo() = default;
100};
101
102
103/// Simple and conservative implementation of LoopSafetyInfo that can give
104/// false-positive answers to its queries in order to avoid complicated
105/// analysis.
107 bool MayThrow = false; // The current loop contains an instruction which
108 // may throw.
109 bool HeaderMayThrow = false; // Same as previous, but specific to loop header
110
111 void computeLoopSafetyInfo();
112
113public:
114 explicit SimpleLoopSafetyInfo(const Loop *L) : LoopSafetyInfo(L) {
115 computeLoopSafetyInfo();
116 }
117
118 bool blockMayThrow(const BasicBlock *BB) const override;
119
120 bool anyBlockMayThrow() const override;
121
122 bool isGuaranteedToExecute(const Instruction &Inst,
123 const DominatorTree *DT) const override;
124};
125
126/// This implementation of LoopSafetyInfo use ImplicitControlFlowTracking to
127/// give precise answers on "may throw" queries. This implementation uses cache
128/// that should be invalidated by calling the methods insertInstructionTo and
129/// removeInstruction whenever we modify a basic block's contents by adding or
130/// removing instructions.
132 bool MayThrow = false; // The current loop contains an instruction which
133 // may throw.
134 // Contains information about implicit control flow in this loop's blocks.
135 mutable ImplicitControlFlowTracking ICF;
136 // Contains information about instruction that may possibly write memory.
137 mutable MemoryWriteTracking MW;
138
139 void computeLoopSafetyInfo();
140
141public:
142 explicit ICFLoopSafetyInfo(const Loop *L) : LoopSafetyInfo(L) {
143 computeLoopSafetyInfo();
144 }
145
146 bool blockMayThrow(const BasicBlock *BB) const override;
147
148 bool anyBlockMayThrow() const override;
149
150 bool isGuaranteedToExecute(const Instruction &Inst,
151 const DominatorTree *DT) const override;
152
153 /// Returns true if we could not execute a memory-modifying instruction before
154 /// we enter \p BB under assumption that the loop is entered.
155 bool doesNotWriteMemoryBefore(const BasicBlock *BB) const;
156
157 /// Returns true if we could not execute a memory-modifying instruction before
158 /// we execute \p I under assumption that the loop is entered.
159 bool doesNotWriteMemoryBefore(const Instruction &I) const;
160
161 /// Inform the safety info that we are planning to insert a new instruction
162 /// \p Inst into the basic block \p BB. It will make all cache updates to keep
163 /// it correct after this insertion.
164 void insertInstructionTo(const Instruction *Inst, const BasicBlock *BB);
165
166 /// Inform safety info that we are planning to remove the instruction \p Inst
167 /// from its block. It will make all cache updates to keep it correct after
168 /// this removal.
169 void removeInstruction(const Instruction *Inst);
170};
171
173 const LoopInfo *LI);
174
175struct MustBeExecutedContextExplorer;
176
177/// Enum that allows us to spell out the direction.
181};
182
183/// Must be executed iterators visit stretches of instructions that are
184/// guaranteed to be executed together, potentially with other instruction
185/// executed in-between.
186///
187/// Given the following code, and assuming all statements are single
188/// instructions which transfer execution to the successor (see
189/// isGuaranteedToTransferExecutionToSuccessor), there are two possible
190/// outcomes. If we start the iterator at A, B, or E, we will visit only A, B,
191/// and E. If we start at C or D, we will visit all instructions A-E.
192///
193/// \code
194/// A;
195/// B;
196/// if (...) {
197/// C;
198/// D;
199/// }
200/// E;
201/// \endcode
202///
203///
204/// Below is the example extneded with instructions F and G. Now we assume F
205/// might not transfer execution to it's successor G. As a result we get the
206/// following visit sets:
207///
208/// Start Instruction | Visit Set
209/// A | A, B, E, F
210/// B | A, B, E, F
211/// C | A, B, C, D, E, F
212/// D | A, B, C, D, E, F
213/// E | A, B, E, F
214/// F | A, B, E, F
215/// G | A, B, E, F, G
216///
217///
218/// \code
219/// A;
220/// B;
221/// if (...) {
222/// C;
223/// D;
224/// }
225/// E;
226/// F; // Might not transfer execution to its successor G.
227/// G;
228/// \endcode
229///
230///
231/// A more complex example involving conditionals, loops, break, and continue
232/// is shown below. We again assume all instructions will transmit control to
233/// the successor and we assume we can prove the inner loop to be finite. We
234/// omit non-trivial branch conditions as the exploration is oblivious to them.
235/// Constant branches are assumed to be unconditional in the CFG. The resulting
236/// visist sets are shown in the table below.
237///
238/// \code
239/// A;
240/// while (true) {
241/// B;
242/// if (...)
243/// C;
244/// if (...)
245/// continue;
246/// D;
247/// if (...)
248/// break;
249/// do {
250/// if (...)
251/// continue;
252/// E;
253/// } while (...);
254/// F;
255/// }
256/// G;
257/// \endcode
258///
259/// Start Instruction | Visit Set
260/// A | A, B
261/// B | A, B
262/// C | A, B, C
263/// D | A, B, D
264/// E | A, B, D, E, F
265/// F | A, B, D, F
266/// G | A, B, D, G
267///
268///
269/// Note that the examples show optimal visist sets but not necessarily the ones
270/// derived by the explorer depending on the available CFG analyses (see
271/// MustBeExecutedContextExplorer). Also note that we, depending on the options,
272/// the visit set can contain instructions from other functions.
274 /// Type declarations that make his class an input iterator.
275 ///{
276 typedef const Instruction *value_type;
277 typedef std::ptrdiff_t difference_type;
278 typedef const Instruction **pointer;
279 typedef const Instruction *&reference;
280 typedef std::input_iterator_tag iterator_category;
281 ///}
282
284
286
288 : Visited(std::move(Other.Visited)), Explorer(Other.Explorer),
289 CurInst(Other.CurInst), Head(Other.Head), Tail(Other.Tail) {}
290
292 if (this != &Other) {
293 std::swap(Visited, Other.Visited);
294 std::swap(CurInst, Other.CurInst);
295 std::swap(Head, Other.Head);
296 std::swap(Tail, Other.Tail);
297 }
298 return *this;
299 }
300
302
303 /// Pre- and post-increment operators.
304 ///{
306 CurInst = advance();
307 return *this;
308 }
309
311 MustBeExecutedIterator tmp(*this);
312 operator++();
313 return tmp;
314 }
315 ///}
316
317 /// Equality and inequality operators. Note that we ignore the history here.
318 ///{
320 return CurInst == Other.CurInst && Head == Other.Head && Tail == Other.Tail;
321 }
322
324 return !(*this == Other);
325 }
326 ///}
327
328 /// Return the underlying instruction.
329 const Instruction *&operator*() { return CurInst; }
330 const Instruction *getCurrentInst() const { return CurInst; }
331
332 /// Return true if \p I was encountered by this iterator already.
333 bool count(const Instruction *I) const {
334 return Visited.count({I, ExplorationDirection::FORWARD}) ||
335 Visited.count({I, ExplorationDirection::BACKWARD});
336 }
337
338private:
339 using VisitedSetTy =
341
342 /// Private constructors.
344
345 /// Reset the iterator to its initial state pointing at \p I.
346 void reset(const Instruction *I);
347
348 /// Reset the iterator to point at \p I, keep cached state.
349 void resetInstruction(const Instruction *I);
350
351 /// Try to advance one of the underlying positions (Head or Tail).
352 ///
353 /// \return The next instruction in the must be executed context, or nullptr
354 /// if none was found.
355 LLVM_ABI const Instruction *advance();
356
357 /// A set to track the visited instructions in order to deal with endless
358 /// loops and recursion.
359 VisitedSetTy Visited;
360
361 /// A reference to the explorer that created this iterator.
362 ExplorerTy &Explorer;
363
364 /// The instruction we are currently exposing to the user. There is always an
365 /// instruction that we know is executed with the given program point,
366 /// initially the program point itself.
367 const Instruction *CurInst;
368
369 /// Two positions that mark the program points where this iterator will look
370 /// for the next instruction. Note that the current instruction is either the
371 /// one pointed to by Head, Tail, or both.
372 const Instruction *Head, *Tail;
373
375};
376
377/// A "must be executed context" for a given program point PP is the set of
378/// instructions, potentially before and after PP, that are executed always when
379/// PP is reached. The MustBeExecutedContextExplorer an interface to explore
380/// "must be executed contexts" in a module through the use of
381/// MustBeExecutedIterator.
382///
383/// The explorer exposes "must be executed iterators" that traverse the must be
384/// executed context. There is little information sharing between iterators as
385/// the expected use case involves few iterators for "far apart" instructions.
386/// If that changes, we should consider caching more intermediate results.
388
389 /// In the description of the parameters we use PP to denote a program point
390 /// for which the must be executed context is explored, or put differently,
391 /// for which the MustBeExecutedIterator is created.
392 ///
393 /// \param ExploreInterBlock Flag to indicate if instructions in blocks
394 /// other than the parent of PP should be
395 /// explored.
396 /// \param ExploreCFGForward Flag to indicate if instructions located after
397 /// PP in the CFG, e.g., post-dominating PP,
398 /// should be explored.
399 /// \param ExploreCFGBackward Flag to indicate if instructions located
400 /// before PP in the CFG, e.g., dominating PP,
401 /// should be explored.
404 GetterTy<const LoopInfo> LIGetter =
405 [](const Function &) { return nullptr; },
406 GetterTy<const DominatorTree> DTGetter =
407 [](const Function &) { return nullptr; },
408 GetterTy<const PostDominatorTree> PDTGetter =
409 [](const Function &) { return nullptr; })
412 ExploreCFGBackward(ExploreCFGBackward), LIGetter(LIGetter),
413 DTGetter(DTGetter), PDTGetter(PDTGetter), EndIterator(*this, nullptr) {}
414
415 /// Iterator-based interface. \see MustBeExecutedIterator.
416 ///{
419
420 /// Return an iterator to explore the context around \p PP.
422 auto &It = InstructionIteratorMap[PP];
423 if (!It)
424 It.reset(new iterator(*this, PP));
425 return *It;
426 }
427
428 /// Return an iterator to explore the cached context around \p PP.
429 const_iterator &begin(const Instruction *PP) const {
430 return *InstructionIteratorMap.find(PP)->second;
431 }
432
433 /// Return an universal end iterator.
434 ///{
435 iterator &end() { return EndIterator; }
436 iterator &end(const Instruction *) { return EndIterator; }
437
438 const_iterator &end() const { return EndIterator; }
439 const_iterator &end(const Instruction *) const { return EndIterator; }
440 ///}
441
442 /// Return an iterator range to explore the context around \p PP.
446
447 /// Return an iterator range to explore the cached context around \p PP.
449 return llvm::make_range(begin(PP), end(PP));
450 }
451 ///}
452
453 /// Check \p Pred on all instructions in the context.
454 ///
455 /// This method will evaluate \p Pred and return
456 /// true if \p Pred holds in every instruction.
458 function_ref<bool(const Instruction *)> Pred) {
459 for (auto EIt = begin(PP), EEnd = end(PP); EIt != EEnd; ++EIt)
460 if (!Pred(*EIt))
461 return false;
462 return true;
463 }
464
465 /// Helper to look for \p I in the context of \p PP.
466 ///
467 /// The context is expanded until \p I was found or no more expansion is
468 /// possible.
469 ///
470 /// \returns True, iff \p I was found.
471 bool findInContextOf(const Instruction *I, const Instruction *PP) {
472 auto EIt = begin(PP), EEnd = end(PP);
473 return findInContextOf(I, EIt, EEnd);
474 }
475
476 /// Helper to look for \p I in the context defined by \p EIt and \p EEnd.
477 ///
478 /// The context is expanded until \p I was found or no more expansion is
479 /// possible.
480 ///
481 /// \returns True, iff \p I was found.
482 bool findInContextOf(const Instruction *I, iterator &EIt, iterator &EEnd) {
483 bool Found = EIt.count(I);
484 while (!Found && EIt != EEnd)
485 Found = (++EIt).getCurrentInst() == I;
486 return Found;
487 }
488
489 /// Return the next instruction that is guaranteed to be executed after \p PP.
490 ///
491 /// \param It The iterator that is used to traverse the must be
492 /// executed context.
493 /// \param PP The program point for which the next instruction
494 /// that is guaranteed to execute is determined.
495 LLVM_ABI const Instruction *
497 const Instruction *PP);
498 /// Return the previous instr. that is guaranteed to be executed before \p PP.
499 ///
500 /// \param It The iterator that is used to traverse the must be
501 /// executed context.
502 /// \param PP The program point for which the previous instr.
503 /// that is guaranteed to execute is determined.
504 LLVM_ABI const Instruction *
506 const Instruction *PP);
507
508 /// Find the next join point from \p InitBB in forward direction.
510
511 /// Find the next join point from \p InitBB in backward direction.
513
514 /// Parameter that limit the performed exploration. See the constructor for
515 /// their meaning.
516 ///{
520 ///}
521
522private:
523 /// Getters for common CFG analyses: LoopInfo, DominatorTree, and
524 /// PostDominatorTree.
525 ///{
526 GetterTy<const LoopInfo> LIGetter;
527 GetterTy<const DominatorTree> DTGetter;
528 GetterTy<const PostDominatorTree> PDTGetter;
529 ///}
530
531 /// Map to cache isGuaranteedToTransferExecutionToSuccessor results.
533
534 /// Map to cache containsIrreducibleCFG results.
536
537 /// Map from instructions to associated must be executed iterators.
539 InstructionIteratorMap;
540
541 /// A unique end iterator.
542 MustBeExecutedIterator EndIterator;
543};
544
546 : public RequiredPassInfoMixin<MustExecutePrinterPass> {
547 raw_ostream &OS;
548
549public:
552};
553
555 : public RequiredPassInfoMixin<MustBeExecutedContextPrinterPass> {
556 raw_ostream &OS;
557
558public:
561};
562
563} // namespace llvm
564
565#endif
#define LLVM_ABI
Definition Compiler.h:215
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
ICFLoopSafetyInfo(const Loop *L)
This class allows to keep track on instructions with implicit control flow.
LLVM_ABI void copyColors(BasicBlock *New, BasicBlock *Old)
Copy colors of block Old into the block New.
LoopSafetyInfo(const Loop *CurLoop)
Definition MustExecute.h:97
LLVM_ABI const DenseMap< BasicBlock *, ColorVector > & getBlockColors() const
Returns block colors map that is used to update funclet operand bundles.
LLVM_ABI void computeBlockColors()
Computes block colors.
virtual ~LoopSafetyInfo()=default
LLVM_ABI bool allLoopPathsLeadToBlock(const BasicBlock *BB, const DominatorTree *DT) const
Return true if we must reach the block BB under assumption that the loop is entered.
virtual bool anyBlockMayThrow() const =0
Returns true iff any block of the loop for which this info is contains an instruction that may throw ...
virtual bool blockMayThrow(const BasicBlock *BB) const =0
Returns true iff the block BB potentially may throw exception.
virtual bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT) const =0
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
const Loop * CurLoop
Definition MustExecute.h:67
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
MustBeExecutedContextPrinterPass(raw_ostream &OS)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
MustExecutePrinterPass(raw_ostream &OS)
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
SimpleLoopSafetyInfo(const Loop *L)
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
@ Other
Any other memory.
Definition ModRef.h:68
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool mayContainIrreducibleControl(const Function &F, const LoopInfo *LI)
ExplorationDirection
Enum that allows us to spell out the direction.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
const bool ExploreInterBlock
Parameter that limit the performed exploration.
const_iterator & begin(const Instruction *PP) const
Return an iterator to explore the cached context around PP.
LLVM_ABI const BasicBlock * findBackwardJoinPoint(const BasicBlock *InitBB)
Find the next join point from InitBB in backward direction.
LLVM_ABI const Instruction * getMustBeExecutedNextInstruction(MustBeExecutedIterator &It, const Instruction *PP)
Return the next instruction that is guaranteed to be executed after PP.
iterator & end()
Return an universal end iterator.
MustBeExecutedContextExplorer(bool ExploreInterBlock, bool ExploreCFGForward, bool ExploreCFGBackward, GetterTy< const LoopInfo > LIGetter=[](const Function &) { return nullptr;}, GetterTy< const DominatorTree > DTGetter=[](const Function &) { return nullptr;}, GetterTy< const PostDominatorTree > PDTGetter=[](const Function &) { return nullptr;})
In the description of the parameters we use PP to denote a program point for which the must be execut...
bool findInContextOf(const Instruction *I, const Instruction *PP)
Helper to look for I in the context of PP.
const_iterator & end() const
iterator & begin(const Instruction *PP)
Return an iterator to explore the context around PP.
llvm::iterator_range< iterator > range(const Instruction *PP)
}
LLVM_ABI const Instruction * getMustBeExecutedPrevInstruction(MustBeExecutedIterator &It, const Instruction *PP)
Return the previous instr.
bool checkForAllContext(const Instruction *PP, function_ref< bool(const Instruction *)> Pred)
}
LLVM_ABI const BasicBlock * findForwardJoinPoint(const BasicBlock *InitBB)
Find the next join point from InitBB in forward direction.
const_iterator & end(const Instruction *) const
bool findInContextOf(const Instruction *I, iterator &EIt, iterator &EEnd)
Helper to look for I in the context defined by EIt and EEnd.
iterator & end(const Instruction *)
llvm::iterator_range< const_iterator > range(const Instruction *PP) const
Return an iterator range to explore the cached context around PP.
const MustBeExecutedIterator const_iterator
MustBeExecutedIterator iterator
Iterator-based interface.
Must be executed iterators visit stretches of instructions that are guaranteed to be executed togethe...
bool operator!=(const MustBeExecutedIterator &Other) const
const Instruction * value_type
Type declarations that make his class an input iterator.
MustBeExecutedIterator(const MustBeExecutedIterator &Other)=default
MustBeExecutedContextExplorer ExplorerTy
}
const Instruction *& reference
const Instruction ** pointer
const Instruction * getCurrentInst() const
bool operator==(const MustBeExecutedIterator &Other) const
}
std::input_iterator_tag iterator_category
MustBeExecutedIterator(MustBeExecutedIterator &&Other)
MustBeExecutedIterator & operator=(MustBeExecutedIterator &&Other)
bool count(const Instruction *I) const
Return true if I was encountered by this iterator already.
MustBeExecutedIterator operator++(int)
friend struct MustBeExecutedContextExplorer
MustBeExecutedIterator & operator++()
Pre- and post-increment operators.
const Instruction *& operator*()
}
A CRTP mix-in for passes that should not be skipped.