LLVM 22.0.0git
BasicBlockUtils.h
Go to the documentation of this file.
1//===- Transform/Utils/BasicBlockUtils.h - BasicBlock Utils -----*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This family of functions perform manipulations on basic blocks, and
10// instructions contained within basic blocks.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
15#define LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
16
17// FIXME: Move to this file: BasicBlock::removePredecessor, BB::splitBasicBlock
18
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/SetVector.h"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/CycleInfo.h"
23#include "llvm/IR/Dominators.h"
26#include <cassert>
27
28namespace llvm {
29class BranchInst;
30class LandingPadInst;
31class Loop;
32class PHINode;
33template <typename PtrType> class SmallPtrSetImpl;
36class DomTreeUpdater;
37class Function;
38class IRBuilderBase;
39class LoopInfo;
40class MDNode;
44class ReturnInst;
46class Value;
47
48/// Replace contents of every block in \p BBs with single unreachable
49/// instruction. If \p Updates is specified, collect all necessary DT updates
50/// into this vector. If \p KeepOneInputPHIs is true, one-input Phis in
51/// successors of blocks being deleted will be preserved.
52LLVM_ABI void
55 bool KeepOneInputPHIs = false);
56
57/// Delete the specified block, which must have no predecessors.
58LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU = nullptr,
59 bool KeepOneInputPHIs = false);
60
61/// Delete the specified blocks from \p BB. The set of deleted blocks must have
62/// no predecessors that are not being deleted themselves. \p BBs must have no
63/// duplicating blocks. If there are loops among this set of blocks, all
64/// relevant loop info updates should be done before this function is called.
65/// If \p KeepOneInputPHIs is true, one-input Phis in successors of blocks
66/// being deleted will be preserved.
68 DomTreeUpdater *DTU = nullptr,
69 bool KeepOneInputPHIs = false);
70
71/// Delete all basic blocks from \p F that are not reachable from its entry
72/// node. If \p KeepOneInputPHIs is true, one-input Phis in successors of
73/// blocks being deleted will be preserved.
75 DomTreeUpdater *DTU = nullptr,
76 bool KeepOneInputPHIs = false);
77
78/// We know that BB has one predecessor. If there are any single-entry PHI nodes
79/// in it, fold them away. This handles the case when all entries to the PHI
80/// nodes in a block are guaranteed equal, such as when the block has exactly
81/// one predecessor.
82LLVM_ABI bool
84 MemoryDependenceResults *MemDep = nullptr);
85
86/// Examine each PHI in the given block and delete it if it is dead. Also
87/// recursively delete any operands that become dead as a result. This includes
88/// tracing the def-use list from the PHI to see if it is ultimately unused or
89/// if it reaches an unused cycle. Return true if any PHIs were deleted.
91 const TargetLibraryInfo *TLI = nullptr,
92 MemorySSAUpdater *MSSAU = nullptr);
93
94/// Attempts to merge a block into its predecessor, if possible. The return
95/// value indicates success or failure.
96/// By default do not merge blocks if BB's predecessor has multiple successors.
97/// If PredecessorWithTwoSuccessors = true, the blocks can only be merged
98/// if BB's Pred has a branch to BB and to AnotherBB, and BB has a single
99/// successor Sing. In this case the branch will be updated with Sing instead of
100/// BB, and BB will still be merged into its predecessor and removed.
101/// If \p DT is not nullptr, update it directly; in that case, DTU must be
102/// nullptr.
104 BasicBlock *BB, DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
105 MemorySSAUpdater *MSSAU = nullptr,
106 MemoryDependenceResults *MemDep = nullptr,
107 bool PredecessorWithTwoSuccessors = false, DominatorTree *DT = nullptr);
108
109/// Merge block(s) sucessors, if possible. Return true if at least two
110/// of the blocks were merged together.
111/// In order to merge, each block must be terminated by an unconditional
112/// branch. If L is provided, then the blocks merged into their predecessors
113/// must be in L. In addition, This utility calls on another utility:
114/// MergeBlockIntoPredecessor. Blocks are successfully merged when the call to
115/// MergeBlockIntoPredecessor returns true.
117 SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L = nullptr,
118 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
119
120/// Try to remove redundant dbg.value instructions from given basic block.
121/// Returns true if at least one instruction was removed. Remove redundant
122/// pseudo ops when RemovePseudoOp is true.
124
125/// Replace all uses of an instruction (specified by BI) with a value, then
126/// remove and delete the original instruction.
128
129/// Replace the instruction specified by BI with the instruction specified by I.
130/// Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc. The
131/// original instruction is deleted and BI is updated to point to the new
132/// instruction.
134 Instruction *I);
135
136/// Replace the instruction specified by From with the instruction specified by
137/// To. Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc.
139
140/// Check if we can prove that all paths starting from this block converge
141/// to a block that either has a @llvm.experimental.deoptimize call
142/// prior to its terminating return instruction or is terminated by unreachable.
143/// All blocks in the traversed sequence must have an unique successor, maybe
144/// except for the last one.
146
147/// Option class for critical edge splitting.
148///
149/// This provides a builder interface for overriding the default options used
150/// during critical edge splitting.
157 bool KeepOneInputPHIs = false;
158 bool PreserveLCSSA = false;
160 /// SplitCriticalEdge is guaranteed to preserve loop-simplify form if LI is
161 /// provided. If it cannot be preserved, no splitting will take place. If it
162 /// is not set, preserve loop-simplify form if possible.
164
166 LoopInfo *LI = nullptr,
167 MemorySSAUpdater *MSSAU = nullptr,
168 PostDominatorTree *PDT = nullptr)
169 : DT(DT), PDT(PDT), LI(LI), MSSAU(MSSAU) {}
170
175
177 KeepOneInputPHIs = true;
178 return *this;
179 }
180
182 PreserveLCSSA = true;
183 return *this;
184 }
185
190
195};
196
197/// When a loop exit edge is split, LCSSA form may require new PHIs in the new
198/// exit block. This function inserts the new PHIs, as needed. Preds is a list
199/// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
200/// the old loop exit, now the successor of SplitBB.
202 BasicBlock *SplitBB,
203 BasicBlock *DestBB);
204
205/// If this edge is a critical edge, insert a new node to split the critical
206/// edge. This will update the analyses passed in through the option struct.
207/// This returns the new block if the edge was split, null otherwise.
208///
209/// If MergeIdenticalEdges in the options struct is true (not the default),
210/// *all* edges from TI to the specified successor will be merged into the same
211/// critical edge block. This is most commonly interesting with switch
212/// instructions, which may have many edges to any one destination. This
213/// ensures that all edges to that dest go to one block instead of each going
214/// to a different block, but isn't the standard definition of a "critical
215/// edge".
216///
217/// It is invalid to call this function on a critical edge that starts at an
218/// IndirectBrInst. Splitting these edges will almost always create an invalid
219/// program because the address of the new block won't be the one that is jumped
220/// to.
221LLVM_ABI BasicBlock *
222SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
223 const CriticalEdgeSplittingOptions &Options =
224 CriticalEdgeSplittingOptions(),
225 const Twine &BBName = "");
226
227/// If it is known that an edge is critical, SplitKnownCriticalEdge can be
228/// called directly, rather than calling SplitCriticalEdge first.
229LLVM_ABI BasicBlock *
230SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum,
231 const CriticalEdgeSplittingOptions &Options =
232 CriticalEdgeSplittingOptions(),
233 const Twine &BBName = "");
234
235/// If an edge from Src to Dst is critical, split the edge and return true,
236/// otherwise return false. This method requires that there be an edge between
237/// the two blocks. It updates the analyses passed in the options struct
238inline BasicBlock *
242 Instruction *TI = Src->getTerminator();
243 unsigned i = 0;
244 while (true) {
245 assert(i != TI->getNumSuccessors() && "Edge doesn't exist!");
246 if (TI->getSuccessor(i) == Dst)
247 return SplitCriticalEdge(TI, i, Options);
248 ++i;
249 }
250}
251
252/// Loop over all of the edges in the CFG, breaking critical edges as they are
253/// found. Returns the number of broken edges.
254LLVM_ABI unsigned
255SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options =
256 CriticalEdgeSplittingOptions());
257
258/// Split the edge connecting the specified blocks, and return the newly created
259/// basic block between \p From and \p To.
260LLVM_ABI BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To,
261 DominatorTree *DT = nullptr,
262 LoopInfo *LI = nullptr,
263 MemorySSAUpdater *MSSAU = nullptr,
264 const Twine &BBName = "");
265
266/// \brief Create a new intermediate target block for a callbr edge.
267///
268/// Create a new basic block between a callbr instruction and one of its
269/// successors. The new block replaces the original successor in the callbr
270/// instruction and unconditionally branches to the original successor. This
271/// is useful for normalizing control flow, e.g., when transforming
272/// irreducible loops.
273///
274/// \param CallBrBlock block containing the callbr instruction
275/// \param Succ original successor block
276/// \param SuccIdx index of the original successor in the callbr
277/// instruction
278/// \param DTU optional \p DomTreeUpdater for updating the
279/// dominator tree
280/// \param CI optional \p CycleInfo for updating cycle membership
281/// \param LI optional \p LoopInfo for updating loop membership
282/// \param UpdatedLI optional output flag indicating if \p LoopInfo has
283/// been updated
284///
285/// \returns newly created intermediate target block
286///
287/// \note This function updates PHI nodes, dominator tree, loop info, and
288/// cycle info as needed.
289LLVM_ABI BasicBlock *
290SplitCallBrEdge(BasicBlock *CallBrBlock, BasicBlock *Succ, unsigned SuccIdx,
291 DomTreeUpdater *DTU = nullptr, CycleInfo *CI = nullptr,
292 LoopInfo *LI = nullptr, bool *UpdatedLI = nullptr);
293
294/// Sets the unwind edge of an instruction to a particular successor.
295LLVM_ABI void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ);
296
297/// Replaces all uses of OldPred with the NewPred block in all PHINodes in a
298/// block.
299LLVM_ABI void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
300 BasicBlock *NewPred, PHINode *Until = nullptr);
301
302/// Split the edge connect the specficed blocks in the case that \p Succ is an
303/// Exception Handling Block
304LLVM_ABI BasicBlock *
305ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
306 LandingPadInst *OriginalPad = nullptr,
307 PHINode *LandingPadReplacement = nullptr,
308 const CriticalEdgeSplittingOptions &Options =
309 CriticalEdgeSplittingOptions(),
310 const Twine &BBName = "");
311
312/// Split the specified block at the specified instruction.
313///
314/// If \p Before is true, splitBlockBefore handles the block
315/// splitting. Otherwise, execution proceeds as described below.
316///
317/// Everything before \p SplitPt stays in \p Old and everything starting with \p
318/// SplitPt moves to a new block. The two blocks are joined by an unconditional
319/// branch. The new block with name \p BBName is returned.
320///
321/// FIXME: deprecated, switch to the DomTreeUpdater-based one.
322LLVM_ABI BasicBlock *SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
323 DominatorTree *DT, LoopInfo *LI = nullptr,
324 MemorySSAUpdater *MSSAU = nullptr,
325 const Twine &BBName = "", bool Before = false);
327 LoopInfo *LI = nullptr,
328 MemorySSAUpdater *MSSAU = nullptr,
329 const Twine &BBName = "", bool Before = false) {
330 return SplitBlock(Old, SplitPt->getIterator(), DT, LI, MSSAU, BBName, Before);
331}
332
333/// Split the specified block at the specified instruction.
334///
335/// If \p Before is true, splitBlockBefore handles the block
336/// splitting. Otherwise, execution proceeds as described below.
337///
338/// Everything before \p SplitPt stays in \p Old and everything starting with \p
339/// SplitPt moves to a new block. The two blocks are joined by an unconditional
340/// branch. The new block with name \p BBName is returned.
341LLVM_ABI BasicBlock *SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
342 DomTreeUpdater *DTU = nullptr,
343 LoopInfo *LI = nullptr,
344 MemorySSAUpdater *MSSAU = nullptr,
345 const Twine &BBName = "", bool Before = false);
347 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
348 MemorySSAUpdater *MSSAU = nullptr,
349 const Twine &BBName = "", bool Before = false) {
350 return SplitBlock(Old, SplitPt->getIterator(), DTU, LI, MSSAU, BBName, Before);
351}
352
353/// Split the specified block at the specified instruction \p SplitPt.
354/// All instructions before \p SplitPt are moved to a new block and all
355/// instructions after \p SplitPt stay in the old block. The new block and the
356/// old block are joined by inserting an unconditional branch to the end of the
357/// new block. The new block with name \p BBName is returned.
358LLVM_ABI BasicBlock *splitBlockBefore(BasicBlock *Old,
359 BasicBlock::iterator SplitPt,
360 DomTreeUpdater *DTU, LoopInfo *LI,
361 MemorySSAUpdater *MSSAU,
362 const Twine &BBName = "");
364 DomTreeUpdater *DTU, LoopInfo *LI,
365 MemorySSAUpdater *MSSAU, const Twine &BBName = "") {
366 return splitBlockBefore(Old, SplitPt->getIterator(), DTU, LI, MSSAU, BBName);
367}
368
369/// This method introduces at least one new basic block into the function and
370/// moves some of the predecessors of BB to be predecessors of the new block.
371/// The new predecessors are indicated by the Preds array. The new block is
372/// given a suffix of 'Suffix'. Returns new basic block to which predecessors
373/// from Preds are now pointing.
374///
375/// If BB is a landingpad block then additional basicblock might be introduced.
376/// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
377/// details on this case.
378///
379/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
380/// no other analyses. In particular, it does not preserve LoopSimplify
381/// (because it's complicated to handle the case where one of the edges being
382/// split is an exit of a loop with other exits).
383///
384/// FIXME: deprecated, switch to the DomTreeUpdater-based one.
386 BasicBlock *BB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
387 DominatorTree *DT, LoopInfo *LI = nullptr,
388 MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
389
390/// This method introduces at least one new basic block into the function and
391/// moves some of the predecessors of BB to be predecessors of the new block.
392/// The new predecessors are indicated by the Preds array. The new block is
393/// given a suffix of 'Suffix'. Returns new basic block to which predecessors
394/// from Preds are now pointing.
395///
396/// If BB is a landingpad block then additional basicblock might be introduced.
397/// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
398/// details on this case.
399///
400/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
401/// no other analyses. In particular, it does not preserve LoopSimplify
402/// (because it's complicated to handle the case where one of the edges being
403/// split is an exit of a loop with other exits).
405 BasicBlock *BB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
406 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
407 MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
408
409/// This method transforms the landing pad, OrigBB, by introducing two new basic
410/// blocks into the function. One of those new basic blocks gets the
411/// predecessors listed in Preds. The other basic block gets the remaining
412/// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
413/// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
414/// 'Suffix2', and are returned in the NewBBs vector.
415///
416/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
417/// no other analyses. In particular, it does not preserve LoopSimplify
418/// (because it's complicated to handle the case where one of the edges being
419/// split is an exit of a loop with other exits).
421 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
422 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
423 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
424 MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
425
426/// This method duplicates the specified return instruction into a predecessor
427/// which ends in an unconditional branch. If the return instruction returns a
428/// value defined by a PHI, propagate the right value into the return. It
429/// returns the new return instruction in the predecessor.
430LLVM_ABI ReturnInst *FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
431 BasicBlock *Pred,
432 DomTreeUpdater *DTU = nullptr);
433
434/// Split the containing block at the specified instruction - everything before
435/// SplitBefore stays in the old basic block, and the rest of the instructions
436/// in the BB are moved to a new block. The two blocks are connected by a
437/// conditional branch (with value of Cmp being the condition).
438/// Before:
439/// Head
440/// SplitBefore
441/// Tail
442/// After:
443/// Head
444/// if (Cond)
445/// ThenBlock
446/// SplitBefore
447/// Tail
448///
449/// If \p ThenBlock is not specified, a new block will be created for it.
450/// If \p Unreachable is true, the newly created block will end with
451/// UnreachableInst, otherwise it branches to Tail.
452/// Returns the NewBasicBlock's terminator.
453///
454/// Updates DTU and LI if given.
455LLVM_ABI Instruction *
457 bool Unreachable, MDNode *BranchWeights = nullptr,
458 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
459 BasicBlock *ThenBlock = nullptr);
460
462 bool Unreachable,
463 MDNode *BranchWeights = nullptr,
464 DomTreeUpdater *DTU = nullptr,
465 LoopInfo *LI = nullptr,
466 BasicBlock *ThenBlock = nullptr) {
467 return SplitBlockAndInsertIfThen(Cond, SplitBefore->getIterator(),
468 Unreachable, BranchWeights, DTU, LI,
469 ThenBlock);
470}
471
472/// Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false
473/// path of the branch.
474LLVM_ABI Instruction *
476 bool Unreachable, MDNode *BranchWeights = nullptr,
477 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
478 BasicBlock *ElseBlock = nullptr);
479
481 bool Unreachable,
482 MDNode *BranchWeights = nullptr,
483 DomTreeUpdater *DTU = nullptr,
484 LoopInfo *LI = nullptr,
485 BasicBlock *ElseBlock = nullptr) {
486 return SplitBlockAndInsertIfElse(Cond, SplitBefore->getIterator(),
487 Unreachable, BranchWeights, DTU, LI,
488 ElseBlock);
489}
490
491/// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
492/// but also creates the ElseBlock.
493/// Before:
494/// Head
495/// SplitBefore
496/// Tail
497/// After:
498/// Head
499/// if (Cond)
500/// ThenBlock
501/// else
502/// ElseBlock
503/// SplitBefore
504/// Tail
505///
506/// Updates DT if given.
508 Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm,
509 Instruction **ElseTerm, MDNode *BranchWeights = nullptr,
510 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
511
513 Instruction **ThenTerm,
514 Instruction **ElseTerm,
515 MDNode *BranchWeights = nullptr,
516 DomTreeUpdater *DTU = nullptr,
517 LoopInfo *LI = nullptr)
518{
519 SplitBlockAndInsertIfThenElse(Cond, SplitBefore->getIterator(), ThenTerm,
520 ElseTerm, BranchWeights, DTU, LI);
521}
522
523/// Split the containing block at the specified instruction - everything before
524/// SplitBefore stays in the old basic block, and the rest of the instructions
525/// in the BB are moved to a new block. The two blocks are connected by a
526/// conditional branch (with value of Cmp being the condition).
527/// Before:
528/// Head
529/// SplitBefore
530/// Tail
531/// After:
532/// Head
533/// if (Cond)
534/// TrueBlock
535/// else
536//// FalseBlock
537/// SplitBefore
538/// Tail
539///
540/// If \p ThenBlock is null, the resulting CFG won't contain the TrueBlock. If
541/// \p ThenBlock is non-null and points to non-null BasicBlock pointer, that
542/// block will be inserted as the TrueBlock. Otherwise a new block will be
543/// created. Likewise for the \p ElseBlock parameter.
544/// If \p UnreachableThen or \p UnreachableElse is true, the corresponding newly
545/// created blocks will end with UnreachableInst, otherwise with branches to
546/// Tail. The function will not modify existing basic blocks passed to it. The
547/// caller must ensure that Tail is reachable from Head.
548/// Returns the newly created blocks in \p ThenBlock and \p ElseBlock.
549/// Updates DTU and LI if given.
551 Value *Cond, BasicBlock::iterator SplitBefore, BasicBlock **ThenBlock,
552 BasicBlock **ElseBlock, bool UnreachableThen = false,
553 bool UnreachableElse = false, MDNode *BranchWeights = nullptr,
554 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
555
557 BasicBlock **ThenBlock,
558 BasicBlock **ElseBlock,
559 bool UnreachableThen = false,
560 bool UnreachableElse = false,
561 MDNode *BranchWeights = nullptr,
562 DomTreeUpdater *DTU = nullptr,
563 LoopInfo *LI = nullptr) {
564 SplitBlockAndInsertIfThenElse(Cond, SplitBefore->getIterator(), ThenBlock,
565 ElseBlock, UnreachableThen, UnreachableElse, BranchWeights, DTU, LI);
566}
567
568/// Insert a for (int i = 0; i < End; i++) loop structure (with the exception
569/// that \p End is assumed > 0, and thus not checked on entry) at \p
570/// SplitBefore. Returns the first insert point in the loop body, and the
571/// PHINode for the induction variable (i.e. "i" above).
572LLVM_ABI std::pair<Instruction *, Value *>
574
575/// Utility function for performing a given action on each lane of a vector
576/// with \p EC elements. To simplify porting legacy code, this defaults to
577/// unrolling the implied loop for non-scalable element counts, but this is
578/// not considered to be part of the contract of this routine, and is
579/// expected to change in the future. The callback takes as arguments an
580/// IRBuilder whose insert point is correctly set for instantiating the
581/// given index, and a value which is (at runtime) the index to access.
582/// This index *may* be a constant.
584 ElementCount EC, Type *IndexTy, BasicBlock::iterator InsertBefore,
585 std::function<void(IRBuilderBase &, Value *)> Func);
586
587/// Utility function for performing a given action on each lane of a vector
588/// with \p EVL effective length. EVL is assumed > 0. To simplify porting legacy
589/// code, this defaults to unrolling the implied loop for non-scalable element
590/// counts, but this is not considered to be part of the contract of this
591/// routine, and is expected to change in the future. The callback takes as
592/// arguments an IRBuilder whose insert point is correctly set for instantiating
593/// the given index, and a value which is (at runtime) the index to access. This
594/// index *may* be a constant.
596 Value *End, BasicBlock::iterator InsertBefore,
597 std::function<void(IRBuilderBase &, Value *)> Func);
598
599/// Check whether BB is the merge point of a if-region.
600/// If so, return the branch instruction that determines which entry into
601/// BB will be taken. Also, return by references the block that will be
602/// entered from if the condition is true, and the block that will be
603/// entered if the condition is false.
604///
605/// This does no checking to see if the true/false blocks have large or unsavory
606/// instructions in them.
607LLVM_ABI BranchInst *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
608 BasicBlock *&IfFalse);
609
610// Split critical edges where the source of the edge is an indirectbr
611// instruction. This isn't always possible, but we can handle some easy cases.
612// This is useful because MI is unable to split such critical edges,
613// which means it will not be able to sink instructions along those edges.
614// This is especially painful for indirect branches with many successors, where
615// we end up having to prepare all outgoing values in the origin block.
616//
617// Our normal algorithm for splitting critical edges requires us to update
618// the outgoing edges of the edge origin block, but for an indirectbr this
619// is hard, since it would require finding and updating the block addresses
620// the indirect branch uses. But if a block only has a single indirectbr
621// predecessor, with the others being regular branches, we can do it in a
622// different way.
623// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
624// We can split D into D0 and D1, where D0 contains only the PHIs from D,
625// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
626// create the following structure:
627// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
628// If BPI and BFI aren't non-null, BPI/BFI will be updated accordingly.
629// When `IgnoreBlocksWithoutPHI` is set to `true` critical edges leading to a
630// block without phi-instructions will not be split.
632 bool IgnoreBlocksWithoutPHI,
633 BranchProbabilityInfo *BPI = nullptr,
634 BlockFrequencyInfo *BFI = nullptr);
635
636// Utility function for inverting branch condition and for swapping its
637// successors
638LLVM_ABI void InvertBranch(BranchInst *PBI, IRBuilderBase &Builder);
639
640// Check whether the function only has simple terminator:
641// br/brcond/unreachable/ret
642LLVM_ABI bool hasOnlySimpleTerminator(const Function &F);
643
644/// Print BasicBlock \p BB as an operand or print "<nullptr>" if \p BB is a
645/// nullptr.
646LLVM_ABI Printable printBasicBlock(const BasicBlock *BB);
647
648} // end namespace llvm
649
650#endif // LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
This file declares the LLVM IR specialization of the GenericCycle templates.
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
static cl::opt< bool > SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), cl::Hidden, cl::desc("Split all critical edges during " "PHI elimination"))
const SmallVectorImpl< MachineOperand > & Cond
This file implements a set that has insertion order iteration characteristics.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
LLVM Basic Block Representation.
Definition BasicBlock.h:62
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Conditional or Unconditional Branch instruction.
Analysis providing branch probability information.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:165
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1078
Provides a lazy, caching interface for making common memory aliasing information queries,...
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
Return a value (possibly void), from a function.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Provides information about what library functions are available for the current target.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
self_iterator getIterator()
Definition ilist_node.h:123
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI bool IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB)
Check if we can prove that all paths starting from this block converge to a block that either has a @...
LLVM_ABI BranchInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
LLVM_ABI void detachDeadBlocks(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs=false)
Replace contents of every block in BBs with single unreachable instruction.
LLVM_ABI bool hasOnlySimpleTerminator(const Function &F)
LLVM_ABI ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
LLVM_ABI std::pair< Instruction *, Value * > SplitBlockAndInsertSimpleForLoop(Value *End, BasicBlock::iterator SplitBefore)
Insert a for (int i = 0; i < End; i++) loop structure (with the exception that End is assumed > 0,...
LLVM_ABI BasicBlock * splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName="")
Split the specified block at the specified instruction SplitPt.
LLVM_ABI Instruction * SplitBlockAndInsertIfElse(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ElseBlock=nullptr)
Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false path of the branch.
LLVM_ABI BasicBlock * SplitCallBrEdge(BasicBlock *CallBrBlock, BasicBlock *Succ, unsigned SuccIdx, DomTreeUpdater *DTU=nullptr, CycleInfo *CI=nullptr, LoopInfo *LI=nullptr, bool *UpdatedLI=nullptr)
Create a new intermediate target block for a callbr edge.
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI void ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V)
Replace all uses of an instruction (specified by BI) with a value, then remove and delete the origina...
LLVM_ABI BasicBlock * SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If it is known that an edge is critical, SplitKnownCriticalEdge can be called directly,...
LLVM_ABI bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr)
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Examine each PHI in the given block and delete it if it is dead.
LLVM_ABI void InvertBranch(BranchInst *PBI, IRBuilderBase &Builder)
LLVM_ABI bool EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete all basic blocks from F that are not reachable from its entry node.
LLVM_ABI bool MergeBlockSuccessorsIntoGivenBlocks(SmallPtrSetImpl< BasicBlock * > &MergeBlocks, Loop *L=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
Merge block(s) sucessors, if possible.
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI BasicBlock * ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ, LandingPadInst *OriginalPad=nullptr, PHINode *LandingPadReplacement=nullptr, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
Split the edge connect the specficed blocks in the case that Succ is an Exception Handling Block.
LLVM_ABI void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock * > Preds, const char *Suffix, const char *Suffix2, SmallVectorImpl< BasicBlock * > &NewBBs, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method transforms the landing pad, OrigBB, by introducing two new basic blocks into the function...
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
LLVM_ABI void createPHIsForSplitLoopExit(ArrayRef< BasicBlock * > Preds, BasicBlock *SplitBB, BasicBlock *DestBB)
When a loop exit edge is split, LCSSA form may require new PHIs in the new exit block.
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
LLVM_ABI bool FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred, BasicBlock *NewPred, PHINode *Until=nullptr)
Replaces all uses of OldPred with the NewPred block in all PHINodes in a block.
LLVM_ABI Printable printBasicBlock(const BasicBlock *BB)
Print BasicBlock BB as an operand or print "<nullptr>" if BB is a nullptr.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
LLVM_ABI void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ)
Sets the unwind edge of an instruction to a particular successor.
LLVM_ABI void SplitBlockAndInsertForEachLane(ElementCount EC, Type *IndexTy, BasicBlock::iterator InsertBefore, std::function< void(IRBuilderBase &, Value *)> Func)
Utility function for performing a given action on each lane of a vector with EC elements.
GenericCycleInfo< SSAContext > CycleInfo
Definition CycleInfo.h:23
Option class for critical edge splitting.
CriticalEdgeSplittingOptions(DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, PostDominatorTree *PDT=nullptr)
CriticalEdgeSplittingOptions & setMergeIdenticalEdges()
CriticalEdgeSplittingOptions & setKeepOneInputPHIs()
bool PreserveLoopSimplify
SplitCriticalEdge is guaranteed to preserve loop-simplify form if LI is provided.
CriticalEdgeSplittingOptions & unsetPreserveLoopSimplify()
CriticalEdgeSplittingOptions & setPreserveLCSSA()
CriticalEdgeSplittingOptions & setIgnoreUnreachableDests()