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