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