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