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