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/CodeGen/MachineInstr.h"
19 #include "llvm/Support/BranchProbability.h"
20 #include "llvm/MC/MCRegisterInfo.h"
21 #include "llvm/Support/DataTypes.h"
28 class MachineFunction;
34 class MachineBranchProbabilityInfo;
36 // Forward declaration to avoid circular include problem with TargetRegisterInfo
37 typedef unsigned LaneBitmask;
40 struct ilist_traits<MachineInstr> : public ilist_default_traits<MachineInstr> {
42 mutable ilist_half_node<MachineInstr> Sentinel;
44 // this is only set by the MachineBasicBlock owning the LiveList
45 friend class MachineBasicBlock;
46 MachineBasicBlock* Parent;
49 MachineInstr *createSentinel() const {
50 return static_cast<MachineInstr*>(&Sentinel);
52 void destroySentinel(MachineInstr *) const {}
54 MachineInstr *provideInitialHead() const { return createSentinel(); }
55 MachineInstr *ensureHead(MachineInstr*) const { return createSentinel(); }
56 static void noteHead(MachineInstr*, MachineInstr*) {}
58 void addNodeToList(MachineInstr* N);
59 void removeNodeFromList(MachineInstr* N);
60 void transferNodesFromList(ilist_traits &SrcTraits,
61 ilist_iterator<MachineInstr> First,
62 ilist_iterator<MachineInstr> Last);
63 void deleteNode(MachineInstr *N);
65 void createNode(const MachineInstr &);
68 class MachineBasicBlock
69 : public ilist_node_with_parent<MachineBasicBlock, MachineFunction> {
71 /// Pair of physical register and lane mask.
72 /// This is not simply a std::pair typedef because the members should be named
73 /// clearly as they both have an integer type.
74 struct RegisterMaskPair {
79 RegisterMaskPair(MCPhysReg PhysReg, LaneBitmask LaneMask)
80 : PhysReg(PhysReg), LaneMask(LaneMask) {}
84 typedef ilist<MachineInstr> Instructions;
88 MachineFunction *xParent;
90 /// Keep track of the predecessor / successor basic blocks.
91 std::vector<MachineBasicBlock *> Predecessors;
92 std::vector<MachineBasicBlock *> Successors;
94 /// Keep track of the probabilities to the successors. This vector has the
95 /// same order as Successors, or it is empty if we don't use it (disable
97 std::vector<BranchProbability> Probs;
98 typedef std::vector<BranchProbability>::iterator probability_iterator;
99 typedef std::vector<BranchProbability>::const_iterator
100 const_probability_iterator;
102 /// Keep track of the physical registers that are livein of the basicblock.
103 typedef std::vector<RegisterMaskPair> LiveInVector;
104 LiveInVector LiveIns;
106 /// Alignment of the basic block. Zero if the basic block does not need to be
107 /// aligned. The alignment is specified as log2(bytes).
108 unsigned Alignment = 0;
110 /// Indicate that this basic block is entered via an exception handler.
111 bool IsEHPad = false;
113 /// Indicate that this basic block is potentially the target of an indirect
115 bool AddressTaken = false;
117 /// Indicate that this basic block is the entry block of an EH funclet.
118 bool IsEHFuncletEntry = false;
120 /// Indicate that this basic block is the entry block of a cleanup funclet.
121 bool IsCleanupFuncletEntry = false;
123 /// \brief since getSymbol is a relatively heavy-weight operation, the symbol
124 /// is only computed once and is cached.
125 mutable MCSymbol *CachedMCSymbol = nullptr;
127 // Intrusive list support
128 MachineBasicBlock() {}
130 explicit MachineBasicBlock(MachineFunction &MF, const BasicBlock *BB);
132 ~MachineBasicBlock();
134 // MachineBasicBlocks are allocated and owned by MachineFunction.
135 friend class MachineFunction;
138 /// Return the LLVM basic block that this instance corresponded to originally.
139 /// Note that this may be NULL if this instance does not correspond directly
140 /// to an LLVM basic block.
141 const BasicBlock *getBasicBlock() const { return BB; }
143 /// Return the name of the corresponding LLVM basic block, or "(null)".
144 StringRef getName() const;
146 /// Return a formatted string to identify this block and its parent function.
147 std::string getFullName() const;
149 /// Test whether this block is potentially the target of an indirect branch.
150 bool hasAddressTaken() const { return AddressTaken; }
152 /// Set this block to reflect that it potentially is the target of an indirect
154 void setHasAddressTaken() { AddressTaken = true; }
156 /// Return the MachineFunction containing this basic block.
157 const MachineFunction *getParent() const { return xParent; }
158 MachineFunction *getParent() { return xParent; }
160 /// MachineBasicBlock iterator that automatically skips over MIs that are
161 /// inside bundles (i.e. walk top level MIs only).
162 template<typename Ty, typename IterTy>
163 class bundle_iterator
164 : public std::iterator<std::bidirectional_iterator_tag, Ty, ptrdiff_t> {
168 bundle_iterator(IterTy MI) : MII(MI) {}
170 bundle_iterator(Ty &MI) : MII(MI) {
171 assert(!MI.isBundledWithPred() &&
172 "It's not legal to initialize bundle_iterator with a bundled MI");
174 bundle_iterator(Ty *MI) : MII(MI) {
175 assert((!MI || !MI->isBundledWithPred()) &&
176 "It's not legal to initialize bundle_iterator with a bundled MI");
178 // Template allows conversion from const to nonconst.
179 template<class OtherTy, class OtherIterTy>
180 bundle_iterator(const bundle_iterator<OtherTy, OtherIterTy> &I)
181 : MII(I.getInstrIterator()) {}
182 bundle_iterator() : MII(nullptr) {}
184 Ty &operator*() const { return *MII; }
185 Ty *operator->() const { return &operator*(); }
187 operator Ty *() const { return MII.getNodePtrUnchecked(); }
189 bool operator==(const bundle_iterator &X) const {
192 bool operator!=(const bundle_iterator &X) const {
193 return !operator==(X);
196 // Increment and decrement operators...
197 bundle_iterator &operator--() { // predecrement - Back up
199 while (MII->isBundledWithPred());
202 bundle_iterator &operator++() { // preincrement - Advance
203 while (MII->isBundledWithSucc())
208 bundle_iterator operator--(int) { // postdecrement operators...
209 bundle_iterator tmp = *this;
213 bundle_iterator operator++(int) { // postincrement operators...
214 bundle_iterator tmp = *this;
219 IterTy getInstrIterator() const {
224 typedef Instructions::iterator instr_iterator;
225 typedef Instructions::const_iterator const_instr_iterator;
226 typedef std::reverse_iterator<instr_iterator> reverse_instr_iterator;
228 std::reverse_iterator<const_instr_iterator> const_reverse_instr_iterator;
231 bundle_iterator<MachineInstr,instr_iterator> iterator;
233 bundle_iterator<const MachineInstr,const_instr_iterator> const_iterator;
234 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
235 typedef std::reverse_iterator<iterator> reverse_iterator;
238 unsigned size() const { return (unsigned)Insts.size(); }
239 bool empty() const { return Insts.empty(); }
241 MachineInstr &instr_front() { return Insts.front(); }
242 MachineInstr &instr_back() { return Insts.back(); }
243 const MachineInstr &instr_front() const { return Insts.front(); }
244 const MachineInstr &instr_back() const { return Insts.back(); }
246 MachineInstr &front() { return Insts.front(); }
247 MachineInstr &back() { return *--end(); }
248 const MachineInstr &front() const { return Insts.front(); }
249 const MachineInstr &back() const { return *--end(); }
251 instr_iterator instr_begin() { return Insts.begin(); }
252 const_instr_iterator instr_begin() const { return Insts.begin(); }
253 instr_iterator instr_end() { return Insts.end(); }
254 const_instr_iterator instr_end() const { return Insts.end(); }
255 reverse_instr_iterator instr_rbegin() { return Insts.rbegin(); }
256 const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(); }
257 reverse_instr_iterator instr_rend () { return Insts.rend(); }
258 const_reverse_instr_iterator instr_rend () const { return Insts.rend(); }
260 iterator begin() { return instr_begin(); }
261 const_iterator begin() const { return instr_begin(); }
262 iterator end () { return instr_end(); }
263 const_iterator end () const { return instr_end(); }
264 reverse_iterator rbegin() { return instr_rbegin(); }
265 const_reverse_iterator rbegin() const { return instr_rbegin(); }
266 reverse_iterator rend () { return instr_rend(); }
267 const_reverse_iterator rend () const { return instr_rend(); }
269 /// Support for MachineInstr::getNextNode().
270 static Instructions MachineBasicBlock::*getSublistAccess(MachineInstr *) {
271 return &MachineBasicBlock::Insts;
274 inline iterator_range<iterator> terminators() {
275 return make_range(getFirstTerminator(), end());
277 inline iterator_range<const_iterator> terminators() const {
278 return make_range(getFirstTerminator(), end());
281 // Machine-CFG iterators
282 typedef std::vector<MachineBasicBlock *>::iterator pred_iterator;
283 typedef std::vector<MachineBasicBlock *>::const_iterator const_pred_iterator;
284 typedef std::vector<MachineBasicBlock *>::iterator succ_iterator;
285 typedef std::vector<MachineBasicBlock *>::const_iterator const_succ_iterator;
286 typedef std::vector<MachineBasicBlock *>::reverse_iterator
287 pred_reverse_iterator;
288 typedef std::vector<MachineBasicBlock *>::const_reverse_iterator
289 const_pred_reverse_iterator;
290 typedef std::vector<MachineBasicBlock *>::reverse_iterator
291 succ_reverse_iterator;
292 typedef std::vector<MachineBasicBlock *>::const_reverse_iterator
293 const_succ_reverse_iterator;
294 pred_iterator pred_begin() { return Predecessors.begin(); }
295 const_pred_iterator pred_begin() const { return Predecessors.begin(); }
296 pred_iterator pred_end() { return Predecessors.end(); }
297 const_pred_iterator pred_end() const { return Predecessors.end(); }
298 pred_reverse_iterator pred_rbegin()
299 { return Predecessors.rbegin();}
300 const_pred_reverse_iterator pred_rbegin() const
301 { return Predecessors.rbegin();}
302 pred_reverse_iterator pred_rend()
303 { return Predecessors.rend(); }
304 const_pred_reverse_iterator pred_rend() const
305 { return Predecessors.rend(); }
306 unsigned pred_size() const {
307 return (unsigned)Predecessors.size();
309 bool pred_empty() const { return Predecessors.empty(); }
310 succ_iterator succ_begin() { return Successors.begin(); }
311 const_succ_iterator succ_begin() const { return Successors.begin(); }
312 succ_iterator succ_end() { return Successors.end(); }
313 const_succ_iterator succ_end() const { return Successors.end(); }
314 succ_reverse_iterator succ_rbegin()
315 { return Successors.rbegin(); }
316 const_succ_reverse_iterator succ_rbegin() const
317 { return Successors.rbegin(); }
318 succ_reverse_iterator succ_rend()
319 { return Successors.rend(); }
320 const_succ_reverse_iterator succ_rend() const
321 { return Successors.rend(); }
322 unsigned succ_size() const {
323 return (unsigned)Successors.size();
325 bool succ_empty() const { return Successors.empty(); }
327 inline iterator_range<pred_iterator> predecessors() {
328 return make_range(pred_begin(), pred_end());
330 inline iterator_range<const_pred_iterator> predecessors() const {
331 return make_range(pred_begin(), pred_end());
333 inline iterator_range<succ_iterator> successors() {
334 return make_range(succ_begin(), succ_end());
336 inline iterator_range<const_succ_iterator> successors() const {
337 return make_range(succ_begin(), succ_end());
340 // LiveIn management methods.
342 /// Adds the specified register as a live in. Note that it is an error to add
343 /// the same register to the same set more than once unless the intention is
344 /// to call sortUniqueLiveIns after all registers are added.
345 void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask = ~0u) {
346 LiveIns.push_back(RegisterMaskPair(PhysReg, LaneMask));
348 void addLiveIn(const RegisterMaskPair &RegMaskPair) {
349 LiveIns.push_back(RegMaskPair);
352 /// Sorts and uniques the LiveIns vector. It can be significantly faster to do
353 /// this than repeatedly calling isLiveIn before calling addLiveIn for every
354 /// LiveIn insertion.
355 void sortUniqueLiveIns();
357 /// Add PhysReg as live in to this block, and ensure that there is a copy of
358 /// PhysReg to a virtual register of class RC. Return the virtual register
359 /// that is a copy of the live in PhysReg.
360 unsigned addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC);
362 /// Remove the specified register from the live in set.
363 void removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask = ~0u);
365 /// Return true if the specified register is in the live in set.
366 bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask = ~0u) const;
368 // Iteration support for live in sets. These sets are kept in sorted
369 // order by their register number.
370 typedef LiveInVector::const_iterator livein_iterator;
371 livein_iterator livein_begin() const { return LiveIns.begin(); }
372 livein_iterator livein_end() const { return LiveIns.end(); }
373 bool livein_empty() const { return LiveIns.empty(); }
374 iterator_range<livein_iterator> liveins() const {
375 return make_range(livein_begin(), livein_end());
378 /// Get the clobber mask for the start of this basic block. Funclets use this
379 /// to prevent register allocation across funclet transitions.
380 const uint32_t *getBeginClobberMask(const TargetRegisterInfo *TRI) const;
382 /// Get the clobber mask for the end of the basic block.
383 /// \see getBeginClobberMask()
384 const uint32_t *getEndClobberMask(const TargetRegisterInfo *TRI) const;
386 /// Return alignment of the basic block. The alignment is specified as
388 unsigned getAlignment() const { return Alignment; }
390 /// Set alignment of the basic block. The alignment is specified as
392 void setAlignment(unsigned Align) { Alignment = Align; }
394 /// Returns true if the block is a landing pad. That is this basic block is
395 /// entered via an exception handler.
396 bool isEHPad() const { return IsEHPad; }
398 /// Indicates the block is a landing pad. That is this basic block is entered
399 /// via an exception handler.
400 void setIsEHPad(bool V = true) { IsEHPad = V; }
402 /// If this block has a successor that is a landing pad, return it. Otherwise
404 const MachineBasicBlock *getLandingPadSuccessor() const;
406 bool hasEHPadSuccessor() const;
408 /// Returns true if this is the entry block of an EH funclet.
409 bool isEHFuncletEntry() const { return IsEHFuncletEntry; }
411 /// Indicates if this is the entry block of an EH funclet.
412 void setIsEHFuncletEntry(bool V = true) { IsEHFuncletEntry = V; }
414 /// Returns true if this is the entry block of a cleanup funclet.
415 bool isCleanupFuncletEntry() const { return IsCleanupFuncletEntry; }
417 /// Indicates if this is the entry block of a cleanup funclet.
418 void setIsCleanupFuncletEntry(bool V = true) { IsCleanupFuncletEntry = V; }
420 // Code Layout methods.
422 /// Move 'this' block before or after the specified block. This only moves
423 /// the block, it does not modify the CFG or adjust potential fall-throughs at
424 /// the end of the block.
425 void moveBefore(MachineBasicBlock *NewAfter);
426 void moveAfter(MachineBasicBlock *NewBefore);
428 /// Update the terminator instructions in block to account for changes to the
429 /// layout. If the block previously used a fallthrough, it may now need a
430 /// branch, and if it previously used branching it may now be able to use a
432 void updateTerminator();
434 // Machine-CFG mutators
436 /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
437 /// of Succ is automatically updated. PROB parameter is stored in
438 /// Probabilities list. The default probability is set as unknown. Mixing
439 /// known and unknown probabilities in successor list is not allowed. When all
440 /// successors have unknown probabilities, 1 / N is returned as the
441 /// probability for each successor, where N is the number of successors.
443 /// Note that duplicate Machine CFG edges are not allowed.
444 void addSuccessor(MachineBasicBlock *Succ,
445 BranchProbability Prob = BranchProbability::getUnknown());
447 /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
448 /// of Succ is automatically updated. The probability is not provided because
449 /// BPI is not available (e.g. -O0 is used), in which case edge probabilities
450 /// won't be used. Using this interface can save some space.
451 void addSuccessorWithoutProb(MachineBasicBlock *Succ);
453 /// Set successor probability of a given iterator.
454 void setSuccProbability(succ_iterator I, BranchProbability Prob);
456 /// Normalize probabilities of all successors so that the sum of them becomes
457 /// one. This is usually done when the current update on this MBB is done, and
458 /// the sum of its successors' probabilities is not guaranteed to be one. The
459 /// user is responsible for the correct use of this function.
460 /// MBB::removeSuccessor() has an option to do this automatically.
461 void normalizeSuccProbs() {
462 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
465 /// Validate successors' probabilities and check if the sum of them is
466 /// approximate one. This only works in DEBUG mode.
467 void validateSuccProbs() const;
469 /// Remove successor from the successors list of this MachineBasicBlock. The
470 /// Predecessors list of Succ is automatically updated.
471 /// If NormalizeSuccProbs is true, then normalize successors' probabilities
472 /// after the successor is removed.
473 void removeSuccessor(MachineBasicBlock *Succ,
474 bool NormalizeSuccProbs = false);
476 /// Remove specified successor from the successors list of this
477 /// MachineBasicBlock. The Predecessors list of Succ is automatically updated.
478 /// If NormalizeSuccProbs is true, then normalize successors' probabilities
479 /// after the successor is removed.
480 /// Return the iterator to the element after the one removed.
481 succ_iterator removeSuccessor(succ_iterator I,
482 bool NormalizeSuccProbs = false);
484 /// Replace successor OLD with NEW and update probability info.
485 void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
487 /// Transfers all the successors from MBB to this machine basic block (i.e.,
488 /// copies all the successors FromMBB and remove all the successors from
490 void transferSuccessors(MachineBasicBlock *FromMBB);
492 /// Transfers all the successors, as in transferSuccessors, and update PHI
493 /// operands in the successor blocks which refer to FromMBB to refer to this.
494 void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB);
496 /// Return true if any of the successors have probabilities attached to them.
497 bool hasSuccessorProbabilities() const { return !Probs.empty(); }
499 /// Return true if the specified MBB is a predecessor of this block.
500 bool isPredecessor(const MachineBasicBlock *MBB) const;
502 /// Return true if the specified MBB is a successor of this block.
503 bool isSuccessor(const MachineBasicBlock *MBB) const;
505 /// Return true if the specified MBB will be emitted immediately after this
506 /// block, such that if this block exits by falling through, control will
507 /// transfer to the specified MBB. Note that MBB need not be a successor at
508 /// all, for example if this block ends with an unconditional branch to some
510 bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
512 /// Return true if the block can implicitly transfer control to the block
513 /// after it by falling off the end of it. This should return false if it can
514 /// reach the block after it, but it uses an explicit branch to do so (e.g., a
515 /// table jump). True is a conservative answer.
516 bool canFallThrough();
518 /// Returns a pointer to the first instruction in this block that is not a
519 /// PHINode instruction. When adding instructions to the beginning of the
520 /// basic block, they should be added before the returned value, not before
521 /// the first instruction, which might be PHI.
522 /// Returns end() is there's no non-PHI instruction.
523 iterator getFirstNonPHI();
525 /// Return the first instruction in MBB after I that is not a PHI or a label.
526 /// This is the correct point to insert copies at the beginning of a basic
528 iterator SkipPHIsAndLabels(iterator I);
530 /// Returns an iterator to the first terminator instruction of this basic
531 /// block. If a terminator does not exist, it returns end().
532 iterator getFirstTerminator();
533 const_iterator getFirstTerminator() const {
534 return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
537 /// Same getFirstTerminator but it ignores bundles and return an
538 /// instr_iterator instead.
539 instr_iterator getFirstInstrTerminator();
541 /// Returns an iterator to the first non-debug instruction in the basic block,
543 iterator getFirstNonDebugInstr();
544 const_iterator getFirstNonDebugInstr() const {
545 return const_cast<MachineBasicBlock *>(this)->getFirstNonDebugInstr();
548 /// Returns an iterator to the last non-debug instruction in the basic block,
550 iterator getLastNonDebugInstr();
551 const_iterator getLastNonDebugInstr() const {
552 return const_cast<MachineBasicBlock *>(this)->getLastNonDebugInstr();
555 /// Convenience function that returns true if the block ends in a return
557 bool isReturnBlock() const {
558 return !empty() && back().isReturn();
561 /// Split the critical edge from this block to the given successor block, and
562 /// return the newly created block, or null if splitting is not possible.
564 /// This function updates LiveVariables, MachineDominatorTree, and
565 /// MachineLoopInfo, as applicable.
566 MachineBasicBlock *SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P);
568 void pop_front() { Insts.pop_front(); }
569 void pop_back() { Insts.pop_back(); }
570 void push_back(MachineInstr *MI) { Insts.push_back(MI); }
572 /// Insert MI into the instruction list before I, possibly inside a bundle.
574 /// If the insertion point is inside a bundle, MI will be added to the bundle,
575 /// otherwise MI will not be added to any bundle. That means this function
576 /// alone can't be used to prepend or append instructions to bundles. See
577 /// MIBundleBuilder::insert() for a more reliable way of doing that.
578 instr_iterator insert(instr_iterator I, MachineInstr *M);
580 /// Insert a range of instructions into the instruction list before I.
581 template<typename IT>
582 void insert(iterator I, IT S, IT E) {
583 assert((I == end() || I->getParent() == this) &&
584 "iterator points outside of basic block");
585 Insts.insert(I.getInstrIterator(), S, E);
588 /// Insert MI into the instruction list before I.
589 iterator insert(iterator I, MachineInstr *MI) {
590 assert((I == end() || I->getParent() == this) &&
591 "iterator points outside of basic block");
592 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
593 "Cannot insert instruction with bundle flags");
594 return Insts.insert(I.getInstrIterator(), MI);
597 /// Insert MI into the instruction list after I.
598 iterator insertAfter(iterator I, MachineInstr *MI) {
599 assert((I == end() || I->getParent() == this) &&
600 "iterator points outside of basic block");
601 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
602 "Cannot insert instruction with bundle flags");
603 return Insts.insertAfter(I.getInstrIterator(), MI);
606 /// Remove an instruction from the instruction list and delete it.
608 /// If the instruction is part of a bundle, the other instructions in the
609 /// bundle will still be bundled after removing the single instruction.
610 instr_iterator erase(instr_iterator I);
612 /// Remove an instruction from the instruction list and delete it.
614 /// If the instruction is part of a bundle, the other instructions in the
615 /// bundle will still be bundled after removing the single instruction.
616 instr_iterator erase_instr(MachineInstr *I) {
617 return erase(instr_iterator(I));
620 /// Remove a range of instructions from the instruction list and delete them.
621 iterator erase(iterator I, iterator E) {
622 return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
625 /// Remove an instruction or bundle from the instruction list and delete it.
627 /// If I points to a bundle of instructions, they are all erased.
628 iterator erase(iterator I) {
629 return erase(I, std::next(I));
632 /// Remove an instruction from the instruction list and delete it.
634 /// If I is the head of a bundle of instructions, the whole bundle will be
636 iterator erase(MachineInstr *I) {
637 return erase(iterator(I));
640 /// Remove the unbundled instruction from the instruction list without
643 /// This function can not be used to remove bundled instructions, use
644 /// remove_instr to remove individual instructions from a bundle.
645 MachineInstr *remove(MachineInstr *I) {
646 assert(!I->isBundled() && "Cannot remove bundled instructions");
647 return Insts.remove(instr_iterator(I));
650 /// Remove the possibly bundled instruction from the instruction list
651 /// without deleting it.
653 /// If the instruction is part of a bundle, the other instructions in the
654 /// bundle will still be bundled after removing the single instruction.
655 MachineInstr *remove_instr(MachineInstr *I);
661 /// Take an instruction from MBB 'Other' at the position From, and insert it
662 /// into this MBB right before 'Where'.
664 /// If From points to a bundle of instructions, the whole bundle is moved.
665 void splice(iterator Where, MachineBasicBlock *Other, iterator From) {
666 // The range splice() doesn't allow noop moves, but this one does.
668 splice(Where, Other, From, std::next(From));
671 /// Take a block of instructions from MBB 'Other' in the range [From, To),
672 /// and insert them into this MBB right before 'Where'.
674 /// The instruction at 'Where' must not be included in the range of
675 /// instructions to move.
676 void splice(iterator Where, MachineBasicBlock *Other,
677 iterator From, iterator To) {
678 Insts.splice(Where.getInstrIterator(), Other->Insts,
679 From.getInstrIterator(), To.getInstrIterator());
682 /// This method unlinks 'this' from the containing function, and returns it,
683 /// but does not delete it.
684 MachineBasicBlock *removeFromParent();
686 /// This method unlinks 'this' from the containing function and deletes it.
687 void eraseFromParent();
689 /// Given a machine basic block that branched to 'Old', change the code and
690 /// CFG so that it branches to 'New' instead.
691 void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
693 /// Various pieces of code can cause excess edges in the CFG to be inserted.
694 /// If we have proven that MBB can only branch to DestA and DestB, remove any
695 /// other MBB successors from the CFG. DestA and DestB can be null. Besides
696 /// DestA and DestB, retain other edges leading to LandingPads (currently
697 /// there can be only one; we don't check or require that here). Note it is
698 /// possible that DestA and/or DestB are LandingPads.
699 bool CorrectExtraCFGEdges(MachineBasicBlock *DestA,
700 MachineBasicBlock *DestB,
703 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
704 /// instructions. Return UnknownLoc if there is none.
705 DebugLoc findDebugLoc(instr_iterator MBBI);
706 DebugLoc findDebugLoc(iterator MBBI) {
707 return findDebugLoc(MBBI.getInstrIterator());
710 /// Possible outcome of a register liveness query to computeRegisterLiveness()
711 enum LivenessQueryResult {
712 LQR_Live, ///< Register is known to be (at least partially) live.
713 LQR_Dead, ///< Register is known to be fully dead.
714 LQR_Unknown ///< Register liveness not decidable from local neighborhood.
717 /// Return whether (physical) register \p Reg has been <def>ined and not
718 /// <kill>ed as of just before \p Before.
720 /// Search is localised to a neighborhood of \p Neighborhood instructions
721 /// before (searching for defs or kills) and \p Neighborhood instructions
722 /// after (searching just for defs) \p Before.
724 /// \p Reg must be a physical register.
725 LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
727 const_iterator Before,
728 unsigned Neighborhood=10) const;
730 // Debugging methods.
732 void print(raw_ostream &OS, SlotIndexes* = nullptr) const;
733 void print(raw_ostream &OS, ModuleSlotTracker &MST,
734 SlotIndexes * = nullptr) const;
736 // Printing method used by LoopInfo.
737 void printAsOperand(raw_ostream &OS, bool PrintType = true) const;
739 /// MachineBasicBlocks are uniquely numbered at the function level, unless
740 /// they're not in a MachineFunction yet, in which case this will return -1.
741 int getNumber() const { return Number; }
742 void setNumber(int N) { Number = N; }
744 /// Return the MCSymbol for this basic block.
745 MCSymbol *getSymbol() const;
749 /// Return probability iterator corresponding to the I successor iterator.
750 probability_iterator getProbabilityIterator(succ_iterator I);
751 const_probability_iterator
752 getProbabilityIterator(const_succ_iterator I) const;
754 friend class MachineBranchProbabilityInfo;
755 friend class MIPrinter;
757 /// Return probability of the edge from this block to MBB. This method should
758 /// NOT be called directly, but by using getEdgeProbability method from
759 /// MachineBranchProbabilityInfo class.
760 BranchProbability getSuccProbability(const_succ_iterator Succ) const;
762 // Methods used to maintain doubly linked list of blocks...
763 friend struct ilist_traits<MachineBasicBlock>;
765 // Machine-CFG mutators
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->addSuccessor instead.
770 void addPredecessor(MachineBasicBlock *Pred);
772 /// Remove Pred as a predecessor of this MachineBasicBlock. Don't do this
773 /// unless you know what you're doing, because it doesn't update Pred's
774 /// successors list. Use Pred->removeSuccessor instead.
775 void removePredecessor(MachineBasicBlock *Pred);
778 raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
780 // This is useful when building IndexedMaps keyed on basic block pointers.
781 struct MBB2NumberFunctor :
782 public std::unary_function<const MachineBasicBlock*, unsigned> {
783 unsigned operator()(const MachineBasicBlock *MBB) const {
784 return MBB->getNumber();
788 //===--------------------------------------------------------------------===//
789 // GraphTraits specializations for machine basic block graphs (machine-CFGs)
790 //===--------------------------------------------------------------------===//
792 // Provide specializations of GraphTraits to be able to treat a
793 // MachineFunction as a graph of MachineBasicBlocks.
796 template <> struct GraphTraits<MachineBasicBlock *> {
797 typedef MachineBasicBlock NodeType;
798 typedef MachineBasicBlock::succ_iterator ChildIteratorType;
800 static NodeType *getEntryNode(MachineBasicBlock *BB) { return BB; }
801 static inline ChildIteratorType child_begin(NodeType *N) {
802 return N->succ_begin();
804 static inline ChildIteratorType child_end(NodeType *N) {
805 return N->succ_end();
809 template <> struct GraphTraits<const MachineBasicBlock *> {
810 typedef const MachineBasicBlock NodeType;
811 typedef MachineBasicBlock::const_succ_iterator ChildIteratorType;
813 static NodeType *getEntryNode(const MachineBasicBlock *BB) { return BB; }
814 static inline ChildIteratorType child_begin(NodeType *N) {
815 return N->succ_begin();
817 static inline ChildIteratorType child_end(NodeType *N) {
818 return N->succ_end();
822 // Provide specializations of GraphTraits to be able to treat a
823 // MachineFunction as a graph of MachineBasicBlocks and to walk it
824 // in inverse order. Inverse order for a function is considered
825 // to be when traversing the predecessor edges of a MBB
826 // instead of the successor edges.
828 template <> struct GraphTraits<Inverse<MachineBasicBlock*> > {
829 typedef MachineBasicBlock NodeType;
830 typedef MachineBasicBlock::pred_iterator ChildIteratorType;
831 static NodeType *getEntryNode(Inverse<MachineBasicBlock *> G) {
834 static inline ChildIteratorType child_begin(NodeType *N) {
835 return N->pred_begin();
837 static inline ChildIteratorType child_end(NodeType *N) {
838 return N->pred_end();
842 template <> struct GraphTraits<Inverse<const MachineBasicBlock*> > {
843 typedef const MachineBasicBlock NodeType;
844 typedef MachineBasicBlock::const_pred_iterator ChildIteratorType;
845 static NodeType *getEntryNode(Inverse<const MachineBasicBlock*> G) {
848 static inline ChildIteratorType child_begin(NodeType *N) {
849 return N->pred_begin();
851 static inline ChildIteratorType child_end(NodeType *N) {
852 return N->pred_end();
858 /// MachineInstrSpan provides an interface to get an iteration range
859 /// containing the instruction it was initialized with, along with all
860 /// those instructions inserted prior to or following that instruction
861 /// at some point after the MachineInstrSpan is constructed.
862 class MachineInstrSpan {
863 MachineBasicBlock &MBB;
864 MachineBasicBlock::iterator I, B, E;
866 MachineInstrSpan(MachineBasicBlock::iterator I)
867 : MBB(*I->getParent()),
869 B(I == MBB.begin() ? MBB.end() : std::prev(I)),
872 MachineBasicBlock::iterator begin() {
873 return B == MBB.end() ? MBB.begin() : std::next(B);
875 MachineBasicBlock::iterator end() { return E; }
876 bool empty() { return begin() == end(); }
878 MachineBasicBlock::iterator getInitial() { return I; }
881 } // End llvm namespace