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