1 //===- llvm/CodeGen/MachineBasicBlock.h -------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Collect the sequence of machine instructions for a basic block.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CODEGEN_MACHINEBASICBLOCK_H
15 #define LLVM_CODEGEN_MACHINEBASICBLOCK_H
17 #include "llvm/ADT/GraphTraits.h"
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/ADT/simple_ilist.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/MC/MCRegisterInfo.h"
27 #include "llvm/Support/BranchProbability.h"
28 #include "llvm/Support/Printable.h"
39 class MachineFunction;
41 class ModuleSlotTracker;
46 class TargetRegisterClass;
47 class TargetRegisterInfo;
49 template <> struct ilist_traits<MachineInstr> {
51 friend class MachineBasicBlock; // Set by the owning MachineBasicBlock.
53 MachineBasicBlock *Parent;
55 using instr_iterator =
56 simple_ilist<MachineInstr, ilist_sentinel_tracking<true>>::iterator;
59 void addNodeToList(MachineInstr *N);
60 void removeNodeFromList(MachineInstr *N);
61 void transferNodesFromList(ilist_traits &OldList, instr_iterator First,
63 void deleteNode(MachineInstr *MI);
66 class MachineBasicBlock
67 : public ilist_node_with_parent<MachineBasicBlock, MachineFunction> {
69 /// Pair of physical register and lane mask.
70 /// This is not simply a std::pair typedef because the members should be named
71 /// clearly as they both have an integer type.
72 struct RegisterMaskPair {
77 RegisterMaskPair(MCPhysReg PhysReg, LaneBitmask LaneMask)
78 : PhysReg(PhysReg), LaneMask(LaneMask) {}
82 using Instructions = ilist<MachineInstr, ilist_sentinel_tracking<true>>;
87 MachineFunction *xParent;
89 /// Keep track of the predecessor / successor basic blocks.
90 std::vector<MachineBasicBlock *> Predecessors;
91 std::vector<MachineBasicBlock *> Successors;
93 /// Keep track of the probabilities to the successors. This vector has the
94 /// same order as Successors, or it is empty if we don't use it (disable
96 std::vector<BranchProbability> Probs;
97 using probability_iterator = std::vector<BranchProbability>::iterator;
98 using const_probability_iterator =
99 std::vector<BranchProbability>::const_iterator;
101 Optional<uint64_t> IrrLoopHeaderWeight;
103 /// Keep track of the physical registers that are livein of the basicblock.
104 using LiveInVector = std::vector<RegisterMaskPair>;
105 LiveInVector LiveIns;
107 /// Alignment of the basic block. Zero if the basic block does not need to be
108 /// aligned. The alignment is specified as log2(bytes).
109 unsigned Alignment = 0;
111 /// Indicate that this basic block is entered via an exception handler.
112 bool IsEHPad = false;
114 /// Indicate that this basic block is potentially the target of an indirect
116 bool AddressTaken = false;
118 /// Indicate that this basic block is the entry block of an EH funclet.
119 bool IsEHFuncletEntry = false;
121 /// Indicate that this basic block is the entry block of a cleanup funclet.
122 bool IsCleanupFuncletEntry = false;
124 /// \brief since getSymbol is a relatively heavy-weight operation, the symbol
125 /// is only computed once and is cached.
126 mutable MCSymbol *CachedMCSymbol = nullptr;
128 // Intrusive list support
129 MachineBasicBlock() = default;
131 explicit MachineBasicBlock(MachineFunction &MF, const BasicBlock *BB);
133 ~MachineBasicBlock();
135 // MachineBasicBlocks are allocated and owned by MachineFunction.
136 friend class MachineFunction;
139 /// Return the LLVM basic block that this instance corresponded to originally.
140 /// Note that this may be NULL if this instance does not correspond directly
141 /// to an LLVM basic block.
142 const BasicBlock *getBasicBlock() const { return BB; }
144 /// Return the name of the corresponding LLVM basic block, or an empty string.
145 StringRef getName() const;
147 /// Return a formatted string to identify this block and its parent function.
148 std::string getFullName() const;
150 /// Test whether this block is potentially the target of an indirect branch.
151 bool hasAddressTaken() const { return AddressTaken; }
153 /// Set this block to reflect that it potentially is the target of an indirect
155 void setHasAddressTaken() { AddressTaken = true; }
157 /// Return the MachineFunction containing this basic block.
158 const MachineFunction *getParent() const { return xParent; }
159 MachineFunction *getParent() { return xParent; }
161 using instr_iterator = Instructions::iterator;
162 using const_instr_iterator = Instructions::const_iterator;
163 using reverse_instr_iterator = Instructions::reverse_iterator;
164 using const_reverse_instr_iterator = Instructions::const_reverse_iterator;
166 using iterator = MachineInstrBundleIterator<MachineInstr>;
167 using const_iterator = MachineInstrBundleIterator<const MachineInstr>;
168 using reverse_iterator = MachineInstrBundleIterator<MachineInstr, true>;
169 using const_reverse_iterator =
170 MachineInstrBundleIterator<const MachineInstr, true>;
172 unsigned size() const { return (unsigned)Insts.size(); }
173 bool empty() const { return Insts.empty(); }
175 MachineInstr &instr_front() { return Insts.front(); }
176 MachineInstr &instr_back() { return Insts.back(); }
177 const MachineInstr &instr_front() const { return Insts.front(); }
178 const MachineInstr &instr_back() const { return Insts.back(); }
180 MachineInstr &front() { return Insts.front(); }
181 MachineInstr &back() { return *--end(); }
182 const MachineInstr &front() const { return Insts.front(); }
183 const MachineInstr &back() const { return *--end(); }
185 instr_iterator instr_begin() { return Insts.begin(); }
186 const_instr_iterator instr_begin() const { return Insts.begin(); }
187 instr_iterator instr_end() { return Insts.end(); }
188 const_instr_iterator instr_end() const { return Insts.end(); }
189 reverse_instr_iterator instr_rbegin() { return Insts.rbegin(); }
190 const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(); }
191 reverse_instr_iterator instr_rend () { return Insts.rend(); }
192 const_reverse_instr_iterator instr_rend () const { return Insts.rend(); }
194 using instr_range = iterator_range<instr_iterator>;
195 using const_instr_range = iterator_range<const_instr_iterator>;
196 instr_range instrs() { return instr_range(instr_begin(), instr_end()); }
197 const_instr_range instrs() const {
198 return const_instr_range(instr_begin(), instr_end());
201 iterator begin() { return instr_begin(); }
202 const_iterator begin() const { return instr_begin(); }
203 iterator end () { return instr_end(); }
204 const_iterator end () const { return instr_end(); }
205 reverse_iterator rbegin() {
206 return reverse_iterator::getAtBundleBegin(instr_rbegin());
208 const_reverse_iterator rbegin() const {
209 return const_reverse_iterator::getAtBundleBegin(instr_rbegin());
211 reverse_iterator rend() { return reverse_iterator(instr_rend()); }
212 const_reverse_iterator rend() const {
213 return const_reverse_iterator(instr_rend());
216 /// Support for MachineInstr::getNextNode().
217 static Instructions MachineBasicBlock::*getSublistAccess(MachineInstr *) {
218 return &MachineBasicBlock::Insts;
221 inline iterator_range<iterator> terminators() {
222 return make_range(getFirstTerminator(), end());
224 inline iterator_range<const_iterator> terminators() const {
225 return make_range(getFirstTerminator(), end());
228 // Machine-CFG iterators
229 using pred_iterator = std::vector<MachineBasicBlock *>::iterator;
230 using const_pred_iterator = std::vector<MachineBasicBlock *>::const_iterator;
231 using succ_iterator = std::vector<MachineBasicBlock *>::iterator;
232 using const_succ_iterator = std::vector<MachineBasicBlock *>::const_iterator;
233 using pred_reverse_iterator =
234 std::vector<MachineBasicBlock *>::reverse_iterator;
235 using const_pred_reverse_iterator =
236 std::vector<MachineBasicBlock *>::const_reverse_iterator;
237 using succ_reverse_iterator =
238 std::vector<MachineBasicBlock *>::reverse_iterator;
239 using const_succ_reverse_iterator =
240 std::vector<MachineBasicBlock *>::const_reverse_iterator;
241 pred_iterator pred_begin() { return Predecessors.begin(); }
242 const_pred_iterator pred_begin() const { return Predecessors.begin(); }
243 pred_iterator pred_end() { return Predecessors.end(); }
244 const_pred_iterator pred_end() const { return Predecessors.end(); }
245 pred_reverse_iterator pred_rbegin()
246 { return Predecessors.rbegin();}
247 const_pred_reverse_iterator pred_rbegin() const
248 { return Predecessors.rbegin();}
249 pred_reverse_iterator pred_rend()
250 { return Predecessors.rend(); }
251 const_pred_reverse_iterator pred_rend() const
252 { return Predecessors.rend(); }
253 unsigned pred_size() const {
254 return (unsigned)Predecessors.size();
256 bool pred_empty() const { return Predecessors.empty(); }
257 succ_iterator succ_begin() { return Successors.begin(); }
258 const_succ_iterator succ_begin() const { return Successors.begin(); }
259 succ_iterator succ_end() { return Successors.end(); }
260 const_succ_iterator succ_end() const { return Successors.end(); }
261 succ_reverse_iterator succ_rbegin()
262 { return Successors.rbegin(); }
263 const_succ_reverse_iterator succ_rbegin() const
264 { return Successors.rbegin(); }
265 succ_reverse_iterator succ_rend()
266 { return Successors.rend(); }
267 const_succ_reverse_iterator succ_rend() const
268 { return Successors.rend(); }
269 unsigned succ_size() const {
270 return (unsigned)Successors.size();
272 bool succ_empty() const { return Successors.empty(); }
274 inline iterator_range<pred_iterator> predecessors() {
275 return make_range(pred_begin(), pred_end());
277 inline iterator_range<const_pred_iterator> predecessors() const {
278 return make_range(pred_begin(), pred_end());
280 inline iterator_range<succ_iterator> successors() {
281 return make_range(succ_begin(), succ_end());
283 inline iterator_range<const_succ_iterator> successors() const {
284 return make_range(succ_begin(), succ_end());
287 // LiveIn management methods.
289 /// Adds the specified register as a live in. Note that it is an error to add
290 /// the same register to the same set more than once unless the intention is
291 /// to call sortUniqueLiveIns after all registers are added.
292 void addLiveIn(MCPhysReg PhysReg,
293 LaneBitmask LaneMask = LaneBitmask::getAll()) {
294 LiveIns.push_back(RegisterMaskPair(PhysReg, LaneMask));
296 void addLiveIn(const RegisterMaskPair &RegMaskPair) {
297 LiveIns.push_back(RegMaskPair);
300 /// Sorts and uniques the LiveIns vector. It can be significantly faster to do
301 /// this than repeatedly calling isLiveIn before calling addLiveIn for every
302 /// LiveIn insertion.
303 void sortUniqueLiveIns();
305 /// Clear live in list.
308 /// Add PhysReg as live in to this block, and ensure that there is a copy of
309 /// PhysReg to a virtual register of class RC. Return the virtual register
310 /// that is a copy of the live in PhysReg.
311 unsigned addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC);
313 /// Remove the specified register from the live in set.
314 void removeLiveIn(MCPhysReg Reg,
315 LaneBitmask LaneMask = LaneBitmask::getAll());
317 /// Return true if the specified register is in the live in set.
318 bool isLiveIn(MCPhysReg Reg,
319 LaneBitmask LaneMask = LaneBitmask::getAll()) const;
321 // Iteration support for live in sets. These sets are kept in sorted
322 // order by their register number.
323 using livein_iterator = LiveInVector::const_iterator;
325 /// Unlike livein_begin, this method does not check that the liveness
326 /// information is accurate. Still for debug purposes it may be useful
327 /// to have iterators that won't assert if the liveness information
329 livein_iterator livein_begin_dbg() const { return LiveIns.begin(); }
330 iterator_range<livein_iterator> liveins_dbg() const {
331 return make_range(livein_begin_dbg(), livein_end());
334 livein_iterator livein_begin() const;
335 livein_iterator livein_end() const { return LiveIns.end(); }
336 bool livein_empty() const { return LiveIns.empty(); }
337 iterator_range<livein_iterator> liveins() const {
338 return make_range(livein_begin(), livein_end());
341 /// Remove entry from the livein set and return iterator to the next.
342 livein_iterator removeLiveIn(livein_iterator I);
344 /// Get the clobber mask for the start of this basic block. Funclets use this
345 /// to prevent register allocation across funclet transitions.
346 const uint32_t *getBeginClobberMask(const TargetRegisterInfo *TRI) const;
348 /// Get the clobber mask for the end of the basic block.
349 /// \see getBeginClobberMask()
350 const uint32_t *getEndClobberMask(const TargetRegisterInfo *TRI) const;
352 /// Return alignment of the basic block. The alignment is specified as
354 unsigned getAlignment() const { return Alignment; }
356 /// Set alignment of the basic block. The alignment is specified as
358 void setAlignment(unsigned Align) { Alignment = Align; }
360 /// Returns true if the block is a landing pad. That is this basic block is
361 /// entered via an exception handler.
362 bool isEHPad() const { return IsEHPad; }
364 /// Indicates the block is a landing pad. That is this basic block is entered
365 /// via an exception handler.
366 void setIsEHPad(bool V = true) { IsEHPad = V; }
368 bool hasEHPadSuccessor() const;
370 /// Returns true if this is the entry block of an EH funclet.
371 bool isEHFuncletEntry() const { return IsEHFuncletEntry; }
373 /// Indicates if this is the entry block of an EH funclet.
374 void setIsEHFuncletEntry(bool V = true) { IsEHFuncletEntry = V; }
376 /// Returns true if this is the entry block of a cleanup funclet.
377 bool isCleanupFuncletEntry() const { return IsCleanupFuncletEntry; }
379 /// Indicates if this is the entry block of a cleanup funclet.
380 void setIsCleanupFuncletEntry(bool V = true) { IsCleanupFuncletEntry = V; }
382 /// Returns true if it is legal to hoist instructions into this block.
383 bool isLegalToHoistInto() const;
385 // Code Layout methods.
387 /// Move 'this' block before or after the specified block. This only moves
388 /// the block, it does not modify the CFG or adjust potential fall-throughs at
389 /// the end of the block.
390 void moveBefore(MachineBasicBlock *NewAfter);
391 void moveAfter(MachineBasicBlock *NewBefore);
393 /// Update the terminator instructions in block to account for changes to the
394 /// layout. If the block previously used a fallthrough, it may now need a
395 /// branch, and if it previously used branching it may now be able to use a
397 void updateTerminator();
399 // Machine-CFG mutators
401 /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
402 /// of Succ is automatically updated. PROB parameter is stored in
403 /// Probabilities list. The default probability is set as unknown. Mixing
404 /// known and unknown probabilities in successor list is not allowed. When all
405 /// successors have unknown probabilities, 1 / N is returned as the
406 /// probability for each successor, where N is the number of successors.
408 /// Note that duplicate Machine CFG edges are not allowed.
409 void addSuccessor(MachineBasicBlock *Succ,
410 BranchProbability Prob = BranchProbability::getUnknown());
412 /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
413 /// of Succ is automatically updated. The probability is not provided because
414 /// BPI is not available (e.g. -O0 is used), in which case edge probabilities
415 /// won't be used. Using this interface can save some space.
416 void addSuccessorWithoutProb(MachineBasicBlock *Succ);
418 /// Set successor probability of a given iterator.
419 void setSuccProbability(succ_iterator I, BranchProbability Prob);
421 /// Normalize probabilities of all successors so that the sum of them becomes
422 /// one. This is usually done when the current update on this MBB is done, and
423 /// the sum of its successors' probabilities is not guaranteed to be one. The
424 /// user is responsible for the correct use of this function.
425 /// MBB::removeSuccessor() has an option to do this automatically.
426 void normalizeSuccProbs() {
427 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
430 /// Validate successors' probabilities and check if the sum of them is
431 /// approximate one. This only works in DEBUG mode.
432 void validateSuccProbs() const;
434 /// Remove successor from the successors list of this MachineBasicBlock. The
435 /// Predecessors list of Succ is automatically updated.
436 /// If NormalizeSuccProbs is true, then normalize successors' probabilities
437 /// after the successor is removed.
438 void removeSuccessor(MachineBasicBlock *Succ,
439 bool NormalizeSuccProbs = false);
441 /// Remove specified successor from the successors list of this
442 /// MachineBasicBlock. The Predecessors list of Succ is automatically updated.
443 /// If NormalizeSuccProbs is true, then normalize successors' probabilities
444 /// after the successor is removed.
445 /// Return the iterator to the element after the one removed.
446 succ_iterator removeSuccessor(succ_iterator I,
447 bool NormalizeSuccProbs = false);
449 /// Replace successor OLD with NEW and update probability info.
450 void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
452 /// Transfers all the successors from MBB to this machine basic block (i.e.,
453 /// copies all the successors FromMBB and remove all the successors from
455 void transferSuccessors(MachineBasicBlock *FromMBB);
457 /// Transfers all the successors, as in transferSuccessors, and update PHI
458 /// operands in the successor blocks which refer to FromMBB to refer to this.
459 void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB);
461 /// Return true if any of the successors have probabilities attached to them.
462 bool hasSuccessorProbabilities() const { return !Probs.empty(); }
464 /// Return true if the specified MBB is a predecessor of this block.
465 bool isPredecessor(const MachineBasicBlock *MBB) const;
467 /// Return true if the specified MBB is a successor of this block.
468 bool isSuccessor(const MachineBasicBlock *MBB) const;
470 /// Return true if the specified MBB will be emitted immediately after this
471 /// block, such that if this block exits by falling through, control will
472 /// transfer to the specified MBB. Note that MBB need not be a successor at
473 /// all, for example if this block ends with an unconditional branch to some
475 bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
477 /// Return the fallthrough block if the block can implicitly
478 /// transfer control to the block after it by falling off the end of
479 /// it. This should return null if it can reach the block after
480 /// it, but it uses an explicit branch to do so (e.g., a table
481 /// jump). Non-null return is a conservative answer.
482 MachineBasicBlock *getFallThrough();
484 /// Return true if the block can implicitly transfer control to the
485 /// block after it by falling off the end of it. This should return
486 /// false if it can reach the block after it, but it uses an
487 /// explicit branch to do so (e.g., a table jump). True is a
488 /// conservative answer.
489 bool canFallThrough();
491 /// Returns a pointer to the first instruction in this block that is not a
492 /// PHINode instruction. When adding instructions to the beginning of the
493 /// basic block, they should be added before the returned value, not before
494 /// the first instruction, which might be PHI.
495 /// Returns end() is there's no non-PHI instruction.
496 iterator getFirstNonPHI();
498 /// Return the first instruction in MBB after I that is not a PHI or a label.
499 /// This is the correct point to insert lowered copies at the beginning of a
500 /// basic block that must be before any debugging information.
501 iterator SkipPHIsAndLabels(iterator I);
503 /// Return the first instruction in MBB after I that is not a PHI, label or
504 /// debug. This is the correct point to insert copies at the beginning of a
506 iterator SkipPHIsLabelsAndDebug(iterator I);
508 /// Returns an iterator to the first terminator instruction of this basic
509 /// block. If a terminator does not exist, it returns end().
510 iterator getFirstTerminator();
511 const_iterator getFirstTerminator() const {
512 return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
515 /// Same getFirstTerminator but it ignores bundles and return an
516 /// instr_iterator instead.
517 instr_iterator getFirstInstrTerminator();
519 /// Returns an iterator to the first non-debug instruction in the basic block,
521 iterator getFirstNonDebugInstr();
522 const_iterator getFirstNonDebugInstr() const {
523 return const_cast<MachineBasicBlock *>(this)->getFirstNonDebugInstr();
526 /// Returns an iterator to the last non-debug instruction in the basic block,
528 iterator getLastNonDebugInstr();
529 const_iterator getLastNonDebugInstr() const {
530 return const_cast<MachineBasicBlock *>(this)->getLastNonDebugInstr();
533 /// Convenience function that returns true if the block ends in a return
535 bool isReturnBlock() const {
536 return !empty() && back().isReturn();
539 /// Split the critical edge from this block to the given successor block, and
540 /// return the newly created block, or null if splitting is not possible.
542 /// This function updates LiveVariables, MachineDominatorTree, and
543 /// MachineLoopInfo, as applicable.
544 MachineBasicBlock *SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P);
546 /// Check if the edge between this block and the given successor \p
547 /// Succ, can be split. If this returns true a subsequent call to
548 /// SplitCriticalEdge is guaranteed to return a valid basic block if
549 /// no changes occured in the meantime.
550 bool canSplitCriticalEdge(const MachineBasicBlock *Succ) const;
552 void pop_front() { Insts.pop_front(); }
553 void pop_back() { Insts.pop_back(); }
554 void push_back(MachineInstr *MI) { Insts.push_back(MI); }
556 /// Insert MI into the instruction list before I, possibly inside a bundle.
558 /// If the insertion point is inside a bundle, MI will be added to the bundle,
559 /// otherwise MI will not be added to any bundle. That means this function
560 /// alone can't be used to prepend or append instructions to bundles. See
561 /// MIBundleBuilder::insert() for a more reliable way of doing that.
562 instr_iterator insert(instr_iterator I, MachineInstr *M);
564 /// Insert a range of instructions into the instruction list before I.
565 template<typename IT>
566 void insert(iterator I, IT S, IT E) {
567 assert((I == end() || I->getParent() == this) &&
568 "iterator points outside of basic block");
569 Insts.insert(I.getInstrIterator(), S, E);
572 /// Insert MI into the instruction list before I.
573 iterator insert(iterator I, MachineInstr *MI) {
574 assert((I == end() || I->getParent() == this) &&
575 "iterator points outside of basic block");
576 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
577 "Cannot insert instruction with bundle flags");
578 return Insts.insert(I.getInstrIterator(), MI);
581 /// Insert MI into the instruction list after I.
582 iterator insertAfter(iterator I, MachineInstr *MI) {
583 assert((I == end() || I->getParent() == this) &&
584 "iterator points outside of basic block");
585 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
586 "Cannot insert instruction with bundle flags");
587 return Insts.insertAfter(I.getInstrIterator(), MI);
590 /// Remove an instruction from the instruction list and delete it.
592 /// If the instruction is part of a bundle, the other instructions in the
593 /// bundle will still be bundled after removing the single instruction.
594 instr_iterator erase(instr_iterator I);
596 /// Remove an instruction from the instruction list and delete it.
598 /// If the instruction is part of a bundle, the other instructions in the
599 /// bundle will still be bundled after removing the single instruction.
600 instr_iterator erase_instr(MachineInstr *I) {
601 return erase(instr_iterator(I));
604 /// Remove a range of instructions from the instruction list and delete them.
605 iterator erase(iterator I, iterator E) {
606 return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
609 /// Remove an instruction or bundle from the instruction list and delete it.
611 /// If I points to a bundle of instructions, they are all erased.
612 iterator erase(iterator I) {
613 return erase(I, std::next(I));
616 /// Remove an instruction from the instruction list and delete it.
618 /// If I is the head of a bundle of instructions, the whole bundle will be
620 iterator erase(MachineInstr *I) {
621 return erase(iterator(I));
624 /// Remove the unbundled instruction from the instruction list without
627 /// This function can not be used to remove bundled instructions, use
628 /// remove_instr to remove individual instructions from a bundle.
629 MachineInstr *remove(MachineInstr *I) {
630 assert(!I->isBundled() && "Cannot remove bundled instructions");
631 return Insts.remove(instr_iterator(I));
634 /// Remove the possibly bundled instruction from the instruction list
635 /// without deleting it.
637 /// If the instruction is part of a bundle, the other instructions in the
638 /// bundle will still be bundled after removing the single instruction.
639 MachineInstr *remove_instr(MachineInstr *I);
645 /// Take an instruction from MBB 'Other' at the position From, and insert it
646 /// into this MBB right before 'Where'.
648 /// If From points to a bundle of instructions, the whole bundle is moved.
649 void splice(iterator Where, MachineBasicBlock *Other, iterator From) {
650 // The range splice() doesn't allow noop moves, but this one does.
652 splice(Where, Other, From, std::next(From));
655 /// Take a block of instructions from MBB 'Other' in the range [From, To),
656 /// and insert them into this MBB right before 'Where'.
658 /// The instruction at 'Where' must not be included in the range of
659 /// instructions to move.
660 void splice(iterator Where, MachineBasicBlock *Other,
661 iterator From, iterator To) {
662 Insts.splice(Where.getInstrIterator(), Other->Insts,
663 From.getInstrIterator(), To.getInstrIterator());
666 /// This method unlinks 'this' from the containing function, and returns it,
667 /// but does not delete it.
668 MachineBasicBlock *removeFromParent();
670 /// This method unlinks 'this' from the containing function and deletes it.
671 void eraseFromParent();
673 /// Given a machine basic block that branched to 'Old', change the code and
674 /// CFG so that it branches to 'New' instead.
675 void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
677 /// Various pieces of code can cause excess edges in the CFG to be inserted.
678 /// If we have proven that MBB can only branch to DestA and DestB, remove any
679 /// other MBB successors from the CFG. DestA and DestB can be null. Besides
680 /// DestA and DestB, retain other edges leading to LandingPads (currently
681 /// there can be only one; we don't check or require that here). Note it is
682 /// possible that DestA and/or DestB are LandingPads.
683 bool CorrectExtraCFGEdges(MachineBasicBlock *DestA,
684 MachineBasicBlock *DestB,
687 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
688 /// instructions. Return UnknownLoc if there is none.
689 DebugLoc findDebugLoc(instr_iterator MBBI);
690 DebugLoc findDebugLoc(iterator MBBI) {
691 return findDebugLoc(MBBI.getInstrIterator());
694 /// Find and return the merged DebugLoc of the branch instructions of the
695 /// block. Return UnknownLoc if there is none.
696 DebugLoc findBranchDebugLoc();
698 /// Possible outcome of a register liveness query to computeRegisterLiveness()
699 enum LivenessQueryResult {
700 LQR_Live, ///< Register is known to be (at least partially) live.
701 LQR_Dead, ///< Register is known to be fully dead.
702 LQR_Unknown ///< Register liveness not decidable from local neighborhood.
705 /// Return whether (physical) register \p Reg has been defined and not
706 /// killed as of just before \p Before.
708 /// Search is localised to a neighborhood of \p Neighborhood instructions
709 /// before (searching for defs or kills) and \p Neighborhood instructions
710 /// after (searching just for defs) \p Before.
712 /// \p Reg must be a physical register.
713 LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
715 const_iterator Before,
716 unsigned Neighborhood = 10) const;
718 // Debugging methods.
720 void print(raw_ostream &OS, const SlotIndexes* = nullptr) const;
721 void print(raw_ostream &OS, ModuleSlotTracker &MST,
722 const SlotIndexes* = nullptr) const;
724 // Printing method used by LoopInfo.
725 void printAsOperand(raw_ostream &OS, bool PrintType = true) const;
727 /// MachineBasicBlocks are uniquely numbered at the function level, unless
728 /// they're not in a MachineFunction yet, in which case this will return -1.
729 int getNumber() const { return Number; }
730 void setNumber(int N) { Number = N; }
732 /// Return the MCSymbol for this basic block.
733 MCSymbol *getSymbol() const;
735 Optional<uint64_t> getIrrLoopHeaderWeight() const {
736 return IrrLoopHeaderWeight;
739 void setIrrLoopHeaderWeight(uint64_t Weight) {
740 IrrLoopHeaderWeight = Weight;
744 /// Return probability iterator corresponding to the I successor iterator.
745 probability_iterator getProbabilityIterator(succ_iterator I);
746 const_probability_iterator
747 getProbabilityIterator(const_succ_iterator I) const;
749 friend class MachineBranchProbabilityInfo;
750 friend class MIPrinter;
752 /// Return probability of the edge from this block to MBB. This method should
753 /// NOT be called directly, but by using getEdgeProbability method from
754 /// MachineBranchProbabilityInfo class.
755 BranchProbability getSuccProbability(const_succ_iterator Succ) const;
757 // Methods used to maintain doubly linked list of blocks...
758 friend struct ilist_callback_traits<MachineBasicBlock>;
760 // Machine-CFG mutators
762 /// Add Pred as a predecessor of this MachineBasicBlock. Don't do this
763 /// unless you know what you're doing, because it doesn't update Pred's
764 /// successors list. Use Pred->addSuccessor instead.
765 void addPredecessor(MachineBasicBlock *Pred);
767 /// Remove Pred as a predecessor of this MachineBasicBlock. Don't do this
768 /// unless you know what you're doing, because it doesn't update Pred's
769 /// successors list. Use Pred->removeSuccessor instead.
770 void removePredecessor(MachineBasicBlock *Pred);
773 raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
775 /// Prints a machine basic block reference.
778 /// %bb.5 - a machine basic block with MBB.getNumber() == 5.
780 /// Usage: OS << printMBBReference(MBB) << '\n';
781 Printable printMBBReference(const MachineBasicBlock &MBB);
783 // This is useful when building IndexedMaps keyed on basic block pointers.
784 struct MBB2NumberFunctor {
785 using argument_type = const MachineBasicBlock *;
786 unsigned operator()(const MachineBasicBlock *MBB) const {
787 return MBB->getNumber();
791 //===--------------------------------------------------------------------===//
792 // GraphTraits specializations for machine basic block graphs (machine-CFGs)
793 //===--------------------------------------------------------------------===//
795 // Provide specializations of GraphTraits to be able to treat a
796 // MachineFunction as a graph of MachineBasicBlocks.
799 template <> struct GraphTraits<MachineBasicBlock *> {
800 using NodeRef = MachineBasicBlock *;
801 using ChildIteratorType = MachineBasicBlock::succ_iterator;
803 static NodeRef getEntryNode(MachineBasicBlock *BB) { return BB; }
804 static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
805 static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
808 template <> struct GraphTraits<const MachineBasicBlock *> {
809 using NodeRef = const MachineBasicBlock *;
810 using ChildIteratorType = MachineBasicBlock::const_succ_iterator;
812 static NodeRef getEntryNode(const MachineBasicBlock *BB) { return BB; }
813 static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
814 static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
817 // Provide specializations of GraphTraits to be able to treat a
818 // MachineFunction as a graph of MachineBasicBlocks and to walk it
819 // in inverse order. Inverse order for a function is considered
820 // to be when traversing the predecessor edges of a MBB
821 // instead of the successor edges.
823 template <> struct GraphTraits<Inverse<MachineBasicBlock*>> {
824 using NodeRef = MachineBasicBlock *;
825 using ChildIteratorType = MachineBasicBlock::pred_iterator;
827 static NodeRef getEntryNode(Inverse<MachineBasicBlock *> G) {
831 static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
832 static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
835 template <> struct GraphTraits<Inverse<const MachineBasicBlock*>> {
836 using NodeRef = const MachineBasicBlock *;
837 using ChildIteratorType = MachineBasicBlock::const_pred_iterator;
839 static NodeRef getEntryNode(Inverse<const MachineBasicBlock *> G) {
843 static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
844 static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
847 /// MachineInstrSpan provides an interface to get an iteration range
848 /// containing the instruction it was initialized with, along with all
849 /// those instructions inserted prior to or following that instruction
850 /// at some point after the MachineInstrSpan is constructed.
851 class MachineInstrSpan {
852 MachineBasicBlock &MBB;
853 MachineBasicBlock::iterator I, B, E;
856 MachineInstrSpan(MachineBasicBlock::iterator I)
857 : MBB(*I->getParent()),
859 B(I == MBB.begin() ? MBB.end() : std::prev(I)),
862 MachineBasicBlock::iterator begin() {
863 return B == MBB.end() ? MBB.begin() : std::next(B);
865 MachineBasicBlock::iterator end() { return E; }
866 bool empty() { return begin() == end(); }
868 MachineBasicBlock::iterator getInitial() { return I; }
871 /// Increment \p It until it points to a non-debug instruction or to \p End
872 /// and return the resulting iterator. This function should only be used
873 /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
874 /// const_instr_iterator} and the respective reverse iterators.
875 template<typename IterT>
876 inline IterT skipDebugInstructionsForward(IterT It, IterT End) {
877 while (It != End && It->isDebugValue())
882 /// Decrement \p It until it points to a non-debug instruction or to \p Begin
883 /// and return the resulting iterator. This function should only be used
884 /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
885 /// const_instr_iterator} and the respective reverse iterators.
886 template<class IterT>
887 inline IterT skipDebugInstructionsBackward(IterT It, IterT Begin) {
888 while (It != Begin && It->isDebugValue())
893 } // end namespace llvm
895 #endif // LLVM_CODEGEN_MACHINEBASICBLOCK_H