LLVM 24.0.0git
BasicBlock.h
Go to the documentation of this file.
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/DenseMap.h"
18#include "llvm/ADT/Twine.h"
19#include "llvm/ADT/ilist.h"
20#include "llvm/ADT/ilist_node.h"
21#include "llvm/ADT/iterator.h"
24#include "llvm/IR/Instruction.h"
26#include "llvm/IR/Value.h"
28#include <cassert>
29#include <cstddef>
30#include <iterator>
31
32namespace llvm {
33
35class CallInst;
36class DataLayout;
37class Function;
38class LandingPadInst;
39class LLVMContext;
40class Module;
41class PHINode;
44class DbgMarker;
45
46/// LLVM Basic Block Representation
47///
48/// This represents a single basic block in LLVM. A basic block is simply a
49/// container of instructions that execute sequentially. Basic blocks are Values
50/// because they are referenced by instructions such as branches and switch
51/// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
52/// represents a label to which a branch can jump.
53///
54/// A well formed basic block is formed of a list of non-terminating
55/// instructions followed by a single terminator instruction. Terminator
56/// instructions may not occur in the middle of basic blocks, and must terminate
57/// the blocks. The BasicBlock class allows malformed basic blocks to occur
58/// because it may be useful in the intermediate stage of constructing or
59/// modifying a program. However, the verifier will ensure that basic blocks are
60/// "well formed".
61class BasicBlock final : public Value, // Basic blocks are data objects also
62 public ilist_node_with_parent<BasicBlock, Function> {
63public:
66
67private:
68 // Allow Function to renumber blocks.
69 friend class Function;
70 /// Per-function unique number.
71 unsigned Number = ~0u;
72
73 friend class BlockAddress;
74 friend class SymbolTableListTraits<BasicBlock>;
75
76 InstListType InstList;
77 Function *Parent;
78
79public:
80 /// Attach a DbgMarker to the given instruction. Enables the storage of any
81 /// debug-info at this position in the program.
84
85 /// Convert variable location debugging information stored in dbg.value
86 /// intrinsics into DbgMarkers / DbgRecords. Deletes all dbg.values in
87 /// the process and sets IsNewDbgInfoFormat = true.
89
90 /// Convert variable location debugging information stored in DbgMarkers and
91 /// DbgRecords into the dbg.value intrinsic representation. Sets
92 /// IsNewDbgInfoFormat = false.
94
95 unsigned getNumber() const {
96 assert(getParent() && "only basic blocks in functions have valid numbers");
97 return Number;
98 }
99
100 /// Record that the collection of DbgRecords in \p M "trails" after the last
101 /// instruction of this block. These are equivalent to dbg.value intrinsics
102 /// that exist at the end of a basic block with no terminator (a transient
103 /// state that occurs regularly).
105
106 /// Fetch the collection of DbgRecords that "trail" after the last instruction
107 /// of this block, see \ref setTrailingDbgRecords. If there are none, returns
108 /// nullptr.
110
111 /// Delete any trailing DbgRecords at the end of this block, see
112 /// \ref setTrailingDbgRecords.
114
115 LLVM_ABI void dumpDbgValues() const;
116
117 /// Return the DbgMarker for the position given by \p It, so that DbgRecords
118 /// can be inserted there. This will either be nullptr if not present, a
119 /// DbgMarker, or TrailingDbgRecords if It is end().
121
122 /// Return the DbgMarker for the position that comes after \p I. \see
123 /// BasicBlock::getMarker, this can be nullptr, a DbgMarker, or
124 /// TrailingDbgRecords if there is no next instruction.
126
127 /// Insert a DbgRecord into a block at the position given by \p I.
129
130 /// Insert a DbgRecord into a block at the position given by \p Here.
133
134 /// Eject any debug-info trailing at the end of a block. DbgRecords can
135 /// transiently be located "off the end" of a block if the blocks terminator
136 /// is temporarily removed. Once a terminator is re-inserted this method will
137 /// move such DbgRecords back to the right place (ahead of the terminator).
139
140 /// In rare circumstances instructions can be speculatively removed from
141 /// blocks, and then be re-inserted back into that position later. When this
142 /// happens in RemoveDIs debug-info mode, some special patching-up needs to
143 /// occur: inserting into the middle of a sequence of dbg.value intrinsics
144 /// does not have an equivalent with DbgRecords.
145 LLVM_ABI void
147 std::optional<DbgRecord::self_iterator> Pos);
148
149private:
150 void setParent(Function *parent);
151
152 /// Constructor.
153 ///
154 /// If the function parameter is specified, the basic block is automatically
155 /// inserted at either the end of the function (if InsertBefore is null), or
156 /// before the specified basic block.
157 LLVM_ABI explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
158 Function *Parent = nullptr,
159 BasicBlock *InsertBefore = nullptr);
160
161public:
162 BasicBlock(const BasicBlock &) = delete;
163 BasicBlock &operator=(const BasicBlock &) = delete;
165
166 /// Get the context in which this basic block lives.
168
169 /// Instruction iterators...
174
175 // These functions and classes need access to the instruction list.
180 friend class llvm::SymbolTableListTraits<
181 llvm::Instruction, ilist_iterator_bits<true>, ilist_parent<BasicBlock>>;
182 friend class llvm::ilist_node_with_parent<llvm::Instruction, llvm::BasicBlock,
183 ilist_iterator_bits<true>,
184 ilist_parent<BasicBlock>>;
185
186 // Friendly methods that need to access us for the maintenence of
187 // debug-info attachments.
188 friend void Instruction::insertBefore(BasicBlock::iterator InsertPos);
189 friend void Instruction::insertAfter(Instruction *InsertPos);
190 friend void Instruction::insertAfter(BasicBlock::iterator InsertPos);
191 friend void Instruction::insertBefore(BasicBlock &BB,
192 InstListType::iterator InsertPos);
193 friend void Instruction::moveBeforeImpl(BasicBlock &BB,
194 InstListType::iterator I,
195 bool Preserve);
196 friend iterator_range<DbgRecord::self_iterator>
198 const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,
199 bool InsertAtHead);
200
201 /// Creates a new BasicBlock.
202 ///
203 /// If the Parent parameter is specified, the basic block is automatically
204 /// inserted at either the end of the function (if InsertBefore is 0), or
205 /// before the specified basic block.
206 static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
207 Function *Parent = nullptr,
208 BasicBlock *InsertBefore = nullptr) {
209 return new BasicBlock(Context, Name, Parent, InsertBefore);
210 }
211
212 /// Return the enclosing method, or null if none.
213 const Function *getParent() const { return Parent; }
214 Function *getParent() { return Parent; }
215
216 /// Return the module owning the function this basic block belongs to, or
217 /// nullptr if the function does not have a module.
218 ///
219 /// Note: this is undefined behavior if the block does not have a parent.
220 LLVM_ABI const Module *getModule() const;
222 return const_cast<Module *>(
223 static_cast<const BasicBlock *>(this)->getModule());
224 }
225
226 /// Get the data layout of the module this basic block belongs to.
227 ///
228 /// Requires the basic block to have a parent module.
229 LLVM_ABI const DataLayout &getDataLayout() const;
230
231 /// Returns whether the block has a terminator.
233 return !InstList.empty() && InstList.back().isTerminator();
234 }
235
236 /// Returns the terminator instruction; assumes that the block is well-formed.
238 assert(hasTerminator() && "cannot get terminator of non-well-formed block");
239 return &InstList.back();
240 }
242 return const_cast<Instruction *>(
243 static_cast<const BasicBlock *>(this)->getTerminator());
244 }
245
246 /// Returns the terminator instruction if the block is well formed or
247 /// null if the block is not well formed.
249 return hasTerminator() ? getTerminator() : nullptr;
250 }
252 return hasTerminator() ? getTerminator() : nullptr;
253 }
254
255 /// Returns the call instruction calling \@llvm.experimental.deoptimize
256 /// prior to the terminating return instruction of this basic block, if such
257 /// a call is present. Otherwise, returns null.
260 return const_cast<CallInst *>(
261 static_cast<const BasicBlock *>(this)->getTerminatingDeoptimizeCall());
262 }
263
264 /// Returns the call instruction calling \@llvm.experimental.deoptimize
265 /// that is present either in current basic block or in block that is a unique
266 /// successor to current block, if such call is present. Otherwise, returns
267 /// null.
270 return const_cast<CallInst *>(static_cast<const BasicBlock *>(this)
271 ->getPostdominatingDeoptimizeCall());
272 }
273
274 /// Returns the call instruction marked 'musttail' prior to the terminating
275 /// return instruction of this basic block, if such a call is present.
276 /// Otherwise, returns null.
279 return const_cast<CallInst *>(
280 static_cast<const BasicBlock *>(this)->getTerminatingMustTailCall());
281 }
282
283 /// Returns an iterator to the first instruction in this block that is not a
284 /// PHINode instruction.
285 ///
286 /// When adding instructions to the beginning of the basic block, they should
287 /// be added before the returned value, not before the first instruction,
288 /// which might be PHI. Returns end() if there's no non-PHI instruction.
289 ///
290 /// Avoid unwrapping the iterator to an Instruction* before inserting here,
291 /// as important debug-info is preserved in the iterator.
295 static_cast<const BasicBlock *>(this)->getFirstNonPHIIt().getNonConst();
296 It.setHeadBit(true);
297 return It;
298 }
299
300 /// Returns an iterator to the first instruction in this block that is not a
301 /// PHINode or a pseudo operation.
304 return static_cast<const BasicBlock *>(this)
306 .getNonConst();
307 }
308
309 /// Returns an iterator to the first instruction in this block that is not a
310 /// PHINode, a lifetime intrinsic, or a pseudo operation.
313 return static_cast<const BasicBlock *>(this)
315 .getNonConst();
316 }
317
318 /// Returns an iterator to the first instruction in this block that is
319 /// suitable for inserting a non-PHI instruction.
320 ///
321 /// In particular, it skips all PHIs and LandingPad instructions.
324 return static_cast<const BasicBlock *>(this)
326 .getNonConst();
327 }
328
329 /// Returns true if there is a valid insertion point for non-PHI instructions
330 /// in this block. Returns false for blocks that can only contain PHI nodes,
331 /// such as blocks with a catchswitch terminator.
332 ///
333 /// This is an O(1) check, unlike getFirstInsertionPt() which must scan
334 /// through all PHI nodes.
335 bool hasInsertionPt() const {
336 return getTerminator()->getOpcode() != Instruction::CatchSwitch;
337 }
338
339 /// Returns an iterator to the first instruction in this block that is
340 /// not a PHINode, a static alloca, or any pseudo operation.
343 return static_cast<const BasicBlock *>(this)
345 .getNonConst();
346 }
347
348 /// Returns the first potential AsynchEH faulty instruction
349 /// currently it checks for loads/stores (which may dereference a null
350 /// pointer) and calls/invokes (which may propagate exceptions)
353 return const_cast<Instruction *>(
354 static_cast<const BasicBlock *>(this)->getFirstMayFaultInst());
355 }
356
357 /// Unlink 'this' from the containing function, but do not delete it.
359
360 /// Unlink 'this' from the containing function and delete it.
361 ///
362 // \returns an iterator pointing to the element after the erased one.
364
365 /// Unlink this basic block from its current function and insert it into
366 /// the function that \p MovePos lives in, right before \p MovePos.
367 inline void moveBefore(BasicBlock *MovePos) {
368 moveBefore(MovePos->getIterator());
369 }
371
372 /// Unlink this basic block from its current function and insert it
373 /// right after \p MovePos in the function \p MovePos lives in.
374 LLVM_ABI void moveAfter(BasicBlock *MovePos);
375
376 /// Insert unlinked basic block into a function.
377 ///
378 /// Inserts an unlinked basic block into \c Parent. If \c InsertBefore is
379 /// provided, inserts before that basic block, otherwise inserts at the end.
380 ///
381 /// \pre \a getParent() is \c nullptr.
382 LLVM_ABI void insertInto(Function *Parent,
383 BasicBlock *InsertBefore = nullptr);
384
385 /// Return the predecessor of this block if it has a single predecessor
386 /// block. Otherwise return a null pointer.
388 BasicBlock *getSinglePredecessor() {
389 return const_cast<BasicBlock *>(
390 static_cast<const BasicBlock *>(this)->getSinglePredecessor());
391 }
392
393 /// Return the predecessor of this block if it has a unique predecessor
394 /// block. Otherwise return a null pointer.
395 ///
396 /// Note that unique predecessor doesn't mean single edge, there can be
397 /// multiple edges from the unique predecessor to this block (for example a
398 /// switch statement with multiple cases having the same destination).
400 BasicBlock *getUniquePredecessor() {
401 return const_cast<BasicBlock *>(
402 static_cast<const BasicBlock *>(this)->getUniquePredecessor());
403 }
404
405 /// Return true if this block has exactly N predecessors.
406 LLVM_ABI bool hasNPredecessors(unsigned N) const;
407
408 /// Return true if this block has N predecessors or more.
409 LLVM_ABI bool hasNPredecessorsOrMore(unsigned N) const;
410
411 /// Return the successor of this block if it has a single successor.
412 /// Otherwise return a null pointer.
413 ///
414 /// This method is analogous to getSinglePredecessor above.
416 BasicBlock *getSingleSuccessor() {
417 return const_cast<BasicBlock *>(
418 static_cast<const BasicBlock *>(this)->getSingleSuccessor());
419 }
420
421 /// Return the successor of this block if it has a unique successor.
422 /// Otherwise return a null pointer.
423 ///
424 /// This method is analogous to getUniquePredecessor above.
426 BasicBlock *getUniqueSuccessor() {
427 return const_cast<BasicBlock *>(
428 static_cast<const BasicBlock *>(this)->getUniqueSuccessor());
429 }
430
431 /// Print the basic block to an output stream with an optional
432 /// AssemblyAnnotationWriter.
433 LLVM_ABI void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
434 bool ShouldPreserveUseListOrder = false,
435 bool IsForDebug = false) const;
436
437 //===--------------------------------------------------------------------===//
438 /// Instruction iterator methods
439 ///
440 inline iterator begin() {
441 iterator It = InstList.begin();
442 // Set the head-inclusive bit to indicate that this iterator includes
443 // any debug-info at the start of the block. This is a no-op unless the
444 // appropriate CMake flag is set.
445 It.setHeadBit(true);
446 return It;
447 }
448 inline const_iterator begin() const {
449 const_iterator It = InstList.begin();
450 It.setHeadBit(true);
451 return It;
452 }
453 inline iterator end() { return InstList.end(); }
454 inline const_iterator end() const { return InstList.end(); }
455
456 inline reverse_iterator rbegin() { return InstList.rbegin(); }
457 inline const_reverse_iterator rbegin() const { return InstList.rbegin(); }
458 inline reverse_iterator rend() { return InstList.rend(); }
459 inline const_reverse_iterator rend() const { return InstList.rend(); }
460
461 inline size_t size() const { return InstList.size(); }
462 inline bool empty() const { return InstList.empty(); }
463 inline const Instruction &front() const { return InstList.front(); }
464 inline Instruction &front() { return InstList.front(); }
465 inline const Instruction &back() const { return InstList.back(); }
466 inline Instruction &back() { return InstList.back(); }
467
468 /// Iterator to walk just the phi nodes in the basic block.
469 template <typename PHINodeT = PHINode, typename BBIteratorT = iterator>
470 class phi_iterator_impl
471 : public iterator_facade_base<phi_iterator_impl<PHINodeT, BBIteratorT>,
472 std::forward_iterator_tag, PHINodeT> {
473 friend BasicBlock;
474
475 PHINodeT *PN;
476
477 phi_iterator_impl(PHINodeT *PN) : PN(PN) {}
478
479 public:
480 // Allow default construction to build variables, but this doesn't build
481 // a useful iterator.
482 phi_iterator_impl() = default;
483
484 // Allow conversion between instantiations where valid.
485 template <typename PHINodeU, typename BBIteratorU,
486 typename = std::enable_if_t<
487 std::is_convertible<PHINodeU *, PHINodeT *>::value>>
488 phi_iterator_impl(const phi_iterator_impl<PHINodeU, BBIteratorU> &Arg)
489 : PN(Arg.PN) {}
490
491 bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
492
493 PHINodeT &operator*() const { return *PN; }
494
495 using phi_iterator_impl::iterator_facade_base::operator++;
496 phi_iterator_impl &operator++() {
497 assert(PN && "Cannot increment the end iterator!");
498 PN = dyn_cast<PHINodeT>(std::next(BBIteratorT(PN)));
499 return *this;
500 }
501 };
505
506 /// Returns a range that iterates over the phis in the basic block.
507 ///
508 /// Note that this cannot be used with basic blocks that have no terminator.
510 return const_cast<BasicBlock *>(this)->phis();
511 }
513
514private:
515 /// Return the underlying instruction list container.
516 /// This is deliberately private because we have implemented an adequate set
517 /// of functions to modify the list, including BasicBlock::splice(),
518 /// BasicBlock::erase(), Instruction::insertInto() etc.
519 const InstListType &getInstList() const { return InstList; }
520 InstListType &getInstList() { return InstList; }
521
522 /// Returns a pointer to a member of the instruction list.
523 /// This is private on purpose, just like `getInstList()`.
524 static InstListType BasicBlock::*getSublistAccess(Instruction *) {
525 return &BasicBlock::InstList;
526 }
527
528 /// Dedicated function for splicing debug-info: when we have an empty
529 /// splice (i.e. zero instructions), the caller may still intend any
530 /// debug-info in between the two "positions" to be spliced.
531 void spliceDebugInfoEmptyBlock(BasicBlock::iterator ToIt, BasicBlock *FromBB,
532 BasicBlock::iterator FromBeginIt,
533 BasicBlock::iterator FromEndIt);
534
535 /// Perform any debug-info specific maintenence for the given splice
536 /// activity. In the DbgRecord debug-info representation, debug-info is not
537 /// in instructions, and so it does not automatically move from one block
538 /// to another.
539 void spliceDebugInfo(BasicBlock::iterator ToIt, BasicBlock *FromBB,
540 BasicBlock::iterator FromBeginIt,
541 BasicBlock::iterator FromEndIt);
542 void spliceDebugInfoImpl(BasicBlock::iterator ToIt, BasicBlock *FromBB,
543 BasicBlock::iterator FromBeginIt,
544 BasicBlock::iterator FromEndIt);
545
546 enum {
547 HasAddressTaken = 1 << 0,
548 InstrOrderValid = 1 << 1,
549 };
550
551 void setHasAddressTaken(bool B) {
552 if (B)
553 SubclassOptionalData |= HasAddressTaken;
554 else
555 SubclassOptionalData &= ~HasAddressTaken;
556 }
557
558 /// Shadow Value::setValueSubclassData with a private forwarding method so
559 /// that any future subclasses cannot accidentally use it.
560 void setValueSubclassData(unsigned short D) {
562 }
563
564public:
565 /// Returns a pointer to the symbol table if one exists.
566 LLVM_ABI ValueSymbolTable *getValueSymbolTable();
567
568 /// Methods for support type inquiry through isa, cast, and dyn_cast.
569 static bool classof(const Value *V) {
570 return V->getValueID() == Value::BasicBlockVal;
571 }
572
573 /// Cause all subinstructions to "let go" of all the references that said
574 /// subinstructions are maintaining.
575 ///
576 /// This allows one to 'delete' a whole class at a time, even though there may
577 /// be circular references... first all references are dropped, and all use
578 /// counts go to zero. Then everything is delete'd for real. Note that no
579 /// operations are valid on an object that has "dropped all references",
580 /// except operator delete.
582
583 /// Update PHI nodes in this BasicBlock before removal of predecessor \p Pred.
584 /// Note that this function does not actually remove the predecessor.
585 ///
586 /// If \p KeepOneInputPHIs is true then don't remove PHIs that are left with
587 /// zero or one incoming values, and don't simplify PHIs with all incoming
588 /// values the same.
590 bool KeepOneInputPHIs = false);
591
592 LLVM_ABI bool canSplitPredecessors() const;
593
594 /// Split the basic block into two basic blocks at the specified instruction.
595 ///
596 /// Note that all instructions BEFORE the specified iterator
597 /// stay as part of the original basic block, an unconditional branch is added
598 /// to the original BB, and the rest of the instructions in the BB are moved
599 /// to the new BB, including the old terminator. The newly formed basic block
600 /// is returned. This function invalidates the specified iterator.
601 ///
602 /// Note that this only works on well formed basic blocks (must have a
603 /// terminator), and \p 'I' must not be the end of instruction list (which
604 /// would cause a degenerate basic block to be formed, having a terminator
605 /// inside of the basic block).
606 ///
607 /// Also note that this doesn't preserve any passes. To split blocks while
608 /// keeping loop information consistent, use the SplitBlock utility function.
609 LLVM_ABI BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
610 BasicBlock *splitBasicBlock(Instruction *I, const Twine &BBName = "") {
611 return splitBasicBlock(I->getIterator(), BBName);
612 }
613
614 /// Split the basic block into two basic blocks at the specified instruction
615 /// and insert the new basic blocks as the predecessor of the current block.
616 ///
617 /// This function ensures all instructions AFTER and including the specified
618 /// iterator \p I are part of the original basic block. All Instructions
619 /// BEFORE the iterator \p I are moved to the new BB and an unconditional
620 /// branch is added to the new BB. The new basic block is returned.
621 ///
622 /// Note that this only works on well formed basic blocks (must have a
623 /// terminator), and \p 'I' must not be the end of instruction list (which
624 /// would cause a degenerate basic block to be formed, having a terminator
625 /// inside of the basic block). \p 'I' cannot be a iterator for a PHINode
626 /// with multiple incoming blocks.
627 ///
628 /// Also note that this doesn't preserve any passes. To split blocks while
629 /// keeping loop information consistent, use the SplitBlockBefore utility
630 /// function.
632 const Twine &BBName = "");
633 BasicBlock *splitBasicBlockBefore(Instruction *I, const Twine &BBName = "") {
634 return splitBasicBlockBefore(I->getIterator(), BBName);
635 }
636
637 /// Transfer all instructions from \p FromBB to this basic block at \p ToIt.
638 void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB) {
639 splice(ToIt, FromBB, FromBB->begin(), FromBB->end());
640 }
641
642 /// Transfer one instruction from \p FromBB at \p FromIt to this basic block
643 /// at \p ToIt.
644 void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB,
645 BasicBlock::iterator FromIt) {
646 auto FromItNext = std::next(FromIt);
647 // Single-element splice is a noop if destination == source.
648 if (ToIt == FromIt || ToIt == FromItNext)
649 return;
650 splice(ToIt, FromBB, FromIt, FromItNext);
651 }
652
653 /// Transfer a range of instructions that belong to \p FromBB from \p
654 /// FromBeginIt to \p FromEndIt, to this basic block at \p ToIt.
656 BasicBlock::iterator FromBeginIt,
657 BasicBlock::iterator FromEndIt);
658
659 /// Erases a range of instructions from \p FromIt to (not including) \p ToIt.
660 /// \Returns \p ToIt.
663
664 /// Returns true if there are any uses of this basic block other than
665 /// direct branches, switches, etc. to it.
666 bool hasAddressTaken() const {
667 return SubclassOptionalData & HasAddressTaken;
668 }
669
670 /// Update all phi nodes in this basic block to refer to basic block \p New
671 /// instead of basic block \p Old.
673
674 /// Update all phi nodes in this basic block's successors to refer to basic
675 /// block \p New instead of basic block \p Old.
677
678 /// Update all phi nodes in this basic block's successors to refer to basic
679 /// block \p New instead of to it.
681
682 /// Return true if this basic block is an exception handling block.
683 bool isEHPad() const { return getFirstNonPHIIt()->isEHPad(); }
684
685 /// Return true if this basic block is a landing pad.
686 ///
687 /// Being a ``landing pad'' means that the basic block is the destination of
688 /// the 'unwind' edge of an invoke instruction.
689 LLVM_ABI bool isLandingPad() const;
690
691 /// Return the landingpad instruction associated with the landing pad.
694 return const_cast<LandingPadInst *>(
695 static_cast<const BasicBlock *>(this)->getLandingPadInst());
696 }
697
698 /// Return true if it is legal to hoist instructions into this block.
699 LLVM_ABI bool isLegalToHoistInto() const;
700
701 /// Return true if this is the entry block of the containing function.
702 /// This method can only be used on blocks that have a parent function.
703 LLVM_ABI bool isEntryBlock() const;
704
705 LLVM_ABI std::optional<uint64_t> getIrrLoopHeaderWeight() const;
706
707 /// Returns true if the Order field of child Instructions is valid.
708 bool isInstrOrderValid() const {
709 return SubclassOptionalData & InstrOrderValid;
710 }
711
712 /// Mark instruction ordering invalid. Done on every instruction insert.
715 SubclassOptionalData &= ~InstrOrderValid;
716 }
717
718 /// Renumber instructions and mark the ordering as valid.
720
721 /// Asserts that instruction order numbers are marked invalid, or that they
722 /// are in ascending order. This is constant time if the ordering is invalid,
723 /// and linear in the number of instructions if the ordering is valid. Callers
724 /// should be careful not to call this in ways that make common operations
725 /// O(n^2). For example, it takes O(n) time to assign order numbers to
726 /// instructions, so the order should be validated no more than once after
727 /// each ordering to ensure that transforms have the same algorithmic
728 /// complexity when asserts are enabled as when they are disabled.
729 LLVM_ABI void validateInstrOrdering() const;
730};
731
732// Create wrappers for C Binding types (see CBindingWrapping.h).
734
735#ifdef NDEBUG
736/// In release builds, this is a no-op. For !NDEBUG builds, the checks are
737/// implemented in the .cpp file to avoid circular header deps.
738inline void BasicBlock::validateInstrOrdering() const {}
739#endif
740
741// Specialize DenseMapInfo for iterators, so that ththey can be installed into
742// maps and sets. The iterator is made up of its node pointer, and the
743// debug-info "head" bit.
744template <> struct DenseMapInfo<BasicBlock::iterator> {
745 static unsigned getHashValue(const BasicBlock::iterator &It) {
747 reinterpret_cast<void *>(It.getNodePtr())) ^
748 (unsigned)It.getHeadBit();
749 }
750
751 static bool isEqual(const BasicBlock::iterator &LHS,
752 const BasicBlock::iterator &RHS) {
753 return LHS == RHS && LHS.getHeadBit() == RHS.getHeadBit();
754 }
755};
756
757} // end namespace llvm
758
759#endif // LLVM_IR_BASICBLOCK_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref)
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_READONLY
Definition Compiler.h:338
This file defines the DenseMap class.
#define I(x, y, z)
Definition MD5.cpp:57
Value * RHS
Value * LHS
Iterator to walk just the phi nodes in the basic block.
Definition BasicBlock.h:472
bool operator==(const phi_iterator_impl &Arg) const
Definition BasicBlock.h:491
phi_iterator_impl(const phi_iterator_impl< PHINodeU, BBIteratorU > &Arg)
Definition BasicBlock.h:488
phi_iterator_impl & operator++()
Definition BasicBlock.h:496
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI BasicBlock::iterator erase(BasicBlock::iterator FromIt, BasicBlock::iterator ToIt)
Erases a range of instructions from FromIt to (not including) ToIt.
bool hasInsertionPt() const
Returns true if there is a valid insertion point for non-PHI instructions in this block.
Definition BasicBlock.h:335
phi_iterator_impl<> phi_iterator
Definition BasicBlock.h:502
LLVM_ABI void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of basic bl...
BasicBlock(const BasicBlock &)=delete
iterator end()
Definition BasicBlock.h:453
unsigned getNumber() const
Definition BasicBlock.h:95
Instruction * getFirstMayFaultInst()
Definition BasicBlock.h:352
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
LLVM_ABI void deleteTrailingDbgRecords()
Delete any trailing DbgRecords at the end of this block, see setTrailingDbgRecords.
InstListType::iterator getFirstNonPHIOrLifetime()
Definition BasicBlock.h:312
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 LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
LLVM_ABI void setTrailingDbgRecords(DbgMarker *M)
Record that the collection of DbgRecords in M "trails" after the last instruction of this block.
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...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
reverse_iterator rbegin()
Definition BasicBlock.h:456
bool hasTerminator() const LLVM_READONLY
Returns whether the block has a terminator.
Definition BasicBlock.h:232
static bool classof(const Value *V)
Methods for support type inquiry through isa, cast, and dyn_cast.
Definition BasicBlock.h:569
LLVM_ABI void renumberInstructions()
Renumber instructions and mark the ordering as valid.
InstListType::iterator getFirstNonPHIIt()
Definition BasicBlock.h:293
bool empty() const
Definition BasicBlock.h:462
LLVM_ABI DbgMarker * createMarker(Instruction *I)
Attach a DbgMarker to the given instruction.
const Instruction & back() const
Definition BasicBlock.h:465
LLVM_ABI BasicBlock * splitBasicBlockBefore(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction and insert the new basic blo...
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
BasicBlock * splitBasicBlockBefore(Instruction *I, const Twine &BBName="")
Definition BasicBlock.h:633
void invalidateOrders()
Mark instruction ordering invalid. Done on every instruction insert.
Definition BasicBlock.h:713
friend void Instruction::removeFromParent()
LLVM_ABI void convertToNewDbgValues()
Convert variable location debugging information stored in dbg.value intrinsics into DbgMarkers / DbgR...
LLVM_ABI void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the basic block to an output stream with an optional AssemblyAnnotationWriter.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
InstListType::iterator getFirstNonPHIOrPseudoProbe()
Definition BasicBlock.h:303
BasicBlock * getUniqueSuccessor()
Definition BasicBlock.h:426
Module * getModule()
Definition BasicBlock.h:221
Instruction & front()
Definition BasicBlock.h:464
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
BasicBlock * getSingleSuccessor()
Definition BasicBlock.h:416
friend BasicBlock::iterator Instruction::eraseFromParent()
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI ValueSymbolTable * getValueSymbolTable()
Returns a pointer to the symbol table if one exists.
BasicBlock * getUniquePredecessor()
Definition BasicBlock.h:400
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 bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
BasicBlock * getSinglePredecessor()
Definition BasicBlock.h:388
LLVM_ABI bool convertFromNewDbgValues()
Convert variable location debugging information stored in DbgMarkers and DbgRecords into the dbg....
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrLifetime() const
Returns an iterator to the first instruction in this block that is not a PHINode, a lifetime intrinsi...
LLVM_ABI std::optional< uint64_t > getIrrLoopHeaderWeight() const
const Instruction & front() const
Definition BasicBlock.h:463
LLVM_ABI void dumpDbgValues() const
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
iterator getFirstNonPHIOrAlloca()
Definition BasicBlock.h:342
Instruction & back()
Definition BasicBlock.h:466
InstListType::reverse_iterator reverse_iterator
Definition BasicBlock.h:172
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
const Instruction * getTerminatorOrNull() 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:248
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
SymbolTableList< Instruction, ilist_iterator_bits< true >, ilist_parent< BasicBlock > > InstListType
Definition BasicBlock.h:64
LLVM_ABI void flushTerminatorDbgRecords()
Eject any debug-info trailing at the end of a block.
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB, BasicBlock::iterator FromIt)
Transfer one instruction from FromBB at FromIt to this basic block at ToIt.
Definition BasicBlock.h:644
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
Function * getParent()
Definition BasicBlock.h:214
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
const_reverse_iterator rend() const
Definition BasicBlock.h:459
reverse_iterator rend()
Definition BasicBlock.h:458
LLVM_ABI void insertDbgRecordAfter(DbgRecord *DR, Instruction *I)
Insert a DbgRecord into a block at the position given by I.
LLVM_ABI void validateInstrOrdering() const
Asserts that instruction order numbers are marked invalid, or that they are in ascending order.
LLVM_ABI DbgMarker * getMarker(InstListType::iterator It)
Return the DbgMarker for the position given by It, so that DbgRecords can be inserted there.
LLVM_ABI ~BasicBlock()
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
CallInst * getPostdominatingDeoptimizeCall()
Definition BasicBlock.h:269
LLVM_ABI const_iterator getFirstNonPHIOrAlloca() const
Returns an iterator to the first instruction in this block that is not a PHINode, a static alloca,...
const_iterator begin() const
Definition BasicBlock.h:448
friend class BlockAddress
Definition BasicBlock.h:73
Instruction * getTerminator()
Definition BasicBlock.h:241
BasicBlock & operator=(const BasicBlock &)=delete
CallInst * getTerminatingDeoptimizeCall()
Definition BasicBlock.h:259
friend class Function
Definition BasicBlock.h:69
LLVM_ABI void dropAllReferences()
Cause all subinstructions to "let go" of all the references that said subinstructions are maintaining...
size_t size() const
Definition BasicBlock.h:461
LLVM_ABI void reinsertInstInDbgRecords(Instruction *I, std::optional< DbgRecord::self_iterator > Pos)
In rare circumstances instructions can be speculatively removed from blocks, and then be re-inserted ...
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition BasicBlock.h:367
LLVM_ABI bool isLandingPad() const
Return true if this basic block is a landing pad.
BasicBlock * splitBasicBlock(Instruction *I, const Twine &BBName="")
Definition BasicBlock.h:610
InstListType::const_reverse_iterator const_reverse_iterator
Definition BasicBlock.h:173
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:683
LLVM_ABI DbgMarker * getTrailingDbgRecords()
Fetch the collection of DbgRecords that "trail" after the last instruction of this block,...
CallInst * getTerminatingMustTailCall()
Definition BasicBlock.h:278
phi_iterator_impl< const PHINode, BasicBlock::const_iterator > const_phi_iterator
Definition BasicBlock.h:503
LLVM_ABI bool canSplitPredecessors() const
const_iterator end() const
Definition BasicBlock.h:454
LLVM_ABI const CallInst * getTerminatingMustTailCall() const
Returns the call instruction marked 'musttail' prior to the terminating return instruction of this ba...
friend BasicBlock::iterator Instruction::insertInto(BasicBlock *BB, BasicBlock::iterator It)
LLVM_ABI bool isLegalToHoistInto() const
Return true if it is legal to hoist instructions into this block.
LLVM_ABI bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
bool isInstrOrderValid() const
Returns true if the Order field of child Instructions is valid.
Definition BasicBlock.h:708
LLVM_ABI const CallInst * getPostdominatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize that is present either in current ...
Instruction * getTerminatorOrNull()
Definition BasicBlock.h:251
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI DbgMarker * getNextMarker(Instruction *I)
Return the DbgMarker for the position that comes after I.
LLVM_ABI const Instruction * getFirstMayFaultInst() const
Returns the first potential AsynchEH faulty instruction currently it checks for loads/stores (which m...
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:638
const_reverse_iterator rbegin() const
Definition BasicBlock.h:457
LandingPadInst * getLandingPadInst()
Definition BasicBlock.h:693
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
iterator getFirstInsertionPt()
Definition BasicBlock.h:323
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
This class represents a function call, abstracting a target machine's calling convention.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Per-instruction record of debug-info.
Base class for non-instruction debug metadata records that have positions within IR.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:71
The landingpad instruction holds all of the information necessary to generate correct exception handl...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
List that automatically updates parent links and symbol tables.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
This class provides a symbol table of name/value pairs.
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:54
unsigned char SubclassOptionalData
Hold arbitary subclass data.
Definition Value.h:85
void setValueSubclassData(unsigned short D)
Definition Value.h:861
self_iterator getIterator()
Definition ilist_node.h:123
An ilist node that can access its parent list.
Definition ilist_node.h:316
typename base_list_type::const_reverse_iterator const_reverse_iterator
Definition ilist.h:124
typename base_list_type::reverse_iterator reverse_iterator
Definition ilist.h:123
typename base_list_type::iterator iterator
Definition ilist.h:121
typename base_list_type::const_iterator const_iterator
Definition ilist.h:122
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 class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
struct LLVMOpaqueBasicBlock * LLVMBasicBlockRef
Represents a basic block of instructions in LLVM IR.
Definition Types.h:82
This file defines classes to implement an intrusive doubly linked list class (i.e.
This file defines the ilist_node class template, which is a convenient base class for creating classe...
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
#define N
static unsigned getHashValue(const BasicBlock::iterator &It)
Definition BasicBlock.h:745
static bool isEqual(const BasicBlock::iterator &LHS, const BasicBlock::iterator &RHS)
Definition BasicBlock.h:751
An information struct used to provide DenseMap with the various necessary components for a given valu...
Option to add extra bits to the ilist_iterator.
Option to add a pointer to this list's owner in every node.