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