Revert r244154 which causes some build failure. See https://llvm.org/bugs/show_bug...
[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 MIRPrinter;
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
340   /// Return alignment of the basic block. The alignment is specified as
341   /// log2(bytes).
342   unsigned getAlignment() const { return Alignment; }
343
344   /// Set alignment of the basic block. The alignment is specified as
345   /// log2(bytes).
346   void setAlignment(unsigned Align) { Alignment = Align; }
347
348   /// Returns true if the block is a landing pad. That is this basic block is
349   /// entered via an exception handler.
350   bool isLandingPad() const { return IsLandingPad; }
351
352   /// Indicates the block is a landing pad.  That is this basic block is entered
353   /// via an exception handler.
354   void setIsLandingPad(bool V = true) { IsLandingPad = V; }
355
356   /// If this block has a successor that is a landing pad, return it. Otherwise
357   /// return NULL.
358   const MachineBasicBlock *getLandingPadSuccessor() const;
359
360   // Code Layout methods.
361
362   /// Move 'this' block before or after the specified block.  This only moves
363   /// the block, it does not modify the CFG or adjust potential fall-throughs at
364   /// the end of the block.
365   void moveBefore(MachineBasicBlock *NewAfter);
366   void moveAfter(MachineBasicBlock *NewBefore);
367
368   /// Update the terminator instructions in block to account for changes to the
369   /// layout. If the block previously used a fallthrough, it may now need a
370   /// branch, and if it previously used branching it may now be able to use a
371   /// fallthrough.
372   void updateTerminator();
373
374   // Machine-CFG mutators
375
376   /// Add succ as a successor of this MachineBasicBlock.  The Predecessors list
377   /// of succ is automatically updated. WEIGHT parameter is stored in Weights
378   /// list and it may be used by MachineBranchProbabilityInfo analysis to
379   /// calculate branch probability.
380   ///
381   /// Note that duplicate Machine CFG edges are not allowed.
382   void addSuccessor(MachineBasicBlock *succ, uint32_t weight = 0);
383
384   /// Set successor weight of a given iterator.
385   void setSuccWeight(succ_iterator I, uint32_t weight);
386
387   /// Remove successor from the successors list of this MachineBasicBlock. The
388   /// Predecessors list of succ is automatically updated.
389   void removeSuccessor(MachineBasicBlock *succ);
390
391   /// Remove specified successor from the successors list of this
392   /// MachineBasicBlock. The Predecessors list of succ is automatically updated.
393   /// Return the iterator to the element after the one removed.
394   succ_iterator removeSuccessor(succ_iterator I);
395
396   /// Replace successor OLD with NEW and update weight info.
397   void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
398
399   /// Transfers all the successors from MBB to this machine basic block (i.e.,
400   /// copies all the successors fromMBB and remove all the successors from
401   /// fromMBB).
402   void transferSuccessors(MachineBasicBlock *fromMBB);
403
404   /// Transfers all the successors, as in transferSuccessors, and update PHI
405   /// operands in the successor blocks which refer to fromMBB to refer to this.
406   void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB);
407
408   /// Return true if any of the successors have weights attached to them.
409   bool hasSuccessorWeights() const { return !Weights.empty(); }
410
411   /// Return true if the specified MBB is a predecessor of this block.
412   bool isPredecessor(const MachineBasicBlock *MBB) const;
413
414   /// Return true if the specified MBB is a successor of this block.
415   bool isSuccessor(const MachineBasicBlock *MBB) const;
416
417   /// Return true if the specified MBB will be emitted immediately after this
418   /// block, such that if this block exits by falling through, control will
419   /// transfer to the specified MBB. Note that MBB need not be a successor at
420   /// all, for example if this block ends with an unconditional branch to some
421   /// other block.
422   bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
423
424   /// Return true if the block can implicitly transfer control to the block
425   /// after it by falling off the end of it.  This should return false if it can
426   /// reach the block after it, but it uses an explicit branch to do so (e.g., a
427   /// table jump).  True is a conservative answer.
428   bool canFallThrough();
429
430   /// Returns a pointer to the first instruction in this block that is not a
431   /// PHINode instruction. When adding instructions to the beginning of the
432   /// basic block, they should be added before the returned value, not before
433   /// the first instruction, which might be PHI.
434   /// Returns end() is there's no non-PHI instruction.
435   iterator getFirstNonPHI();
436
437   /// Return the first instruction in MBB after I that is not a PHI or a label.
438   /// This is the correct point to insert copies at the beginning of a basic
439   /// block.
440   iterator SkipPHIsAndLabels(iterator I);
441
442   /// Returns an iterator to the first terminator instruction of this basic
443   /// block. If a terminator does not exist, it returns end().
444   iterator getFirstTerminator();
445   const_iterator getFirstTerminator() const {
446     return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
447   }
448
449   /// Same getFirstTerminator but it ignores bundles and return an
450   /// instr_iterator instead.
451   instr_iterator getFirstInstrTerminator();
452
453   /// Returns an iterator to the first non-debug instruction in the basic block,
454   /// or end().
455   iterator getFirstNonDebugInstr();
456   const_iterator getFirstNonDebugInstr() const {
457     return const_cast<MachineBasicBlock *>(this)->getFirstNonDebugInstr();
458   }
459
460   /// Returns an iterator to the last non-debug instruction in the basic block,
461   /// or end().
462   iterator getLastNonDebugInstr();
463   const_iterator getLastNonDebugInstr() const {
464     return const_cast<MachineBasicBlock *>(this)->getLastNonDebugInstr();
465   }
466
467   /// Split the critical edge from this block to the given successor block, and
468   /// return the newly created block, or null 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   /// This method unlinks 'this' from the containing function, and returns it,
589   /// but does not delete it.
590   MachineBasicBlock *removeFromParent();
591
592   /// This method unlinks 'this' from the containing function and deletes it.
593   void eraseFromParent();
594
595   /// Given a machine basic block that branched to 'Old', change the code and
596   /// CFG so that it branches to 'New' instead.
597   void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
598
599   /// Various pieces of code can cause excess edges in the CFG to be inserted.
600   /// If we have proven that MBB can only branch to DestA and DestB, remove any
601   /// other MBB successors from the CFG. DestA and DestB can be null. Besides
602   /// DestA and DestB, retain other edges leading to LandingPads (currently
603   /// there can be only one; we don't check or require that here). Note it is
604   /// possible that DestA and/or DestB are LandingPads.
605   bool CorrectExtraCFGEdges(MachineBasicBlock *DestA,
606                             MachineBasicBlock *DestB,
607                             bool isCond);
608
609   /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
610   /// instructions.  Return UnknownLoc if there is none.
611   DebugLoc findDebugLoc(instr_iterator MBBI);
612   DebugLoc findDebugLoc(iterator MBBI) {
613     return findDebugLoc(MBBI.getInstrIterator());
614   }
615
616   /// Possible outcome of a register liveness query to computeRegisterLiveness()
617   enum LivenessQueryResult {
618     LQR_Live,            ///< Register is known to be live.
619     LQR_OverlappingLive, ///< Register itself is not live, but some overlapping
620                          ///< register is.
621     LQR_Dead,            ///< Register is known to be dead.
622     LQR_Unknown          ///< Register liveness not decidable from local
623                          ///< neighborhood.
624   };
625
626   /// Return whether (physical) register \p Reg has been <def>ined and not
627   /// <kill>ed as of just before \p Before.
628   ///
629   /// Search is localised to a neighborhood of \p Neighborhood instructions
630   /// before (searching for defs or kills) and \p Neighborhood instructions
631   /// after (searching just for defs) \p Before.
632   ///
633   /// \p Reg must be a physical register.
634   LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
635                                               unsigned Reg,
636                                               const_iterator Before,
637                                               unsigned Neighborhood=10) const;
638
639   // Debugging methods.
640   void dump() const;
641   void print(raw_ostream &OS, SlotIndexes* = nullptr) const;
642   void print(raw_ostream &OS, ModuleSlotTracker &MST,
643              SlotIndexes * = nullptr) const;
644
645   // Printing method used by LoopInfo.
646   void printAsOperand(raw_ostream &OS, bool PrintType = true) const;
647
648   /// MachineBasicBlocks are uniquely numbered at the function level, unless
649   /// they're not in a MachineFunction yet, in which case this will return -1.
650   int getNumber() const { return Number; }
651   void setNumber(int N) { Number = N; }
652
653   /// Return the MCSymbol for this basic block.
654   MCSymbol *getSymbol() const;
655
656
657 private:
658   /// Return weight iterator corresponding to the I successor iterator.
659   weight_iterator getWeightIterator(succ_iterator I);
660   const_weight_iterator getWeightIterator(const_succ_iterator I) const;
661
662   friend class MachineBranchProbabilityInfo;
663   friend class MIRPrinter;
664
665   /// Return weight of the edge from this block to MBB. This method should NOT
666   /// be called directly, but by using getEdgeWeight method from
667   /// MachineBranchProbabilityInfo class.
668   uint32_t getSuccWeight(const_succ_iterator Succ) const;
669
670
671   // Methods used to maintain doubly linked list of blocks...
672   friend struct ilist_traits<MachineBasicBlock>;
673
674   // Machine-CFG mutators
675
676   /// Remove pred as a predecessor of this MachineBasicBlock. Don't do this
677   /// unless you know what you're doing, because it doesn't update pred's
678   /// successors list. Use pred->addSuccessor instead.
679   void addPredecessor(MachineBasicBlock *pred);
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->removeSuccessor instead.
684   void removePredecessor(MachineBasicBlock *pred);
685 };
686
687 raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
688
689 // This is useful when building IndexedMaps keyed on basic block pointers.
690 struct MBB2NumberFunctor :
691   public std::unary_function<const MachineBasicBlock*, unsigned> {
692   unsigned operator()(const MachineBasicBlock *MBB) const {
693     return MBB->getNumber();
694   }
695 };
696
697 //===--------------------------------------------------------------------===//
698 // GraphTraits specializations for machine basic block graphs (machine-CFGs)
699 //===--------------------------------------------------------------------===//
700
701 // Provide specializations of GraphTraits to be able to treat a
702 // MachineFunction as a graph of MachineBasicBlocks.
703 //
704
705 template <> struct GraphTraits<MachineBasicBlock *> {
706   typedef MachineBasicBlock NodeType;
707   typedef MachineBasicBlock::succ_iterator ChildIteratorType;
708
709   static NodeType *getEntryNode(MachineBasicBlock *BB) { return BB; }
710   static inline ChildIteratorType child_begin(NodeType *N) {
711     return N->succ_begin();
712   }
713   static inline ChildIteratorType child_end(NodeType *N) {
714     return N->succ_end();
715   }
716 };
717
718 template <> struct GraphTraits<const MachineBasicBlock *> {
719   typedef const MachineBasicBlock NodeType;
720   typedef MachineBasicBlock::const_succ_iterator ChildIteratorType;
721
722   static NodeType *getEntryNode(const MachineBasicBlock *BB) { return BB; }
723   static inline ChildIteratorType child_begin(NodeType *N) {
724     return N->succ_begin();
725   }
726   static inline ChildIteratorType child_end(NodeType *N) {
727     return N->succ_end();
728   }
729 };
730
731 // Provide specializations of GraphTraits to be able to treat a
732 // MachineFunction as a graph of MachineBasicBlocks and to walk it
733 // in inverse order.  Inverse order for a function is considered
734 // to be when traversing the predecessor edges of a MBB
735 // instead of the successor edges.
736 //
737 template <> struct GraphTraits<Inverse<MachineBasicBlock*> > {
738   typedef MachineBasicBlock NodeType;
739   typedef MachineBasicBlock::pred_iterator ChildIteratorType;
740   static NodeType *getEntryNode(Inverse<MachineBasicBlock *> G) {
741     return G.Graph;
742   }
743   static inline ChildIteratorType child_begin(NodeType *N) {
744     return N->pred_begin();
745   }
746   static inline ChildIteratorType child_end(NodeType *N) {
747     return N->pred_end();
748   }
749 };
750
751 template <> struct GraphTraits<Inverse<const MachineBasicBlock*> > {
752   typedef const MachineBasicBlock NodeType;
753   typedef MachineBasicBlock::const_pred_iterator ChildIteratorType;
754   static NodeType *getEntryNode(Inverse<const MachineBasicBlock*> G) {
755     return G.Graph;
756   }
757   static inline ChildIteratorType child_begin(NodeType *N) {
758     return N->pred_begin();
759   }
760   static inline ChildIteratorType child_end(NodeType *N) {
761     return N->pred_end();
762   }
763 };
764
765
766
767 /// MachineInstrSpan provides an interface to get an iteration range
768 /// containing the instruction it was initialized with, along with all
769 /// those instructions inserted prior to or following that instruction
770 /// at some point after the MachineInstrSpan is constructed.
771 class MachineInstrSpan {
772   MachineBasicBlock &MBB;
773   MachineBasicBlock::iterator I, B, E;
774 public:
775   MachineInstrSpan(MachineBasicBlock::iterator I)
776     : MBB(*I->getParent()),
777       I(I),
778       B(I == MBB.begin() ? MBB.end() : std::prev(I)),
779       E(std::next(I)) {}
780
781   MachineBasicBlock::iterator begin() {
782     return B == MBB.end() ? MBB.begin() : std::next(B);
783   }
784   MachineBasicBlock::iterator end() { return E; }
785   bool empty() { return begin() == end(); }
786
787   MachineBasicBlock::iterator getInitial() { return I; }
788 };
789
790 } // End llvm namespace
791
792 #endif