LLVM 22.0.0git
CFG.h
Go to the documentation of this file.
1//===- CFG.h ----------------------------------------------------*- 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///
10/// This file provides various utilities for inspecting and working with the
11/// control flow graph in LLVM IR. This includes generic facilities for
12/// iterating successors and predecessors of basic blocks, the successors of
13/// specific terminator instructions, etc. It also defines specializations of
14/// GraphTraits that allow Function and BasicBlock graphs to be treated as
15/// proper graphs for generic algorithms.
16///
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_IR_CFG_H
20#define LLVM_IR_CFG_H
21
23#include "llvm/ADT/iterator.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/Value.h"
28#include <cassert>
29#include <cstddef>
30#include <iterator>
31
32namespace llvm {
33
34class Instruction;
35class Use;
36
37//===----------------------------------------------------------------------===//
38// BasicBlock pred_iterator definition
39//===----------------------------------------------------------------------===//
40
41template <class Ptr, class USE_iterator> // Predecessor Iterator
43public:
44 using iterator_category = std::forward_iterator_tag;
45 using value_type = Ptr;
46 using difference_type = std::ptrdiff_t;
47 using pointer = Ptr *;
48 using reference = Ptr *;
49
50protected:
52 USE_iterator It;
53
55 // Loop to ignore non-terminator uses (for example BlockAddresses).
56 while (!It.atEnd()) {
57 if (auto *Inst = dyn_cast<Instruction>(*It)) {
58 assert(Inst->isTerminator() && "BasicBlock used in non-terminator");
59 break;
60 }
61
62 ++It;
63 }
64 }
65
66public:
67 PredIterator() = default;
68 explicit inline PredIterator(Ptr *bb) : It(bb->user_begin()) {
70 }
71 inline PredIterator(Ptr *bb, bool) : It(bb->user_end()) {}
72
73 inline bool operator==(const Self& x) const { return It == x.It; }
74 inline bool operator!=(const Self& x) const { return !operator==(x); }
75
76 inline reference operator*() const {
77 assert(!It.atEnd() && "pred_iterator out of range!");
78 return cast<Instruction>(*It)->getParent();
79 }
80 inline pointer *operator->() const { return &operator*(); }
81
82 inline Self& operator++() { // Preincrement
83 assert(!It.atEnd() && "pred_iterator out of range!");
85 return *this;
86 }
87
88 inline Self operator++(int) { // Postincrement
89 Self tmp = *this; ++*this; return tmp;
90 }
91
92 /// getOperandNo - Return the operand number in the predecessor's
93 /// terminator of the successor.
94 unsigned getOperandNo() const {
95 return It.getOperandNo();
96 }
97
98 /// getUse - Return the operand Use in the predecessor's terminator
99 /// of the successor.
100 Use &getUse() const {
101 return It.getUse();
102 }
103};
104
110
113 return const_pred_iterator(BB);
114}
115inline pred_iterator pred_end(BasicBlock *BB) { return pred_iterator(BB, true);}
117 return const_pred_iterator(BB, true);
118}
119inline bool pred_empty(const BasicBlock *BB) {
120 return pred_begin(BB) == pred_end(BB);
121}
122/// Get the number of predecessors of \p BB. This is a linear time operation.
123/// Use \ref BasicBlock::hasNPredecessors() or hasNPredecessorsOrMore if able.
124inline unsigned pred_size(const BasicBlock *BB) {
125 return std::distance(pred_begin(BB), pred_end(BB));
126}
128 return pred_range(pred_begin(BB), pred_end(BB));
129}
131 return const_pred_range(pred_begin(BB), pred_end(BB));
132}
133
134//===----------------------------------------------------------------------===//
135// Instruction and BasicBlock succ_iterator helpers
136//===----------------------------------------------------------------------===//
137
138template <class InstructionT, class BlockT>
140 : public iterator_facade_base<SuccIterator<InstructionT, BlockT>,
141 std::random_access_iterator_tag, BlockT, int,
142 BlockT *, BlockT *> {
143public:
144 using difference_type = int;
145 using pointer = BlockT *;
146 using reference = BlockT *;
147
148private:
149 InstructionT *Inst;
150 int Idx;
152
153 inline bool index_is_valid(int Idx) {
154 // Note that we specially support the index of zero being valid even in the
155 // face of a null instruction.
156 return Idx >= 0 && (Idx == 0 || Idx <= (int)Inst->getNumSuccessors());
157 }
158
159 /// Proxy object to allow write access in operator[]
160 class SuccessorProxy {
161 Self It;
162
163 public:
164 explicit SuccessorProxy(const Self &It) : It(It) {}
165
166 SuccessorProxy(const SuccessorProxy &) = default;
167
168 SuccessorProxy &operator=(SuccessorProxy RHS) {
169 *this = reference(RHS);
170 return *this;
171 }
172
173 SuccessorProxy &operator=(reference RHS) {
174 It.Inst->setSuccessor(It.Idx, RHS);
175 return *this;
176 }
177
178 operator reference() const { return *It; }
179 };
180
181public:
182 // begin iterator
183 explicit inline SuccIterator(InstructionT *Inst) : Inst(Inst), Idx(0) {}
184 // end iterator
185 inline SuccIterator(InstructionT *Inst, bool) : Inst(Inst) {
186 if (Inst)
187 Idx = Inst->getNumSuccessors();
188 else
189 // Inst == NULL happens, if a basic block is not fully constructed and
190 // consequently getTerminator() returns NULL. In this case we construct
191 // a SuccIterator which describes a basic block that has zero
192 // successors.
193 // Defining SuccIterator for incomplete and malformed CFGs is especially
194 // useful for debugging.
195 Idx = 0;
196 }
197
198 /// This is used to interface between code that wants to
199 /// operate on terminator instructions directly.
200 int getSuccessorIndex() const { return Idx; }
201
202 inline bool operator==(const Self &x) const { return Idx == x.Idx; }
203
204 inline BlockT *operator*() const { return Inst->getSuccessor(Idx); }
205
206 // We use the basic block pointer directly for operator->.
207 inline BlockT *operator->() const { return operator*(); }
208
209 inline bool operator<(const Self &RHS) const {
210 assert(Inst == RHS.Inst && "Cannot compare iterators of different blocks!");
211 return Idx < RHS.Idx;
212 }
213
214 int operator-(const Self &RHS) const {
215 assert(Inst == RHS.Inst && "Cannot compare iterators of different blocks!");
216 return Idx - RHS.Idx;
217 }
218
219 inline Self &operator+=(int RHS) {
220 int NewIdx = Idx + RHS;
221 assert(index_is_valid(NewIdx) && "Iterator index out of bound");
222 Idx = NewIdx;
223 return *this;
224 }
225
226 inline Self &operator-=(int RHS) { return operator+=(-RHS); }
227
228 // Specially implement the [] operation using a proxy object to support
229 // assignment.
230 inline SuccessorProxy operator[](int Offset) {
231 Self TmpIt = *this;
232 TmpIt += Offset;
233 return SuccessorProxy(TmpIt);
234 }
235
236 /// Get the source BlockT of this iterator.
237 inline BlockT *getSource() {
238 assert(Inst && "Source not available, if basic block was malformed");
239 return Inst->getParent();
240 }
241};
242
247
250 return const_succ_iterator(I);
251}
254 return const_succ_iterator(I, true);
255}
256inline bool succ_empty(const Instruction *I) {
257 return succ_begin(I) == succ_end(I);
258}
259inline unsigned succ_size(const Instruction *I) {
260 return std::distance(succ_begin(I), succ_end(I));
261}
263 return succ_range(succ_begin(I), succ_end(I));
264}
267}
268
270 return succ_iterator(BB->getTerminator());
271}
274}
276 return succ_iterator(BB->getTerminator(), true);
277}
279 return const_succ_iterator(BB->getTerminator(), true);
280}
281inline bool succ_empty(const BasicBlock *BB) {
282 return succ_begin(BB) == succ_end(BB);
283}
284inline unsigned succ_size(const BasicBlock *BB) {
285 return std::distance(succ_begin(BB), succ_end(BB));
286}
288 return succ_range(succ_begin(BB), succ_end(BB));
289}
291 return const_succ_range(succ_begin(BB), succ_end(BB));
292}
293
294//===--------------------------------------------------------------------===//
295// GraphTraits specializations for basic block graphs (CFGs)
296//===--------------------------------------------------------------------===//
297
298// Provide specializations of GraphTraits to be able to treat a function as a
299// graph of basic blocks...
300
301template <> struct GraphTraits<BasicBlock*> {
304
305 static NodeRef getEntryNode(BasicBlock *BB) { return BB; }
308
309 static unsigned getNumber(const BasicBlock *BB) { return BB->getNumber(); }
310};
311
312static_assert(GraphHasNodeNumbers<BasicBlock *>,
313 "GraphTraits getNumber() not detected");
314
315template <> struct GraphTraits<const BasicBlock*> {
316 using NodeRef = const BasicBlock *;
318
319 static NodeRef getEntryNode(const BasicBlock *BB) { return BB; }
320
323
324 static unsigned getNumber(const BasicBlock *BB) { return BB->getNumber(); }
325};
326
327static_assert(GraphHasNodeNumbers<const BasicBlock *>,
328 "GraphTraits getNumber() not detected");
329
330// Provide specializations of GraphTraits to be able to treat a function as a
331// graph of basic blocks... and to walk it in inverse order. Inverse order for
332// a function is considered to be when traversing the predecessor edges of a BB
333// instead of the successor edges.
334//
335template <> struct GraphTraits<Inverse<BasicBlock*>> {
338
339 static NodeRef getEntryNode(Inverse<BasicBlock *> G) { return G.Graph; }
342
343 static unsigned getNumber(const BasicBlock *BB) { return BB->getNumber(); }
344};
345
346static_assert(GraphHasNodeNumbers<Inverse<BasicBlock *>>,
347 "GraphTraits getNumber() not detected");
348
349template <> struct GraphTraits<Inverse<const BasicBlock*>> {
350 using NodeRef = const BasicBlock *;
352
356
357 static unsigned getNumber(const BasicBlock *BB) { return BB->getNumber(); }
358};
359
360static_assert(GraphHasNodeNumbers<Inverse<const BasicBlock *>>,
361 "GraphTraits getNumber() not detected");
362
363//===--------------------------------------------------------------------===//
364// GraphTraits specializations for function basic block graphs (CFGs)
365//===--------------------------------------------------------------------===//
366
367// Provide specializations of GraphTraits to be able to treat a function as a
368// graph of basic blocks... these are the same as the basic block iterators,
369// except that the root node is implicitly the first node of the function.
370//
371template <> struct GraphTraits<Function*> : public GraphTraits<BasicBlock*> {
372 static NodeRef getEntryNode(Function *F) { return &F->getEntryBlock(); }
373
374 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
376
378 return nodes_iterator(F->begin());
379 }
380
382 return nodes_iterator(F->end());
383 }
384
385 static size_t size(Function *F) { return F->size(); }
386
387 static unsigned getMaxNumber(const Function *F) {
388 return F->getMaxBlockNumber();
389 }
390 static unsigned getNumberEpoch(const Function *F) {
391 return F->getBlockNumberEpoch();
392 }
393};
394template <> struct GraphTraits<const Function*> :
396 static NodeRef getEntryNode(const Function *F) { return &F->getEntryBlock(); }
397
398 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
400
402 return nodes_iterator(F->begin());
403 }
404
406 return nodes_iterator(F->end());
407 }
408
409 static size_t size(const Function *F) { return F->size(); }
410
411 static unsigned getMaxNumber(const Function *F) {
412 return F->getMaxBlockNumber();
413 }
414 static unsigned getNumberEpoch(const Function *F) {
415 return F->getBlockNumberEpoch();
416 }
417};
418
419// Provide specializations of GraphTraits to be able to treat a function as a
420// graph of basic blocks... and to walk it in inverse order. Inverse order for
421// a function is considered to be when traversing the predecessor edges of a BB
422// instead of the successor edges.
423//
424template <> struct GraphTraits<Inverse<Function*>> :
427 return &G.Graph->getEntryBlock();
428 }
429
430 static unsigned getMaxNumber(const Function *F) {
431 return F->getMaxBlockNumber();
432 }
433 static unsigned getNumberEpoch(const Function *F) {
434 return F->getBlockNumberEpoch();
435 }
436};
437template <> struct GraphTraits<Inverse<const Function*>> :
440 return &G.Graph->getEntryBlock();
441 }
442
443 static unsigned getMaxNumber(const Function *F) {
444 return F->getMaxBlockNumber();
445 }
446 static unsigned getNumberEpoch(const Function *F) {
447 return F->getBlockNumberEpoch();
448 }
449};
450
451} // end namespace llvm
452
453#endif // LLVM_IR_CFG_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
Value * RHS
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
unsigned getNumber() const
Definition: BasicBlock.h:95
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:233
bool operator==(const Self &x) const
Definition: CFG.h:73
Self & operator++()
Definition: CFG.h:82
Ptr * pointer
Definition: CFG.h:47
PredIterator(Ptr *bb)
Definition: CFG.h:68
void advancePastNonTerminators()
Definition: CFG.h:54
PredIterator()=default
Self operator++(int)
Definition: CFG.h:88
PredIterator(Ptr *bb, bool)
Definition: CFG.h:71
bool operator!=(const Self &x) const
Definition: CFG.h:74
USE_iterator It
Definition: CFG.h:52
std::forward_iterator_tag iterator_category
Definition: CFG.h:44
reference operator*() const
Definition: CFG.h:76
Ptr value_type
Definition: CFG.h:45
std::ptrdiff_t difference_type
Definition: CFG.h:46
pointer * operator->() const
Definition: CFG.h:80
unsigned getOperandNo() const
getOperandNo - Return the operand number in the predecessor's terminator of the successor.
Definition: CFG.h:94
Use & getUse() const
getUse - Return the operand Use in the predecessor's terminator of the successor.
Definition: CFG.h:100
Ptr * reference
Definition: CFG.h:48
bool operator==(const Self &x) const
Definition: CFG.h:202
SuccIterator(InstructionT *Inst, bool)
Definition: CFG.h:185
int difference_type
Definition: CFG.h:144
Self & operator-=(int RHS)
Definition: CFG.h:226
BlockT * reference
Definition: CFG.h:146
int getSuccessorIndex() const
This is used to interface between code that wants to operate on terminator instructions directly.
Definition: CFG.h:200
BlockT * operator->() const
Definition: CFG.h:207
bool operator<(const Self &RHS) const
Definition: CFG.h:209
BlockT * operator*() const
Definition: CFG.h:204
BlockT * getSource()
Get the source BlockT of this iterator.
Definition: CFG.h:237
SuccessorProxy operator[](int Offset)
Definition: CFG.h:230
BlockT * pointer
Definition: CFG.h:145
Self & operator+=(int RHS)
Definition: CFG.h:219
int operator-(const Self &RHS) const
Definition: CFG.h:214
SuccIterator(InstructionT *Inst)
Definition: CFG.h:183
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition: iterator.h:80
A range adaptor for a pair of iterators.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
NodeAddr< UseNode * > Use
Definition: RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:477
bool succ_empty(const Instruction *I)
Definition: CFG.h:256
auto pred_end(const MachineBasicBlock *BB)
auto successors(const MachineBasicBlock *BB)
auto pred_size(const MachineBasicBlock *BB)
SuccIterator< Instruction, BasicBlock > succ_iterator
Definition: CFG.h:243
iterator_range< succ_iterator > succ_range
Definition: CFG.h:245
auto succ_size(const MachineBasicBlock *BB)
iterator_range< const_succ_iterator > const_succ_range
Definition: CFG.h:246
iterator_range< pred_iterator > pred_range
Definition: CFG.h:108
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
iterator_range< const_pred_iterator > const_pred_range
Definition: CFG.h:109
auto pred_begin(const MachineBasicBlock *BB)
PredIterator< const BasicBlock, Value::const_user_iterator > const_pred_iterator
Definition: CFG.h:107
auto predecessors(const MachineBasicBlock *BB)
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:119
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition: CFG.h:105
SuccIterator< const Instruction, const BasicBlock > const_succ_iterator
Definition: CFG.h:244
#define N
static NodeRef getEntryNode(BasicBlock *BB)
Definition: CFG.h:305
static ChildIteratorType child_begin(NodeRef N)
Definition: CFG.h:306
static unsigned getNumber(const BasicBlock *BB)
Definition: CFG.h:309
static ChildIteratorType child_end(NodeRef N)
Definition: CFG.h:307
static unsigned getMaxNumber(const Function *F)
Definition: CFG.h:387
static nodes_iterator nodes_begin(Function *F)
Definition: CFG.h:377
static unsigned getNumberEpoch(const Function *F)
Definition: CFG.h:390
static nodes_iterator nodes_end(Function *F)
Definition: CFG.h:381
static size_t size(Function *F)
Definition: CFG.h:385
static NodeRef getEntryNode(Function *F)
Definition: CFG.h:372
static ChildIteratorType child_begin(NodeRef N)
Definition: CFG.h:340
static unsigned getNumber(const BasicBlock *BB)
Definition: CFG.h:343
static ChildIteratorType child_end(NodeRef N)
Definition: CFG.h:341
static NodeRef getEntryNode(Inverse< BasicBlock * > G)
Definition: CFG.h:339
static unsigned getNumberEpoch(const Function *F)
Definition: CFG.h:433
static unsigned getMaxNumber(const Function *F)
Definition: CFG.h:430
static NodeRef getEntryNode(Inverse< Function * > G)
Definition: CFG.h:426
static ChildIteratorType child_end(NodeRef N)
Definition: CFG.h:355
static NodeRef getEntryNode(Inverse< const BasicBlock * > G)
Definition: CFG.h:353
static ChildIteratorType child_begin(NodeRef N)
Definition: CFG.h:354
static unsigned getNumber(const BasicBlock *BB)
Definition: CFG.h:357
static unsigned getMaxNumber(const Function *F)
Definition: CFG.h:443
static NodeRef getEntryNode(Inverse< const Function * > G)
Definition: CFG.h:439
static unsigned getNumberEpoch(const Function *F)
Definition: CFG.h:446
static ChildIteratorType child_begin(NodeRef N)
Definition: CFG.h:321
static unsigned getNumber(const BasicBlock *BB)
Definition: CFG.h:324
static NodeRef getEntryNode(const BasicBlock *BB)
Definition: CFG.h:319
static ChildIteratorType child_end(NodeRef N)
Definition: CFG.h:322
static size_t size(const Function *F)
Definition: CFG.h:409
static nodes_iterator nodes_begin(const Function *F)
Definition: CFG.h:401
static NodeRef getEntryNode(const Function *F)
Definition: CFG.h:396
static unsigned getNumberEpoch(const Function *F)
Definition: CFG.h:414
static unsigned getMaxNumber(const Function *F)
Definition: CFG.h:411
static nodes_iterator nodes_end(const Function *F)
Definition: CFG.h:405