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