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