1//===-- llvm/CodeGen/MachineBasicBlock.h ------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Collect the sequence of machine instructions for a basic block.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CODEGEN_MACHINEBASICBLOCK_H
15#define LLVM_CODEGEN_MACHINEBASICBLOCK_H
16
17#include "llvm/ADT/GraphTraits.h"
18#include "llvm/CodeGen/MachineInstr.h"
19#include "llvm/Support/DataTypes.h"
20#include <functional>
21
22namespace llvm {
23
24class Pass;
25class BasicBlock;
26class MachineFunction;
27class MCSymbol;
28class SlotIndexes;
29class StringRef;
30class raw_ostream;
31class MachineBranchProbabilityInfo;
32
33template <>
34struct ilist_traits<MachineInstr> : public ilist_default_traits<MachineInstr> {
35private:
36  mutable ilist_half_node<MachineInstr> Sentinel;
37
38  // this is only set by the MachineBasicBlock owning the LiveList
39  friend class MachineBasicBlock;
40  MachineBasicBlock* Parent;
41
42public:
43  MachineInstr *createSentinel() const {
44    return static_cast<MachineInstr*>(&Sentinel);
45  }
46  void destroySentinel(MachineInstr *) const {}
47
48  MachineInstr *provideInitialHead() const { return createSentinel(); }
49  MachineInstr *ensureHead(MachineInstr*) const { return createSentinel(); }
50  static void noteHead(MachineInstr*, MachineInstr*) {}
51
52  void addNodeToList(MachineInstr* N);
53  void removeNodeFromList(MachineInstr* N);
54  void transferNodesFromList(ilist_traits &SrcTraits,
55                             ilist_iterator<MachineInstr> first,
56                             ilist_iterator<MachineInstr> last);
57  void deleteNode(MachineInstr *N);
58private:
59  void createNode(const MachineInstr &);
60};
61
62class MachineBasicBlock : public ilist_node<MachineBasicBlock> {
63  typedef ilist<MachineInstr> Instructions;
64  Instructions Insts;
65  const BasicBlock *BB;
66  int Number;
67  MachineFunction *xParent;
68
69  /// Predecessors/Successors - Keep track of the predecessor / successor
70  /// basicblocks.
71  std::vector<MachineBasicBlock *> Predecessors;
72  std::vector<MachineBasicBlock *> Successors;
73
74  /// Weights - Keep track of the weights to the successors. This vector
75  /// has the same order as Successors, or it is empty if we don't use it
76  /// (disable optimization).
77  std::vector<uint32_t> Weights;
78  typedef std::vector<uint32_t>::iterator weight_iterator;
79  typedef std::vector<uint32_t>::const_iterator const_weight_iterator;
80
81  /// LiveIns - Keep track of the physical registers that are livein of
82  /// the basicblock.
83  std::vector<unsigned> LiveIns;
84
85  /// Alignment - Alignment of the basic block. Zero if the basic block does
86  /// not need to be aligned.
87  /// The alignment is specified as log2(bytes).
88  unsigned Alignment;
89
90  /// IsLandingPad - Indicate that this basic block is entered via an
91  /// exception handler.
92  bool IsLandingPad;
93
94  /// AddressTaken - Indicate that this basic block is potentially the
95  /// target of an indirect branch.
96  bool AddressTaken;
97
98  /// \brief since getSymbol is a relatively heavy-weight operation, the symbol
99  /// is only computed once and is cached.
100  mutable MCSymbol *CachedMCSymbol;
101
102  // Intrusive list support
103  MachineBasicBlock() {}
104
105  explicit MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb);
106
107  ~MachineBasicBlock();
108
109  // MachineBasicBlocks are allocated and owned by MachineFunction.
110  friend class MachineFunction;
111
112public:
113  /// getBasicBlock - Return the LLVM basic block that this instance
114  /// corresponded to originally. Note that this may be NULL if this instance
115  /// does not correspond directly to an LLVM basic block.
116  ///
117  const BasicBlock *getBasicBlock() const { return BB; }
118
119  /// getName - Return the name of the corresponding LLVM basic block, or
120  /// "(null)".
121  StringRef getName() const;
122
123  /// getFullName - Return a formatted string to identify this block and its
124  /// parent function.
125  std::string getFullName() const;
126
127  /// hasAddressTaken - Test whether this block is potentially the target
128  /// of an indirect branch.
129  bool hasAddressTaken() const { return AddressTaken; }
130
131  /// setHasAddressTaken - Set this block to reflect that it potentially
132  /// is the target of an indirect branch.
133  void setHasAddressTaken() { AddressTaken = true; }
134
135  /// getParent - Return the MachineFunction containing this basic block.
136  ///
137  const MachineFunction *getParent() const { return xParent; }
138  MachineFunction *getParent() { return xParent; }
139
140
141  /// bundle_iterator - MachineBasicBlock iterator that automatically skips over
142  /// MIs that are inside bundles (i.e. walk top level MIs only).
143  template<typename Ty, typename IterTy>
144  class bundle_iterator
145    : public std::iterator<std::bidirectional_iterator_tag, Ty, ptrdiff_t> {
146    IterTy MII;
147
148  public:
149    bundle_iterator(IterTy mii) : MII(mii) {}
150
151    bundle_iterator(Ty &mi) : MII(mi) {
152      assert(!mi.isBundledWithPred() &&
153             "It's not legal to initialize bundle_iterator with a bundled MI");
154    }
155    bundle_iterator(Ty *mi) : MII(mi) {
156      assert((!mi || !mi->isBundledWithPred()) &&
157             "It's not legal to initialize bundle_iterator with a bundled MI");
158    }
159    // Template allows conversion from const to nonconst.
160    template<class OtherTy, class OtherIterTy>
161    bundle_iterator(const bundle_iterator<OtherTy, OtherIterTy> &I)
162      : MII(I.getInstrIterator()) {}
163    bundle_iterator() : MII(nullptr) {}
164
165    Ty &operator*() const { return *MII; }
166    Ty *operator->() const { return &operator*(); }
167
168    operator Ty*() const { return MII; }
169
170    bool operator==(const bundle_iterator &x) const {
171      return MII == x.MII;
172    }
173    bool operator!=(const bundle_iterator &x) const {
174      return !operator==(x);
175    }
176
177    // Increment and decrement operators...
178    bundle_iterator &operator--() {      // predecrement - Back up
179      do --MII;
180      while (MII->isBundledWithPred());
181      return *this;
182    }
183    bundle_iterator &operator++() {      // preincrement - Advance
184      while (MII->isBundledWithSucc())
185        ++MII;
186      ++MII;
187      return *this;
188    }
189    bundle_iterator operator--(int) {    // postdecrement operators...
190      bundle_iterator tmp = *this;
191      --*this;
192      return tmp;
193    }
194    bundle_iterator operator++(int) {    // postincrement operators...
195      bundle_iterator tmp = *this;
196      ++*this;
197      return tmp;
198    }
199
200    IterTy getInstrIterator() const {
201      return MII;
202    }
203  };
204
205  typedef Instructions::iterator                                 instr_iterator;
206  typedef Instructions::const_iterator                     const_instr_iterator;
207  typedef std::reverse_iterator<instr_iterator>          reverse_instr_iterator;
208  typedef
209  std::reverse_iterator<const_instr_iterator>      const_reverse_instr_iterator;
210
211  typedef
212  bundle_iterator<MachineInstr,instr_iterator>                         iterator;
213  typedef
214  bundle_iterator<const MachineInstr,const_instr_iterator>       const_iterator;
215  typedef std::reverse_iterator<const_iterator>          const_reverse_iterator;
216  typedef std::reverse_iterator<iterator>                      reverse_iterator;
217
218
219  unsigned size() const { return (unsigned)Insts.size(); }
220  bool empty() const { return Insts.empty(); }
221
222  MachineInstr       &instr_front()       { return Insts.front(); }
223  MachineInstr       &instr_back()        { return Insts.back();  }
224  const MachineInstr &instr_front() const { return Insts.front(); }
225  const MachineInstr &instr_back()  const { return Insts.back();  }
226
227  MachineInstr       &front()             { return Insts.front(); }
228  MachineInstr       &back()              { return *--end();      }
229  const MachineInstr &front()       const { return Insts.front(); }
230  const MachineInstr &back()        const { return *--end();      }
231
232  instr_iterator                instr_begin()       { return Insts.begin();  }
233  const_instr_iterator          instr_begin() const { return Insts.begin();  }
234  instr_iterator                  instr_end()       { return Insts.end();    }
235  const_instr_iterator            instr_end() const { return Insts.end();    }
236  reverse_instr_iterator       instr_rbegin()       { return Insts.rbegin(); }
237  const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(); }
238  reverse_instr_iterator       instr_rend  ()       { return Insts.rend();   }
239  const_reverse_instr_iterator instr_rend  () const { return Insts.rend();   }
240
241  iterator                begin()       { return instr_begin();  }
242  const_iterator          begin() const { return instr_begin();  }
243  iterator                end  ()       { return instr_end();    }
244  const_iterator          end  () const { return instr_end();    }
245  reverse_iterator       rbegin()       { return instr_rbegin(); }
246  const_reverse_iterator rbegin() const { return instr_rbegin(); }
247  reverse_iterator       rend  ()       { return instr_rend();   }
248  const_reverse_iterator rend  () const { return instr_rend();   }
249
250  inline iterator_range<iterator> terminators() {
251    return iterator_range<iterator>(getFirstTerminator(), end());
252  }
253  inline iterator_range<const_iterator> terminators() const {
254    return iterator_range<const_iterator>(getFirstTerminator(), end());
255  }
256
257  // Machine-CFG iterators
258  typedef std::vector<MachineBasicBlock *>::iterator       pred_iterator;
259  typedef std::vector<MachineBasicBlock *>::const_iterator const_pred_iterator;
260  typedef std::vector<MachineBasicBlock *>::iterator       succ_iterator;
261  typedef std::vector<MachineBasicBlock *>::const_iterator const_succ_iterator;
262  typedef std::vector<MachineBasicBlock *>::reverse_iterator
263                                                         pred_reverse_iterator;
264  typedef std::vector<MachineBasicBlock *>::const_reverse_iterator
265                                                   const_pred_reverse_iterator;
266  typedef std::vector<MachineBasicBlock *>::reverse_iterator
267                                                         succ_reverse_iterator;
268  typedef std::vector<MachineBasicBlock *>::const_reverse_iterator
269                                                   const_succ_reverse_iterator;
270  pred_iterator        pred_begin()       { return Predecessors.begin(); }
271  const_pred_iterator  pred_begin() const { return Predecessors.begin(); }
272  pred_iterator        pred_end()         { return Predecessors.end();   }
273  const_pred_iterator  pred_end()   const { return Predecessors.end();   }
274  pred_reverse_iterator        pred_rbegin()
275                                          { return Predecessors.rbegin();}
276  const_pred_reverse_iterator  pred_rbegin() const
277                                          { return Predecessors.rbegin();}
278  pred_reverse_iterator        pred_rend()
279                                          { return Predecessors.rend();  }
280  const_pred_reverse_iterator  pred_rend()   const
281                                          { return Predecessors.rend();  }
282  unsigned             pred_size()  const {
283    return (unsigned)Predecessors.size();
284  }
285  bool                 pred_empty() const { return Predecessors.empty(); }
286  succ_iterator        succ_begin()       { return Successors.begin();   }
287  const_succ_iterator  succ_begin() const { return Successors.begin();   }
288  succ_iterator        succ_end()         { return Successors.end();     }
289  const_succ_iterator  succ_end()   const { return Successors.end();     }
290  succ_reverse_iterator        succ_rbegin()
291                                          { return Successors.rbegin();  }
292  const_succ_reverse_iterator  succ_rbegin() const
293                                          { return Successors.rbegin();  }
294  succ_reverse_iterator        succ_rend()
295                                          { return Successors.rend();    }
296  const_succ_reverse_iterator  succ_rend()   const
297                                          { return Successors.rend();    }
298  unsigned             succ_size()  const {
299    return (unsigned)Successors.size();
300  }
301  bool                 succ_empty() const { return Successors.empty();   }
302
303  inline iterator_range<pred_iterator> predecessors() {
304    return iterator_range<pred_iterator>(pred_begin(), pred_end());
305  }
306  inline iterator_range<const_pred_iterator> predecessors() const {
307    return iterator_range<const_pred_iterator>(pred_begin(), pred_end());
308  }
309  inline iterator_range<succ_iterator> successors() {
310    return iterator_range<succ_iterator>(succ_begin(), succ_end());
311  }
312  inline iterator_range<const_succ_iterator> successors() const {
313    return iterator_range<const_succ_iterator>(succ_begin(), succ_end());
314  }
315
316  // LiveIn management methods.
317
318  /// addLiveIn - Add the specified register as a live in.  Note that it
319  /// is an error to add the same register to the same set more than once.
320  void addLiveIn(unsigned Reg)  { LiveIns.push_back(Reg); }
321
322  /// Add PhysReg as live in to this block, and ensure that there is a copy of
323  /// PhysReg to a virtual register of class RC. Return the virtual register
324  /// that is a copy of the live in PhysReg.
325  unsigned addLiveIn(unsigned PhysReg, const TargetRegisterClass *RC);
326
327  /// removeLiveIn - Remove the specified register from the live in set.
328  ///
329  void removeLiveIn(unsigned Reg);
330
331  /// isLiveIn - Return true if the specified register is in the live in set.
332  ///
333  bool isLiveIn(unsigned Reg) const;
334
335  // Iteration support for live in sets.  These sets are kept in sorted
336  // order by their register number.
337  typedef std::vector<unsigned>::const_iterator livein_iterator;
338  livein_iterator livein_begin() const { return LiveIns.begin(); }
339  livein_iterator livein_end()   const { return LiveIns.end(); }
340  bool            livein_empty() const { return LiveIns.empty(); }
341
342  /// getAlignment - Return alignment of the basic block.
343  /// The alignment is specified as log2(bytes).
344  ///
345  unsigned getAlignment() const { return Alignment; }
346
347  /// setAlignment - Set alignment of the basic block.
348  /// The alignment is specified as log2(bytes).
349  ///
350  void setAlignment(unsigned Align) { Alignment = Align; }
351
352  /// isLandingPad - Returns true if the block is a landing pad. That is
353  /// this basic block is entered via an exception handler.
354  bool isLandingPad() const { return IsLandingPad; }
355
356  /// setIsLandingPad - Indicates the block is a landing pad.  That is
357  /// this basic block is entered via an exception handler.
358  void setIsLandingPad(bool V = true) { IsLandingPad = V; }
359
360  /// getLandingPadSuccessor - If this block has a successor that is a landing
361  /// pad, return it. Otherwise return NULL.
362  const MachineBasicBlock *getLandingPadSuccessor() const;
363
364  // Code Layout methods.
365
366  /// moveBefore/moveAfter - move 'this' block before or after the specified
367  /// block.  This only moves the block, it does not modify the CFG or adjust
368  /// potential fall-throughs at the end of the block.
369  void moveBefore(MachineBasicBlock *NewAfter);
370  void moveAfter(MachineBasicBlock *NewBefore);
371
372  /// updateTerminator - Update the terminator instructions in block to account
373  /// for changes to the layout. If the block previously used a fallthrough,
374  /// it may now need a branch, and if it previously used branching it may now
375  /// be able to use a fallthrough.
376  void updateTerminator();
377
378  // Machine-CFG mutators
379
380  /// addSuccessor - Add succ as a successor of this MachineBasicBlock.
381  /// The Predecessors list of succ is automatically updated. WEIGHT
382  /// parameter is stored in Weights list and it may be used by
383  /// MachineBranchProbabilityInfo analysis to calculate branch probability.
384  ///
385  /// Note that duplicate Machine CFG edges are not allowed.
386  ///
387  void addSuccessor(MachineBasicBlock *succ, uint32_t weight = 0);
388
389  /// Set successor weight of a given iterator.
390  void setSuccWeight(succ_iterator I, uint32_t weight);
391
392  /// removeSuccessor - Remove successor from the successors list of this
393  /// MachineBasicBlock. The Predecessors list of succ is automatically updated.
394  ///
395  void removeSuccessor(MachineBasicBlock *succ);
396
397  /// removeSuccessor - Remove specified successor from the successors list of
398  /// this MachineBasicBlock. The Predecessors list of succ is automatically
399  /// updated.  Return the iterator to the element after the one removed.
400  ///
401  succ_iterator removeSuccessor(succ_iterator I);
402
403  /// replaceSuccessor - Replace successor OLD with NEW and update weight info.
404  ///
405  void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
406
407
408  /// transferSuccessors - Transfers all the successors from MBB to this
409  /// machine basic block (i.e., copies all the successors fromMBB and
410  /// remove all the successors from fromMBB).
411  void transferSuccessors(MachineBasicBlock *fromMBB);
412
413  /// transferSuccessorsAndUpdatePHIs - Transfers all the successors, as
414  /// in transferSuccessors, and update PHI operands in the successor blocks
415  /// which refer to fromMBB to refer to this.
416  void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB);
417
418  /// isPredecessor - Return true if the specified MBB is a predecessor of this
419  /// block.
420  bool isPredecessor(const MachineBasicBlock *MBB) const;
421
422  /// isSuccessor - Return true if the specified MBB is a successor of this
423  /// block.
424  bool isSuccessor(const MachineBasicBlock *MBB) const;
425
426  /// isLayoutSuccessor - Return true if the specified MBB will be emitted
427  /// immediately after this block, such that if this block exits by
428  /// falling through, control will transfer to the specified MBB. Note
429  /// that MBB need not be a successor at all, for example if this block
430  /// ends with an unconditional branch to some other block.
431  bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
432
433  /// canFallThrough - Return true if the block can implicitly transfer
434  /// control to the block after it by falling off the end of it.  This should
435  /// return false if it can reach the block after it, but it uses an explicit
436  /// branch to do so (e.g., a table jump).  True is a conservative answer.
437  bool canFallThrough();
438
439  /// Returns a pointer to the first instruction in this block that is not a
440  /// PHINode instruction. When adding instructions to the beginning of the
441  /// basic block, they should be added before the returned value, not before
442  /// the first instruction, which might be PHI.
443  /// Returns end() is there's no non-PHI instruction.
444  iterator getFirstNonPHI();
445
446  /// SkipPHIsAndLabels - Return the first instruction in MBB after I that is
447  /// not a PHI or a label. This is the correct point to insert copies at the
448  /// beginning of a basic block.
449  iterator SkipPHIsAndLabels(iterator I);
450
451  /// getFirstTerminator - returns an iterator to the first terminator
452  /// instruction of this basic block. If a terminator does not exist,
453  /// it returns end()
454  iterator getFirstTerminator();
455  const_iterator getFirstTerminator() const;
456
457  /// getFirstInstrTerminator - Same getFirstTerminator but it ignores bundles
458  /// and return an instr_iterator instead.
459  instr_iterator getFirstInstrTerminator();
460
461  /// getLastNonDebugInstr - returns an iterator to the last non-debug
462  /// instruction in the basic block, or end()
463  iterator getLastNonDebugInstr();
464  const_iterator getLastNonDebugInstr() const;
465
466  /// SplitCriticalEdge - Split the critical edge from this block to the
467  /// given successor block, and return the newly created block, or null
468  /// if splitting is not possible.
469  ///
470  /// This function updates LiveVariables, MachineDominatorTree, and
471  /// MachineLoopInfo, as applicable.
472  MachineBasicBlock *SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P);
473
474  void pop_front() { Insts.pop_front(); }
475  void pop_back() { Insts.pop_back(); }
476  void push_back(MachineInstr *MI) { Insts.push_back(MI); }
477
478  /// Insert MI into the instruction list before I, possibly inside a bundle.
479  ///
480  /// If the insertion point is inside a bundle, MI will be added to the bundle,
481  /// otherwise MI will not be added to any bundle. That means this function
482  /// alone can't be used to prepend or append instructions to bundles. See
483  /// MIBundleBuilder::insert() for a more reliable way of doing that.
484  instr_iterator insert(instr_iterator I, MachineInstr *M);
485
486  /// Insert a range of instructions into the instruction list before I.
487  template<typename IT>
488  void insert(iterator I, IT S, IT E) {
489    assert((I == end() || I->getParent() == this) &&
490           "iterator points outside of basic block");
491    Insts.insert(I.getInstrIterator(), S, E);
492  }
493
494  /// Insert MI into the instruction list before I.
495  iterator insert(iterator I, MachineInstr *MI) {
496    assert((I == end() || I->getParent() == this) &&
497           "iterator points outside of basic block");
498    assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
499           "Cannot insert instruction with bundle flags");
500    return Insts.insert(I.getInstrIterator(), MI);
501  }
502
503  /// Insert MI into the instruction list after I.
504  iterator insertAfter(iterator I, MachineInstr *MI) {
505    assert((I == end() || I->getParent() == this) &&
506           "iterator points outside of basic block");
507    assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
508           "Cannot insert instruction with bundle flags");
509    return Insts.insertAfter(I.getInstrIterator(), MI);
510  }
511
512  /// Remove an instruction from the instruction list and delete it.
513  ///
514  /// If the instruction is part of a bundle, the other instructions in the
515  /// bundle will still be bundled after removing the single instruction.
516  instr_iterator erase(instr_iterator I);
517
518  /// Remove an instruction from the instruction list and delete it.
519  ///
520  /// If the instruction is part of a bundle, the other instructions in the
521  /// bundle will still be bundled after removing the single instruction.
522  instr_iterator erase_instr(MachineInstr *I) {
523    return erase(instr_iterator(I));
524  }
525
526  /// Remove a range of instructions from the instruction list and delete them.
527  iterator erase(iterator I, iterator E) {
528    return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
529  }
530
531  /// Remove an instruction or bundle from the instruction list and delete it.
532  ///
533  /// If I points to a bundle of instructions, they are all erased.
534  iterator erase(iterator I) {
535    return erase(I, std::next(I));
536  }
537
538  /// Remove an instruction from the instruction list and delete it.
539  ///
540  /// If I is the head of a bundle of instructions, the whole bundle will be
541  /// erased.
542  iterator erase(MachineInstr *I) {
543    return erase(iterator(I));
544  }
545
546  /// Remove the unbundled instruction from the instruction list without
547  /// deleting it.
548  ///
549  /// This function can not be used to remove bundled instructions, use
550  /// remove_instr to remove individual instructions from a bundle.
551  MachineInstr *remove(MachineInstr *I) {
552    assert(!I->isBundled() && "Cannot remove bundled instructions");
553    return Insts.remove(I);
554  }
555
556  /// Remove the possibly bundled instruction from the instruction list
557  /// without deleting it.
558  ///
559  /// If the instruction is part of a bundle, the other instructions in the
560  /// bundle will still be bundled after removing the single instruction.
561  MachineInstr *remove_instr(MachineInstr *I);
562
563  void clear() {
564    Insts.clear();
565  }
566
567  /// Take an instruction from MBB 'Other' at the position From, and insert it
568  /// into this MBB right before 'Where'.
569  ///
570  /// If From points to a bundle of instructions, the whole bundle is moved.
571  void splice(iterator Where, MachineBasicBlock *Other, iterator From) {
572    // The range splice() doesn't allow noop moves, but this one does.
573    if (Where != From)
574      splice(Where, Other, From, std::next(From));
575  }
576
577  /// Take a block of instructions from MBB 'Other' in the range [From, To),
578  /// and insert them into this MBB right before 'Where'.
579  ///
580  /// The instruction at 'Where' must not be included in the range of
581  /// instructions to move.
582  void splice(iterator Where, MachineBasicBlock *Other,
583              iterator From, iterator To) {
584    Insts.splice(Where.getInstrIterator(), Other->Insts,
585                 From.getInstrIterator(), To.getInstrIterator());
586  }
587
588  /// removeFromParent - This method unlinks 'this' from the containing
589  /// function, and returns it, but does not delete it.
590  MachineBasicBlock *removeFromParent();
591
592  /// eraseFromParent - This method unlinks 'this' from the containing
593  /// function and deletes it.
594  void eraseFromParent();
595
596  /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
597  /// 'Old', change the code and CFG so that it branches to 'New' instead.
598  void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
599
600  /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in
601  /// the CFG to be inserted.  If we have proven that MBB can only branch to
602  /// DestA and DestB, remove any other MBB successors from the CFG. DestA and
603  /// DestB can be null. Besides DestA and DestB, retain other edges leading
604  /// to LandingPads (currently there can be only one; we don't check or require
605  /// that here). Note it is possible that DestA and/or DestB are LandingPads.
606  bool CorrectExtraCFGEdges(MachineBasicBlock *DestA,
607                            MachineBasicBlock *DestB,
608                            bool isCond);
609
610  /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
611  /// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
612  DebugLoc findDebugLoc(instr_iterator MBBI);
613  DebugLoc findDebugLoc(iterator MBBI) {
614    return findDebugLoc(MBBI.getInstrIterator());
615  }
616
617  /// Possible outcome of a register liveness query to computeRegisterLiveness()
618  enum LivenessQueryResult {
619    LQR_Live,            ///< Register is known to be live.
620    LQR_OverlappingLive, ///< Register itself is not live, but some overlapping
621                         ///< register is.
622    LQR_Dead,            ///< Register is known to be dead.
623    LQR_Unknown          ///< Register liveness not decidable from local
624                         ///< neighborhood.
625  };
626
627  /// computeRegisterLiveness - Return whether (physical) register \c Reg
628  /// has been <def>ined and not <kill>ed as of just before \c MI.
629  ///
630  /// Search is localised to a neighborhood of
631  /// \c Neighborhood instructions before (searching for defs or kills) and
632  /// Neighborhood instructions after (searching just for defs) MI.
633  ///
634  /// \c Reg must be a physical register.
635  LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
636                                              unsigned Reg, MachineInstr *MI,
637                                              unsigned Neighborhood=10);
638
639  // Debugging methods.
640  void dump() const;
641  void print(raw_ostream &OS, SlotIndexes* = nullptr) const;
642
643  // Printing method used by LoopInfo.
644  void printAsOperand(raw_ostream &OS, bool PrintType = true) const;
645
646  /// getNumber - MachineBasicBlocks are uniquely numbered at the function
647  /// level, unless they're not in a MachineFunction yet, in which case this
648  /// will return -1.
649  ///
650  int getNumber() const { return Number; }
651  void setNumber(int N) { Number = N; }
652
653  /// getSymbol - Return the MCSymbol for this basic block.
654  ///
655  MCSymbol *getSymbol() const;
656
657
658private:
659  /// getWeightIterator - Return weight iterator corresponding to the I
660  /// successor iterator.
661  weight_iterator getWeightIterator(succ_iterator I);
662  const_weight_iterator getWeightIterator(const_succ_iterator I) const;
663
664  friend class MachineBranchProbabilityInfo;
665
666  /// getSuccWeight - Return weight of the edge from this block to MBB. This
667  /// method should NOT be called directly, but by using getEdgeWeight method
668  /// from MachineBranchProbabilityInfo class.
669  uint32_t getSuccWeight(const_succ_iterator Succ) const;
670
671
672  // Methods used to maintain doubly linked list of blocks...
673  friend struct ilist_traits<MachineBasicBlock>;
674
675  // Machine-CFG mutators
676
677  /// addPredecessor - Remove pred as a predecessor of this MachineBasicBlock.
678  /// Don't do this unless you know what you're doing, because it doesn't
679  /// update pred's successors list. Use pred->addSuccessor instead.
680  ///
681  void addPredecessor(MachineBasicBlock *pred);
682
683  /// removePredecessor - Remove pred as a predecessor of this
684  /// MachineBasicBlock. Don't do this unless you know what you're
685  /// doing, because it doesn't update pred's successors list. Use
686  /// pred->removeSuccessor instead.
687  ///
688  void removePredecessor(MachineBasicBlock *pred);
689};
690
691raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
692
693// This is useful when building IndexedMaps keyed on basic block pointers.
694struct MBB2NumberFunctor :
695  public std::unary_function<const MachineBasicBlock*, unsigned> {
696  unsigned operator()(const MachineBasicBlock *MBB) const {
697    return MBB->getNumber();
698  }
699};
700
701//===--------------------------------------------------------------------===//
702// GraphTraits specializations for machine basic block graphs (machine-CFGs)
703//===--------------------------------------------------------------------===//
704
705// Provide specializations of GraphTraits to be able to treat a
706// MachineFunction as a graph of MachineBasicBlocks...
707//
708
709template <> struct GraphTraits<MachineBasicBlock *> {
710  typedef MachineBasicBlock NodeType;
711  typedef MachineBasicBlock::succ_iterator ChildIteratorType;
712
713  static NodeType *getEntryNode(MachineBasicBlock *BB) { return BB; }
714  static inline ChildIteratorType child_begin(NodeType *N) {
715    return N->succ_begin();
716  }
717  static inline ChildIteratorType child_end(NodeType *N) {
718    return N->succ_end();
719  }
720};
721
722template <> struct GraphTraits<const MachineBasicBlock *> {
723  typedef const MachineBasicBlock NodeType;
724  typedef MachineBasicBlock::const_succ_iterator ChildIteratorType;
725
726  static NodeType *getEntryNode(const MachineBasicBlock *BB) { return BB; }
727  static inline ChildIteratorType child_begin(NodeType *N) {
728    return N->succ_begin();
729  }
730  static inline ChildIteratorType child_end(NodeType *N) {
731    return N->succ_end();
732  }
733};
734
735// Provide specializations of GraphTraits to be able to treat a
736// MachineFunction as a graph of MachineBasicBlocks... and to walk it
737// in inverse order.  Inverse order for a function is considered
738// to be when traversing the predecessor edges of a MBB
739// instead of the successor edges.
740//
741template <> struct GraphTraits<Inverse<MachineBasicBlock*> > {
742  typedef MachineBasicBlock NodeType;
743  typedef MachineBasicBlock::pred_iterator ChildIteratorType;
744  static NodeType *getEntryNode(Inverse<MachineBasicBlock *> G) {
745    return G.Graph;
746  }
747  static inline ChildIteratorType child_begin(NodeType *N) {
748    return N->pred_begin();
749  }
750  static inline ChildIteratorType child_end(NodeType *N) {
751    return N->pred_end();
752  }
753};
754
755template <> struct GraphTraits<Inverse<const MachineBasicBlock*> > {
756  typedef const MachineBasicBlock NodeType;
757  typedef MachineBasicBlock::const_pred_iterator ChildIteratorType;
758  static NodeType *getEntryNode(Inverse<const MachineBasicBlock*> G) {
759    return G.Graph;
760  }
761  static inline ChildIteratorType child_begin(NodeType *N) {
762    return N->pred_begin();
763  }
764  static inline ChildIteratorType child_end(NodeType *N) {
765    return N->pred_end();
766  }
767};
768
769
770
771/// MachineInstrSpan provides an interface to get an iteration range
772/// containing the instruction it was initialized with, along with all
773/// those instructions inserted prior to or following that instruction
774/// at some point after the MachineInstrSpan is constructed.
775class MachineInstrSpan {
776  MachineBasicBlock &MBB;
777  MachineBasicBlock::iterator I, B, E;
778public:
779  MachineInstrSpan(MachineBasicBlock::iterator I)
780    : MBB(*I->getParent()),
781      I(I),
782      B(I == MBB.begin() ? MBB.end() : std::prev(I)),
783      E(std::next(I)) {}
784
785  MachineBasicBlock::iterator begin() {
786    return B == MBB.end() ? MBB.begin() : std::next(B);
787  }
788  MachineBasicBlock::iterator end() { return E; }
789  bool empty() { return begin() == end(); }
790
791  MachineBasicBlock::iterator getInitial() { return I; }
792};
793
794} // End llvm namespace
795
796#endif
797