MachineBasicBlock.h revision 224145
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/CodeGen/MachineInstr.h"
18#include "llvm/ADT/GraphTraits.h"
19#include "llvm/Support/DataTypes.h"
20#include <functional>
21
22namespace llvm {
23
24class Pass;
25class BasicBlock;
26class MachineFunction;
27class MCSymbol;
28class SlotIndexes;
29class StringRef;
30class raw_ostream;
31class MachineBranchProbabilityInfo;
32
33template <>
34struct ilist_traits<MachineInstr> : public ilist_default_traits<MachineInstr> {
35private:
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
42public:
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);
58private:
59  void createNode(const MachineInstr &);
60};
61
62class 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
75  /// Weights - Keep track of the weights to the successors. This vector
76  /// has the same order as Successors, or it is empty if we don't use it
77  /// (disable optimization).
78  std::vector<uint32_t> Weights;
79  typedef std::vector<uint32_t>::iterator 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  unsigned Alignment;
88
89  /// IsLandingPad - Indicate that this basic block is entered via an
90  /// exception handler.
91  bool IsLandingPad;
92
93  /// AddressTaken - Indicate that this basic block is potentially the
94  /// target of an indirect branch.
95  bool AddressTaken;
96
97  // Intrusive list support
98  MachineBasicBlock() {}
99
100  explicit MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb);
101
102  ~MachineBasicBlock();
103
104  // MachineBasicBlocks are allocated and owned by MachineFunction.
105  friend class MachineFunction;
106
107public:
108  /// getBasicBlock - Return the LLVM basic block that this instance
109  /// corresponded to originally. Note that this may be NULL if this instance
110  /// does not correspond directly to an LLVM basic block.
111  ///
112  const BasicBlock *getBasicBlock() const { return BB; }
113
114  /// getName - Return the name of the corresponding LLVM basic block, or
115  /// "(null)".
116  StringRef getName() const;
117
118  /// hasAddressTaken - Test whether this block is potentially the target
119  /// of an indirect branch.
120  bool hasAddressTaken() const { return AddressTaken; }
121
122  /// setHasAddressTaken - Set this block to reflect that it potentially
123  /// is the target of an indirect branch.
124  void setHasAddressTaken() { AddressTaken = true; }
125
126  /// getParent - Return the MachineFunction containing this basic block.
127  ///
128  const MachineFunction *getParent() const { return xParent; }
129  MachineFunction *getParent() { return xParent; }
130
131  typedef Instructions::iterator                              iterator;
132  typedef Instructions::const_iterator                  const_iterator;
133  typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
134  typedef std::reverse_iterator<iterator>             reverse_iterator;
135
136  unsigned size() const { return (unsigned)Insts.size(); }
137  bool empty() const { return Insts.empty(); }
138
139  MachineInstr& front() { return Insts.front(); }
140  MachineInstr& back()  { return Insts.back(); }
141  const MachineInstr& front() const { return Insts.front(); }
142  const MachineInstr& back()  const { return Insts.back(); }
143
144  iterator                begin()       { return Insts.begin();  }
145  const_iterator          begin() const { return Insts.begin();  }
146  iterator                  end()       { return Insts.end();    }
147  const_iterator            end() const { return Insts.end();    }
148  reverse_iterator       rbegin()       { return Insts.rbegin(); }
149  const_reverse_iterator rbegin() const { return Insts.rbegin(); }
150  reverse_iterator       rend  ()       { return Insts.rend();   }
151  const_reverse_iterator rend  () const { return Insts.rend();   }
152
153  // Machine-CFG iterators
154  typedef std::vector<MachineBasicBlock *>::iterator       pred_iterator;
155  typedef std::vector<MachineBasicBlock *>::const_iterator const_pred_iterator;
156  typedef std::vector<MachineBasicBlock *>::iterator       succ_iterator;
157  typedef std::vector<MachineBasicBlock *>::const_iterator const_succ_iterator;
158  typedef std::vector<MachineBasicBlock *>::reverse_iterator
159                                                         pred_reverse_iterator;
160  typedef std::vector<MachineBasicBlock *>::const_reverse_iterator
161                                                   const_pred_reverse_iterator;
162  typedef std::vector<MachineBasicBlock *>::reverse_iterator
163                                                         succ_reverse_iterator;
164  typedef std::vector<MachineBasicBlock *>::const_reverse_iterator
165                                                   const_succ_reverse_iterator;
166
167  pred_iterator        pred_begin()       { return Predecessors.begin(); }
168  const_pred_iterator  pred_begin() const { return Predecessors.begin(); }
169  pred_iterator        pred_end()         { return Predecessors.end();   }
170  const_pred_iterator  pred_end()   const { return Predecessors.end();   }
171  pred_reverse_iterator        pred_rbegin()
172                                          { return Predecessors.rbegin();}
173  const_pred_reverse_iterator  pred_rbegin() const
174                                          { return Predecessors.rbegin();}
175  pred_reverse_iterator        pred_rend()
176                                          { return Predecessors.rend();  }
177  const_pred_reverse_iterator  pred_rend()   const
178                                          { return Predecessors.rend();  }
179  unsigned             pred_size()  const {
180    return (unsigned)Predecessors.size();
181  }
182  bool                 pred_empty() const { return Predecessors.empty(); }
183  succ_iterator        succ_begin()       { return Successors.begin();   }
184  const_succ_iterator  succ_begin() const { return Successors.begin();   }
185  succ_iterator        succ_end()         { return Successors.end();     }
186  const_succ_iterator  succ_end()   const { return Successors.end();     }
187  succ_reverse_iterator        succ_rbegin()
188                                          { return Successors.rbegin();  }
189  const_succ_reverse_iterator  succ_rbegin() const
190                                          { return Successors.rbegin();  }
191  succ_reverse_iterator        succ_rend()
192                                          { return Successors.rend();    }
193  const_succ_reverse_iterator  succ_rend()   const
194                                          { return Successors.rend();    }
195  unsigned             succ_size()  const {
196    return (unsigned)Successors.size();
197  }
198  bool                 succ_empty() const { return Successors.empty();   }
199
200  // LiveIn management methods.
201
202  /// addLiveIn - Add the specified register as a live in.  Note that it
203  /// is an error to add the same register to the same set more than once.
204  void addLiveIn(unsigned Reg)  { LiveIns.push_back(Reg); }
205
206  /// removeLiveIn - Remove the specified register from the live in set.
207  ///
208  void removeLiveIn(unsigned Reg);
209
210  /// isLiveIn - Return true if the specified register is in the live in set.
211  ///
212  bool isLiveIn(unsigned Reg) const;
213
214  // Iteration support for live in sets.  These sets are kept in sorted
215  // order by their register number.
216  typedef std::vector<unsigned>::const_iterator livein_iterator;
217  livein_iterator livein_begin() const { return LiveIns.begin(); }
218  livein_iterator livein_end()   const { return LiveIns.end(); }
219  bool            livein_empty() const { return LiveIns.empty(); }
220
221  /// getAlignment - Return alignment of the basic block.
222  ///
223  unsigned getAlignment() const { return Alignment; }
224
225  /// setAlignment - Set alignment of the basic block.
226  ///
227  void setAlignment(unsigned Align) { Alignment = Align; }
228
229  /// isLandingPad - Returns true if the block is a landing pad. That is
230  /// this basic block is entered via an exception handler.
231  bool isLandingPad() const { return IsLandingPad; }
232
233  /// setIsLandingPad - Indicates the block is a landing pad.  That is
234  /// this basic block is entered via an exception handler.
235  void setIsLandingPad() { IsLandingPad = true; }
236
237  /// getLandingPadSuccessor - If this block has a successor that is a landing
238  /// pad, return it. Otherwise return NULL.
239  const MachineBasicBlock *getLandingPadSuccessor() const;
240
241  // Code Layout methods.
242
243  /// moveBefore/moveAfter - move 'this' block before or after the specified
244  /// block.  This only moves the block, it does not modify the CFG or adjust
245  /// potential fall-throughs at the end of the block.
246  void moveBefore(MachineBasicBlock *NewAfter);
247  void moveAfter(MachineBasicBlock *NewBefore);
248
249  /// updateTerminator - Update the terminator instructions in block to account
250  /// for changes to the layout. If the block previously used a fallthrough,
251  /// it may now need a branch, and if it previously used branching it may now
252  /// be able to use a fallthrough.
253  void updateTerminator();
254
255  // Machine-CFG mutators
256
257  /// addSuccessor - Add succ as a successor of this MachineBasicBlock.
258  /// The Predecessors list of succ is automatically updated. WEIGHT
259  /// parameter is stored in Weights list and it may be used by
260  /// MachineBranchProbabilityInfo analysis to calculate branch probability.
261  ///
262  void addSuccessor(MachineBasicBlock *succ, uint32_t weight = 0);
263
264  /// removeSuccessor - Remove successor from the successors list of this
265  /// MachineBasicBlock. The Predecessors list of succ is automatically updated.
266  ///
267  void removeSuccessor(MachineBasicBlock *succ);
268
269  /// removeSuccessor - Remove specified successor from the successors list of
270  /// this MachineBasicBlock. The Predecessors list of succ is automatically
271  /// updated.  Return the iterator to the element after the one removed.
272  ///
273  succ_iterator removeSuccessor(succ_iterator I);
274
275  /// replaceSuccessor - Replace successor OLD with NEW and update weight info.
276  ///
277  void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
278
279
280  /// transferSuccessors - Transfers all the successors from MBB to this
281  /// machine basic block (i.e., copies all the successors fromMBB and
282  /// remove all the successors from fromMBB).
283  void transferSuccessors(MachineBasicBlock *fromMBB);
284
285  /// transferSuccessorsAndUpdatePHIs - Transfers all the successors, as
286  /// in transferSuccessors, and update PHI operands in the successor blocks
287  /// which refer to fromMBB to refer to this.
288  void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB);
289
290  /// isSuccessor - Return true if the specified MBB is a successor of this
291  /// block.
292  bool isSuccessor(const MachineBasicBlock *MBB) const;
293
294  /// isLayoutSuccessor - Return true if the specified MBB will be emitted
295  /// immediately after this block, such that if this block exits by
296  /// falling through, control will transfer to the specified MBB. Note
297  /// that MBB need not be a successor at all, for example if this block
298  /// ends with an unconditional branch to some other block.
299  bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
300
301  /// canFallThrough - Return true if the block can implicitly transfer
302  /// control to the block after it by falling off the end of it.  This should
303  /// return false if it can reach the block after it, but it uses an explicit
304  /// branch to do so (e.g., a table jump).  True is a conservative answer.
305  bool canFallThrough();
306
307  /// Returns a pointer to the first instructon in this block that is not a
308  /// PHINode instruction. When adding instruction to the beginning of the
309  /// basic block, they should be added before the returned value, not before
310  /// the first instruction, which might be PHI.
311  /// Returns end() is there's no non-PHI instruction.
312  iterator getFirstNonPHI();
313
314  /// SkipPHIsAndLabels - Return the first instruction in MBB after I that is
315  /// not a PHI or a label. This is the correct point to insert copies at the
316  /// beginning of a basic block.
317  iterator SkipPHIsAndLabels(iterator I);
318
319  /// getFirstTerminator - returns an iterator to the first terminator
320  /// instruction of this basic block. If a terminator does not exist,
321  /// it returns end()
322  iterator getFirstTerminator();
323
324  const_iterator getFirstTerminator() const {
325    return const_cast<MachineBasicBlock*>(this)->getFirstTerminator();
326  }
327
328  /// getLastNonDebugInstr - returns an iterator to the last non-debug
329  /// instruction in the basic block, or end()
330  iterator getLastNonDebugInstr();
331
332  const_iterator getLastNonDebugInstr() const {
333    return const_cast<MachineBasicBlock*>(this)->getLastNonDebugInstr();
334  }
335
336  /// SplitCriticalEdge - Split the critical edge from this block to the
337  /// given successor block, and return the newly created block, or null
338  /// if splitting is not possible.
339  ///
340  /// This function updates LiveVariables, MachineDominatorTree, and
341  /// MachineLoopInfo, as applicable.
342  MachineBasicBlock *SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P);
343
344  void pop_front() { Insts.pop_front(); }
345  void pop_back() { Insts.pop_back(); }
346  void push_back(MachineInstr *MI) { Insts.push_back(MI); }
347  template<typename IT>
348  void insert(iterator I, IT S, IT E) { Insts.insert(I, S, E); }
349  iterator insert(iterator I, MachineInstr *M) { return Insts.insert(I, M); }
350  iterator insertAfter(iterator I, MachineInstr *M) {
351    return Insts.insertAfter(I, M);
352  }
353
354  // erase - Remove the specified element or range from the instruction list.
355  // These functions delete any instructions removed.
356  //
357  iterator erase(iterator I)             { return Insts.erase(I); }
358  iterator erase(iterator I, iterator E) { return Insts.erase(I, E); }
359  MachineInstr *remove(MachineInstr *I)  { return Insts.remove(I); }
360  void clear()                           { Insts.clear(); }
361
362  /// splice - Take an instruction from MBB 'Other' at the position From,
363  /// and insert it into this MBB right before 'where'.
364  void splice(iterator where, MachineBasicBlock *Other, iterator From) {
365    Insts.splice(where, Other->Insts, From);
366  }
367
368  /// splice - Take a block of instructions from MBB 'Other' in the range [From,
369  /// To), and insert them into this MBB right before 'where'.
370  void splice(iterator where, MachineBasicBlock *Other, iterator From,
371              iterator To) {
372    Insts.splice(where, Other->Insts, From, To);
373  }
374
375  /// removeFromParent - This method unlinks 'this' from the containing
376  /// function, and returns it, but does not delete it.
377  MachineBasicBlock *removeFromParent();
378
379  /// eraseFromParent - This method unlinks 'this' from the containing
380  /// function and deletes it.
381  void eraseFromParent();
382
383  /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
384  /// 'Old', change the code and CFG so that it branches to 'New' instead.
385  void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
386
387  /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in
388  /// the CFG to be inserted.  If we have proven that MBB can only branch to
389  /// DestA and DestB, remove any other MBB successors from the CFG. DestA and
390  /// DestB can be null. Besides DestA and DestB, retain other edges leading
391  /// to LandingPads (currently there can be only one; we don't check or require
392  /// that here). Note it is possible that DestA and/or DestB are LandingPads.
393  bool CorrectExtraCFGEdges(MachineBasicBlock *DestA,
394                            MachineBasicBlock *DestB,
395                            bool isCond);
396
397  /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
398  /// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
399  DebugLoc findDebugLoc(MachineBasicBlock::iterator &MBBI);
400
401  // Debugging methods.
402  void dump() const;
403  void print(raw_ostream &OS, SlotIndexes* = 0) const;
404
405  /// getNumber - MachineBasicBlocks are uniquely numbered at the function
406  /// level, unless they're not in a MachineFunction yet, in which case this
407  /// will return -1.
408  ///
409  int getNumber() const { return Number; }
410  void setNumber(int N) { Number = N; }
411
412  /// getSymbol - Return the MCSymbol for this basic block.
413  ///
414  MCSymbol *getSymbol() const;
415
416
417private:
418  /// getWeightIterator - Return weight iterator corresponding to the I
419  /// successor iterator.
420  weight_iterator getWeightIterator(succ_iterator I);
421
422  friend class MachineBranchProbabilityInfo;
423
424  /// getSuccWeight - Return weight of the edge from this block to MBB. This
425  /// method should NOT be called directly, but by using getEdgeWeight method
426  /// from MachineBranchProbabilityInfo class.
427  uint32_t getSuccWeight(MachineBasicBlock *succ);
428
429
430  // Methods used to maintain doubly linked list of blocks...
431  friend struct ilist_traits<MachineBasicBlock>;
432
433  // Machine-CFG mutators
434
435  /// addPredecessor - Remove pred as a predecessor of this MachineBasicBlock.
436  /// Don't do this unless you know what you're doing, because it doesn't
437  /// update pred's successors list. Use pred->addSuccessor instead.
438  ///
439  void addPredecessor(MachineBasicBlock *pred);
440
441  /// removePredecessor - Remove pred as a predecessor of this
442  /// MachineBasicBlock. Don't do this unless you know what you're
443  /// doing, because it doesn't update pred's successors list. Use
444  /// pred->removeSuccessor instead.
445  ///
446  void removePredecessor(MachineBasicBlock *pred);
447};
448
449raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
450
451void WriteAsOperand(raw_ostream &, const MachineBasicBlock*, bool t);
452
453// This is useful when building IndexedMaps keyed on basic block pointers.
454struct MBB2NumberFunctor :
455  public std::unary_function<const MachineBasicBlock*, unsigned> {
456  unsigned operator()(const MachineBasicBlock *MBB) const {
457    return MBB->getNumber();
458  }
459};
460
461//===--------------------------------------------------------------------===//
462// GraphTraits specializations for machine basic block graphs (machine-CFGs)
463//===--------------------------------------------------------------------===//
464
465// Provide specializations of GraphTraits to be able to treat a
466// MachineFunction as a graph of MachineBasicBlocks...
467//
468
469template <> struct GraphTraits<MachineBasicBlock *> {
470  typedef MachineBasicBlock NodeType;
471  typedef MachineBasicBlock::succ_iterator ChildIteratorType;
472
473  static NodeType *getEntryNode(MachineBasicBlock *BB) { return BB; }
474  static inline ChildIteratorType child_begin(NodeType *N) {
475    return N->succ_begin();
476  }
477  static inline ChildIteratorType child_end(NodeType *N) {
478    return N->succ_end();
479  }
480};
481
482template <> struct GraphTraits<const MachineBasicBlock *> {
483  typedef const MachineBasicBlock NodeType;
484  typedef MachineBasicBlock::const_succ_iterator ChildIteratorType;
485
486  static NodeType *getEntryNode(const MachineBasicBlock *BB) { return BB; }
487  static inline ChildIteratorType child_begin(NodeType *N) {
488    return N->succ_begin();
489  }
490  static inline ChildIteratorType child_end(NodeType *N) {
491    return N->succ_end();
492  }
493};
494
495// Provide specializations of GraphTraits to be able to treat a
496// MachineFunction as a graph of MachineBasicBlocks... and to walk it
497// in inverse order.  Inverse order for a function is considered
498// to be when traversing the predecessor edges of a MBB
499// instead of the successor edges.
500//
501template <> struct GraphTraits<Inverse<MachineBasicBlock*> > {
502  typedef MachineBasicBlock NodeType;
503  typedef MachineBasicBlock::pred_iterator ChildIteratorType;
504  static NodeType *getEntryNode(Inverse<MachineBasicBlock *> G) {
505    return G.Graph;
506  }
507  static inline ChildIteratorType child_begin(NodeType *N) {
508    return N->pred_begin();
509  }
510  static inline ChildIteratorType child_end(NodeType *N) {
511    return N->pred_end();
512  }
513};
514
515template <> struct GraphTraits<Inverse<const MachineBasicBlock*> > {
516  typedef const MachineBasicBlock NodeType;
517  typedef MachineBasicBlock::const_pred_iterator ChildIteratorType;
518  static NodeType *getEntryNode(Inverse<const MachineBasicBlock*> G) {
519    return G.Graph;
520  }
521  static inline ChildIteratorType child_begin(NodeType *N) {
522    return N->pred_begin();
523  }
524  static inline ChildIteratorType child_end(NodeType *N) {
525    return N->pred_end();
526  }
527};
528
529} // End llvm namespace
530
531#endif
532