1 //===- llvm/BasicBlock.h - Represent a basic block in the VM ----*- 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 //
9 // This file contains the declaration of the BasicBlock class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_IR_BASICBLOCK_H
14 #define LLVM_IR_BASICBLOCK_H
15
16 #include "llvm-c/Types.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/ADT/iterator.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/IR/DebugProgramInstruction.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/DebugProgramInstruction.h"
25 #include "llvm/IR/SymbolTableListTraits.h"
26 #include "llvm/IR/Value.h"
27 #include <cassert>
28 #include <cstddef>
29 #include <iterator>
30
31 namespace llvm {
32
33 class AssemblyAnnotationWriter;
34 class CallInst;
35 class Function;
36 class LandingPadInst;
37 class LLVMContext;
38 class Module;
39 class PHINode;
40 class ValueSymbolTable;
41 class DPValue;
42 class DPMarker;
43
44 /// LLVM Basic Block Representation
45 ///
46 /// This represents a single basic block in LLVM. A basic block is simply a
47 /// container of instructions that execute sequentially. Basic blocks are Values
48 /// because they are referenced by instructions such as branches and switch
49 /// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
50 /// represents a label to which a branch can jump.
51 ///
52 /// A well formed basic block is formed of a list of non-terminating
53 /// instructions followed by a single terminator instruction. Terminator
54 /// instructions may not occur in the middle of basic blocks, and must terminate
55 /// the blocks. The BasicBlock class allows malformed basic blocks to occur
56 /// because it may be useful in the intermediate stage of constructing or
57 /// modifying a program. However, the verifier will ensure that basic blocks are
58 /// "well formed".
59 class BasicBlock final : public Value, // Basic blocks are data objects also
60 public ilist_node_with_parent<BasicBlock, Function> {
61 public:
62 using InstListType = SymbolTableList<Instruction, ilist_iterator_bits<true>>;
63 /// Flag recording whether or not this block stores debug-info in the form
64 /// of intrinsic instructions (false) or non-instruction records (true).
65 bool IsNewDbgInfoFormat;
66
67 private:
68 friend class BlockAddress;
69 friend class SymbolTableListTraits<BasicBlock>;
70
71 InstListType InstList;
72 Function *Parent;
73
74 public:
75 /// Attach a DPMarker to the given instruction. Enables the storage of any
76 /// debug-info at this position in the program.
77 DPMarker *createMarker(Instruction *I);
78 DPMarker *createMarker(InstListType::iterator It);
79
80 /// Convert variable location debugging information stored in dbg.value
81 /// intrinsics into DPMarkers / DbgRecords. Deletes all dbg.values in
82 /// the process and sets IsNewDbgInfoFormat = true. Only takes effect if
83 /// the UseNewDbgInfoFormat LLVM command line option is given.
84 void convertToNewDbgValues();
85
86 /// Convert variable location debugging information stored in DPMarkers and
87 /// DbgRecords into the dbg.value intrinsic representation. Sets
88 /// IsNewDbgInfoFormat = false.
89 void convertFromNewDbgValues();
90
91 /// Ensure the block is in "old" dbg.value format (\p NewFlag == false) or
92 /// in the new format (\p NewFlag == true), converting to the desired format
93 /// if necessary.
94 void setIsNewDbgInfoFormat(bool NewFlag);
95
96 /// Record that the collection of DbgRecords in \p M "trails" after the last
97 /// instruction of this block. These are equivalent to dbg.value intrinsics
98 /// that exist at the end of a basic block with no terminator (a transient
99 /// state that occurs regularly).
100 void setTrailingDbgRecords(DPMarker *M);
101
102 /// Fetch the collection of DbgRecords that "trail" after the last instruction
103 /// of this block, see \ref setTrailingDbgRecords. If there are none, returns
104 /// nullptr.
105 DPMarker *getTrailingDbgRecords();
106
107 /// Delete any trailing DbgRecords at the end of this block, see
108 /// \ref setTrailingDbgRecords.
109 void deleteTrailingDbgRecords();
110
111 void dumpDbgValues() const;
112
113 /// Return the DPMarker for the position given by \p It, so that DbgRecords
114 /// can be inserted there. This will either be nullptr if not present, a
115 /// DPMarker, or TrailingDbgRecords if It is end().
116 DPMarker *getMarker(InstListType::iterator It);
117
118 /// Return the DPMarker for the position that comes after \p I. \see
119 /// BasicBlock::getMarker, this can be nullptr, a DPMarker, or
120 /// TrailingDbgRecords if there is no next instruction.
121 DPMarker *getNextMarker(Instruction *I);
122
123 /// Insert a DbgRecord into a block at the position given by \p I.
124 void insertDbgRecordAfter(DbgRecord *DPV, Instruction *I);
125
126 /// Insert a DbgRecord into a block at the position given by \p Here.
127 void insertDbgRecordBefore(DbgRecord *DPV, InstListType::iterator Here);
128
129 /// Eject any debug-info trailing at the end of a block. DbgRecords can
130 /// transiently be located "off the end" of a block if the blocks terminator
131 /// is temporarily removed. Once a terminator is re-inserted this method will
132 /// move such DbgRecords back to the right place (ahead of the terminator).
133 void flushTerminatorDbgRecords();
134
135 /// In rare circumstances instructions can be speculatively removed from
136 /// blocks, and then be re-inserted back into that position later. When this
137 /// happens in RemoveDIs debug-info mode, some special patching-up needs to
138 /// occur: inserting into the middle of a sequence of dbg.value intrinsics
139 /// does not have an equivalent with DbgRecords.
140 void reinsertInstInDbgRecords(Instruction *I,
141 std::optional<DbgRecord::self_iterator> Pos);
142
143 private:
144 void setParent(Function *parent);
145
146 /// Constructor.
147 ///
148 /// If the function parameter is specified, the basic block is automatically
149 /// inserted at either the end of the function (if InsertBefore is null), or
150 /// before the specified basic block.
151 explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
152 Function *Parent = nullptr,
153 BasicBlock *InsertBefore = nullptr);
154
155 public:
156 BasicBlock(const BasicBlock &) = delete;
157 BasicBlock &operator=(const BasicBlock &) = delete;
158 ~BasicBlock();
159
160 /// Get the context in which this basic block lives.
161 LLVMContext &getContext() const;
162
163 /// Instruction iterators...
164 using iterator = InstListType::iterator;
165 using const_iterator = InstListType::const_iterator;
166 using reverse_iterator = InstListType::reverse_iterator;
167 using const_reverse_iterator = InstListType::const_reverse_iterator;
168
169 // These functions and classes need access to the instruction list.
170 friend void Instruction::removeFromParent();
171 friend BasicBlock::iterator Instruction::eraseFromParent();
172 friend BasicBlock::iterator Instruction::insertInto(BasicBlock *BB,
173 BasicBlock::iterator It);
174 friend class llvm::SymbolTableListTraits<llvm::Instruction,
175 ilist_iterator_bits<true>>;
176 friend class llvm::ilist_node_with_parent<llvm::Instruction, llvm::BasicBlock,
177 ilist_iterator_bits<true>>;
178
179 // Friendly methods that need to access us for the maintenence of
180 // debug-info attachments.
181 friend void Instruction::insertBefore(BasicBlock::iterator InsertPos);
182 friend void Instruction::insertAfter(Instruction *InsertPos);
183 friend void Instruction::insertBefore(BasicBlock &BB,
184 InstListType::iterator InsertPos);
185 friend void Instruction::moveBeforeImpl(BasicBlock &BB,
186 InstListType::iterator I,
187 bool Preserve);
188 friend iterator_range<DbgRecord::self_iterator>
189 Instruction::cloneDebugInfoFrom(
190 const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,
191 bool InsertAtHead);
192
193 /// Creates a new BasicBlock.
194 ///
195 /// If the Parent parameter is specified, the basic block is automatically
196 /// inserted at either the end of the function (if InsertBefore is 0), or
197 /// before the specified basic block.
198 static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
199 Function *Parent = nullptr,
200 BasicBlock *InsertBefore = nullptr) {
201 return new BasicBlock(Context, Name, Parent, InsertBefore);
202 }
203
204 /// Return the enclosing method, or null if none.
getParent()205 const Function *getParent() const { return Parent; }
getParent()206 Function *getParent() { return Parent; }
207
208 /// Return the module owning the function this basic block belongs to, or
209 /// nullptr if the function does not have a module.
210 ///
211 /// Note: this is undefined behavior if the block does not have a parent.
212 const Module *getModule() const;
getModule()213 Module *getModule() {
214 return const_cast<Module *>(
215 static_cast<const BasicBlock *>(this)->getModule());
216 }
217
218 /// Returns the terminator instruction if the block is well formed or null
219 /// if the block is not well formed.
getTerminator()220 const Instruction *getTerminator() const LLVM_READONLY {
221 if (InstList.empty() || !InstList.back().isTerminator())
222 return nullptr;
223 return &InstList.back();
224 }
getTerminator()225 Instruction *getTerminator() {
226 return const_cast<Instruction *>(
227 static_cast<const BasicBlock *>(this)->getTerminator());
228 }
229
230 /// Returns the call instruction calling \@llvm.experimental.deoptimize
231 /// prior to the terminating return instruction of this basic block, if such
232 /// a call is present. Otherwise, returns null.
233 const CallInst *getTerminatingDeoptimizeCall() const;
getTerminatingDeoptimizeCall()234 CallInst *getTerminatingDeoptimizeCall() {
235 return const_cast<CallInst *>(
236 static_cast<const BasicBlock *>(this)->getTerminatingDeoptimizeCall());
237 }
238
239 /// Returns the call instruction calling \@llvm.experimental.deoptimize
240 /// that is present either in current basic block or in block that is a unique
241 /// successor to current block, if such call is present. Otherwise, returns null.
242 const CallInst *getPostdominatingDeoptimizeCall() const;
getPostdominatingDeoptimizeCall()243 CallInst *getPostdominatingDeoptimizeCall() {
244 return const_cast<CallInst *>(
245 static_cast<const BasicBlock *>(this)->getPostdominatingDeoptimizeCall());
246 }
247
248 /// Returns the call instruction marked 'musttail' prior to the terminating
249 /// return instruction of this basic block, if such a call is present.
250 /// Otherwise, returns null.
251 const CallInst *getTerminatingMustTailCall() const;
getTerminatingMustTailCall()252 CallInst *getTerminatingMustTailCall() {
253 return const_cast<CallInst *>(
254 static_cast<const BasicBlock *>(this)->getTerminatingMustTailCall());
255 }
256
257 /// Returns a pointer to the first instruction in this block that is not a
258 /// PHINode instruction.
259 ///
260 /// When adding instructions to the beginning of the basic block, they should
261 /// be added before the returned value, not before the first instruction,
262 /// which might be PHI. Returns 0 is there's no non-PHI instruction.
263 const Instruction* getFirstNonPHI() const;
getFirstNonPHI()264 Instruction* getFirstNonPHI() {
265 return const_cast<Instruction *>(
266 static_cast<const BasicBlock *>(this)->getFirstNonPHI());
267 }
268
269 /// Iterator returning form of getFirstNonPHI. Installed as a placeholder for
270 /// the RemoveDIs project that will eventually remove debug intrinsics.
271 InstListType::const_iterator getFirstNonPHIIt() const;
getFirstNonPHIIt()272 InstListType::iterator getFirstNonPHIIt() {
273 BasicBlock::iterator It =
274 static_cast<const BasicBlock *>(this)->getFirstNonPHIIt().getNonConst();
275 It.setHeadBit(true);
276 return It;
277 }
278
279 /// Returns a pointer to the first instruction in this block that is not a
280 /// PHINode or a debug intrinsic, or any pseudo operation if \c SkipPseudoOp
281 /// is true.
282 const Instruction *getFirstNonPHIOrDbg(bool SkipPseudoOp = true) const;
283 Instruction *getFirstNonPHIOrDbg(bool SkipPseudoOp = true) {
284 return const_cast<Instruction *>(
285 static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbg(
286 SkipPseudoOp));
287 }
288
289 /// Returns a pointer to the first instruction in this block that is not a
290 /// PHINode, a debug intrinsic, or a lifetime intrinsic, or any pseudo
291 /// operation if \c SkipPseudoOp is true.
292 const Instruction *
293 getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp = true) const;
294 Instruction *getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp = true) {
295 return const_cast<Instruction *>(
296 static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbgOrLifetime(
297 SkipPseudoOp));
298 }
299
300 /// Returns an iterator to the first instruction in this block that is
301 /// suitable for inserting a non-PHI instruction.
302 ///
303 /// In particular, it skips all PHIs and LandingPad instructions.
304 const_iterator getFirstInsertionPt() const;
getFirstInsertionPt()305 iterator getFirstInsertionPt() {
306 return static_cast<const BasicBlock *>(this)
307 ->getFirstInsertionPt().getNonConst();
308 }
309
310 /// Returns an iterator to the first instruction in this block that is
311 /// not a PHINode, a debug intrinsic, a static alloca or any pseudo operation.
312 const_iterator getFirstNonPHIOrDbgOrAlloca() const;
getFirstNonPHIOrDbgOrAlloca()313 iterator getFirstNonPHIOrDbgOrAlloca() {
314 return static_cast<const BasicBlock *>(this)
315 ->getFirstNonPHIOrDbgOrAlloca()
316 .getNonConst();
317 }
318
319 /// Returns the first potential AsynchEH faulty instruction
320 /// currently it checks for loads/stores (which may dereference a null
321 /// pointer) and calls/invokes (which may propagate exceptions)
322 const Instruction* getFirstMayFaultInst() const;
getFirstMayFaultInst()323 Instruction* getFirstMayFaultInst() {
324 return const_cast<Instruction*>(
325 static_cast<const BasicBlock*>(this)->getFirstMayFaultInst());
326 }
327
328 /// Return a const iterator range over the instructions in the block, skipping
329 /// any debug instructions. Skip any pseudo operations as well if \c
330 /// SkipPseudoOp is true.
331 iterator_range<filter_iterator<BasicBlock::const_iterator,
332 std::function<bool(const Instruction &)>>>
333 instructionsWithoutDebug(bool SkipPseudoOp = true) const;
334
335 /// Return an iterator range over the instructions in the block, skipping any
336 /// debug instructions. Skip and any pseudo operations as well if \c
337 /// SkipPseudoOp is true.
338 iterator_range<
339 filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>>
340 instructionsWithoutDebug(bool SkipPseudoOp = true);
341
342 /// Return the size of the basic block ignoring debug instructions
343 filter_iterator<BasicBlock::const_iterator,
344 std::function<bool(const Instruction &)>>::difference_type
345 sizeWithoutDebug() const;
346
347 /// Unlink 'this' from the containing function, but do not delete it.
348 void removeFromParent();
349
350 /// Unlink 'this' from the containing function and delete it.
351 ///
352 // \returns an iterator pointing to the element after the erased one.
353 SymbolTableList<BasicBlock>::iterator eraseFromParent();
354
355 /// Unlink this basic block from its current function and insert it into
356 /// the function that \p MovePos lives in, right before \p MovePos.
moveBefore(BasicBlock * MovePos)357 inline void moveBefore(BasicBlock *MovePos) {
358 moveBefore(MovePos->getIterator());
359 }
360 void moveBefore(SymbolTableList<BasicBlock>::iterator MovePos);
361
362 /// Unlink this basic block from its current function and insert it
363 /// right after \p MovePos in the function \p MovePos lives in.
364 void moveAfter(BasicBlock *MovePos);
365
366 /// Insert unlinked basic block into a function.
367 ///
368 /// Inserts an unlinked basic block into \c Parent. If \c InsertBefore is
369 /// provided, inserts before that basic block, otherwise inserts at the end.
370 ///
371 /// \pre \a getParent() is \c nullptr.
372 void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
373
374 /// Return the predecessor of this block if it has a single predecessor
375 /// block. Otherwise return a null pointer.
376 const BasicBlock *getSinglePredecessor() const;
getSinglePredecessor()377 BasicBlock *getSinglePredecessor() {
378 return const_cast<BasicBlock *>(
379 static_cast<const BasicBlock *>(this)->getSinglePredecessor());
380 }
381
382 /// Return the predecessor of this block if it has a unique predecessor
383 /// block. Otherwise return a null pointer.
384 ///
385 /// Note that unique predecessor doesn't mean single edge, there can be
386 /// multiple edges from the unique predecessor to this block (for example a
387 /// switch statement with multiple cases having the same destination).
388 const BasicBlock *getUniquePredecessor() const;
getUniquePredecessor()389 BasicBlock *getUniquePredecessor() {
390 return const_cast<BasicBlock *>(
391 static_cast<const BasicBlock *>(this)->getUniquePredecessor());
392 }
393
394 /// Return true if this block has exactly N predecessors.
395 bool hasNPredecessors(unsigned N) const;
396
397 /// Return true if this block has N predecessors or more.
398 bool hasNPredecessorsOrMore(unsigned N) const;
399
400 /// Return the successor of this block if it has a single successor.
401 /// Otherwise return a null pointer.
402 ///
403 /// This method is analogous to getSinglePredecessor above.
404 const BasicBlock *getSingleSuccessor() const;
getSingleSuccessor()405 BasicBlock *getSingleSuccessor() {
406 return const_cast<BasicBlock *>(
407 static_cast<const BasicBlock *>(this)->getSingleSuccessor());
408 }
409
410 /// Return the successor of this block if it has a unique successor.
411 /// Otherwise return a null pointer.
412 ///
413 /// This method is analogous to getUniquePredecessor above.
414 const BasicBlock *getUniqueSuccessor() const;
getUniqueSuccessor()415 BasicBlock *getUniqueSuccessor() {
416 return const_cast<BasicBlock *>(
417 static_cast<const BasicBlock *>(this)->getUniqueSuccessor());
418 }
419
420 /// Print the basic block to an output stream with an optional
421 /// AssemblyAnnotationWriter.
422 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
423 bool ShouldPreserveUseListOrder = false,
424 bool IsForDebug = false) const;
425
426 //===--------------------------------------------------------------------===//
427 /// Instruction iterator methods
428 ///
begin()429 inline iterator begin() {
430 iterator It = InstList.begin();
431 // Set the head-inclusive bit to indicate that this iterator includes
432 // any debug-info at the start of the block. This is a no-op unless the
433 // appropriate CMake flag is set.
434 It.setHeadBit(true);
435 return It;
436 }
begin()437 inline const_iterator begin() const {
438 const_iterator It = InstList.begin();
439 It.setHeadBit(true);
440 return It;
441 }
end()442 inline iterator end () { return InstList.end(); }
end()443 inline const_iterator end () const { return InstList.end(); }
444
rbegin()445 inline reverse_iterator rbegin() { return InstList.rbegin(); }
rbegin()446 inline const_reverse_iterator rbegin() const { return InstList.rbegin(); }
rend()447 inline reverse_iterator rend () { return InstList.rend(); }
rend()448 inline const_reverse_iterator rend () const { return InstList.rend(); }
449
size()450 inline size_t size() const { return InstList.size(); }
empty()451 inline bool empty() const { return InstList.empty(); }
front()452 inline const Instruction &front() const { return InstList.front(); }
front()453 inline Instruction &front() { return InstList.front(); }
back()454 inline const Instruction &back() const { return InstList.back(); }
back()455 inline Instruction &back() { return InstList.back(); }
456
457 /// Iterator to walk just the phi nodes in the basic block.
458 template <typename PHINodeT = PHINode, typename BBIteratorT = iterator>
459 class phi_iterator_impl
460 : public iterator_facade_base<phi_iterator_impl<PHINodeT, BBIteratorT>,
461 std::forward_iterator_tag, PHINodeT> {
462 friend BasicBlock;
463
464 PHINodeT *PN;
465
phi_iterator_impl(PHINodeT * PN)466 phi_iterator_impl(PHINodeT *PN) : PN(PN) {}
467
468 public:
469 // Allow default construction to build variables, but this doesn't build
470 // a useful iterator.
471 phi_iterator_impl() = default;
472
473 // Allow conversion between instantiations where valid.
474 template <typename PHINodeU, typename BBIteratorU,
475 typename = std::enable_if_t<
476 std::is_convertible<PHINodeU *, PHINodeT *>::value>>
phi_iterator_impl(const phi_iterator_impl<PHINodeU,BBIteratorU> & Arg)477 phi_iterator_impl(const phi_iterator_impl<PHINodeU, BBIteratorU> &Arg)
478 : PN(Arg.PN) {}
479
480 bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
481
482 PHINodeT &operator*() const { return *PN; }
483
484 using phi_iterator_impl::iterator_facade_base::operator++;
485 phi_iterator_impl &operator++() {
486 assert(PN && "Cannot increment the end iterator!");
487 PN = dyn_cast<PHINodeT>(std::next(BBIteratorT(PN)));
488 return *this;
489 }
490 };
491 using phi_iterator = phi_iterator_impl<>;
492 using const_phi_iterator =
493 phi_iterator_impl<const PHINode, BasicBlock::const_iterator>;
494
495 /// Returns a range that iterates over the phis in the basic block.
496 ///
497 /// Note that this cannot be used with basic blocks that have no terminator.
phis()498 iterator_range<const_phi_iterator> phis() const {
499 return const_cast<BasicBlock *>(this)->phis();
500 }
501 iterator_range<phi_iterator> phis();
502
503 private:
504 /// Return the underlying instruction list container.
505 /// This is deliberately private because we have implemented an adequate set
506 /// of functions to modify the list, including BasicBlock::splice(),
507 /// BasicBlock::erase(), Instruction::insertInto() etc.
getInstList()508 const InstListType &getInstList() const { return InstList; }
getInstList()509 InstListType &getInstList() { return InstList; }
510
511 /// Returns a pointer to a member of the instruction list.
512 /// This is private on purpose, just like `getInstList()`.
getSublistAccess(Instruction *)513 static InstListType BasicBlock::*getSublistAccess(Instruction *) {
514 return &BasicBlock::InstList;
515 }
516
517 /// Dedicated function for splicing debug-info: when we have an empty
518 /// splice (i.e. zero instructions), the caller may still intend any
519 /// debug-info in between the two "positions" to be spliced.
520 void spliceDebugInfoEmptyBlock(BasicBlock::iterator ToIt, BasicBlock *FromBB,
521 BasicBlock::iterator FromBeginIt,
522 BasicBlock::iterator FromEndIt);
523
524 /// Perform any debug-info specific maintenence for the given splice
525 /// activity. In the DbgRecord debug-info representation, debug-info is not
526 /// in instructions, and so it does not automatically move from one block
527 /// to another.
528 void spliceDebugInfo(BasicBlock::iterator ToIt, BasicBlock *FromBB,
529 BasicBlock::iterator FromBeginIt,
530 BasicBlock::iterator FromEndIt);
531 void spliceDebugInfoImpl(BasicBlock::iterator ToIt, BasicBlock *FromBB,
532 BasicBlock::iterator FromBeginIt,
533 BasicBlock::iterator FromEndIt);
534
535 public:
536 /// Returns a pointer to the symbol table if one exists.
537 ValueSymbolTable *getValueSymbolTable();
538
539 /// Methods for support type inquiry through isa, cast, and dyn_cast.
classof(const Value * V)540 static bool classof(const Value *V) {
541 return V->getValueID() == Value::BasicBlockVal;
542 }
543
544 /// Cause all subinstructions to "let go" of all the references that said
545 /// subinstructions are maintaining.
546 ///
547 /// This allows one to 'delete' a whole class at a time, even though there may
548 /// be circular references... first all references are dropped, and all use
549 /// counts go to zero. Then everything is delete'd for real. Note that no
550 /// operations are valid on an object that has "dropped all references",
551 /// except operator delete.
552 void dropAllReferences();
553
554 /// Update PHI nodes in this BasicBlock before removal of predecessor \p Pred.
555 /// Note that this function does not actually remove the predecessor.
556 ///
557 /// If \p KeepOneInputPHIs is true then don't remove PHIs that are left with
558 /// zero or one incoming values, and don't simplify PHIs with all incoming
559 /// values the same.
560 void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs = false);
561
562 bool canSplitPredecessors() const;
563
564 /// Split the basic block into two basic blocks at the specified instruction.
565 ///
566 /// If \p Before is true, splitBasicBlockBefore handles the
567 /// block splitting. Otherwise, execution proceeds as described below.
568 ///
569 /// Note that all instructions BEFORE the specified iterator
570 /// stay as part of the original basic block, an unconditional branch is added
571 /// to the original BB, and the rest of the instructions in the BB are moved
572 /// to the new BB, including the old terminator. The newly formed basic block
573 /// is returned. This function invalidates the specified iterator.
574 ///
575 /// Note that this only works on well formed basic blocks (must have a
576 /// terminator), and \p 'I' must not be the end of instruction list (which
577 /// would cause a degenerate basic block to be formed, having a terminator
578 /// inside of the basic block).
579 ///
580 /// Also note that this doesn't preserve any passes. To split blocks while
581 /// keeping loop information consistent, use the SplitBlock utility function.
582 BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "",
583 bool Before = false);
584 BasicBlock *splitBasicBlock(Instruction *I, const Twine &BBName = "",
585 bool Before = false) {
586 return splitBasicBlock(I->getIterator(), BBName, Before);
587 }
588
589 /// Split the basic block into two basic blocks at the specified instruction
590 /// and insert the new basic blocks as the predecessor of the current block.
591 ///
592 /// This function ensures all instructions AFTER and including the specified
593 /// iterator \p I are part of the original basic block. All Instructions
594 /// BEFORE the iterator \p I are moved to the new BB and an unconditional
595 /// branch is added to the new BB. The new basic block is returned.
596 ///
597 /// Note that this only works on well formed basic blocks (must have a
598 /// terminator), and \p 'I' must not be the end of instruction list (which
599 /// would cause a degenerate basic block to be formed, having a terminator
600 /// inside of the basic block). \p 'I' cannot be a iterator for a PHINode
601 /// with multiple incoming blocks.
602 ///
603 /// Also note that this doesn't preserve any passes. To split blocks while
604 /// keeping loop information consistent, use the SplitBlockBefore utility
605 /// function.
606 BasicBlock *splitBasicBlockBefore(iterator I, const Twine &BBName = "");
607 BasicBlock *splitBasicBlockBefore(Instruction *I, const Twine &BBName = "") {
608 return splitBasicBlockBefore(I->getIterator(), BBName);
609 }
610
611 /// Transfer all instructions from \p FromBB to this basic block at \p ToIt.
splice(BasicBlock::iterator ToIt,BasicBlock * FromBB)612 void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB) {
613 splice(ToIt, FromBB, FromBB->begin(), FromBB->end());
614 }
615
616 /// Transfer one instruction from \p FromBB at \p FromIt to this basic block
617 /// at \p ToIt.
splice(BasicBlock::iterator ToIt,BasicBlock * FromBB,BasicBlock::iterator FromIt)618 void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB,
619 BasicBlock::iterator FromIt) {
620 auto FromItNext = std::next(FromIt);
621 // Single-element splice is a noop if destination == source.
622 if (ToIt == FromIt || ToIt == FromItNext)
623 return;
624 splice(ToIt, FromBB, FromIt, FromItNext);
625 }
626
627 /// Transfer a range of instructions that belong to \p FromBB from \p
628 /// FromBeginIt to \p FromEndIt, to this basic block at \p ToIt.
629 void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB,
630 BasicBlock::iterator FromBeginIt,
631 BasicBlock::iterator FromEndIt);
632
633 /// Erases a range of instructions from \p FromIt to (not including) \p ToIt.
634 /// \Returns \p ToIt.
635 BasicBlock::iterator erase(BasicBlock::iterator FromIt, BasicBlock::iterator ToIt);
636
637 /// Returns true if there are any uses of this basic block other than
638 /// direct branches, switches, etc. to it.
hasAddressTaken()639 bool hasAddressTaken() const {
640 return getBasicBlockBits().BlockAddressRefCount != 0;
641 }
642
643 /// Update all phi nodes in this basic block to refer to basic block \p New
644 /// instead of basic block \p Old.
645 void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New);
646
647 /// Update all phi nodes in this basic block's successors to refer to basic
648 /// block \p New instead of basic block \p Old.
649 void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New);
650
651 /// Update all phi nodes in this basic block's successors to refer to basic
652 /// block \p New instead of to it.
653 void replaceSuccessorsPhiUsesWith(BasicBlock *New);
654
655 /// Return true if this basic block is an exception handling block.
isEHPad()656 bool isEHPad() const { return getFirstNonPHI()->isEHPad(); }
657
658 /// Return true if this basic block is a landing pad.
659 ///
660 /// Being a ``landing pad'' means that the basic block is the destination of
661 /// the 'unwind' edge of an invoke instruction.
662 bool isLandingPad() const;
663
664 /// Return the landingpad instruction associated with the landing pad.
665 const LandingPadInst *getLandingPadInst() const;
getLandingPadInst()666 LandingPadInst *getLandingPadInst() {
667 return const_cast<LandingPadInst *>(
668 static_cast<const BasicBlock *>(this)->getLandingPadInst());
669 }
670
671 /// Return true if it is legal to hoist instructions into this block.
672 bool isLegalToHoistInto() const;
673
674 /// Return true if this is the entry block of the containing function.
675 /// This method can only be used on blocks that have a parent function.
676 bool isEntryBlock() const;
677
678 std::optional<uint64_t> getIrrLoopHeaderWeight() const;
679
680 /// Returns true if the Order field of child Instructions is valid.
isInstrOrderValid()681 bool isInstrOrderValid() const {
682 return getBasicBlockBits().InstrOrderValid;
683 }
684
685 /// Mark instruction ordering invalid. Done on every instruction insert.
invalidateOrders()686 void invalidateOrders() {
687 validateInstrOrdering();
688 BasicBlockBits Bits = getBasicBlockBits();
689 Bits.InstrOrderValid = false;
690 setBasicBlockBits(Bits);
691 }
692
693 /// Renumber instructions and mark the ordering as valid.
694 void renumberInstructions();
695
696 /// Asserts that instruction order numbers are marked invalid, or that they
697 /// are in ascending order. This is constant time if the ordering is invalid,
698 /// and linear in the number of instructions if the ordering is valid. Callers
699 /// should be careful not to call this in ways that make common operations
700 /// O(n^2). For example, it takes O(n) time to assign order numbers to
701 /// instructions, so the order should be validated no more than once after
702 /// each ordering to ensure that transforms have the same algorithmic
703 /// complexity when asserts are enabled as when they are disabled.
704 void validateInstrOrdering() const;
705
706 private:
707 #if defined(_AIX) && (!defined(__GNUC__) || defined(__clang__))
708 // Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
709 // and give the `pack` pragma push semantics.
710 #define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")
711 #define END_TWO_BYTE_PACK() _Pragma("pack(pop)")
712 #else
713 #define BEGIN_TWO_BYTE_PACK()
714 #define END_TWO_BYTE_PACK()
715 #endif
716
717 BEGIN_TWO_BYTE_PACK()
718 /// Bitfield to help interpret the bits in Value::SubclassData.
719 struct BasicBlockBits {
720 unsigned short BlockAddressRefCount : 15;
721 unsigned short InstrOrderValid : 1;
722 };
END_TWO_BYTE_PACK()723 END_TWO_BYTE_PACK()
724
725 #undef BEGIN_TWO_BYTE_PACK
726 #undef END_TWO_BYTE_PACK
727
728 /// Safely reinterpret the subclass data bits to a more useful form.
729 BasicBlockBits getBasicBlockBits() const {
730 static_assert(sizeof(BasicBlockBits) == sizeof(unsigned short),
731 "too many bits for Value::SubclassData");
732 unsigned short ValueData = getSubclassDataFromValue();
733 BasicBlockBits AsBits;
734 memcpy(&AsBits, &ValueData, sizeof(AsBits));
735 return AsBits;
736 }
737
738 /// Reinterpret our subclass bits and store them back into Value.
setBasicBlockBits(BasicBlockBits AsBits)739 void setBasicBlockBits(BasicBlockBits AsBits) {
740 unsigned short D;
741 memcpy(&D, &AsBits, sizeof(D));
742 Value::setValueSubclassData(D);
743 }
744
745 /// Increment the internal refcount of the number of BlockAddresses
746 /// referencing this BasicBlock by \p Amt.
747 ///
748 /// This is almost always 0, sometimes one possibly, but almost never 2, and
749 /// inconceivably 3 or more.
AdjustBlockAddressRefCount(int Amt)750 void AdjustBlockAddressRefCount(int Amt) {
751 BasicBlockBits Bits = getBasicBlockBits();
752 Bits.BlockAddressRefCount += Amt;
753 setBasicBlockBits(Bits);
754 assert(Bits.BlockAddressRefCount < 255 && "Refcount wrap-around");
755 }
756
757 /// Shadow Value::setValueSubclassData with a private forwarding method so
758 /// that any future subclasses cannot accidentally use it.
setValueSubclassData(unsigned short D)759 void setValueSubclassData(unsigned short D) {
760 Value::setValueSubclassData(D);
761 }
762 };
763
764 // Create wrappers for C Binding types (see CBindingWrapping.h).
765 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
766
767 /// Advance \p It while it points to a debug instruction and return the result.
768 /// This assumes that \p It is not at the end of a block.
769 BasicBlock::iterator skipDebugIntrinsics(BasicBlock::iterator It);
770
771 #ifdef NDEBUG
772 /// In release builds, this is a no-op. For !NDEBUG builds, the checks are
773 /// implemented in the .cpp file to avoid circular header deps.
validateInstrOrdering()774 inline void BasicBlock::validateInstrOrdering() const {}
775 #endif
776
777 } // end namespace llvm
778
779 #endif // LLVM_IR_BASICBLOCK_H
780