1 //===- llvm/CodeGen/MachineBasicBlock.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 //
9 // Collect the sequence of machine instructions for a basic block.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CODEGEN_MACHINEBASICBLOCK_H
14 #define LLVM_CODEGEN_MACHINEBASICBLOCK_H
15 
16 #include "llvm/ADT/GraphTraits.h"
17 #include "llvm/ADT/SparseBitVector.h"
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
22 #include "llvm/IR/DebugLoc.h"
23 #include "llvm/MC/LaneBitmask.h"
24 #include "llvm/Support/BranchProbability.h"
25 #include <cassert>
26 #include <cstdint>
27 #include <iterator>
28 #include <string>
29 #include <vector>
30 
31 namespace llvm {
32 
33 class BasicBlock;
34 class MachineFunction;
35 class MCSymbol;
36 class ModuleSlotTracker;
37 class Pass;
38 class Printable;
39 class SlotIndexes;
40 class StringRef;
41 class raw_ostream;
42 class LiveIntervals;
43 class TargetRegisterClass;
44 class TargetRegisterInfo;
45 
46 // This structure uniquely identifies a basic block section.
47 // Possible values are
48 //  {Type: Default, Number: (unsigned)} (These are regular section IDs)
49 //  {Type: Exception, Number: 0}  (ExceptionSectionID)
50 //  {Type: Cold, Number: 0}  (ColdSectionID)
51 struct MBBSectionID {
52   enum SectionType {
53     Default = 0, // Regular section (these sections are distinguished by the
54                  // Number field).
55     Exception,   // Special section type for exception handling blocks
56     Cold,        // Special section type for cold blocks
57   } Type;
58   unsigned Number;
59 
MBBSectionIDMBBSectionID60   MBBSectionID(unsigned N) : Type(Default), Number(N) {}
61 
62   // Special unique sections for cold and exception blocks.
63   const static MBBSectionID ColdSectionID;
64   const static MBBSectionID ExceptionSectionID;
65 
66   bool operator==(const MBBSectionID &Other) const {
67     return Type == Other.Type && Number == Other.Number;
68   }
69 
70   bool operator!=(const MBBSectionID &Other) const { return !(*this == Other); }
71 
72 private:
73   // This is only used to construct the special cold and exception sections.
MBBSectionIDMBBSectionID74   MBBSectionID(SectionType T) : Type(T), Number(0) {}
75 };
76 
77 // This structure represents the information for a basic block.
78 struct UniqueBBID {
79   unsigned BaseID;
80   // sections profile).
81   unsigned CloneID;
82 };
83 
84 template <> struct ilist_traits<MachineInstr> {
85 private:
86   friend class MachineBasicBlock; // Set by the owning MachineBasicBlock.
87 
88   MachineBasicBlock *Parent;
89 
90   using instr_iterator =
91       simple_ilist<MachineInstr, ilist_sentinel_tracking<true>>::iterator;
92 
93 public:
94   void addNodeToList(MachineInstr *N);
95   void removeNodeFromList(MachineInstr *N);
96   void transferNodesFromList(ilist_traits &FromList, instr_iterator First,
97                              instr_iterator Last);
98   void deleteNode(MachineInstr *MI);
99 };
100 
101 class MachineBasicBlock
102     : public ilist_node_with_parent<MachineBasicBlock, MachineFunction> {
103 public:
104   /// Pair of physical register and lane mask.
105   /// This is not simply a std::pair typedef because the members should be named
106   /// clearly as they both have an integer type.
107   struct RegisterMaskPair {
108   public:
109     MCPhysReg PhysReg;
110     LaneBitmask LaneMask;
111 
112     RegisterMaskPair(MCPhysReg PhysReg, LaneBitmask LaneMask)
113         : PhysReg(PhysReg), LaneMask(LaneMask) {}
114   };
115 
116 private:
117   using Instructions = ilist<MachineInstr, ilist_sentinel_tracking<true>>;
118 
119   const BasicBlock *BB;
120   int Number;
121 
122   /// The call frame size on entry to this basic block due to call frame setup
123   /// instructions in a predecessor. This is usually zero, unless basic blocks
124   /// are split in the middle of a call sequence.
125   ///
126   /// This information is only maintained until PrologEpilogInserter eliminates
127   /// call frame pseudos.
128   unsigned CallFrameSize = 0;
129 
130   MachineFunction *xParent;
131   Instructions Insts;
132 
133   /// Keep track of the predecessor / successor basic blocks.
134   std::vector<MachineBasicBlock *> Predecessors;
135   std::vector<MachineBasicBlock *> Successors;
136 
137   /// Keep track of the probabilities to the successors. This vector has the
138   /// same order as Successors, or it is empty if we don't use it (disable
139   /// optimization).
140   std::vector<BranchProbability> Probs;
141   using probability_iterator = std::vector<BranchProbability>::iterator;
142   using const_probability_iterator =
143       std::vector<BranchProbability>::const_iterator;
144 
145   std::optional<uint64_t> IrrLoopHeaderWeight;
146 
147   /// Keep track of the physical registers that are livein of the basicblock.
148   using LiveInVector = std::vector<RegisterMaskPair>;
149   LiveInVector LiveIns;
150 
151   /// Alignment of the basic block. One if the basic block does not need to be
152   /// aligned.
153   Align Alignment;
154   /// Maximum amount of bytes that can be added to align the basic block. If the
155   /// alignment cannot be reached in this many bytes, no bytes are emitted.
156   /// Zero to represent no maximum.
157   unsigned MaxBytesForAlignment = 0;
158 
159   /// Indicate that this basic block is entered via an exception handler.
160   bool IsEHPad = false;
161 
162   /// Indicate that this MachineBasicBlock is referenced somewhere other than
163   /// as predecessor/successor, a terminator MachineInstr, or a jump table.
164   bool MachineBlockAddressTaken = false;
165 
166   /// If this MachineBasicBlock corresponds to an IR-level "blockaddress"
167   /// constant, this contains a pointer to that block.
168   BasicBlock *AddressTakenIRBlock = nullptr;
169 
170   /// Indicate that this basic block needs its symbol be emitted regardless of
171   /// whether the flow just falls-through to it.
172   bool LabelMustBeEmitted = false;
173 
174   /// Indicate that this basic block is the entry block of an EH scope, i.e.,
175   /// the block that used to have a catchpad or cleanuppad instruction in the
176   /// LLVM IR.
177   bool IsEHScopeEntry = false;
178 
179   /// Indicates if this is a target block of a catchret.
180   bool IsEHCatchretTarget = false;
181 
182   /// Indicate that this basic block is the entry block of an EH funclet.
183   bool IsEHFuncletEntry = false;
184 
185   /// Indicate that this basic block is the entry block of a cleanup funclet.
186   bool IsCleanupFuncletEntry = false;
187 
188   /// Fixed unique ID assigned to this basic block upon creation. Used with
189   /// basic block sections and basic block labels.
190   std::optional<UniqueBBID> BBID;
191 
192   /// With basic block sections, this stores the Section ID of the basic block.
193   MBBSectionID SectionID{0};
194 
195   // Indicate that this basic block begins a section.
196   bool IsBeginSection = false;
197 
198   // Indicate that this basic block ends a section.
199   bool IsEndSection = false;
200 
201   /// Indicate that this basic block is the indirect dest of an INLINEASM_BR.
202   bool IsInlineAsmBrIndirectTarget = false;
203 
204   /// since getSymbol is a relatively heavy-weight operation, the symbol
205   /// is only computed once and is cached.
206   mutable MCSymbol *CachedMCSymbol = nullptr;
207 
208   /// Cached MCSymbol for this block (used if IsEHCatchRetTarget).
209   mutable MCSymbol *CachedEHCatchretMCSymbol = nullptr;
210 
211   /// Marks the end of the basic block. Used during basic block sections to
212   /// calculate the size of the basic block, or the BB section ending with it.
213   mutable MCSymbol *CachedEndMCSymbol = nullptr;
214 
215   // Intrusive list support
216   MachineBasicBlock() = default;
217 
218   explicit MachineBasicBlock(MachineFunction &MF, const BasicBlock *BB);
219 
220   ~MachineBasicBlock();
221 
222   // MachineBasicBlocks are allocated and owned by MachineFunction.
223   friend class MachineFunction;
224 
225 public:
226   /// Return the LLVM basic block that this instance corresponded to originally.
227   /// Note that this may be NULL if this instance does not correspond directly
228   /// to an LLVM basic block.
229   const BasicBlock *getBasicBlock() const { return BB; }
230 
231   /// Remove the reference to the underlying IR BasicBlock. This is for
232   /// reduction tools and should generally not be used.
233   void clearBasicBlock() {
234     BB = nullptr;
235   }
236 
237   /// Return the name of the corresponding LLVM basic block, or an empty string.
238   StringRef getName() const;
239 
240   /// Return a formatted string to identify this block and its parent function.
241   std::string getFullName() const;
242 
243   /// Test whether this block is used as something other than the target
244   /// of a terminator, exception-handling target, or jump table. This is
245   /// either the result of an IR-level "blockaddress", or some form
246   /// of target-specific branch lowering.
247   bool hasAddressTaken() const {
248     return MachineBlockAddressTaken || AddressTakenIRBlock;
249   }
250 
251   /// Test whether this block is used as something other than the target of a
252   /// terminator, exception-handling target, jump table, or IR blockaddress.
253   /// For example, its address might be loaded into a register, or
254   /// stored in some branch table that isn't part of MachineJumpTableInfo.
255   bool isMachineBlockAddressTaken() const { return MachineBlockAddressTaken; }
256 
257   /// Test whether this block is the target of an IR BlockAddress.  (There can
258   /// more than one MBB associated with an IR BB where the address is taken.)
259   bool isIRBlockAddressTaken() const { return AddressTakenIRBlock; }
260 
261   /// Retrieves the BasicBlock which corresponds to this MachineBasicBlock.
262   BasicBlock *getAddressTakenIRBlock() const { return AddressTakenIRBlock; }
263 
264   /// Set this block to indicate that its address is used as something other
265   /// than the target of a terminator, exception-handling target, jump table,
266   /// or IR-level "blockaddress".
267   void setMachineBlockAddressTaken() { MachineBlockAddressTaken = true; }
268 
269   /// Set this block to reflect that it corresponds to an IR-level basic block
270   /// with a BlockAddress.
271   void setAddressTakenIRBlock(BasicBlock *BB) { AddressTakenIRBlock = BB; }
272 
273   /// Test whether this block must have its label emitted.
274   bool hasLabelMustBeEmitted() const { return LabelMustBeEmitted; }
275 
276   /// Set this block to reflect that, regardless how we flow to it, we need
277   /// its label be emitted.
278   void setLabelMustBeEmitted() { LabelMustBeEmitted = true; }
279 
280   /// Return the MachineFunction containing this basic block.
281   const MachineFunction *getParent() const { return xParent; }
282   MachineFunction *getParent() { return xParent; }
283 
284   using instr_iterator = Instructions::iterator;
285   using const_instr_iterator = Instructions::const_iterator;
286   using reverse_instr_iterator = Instructions::reverse_iterator;
287   using const_reverse_instr_iterator = Instructions::const_reverse_iterator;
288 
289   using iterator = MachineInstrBundleIterator<MachineInstr>;
290   using const_iterator = MachineInstrBundleIterator<const MachineInstr>;
291   using reverse_iterator = MachineInstrBundleIterator<MachineInstr, true>;
292   using const_reverse_iterator =
293       MachineInstrBundleIterator<const MachineInstr, true>;
294 
295   unsigned size() const { return (unsigned)Insts.size(); }
296   bool sizeWithoutDebugLargerThan(unsigned Limit) const;
297   bool empty() const { return Insts.empty(); }
298 
299   MachineInstr       &instr_front()       { return Insts.front(); }
300   MachineInstr       &instr_back()        { return Insts.back();  }
301   const MachineInstr &instr_front() const { return Insts.front(); }
302   const MachineInstr &instr_back()  const { return Insts.back();  }
303 
304   MachineInstr       &front()             { return Insts.front(); }
305   MachineInstr       &back()              { return *--end();      }
306   const MachineInstr &front()       const { return Insts.front(); }
307   const MachineInstr &back()        const { return *--end();      }
308 
309   instr_iterator                instr_begin()       { return Insts.begin();  }
310   const_instr_iterator          instr_begin() const { return Insts.begin();  }
311   instr_iterator                  instr_end()       { return Insts.end();    }
312   const_instr_iterator            instr_end() const { return Insts.end();    }
313   reverse_instr_iterator       instr_rbegin()       { return Insts.rbegin(); }
314   const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(); }
315   reverse_instr_iterator       instr_rend  ()       { return Insts.rend();   }
316   const_reverse_instr_iterator instr_rend  () const { return Insts.rend();   }
317 
318   using instr_range = iterator_range<instr_iterator>;
319   using const_instr_range = iterator_range<const_instr_iterator>;
320   instr_range instrs() { return instr_range(instr_begin(), instr_end()); }
321   const_instr_range instrs() const {
322     return const_instr_range(instr_begin(), instr_end());
323   }
324 
325   iterator                begin()       { return instr_begin();  }
326   const_iterator          begin() const { return instr_begin();  }
327   iterator                end  ()       { return instr_end();    }
328   const_iterator          end  () const { return instr_end();    }
329   reverse_iterator rbegin() {
330     return reverse_iterator::getAtBundleBegin(instr_rbegin());
331   }
332   const_reverse_iterator rbegin() const {
333     return const_reverse_iterator::getAtBundleBegin(instr_rbegin());
334   }
335   reverse_iterator rend() { return reverse_iterator(instr_rend()); }
336   const_reverse_iterator rend() const {
337     return const_reverse_iterator(instr_rend());
338   }
339 
340   /// Support for MachineInstr::getNextNode().
341   static Instructions MachineBasicBlock::*getSublistAccess(MachineInstr *) {
342     return &MachineBasicBlock::Insts;
343   }
344 
345   inline iterator_range<iterator> terminators() {
346     return make_range(getFirstTerminator(), end());
347   }
348   inline iterator_range<const_iterator> terminators() const {
349     return make_range(getFirstTerminator(), end());
350   }
351 
352   /// Returns a range that iterates over the phis in the basic block.
353   inline iterator_range<iterator> phis() {
354     return make_range(begin(), getFirstNonPHI());
355   }
356   inline iterator_range<const_iterator> phis() const {
357     return const_cast<MachineBasicBlock *>(this)->phis();
358   }
359 
360   // Machine-CFG iterators
361   using pred_iterator = std::vector<MachineBasicBlock *>::iterator;
362   using const_pred_iterator = std::vector<MachineBasicBlock *>::const_iterator;
363   using succ_iterator = std::vector<MachineBasicBlock *>::iterator;
364   using const_succ_iterator = std::vector<MachineBasicBlock *>::const_iterator;
365   using pred_reverse_iterator =
366       std::vector<MachineBasicBlock *>::reverse_iterator;
367   using const_pred_reverse_iterator =
368       std::vector<MachineBasicBlock *>::const_reverse_iterator;
369   using succ_reverse_iterator =
370       std::vector<MachineBasicBlock *>::reverse_iterator;
371   using const_succ_reverse_iterator =
372       std::vector<MachineBasicBlock *>::const_reverse_iterator;
373   pred_iterator        pred_begin()       { return Predecessors.begin(); }
374   const_pred_iterator  pred_begin() const { return Predecessors.begin(); }
375   pred_iterator        pred_end()         { return Predecessors.end();   }
376   const_pred_iterator  pred_end()   const { return Predecessors.end();   }
377   pred_reverse_iterator        pred_rbegin()
378                                           { return Predecessors.rbegin();}
379   const_pred_reverse_iterator  pred_rbegin() const
380                                           { return Predecessors.rbegin();}
381   pred_reverse_iterator        pred_rend()
382                                           { return Predecessors.rend();  }
383   const_pred_reverse_iterator  pred_rend()   const
384                                           { return Predecessors.rend();  }
385   unsigned             pred_size()  const {
386     return (unsigned)Predecessors.size();
387   }
388   bool                 pred_empty() const { return Predecessors.empty(); }
389   succ_iterator        succ_begin()       { return Successors.begin();   }
390   const_succ_iterator  succ_begin() const { return Successors.begin();   }
391   succ_iterator        succ_end()         { return Successors.end();     }
392   const_succ_iterator  succ_end()   const { return Successors.end();     }
393   succ_reverse_iterator        succ_rbegin()
394                                           { return Successors.rbegin();  }
395   const_succ_reverse_iterator  succ_rbegin() const
396                                           { return Successors.rbegin();  }
397   succ_reverse_iterator        succ_rend()
398                                           { return Successors.rend();    }
399   const_succ_reverse_iterator  succ_rend()   const
400                                           { return Successors.rend();    }
401   unsigned             succ_size()  const {
402     return (unsigned)Successors.size();
403   }
404   bool                 succ_empty() const { return Successors.empty();   }
405 
406   inline iterator_range<pred_iterator> predecessors() {
407     return make_range(pred_begin(), pred_end());
408   }
409   inline iterator_range<const_pred_iterator> predecessors() const {
410     return make_range(pred_begin(), pred_end());
411   }
412   inline iterator_range<succ_iterator> successors() {
413     return make_range(succ_begin(), succ_end());
414   }
415   inline iterator_range<const_succ_iterator> successors() const {
416     return make_range(succ_begin(), succ_end());
417   }
418 
419   // LiveIn management methods.
420 
421   /// Adds the specified register as a live in. Note that it is an error to add
422   /// the same register to the same set more than once unless the intention is
423   /// to call sortUniqueLiveIns after all registers are added.
424   void addLiveIn(MCRegister PhysReg,
425                  LaneBitmask LaneMask = LaneBitmask::getAll()) {
426     LiveIns.push_back(RegisterMaskPair(PhysReg, LaneMask));
427   }
428   void addLiveIn(const RegisterMaskPair &RegMaskPair) {
429     LiveIns.push_back(RegMaskPair);
430   }
431 
432   /// Sorts and uniques the LiveIns vector. It can be significantly faster to do
433   /// this than repeatedly calling isLiveIn before calling addLiveIn for every
434   /// LiveIn insertion.
435   void sortUniqueLiveIns();
436 
437   /// Clear live in list.
438   void clearLiveIns();
439 
440   /// Add PhysReg as live in to this block, and ensure that there is a copy of
441   /// PhysReg to a virtual register of class RC. Return the virtual register
442   /// that is a copy of the live in PhysReg.
443   Register addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC);
444 
445   /// Remove the specified register from the live in set.
446   void removeLiveIn(MCPhysReg Reg,
447                     LaneBitmask LaneMask = LaneBitmask::getAll());
448 
449   /// Return true if the specified register is in the live in set.
450   bool isLiveIn(MCPhysReg Reg,
451                 LaneBitmask LaneMask = LaneBitmask::getAll()) const;
452 
453   // Iteration support for live in sets.  These sets are kept in sorted
454   // order by their register number.
455   using livein_iterator = LiveInVector::const_iterator;
456 
457   /// Unlike livein_begin, this method does not check that the liveness
458   /// information is accurate. Still for debug purposes it may be useful
459   /// to have iterators that won't assert if the liveness information
460   /// is not current.
461   livein_iterator livein_begin_dbg() const { return LiveIns.begin(); }
462   iterator_range<livein_iterator> liveins_dbg() const {
463     return make_range(livein_begin_dbg(), livein_end());
464   }
465 
466   livein_iterator livein_begin() const;
467   livein_iterator livein_end()   const { return LiveIns.end(); }
468   bool            livein_empty() const { return LiveIns.empty(); }
469   iterator_range<livein_iterator> liveins() const {
470     return make_range(livein_begin(), livein_end());
471   }
472 
473   /// Remove entry from the livein set and return iterator to the next.
474   livein_iterator removeLiveIn(livein_iterator I);
475 
476   class liveout_iterator {
477   public:
478     using iterator_category = std::input_iterator_tag;
479     using difference_type = std::ptrdiff_t;
480     using value_type = RegisterMaskPair;
481     using pointer = const RegisterMaskPair *;
482     using reference = const RegisterMaskPair &;
483 
484     liveout_iterator(const MachineBasicBlock &MBB, MCPhysReg ExceptionPointer,
485                      MCPhysReg ExceptionSelector, bool End)
486         : ExceptionPointer(ExceptionPointer),
487           ExceptionSelector(ExceptionSelector), BlockI(MBB.succ_begin()),
488           BlockEnd(MBB.succ_end()) {
489       if (End)
490         BlockI = BlockEnd;
491       else if (BlockI != BlockEnd) {
492         LiveRegI = (*BlockI)->livein_begin();
493         if (!advanceToValidPosition())
494           return;
495         if (LiveRegI->PhysReg == ExceptionPointer ||
496             LiveRegI->PhysReg == ExceptionSelector)
497           ++(*this);
498       }
499     }
500 
501     liveout_iterator &operator++() {
502       do {
503         ++LiveRegI;
504         if (!advanceToValidPosition())
505           return *this;
506       } while ((*BlockI)->isEHPad() &&
507                (LiveRegI->PhysReg == ExceptionPointer ||
508                 LiveRegI->PhysReg == ExceptionSelector));
509       return *this;
510     }
511 
512     liveout_iterator operator++(int) {
513       liveout_iterator Tmp = *this;
514       ++(*this);
515       return Tmp;
516     }
517 
518     reference operator*() const {
519       return *LiveRegI;
520     }
521 
522     pointer operator->() const {
523       return &*LiveRegI;
524     }
525 
526     bool operator==(const liveout_iterator &RHS) const {
527       if (BlockI != BlockEnd)
528         return BlockI == RHS.BlockI && LiveRegI == RHS.LiveRegI;
529       return RHS.BlockI == BlockEnd;
530     }
531 
532     bool operator!=(const liveout_iterator &RHS) const {
533       return !(*this == RHS);
534     }
535   private:
536     bool advanceToValidPosition() {
537       if (LiveRegI != (*BlockI)->livein_end())
538         return true;
539 
540       do {
541         ++BlockI;
542       } while (BlockI != BlockEnd && (*BlockI)->livein_empty());
543       if (BlockI == BlockEnd)
544         return false;
545 
546       LiveRegI = (*BlockI)->livein_begin();
547       return true;
548     }
549 
550     MCPhysReg ExceptionPointer, ExceptionSelector;
551     const_succ_iterator BlockI;
552     const_succ_iterator BlockEnd;
553     livein_iterator LiveRegI;
554   };
555 
556   /// Iterator scanning successor basic blocks' liveins to determine the
557   /// registers potentially live at the end of this block. There may be
558   /// duplicates or overlapping registers in the list returned.
559   liveout_iterator liveout_begin() const;
560   liveout_iterator liveout_end() const {
561     return liveout_iterator(*this, 0, 0, true);
562   }
563   iterator_range<liveout_iterator> liveouts() const {
564     return make_range(liveout_begin(), liveout_end());
565   }
566 
567   /// Get the clobber mask for the start of this basic block. Funclets use this
568   /// to prevent register allocation across funclet transitions.
569   const uint32_t *getBeginClobberMask(const TargetRegisterInfo *TRI) const;
570 
571   /// Get the clobber mask for the end of the basic block.
572   /// \see getBeginClobberMask()
573   const uint32_t *getEndClobberMask(const TargetRegisterInfo *TRI) const;
574 
575   /// Return alignment of the basic block.
576   Align getAlignment() const { return Alignment; }
577 
578   /// Set alignment of the basic block.
579   void setAlignment(Align A) { Alignment = A; }
580 
581   void setAlignment(Align A, unsigned MaxBytes) {
582     setAlignment(A);
583     setMaxBytesForAlignment(MaxBytes);
584   }
585 
586   /// Return the maximum amount of padding allowed for aligning the basic block.
587   unsigned getMaxBytesForAlignment() const { return MaxBytesForAlignment; }
588 
589   /// Set the maximum amount of padding allowed for aligning the basic block
590   void setMaxBytesForAlignment(unsigned MaxBytes) {
591     MaxBytesForAlignment = MaxBytes;
592   }
593 
594   /// Returns true if the block is a landing pad. That is this basic block is
595   /// entered via an exception handler.
596   bool isEHPad() const { return IsEHPad; }
597 
598   /// Indicates the block is a landing pad.  That is this basic block is entered
599   /// via an exception handler.
600   void setIsEHPad(bool V = true) { IsEHPad = V; }
601 
602   bool hasEHPadSuccessor() const;
603 
604   /// Returns true if this is the entry block of the function.
605   bool isEntryBlock() const;
606 
607   /// Returns true if this is the entry block of an EH scope, i.e., the block
608   /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
609   bool isEHScopeEntry() const { return IsEHScopeEntry; }
610 
611   /// Indicates if this is the entry block of an EH scope, i.e., the block that
612   /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
613   void setIsEHScopeEntry(bool V = true) { IsEHScopeEntry = V; }
614 
615   /// Returns true if this is a target block of a catchret.
616   bool isEHCatchretTarget() const { return IsEHCatchretTarget; }
617 
618   /// Indicates if this is a target block of a catchret.
619   void setIsEHCatchretTarget(bool V = true) { IsEHCatchretTarget = V; }
620 
621   /// Returns true if this is the entry block of an EH funclet.
622   bool isEHFuncletEntry() const { return IsEHFuncletEntry; }
623 
624   /// Indicates if this is the entry block of an EH funclet.
625   void setIsEHFuncletEntry(bool V = true) { IsEHFuncletEntry = V; }
626 
627   /// Returns true if this is the entry block of a cleanup funclet.
628   bool isCleanupFuncletEntry() const { return IsCleanupFuncletEntry; }
629 
630   /// Indicates if this is the entry block of a cleanup funclet.
631   void setIsCleanupFuncletEntry(bool V = true) { IsCleanupFuncletEntry = V; }
632 
633   /// Returns true if this block begins any section.
634   bool isBeginSection() const { return IsBeginSection; }
635 
636   /// Returns true if this block ends any section.
637   bool isEndSection() const { return IsEndSection; }
638 
639   void setIsBeginSection(bool V = true) { IsBeginSection = V; }
640 
641   void setIsEndSection(bool V = true) { IsEndSection = V; }
642 
643   std::optional<UniqueBBID> getBBID() const { return BBID; }
644 
645   /// Returns the section ID of this basic block.
646   MBBSectionID getSectionID() const { return SectionID; }
647 
648   /// Returns the unique section ID number of this basic block.
649   unsigned getSectionIDNum() const {
650     return ((unsigned)MBBSectionID::SectionType::Cold) -
651            ((unsigned)SectionID.Type) + SectionID.Number;
652   }
653 
654   /// Sets the fixed BBID of this basic block.
655   void setBBID(const UniqueBBID &V) {
656     assert(!BBID.has_value() && "Cannot change BBID.");
657     BBID = V;
658   }
659 
660   /// Sets the section ID for this basic block.
661   void setSectionID(MBBSectionID V) { SectionID = V; }
662 
663   /// Returns the MCSymbol marking the end of this basic block.
664   MCSymbol *getEndSymbol() const;
665 
666   /// Returns true if this block may have an INLINEASM_BR (overestimate, by
667   /// checking if any of the successors are indirect targets of any inlineasm_br
668   /// in the function).
669   bool mayHaveInlineAsmBr() const;
670 
671   /// Returns true if this is the indirect dest of an INLINEASM_BR.
672   bool isInlineAsmBrIndirectTarget() const {
673     return IsInlineAsmBrIndirectTarget;
674   }
675 
676   /// Indicates if this is the indirect dest of an INLINEASM_BR.
677   void setIsInlineAsmBrIndirectTarget(bool V = true) {
678     IsInlineAsmBrIndirectTarget = V;
679   }
680 
681   /// Returns true if it is legal to hoist instructions into this block.
682   bool isLegalToHoistInto() const;
683 
684   // Code Layout methods.
685 
686   /// Move 'this' block before or after the specified block.  This only moves
687   /// the block, it does not modify the CFG or adjust potential fall-throughs at
688   /// the end of the block.
689   void moveBefore(MachineBasicBlock *NewAfter);
690   void moveAfter(MachineBasicBlock *NewBefore);
691 
692   /// Returns true if this and MBB belong to the same section.
693   bool sameSection(const MachineBasicBlock *MBB) const {
694     return getSectionID() == MBB->getSectionID();
695   }
696 
697   /// Update the terminator instructions in block to account for changes to
698   /// block layout which may have been made. PreviousLayoutSuccessor should be
699   /// set to the block which may have been used as fallthrough before the block
700   /// layout was modified.  If the block previously fell through to that block,
701   /// it may now need a branch. If it previously branched to another block, it
702   /// may now be able to fallthrough to the current layout successor.
703   void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor);
704 
705   // Machine-CFG mutators
706 
707   /// Add Succ as a successor of this MachineBasicBlock.  The Predecessors list
708   /// of Succ is automatically updated. PROB parameter is stored in
709   /// Probabilities list. The default probability is set as unknown. Mixing
710   /// known and unknown probabilities in successor list is not allowed. When all
711   /// successors have unknown probabilities, 1 / N is returned as the
712   /// probability for each successor, where N is the number of successors.
713   ///
714   /// Note that duplicate Machine CFG edges are not allowed.
715   void addSuccessor(MachineBasicBlock *Succ,
716                     BranchProbability Prob = BranchProbability::getUnknown());
717 
718   /// Add Succ as a successor of this MachineBasicBlock.  The Predecessors list
719   /// of Succ is automatically updated. The probability is not provided because
720   /// BPI is not available (e.g. -O0 is used), in which case edge probabilities
721   /// won't be used. Using this interface can save some space.
722   void addSuccessorWithoutProb(MachineBasicBlock *Succ);
723 
724   /// Set successor probability of a given iterator.
725   void setSuccProbability(succ_iterator I, BranchProbability Prob);
726 
727   /// Normalize probabilities of all successors so that the sum of them becomes
728   /// one. This is usually done when the current update on this MBB is done, and
729   /// the sum of its successors' probabilities is not guaranteed to be one. The
730   /// user is responsible for the correct use of this function.
731   /// MBB::removeSuccessor() has an option to do this automatically.
732   void normalizeSuccProbs() {
733     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
734   }
735 
736   /// Validate successors' probabilities and check if the sum of them is
737   /// approximate one. This only works in DEBUG mode.
738   void validateSuccProbs() const;
739 
740   /// Remove successor from the successors list of this MachineBasicBlock. The
741   /// Predecessors list of Succ is automatically updated.
742   /// If NormalizeSuccProbs is true, then normalize successors' probabilities
743   /// after the successor is removed.
744   void removeSuccessor(MachineBasicBlock *Succ,
745                        bool NormalizeSuccProbs = false);
746 
747   /// Remove specified successor from the successors list of this
748   /// MachineBasicBlock. The Predecessors list of Succ is automatically updated.
749   /// If NormalizeSuccProbs is true, then normalize successors' probabilities
750   /// after the successor is removed.
751   /// Return the iterator to the element after the one removed.
752   succ_iterator removeSuccessor(succ_iterator I,
753                                 bool NormalizeSuccProbs = false);
754 
755   /// Replace successor OLD with NEW and update probability info.
756   void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
757 
758   /// Copy a successor (and any probability info) from original block to this
759   /// block's. Uses an iterator into the original blocks successors.
760   ///
761   /// This is useful when doing a partial clone of successors. Afterward, the
762   /// probabilities may need to be normalized.
763   void copySuccessor(const MachineBasicBlock *Orig, succ_iterator I);
764 
765   /// Split the old successor into old plus new and updates the probability
766   /// info.
767   void splitSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New,
768                       bool NormalizeSuccProbs = false);
769 
770   /// Transfers all the successors from MBB to this machine basic block (i.e.,
771   /// copies all the successors FromMBB and remove all the successors from
772   /// FromMBB).
773   void transferSuccessors(MachineBasicBlock *FromMBB);
774 
775   /// Transfers all the successors, as in transferSuccessors, and update PHI
776   /// operands in the successor blocks which refer to FromMBB to refer to this.
777   void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB);
778 
779   /// Return true if any of the successors have probabilities attached to them.
780   bool hasSuccessorProbabilities() const { return !Probs.empty(); }
781 
782   /// Return true if the specified MBB is a predecessor of this block.
783   bool isPredecessor(const MachineBasicBlock *MBB) const;
784 
785   /// Return true if the specified MBB is a successor of this block.
786   bool isSuccessor(const MachineBasicBlock *MBB) const;
787 
788   /// Return true if the specified MBB will be emitted immediately after this
789   /// block, such that if this block exits by falling through, control will
790   /// transfer to the specified MBB. Note that MBB need not be a successor at
791   /// all, for example if this block ends with an unconditional branch to some
792   /// other block.
793   bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
794 
795   /// Return the successor of this block if it has a single successor.
796   /// Otherwise return a null pointer.
797   ///
798   const MachineBasicBlock *getSingleSuccessor() const;
799   MachineBasicBlock *getSingleSuccessor() {
800     return const_cast<MachineBasicBlock *>(
801         static_cast<const MachineBasicBlock *>(this)->getSingleSuccessor());
802   }
803 
804   /// Return the predecessor of this block if it has a single predecessor.
805   /// Otherwise return a null pointer.
806   ///
807   const MachineBasicBlock *getSinglePredecessor() const;
808   MachineBasicBlock *getSinglePredecessor() {
809     return const_cast<MachineBasicBlock *>(
810         static_cast<const MachineBasicBlock *>(this)->getSinglePredecessor());
811   }
812 
813   /// Return the fallthrough block if the block can implicitly
814   /// transfer control to the block after it by falling off the end of
815   /// it. If an explicit branch to the fallthrough block is not allowed,
816   /// set JumpToFallThrough to be false. Non-null return is a conservative
817   /// answer.
818   MachineBasicBlock *getFallThrough(bool JumpToFallThrough = true);
819 
820   /// Return the fallthrough block if the block can implicitly
821   /// transfer control to it's successor, whether by a branch or
822   /// a fallthrough. Non-null return is a conservative answer.
823   MachineBasicBlock *getLogicalFallThrough() { return getFallThrough(false); }
824 
825   /// Return true if the block can implicitly transfer control to the
826   /// block after it by falling off the end of it.  This should return
827   /// false if it can reach the block after it, but it uses an
828   /// explicit branch to do so (e.g., a table jump).  True is a
829   /// conservative answer.
830   bool canFallThrough();
831 
832   /// Returns a pointer to the first instruction in this block that is not a
833   /// PHINode instruction. When adding instructions to the beginning of the
834   /// basic block, they should be added before the returned value, not before
835   /// the first instruction, which might be PHI.
836   /// Returns end() is there's no non-PHI instruction.
837   iterator getFirstNonPHI();
838   const_iterator getFirstNonPHI() const {
839     return const_cast<MachineBasicBlock *>(this)->getFirstNonPHI();
840   }
841 
842   /// Return the first instruction in MBB after I that is not a PHI or a label.
843   /// This is the correct point to insert lowered copies at the beginning of a
844   /// basic block that must be before any debugging information.
845   iterator SkipPHIsAndLabels(iterator I);
846 
847   /// Return the first instruction in MBB after I that is not a PHI, label or
848   /// debug.  This is the correct point to insert copies at the beginning of a
849   /// basic block. \p Reg is the register being used by a spill or defined for a
850   /// restore/split during register allocation.
851   iterator SkipPHIsLabelsAndDebug(iterator I, Register Reg = Register(),
852                                   bool SkipPseudoOp = true);
853 
854   /// Returns an iterator to the first terminator instruction of this basic
855   /// block. If a terminator does not exist, it returns end().
856   iterator getFirstTerminator();
857   const_iterator getFirstTerminator() const {
858     return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
859   }
860 
861   /// Same getFirstTerminator but it ignores bundles and return an
862   /// instr_iterator instead.
863   instr_iterator getFirstInstrTerminator();
864 
865   /// Finds the first terminator in a block by scanning forward. This can handle
866   /// cases in GlobalISel where there may be non-terminator instructions between
867   /// terminators, for which getFirstTerminator() will not work correctly.
868   iterator getFirstTerminatorForward();
869 
870   /// Returns an iterator to the first non-debug instruction in the basic block,
871   /// or end(). Skip any pseudo probe operation if \c SkipPseudoOp is true.
872   /// Pseudo probes are like debug instructions which do not turn into real
873   /// machine code. We try to use the function to skip both debug instructions
874   /// and pseudo probe operations to avoid API proliferation. This should work
875   /// most of the time when considering optimizing the rest of code in the
876   /// block, except for certain cases where pseudo probes are designed to block
877   /// the optimizations. For example, code merge like optimizations are supposed
878   /// to be blocked by pseudo probes for better AutoFDO profile quality.
879   /// Therefore, they should be considered as a valid instruction when this
880   /// function is called in a context of such optimizations. On the other hand,
881   /// \c SkipPseudoOp should be true when it's used in optimizations that
882   /// unlikely hurt profile quality, e.g., without block merging. The default
883   /// value of \c SkipPseudoOp is set to true to maximize code quality in
884   /// general, with an explict false value passed in in a few places like branch
885   /// folding and if-conversion to favor profile quality.
886   iterator getFirstNonDebugInstr(bool SkipPseudoOp = true);
887   const_iterator getFirstNonDebugInstr(bool SkipPseudoOp = true) const {
888     return const_cast<MachineBasicBlock *>(this)->getFirstNonDebugInstr(
889         SkipPseudoOp);
890   }
891 
892   /// Returns an iterator to the last non-debug instruction in the basic block,
893   /// or end(). Skip any pseudo operation if \c SkipPseudoOp is true.
894   /// Pseudo probes are like debug instructions which do not turn into real
895   /// machine code. We try to use the function to skip both debug instructions
896   /// and pseudo probe operations to avoid API proliferation. This should work
897   /// most of the time when considering optimizing the rest of code in the
898   /// block, except for certain cases where pseudo probes are designed to block
899   /// the optimizations. For example, code merge like optimizations are supposed
900   /// to be blocked by pseudo probes for better AutoFDO profile quality.
901   /// Therefore, they should be considered as a valid instruction when this
902   /// function is called in a context of such optimizations. On the other hand,
903   /// \c SkipPseudoOp should be true when it's used in optimizations that
904   /// unlikely hurt profile quality, e.g., without block merging. The default
905   /// value of \c SkipPseudoOp is set to true to maximize code quality in
906   /// general, with an explict false value passed in in a few places like branch
907   /// folding and if-conversion to favor profile quality.
908   iterator getLastNonDebugInstr(bool SkipPseudoOp = true);
909   const_iterator getLastNonDebugInstr(bool SkipPseudoOp = true) const {
910     return const_cast<MachineBasicBlock *>(this)->getLastNonDebugInstr(
911         SkipPseudoOp);
912   }
913 
914   /// Convenience function that returns true if the block ends in a return
915   /// instruction.
916   bool isReturnBlock() const {
917     return !empty() && back().isReturn();
918   }
919 
920   /// Convenience function that returns true if the bock ends in a EH scope
921   /// return instruction.
922   bool isEHScopeReturnBlock() const {
923     return !empty() && back().isEHScopeReturn();
924   }
925 
926   /// Split a basic block into 2 pieces at \p SplitPoint. A new block will be
927   /// inserted after this block, and all instructions after \p SplitInst moved
928   /// to it (\p SplitInst will be in the original block). If \p LIS is provided,
929   /// LiveIntervals will be appropriately updated. \return the newly inserted
930   /// block.
931   ///
932   /// If \p UpdateLiveIns is true, this will ensure the live ins list is
933   /// accurate, including for physreg uses/defs in the original block.
934   MachineBasicBlock *splitAt(MachineInstr &SplitInst, bool UpdateLiveIns = true,
935                              LiveIntervals *LIS = nullptr);
936 
937   /// Split the critical edge from this block to the given successor block, and
938   /// return the newly created block, or null if splitting is not possible.
939   ///
940   /// This function updates LiveVariables, MachineDominatorTree, and
941   /// MachineLoopInfo, as applicable.
942   MachineBasicBlock *
943   SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P,
944                     std::vector<SparseBitVector<>> *LiveInSets = nullptr);
945 
946   /// Check if the edge between this block and the given successor \p
947   /// Succ, can be split. If this returns true a subsequent call to
948   /// SplitCriticalEdge is guaranteed to return a valid basic block if
949   /// no changes occurred in the meantime.
950   bool canSplitCriticalEdge(const MachineBasicBlock *Succ) const;
951 
952   void pop_front() { Insts.pop_front(); }
953   void pop_back() { Insts.pop_back(); }
954   void push_back(MachineInstr *MI) { Insts.push_back(MI); }
955 
956   /// Insert MI into the instruction list before I, possibly inside a bundle.
957   ///
958   /// If the insertion point is inside a bundle, MI will be added to the bundle,
959   /// otherwise MI will not be added to any bundle. That means this function
960   /// alone can't be used to prepend or append instructions to bundles. See
961   /// MIBundleBuilder::insert() for a more reliable way of doing that.
962   instr_iterator insert(instr_iterator I, MachineInstr *M);
963 
964   /// Insert a range of instructions into the instruction list before I.
965   template<typename IT>
966   void insert(iterator I, IT S, IT E) {
967     assert((I == end() || I->getParent() == this) &&
968            "iterator points outside of basic block");
969     Insts.insert(I.getInstrIterator(), S, E);
970   }
971 
972   /// Insert MI into the instruction list before I.
973   iterator insert(iterator I, MachineInstr *MI) {
974     assert((I == end() || I->getParent() == this) &&
975            "iterator points outside of basic block");
976     assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
977            "Cannot insert instruction with bundle flags");
978     return Insts.insert(I.getInstrIterator(), MI);
979   }
980 
981   /// Insert MI into the instruction list after I.
982   iterator insertAfter(iterator I, MachineInstr *MI) {
983     assert((I == end() || I->getParent() == this) &&
984            "iterator points outside of basic block");
985     assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
986            "Cannot insert instruction with bundle flags");
987     return Insts.insertAfter(I.getInstrIterator(), MI);
988   }
989 
990   /// If I is bundled then insert MI into the instruction list after the end of
991   /// the bundle, otherwise insert MI immediately after I.
992   instr_iterator insertAfterBundle(instr_iterator I, MachineInstr *MI) {
993     assert((I == instr_end() || I->getParent() == this) &&
994            "iterator points outside of basic block");
995     assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
996            "Cannot insert instruction with bundle flags");
997     while (I->isBundledWithSucc())
998       ++I;
999     return Insts.insertAfter(I, MI);
1000   }
1001 
1002   /// Remove an instruction from the instruction list and delete it.
1003   ///
1004   /// If the instruction is part of a bundle, the other instructions in the
1005   /// bundle will still be bundled after removing the single instruction.
1006   instr_iterator erase(instr_iterator I);
1007 
1008   /// Remove an instruction from the instruction list and delete it.
1009   ///
1010   /// If the instruction is part of a bundle, the other instructions in the
1011   /// bundle will still be bundled after removing the single instruction.
1012   instr_iterator erase_instr(MachineInstr *I) {
1013     return erase(instr_iterator(I));
1014   }
1015 
1016   /// Remove a range of instructions from the instruction list and delete them.
1017   iterator erase(iterator I, iterator E) {
1018     return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
1019   }
1020 
1021   /// Remove an instruction or bundle from the instruction list and delete it.
1022   ///
1023   /// If I points to a bundle of instructions, they are all erased.
1024   iterator erase(iterator I) {
1025     return erase(I, std::next(I));
1026   }
1027 
1028   /// Remove an instruction from the instruction list and delete it.
1029   ///
1030   /// If I is the head of a bundle of instructions, the whole bundle will be
1031   /// erased.
1032   iterator erase(MachineInstr *I) {
1033     return erase(iterator(I));
1034   }
1035 
1036   /// Remove the unbundled instruction from the instruction list without
1037   /// deleting it.
1038   ///
1039   /// This function can not be used to remove bundled instructions, use
1040   /// remove_instr to remove individual instructions from a bundle.
1041   MachineInstr *remove(MachineInstr *I) {
1042     assert(!I->isBundled() && "Cannot remove bundled instructions");
1043     return Insts.remove(instr_iterator(I));
1044   }
1045 
1046   /// Remove the possibly bundled instruction from the instruction list
1047   /// without deleting it.
1048   ///
1049   /// If the instruction is part of a bundle, the other instructions in the
1050   /// bundle will still be bundled after removing the single instruction.
1051   MachineInstr *remove_instr(MachineInstr *I);
1052 
1053   void clear() {
1054     Insts.clear();
1055   }
1056 
1057   /// Take an instruction from MBB 'Other' at the position From, and insert it
1058   /// into this MBB right before 'Where'.
1059   ///
1060   /// If From points to a bundle of instructions, the whole bundle is moved.
1061   void splice(iterator Where, MachineBasicBlock *Other, iterator From) {
1062     // The range splice() doesn't allow noop moves, but this one does.
1063     if (Where != From)
1064       splice(Where, Other, From, std::next(From));
1065   }
1066 
1067   /// Take a block of instructions from MBB 'Other' in the range [From, To),
1068   /// and insert them into this MBB right before 'Where'.
1069   ///
1070   /// The instruction at 'Where' must not be included in the range of
1071   /// instructions to move.
1072   void splice(iterator Where, MachineBasicBlock *Other,
1073               iterator From, iterator To) {
1074     Insts.splice(Where.getInstrIterator(), Other->Insts,
1075                  From.getInstrIterator(), To.getInstrIterator());
1076   }
1077 
1078   /// This method unlinks 'this' from the containing function, and returns it,
1079   /// but does not delete it.
1080   MachineBasicBlock *removeFromParent();
1081 
1082   /// This method unlinks 'this' from the containing function and deletes it.
1083   void eraseFromParent();
1084 
1085   /// Given a machine basic block that branched to 'Old', change the code and
1086   /// CFG so that it branches to 'New' instead.
1087   void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
1088 
1089   /// Update all phi nodes in this basic block to refer to basic block \p New
1090   /// instead of basic block \p Old.
1091   void replacePhiUsesWith(MachineBasicBlock *Old, MachineBasicBlock *New);
1092 
1093   /// Find the next valid DebugLoc starting at MBBI, skipping any debug
1094   /// instructions.  Return UnknownLoc if there is none.
1095   DebugLoc findDebugLoc(instr_iterator MBBI);
1096   DebugLoc findDebugLoc(iterator MBBI) {
1097     return findDebugLoc(MBBI.getInstrIterator());
1098   }
1099 
1100   /// Has exact same behavior as @ref findDebugLoc (it also searches towards the
1101   /// end of this MBB) except that this function takes a reverse iterator to
1102   /// identify the starting MI.
1103   DebugLoc rfindDebugLoc(reverse_instr_iterator MBBI);
1104   DebugLoc rfindDebugLoc(reverse_iterator MBBI) {
1105     return rfindDebugLoc(MBBI.getInstrIterator());
1106   }
1107 
1108   /// Find the previous valid DebugLoc preceding MBBI, skipping any debug
1109   /// instructions. It is possible to find the last DebugLoc in the MBB using
1110   /// findPrevDebugLoc(instr_end()).  Return UnknownLoc if there is none.
1111   DebugLoc findPrevDebugLoc(instr_iterator MBBI);
1112   DebugLoc findPrevDebugLoc(iterator MBBI) {
1113     return findPrevDebugLoc(MBBI.getInstrIterator());
1114   }
1115 
1116   /// Has exact same behavior as @ref findPrevDebugLoc (it also searches towards
1117   /// the beginning of this MBB) except that this function takes reverse
1118   /// iterator to identify the starting MI. A minor difference compared to
1119   /// findPrevDebugLoc is that we can't start scanning at "instr_end".
1120   DebugLoc rfindPrevDebugLoc(reverse_instr_iterator MBBI);
1121   DebugLoc rfindPrevDebugLoc(reverse_iterator MBBI) {
1122     return rfindPrevDebugLoc(MBBI.getInstrIterator());
1123   }
1124 
1125   /// Find and return the merged DebugLoc of the branch instructions of the
1126   /// block. Return UnknownLoc if there is none.
1127   DebugLoc findBranchDebugLoc();
1128 
1129   /// Possible outcome of a register liveness query to computeRegisterLiveness()
1130   enum LivenessQueryResult {
1131     LQR_Live,   ///< Register is known to be (at least partially) live.
1132     LQR_Dead,   ///< Register is known to be fully dead.
1133     LQR_Unknown ///< Register liveness not decidable from local neighborhood.
1134   };
1135 
1136   /// Return whether (physical) register \p Reg has been defined and not
1137   /// killed as of just before \p Before.
1138   ///
1139   /// Search is localised to a neighborhood of \p Neighborhood instructions
1140   /// before (searching for defs or kills) and \p Neighborhood instructions
1141   /// after (searching just for defs) \p Before.
1142   ///
1143   /// \p Reg must be a physical register.
1144   LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
1145                                               MCRegister Reg,
1146                                               const_iterator Before,
1147                                               unsigned Neighborhood = 10) const;
1148 
1149   // Debugging methods.
1150   void dump() const;
1151   void print(raw_ostream &OS, const SlotIndexes * = nullptr,
1152              bool IsStandalone = true) const;
1153   void print(raw_ostream &OS, ModuleSlotTracker &MST,
1154              const SlotIndexes * = nullptr, bool IsStandalone = true) const;
1155 
1156   enum PrintNameFlag {
1157     PrintNameIr = (1 << 0), ///< Add IR name where available
1158     PrintNameAttributes = (1 << 1), ///< Print attributes
1159   };
1160 
1161   void printName(raw_ostream &os, unsigned printNameFlags = PrintNameIr,
1162                  ModuleSlotTracker *moduleSlotTracker = nullptr) const;
1163 
1164   // Printing method used by LoopInfo.
1165   void printAsOperand(raw_ostream &OS, bool PrintType = true) const;
1166 
1167   /// MachineBasicBlocks are uniquely numbered at the function level, unless
1168   /// they're not in a MachineFunction yet, in which case this will return -1.
1169   int getNumber() const { return Number; }
1170   void setNumber(int N) { Number = N; }
1171 
1172   /// Return the call frame size on entry to this basic block.
1173   unsigned getCallFrameSize() const { return CallFrameSize; }
1174   /// Set the call frame size on entry to this basic block.
1175   void setCallFrameSize(unsigned N) { CallFrameSize = N; }
1176 
1177   /// Return the MCSymbol for this basic block.
1178   MCSymbol *getSymbol() const;
1179 
1180   /// Return the EHCatchret Symbol for this basic block.
1181   MCSymbol *getEHCatchretSymbol() const;
1182 
1183   std::optional<uint64_t> getIrrLoopHeaderWeight() const {
1184     return IrrLoopHeaderWeight;
1185   }
1186 
1187   void setIrrLoopHeaderWeight(uint64_t Weight) {
1188     IrrLoopHeaderWeight = Weight;
1189   }
1190 
1191   /// Return probability of the edge from this block to MBB. This method should
1192   /// NOT be called directly, but by using getEdgeProbability method from
1193   /// MachineBranchProbabilityInfo class.
1194   BranchProbability getSuccProbability(const_succ_iterator Succ) const;
1195 
1196 private:
1197   /// Return probability iterator corresponding to the I successor iterator.
1198   probability_iterator getProbabilityIterator(succ_iterator I);
1199   const_probability_iterator
1200   getProbabilityIterator(const_succ_iterator I) const;
1201 
1202   friend class MachineBranchProbabilityInfo;
1203   friend class MIPrinter;
1204 
1205   // Methods used to maintain doubly linked list of blocks...
1206   friend struct ilist_callback_traits<MachineBasicBlock>;
1207 
1208   // Machine-CFG mutators
1209 
1210   /// Add Pred as a predecessor of this MachineBasicBlock. Don't do this
1211   /// unless you know what you're doing, because it doesn't update Pred's
1212   /// successors list. Use Pred->addSuccessor instead.
1213   void addPredecessor(MachineBasicBlock *Pred);
1214 
1215   /// Remove Pred as a predecessor of this MachineBasicBlock. Don't do this
1216   /// unless you know what you're doing, because it doesn't update Pred's
1217   /// successors list. Use Pred->removeSuccessor instead.
1218   void removePredecessor(MachineBasicBlock *Pred);
1219 };
1220 
1221 raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
1222 
1223 /// Prints a machine basic block reference.
1224 ///
1225 /// The format is:
1226 ///   %bb.5           - a machine basic block with MBB.getNumber() == 5.
1227 ///
1228 /// Usage: OS << printMBBReference(MBB) << '\n';
1229 Printable printMBBReference(const MachineBasicBlock &MBB);
1230 
1231 // This is useful when building IndexedMaps keyed on basic block pointers.
1232 struct MBB2NumberFunctor {
1233   using argument_type = const MachineBasicBlock *;
1234   unsigned operator()(const MachineBasicBlock *MBB) const {
1235     return MBB->getNumber();
1236   }
1237 };
1238 
1239 //===--------------------------------------------------------------------===//
1240 // GraphTraits specializations for machine basic block graphs (machine-CFGs)
1241 //===--------------------------------------------------------------------===//
1242 
1243 // Provide specializations of GraphTraits to be able to treat a
1244 // MachineFunction as a graph of MachineBasicBlocks.
1245 //
1246 
1247 template <> struct GraphTraits<MachineBasicBlock *> {
1248   using NodeRef = MachineBasicBlock *;
1249   using ChildIteratorType = MachineBasicBlock::succ_iterator;
1250 
1251   static NodeRef getEntryNode(MachineBasicBlock *BB) { return BB; }
1252   static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
1253   static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
1254 };
1255 
1256 template <> struct GraphTraits<const MachineBasicBlock *> {
1257   using NodeRef = const MachineBasicBlock *;
1258   using ChildIteratorType = MachineBasicBlock::const_succ_iterator;
1259 
1260   static NodeRef getEntryNode(const MachineBasicBlock *BB) { return BB; }
1261   static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
1262   static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
1263 };
1264 
1265 // Provide specializations of GraphTraits to be able to treat a
1266 // MachineFunction as a graph of MachineBasicBlocks and to walk it
1267 // in inverse order.  Inverse order for a function is considered
1268 // to be when traversing the predecessor edges of a MBB
1269 // instead of the successor edges.
1270 //
1271 template <> struct GraphTraits<Inverse<MachineBasicBlock*>> {
1272   using NodeRef = MachineBasicBlock *;
1273   using ChildIteratorType = MachineBasicBlock::pred_iterator;
1274 
1275   static NodeRef getEntryNode(Inverse<MachineBasicBlock *> G) {
1276     return G.Graph;
1277   }
1278 
1279   static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
1280   static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
1281 };
1282 
1283 template <> struct GraphTraits<Inverse<const MachineBasicBlock*>> {
1284   using NodeRef = const MachineBasicBlock *;
1285   using ChildIteratorType = MachineBasicBlock::const_pred_iterator;
1286 
1287   static NodeRef getEntryNode(Inverse<const MachineBasicBlock *> G) {
1288     return G.Graph;
1289   }
1290 
1291   static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
1292   static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
1293 };
1294 
1295 // These accessors are handy for sharing templated code between IR and MIR.
1296 inline auto successors(const MachineBasicBlock *BB) { return BB->successors(); }
1297 inline auto predecessors(const MachineBasicBlock *BB) {
1298   return BB->predecessors();
1299 }
1300 
1301 /// MachineInstrSpan provides an interface to get an iteration range
1302 /// containing the instruction it was initialized with, along with all
1303 /// those instructions inserted prior to or following that instruction
1304 /// at some point after the MachineInstrSpan is constructed.
1305 class MachineInstrSpan {
1306   MachineBasicBlock &MBB;
1307   MachineBasicBlock::iterator I, B, E;
1308 
1309 public:
1310   MachineInstrSpan(MachineBasicBlock::iterator I, MachineBasicBlock *BB)
1311       : MBB(*BB), I(I), B(I == MBB.begin() ? MBB.end() : std::prev(I)),
1312         E(std::next(I)) {
1313     assert(I == BB->end() || I->getParent() == BB);
1314   }
1315 
1316   MachineBasicBlock::iterator begin() {
1317     return B == MBB.end() ? MBB.begin() : std::next(B);
1318   }
1319   MachineBasicBlock::iterator end() { return E; }
1320   bool empty() { return begin() == end(); }
1321 
1322   MachineBasicBlock::iterator getInitial() { return I; }
1323 };
1324 
1325 /// Increment \p It until it points to a non-debug instruction or to \p End
1326 /// and return the resulting iterator. This function should only be used
1327 /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
1328 /// const_instr_iterator} and the respective reverse iterators.
1329 template <typename IterT>
1330 inline IterT skipDebugInstructionsForward(IterT It, IterT End,
1331                                           bool SkipPseudoOp = true) {
1332   while (It != End &&
1333          (It->isDebugInstr() || (SkipPseudoOp && It->isPseudoProbe())))
1334     ++It;
1335   return It;
1336 }
1337 
1338 /// Decrement \p It until it points to a non-debug instruction or to \p Begin
1339 /// and return the resulting iterator. This function should only be used
1340 /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
1341 /// const_instr_iterator} and the respective reverse iterators.
1342 template <class IterT>
1343 inline IterT skipDebugInstructionsBackward(IterT It, IterT Begin,
1344                                            bool SkipPseudoOp = true) {
1345   while (It != Begin &&
1346          (It->isDebugInstr() || (SkipPseudoOp && It->isPseudoProbe())))
1347     --It;
1348   return It;
1349 }
1350 
1351 /// Increment \p It, then continue incrementing it while it points to a debug
1352 /// instruction. A replacement for std::next.
1353 template <typename IterT>
1354 inline IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp = true) {
1355   return skipDebugInstructionsForward(std::next(It), End, SkipPseudoOp);
1356 }
1357 
1358 /// Decrement \p It, then continue decrementing it while it points to a debug
1359 /// instruction. A replacement for std::prev.
1360 template <typename IterT>
1361 inline IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp = true) {
1362   return skipDebugInstructionsBackward(std::prev(It), Begin, SkipPseudoOp);
1363 }
1364 
1365 /// Construct a range iterator which begins at \p It and moves forwards until
1366 /// \p End is reached, skipping any debug instructions.
1367 template <typename IterT>
1368 inline auto instructionsWithoutDebug(IterT It, IterT End,
1369                                      bool SkipPseudoOp = true) {
1370   return make_filter_range(make_range(It, End), [=](const MachineInstr &MI) {
1371     return !MI.isDebugInstr() && !(SkipPseudoOp && MI.isPseudoProbe());
1372   });
1373 }
1374 
1375 } // end namespace llvm
1376 
1377 #endif // LLVM_CODEGEN_MACHINEBASICBLOCK_H
1378