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