LLVM 22.0.0git
BasicBlockUtils.cpp
Go to the documentation of this file.
1//===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==//
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
15#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/Twine.h"
19#include "llvm/Analysis/CFG.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CFG.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DebugInfo.h"
29#include "llvm/IR/Dominators.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Type.h"
37#include "llvm/IR/User.h"
38#include "llvm/IR/Value.h"
39#include "llvm/IR/ValueHandle.h"
42#include "llvm/Support/Debug.h"
45#include <cassert>
46#include <cstdint>
47#include <string>
48#include <utility>
49#include <vector>
50
51using namespace llvm;
52
53#define DEBUG_TYPE "basicblock-utils"
54
56 "max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden,
57 cl::desc("Set the maximum path length when checking whether a basic block "
58 "is followed by a block that either has a terminating "
59 "deoptimizing call or is terminated with an unreachable"));
60
61/// Zap all the instructions in the block and replace them with an unreachable
62/// instruction and notify the basic block's successors that one of their
63/// predecessors is going away.
64static void
67 bool KeepOneInputPHIs) {
68 // Loop through all of our successors and make sure they know that one
69 // of their predecessors is going away.
70 SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
71 for (BasicBlock *Succ : successors(BB)) {
72 Succ->removePredecessor(BB, KeepOneInputPHIs);
73 if (Updates && UniqueSuccessors.insert(Succ).second)
74 Updates->push_back({DominatorTree::Delete, BB, Succ});
75 }
76
77 // Zap all the instructions in the block.
78 while (!BB->empty()) {
79 Instruction &I = BB->back();
80 // If this instruction is used, replace uses with an arbitrary value.
81 // Because control flow can't get here, we don't care what we replace the
82 // value with. Note that since this block is unreachable, and all values
83 // contained within it must dominate their uses, that all uses will
84 // eventually be removed (they are themselves dead).
85 if (!I.use_empty())
86 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
87 BB->back().eraseFromParent();
88 }
89 new UnreachableInst(BB->getContext(), BB);
90 assert(BB->size() == 1 && isa<UnreachableInst>(BB->getTerminator()) &&
91 "The successor list of BB isn't empty before "
92 "applying corresponding DTU updates.");
93}
94
96 for (const Instruction &I : *BB) {
98 if (CCI && (CCI->isLoop() || CCI->isEntry()))
99 return true;
100 }
101 return false;
102}
103
106 bool KeepOneInputPHIs) {
107 SmallPtrSet<BasicBlock *, 4> UniqueEHRetBlocksToDelete;
108 for (auto *BB : BBs) {
109 auto NonFirstPhiIt = BB->getFirstNonPHIIt();
110 if (NonFirstPhiIt != BB->end()) {
111 Instruction &I = *NonFirstPhiIt;
112 // Exception handling funclets need to be explicitly addressed.
113 // These funclets must begin with cleanuppad or catchpad and end with
114 // cleanupred or catchret. The return instructions can be in different
115 // basic blocks than the pad instruction. If we would only delete the
116 // first block, the we would have possible cleanupret and catchret
117 // instructions with poison arguments, which wouldn't be valid.
118 if (isa<FuncletPadInst>(I)) {
119 UniqueEHRetBlocksToDelete.clear();
120
121 for (User *User : I.users()) {
122 Instruction *ReturnInstr = dyn_cast<Instruction>(User);
123 // If we have a cleanupret or catchret block, replace it with just an
124 // unreachable. The other alternative, that may use a catchpad is a
125 // catchswitch. That does not need special handling for now.
126 if (isa<CatchReturnInst>(ReturnInstr) ||
127 isa<CleanupReturnInst>(ReturnInstr)) {
128 BasicBlock *ReturnInstrBB = ReturnInstr->getParent();
129 UniqueEHRetBlocksToDelete.insert(ReturnInstrBB);
130 }
131 }
132
133 for (BasicBlock *EHRetBB : UniqueEHRetBlocksToDelete)
134 emptyAndDetachBlock(EHRetBB, Updates, KeepOneInputPHIs);
135 }
136 }
137
138 UniqueEHRetBlocksToDelete.clear();
139
140 // Detaching and emptying the current basic block.
141 emptyAndDetachBlock(BB, Updates, KeepOneInputPHIs);
142 }
143}
144
146 bool KeepOneInputPHIs) {
147 DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
148}
149
151 bool KeepOneInputPHIs) {
152#ifndef NDEBUG
153 // Make sure that all predecessors of each dead block is also dead.
155 assert(Dead.size() == BBs.size() && "Duplicating blocks?");
156 for (auto *BB : Dead)
157 for (BasicBlock *Pred : predecessors(BB))
158 assert(Dead.count(Pred) && "All predecessors must be dead!");
159#endif
160
162 detachDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
163
164 if (DTU)
165 DTU->applyUpdates(Updates);
166
167 for (BasicBlock *BB : BBs)
168 if (DTU)
169 DTU->deleteBB(BB);
170 else
171 BB->eraseFromParent();
172}
173
175 bool KeepOneInputPHIs) {
177
178 // Mark all reachable blocks.
179 for (BasicBlock *BB : depth_first_ext(&F, Reachable))
180 (void)BB/* Mark all reachable blocks */;
181
182 // Collect all dead blocks.
183 std::vector<BasicBlock*> DeadBlocks;
184 for (BasicBlock &BB : F)
185 if (!Reachable.count(&BB))
186 DeadBlocks.push_back(&BB);
187
188 // Delete the dead blocks.
189 DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
190
191 return !DeadBlocks.empty();
192}
193
195 MemoryDependenceResults *MemDep) {
196 if (!isa<PHINode>(BB->begin()))
197 return false;
198
199 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
200 if (PN->getIncomingValue(0) != PN)
201 PN->replaceAllUsesWith(PN->getIncomingValue(0));
202 else
203 PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
204
205 if (MemDep)
206 MemDep->removeInstruction(PN); // Memdep updates AA itself.
207
208 PN->eraseFromParent();
209 }
210 return true;
211}
212
214 MemorySSAUpdater *MSSAU) {
215 // Recursively deleting a PHI may cause multiple PHIs to be deleted
216 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
218
219 bool Changed = false;
220 for (const auto &PHI : PHIs)
221 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHI.operator Value *()))
222 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
223
224 return Changed;
225}
226
228 LoopInfo *LI, MemorySSAUpdater *MSSAU,
230 bool PredecessorWithTwoSuccessors,
231 DominatorTree *DT) {
232 if (BB->hasAddressTaken())
233 return false;
234
235 // Can't merge if there are multiple predecessors, or no predecessors.
236 BasicBlock *PredBB = BB->getUniquePredecessor();
237 if (!PredBB) return false;
238
239 // Don't break self-loops.
240 if (PredBB == BB) return false;
241
242 // Don't break unwinding instructions or terminators with other side-effects.
243 Instruction *PTI = PredBB->getTerminator();
244 if (PTI->isSpecialTerminator() || PTI->mayHaveSideEffects())
245 return false;
246
247 // Can't merge if there are multiple distinct successors.
248 if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
249 return false;
250
251 // Currently only allow PredBB to have two predecessors, one being BB.
252 // Update BI to branch to BB's only successor instead of BB.
253 BranchInst *PredBB_BI;
254 BasicBlock *NewSucc = nullptr;
255 unsigned FallThruPath;
256 if (PredecessorWithTwoSuccessors) {
257 if (!(PredBB_BI = dyn_cast<BranchInst>(PTI)))
258 return false;
260 if (!BB_JmpI || !BB_JmpI->isUnconditional())
261 return false;
262 NewSucc = BB_JmpI->getSuccessor(0);
263 FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
264 }
265
266 // Can't merge if there is PHI loop.
267 for (PHINode &PN : BB->phis())
268 if (llvm::is_contained(PN.incoming_values(), &PN))
269 return false;
270
271 // Don't break if both the basic block and the predecessor contain loop or
272 // entry convergent intrinsics, since there may only be one convergence token
273 // per block.
276 return false;
277
278 LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
279 << PredBB->getName() << "\n");
280
281 // Begin by getting rid of unneeded PHIs.
282 SmallVector<AssertingVH<Value>, 4> IncomingValues;
283 if (isa<PHINode>(BB->front())) {
284 for (PHINode &PN : BB->phis())
285 if (!isa<PHINode>(PN.getIncomingValue(0)) ||
286 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
287 IncomingValues.push_back(PN.getIncomingValue(0));
288 FoldSingleEntryPHINodes(BB, MemDep);
289 }
290
291 if (DT) {
292 assert(!DTU && "cannot use both DT and DTU for updates");
293 DomTreeNode *PredNode = DT->getNode(PredBB);
294 DomTreeNode *BBNode = DT->getNode(BB);
295 if (PredNode) {
296 assert(BBNode && "PredNode unreachable but BBNode reachable?");
297 for (DomTreeNode *C : to_vector(BBNode->children()))
298 C->setIDom(PredNode);
299 }
300 }
301 // DTU update: Collect all the edges that exit BB.
302 // These dominator edges will be redirected from Pred.
303 std::vector<DominatorTree::UpdateType> Updates;
304 if (DTU) {
305 assert(!DT && "cannot use both DT and DTU for updates");
306 // To avoid processing the same predecessor more than once.
309 successors(PredBB));
310 Updates.reserve(Updates.size() + 2 * succ_size(BB) + 1);
311 // Add insert edges first. Experimentally, for the particular case of two
312 // blocks that can be merged, with a single successor and single predecessor
313 // respectively, it is beneficial to have all insert updates first. Deleting
314 // edges first may lead to unreachable blocks, followed by inserting edges
315 // making the blocks reachable again. Such DT updates lead to high compile
316 // times. We add inserts before deletes here to reduce compile time.
317 for (BasicBlock *SuccOfBB : successors(BB))
318 // This successor of BB may already be a PredBB's successor.
319 if (!SuccsOfPredBB.contains(SuccOfBB))
320 if (SeenSuccs.insert(SuccOfBB).second)
321 Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
322 SeenSuccs.clear();
323 for (BasicBlock *SuccOfBB : successors(BB))
324 if (SeenSuccs.insert(SuccOfBB).second)
325 Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
326 Updates.push_back({DominatorTree::Delete, PredBB, BB});
327 }
328
329 Instruction *STI = BB->getTerminator();
330 Instruction *Start = &*BB->begin();
331 // If there's nothing to move, mark the starting instruction as the last
332 // instruction in the block. Terminator instruction is handled separately.
333 if (Start == STI)
334 Start = PTI;
335
336 // Move all definitions in the successor to the predecessor...
337 PredBB->splice(PTI->getIterator(), BB, BB->begin(), STI->getIterator());
338
339 if (MSSAU)
340 MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
341
342 // Make all PHI nodes that referred to BB now refer to Pred as their
343 // source...
344 BB->replaceAllUsesWith(PredBB);
345
346 if (PredecessorWithTwoSuccessors) {
347 // Delete the unconditional branch from BB.
348 BB->back().eraseFromParent();
349
350 // Update branch in the predecessor.
351 PredBB_BI->setSuccessor(FallThruPath, NewSucc);
352 } else {
353 // Delete the unconditional branch from the predecessor.
354 PredBB->back().eraseFromParent();
355
356 // Move terminator instruction.
357 BB->back().moveBeforePreserving(*PredBB, PredBB->end());
358
359 // Terminator may be a memory accessing instruction too.
360 if (MSSAU)
362 MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
363 MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
364 }
365 // Add unreachable to now empty BB.
366 new UnreachableInst(BB->getContext(), BB);
367
368 // Inherit predecessors name if it exists.
369 if (!PredBB->hasName())
370 PredBB->takeName(BB);
371
372 if (LI)
373 LI->removeBlock(BB);
374
375 if (MemDep)
377
378 if (DTU)
379 DTU->applyUpdates(Updates);
380
381 if (DT) {
382 assert(succ_empty(BB) &&
383 "successors should have been transferred to PredBB");
384 DT->eraseNode(BB);
385 }
386
387 // Finally, erase the old block and update dominator info.
388 DeleteDeadBlock(BB, DTU);
389
390 return true;
391}
392
395 LoopInfo *LI) {
396 assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
397
398 bool BlocksHaveBeenMerged = false;
399 while (!MergeBlocks.empty()) {
400 BasicBlock *BB = *MergeBlocks.begin();
401 BasicBlock *Dest = BB->getSingleSuccessor();
402 if (Dest && (!L || L->contains(Dest))) {
403 BasicBlock *Fold = Dest->getUniquePredecessor();
404 (void)Fold;
405 if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
406 assert(Fold == BB &&
407 "Expecting BB to be unique predecessor of the Dest block");
408 MergeBlocks.erase(Dest);
409 BlocksHaveBeenMerged = true;
410 } else
411 MergeBlocks.erase(BB);
412 } else
413 MergeBlocks.erase(BB);
414 }
415 return BlocksHaveBeenMerged;
416}
417
418/// Remove redundant instructions within sequences of consecutive dbg.value
419/// instructions. This is done using a backward scan to keep the last dbg.value
420/// describing a specific variable/fragment.
421///
422/// BackwardScan strategy:
423/// ----------------------
424/// Given a sequence of consecutive DbgValueInst like this
425///
426/// dbg.value ..., "x", FragmentX1 (*)
427/// dbg.value ..., "y", FragmentY1
428/// dbg.value ..., "x", FragmentX2
429/// dbg.value ..., "x", FragmentX1 (**)
430///
431/// then the instruction marked with (*) can be removed (it is guaranteed to be
432/// obsoleted by the instruction marked with (**) as the latter instruction is
433/// describing the same variable using the same fragment info).
434///
435/// Possible improvements:
436/// - Check fully overlapping fragments and not only identical fragments.
440 for (auto &I : reverse(*BB)) {
441 for (DbgVariableRecord &DVR :
442 reverse(filterDbgVars(I.getDbgRecordRange()))) {
443 DebugVariable Key(DVR.getVariable(), DVR.getExpression(),
444 DVR.getDebugLoc()->getInlinedAt());
445 auto R = VariableSet.insert(Key);
446 // If the same variable fragment is described more than once it is enough
447 // to keep the last one (i.e. the first found since we for reverse
448 // iteration).
449 if (R.second)
450 continue;
451
452 if (DVR.isDbgAssign()) {
453 // Don't delete dbg.assign intrinsics that are linked to instructions.
454 if (!at::getAssignmentInsts(&DVR).empty())
455 continue;
456 // Unlinked dbg.assign intrinsics can be treated like dbg.values.
457 }
458
459 ToBeRemoved.push_back(&DVR);
460 }
461 // Sequence with consecutive dbg.value instrs ended. Clear the map to
462 // restart identifying redundant instructions if case we find another
463 // dbg.value sequence.
464 VariableSet.clear();
465 }
466
467 for (auto &DVR : ToBeRemoved)
468 DVR->eraseFromParent();
469
470 return !ToBeRemoved.empty();
471}
472
473/// Remove redundant dbg.value instructions using a forward scan. This can
474/// remove a dbg.value instruction that is redundant due to indicating that a
475/// variable has the same value as already being indicated by an earlier
476/// dbg.value.
477///
478/// ForwardScan strategy:
479/// ---------------------
480/// Given two identical dbg.value instructions, separated by a block of
481/// instructions that isn't describing the same variable, like this
482///
483/// dbg.value X1, "x", FragmentX1 (**)
484/// <block of instructions, none being "dbg.value ..., "x", ...">
485/// dbg.value X1, "x", FragmentX1 (*)
486///
487/// then the instruction marked with (*) can be removed. Variable "x" is already
488/// described as being mapped to the SSA value X1.
489///
490/// Possible improvements:
491/// - Keep track of non-overlapping fragments.
493 bool RemovedAny = false;
495 std::pair<SmallVector<Value *, 4>, DIExpression *>, 4>
496 VariableMap;
497 for (auto &I : *BB) {
498 for (DbgVariableRecord &DVR :
499 make_early_inc_range(filterDbgVars(I.getDbgRecordRange()))) {
500 if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
501 continue;
502 DebugVariable Key(DVR.getVariable(), std::nullopt,
503 DVR.getDebugLoc()->getInlinedAt());
504 auto [VMI, Inserted] = VariableMap.try_emplace(Key);
505 // A dbg.assign with no linked instructions can be treated like a
506 // dbg.value (i.e. can be deleted).
507 bool IsDbgValueKind =
508 (!DVR.isDbgAssign() || at::getAssignmentInsts(&DVR).empty());
509
510 // Update the map if we found a new value/expression describing the
511 // variable, or if the variable wasn't mapped already.
512 SmallVector<Value *, 4> Values(DVR.location_ops());
513 if (Inserted || VMI->second.first != Values ||
514 VMI->second.second != DVR.getExpression()) {
515 if (IsDbgValueKind)
516 VMI->second = {Values, DVR.getExpression()};
517 else
518 VMI->second = {Values, nullptr};
519 continue;
520 }
521 // Don't delete dbg.assign intrinsics that are linked to instructions.
522 if (!IsDbgValueKind)
523 continue;
524 // Found an identical mapping. Remember the instruction for later removal.
525 DVR.eraseFromParent();
526 RemovedAny = true;
527 }
528 }
529
530 return RemovedAny;
531}
532
533/// Remove redundant undef dbg.assign intrinsic from an entry block using a
534/// forward scan.
535/// Strategy:
536/// ---------------------
537/// Scanning forward, delete dbg.assign intrinsics iff they are undef, not
538/// linked to an intrinsic, and don't share an aggregate variable with a debug
539/// intrinsic that didn't meet the criteria. In other words, undef dbg.assigns
540/// that come before non-undef debug intrinsics for the variable are
541/// deleted. Given:
542///
543/// dbg.assign undef, "x", FragmentX1 (*)
544/// <block of instructions, none being "dbg.value ..., "x", ...">
545/// dbg.value %V, "x", FragmentX2
546/// <block of instructions, none being "dbg.value ..., "x", ...">
547/// dbg.assign undef, "x", FragmentX1
548///
549/// then (only) the instruction marked with (*) can be removed.
550/// Possible improvements:
551/// - Keep track of non-overlapping fragments.
553 assert(BB->isEntryBlock() && "expected entry block");
554 bool RemovedAny = false;
555 DenseSet<DebugVariableAggregate> SeenDefForAggregate;
556
557 // Remove undef dbg.assign intrinsics that are encountered before
558 // any non-undef intrinsics from the entry block.
559 for (auto &I : *BB) {
560 for (DbgVariableRecord &DVR :
561 make_early_inc_range(filterDbgVars(I.getDbgRecordRange()))) {
562 if (!DVR.isDbgValue() && !DVR.isDbgAssign())
563 continue;
564 bool IsDbgValueKind =
565 (DVR.isDbgValue() || at::getAssignmentInsts(&DVR).empty());
566
567 DebugVariableAggregate Aggregate(&DVR);
568 if (!SeenDefForAggregate.contains(Aggregate)) {
569 bool IsKill = DVR.isKillLocation() && IsDbgValueKind;
570 if (!IsKill) {
571 SeenDefForAggregate.insert(Aggregate);
572 } else if (DVR.isDbgAssign()) {
573 DVR.eraseFromParent();
574 RemovedAny = true;
575 }
576 }
577 }
578 }
579
580 return RemovedAny;
581}
582
584 bool MadeChanges = false;
585 // By using the "backward scan" strategy before the "forward scan" strategy we
586 // can remove both dbg.value (2) and (3) in a situation like this:
587 //
588 // (1) dbg.value V1, "x", DIExpression()
589 // ...
590 // (2) dbg.value V2, "x", DIExpression()
591 // (3) dbg.value V1, "x", DIExpression()
592 //
593 // The backward scan will remove (2), it is made obsolete by (3). After
594 // getting (2) out of the way, the foward scan will remove (3) since "x"
595 // already is described as having the value V1 at (1).
597 if (BB->isEntryBlock() &&
599 MadeChanges |= removeUndefDbgAssignsFromEntryBlock(BB);
601
602 if (MadeChanges)
603 LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
604 << BB->getName() << "\n");
605 return MadeChanges;
606}
607
609 Instruction &I = *BI;
610 // Replaces all of the uses of the instruction with uses of the value
611 I.replaceAllUsesWith(V);
612
613 // Make sure to propagate a name if there is one already.
614 if (I.hasName() && !V->hasName())
615 V->takeName(&I);
616
617 // Delete the unnecessary instruction now...
618 BI = BI->eraseFromParent();
619}
620
622 Instruction *I) {
623 assert(I->getParent() == nullptr &&
624 "ReplaceInstWithInst: Instruction already inserted into basic block!");
625
626 // Copy debug location to newly added instruction, if it wasn't already set
627 // by the caller.
628 if (!I->getDebugLoc())
629 I->setDebugLoc(BI->getDebugLoc());
630
631 // Insert the new instruction into the basic block...
632 BasicBlock::iterator New = I->insertInto(BB, BI);
633
634 // Replace all uses of the old instruction, and delete it.
636
637 // Move BI back to point to the newly inserted instruction
638 BI = New;
639}
640
642 // Remember visited blocks to avoid infinite loop
644 unsigned Depth = 0;
646 VisitedBlocks.insert(BB).second) {
649 return true;
650 BB = BB->getUniqueSuccessor();
651 }
652 return false;
653}
654
656 BasicBlock::iterator BI(From);
657 ReplaceInstWithInst(From->getParent(), BI, To);
658}
659
661 LoopInfo *LI, MemorySSAUpdater *MSSAU,
662 const Twine &BBName) {
663 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
664
665 Instruction *LatchTerm = BB->getTerminator();
666
669
670 if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
671 // If this is a critical edge, let SplitKnownCriticalEdge do it.
672 return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
673 }
674
675 // If the edge isn't critical, then BB has a single successor or Succ has a
676 // single pred. Split the block.
677 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
678 // If the successor only has a single pred, split the top of the successor
679 // block.
680 assert(SP == BB && "CFG broken");
681 (void)SP;
682 return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName,
683 /*Before=*/true);
684 }
685
686 // Otherwise, if BB has a single successor, split it at the bottom of the
687 // block.
688 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
689 "Should have a single succ!");
690 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
691}
692
693/// Helper function to update the cycle or loop information after inserting a
694/// new block between a callbr instruction and one of its target blocks. Adds
695/// the new block to the innermost cycle or loop that the callbr instruction and
696/// the original target block share.
697/// \p LCI cycle or loop information to update
698/// \p CallBrBlock block containing the callbr instruction
699/// \p CallBrTarget new target block of the callbr instruction
700/// \p Succ original target block of the callbr instruction
701template <typename TI, typename T>
702static bool updateCycleLoopInfo(TI *LCI, BasicBlock *CallBrBlock,
703 BasicBlock *CallBrTarget, BasicBlock *Succ) {
704 static_assert(std::is_same_v<TI, CycleInfo> || std::is_same_v<TI, LoopInfo>,
705 "type must be CycleInfo or LoopInfo");
706 if (!LCI)
707 return false;
708
709 T *LC;
710 if constexpr (std::is_same_v<TI, CycleInfo>)
711 LC = LCI->getSmallestCommonCycle(CallBrBlock, Succ);
712 else
713 LC = LCI->getSmallestCommonLoop(CallBrBlock, Succ);
714 if (!LC)
715 return false;
716
717 if constexpr (std::is_same_v<TI, CycleInfo>)
718 LCI->addBlockToCycle(CallBrTarget, LC);
719 else
720 LC->addBasicBlockToLoop(CallBrTarget, *LCI);
721
722 return true;
723}
724
726 unsigned SuccIdx, DomTreeUpdater *DTU,
727 CycleInfo *CI, LoopInfo *LI,
728 bool *UpdatedLI) {
729 CallBrInst *CallBr = dyn_cast<CallBrInst>(CallBrBlock->getTerminator());
730 assert(CallBr && "expected callbr terminator");
731 assert(SuccIdx < CallBr->getNumSuccessors() &&
732 Succ == CallBr->getSuccessor(SuccIdx) && "invalid successor index");
733
734 // Create a new block between callbr and the specified successor.
735 // splitBlockBefore cannot be re-used here since it cannot split if the split
736 // point is a PHI node (because BasicBlock::splitBasicBlockBefore cannot
737 // handle that). But we don't need to rewire every part of a potential PHI
738 // node. We only care about the edge between CallBrBlock and the original
739 // successor.
740 BasicBlock *CallBrTarget =
741 BasicBlock::Create(CallBrBlock->getContext(),
742 CallBrBlock->getName() + ".target." + Succ->getName(),
743 CallBrBlock->getParent());
744 // Rewire control flow from the new target block to the original successor.
745 Succ->replacePhiUsesWith(CallBrBlock, CallBrTarget);
746 // Rewire control flow from callbr to the new target block.
747 CallBr->setSuccessor(SuccIdx, CallBrTarget);
748 // Jump from the new target block to the original successor.
749 BranchInst::Create(Succ, CallBrTarget);
750
751 bool Updated =
752 updateCycleLoopInfo<LoopInfo, Loop>(LI, CallBrBlock, CallBrTarget, Succ);
753 if (UpdatedLI)
754 *UpdatedLI = Updated;
755 updateCycleLoopInfo<CycleInfo, Cycle>(CI, CallBrBlock, CallBrTarget, Succ);
756 if (DTU) {
757 DTU->applyUpdates({{DominatorTree::Insert, CallBrBlock, CallBrTarget}});
758 if (DTU->getDomTree().dominates(CallBrBlock, Succ)) {
759 if (!is_contained(successors(CallBrBlock), Succ))
760 DTU->applyUpdates({{DominatorTree::Delete, CallBrBlock, Succ}});
761 DTU->applyUpdates({{DominatorTree::Insert, CallBrTarget, Succ}});
762 }
763 }
764
765 return CallBrTarget;
766}
767
769 if (auto *II = dyn_cast<InvokeInst>(TI))
770 II->setUnwindDest(Succ);
771 else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
772 CS->setUnwindDest(Succ);
773 else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
774 CR->setUnwindDest(Succ);
775 else
776 llvm_unreachable("unexpected terminator instruction");
777}
778
780 BasicBlock *NewPred, PHINode *Until) {
781 int BBIdx = 0;
782 for (PHINode &PN : DestBB->phis()) {
783 // We manually update the LandingPadReplacement PHINode and it is the last
784 // PHI Node. So, if we find it, we are done.
785 if (Until == &PN)
786 break;
787
788 // Reuse the previous value of BBIdx if it lines up. In cases where we
789 // have multiple phi nodes with *lots* of predecessors, this is a speed
790 // win because we don't have to scan the PHI looking for TIBB. This
791 // happens because the BB list of PHI nodes are usually in the same
792 // order.
793 if (PN.getIncomingBlock(BBIdx) != OldPred)
794 BBIdx = PN.getBasicBlockIndex(OldPred);
795
796 assert(BBIdx != -1 && "Invalid PHI Index!");
797 PN.setIncomingBlock(BBIdx, NewPred);
798 }
799}
800
802 LandingPadInst *OriginalPad,
803 PHINode *LandingPadReplacement,
805 const Twine &BBName) {
806
807 auto PadInst = Succ->getFirstNonPHIIt();
808 if (!LandingPadReplacement && !PadInst->isEHPad())
809 return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
810
811 auto *LI = Options.LI;
813 // Check if extra modifications will be required to preserve loop-simplify
814 // form after splitting. If it would require splitting blocks with IndirectBr
815 // terminators, bail out if preserving loop-simplify form is requested.
816 if (Options.PreserveLoopSimplify && LI) {
817 if (Loop *BBLoop = LI->getLoopFor(BB)) {
818
819 // The only way that we can break LoopSimplify form by splitting a
820 // critical edge is when there exists some edge from BBLoop to Succ *and*
821 // the only edge into Succ from outside of BBLoop is that of NewBB after
822 // the split. If the first isn't true, then LoopSimplify still holds,
823 // NewBB is the new exit block and it has no non-loop predecessors. If the
824 // second isn't true, then Succ was not in LoopSimplify form prior to
825 // the split as it had a non-loop predecessor. In both of these cases,
826 // the predecessor must be directly in BBLoop, not in a subloop, or again
827 // LoopSimplify doesn't hold.
828 for (BasicBlock *P : predecessors(Succ)) {
829 if (P == BB)
830 continue; // The new block is known.
831 if (LI->getLoopFor(P) != BBLoop) {
832 // Loop is not in LoopSimplify form, no need to re simplify after
833 // splitting edge.
834 LoopPreds.clear();
835 break;
836 }
837 LoopPreds.push_back(P);
838 }
839 // Loop-simplify form can be preserved, if we can split all in-loop
840 // predecessors.
841 if (any_of(LoopPreds, [](BasicBlock *Pred) {
842 return isa<IndirectBrInst>(Pred->getTerminator());
843 })) {
844 return nullptr;
845 }
846 }
847 }
848
849 auto *NewBB =
850 BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
851 setUnwindEdgeTo(BB->getTerminator(), NewBB);
852 updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
853
854 if (LandingPadReplacement) {
855 auto *NewLP = OriginalPad->clone();
856 auto *Terminator = BranchInst::Create(Succ, NewBB);
857 NewLP->insertBefore(Terminator->getIterator());
858 LandingPadReplacement->addIncoming(NewLP, NewBB);
859 } else {
860 Value *ParentPad = nullptr;
861 if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
862 ParentPad = FuncletPad->getParentPad();
863 else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
864 ParentPad = CatchSwitch->getParentPad();
865 else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
866 ParentPad = CleanupPad->getParentPad();
867 else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
868 ParentPad = LandingPad->getParent();
869 else
870 llvm_unreachable("handling for other EHPads not implemented yet");
871
872 auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
873 CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
874 }
875
876 auto *DT = Options.DT;
877 auto *MSSAU = Options.MSSAU;
878 if (!DT && !LI)
879 return NewBB;
880
881 if (DT) {
882 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
884
885 Updates.push_back({DominatorTree::Insert, BB, NewBB});
886 Updates.push_back({DominatorTree::Insert, NewBB, Succ});
887 Updates.push_back({DominatorTree::Delete, BB, Succ});
888
889 DTU.applyUpdates(Updates);
890 DTU.flush();
891
892 if (MSSAU) {
893 MSSAU->applyUpdates(Updates, *DT);
894 if (VerifyMemorySSA)
895 MSSAU->getMemorySSA()->verifyMemorySSA();
896 }
897 }
898
899 if (LI) {
900 if (Loop *BBLoop = LI->getLoopFor(BB)) {
901 // If one or the other blocks were not in a loop, the new block is not
902 // either, and thus LI doesn't need to be updated.
903 if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
904 if (BBLoop == SuccLoop) {
905 // Both in the same loop, the NewBB joins loop.
906 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
907 } else if (BBLoop->contains(SuccLoop)) {
908 // Edge from an outer loop to an inner loop. Add to the outer loop.
909 BBLoop->addBasicBlockToLoop(NewBB, *LI);
910 } else if (SuccLoop->contains(BBLoop)) {
911 // Edge from an inner loop to an outer loop. Add to the outer loop.
912 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
913 } else {
914 // Edge from two loops with no containment relation. Because these
915 // are natural loops, we know that the destination block must be the
916 // header of its loop (adding a branch into a loop elsewhere would
917 // create an irreducible loop).
918 assert(SuccLoop->getHeader() == Succ &&
919 "Should not create irreducible loops!");
920 if (Loop *P = SuccLoop->getParentLoop())
921 P->addBasicBlockToLoop(NewBB, *LI);
922 }
923 }
924
925 // If BB is in a loop and Succ is outside of that loop, we may need to
926 // update LoopSimplify form and LCSSA form.
927 if (!BBLoop->contains(Succ)) {
928 assert(!BBLoop->contains(NewBB) &&
929 "Split point for loop exit is contained in loop!");
930
931 // Update LCSSA form in the newly created exit block.
932 if (Options.PreserveLCSSA) {
933 createPHIsForSplitLoopExit(BB, NewBB, Succ);
934 }
935
936 if (!LoopPreds.empty()) {
938 Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
939 if (Options.PreserveLCSSA)
940 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
941 }
942 }
943 }
944 }
945
946 return NewBB;
947}
948
950 BasicBlock *SplitBB, BasicBlock *DestBB) {
951 // SplitBB shouldn't have anything non-trivial in it yet.
952 assert((&*SplitBB->getFirstNonPHIIt() == SplitBB->getTerminator() ||
953 SplitBB->isLandingPad()) &&
954 "SplitBB has non-PHI nodes!");
955
956 // For each PHI in the destination block.
957 for (PHINode &PN : DestBB->phis()) {
958 int Idx = PN.getBasicBlockIndex(SplitBB);
959 assert(Idx >= 0 && "Invalid Block Index");
960 Value *V = PN.getIncomingValue(Idx);
961
962 // If the input is a PHI which already satisfies LCSSA, don't create
963 // a new one.
964 if (const PHINode *VP = dyn_cast<PHINode>(V))
965 if (VP->getParent() == SplitBB)
966 continue;
967
968 // Otherwise a new PHI is needed. Create one and populate it.
969 PHINode *NewPN = PHINode::Create(PN.getType(), Preds.size(), "split");
970 BasicBlock::iterator InsertPos =
971 SplitBB->isLandingPad() ? SplitBB->begin()
972 : SplitBB->getTerminator()->getIterator();
973 NewPN->insertBefore(InsertPos);
974 for (BasicBlock *BB : Preds)
975 NewPN->addIncoming(V, BB);
976
977 // Update the original PHI.
978 PN.setIncomingValue(Idx, NewPN);
979 }
980}
981
982unsigned
985 unsigned NumBroken = 0;
986 for (BasicBlock &BB : F) {
987 Instruction *TI = BB.getTerminator();
988 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
989 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
990 if (SplitCriticalEdge(TI, i, Options))
991 ++NumBroken;
992 }
993 return NumBroken;
994}
995
998 LoopInfo *LI, MemorySSAUpdater *MSSAU,
999 const Twine &BBName, bool Before) {
1000 if (Before) {
1001 DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1002 return splitBlockBefore(Old, SplitPt,
1003 DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU,
1004 BBName);
1005 }
1006 BasicBlock::iterator SplitIt = SplitPt;
1007 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
1008 ++SplitIt;
1009 assert(SplitIt != SplitPt->getParent()->end());
1010 }
1011 std::string Name = BBName.str();
1012 BasicBlock *New = Old->splitBasicBlock(
1013 SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
1014
1015 // The new block lives in whichever loop the old one did. This preserves
1016 // LCSSA as well, because we force the split point to be after any PHI nodes.
1017 if (LI)
1018 if (Loop *L = LI->getLoopFor(Old))
1019 L->addBasicBlockToLoop(New, *LI);
1020
1021 if (DTU) {
1023 // Old dominates New. New node dominates all other nodes dominated by Old.
1024 SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld;
1025 Updates.push_back({DominatorTree::Insert, Old, New});
1026 Updates.reserve(Updates.size() + 2 * succ_size(New));
1027 for (BasicBlock *SuccessorOfOld : successors(New))
1028 if (UniqueSuccessorsOfOld.insert(SuccessorOfOld).second) {
1029 Updates.push_back({DominatorTree::Insert, New, SuccessorOfOld});
1030 Updates.push_back({DominatorTree::Delete, Old, SuccessorOfOld});
1031 }
1032
1033 DTU->applyUpdates(Updates);
1034 } else if (DT)
1035 // Old dominates New. New node dominates all other nodes dominated by Old.
1036 if (DomTreeNode *OldNode = DT->getNode(Old)) {
1037 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1038
1039 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
1040 for (DomTreeNode *I : Children)
1041 DT->changeImmediateDominator(I, NewNode);
1042 }
1043
1044 // Move MemoryAccesses still tracked in Old, but part of New now.
1045 // Update accesses in successor blocks accordingly.
1046 if (MSSAU)
1047 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
1048
1049 return New;
1050}
1051
1053 DominatorTree *DT, LoopInfo *LI,
1054 MemorySSAUpdater *MSSAU, const Twine &BBName,
1055 bool Before) {
1056 return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName,
1057 Before);
1058}
1060 DomTreeUpdater *DTU, LoopInfo *LI,
1061 MemorySSAUpdater *MSSAU, const Twine &BBName,
1062 bool Before) {
1063 return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName,
1064 Before);
1065}
1066
1068 DomTreeUpdater *DTU, LoopInfo *LI,
1069 MemorySSAUpdater *MSSAU,
1070 const Twine &BBName) {
1071
1072 BasicBlock::iterator SplitIt = SplitPt;
1073 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
1074 ++SplitIt;
1075 std::string Name = BBName.str();
1076 BasicBlock *New = Old->splitBasicBlock(
1077 SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
1078 /* Before=*/true);
1079
1080 // The new block lives in whichever loop the old one did. This preserves
1081 // LCSSA as well, because we force the split point to be after any PHI nodes.
1082 if (LI)
1083 if (Loop *L = LI->getLoopFor(Old))
1084 L->addBasicBlockToLoop(New, *LI);
1085
1086 if (DTU) {
1088 // New dominates Old. The predecessor nodes of the Old node dominate
1089 // New node.
1090 SmallPtrSet<BasicBlock *, 8> UniquePredecessorsOfOld;
1091 DTUpdates.push_back({DominatorTree::Insert, New, Old});
1092 DTUpdates.reserve(DTUpdates.size() + 2 * pred_size(New));
1093 for (BasicBlock *PredecessorOfOld : predecessors(New))
1094 if (UniquePredecessorsOfOld.insert(PredecessorOfOld).second) {
1095 DTUpdates.push_back({DominatorTree::Insert, PredecessorOfOld, New});
1096 DTUpdates.push_back({DominatorTree::Delete, PredecessorOfOld, Old});
1097 }
1098
1099 DTU->applyUpdates(DTUpdates);
1100
1101 // Move MemoryAccesses still tracked in Old, but part of New now.
1102 // Update accesses in successor blocks accordingly.
1103 if (MSSAU) {
1104 MSSAU->applyUpdates(DTUpdates, DTU->getDomTree());
1105 if (VerifyMemorySSA)
1106 MSSAU->getMemorySSA()->verifyMemorySSA();
1107 }
1108 }
1109 return New;
1110}
1111
1112/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
1113/// Invalidates DFS Numbering when DTU or DT is provided.
1116 DomTreeUpdater *DTU, DominatorTree *DT,
1117 LoopInfo *LI, MemorySSAUpdater *MSSAU,
1118 bool PreserveLCSSA, bool &HasLoopExit) {
1119 // Update dominator tree if available.
1120 if (DTU) {
1121 // Recalculation of DomTree is needed when updating a forward DomTree and
1122 // the Entry BB is replaced.
1123 if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
1124 // The entry block was removed and there is no external interface for
1125 // the dominator tree to be notified of this change. In this corner-case
1126 // we recalculate the entire tree.
1127 DTU->recalculate(*NewBB->getParent());
1128 } else {
1129 // Split block expects NewBB to have a non-empty set of predecessors.
1131 SmallPtrSet<BasicBlock *, 8> UniquePreds;
1132 Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
1133 Updates.reserve(Updates.size() + 2 * Preds.size());
1134 for (auto *Pred : Preds)
1135 if (UniquePreds.insert(Pred).second) {
1136 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
1137 Updates.push_back({DominatorTree::Delete, Pred, OldBB});
1138 }
1139 DTU->applyUpdates(Updates);
1140 }
1141 } else if (DT) {
1142 if (OldBB == DT->getRootNode()->getBlock()) {
1143 assert(NewBB->isEntryBlock());
1144 DT->setNewRoot(NewBB);
1145 } else {
1146 // Split block expects NewBB to have a non-empty set of predecessors.
1147 DT->splitBlock(NewBB);
1148 }
1149 }
1150
1151 // Update MemoryPhis after split if MemorySSA is available
1152 if (MSSAU)
1153 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
1154
1155 // The rest of the logic is only relevant for updating the loop structures.
1156 if (!LI)
1157 return;
1158
1159 if (DTU && DTU->hasDomTree())
1160 DT = &DTU->getDomTree();
1161 assert(DT && "DT should be available to update LoopInfo!");
1162 Loop *L = LI->getLoopFor(OldBB);
1163
1164 // If we need to preserve loop analyses, collect some information about how
1165 // this split will affect loops.
1166 bool IsLoopEntry = !!L;
1167 bool SplitMakesNewLoopHeader = false;
1168 for (BasicBlock *Pred : Preds) {
1169 // Preds that are not reachable from entry should not be used to identify if
1170 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
1171 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
1172 // as true and make the NewBB the header of some loop. This breaks LI.
1173 if (!DT->isReachableFromEntry(Pred))
1174 continue;
1175 // If we need to preserve LCSSA, determine if any of the preds is a loop
1176 // exit.
1177 if (PreserveLCSSA)
1178 if (Loop *PL = LI->getLoopFor(Pred))
1179 if (!PL->contains(OldBB))
1180 HasLoopExit = true;
1181
1182 // If we need to preserve LoopInfo, note whether any of the preds crosses
1183 // an interesting loop boundary.
1184 if (!L)
1185 continue;
1186 if (L->contains(Pred))
1187 IsLoopEntry = false;
1188 else
1189 SplitMakesNewLoopHeader = true;
1190 }
1191
1192 // Unless we have a loop for OldBB, nothing else to do here.
1193 if (!L)
1194 return;
1195
1196 if (IsLoopEntry) {
1197 // Add the new block to the nearest enclosing loop (and not an adjacent
1198 // loop). To find this, examine each of the predecessors and determine which
1199 // loops enclose them, and select the most-nested loop which contains the
1200 // loop containing the block being split.
1201 Loop *InnermostPredLoop = nullptr;
1202 for (BasicBlock *Pred : Preds) {
1203 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
1204 // Seek a loop which actually contains the block being split (to avoid
1205 // adjacent loops).
1206 while (PredLoop && !PredLoop->contains(OldBB))
1207 PredLoop = PredLoop->getParentLoop();
1208
1209 // Select the most-nested of these loops which contains the block.
1210 if (PredLoop && PredLoop->contains(OldBB) &&
1211 (!InnermostPredLoop ||
1212 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
1213 InnermostPredLoop = PredLoop;
1214 }
1215 }
1216
1217 if (InnermostPredLoop)
1218 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
1219 } else {
1220 L->addBasicBlockToLoop(NewBB, *LI);
1221 if (SplitMakesNewLoopHeader)
1222 L->moveToHeader(NewBB);
1223 }
1224}
1225
1226/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
1227/// This also updates AliasAnalysis, if available.
1228static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
1230 bool HasLoopExit) {
1231 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
1233 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
1234 PHINode *PN = cast<PHINode>(I++);
1235
1236 // Check to see if all of the values coming in are the same. If so, we
1237 // don't need to create a new PHI node, unless it's needed for LCSSA.
1238 Value *InVal = nullptr;
1239 if (!HasLoopExit) {
1240 InVal = PN->getIncomingValueForBlock(Preds[0]);
1241 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1242 if (!PredSet.count(PN->getIncomingBlock(i)))
1243 continue;
1244 if (!InVal)
1245 InVal = PN->getIncomingValue(i);
1246 else if (InVal != PN->getIncomingValue(i)) {
1247 InVal = nullptr;
1248 break;
1249 }
1250 }
1251 }
1252
1253 if (InVal) {
1254 // If all incoming values for the new PHI would be the same, just don't
1255 // make a new PHI. Instead, just remove the incoming values from the old
1256 // PHI.
1258 [&](unsigned Idx) {
1259 return PredSet.contains(PN->getIncomingBlock(Idx));
1260 },
1261 /* DeletePHIIfEmpty */ false);
1262
1263 // Add an incoming value to the PHI node in the loop for the preheader
1264 // edge.
1265 PN->addIncoming(InVal, NewBB);
1266 continue;
1267 }
1268
1269 // If the values coming into the block are not the same, we need a new
1270 // PHI.
1271 // Create the new PHI node, insert it into NewBB at the end of the block
1272 PHINode *NewPHI =
1273 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI->getIterator());
1274
1275 // NOTE! This loop walks backwards for a reason! First off, this minimizes
1276 // the cost of removal if we end up removing a large number of values, and
1277 // second off, this ensures that the indices for the incoming values aren't
1278 // invalidated when we remove one.
1279 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
1280 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
1281 if (PredSet.count(IncomingBB)) {
1282 Value *V = PN->removeIncomingValue(i, false);
1283 NewPHI->addIncoming(V, IncomingBB);
1284 }
1285 }
1286
1287 PN->addIncoming(NewPHI, NewBB);
1288 }
1289}
1290
1292 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1293 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1294 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1295 MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
1296
1297static BasicBlock *
1299 const char *Suffix, DomTreeUpdater *DTU,
1300 DominatorTree *DT, LoopInfo *LI,
1301 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1302 // Do not attempt to split that which cannot be split.
1303 if (!BB->canSplitPredecessors())
1304 return nullptr;
1305
1306 // For the landingpads we need to act a bit differently.
1307 // Delegate this work to the SplitLandingPadPredecessors.
1308 if (BB->isLandingPad()) {
1310 std::string NewName = std::string(Suffix) + ".split-lp";
1311
1312 SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
1313 DTU, DT, LI, MSSAU, PreserveLCSSA);
1314 return NewBBs[0];
1315 }
1316
1317 // Create new basic block, insert right before the original block.
1319 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
1320
1321 // The new block unconditionally branches to the old block.
1322 BranchInst *BI = BranchInst::Create(BB, NewBB);
1323
1324 Loop *L = nullptr;
1325 BasicBlock *OldLatch = nullptr;
1326 // Splitting the predecessors of a loop header creates a preheader block.
1327 if (LI && LI->isLoopHeader(BB)) {
1328 L = LI->getLoopFor(BB);
1329 // Using the loop start line number prevents debuggers stepping into the
1330 // loop body for this instruction.
1331 BI->setDebugLoc(L->getStartLoc());
1332
1333 // If BB is the header of the Loop, it is possible that the loop is
1334 // modified, such that the current latch does not remain the latch of the
1335 // loop. If that is the case, the loop metadata from the current latch needs
1336 // to be applied to the new latch.
1337 OldLatch = L->getLoopLatch();
1338 } else
1339 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
1340
1341 // Move the edges from Preds to point to NewBB instead of BB.
1342 for (BasicBlock *Pred : Preds) {
1343 // This is slightly more strict than necessary; the minimum requirement
1344 // is that there be no more than one indirectbr branching to BB. And
1345 // all BlockAddress uses would need to be updated.
1346 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1347 "Cannot split an edge from an IndirectBrInst");
1348 Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
1349 }
1350
1351 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
1352 // node becomes an incoming value for BB's phi node. However, if the Preds
1353 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
1354 // account for the newly created predecessor.
1355 if (Preds.empty()) {
1356 // Insert dummy values as the incoming value.
1357 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
1358 cast<PHINode>(I)->addIncoming(PoisonValue::get(I->getType()), NewBB);
1359 }
1360
1361 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
1362 bool HasLoopExit = false;
1363 UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
1364 HasLoopExit);
1365
1366 if (!Preds.empty()) {
1367 // Update the PHI nodes in BB with the values coming from NewBB.
1368 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
1369 }
1370
1371 if (OldLatch) {
1372 BasicBlock *NewLatch = L->getLoopLatch();
1373 if (NewLatch != OldLatch) {
1374 MDNode *MD = OldLatch->getTerminator()->getMetadata(LLVMContext::MD_loop);
1375 NewLatch->getTerminator()->setMetadata(LLVMContext::MD_loop, MD);
1376 // It's still possible that OldLatch is the latch of another inner loop,
1377 // in which case we do not remove the metadata.
1378 Loop *IL = LI->getLoopFor(OldLatch);
1379 if (IL && IL->getLoopLatch() != OldLatch)
1380 OldLatch->getTerminator()->setMetadata(LLVMContext::MD_loop, nullptr);
1381 }
1382 }
1383
1384 return NewBB;
1385}
1386
1389 const char *Suffix, DominatorTree *DT,
1390 LoopInfo *LI, MemorySSAUpdater *MSSAU,
1391 bool PreserveLCSSA) {
1392 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI,
1393 MSSAU, PreserveLCSSA);
1394}
1397 const char *Suffix,
1398 DomTreeUpdater *DTU, LoopInfo *LI,
1399 MemorySSAUpdater *MSSAU,
1400 bool PreserveLCSSA) {
1401 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
1402 /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA);
1403}
1404
1406 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1407 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1408 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1409 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1410 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
1411
1412 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
1413 // it right before the original block.
1414 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
1415 OrigBB->getName() + Suffix1,
1416 OrigBB->getParent(), OrigBB);
1417 NewBBs.push_back(NewBB1);
1418
1419 // The new block unconditionally branches to the old block.
1420 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
1421 BI1->setDebugLoc(OrigBB->getFirstNonPHIIt()->getDebugLoc());
1422
1423 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
1424 for (BasicBlock *Pred : Preds) {
1425 // This is slightly more strict than necessary; the minimum requirement
1426 // is that there be no more than one indirectbr branching to BB. And
1427 // all BlockAddress uses would need to be updated.
1428 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1429 "Cannot split an edge from an IndirectBrInst");
1430 Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
1431 }
1432
1433 bool HasLoopExit = false;
1434 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
1435 PreserveLCSSA, HasLoopExit);
1436
1437 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
1438 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
1439
1440 // Move the remaining edges from OrigBB to point to NewBB2.
1441 SmallVector<BasicBlock*, 8> NewBB2Preds;
1442 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
1443 i != e; ) {
1444 BasicBlock *Pred = *i++;
1445 if (Pred == NewBB1) continue;
1446 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1447 "Cannot split an edge from an IndirectBrInst");
1448 NewBB2Preds.push_back(Pred);
1449 e = pred_end(OrigBB);
1450 }
1451
1452 BasicBlock *NewBB2 = nullptr;
1453 if (!NewBB2Preds.empty()) {
1454 // Create another basic block for the rest of OrigBB's predecessors.
1455 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
1456 OrigBB->getName() + Suffix2,
1457 OrigBB->getParent(), OrigBB);
1458 NewBBs.push_back(NewBB2);
1459
1460 // The new block unconditionally branches to the old block.
1461 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
1462 BI2->setDebugLoc(OrigBB->getFirstNonPHIIt()->getDebugLoc());
1463
1464 // Move the remaining edges from OrigBB to point to NewBB2.
1465 for (BasicBlock *NewBB2Pred : NewBB2Preds)
1466 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
1467
1468 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
1469 HasLoopExit = false;
1470 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
1471 PreserveLCSSA, HasLoopExit);
1472
1473 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
1474 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
1475 }
1476
1477 LandingPadInst *LPad = OrigBB->getLandingPadInst();
1478 Instruction *Clone1 = LPad->clone();
1479 Clone1->setName(Twine("lpad") + Suffix1);
1480 Clone1->insertInto(NewBB1, NewBB1->getFirstInsertionPt());
1481
1482 if (NewBB2) {
1483 Instruction *Clone2 = LPad->clone();
1484 Clone2->setName(Twine("lpad") + Suffix2);
1485 Clone2->insertInto(NewBB2, NewBB2->getFirstInsertionPt());
1486
1487 // Create a PHI node for the two cloned landingpad instructions only
1488 // if the original landingpad instruction has some uses.
1489 if (!LPad->use_empty()) {
1490 assert(!LPad->getType()->isTokenTy() &&
1491 "Split cannot be applied if LPad is token type. Otherwise an "
1492 "invalid PHINode of token type would be created.");
1493 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad->getIterator());
1494 PN->addIncoming(Clone1, NewBB1);
1495 PN->addIncoming(Clone2, NewBB2);
1496 LPad->replaceAllUsesWith(PN);
1497 }
1498 LPad->eraseFromParent();
1499 } else {
1500 // There is no second clone. Just replace the landing pad with the first
1501 // clone.
1502 LPad->replaceAllUsesWith(Clone1);
1503 LPad->eraseFromParent();
1504 }
1505}
1506
1509 const char *Suffix1, const char *Suffix2,
1511 DomTreeUpdater *DTU, LoopInfo *LI,
1512 MemorySSAUpdater *MSSAU,
1513 bool PreserveLCSSA) {
1514 return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
1515 NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU,
1516 PreserveLCSSA);
1517}
1518
1520 BasicBlock *Pred,
1521 DomTreeUpdater *DTU) {
1522 Instruction *UncondBranch = Pred->getTerminator();
1523 // Clone the return and add it to the end of the predecessor.
1524 Instruction *NewRet = RI->clone();
1525 NewRet->insertInto(Pred, Pred->end());
1526
1527 // If the return instruction returns a value, and if the value was a
1528 // PHI node in "BB", propagate the right value into the return.
1529 for (Use &Op : NewRet->operands()) {
1530 Value *V = Op;
1531 Instruction *NewBC = nullptr;
1532 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
1533 // Return value might be bitcasted. Clone and insert it before the
1534 // return instruction.
1535 V = BCI->getOperand(0);
1536 NewBC = BCI->clone();
1537 NewBC->insertInto(Pred, NewRet->getIterator());
1538 Op = NewBC;
1539 }
1540
1541 Instruction *NewEV = nullptr;
1543 V = EVI->getOperand(0);
1544 NewEV = EVI->clone();
1545 if (NewBC) {
1546 NewBC->setOperand(0, NewEV);
1547 NewEV->insertInto(Pred, NewBC->getIterator());
1548 } else {
1549 NewEV->insertInto(Pred, NewRet->getIterator());
1550 Op = NewEV;
1551 }
1552 }
1553
1554 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1555 if (PN->getParent() == BB) {
1556 if (NewEV) {
1557 NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
1558 } else if (NewBC)
1559 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
1560 else
1561 Op = PN->getIncomingValueForBlock(Pred);
1562 }
1563 }
1564 }
1565
1566 // Update any PHI nodes in the returning block to realize that we no
1567 // longer branch to them.
1568 BB->removePredecessor(Pred);
1569 UncondBranch->eraseFromParent();
1570
1571 if (DTU)
1572 DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
1573
1574 return cast<ReturnInst>(NewRet);
1575}
1576
1578 BasicBlock::iterator SplitBefore,
1579 bool Unreachable,
1580 MDNode *BranchWeights,
1581 DomTreeUpdater *DTU, LoopInfo *LI,
1582 BasicBlock *ThenBlock) {
1584 Cond, SplitBefore, &ThenBlock, /* ElseBlock */ nullptr,
1585 /* UnreachableThen */ Unreachable,
1586 /* UnreachableElse */ false, BranchWeights, DTU, LI);
1587 return ThenBlock->getTerminator();
1588}
1589
1591 BasicBlock::iterator SplitBefore,
1592 bool Unreachable,
1593 MDNode *BranchWeights,
1594 DomTreeUpdater *DTU, LoopInfo *LI,
1595 BasicBlock *ElseBlock) {
1597 Cond, SplitBefore, /* ThenBlock */ nullptr, &ElseBlock,
1598 /* UnreachableThen */ false,
1599 /* UnreachableElse */ Unreachable, BranchWeights, DTU, LI);
1600 return ElseBlock->getTerminator();
1601}
1602
1604 Instruction **ThenTerm,
1605 Instruction **ElseTerm,
1606 MDNode *BranchWeights,
1607 DomTreeUpdater *DTU, LoopInfo *LI) {
1608 BasicBlock *ThenBlock = nullptr;
1609 BasicBlock *ElseBlock = nullptr;
1611 Cond, SplitBefore, &ThenBlock, &ElseBlock, /* UnreachableThen */ false,
1612 /* UnreachableElse */ false, BranchWeights, DTU, LI);
1613
1614 *ThenTerm = ThenBlock->getTerminator();
1615 *ElseTerm = ElseBlock->getTerminator();
1616}
1617
1619 Value *Cond, BasicBlock::iterator SplitBefore, BasicBlock **ThenBlock,
1620 BasicBlock **ElseBlock, bool UnreachableThen, bool UnreachableElse,
1621 MDNode *BranchWeights, DomTreeUpdater *DTU, LoopInfo *LI) {
1622 assert((ThenBlock || ElseBlock) &&
1623 "At least one branch block must be created");
1624 assert((!UnreachableThen || !UnreachableElse) &&
1625 "Split block tail must be reachable");
1626
1628 SmallPtrSet<BasicBlock *, 8> UniqueOrigSuccessors;
1629 BasicBlock *Head = SplitBefore->getParent();
1630 if (DTU) {
1631 UniqueOrigSuccessors.insert_range(successors(Head));
1632 Updates.reserve(4 + 2 * UniqueOrigSuccessors.size());
1633 }
1634
1635 LLVMContext &C = Head->getContext();
1636 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
1637 BasicBlock *TrueBlock = Tail;
1638 BasicBlock *FalseBlock = Tail;
1639 bool ThenToTailEdge = false;
1640 bool ElseToTailEdge = false;
1641
1642 // Encapsulate the logic around creation/insertion/etc of a new block.
1643 auto handleBlock = [&](BasicBlock **PBB, bool Unreachable, BasicBlock *&BB,
1644 bool &ToTailEdge) {
1645 if (PBB == nullptr)
1646 return; // Do not create/insert a block.
1647
1648 if (*PBB)
1649 BB = *PBB; // Caller supplied block, use it.
1650 else {
1651 // Create a new block.
1652 BB = BasicBlock::Create(C, "", Head->getParent(), Tail);
1653 if (Unreachable)
1654 (void)new UnreachableInst(C, BB);
1655 else {
1656 (void)BranchInst::Create(Tail, BB);
1657 ToTailEdge = true;
1658 }
1659 BB->getTerminator()->setDebugLoc(SplitBefore->getDebugLoc());
1660 // Pass the new block back to the caller.
1661 *PBB = BB;
1662 }
1663 };
1664
1665 handleBlock(ThenBlock, UnreachableThen, TrueBlock, ThenToTailEdge);
1666 handleBlock(ElseBlock, UnreachableElse, FalseBlock, ElseToTailEdge);
1667
1668 Instruction *HeadOldTerm = Head->getTerminator();
1669 BranchInst *HeadNewTerm =
1670 BranchInst::Create(/*ifTrue*/ TrueBlock, /*ifFalse*/ FalseBlock, Cond);
1671 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
1672 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
1673
1674 if (DTU) {
1675 Updates.emplace_back(DominatorTree::Insert, Head, TrueBlock);
1676 Updates.emplace_back(DominatorTree::Insert, Head, FalseBlock);
1677 if (ThenToTailEdge)
1678 Updates.emplace_back(DominatorTree::Insert, TrueBlock, Tail);
1679 if (ElseToTailEdge)
1680 Updates.emplace_back(DominatorTree::Insert, FalseBlock, Tail);
1681 for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1682 Updates.emplace_back(DominatorTree::Insert, Tail, UniqueOrigSuccessor);
1683 for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1684 Updates.emplace_back(DominatorTree::Delete, Head, UniqueOrigSuccessor);
1685 DTU->applyUpdates(Updates);
1686 }
1687
1688 if (LI) {
1689 if (Loop *L = LI->getLoopFor(Head); L) {
1690 if (ThenToTailEdge)
1691 L->addBasicBlockToLoop(TrueBlock, *LI);
1692 if (ElseToTailEdge)
1693 L->addBasicBlockToLoop(FalseBlock, *LI);
1694 L->addBasicBlockToLoop(Tail, *LI);
1695 }
1696 }
1697}
1698
1699std::pair<Instruction *, Value *>
1701 BasicBlock::iterator SplitBefore) {
1702 BasicBlock *LoopPred = SplitBefore->getParent();
1703 BasicBlock *LoopBody = SplitBlock(SplitBefore->getParent(), SplitBefore);
1704 BasicBlock *LoopExit = SplitBlock(SplitBefore->getParent(), SplitBefore);
1705
1706 auto *Ty = End->getType();
1707 auto &DL = SplitBefore->getDataLayout();
1708 const unsigned Bitwidth = DL.getTypeSizeInBits(Ty);
1709
1710 IRBuilder<> Builder(LoopBody->getTerminator());
1711 auto *IV = Builder.CreatePHI(Ty, 2, "iv");
1712 auto *IVNext =
1713 Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
1714 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
1715 auto *IVCheck = Builder.CreateICmpEQ(IVNext, End,
1716 IV->getName() + ".check");
1717 Builder.CreateCondBr(IVCheck, LoopExit, LoopBody);
1718 LoopBody->getTerminator()->eraseFromParent();
1719
1720 // Populate the IV PHI.
1721 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPred);
1722 IV->addIncoming(IVNext, LoopBody);
1723
1724 return std::make_pair(&*LoopBody->getFirstNonPHIIt(), IV);
1725}
1726
1728 ElementCount EC, Type *IndexTy, BasicBlock::iterator InsertBefore,
1729 std::function<void(IRBuilderBase &, Value *)> Func) {
1730
1731 IRBuilder<> IRB(InsertBefore->getParent(), InsertBefore);
1732
1733 if (EC.isScalable()) {
1734 Value *NumElements = IRB.CreateElementCount(IndexTy, EC);
1735
1736 auto [BodyIP, Index] =
1737 SplitBlockAndInsertSimpleForLoop(NumElements, InsertBefore);
1738
1739 IRB.SetInsertPoint(BodyIP);
1740 Func(IRB, Index);
1741 return;
1742 }
1743
1744 unsigned Num = EC.getFixedValue();
1745 for (unsigned Idx = 0; Idx < Num; ++Idx) {
1746 IRB.SetInsertPoint(InsertBefore);
1747 Func(IRB, ConstantInt::get(IndexTy, Idx));
1748 }
1749}
1750
1752 Value *EVL, BasicBlock::iterator InsertBefore,
1753 std::function<void(IRBuilderBase &, Value *)> Func) {
1754
1755 IRBuilder<> IRB(InsertBefore->getParent(), InsertBefore);
1756 Type *Ty = EVL->getType();
1757
1758 if (!isa<ConstantInt>(EVL)) {
1759 auto [BodyIP, Index] = SplitBlockAndInsertSimpleForLoop(EVL, InsertBefore);
1760 IRB.SetInsertPoint(BodyIP);
1761 Func(IRB, Index);
1762 return;
1763 }
1764
1765 unsigned Num = cast<ConstantInt>(EVL)->getZExtValue();
1766 for (unsigned Idx = 0; Idx < Num; ++Idx) {
1767 IRB.SetInsertPoint(InsertBefore);
1768 Func(IRB, ConstantInt::get(Ty, Idx));
1769 }
1770}
1771
1773 BasicBlock *&IfFalse) {
1774 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
1775 BasicBlock *Pred1 = nullptr;
1776 BasicBlock *Pred2 = nullptr;
1777
1778 if (SomePHI) {
1779 if (SomePHI->getNumIncomingValues() != 2)
1780 return nullptr;
1781 Pred1 = SomePHI->getIncomingBlock(0);
1782 Pred2 = SomePHI->getIncomingBlock(1);
1783 } else {
1784 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1785 if (PI == PE) // No predecessor
1786 return nullptr;
1787 Pred1 = *PI++;
1788 if (PI == PE) // Only one predecessor
1789 return nullptr;
1790 Pred2 = *PI++;
1791 if (PI != PE) // More than two predecessors
1792 return nullptr;
1793 }
1794
1795 // We can only handle branches. Other control flow will be lowered to
1796 // branches if possible anyway.
1797 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
1798 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
1799 if (!Pred1Br || !Pred2Br)
1800 return nullptr;
1801
1802 // Eliminate code duplication by ensuring that Pred1Br is conditional if
1803 // either are.
1804 if (Pred2Br->isConditional()) {
1805 // If both branches are conditional, we don't have an "if statement". In
1806 // reality, we could transform this case, but since the condition will be
1807 // required anyway, we stand no chance of eliminating it, so the xform is
1808 // probably not profitable.
1809 if (Pred1Br->isConditional())
1810 return nullptr;
1811
1812 std::swap(Pred1, Pred2);
1813 std::swap(Pred1Br, Pred2Br);
1814 }
1815
1816 if (Pred1Br->isConditional()) {
1817 // The only thing we have to watch out for here is to make sure that Pred2
1818 // doesn't have incoming edges from other blocks. If it does, the condition
1819 // doesn't dominate BB.
1820 if (!Pred2->getSinglePredecessor())
1821 return nullptr;
1822
1823 // If we found a conditional branch predecessor, make sure that it branches
1824 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
1825 if (Pred1Br->getSuccessor(0) == BB &&
1826 Pred1Br->getSuccessor(1) == Pred2) {
1827 IfTrue = Pred1;
1828 IfFalse = Pred2;
1829 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
1830 Pred1Br->getSuccessor(1) == BB) {
1831 IfTrue = Pred2;
1832 IfFalse = Pred1;
1833 } else {
1834 // We know that one arm of the conditional goes to BB, so the other must
1835 // go somewhere unrelated, and this must not be an "if statement".
1836 return nullptr;
1837 }
1838
1839 return Pred1Br;
1840 }
1841
1842 // Ok, if we got here, both predecessors end with an unconditional branch to
1843 // BB. Don't panic! If both blocks only have a single (identical)
1844 // predecessor, and THAT is a conditional branch, then we're all ok!
1845 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
1846 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
1847 return nullptr;
1848
1849 // Otherwise, if this is a conditional branch, then we can use it!
1850 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
1851 if (!BI) return nullptr;
1852
1853 assert(BI->isConditional() && "Two successors but not conditional?");
1854 if (BI->getSuccessor(0) == Pred1) {
1855 IfTrue = Pred1;
1856 IfFalse = Pred2;
1857 } else {
1858 IfTrue = Pred2;
1859 IfFalse = Pred1;
1860 }
1861 return BI;
1862}
1863
1865 Value *NewCond = PBI->getCondition();
1866 // If this is a "cmp" instruction, only used for branching (and nowhere
1867 // else), then we can simply invert the predicate.
1868 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
1869 CmpInst *CI = cast<CmpInst>(NewCond);
1871 } else
1872 NewCond = Builder.CreateNot(NewCond, NewCond->getName() + ".not");
1873
1874 PBI->setCondition(NewCond);
1875 PBI->swapSuccessors();
1876}
1877
1879 for (auto &BB : F) {
1880 auto *Term = BB.getTerminator();
1881 if (!(isa<ReturnInst>(Term) || isa<UnreachableInst>(Term) ||
1882 isa<BranchInst>(Term)))
1883 return false;
1884 }
1885 return true;
1886}
1887
1889 return Printable([BB](raw_ostream &OS) {
1890 if (!BB) {
1891 OS << "<nullptr>";
1892 return;
1893 }
1894 BB->printAsOperand(OS);
1895 });
1896}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static BasicBlock * SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB)
Remove redundant instructions within sequences of consecutive dbg.value instructions.
static BasicBlock * SplitBlockImpl(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName, bool Before)
static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, ArrayRef< BasicBlock * > Preds, BranchInst *BI, bool HasLoopExit)
Update the PHI nodes in OrigBB to include the values coming from NewBB.
static bool removeUndefDbgAssignsFromEntryBlock(BasicBlock *BB)
Remove redundant undef dbg.assign intrinsic from an entry block using a forward scan.
static bool updateCycleLoopInfo(TI *LCI, BasicBlock *CallBrBlock, BasicBlock *CallBrTarget, BasicBlock *Succ)
Helper function to update the cycle or loop information after inserting a new block between a callbr ...
static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB, ArrayRef< BasicBlock * > Preds, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA, bool &HasLoopExit)
Update DominatorTree, LoopInfo, and LCCSA analysis information.
static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB)
Remove redundant dbg.value instructions using a forward scan.
static void SplitLandingPadPredecessorsImpl(BasicBlock *OrigBB, ArrayRef< BasicBlock * > Preds, const char *Suffix1, const char *Suffix2, SmallVectorImpl< BasicBlock * > &NewBBs, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
static cl::opt< unsigned > MaxDeoptOrUnreachableSuccessorCheckDepth("max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden, cl::desc("Set the maximum path length when checking whether a basic block " "is followed by a block that either has a terminating " "deoptimizing call or is terminated with an unreachable"))
static void emptyAndDetachBlock(BasicBlock *BB, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs)
Zap all the instructions in the block and replace them with an unreachable instruction and notify the...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static const uint32_t IV[8]
Definition blake3_impl.h:83
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:472
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:459
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:528
LLVM_ABI const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool empty() const
Definition BasicBlock.h:481
const Instruction & back() const
Definition BasicBlock.h:484
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:690
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="", bool Before=false)
Split the basic block into two basic blocks at the specified instruction.
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:482
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
size_t size() const
Definition BasicBlock.h:480
LLVM_ABI bool isLandingPad() const
Return true if this basic block is a landing pad.
LLVM_ABI bool canSplitPredecessors() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:662
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
This class represents a no-op cast from one type to another.
Conditional or Unconditional Branch instruction.
void setCondition(Value *V)
LLVM_ABI void swapSuccessors()
Swap the successors of this branch instruction.
bool isConditional() const
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
Value * getCondition() const
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
void setSuccessor(unsigned i, BasicBlock *NewSucc)
BasicBlock * getSuccessor(unsigned i) const
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
This class is the base class for the comparison instructions.
Definition InstrTypes.h:664
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition InstrTypes.h:768
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:789
Represents calls to the llvm.experimintal.convergence.* intrinsics.
DWARF expression.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
Identifies a unique instance of a whole variable (discards/ignores fragment information).
Identifies a unique instance of a variable.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:256
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
iterator_range< iterator > children()
NodeT * getBlock() const
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
void splitBlock(NodeT *NewBB)
splitBlock - BB is split and now it has one successor.
DomTreeNodeBase< NodeT > * setNewRoot(NodeT *BB)
Add a new node to the forward dominator tree and make it a new root.
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
bool hasDomTree() const
Returns true if it holds a DomTreeT.
void recalculate(FuncT &F)
Notify DTU that the entry block was replaced.
Module * getParent()
Get the module that this global value is contained inside of...
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:207
LLVM_ABI Value * CreateElementCount(Type *Ty, ElementCount EC)
Create an expression which evaluates to the number of elements in EC at runtime.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI void moveBeforePreserving(InstListType::iterator MovePos)
Perform a moveBefore operation, while signalling that the caller intends to preserve the original ord...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
bool isSpecialTerminator() const
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
The landingpad instruction holds all of the information necessary to generate correct exception handl...
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
unsigned getLoopDepth() const
Return the nesting level of this loop.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
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,...
void invalidateCachedPredecessors()
Clears the PredIteratorCache info.
void removeInstruction(Instruction *InstToRemove)
Removes an instruction from the dependence analysis, updating the dependence of instructions that pre...
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI void moveAllAfterSpliceBlocks(BasicBlock *From, BasicBlock *To, Instruction *Start)
From block was spliced into From and To.
LLVM_ABI void applyUpdates(ArrayRef< CFGUpdate > Updates, DominatorTree &DT, bool UpdateDTFirst=false)
Apply CFG updates, analogous with the DT edge updates.
LLVM_ABI void moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To, Instruction *Start)
From block was merged into To.
LLVM_ABI void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
LLVM_ABI void wireOldPredecessorsToNewImmediatePredecessor(BasicBlock *Old, BasicBlock *New, ArrayRef< BasicBlock * > Preds, bool IdenticalEdgesWereMerged=true)
A new empty BasicBlock (New) now branches directly to Old.
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:720
Class that has the common methods + fields of memory uses/defs.
Definition MemorySSA.h:250
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
LLVM_ABI void removeIncomingValueIf(function_ref< bool(unsigned)> Predicate, bool DeletePHIIfEmpty=true)
Remove all incoming values for which the predicate returns true.
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Simple wrapper around std::function<void(raw_ostream&)>.
Definition Printable.h:38
Return a value (possibly void), from a function.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:291
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:234
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:292
void setOperand(unsigned i, Value *Val)
Definition User.h:237
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
bool use_empty() const
Definition Value.h:346
bool hasName() const
Definition Value.h:262
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
initializer< Ty > init(const Ty &Val)
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.
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
bool succ_empty(const Instruction *I)
Definition CFG.h:257
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 unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Definition CFG.cpp:80
auto pred_end(const MachineBasicBlock *BB)
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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool hasOnlySimpleTerminator(const Function &F)
auto successors(const MachineBasicBlock *BB)
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...
constexpr from_range_t from_range
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.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:632
auto cast_or_null(const Y &Val)
Definition Casting.h:714
auto pred_size(const MachineBasicBlock *BB)
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,...
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:94
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1744
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 bool HasLoopOrEntryConvergenceToken(const BasicBlock *BB)
Check if the given basic block contains any loop or entry convergent intrinsic instructions.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
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 raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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.
auto succ_size(const MachineBasicBlock *BB)
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
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_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
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 bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:84
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 bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
DWARFExpression::Operation Op
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:105
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 bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition CFG.cpp:96
LLVM_ABI unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found.
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.
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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.
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:363
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1909
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition Local.cpp:641
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.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
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
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
Option class for critical edge splitting.
CriticalEdgeSplittingOptions & setPreserveLCSSA()