blob: 2bad64c6cc2ee138f0c4e3ea609751ae60b66834 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- llvm/CodeGen/MachineBasicBlock.h -------------------------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
7//===----------------------------------------------------------------------===//
8//
9// Collect the sequence of machine instructions for a basic block.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CODEGEN_MACHINEBASICBLOCK_H
14#define LLVM_CODEGEN_MACHINEBASICBLOCK_H
15
16#include "llvm/ADT/GraphTraits.h"
17#include "llvm/ADT/ilist.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010018#include "llvm/ADT/iterator_range.h"
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020019#include "llvm/ADT/SparseBitVector.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010020#include "llvm/CodeGen/MachineInstr.h"
21#include "llvm/CodeGen/MachineInstrBundleIterator.h"
22#include "llvm/IR/DebugLoc.h"
23#include "llvm/MC/LaneBitmask.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010024#include "llvm/Support/BranchProbability.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010025#include <cassert>
26#include <cstdint>
27#include <functional>
28#include <iterator>
29#include <string>
30#include <vector>
31
32namespace llvm {
33
34class BasicBlock;
35class MachineFunction;
36class MCSymbol;
37class ModuleSlotTracker;
38class Pass;
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020039class Printable;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010040class SlotIndexes;
41class StringRef;
42class raw_ostream;
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020043class LiveIntervals;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010044class TargetRegisterClass;
45class TargetRegisterInfo;
46
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020047// This structure uniquely identifies a basic block section.
48// Possible values are
49// {Type: Default, Number: (unsigned)} (These are regular section IDs)
50// {Type: Exception, Number: 0} (ExceptionSectionID)
51// {Type: Cold, Number: 0} (ColdSectionID)
52struct MBBSectionID {
53 enum SectionType {
54 Default = 0, // Regular section (these sections are distinguished by the
55 // Number field).
56 Exception, // Special section type for exception handling blocks
57 Cold, // Special section type for cold blocks
58 } Type;
59 unsigned Number;
60
61 MBBSectionID(unsigned N) : Type(Default), Number(N) {}
62
63 // Special unique sections for cold and exception blocks.
64 const static MBBSectionID ColdSectionID;
65 const static MBBSectionID ExceptionSectionID;
66
67 bool operator==(const MBBSectionID &Other) const {
68 return Type == Other.Type && Number == Other.Number;
69 }
70
71 bool operator!=(const MBBSectionID &Other) const { return !(*this == Other); }
72
73private:
74 // This is only used to construct the special cold and exception sections.
75 MBBSectionID(SectionType T) : Type(T), Number(0) {}
76};
77
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010078template <> struct ilist_traits<MachineInstr> {
79private:
80 friend class MachineBasicBlock; // Set by the owning MachineBasicBlock.
81
82 MachineBasicBlock *Parent;
83
84 using instr_iterator =
85 simple_ilist<MachineInstr, ilist_sentinel_tracking<true>>::iterator;
86
87public:
88 void addNodeToList(MachineInstr *N);
89 void removeNodeFromList(MachineInstr *N);
Andrew Scullcdfcccc2018-10-05 20:58:37 +010090 void transferNodesFromList(ilist_traits &FromList, instr_iterator First,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010091 instr_iterator Last);
92 void deleteNode(MachineInstr *MI);
93};
94
95class MachineBasicBlock
96 : public ilist_node_with_parent<MachineBasicBlock, MachineFunction> {
97public:
98 /// Pair of physical register and lane mask.
99 /// This is not simply a std::pair typedef because the members should be named
100 /// clearly as they both have an integer type.
101 struct RegisterMaskPair {
102 public:
103 MCPhysReg PhysReg;
104 LaneBitmask LaneMask;
105
106 RegisterMaskPair(MCPhysReg PhysReg, LaneBitmask LaneMask)
107 : PhysReg(PhysReg), LaneMask(LaneMask) {}
108 };
109
110private:
111 using Instructions = ilist<MachineInstr, ilist_sentinel_tracking<true>>;
112
113 Instructions Insts;
114 const BasicBlock *BB;
115 int Number;
116 MachineFunction *xParent;
117
118 /// Keep track of the predecessor / successor basic blocks.
119 std::vector<MachineBasicBlock *> Predecessors;
120 std::vector<MachineBasicBlock *> Successors;
121
122 /// Keep track of the probabilities to the successors. This vector has the
123 /// same order as Successors, or it is empty if we don't use it (disable
124 /// optimization).
125 std::vector<BranchProbability> Probs;
126 using probability_iterator = std::vector<BranchProbability>::iterator;
127 using const_probability_iterator =
128 std::vector<BranchProbability>::const_iterator;
129
130 Optional<uint64_t> IrrLoopHeaderWeight;
131
132 /// Keep track of the physical registers that are livein of the basicblock.
133 using LiveInVector = std::vector<RegisterMaskPair>;
134 LiveInVector LiveIns;
135
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200136 /// Alignment of the basic block. One if the basic block does not need to be
137 /// aligned.
138 Align Alignment;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100139
140 /// Indicate that this basic block is entered via an exception handler.
141 bool IsEHPad = false;
142
143 /// Indicate that this basic block is potentially the target of an indirect
144 /// branch.
145 bool AddressTaken = false;
146
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100147 /// Indicate that this basic block needs its symbol be emitted regardless of
148 /// whether the flow just falls-through to it.
149 bool LabelMustBeEmitted = false;
150
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100151 /// Indicate that this basic block is the entry block of an EH scope, i.e.,
152 /// the block that used to have a catchpad or cleanuppad instruction in the
153 /// LLVM IR.
154 bool IsEHScopeEntry = false;
155
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100156 /// Indicate that this basic block is the entry block of an EH funclet.
157 bool IsEHFuncletEntry = false;
158
159 /// Indicate that this basic block is the entry block of a cleanup funclet.
160 bool IsCleanupFuncletEntry = false;
161
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200162 /// With basic block sections, this stores the Section ID of the basic block.
163 MBBSectionID SectionID{0};
164
165 // Indicate that this basic block begins a section.
166 bool IsBeginSection = false;
167
168 // Indicate that this basic block ends a section.
169 bool IsEndSection = false;
170
171 /// Indicate that this basic block is the indirect dest of an INLINEASM_BR.
172 bool IsInlineAsmBrIndirectTarget = false;
173
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100174 /// since getSymbol is a relatively heavy-weight operation, the symbol
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100175 /// is only computed once and is cached.
176 mutable MCSymbol *CachedMCSymbol = nullptr;
177
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200178 /// Marks the end of the basic block. Used during basic block sections to
179 /// calculate the size of the basic block, or the BB section ending with it.
180 mutable MCSymbol *CachedEndMCSymbol = nullptr;
181
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100182 // Intrusive list support
183 MachineBasicBlock() = default;
184
185 explicit MachineBasicBlock(MachineFunction &MF, const BasicBlock *BB);
186
187 ~MachineBasicBlock();
188
189 // MachineBasicBlocks are allocated and owned by MachineFunction.
190 friend class MachineFunction;
191
192public:
193 /// Return the LLVM basic block that this instance corresponded to originally.
194 /// Note that this may be NULL if this instance does not correspond directly
195 /// to an LLVM basic block.
196 const BasicBlock *getBasicBlock() const { return BB; }
197
198 /// Return the name of the corresponding LLVM basic block, or an empty string.
199 StringRef getName() const;
200
201 /// Return a formatted string to identify this block and its parent function.
202 std::string getFullName() const;
203
204 /// Test whether this block is potentially the target of an indirect branch.
205 bool hasAddressTaken() const { return AddressTaken; }
206
207 /// Set this block to reflect that it potentially is the target of an indirect
208 /// branch.
209 void setHasAddressTaken() { AddressTaken = true; }
210
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100211 /// Test whether this block must have its label emitted.
212 bool hasLabelMustBeEmitted() const { return LabelMustBeEmitted; }
213
214 /// Set this block to reflect that, regardless how we flow to it, we need
215 /// its label be emitted.
216 void setLabelMustBeEmitted() { LabelMustBeEmitted = true; }
217
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100218 /// Return the MachineFunction containing this basic block.
219 const MachineFunction *getParent() const { return xParent; }
220 MachineFunction *getParent() { return xParent; }
221
222 using instr_iterator = Instructions::iterator;
223 using const_instr_iterator = Instructions::const_iterator;
224 using reverse_instr_iterator = Instructions::reverse_iterator;
225 using const_reverse_instr_iterator = Instructions::const_reverse_iterator;
226
227 using iterator = MachineInstrBundleIterator<MachineInstr>;
228 using const_iterator = MachineInstrBundleIterator<const MachineInstr>;
229 using reverse_iterator = MachineInstrBundleIterator<MachineInstr, true>;
230 using const_reverse_iterator =
231 MachineInstrBundleIterator<const MachineInstr, true>;
232
233 unsigned size() const { return (unsigned)Insts.size(); }
234 bool empty() const { return Insts.empty(); }
235
236 MachineInstr &instr_front() { return Insts.front(); }
237 MachineInstr &instr_back() { return Insts.back(); }
238 const MachineInstr &instr_front() const { return Insts.front(); }
239 const MachineInstr &instr_back() const { return Insts.back(); }
240
241 MachineInstr &front() { return Insts.front(); }
242 MachineInstr &back() { return *--end(); }
243 const MachineInstr &front() const { return Insts.front(); }
244 const MachineInstr &back() const { return *--end(); }
245
246 instr_iterator instr_begin() { return Insts.begin(); }
247 const_instr_iterator instr_begin() const { return Insts.begin(); }
248 instr_iterator instr_end() { return Insts.end(); }
249 const_instr_iterator instr_end() const { return Insts.end(); }
250 reverse_instr_iterator instr_rbegin() { return Insts.rbegin(); }
251 const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(); }
252 reverse_instr_iterator instr_rend () { return Insts.rend(); }
253 const_reverse_instr_iterator instr_rend () const { return Insts.rend(); }
254
255 using instr_range = iterator_range<instr_iterator>;
256 using const_instr_range = iterator_range<const_instr_iterator>;
257 instr_range instrs() { return instr_range(instr_begin(), instr_end()); }
258 const_instr_range instrs() const {
259 return const_instr_range(instr_begin(), instr_end());
260 }
261
262 iterator begin() { return instr_begin(); }
263 const_iterator begin() const { return instr_begin(); }
264 iterator end () { return instr_end(); }
265 const_iterator end () const { return instr_end(); }
266 reverse_iterator rbegin() {
267 return reverse_iterator::getAtBundleBegin(instr_rbegin());
268 }
269 const_reverse_iterator rbegin() const {
270 return const_reverse_iterator::getAtBundleBegin(instr_rbegin());
271 }
272 reverse_iterator rend() { return reverse_iterator(instr_rend()); }
273 const_reverse_iterator rend() const {
274 return const_reverse_iterator(instr_rend());
275 }
276
277 /// Support for MachineInstr::getNextNode().
278 static Instructions MachineBasicBlock::*getSublistAccess(MachineInstr *) {
279 return &MachineBasicBlock::Insts;
280 }
281
282 inline iterator_range<iterator> terminators() {
283 return make_range(getFirstTerminator(), end());
284 }
285 inline iterator_range<const_iterator> terminators() const {
286 return make_range(getFirstTerminator(), end());
287 }
288
289 /// Returns a range that iterates over the phis in the basic block.
290 inline iterator_range<iterator> phis() {
291 return make_range(begin(), getFirstNonPHI());
292 }
293 inline iterator_range<const_iterator> phis() const {
294 return const_cast<MachineBasicBlock *>(this)->phis();
295 }
296
297 // Machine-CFG iterators
298 using pred_iterator = std::vector<MachineBasicBlock *>::iterator;
299 using const_pred_iterator = std::vector<MachineBasicBlock *>::const_iterator;
300 using succ_iterator = std::vector<MachineBasicBlock *>::iterator;
301 using const_succ_iterator = std::vector<MachineBasicBlock *>::const_iterator;
302 using pred_reverse_iterator =
303 std::vector<MachineBasicBlock *>::reverse_iterator;
304 using const_pred_reverse_iterator =
305 std::vector<MachineBasicBlock *>::const_reverse_iterator;
306 using succ_reverse_iterator =
307 std::vector<MachineBasicBlock *>::reverse_iterator;
308 using const_succ_reverse_iterator =
309 std::vector<MachineBasicBlock *>::const_reverse_iterator;
310 pred_iterator pred_begin() { return Predecessors.begin(); }
311 const_pred_iterator pred_begin() const { return Predecessors.begin(); }
312 pred_iterator pred_end() { return Predecessors.end(); }
313 const_pred_iterator pred_end() const { return Predecessors.end(); }
314 pred_reverse_iterator pred_rbegin()
315 { return Predecessors.rbegin();}
316 const_pred_reverse_iterator pred_rbegin() const
317 { return Predecessors.rbegin();}
318 pred_reverse_iterator pred_rend()
319 { return Predecessors.rend(); }
320 const_pred_reverse_iterator pred_rend() const
321 { return Predecessors.rend(); }
322 unsigned pred_size() const {
323 return (unsigned)Predecessors.size();
324 }
325 bool pred_empty() const { return Predecessors.empty(); }
326 succ_iterator succ_begin() { return Successors.begin(); }
327 const_succ_iterator succ_begin() const { return Successors.begin(); }
328 succ_iterator succ_end() { return Successors.end(); }
329 const_succ_iterator succ_end() const { return Successors.end(); }
330 succ_reverse_iterator succ_rbegin()
331 { return Successors.rbegin(); }
332 const_succ_reverse_iterator succ_rbegin() const
333 { return Successors.rbegin(); }
334 succ_reverse_iterator succ_rend()
335 { return Successors.rend(); }
336 const_succ_reverse_iterator succ_rend() const
337 { return Successors.rend(); }
338 unsigned succ_size() const {
339 return (unsigned)Successors.size();
340 }
341 bool succ_empty() const { return Successors.empty(); }
342
343 inline iterator_range<pred_iterator> predecessors() {
344 return make_range(pred_begin(), pred_end());
345 }
346 inline iterator_range<const_pred_iterator> predecessors() const {
347 return make_range(pred_begin(), pred_end());
348 }
349 inline iterator_range<succ_iterator> successors() {
350 return make_range(succ_begin(), succ_end());
351 }
352 inline iterator_range<const_succ_iterator> successors() const {
353 return make_range(succ_begin(), succ_end());
354 }
355
356 // LiveIn management methods.
357
358 /// Adds the specified register as a live in. Note that it is an error to add
359 /// the same register to the same set more than once unless the intention is
360 /// to call sortUniqueLiveIns after all registers are added.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200361 void addLiveIn(MCRegister PhysReg,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100362 LaneBitmask LaneMask = LaneBitmask::getAll()) {
363 LiveIns.push_back(RegisterMaskPair(PhysReg, LaneMask));
364 }
365 void addLiveIn(const RegisterMaskPair &RegMaskPair) {
366 LiveIns.push_back(RegMaskPair);
367 }
368
369 /// Sorts and uniques the LiveIns vector. It can be significantly faster to do
370 /// this than repeatedly calling isLiveIn before calling addLiveIn for every
371 /// LiveIn insertion.
372 void sortUniqueLiveIns();
373
374 /// Clear live in list.
375 void clearLiveIns();
376
377 /// Add PhysReg as live in to this block, and ensure that there is a copy of
378 /// PhysReg to a virtual register of class RC. Return the virtual register
379 /// that is a copy of the live in PhysReg.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200380 Register addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100381
382 /// Remove the specified register from the live in set.
383 void removeLiveIn(MCPhysReg Reg,
384 LaneBitmask LaneMask = LaneBitmask::getAll());
385
386 /// Return true if the specified register is in the live in set.
387 bool isLiveIn(MCPhysReg Reg,
388 LaneBitmask LaneMask = LaneBitmask::getAll()) const;
389
390 // Iteration support for live in sets. These sets are kept in sorted
391 // order by their register number.
392 using livein_iterator = LiveInVector::const_iterator;
393#ifndef NDEBUG
394 /// Unlike livein_begin, this method does not check that the liveness
395 /// information is accurate. Still for debug purposes it may be useful
396 /// to have iterators that won't assert if the liveness information
397 /// is not current.
398 livein_iterator livein_begin_dbg() const { return LiveIns.begin(); }
399 iterator_range<livein_iterator> liveins_dbg() const {
400 return make_range(livein_begin_dbg(), livein_end());
401 }
402#endif
403 livein_iterator livein_begin() const;
404 livein_iterator livein_end() const { return LiveIns.end(); }
405 bool livein_empty() const { return LiveIns.empty(); }
406 iterator_range<livein_iterator> liveins() const {
407 return make_range(livein_begin(), livein_end());
408 }
409
410 /// Remove entry from the livein set and return iterator to the next.
411 livein_iterator removeLiveIn(livein_iterator I);
412
413 /// Get the clobber mask for the start of this basic block. Funclets use this
414 /// to prevent register allocation across funclet transitions.
415 const uint32_t *getBeginClobberMask(const TargetRegisterInfo *TRI) const;
416
417 /// Get the clobber mask for the end of the basic block.
418 /// \see getBeginClobberMask()
419 const uint32_t *getEndClobberMask(const TargetRegisterInfo *TRI) const;
420
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200421 /// Return alignment of the basic block.
422 Align getAlignment() const { return Alignment; }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100423
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200424 /// Set alignment of the basic block.
425 void setAlignment(Align A) { Alignment = A; }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100426
427 /// Returns true if the block is a landing pad. That is this basic block is
428 /// entered via an exception handler.
429 bool isEHPad() const { return IsEHPad; }
430
431 /// Indicates the block is a landing pad. That is this basic block is entered
432 /// via an exception handler.
433 void setIsEHPad(bool V = true) { IsEHPad = V; }
434
435 bool hasEHPadSuccessor() const;
436
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200437 /// Returns true if this is the entry block of the function.
438 bool isEntryBlock() const;
439
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100440 /// Returns true if this is the entry block of an EH scope, i.e., the block
441 /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
442 bool isEHScopeEntry() const { return IsEHScopeEntry; }
443
444 /// Indicates if this is the entry block of an EH scope, i.e., the block that
445 /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
446 void setIsEHScopeEntry(bool V = true) { IsEHScopeEntry = V; }
447
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100448 /// Returns true if this is the entry block of an EH funclet.
449 bool isEHFuncletEntry() const { return IsEHFuncletEntry; }
450
451 /// Indicates if this is the entry block of an EH funclet.
452 void setIsEHFuncletEntry(bool V = true) { IsEHFuncletEntry = V; }
453
454 /// Returns true if this is the entry block of a cleanup funclet.
455 bool isCleanupFuncletEntry() const { return IsCleanupFuncletEntry; }
456
457 /// Indicates if this is the entry block of a cleanup funclet.
458 void setIsCleanupFuncletEntry(bool V = true) { IsCleanupFuncletEntry = V; }
459
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200460 /// Returns true if this block begins any section.
461 bool isBeginSection() const { return IsBeginSection; }
462
463 /// Returns true if this block ends any section.
464 bool isEndSection() const { return IsEndSection; }
465
466 void setIsBeginSection(bool V = true) { IsBeginSection = V; }
467
468 void setIsEndSection(bool V = true) { IsEndSection = V; }
469
470 /// Returns the section ID of this basic block.
471 MBBSectionID getSectionID() const { return SectionID; }
472
473 /// Returns the unique section ID number of this basic block.
474 unsigned getSectionIDNum() const {
475 return ((unsigned)MBBSectionID::SectionType::Cold) -
476 ((unsigned)SectionID.Type) + SectionID.Number;
477 }
478
479 /// Sets the section ID for this basic block.
480 void setSectionID(MBBSectionID V) { SectionID = V; }
481
482 /// Returns the MCSymbol marking the end of this basic block.
483 MCSymbol *getEndSymbol() const;
484
485 /// Returns true if this block may have an INLINEASM_BR (overestimate, by
486 /// checking if any of the successors are indirect targets of any inlineasm_br
487 /// in the function).
488 bool mayHaveInlineAsmBr() const;
489
490 /// Returns true if this is the indirect dest of an INLINEASM_BR.
491 bool isInlineAsmBrIndirectTarget() const {
492 return IsInlineAsmBrIndirectTarget;
493 }
494
495 /// Indicates if this is the indirect dest of an INLINEASM_BR.
496 void setIsInlineAsmBrIndirectTarget(bool V = true) {
497 IsInlineAsmBrIndirectTarget = V;
498 }
499
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100500 /// Returns true if it is legal to hoist instructions into this block.
501 bool isLegalToHoistInto() const;
502
503 // Code Layout methods.
504
505 /// Move 'this' block before or after the specified block. This only moves
506 /// the block, it does not modify the CFG or adjust potential fall-throughs at
507 /// the end of the block.
508 void moveBefore(MachineBasicBlock *NewAfter);
509 void moveAfter(MachineBasicBlock *NewBefore);
510
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200511 /// Returns true if this and MBB belong to the same section.
512 bool sameSection(const MachineBasicBlock *MBB) const {
513 return getSectionID() == MBB->getSectionID();
514 }
515
516 /// Update the terminator instructions in block to account for changes to
517 /// block layout which may have been made. PreviousLayoutSuccessor should be
518 /// set to the block which may have been used as fallthrough before the block
519 /// layout was modified. If the block previously fell through to that block,
520 /// it may now need a branch. If it previously branched to another block, it
521 /// may now be able to fallthrough to the current layout successor.
522 void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100523
524 // Machine-CFG mutators
525
526 /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
527 /// of Succ is automatically updated. PROB parameter is stored in
528 /// Probabilities list. The default probability is set as unknown. Mixing
529 /// known and unknown probabilities in successor list is not allowed. When all
530 /// successors have unknown probabilities, 1 / N is returned as the
531 /// probability for each successor, where N is the number of successors.
532 ///
533 /// Note that duplicate Machine CFG edges are not allowed.
534 void addSuccessor(MachineBasicBlock *Succ,
535 BranchProbability Prob = BranchProbability::getUnknown());
536
537 /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
538 /// of Succ is automatically updated. The probability is not provided because
539 /// BPI is not available (e.g. -O0 is used), in which case edge probabilities
540 /// won't be used. Using this interface can save some space.
541 void addSuccessorWithoutProb(MachineBasicBlock *Succ);
542
543 /// Set successor probability of a given iterator.
544 void setSuccProbability(succ_iterator I, BranchProbability Prob);
545
546 /// Normalize probabilities of all successors so that the sum of them becomes
547 /// one. This is usually done when the current update on this MBB is done, and
548 /// the sum of its successors' probabilities is not guaranteed to be one. The
549 /// user is responsible for the correct use of this function.
550 /// MBB::removeSuccessor() has an option to do this automatically.
551 void normalizeSuccProbs() {
552 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
553 }
554
555 /// Validate successors' probabilities and check if the sum of them is
556 /// approximate one. This only works in DEBUG mode.
557 void validateSuccProbs() const;
558
559 /// Remove successor from the successors list of this MachineBasicBlock. The
560 /// Predecessors list of Succ is automatically updated.
561 /// If NormalizeSuccProbs is true, then normalize successors' probabilities
562 /// after the successor is removed.
563 void removeSuccessor(MachineBasicBlock *Succ,
564 bool NormalizeSuccProbs = false);
565
566 /// Remove specified successor from the successors list of this
567 /// MachineBasicBlock. The Predecessors list of Succ is automatically updated.
568 /// If NormalizeSuccProbs is true, then normalize successors' probabilities
569 /// after the successor is removed.
570 /// Return the iterator to the element after the one removed.
571 succ_iterator removeSuccessor(succ_iterator I,
572 bool NormalizeSuccProbs = false);
573
574 /// Replace successor OLD with NEW and update probability info.
575 void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
576
577 /// Copy a successor (and any probability info) from original block to this
578 /// block's. Uses an iterator into the original blocks successors.
579 ///
580 /// This is useful when doing a partial clone of successors. Afterward, the
581 /// probabilities may need to be normalized.
582 void copySuccessor(MachineBasicBlock *Orig, succ_iterator I);
583
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100584 /// Split the old successor into old plus new and updates the probability
585 /// info.
586 void splitSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New,
587 bool NormalizeSuccProbs = false);
588
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100589 /// Transfers all the successors from MBB to this machine basic block (i.e.,
590 /// copies all the successors FromMBB and remove all the successors from
591 /// FromMBB).
592 void transferSuccessors(MachineBasicBlock *FromMBB);
593
594 /// Transfers all the successors, as in transferSuccessors, and update PHI
595 /// operands in the successor blocks which refer to FromMBB to refer to this.
596 void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB);
597
598 /// Return true if any of the successors have probabilities attached to them.
599 bool hasSuccessorProbabilities() const { return !Probs.empty(); }
600
601 /// Return true if the specified MBB is a predecessor of this block.
602 bool isPredecessor(const MachineBasicBlock *MBB) const;
603
604 /// Return true if the specified MBB is a successor of this block.
605 bool isSuccessor(const MachineBasicBlock *MBB) const;
606
607 /// Return true if the specified MBB will be emitted immediately after this
608 /// block, such that if this block exits by falling through, control will
609 /// transfer to the specified MBB. Note that MBB need not be a successor at
610 /// all, for example if this block ends with an unconditional branch to some
611 /// other block.
612 bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
613
614 /// Return the fallthrough block if the block can implicitly
615 /// transfer control to the block after it by falling off the end of
616 /// it. This should return null if it can reach the block after
617 /// it, but it uses an explicit branch to do so (e.g., a table
618 /// jump). Non-null return is a conservative answer.
619 MachineBasicBlock *getFallThrough();
620
621 /// Return true if the block can implicitly transfer control to the
622 /// block after it by falling off the end of it. This should return
623 /// false if it can reach the block after it, but it uses an
624 /// explicit branch to do so (e.g., a table jump). True is a
625 /// conservative answer.
626 bool canFallThrough();
627
628 /// Returns a pointer to the first instruction in this block that is not a
629 /// PHINode instruction. When adding instructions to the beginning of the
630 /// basic block, they should be added before the returned value, not before
631 /// the first instruction, which might be PHI.
632 /// Returns end() is there's no non-PHI instruction.
633 iterator getFirstNonPHI();
634
635 /// Return the first instruction in MBB after I that is not a PHI or a label.
636 /// This is the correct point to insert lowered copies at the beginning of a
637 /// basic block that must be before any debugging information.
638 iterator SkipPHIsAndLabels(iterator I);
639
640 /// Return the first instruction in MBB after I that is not a PHI, label or
641 /// debug. This is the correct point to insert copies at the beginning of a
642 /// basic block.
643 iterator SkipPHIsLabelsAndDebug(iterator I);
644
645 /// Returns an iterator to the first terminator instruction of this basic
646 /// block. If a terminator does not exist, it returns end().
647 iterator getFirstTerminator();
648 const_iterator getFirstTerminator() const {
649 return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
650 }
651
652 /// Same getFirstTerminator but it ignores bundles and return an
653 /// instr_iterator instead.
654 instr_iterator getFirstInstrTerminator();
655
656 /// Returns an iterator to the first non-debug instruction in the basic block,
657 /// or end().
658 iterator getFirstNonDebugInstr();
659 const_iterator getFirstNonDebugInstr() const {
660 return const_cast<MachineBasicBlock *>(this)->getFirstNonDebugInstr();
661 }
662
663 /// Returns an iterator to the last non-debug instruction in the basic block,
664 /// or end().
665 iterator getLastNonDebugInstr();
666 const_iterator getLastNonDebugInstr() const {
667 return const_cast<MachineBasicBlock *>(this)->getLastNonDebugInstr();
668 }
669
670 /// Convenience function that returns true if the block ends in a return
671 /// instruction.
672 bool isReturnBlock() const {
673 return !empty() && back().isReturn();
674 }
675
Andrew Scull0372a572018-11-16 15:47:06 +0000676 /// Convenience function that returns true if the bock ends in a EH scope
677 /// return instruction.
678 bool isEHScopeReturnBlock() const {
679 return !empty() && back().isEHScopeReturn();
680 }
681
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200682 /// Split a basic block into 2 pieces at \p SplitPoint. A new block will be
683 /// inserted after this block, and all instructions after \p SplitInst moved
684 /// to it (\p SplitInst will be in the original block). If \p LIS is provided,
685 /// LiveIntervals will be appropriately updated. \return the newly inserted
686 /// block.
687 ///
688 /// If \p UpdateLiveIns is true, this will ensure the live ins list is
689 /// accurate, including for physreg uses/defs in the original block.
690 MachineBasicBlock *splitAt(MachineInstr &SplitInst, bool UpdateLiveIns = true,
691 LiveIntervals *LIS = nullptr);
692
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100693 /// Split the critical edge from this block to the given successor block, and
694 /// return the newly created block, or null if splitting is not possible.
695 ///
696 /// This function updates LiveVariables, MachineDominatorTree, and
697 /// MachineLoopInfo, as applicable.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200698 MachineBasicBlock *
699 SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P,
700 std::vector<SparseBitVector<>> *LiveInSets = nullptr);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100701
702 /// Check if the edge between this block and the given successor \p
703 /// Succ, can be split. If this returns true a subsequent call to
704 /// SplitCriticalEdge is guaranteed to return a valid basic block if
705 /// no changes occurred in the meantime.
706 bool canSplitCriticalEdge(const MachineBasicBlock *Succ) const;
707
708 void pop_front() { Insts.pop_front(); }
709 void pop_back() { Insts.pop_back(); }
710 void push_back(MachineInstr *MI) { Insts.push_back(MI); }
711
712 /// Insert MI into the instruction list before I, possibly inside a bundle.
713 ///
714 /// If the insertion point is inside a bundle, MI will be added to the bundle,
715 /// otherwise MI will not be added to any bundle. That means this function
716 /// alone can't be used to prepend or append instructions to bundles. See
717 /// MIBundleBuilder::insert() for a more reliable way of doing that.
718 instr_iterator insert(instr_iterator I, MachineInstr *M);
719
720 /// Insert a range of instructions into the instruction list before I.
721 template<typename IT>
722 void insert(iterator I, IT S, IT E) {
723 assert((I == end() || I->getParent() == this) &&
724 "iterator points outside of basic block");
725 Insts.insert(I.getInstrIterator(), S, E);
726 }
727
728 /// Insert MI into the instruction list before I.
729 iterator insert(iterator I, MachineInstr *MI) {
730 assert((I == end() || I->getParent() == this) &&
731 "iterator points outside of basic block");
732 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
733 "Cannot insert instruction with bundle flags");
734 return Insts.insert(I.getInstrIterator(), MI);
735 }
736
737 /// Insert MI into the instruction list after I.
738 iterator insertAfter(iterator I, MachineInstr *MI) {
739 assert((I == end() || I->getParent() == this) &&
740 "iterator points outside of basic block");
741 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
742 "Cannot insert instruction with bundle flags");
743 return Insts.insertAfter(I.getInstrIterator(), MI);
744 }
745
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200746 /// If I is bundled then insert MI into the instruction list after the end of
747 /// the bundle, otherwise insert MI immediately after I.
748 instr_iterator insertAfterBundle(instr_iterator I, MachineInstr *MI) {
749 assert((I == instr_end() || I->getParent() == this) &&
750 "iterator points outside of basic block");
751 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
752 "Cannot insert instruction with bundle flags");
753 while (I->isBundledWithSucc())
754 ++I;
755 return Insts.insertAfter(I, MI);
756 }
757
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100758 /// Remove an instruction from the instruction list and delete it.
759 ///
760 /// If the instruction is part of a bundle, the other instructions in the
761 /// bundle will still be bundled after removing the single instruction.
762 instr_iterator erase(instr_iterator I);
763
764 /// Remove an instruction from the instruction list and delete it.
765 ///
766 /// If the instruction is part of a bundle, the other instructions in the
767 /// bundle will still be bundled after removing the single instruction.
768 instr_iterator erase_instr(MachineInstr *I) {
769 return erase(instr_iterator(I));
770 }
771
772 /// Remove a range of instructions from the instruction list and delete them.
773 iterator erase(iterator I, iterator E) {
774 return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
775 }
776
777 /// Remove an instruction or bundle from the instruction list and delete it.
778 ///
779 /// If I points to a bundle of instructions, they are all erased.
780 iterator erase(iterator I) {
781 return erase(I, std::next(I));
782 }
783
784 /// Remove an instruction from the instruction list and delete it.
785 ///
786 /// If I is the head of a bundle of instructions, the whole bundle will be
787 /// erased.
788 iterator erase(MachineInstr *I) {
789 return erase(iterator(I));
790 }
791
792 /// Remove the unbundled instruction from the instruction list without
793 /// deleting it.
794 ///
795 /// This function can not be used to remove bundled instructions, use
796 /// remove_instr to remove individual instructions from a bundle.
797 MachineInstr *remove(MachineInstr *I) {
798 assert(!I->isBundled() && "Cannot remove bundled instructions");
799 return Insts.remove(instr_iterator(I));
800 }
801
802 /// Remove the possibly bundled instruction from the instruction list
803 /// without deleting it.
804 ///
805 /// If the instruction is part of a bundle, the other instructions in the
806 /// bundle will still be bundled after removing the single instruction.
807 MachineInstr *remove_instr(MachineInstr *I);
808
809 void clear() {
810 Insts.clear();
811 }
812
813 /// Take an instruction from MBB 'Other' at the position From, and insert it
814 /// into this MBB right before 'Where'.
815 ///
816 /// If From points to a bundle of instructions, the whole bundle is moved.
817 void splice(iterator Where, MachineBasicBlock *Other, iterator From) {
818 // The range splice() doesn't allow noop moves, but this one does.
819 if (Where != From)
820 splice(Where, Other, From, std::next(From));
821 }
822
823 /// Take a block of instructions from MBB 'Other' in the range [From, To),
824 /// and insert them into this MBB right before 'Where'.
825 ///
826 /// The instruction at 'Where' must not be included in the range of
827 /// instructions to move.
828 void splice(iterator Where, MachineBasicBlock *Other,
829 iterator From, iterator To) {
830 Insts.splice(Where.getInstrIterator(), Other->Insts,
831 From.getInstrIterator(), To.getInstrIterator());
832 }
833
834 /// This method unlinks 'this' from the containing function, and returns it,
835 /// but does not delete it.
836 MachineBasicBlock *removeFromParent();
837
838 /// This method unlinks 'this' from the containing function and deletes it.
839 void eraseFromParent();
840
841 /// Given a machine basic block that branched to 'Old', change the code and
842 /// CFG so that it branches to 'New' instead.
843 void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
844
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200845 /// Update all phi nodes in this basic block to refer to basic block \p New
846 /// instead of basic block \p Old.
847 void replacePhiUsesWith(MachineBasicBlock *Old, MachineBasicBlock *New);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100848
849 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100850 /// and DBG_LABEL instructions. Return UnknownLoc if there is none.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100851 DebugLoc findDebugLoc(instr_iterator MBBI);
852 DebugLoc findDebugLoc(iterator MBBI) {
853 return findDebugLoc(MBBI.getInstrIterator());
854 }
855
856 /// Find the previous valid DebugLoc preceding MBBI, skipping and DBG_VALUE
857 /// instructions. Return UnknownLoc if there is none.
858 DebugLoc findPrevDebugLoc(instr_iterator MBBI);
859 DebugLoc findPrevDebugLoc(iterator MBBI) {
860 return findPrevDebugLoc(MBBI.getInstrIterator());
861 }
862
863 /// Find and return the merged DebugLoc of the branch instructions of the
864 /// block. Return UnknownLoc if there is none.
865 DebugLoc findBranchDebugLoc();
866
867 /// Possible outcome of a register liveness query to computeRegisterLiveness()
868 enum LivenessQueryResult {
869 LQR_Live, ///< Register is known to be (at least partially) live.
870 LQR_Dead, ///< Register is known to be fully dead.
871 LQR_Unknown ///< Register liveness not decidable from local neighborhood.
872 };
873
874 /// Return whether (physical) register \p Reg has been defined and not
875 /// killed as of just before \p Before.
876 ///
877 /// Search is localised to a neighborhood of \p Neighborhood instructions
878 /// before (searching for defs or kills) and \p Neighborhood instructions
879 /// after (searching just for defs) \p Before.
880 ///
881 /// \p Reg must be a physical register.
882 LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200883 MCRegister Reg,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100884 const_iterator Before,
885 unsigned Neighborhood = 10) const;
886
887 // Debugging methods.
888 void dump() const;
889 void print(raw_ostream &OS, const SlotIndexes * = nullptr,
890 bool IsStandalone = true) const;
891 void print(raw_ostream &OS, ModuleSlotTracker &MST,
892 const SlotIndexes * = nullptr, bool IsStandalone = true) const;
893
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200894 enum PrintNameFlag {
895 PrintNameIr = (1 << 0), ///< Add IR name where available
896 PrintNameAttributes = (1 << 1), ///< Print attributes
897 };
898
899 void printName(raw_ostream &os, unsigned printNameFlags = PrintNameIr,
900 ModuleSlotTracker *moduleSlotTracker = nullptr) const;
901
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100902 // Printing method used by LoopInfo.
903 void printAsOperand(raw_ostream &OS, bool PrintType = true) const;
904
905 /// MachineBasicBlocks are uniquely numbered at the function level, unless
906 /// they're not in a MachineFunction yet, in which case this will return -1.
907 int getNumber() const { return Number; }
908 void setNumber(int N) { Number = N; }
909
910 /// Return the MCSymbol for this basic block.
911 MCSymbol *getSymbol() const;
912
913 Optional<uint64_t> getIrrLoopHeaderWeight() const {
914 return IrrLoopHeaderWeight;
915 }
916
917 void setIrrLoopHeaderWeight(uint64_t Weight) {
918 IrrLoopHeaderWeight = Weight;
919 }
920
921private:
922 /// Return probability iterator corresponding to the I successor iterator.
923 probability_iterator getProbabilityIterator(succ_iterator I);
924 const_probability_iterator
925 getProbabilityIterator(const_succ_iterator I) const;
926
927 friend class MachineBranchProbabilityInfo;
928 friend class MIPrinter;
929
930 /// Return probability of the edge from this block to MBB. This method should
931 /// NOT be called directly, but by using getEdgeProbability method from
932 /// MachineBranchProbabilityInfo class.
933 BranchProbability getSuccProbability(const_succ_iterator Succ) const;
934
935 // Methods used to maintain doubly linked list of blocks...
936 friend struct ilist_callback_traits<MachineBasicBlock>;
937
938 // Machine-CFG mutators
939
940 /// Add Pred as a predecessor of this MachineBasicBlock. Don't do this
941 /// unless you know what you're doing, because it doesn't update Pred's
942 /// successors list. Use Pred->addSuccessor instead.
943 void addPredecessor(MachineBasicBlock *Pred);
944
945 /// Remove Pred as a predecessor of this MachineBasicBlock. Don't do this
946 /// unless you know what you're doing, because it doesn't update Pred's
947 /// successors list. Use Pred->removeSuccessor instead.
948 void removePredecessor(MachineBasicBlock *Pred);
949};
950
951raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
952
953/// Prints a machine basic block reference.
954///
955/// The format is:
956/// %bb.5 - a machine basic block with MBB.getNumber() == 5.
957///
958/// Usage: OS << printMBBReference(MBB) << '\n';
959Printable printMBBReference(const MachineBasicBlock &MBB);
960
961// This is useful when building IndexedMaps keyed on basic block pointers.
962struct MBB2NumberFunctor {
963 using argument_type = const MachineBasicBlock *;
964 unsigned operator()(const MachineBasicBlock *MBB) const {
965 return MBB->getNumber();
966 }
967};
968
969//===--------------------------------------------------------------------===//
970// GraphTraits specializations for machine basic block graphs (machine-CFGs)
971//===--------------------------------------------------------------------===//
972
973// Provide specializations of GraphTraits to be able to treat a
974// MachineFunction as a graph of MachineBasicBlocks.
975//
976
977template <> struct GraphTraits<MachineBasicBlock *> {
978 using NodeRef = MachineBasicBlock *;
979 using ChildIteratorType = MachineBasicBlock::succ_iterator;
980
981 static NodeRef getEntryNode(MachineBasicBlock *BB) { return BB; }
982 static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
983 static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
984};
985
986template <> struct GraphTraits<const MachineBasicBlock *> {
987 using NodeRef = const MachineBasicBlock *;
988 using ChildIteratorType = MachineBasicBlock::const_succ_iterator;
989
990 static NodeRef getEntryNode(const MachineBasicBlock *BB) { return BB; }
991 static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
992 static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
993};
994
995// Provide specializations of GraphTraits to be able to treat a
996// MachineFunction as a graph of MachineBasicBlocks and to walk it
997// in inverse order. Inverse order for a function is considered
998// to be when traversing the predecessor edges of a MBB
999// instead of the successor edges.
1000//
1001template <> struct GraphTraits<Inverse<MachineBasicBlock*>> {
1002 using NodeRef = MachineBasicBlock *;
1003 using ChildIteratorType = MachineBasicBlock::pred_iterator;
1004
1005 static NodeRef getEntryNode(Inverse<MachineBasicBlock *> G) {
1006 return G.Graph;
1007 }
1008
1009 static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
1010 static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
1011};
1012
1013template <> struct GraphTraits<Inverse<const MachineBasicBlock*>> {
1014 using NodeRef = const MachineBasicBlock *;
1015 using ChildIteratorType = MachineBasicBlock::const_pred_iterator;
1016
1017 static NodeRef getEntryNode(Inverse<const MachineBasicBlock *> G) {
1018 return G.Graph;
1019 }
1020
1021 static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
1022 static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
1023};
1024
1025/// MachineInstrSpan provides an interface to get an iteration range
1026/// containing the instruction it was initialized with, along with all
1027/// those instructions inserted prior to or following that instruction
1028/// at some point after the MachineInstrSpan is constructed.
1029class MachineInstrSpan {
1030 MachineBasicBlock &MBB;
1031 MachineBasicBlock::iterator I, B, E;
1032
1033public:
Andrew Walbran3d2c1972020-04-07 12:24:26 +01001034 MachineInstrSpan(MachineBasicBlock::iterator I, MachineBasicBlock *BB)
1035 : MBB(*BB), I(I), B(I == MBB.begin() ? MBB.end() : std::prev(I)),
1036 E(std::next(I)) {
1037 assert(I == BB->end() || I->getParent() == BB);
1038 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001039
1040 MachineBasicBlock::iterator begin() {
1041 return B == MBB.end() ? MBB.begin() : std::next(B);
1042 }
1043 MachineBasicBlock::iterator end() { return E; }
1044 bool empty() { return begin() == end(); }
1045
1046 MachineBasicBlock::iterator getInitial() { return I; }
1047};
1048
1049/// Increment \p It until it points to a non-debug instruction or to \p End
1050/// and return the resulting iterator. This function should only be used
1051/// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
1052/// const_instr_iterator} and the respective reverse iterators.
1053template<typename IterT>
1054inline IterT skipDebugInstructionsForward(IterT It, IterT End) {
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001055 while (It != End && It->isDebugInstr())
Olivier Deprezf4ef2d02021-04-20 13:36:24 +02001056 ++It;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001057 return It;
1058}
1059
1060/// Decrement \p It until it points to a non-debug instruction or to \p Begin
1061/// and return the resulting iterator. This function should only be used
1062/// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
1063/// const_instr_iterator} and the respective reverse iterators.
1064template<class IterT>
1065inline IterT skipDebugInstructionsBackward(IterT It, IterT Begin) {
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001066 while (It != Begin && It->isDebugInstr())
Olivier Deprezf4ef2d02021-04-20 13:36:24 +02001067 --It;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001068 return It;
1069}
1070
Olivier Deprezf4ef2d02021-04-20 13:36:24 +02001071/// Increment \p It, then continue incrementing it while it points to a debug
1072/// instruction. A replacement for std::next.
1073template <typename IterT> inline IterT next_nodbg(IterT It, IterT End) {
1074 return skipDebugInstructionsForward(std::next(It), End);
1075}
1076
1077/// Decrement \p It, then continue decrementing it while it points to a debug
1078/// instruction. A replacement for std::prev.
1079template <typename IterT> inline IterT prev_nodbg(IterT It, IterT Begin) {
1080 return skipDebugInstructionsBackward(std::prev(It), Begin);
1081}
1082
1083/// Construct a range iterator which begins at \p It and moves forwards until
1084/// \p End is reached, skipping any debug instructions.
1085template <typename IterT>
1086inline auto instructionsWithoutDebug(IterT It, IterT End) {
1087 return make_filter_range(make_range(It, End), [](const MachineInstr &MI) {
1088 return !MI.isDebugInstr();
1089 });
1090}
1091
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001092} // end namespace llvm
1093
1094#endif // LLVM_CODEGEN_MACHINEBASICBLOCK_H