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