LLVM 19.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/InstrTypes.h"
32#include "llvm/IR/Instruction.h"
35#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Type.h"
38#include "llvm/IR/User.h"
39#include "llvm/IR/Value.h"
40#include "llvm/IR/ValueHandle.h"
43#include "llvm/Support/Debug.h"
46#include <cassert>
47#include <cstdint>
48#include <string>
49#include <utility>
50#include <vector>
51
52using namespace llvm;
53
54#define DEBUG_TYPE "basicblock-utils"
55
57 "max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden,
58 cl::desc("Set the maximum path length when checking whether a basic block "
59 "is followed by a block that either has a terminating "
60 "deoptimizing call or is terminated with an unreachable"));
61
65 bool KeepOneInputPHIs) {
66 for (auto *BB : BBs) {
67 // Loop through all of our successors and make sure they know that one
68 // of their predecessors is going away.
69 SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
70 for (BasicBlock *Succ : successors(BB)) {
71 Succ->removePredecessor(BB, KeepOneInputPHIs);
72 if (Updates && UniqueSuccessors.insert(Succ).second)
73 Updates->push_back({DominatorTree::Delete, BB, Succ});
74 }
75
76 // Zap all the instructions in the block.
77 while (!BB->empty()) {
78 Instruction &I = BB->back();
79 // If this instruction is used, replace uses with an arbitrary value.
80 // Because control flow can't get here, we don't care what we replace the
81 // value with. Note that since this block is unreachable, and all values
82 // contained within it must dominate their uses, that all uses will
83 // eventually be removed (they are themselves dead).
84 if (!I.use_empty())
85 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
86 BB->back().eraseFromParent();
87 }
88 new UnreachableInst(BB->getContext(), BB);
89 assert(BB->size() == 1 &&
90 isa<UnreachableInst>(BB->getTerminator()) &&
91 "The successor list of BB isn't empty before "
92 "applying corresponding DTU updates.");
93 }
94}
95
97 bool KeepOneInputPHIs) {
98 DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
99}
100
101void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
102 bool KeepOneInputPHIs) {
103#ifndef NDEBUG
104 // Make sure that all predecessors of each dead block is also dead.
105 SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
106 assert(Dead.size() == BBs.size() && "Duplicating blocks?");
107 for (auto *BB : Dead)
108 for (BasicBlock *Pred : predecessors(BB))
109 assert(Dead.count(Pred) && "All predecessors must be dead!");
110#endif
111
113 detachDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
114
115 if (DTU)
116 DTU->applyUpdates(Updates);
117
118 for (BasicBlock *BB : BBs)
119 if (DTU)
120 DTU->deleteBB(BB);
121 else
122 BB->eraseFromParent();
123}
124
126 bool KeepOneInputPHIs) {
128
129 // Mark all reachable blocks.
130 for (BasicBlock *BB : depth_first_ext(&F, Reachable))
131 (void)BB/* Mark all reachable blocks */;
132
133 // Collect all dead blocks.
134 std::vector<BasicBlock*> DeadBlocks;
135 for (BasicBlock &BB : F)
136 if (!Reachable.count(&BB))
137 DeadBlocks.push_back(&BB);
138
139 // Delete the dead blocks.
140 DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
141
142 return !DeadBlocks.empty();
143}
144
146 MemoryDependenceResults *MemDep) {
147 if (!isa<PHINode>(BB->begin()))
148 return false;
149
150 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
151 if (PN->getIncomingValue(0) != PN)
152 PN->replaceAllUsesWith(PN->getIncomingValue(0));
153 else
154 PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
155
156 if (MemDep)
157 MemDep->removeInstruction(PN); // Memdep updates AA itself.
158
159 PN->eraseFromParent();
160 }
161 return true;
162}
163
165 MemorySSAUpdater *MSSAU) {
166 // Recursively deleting a PHI may cause multiple PHIs to be deleted
167 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
169 for (PHINode &PN : BB->phis())
170 PHIs.push_back(&PN);
171
172 bool Changed = false;
173 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
174 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
175 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
176
177 return Changed;
178}
179
181 LoopInfo *LI, MemorySSAUpdater *MSSAU,
183 bool PredecessorWithTwoSuccessors,
184 DominatorTree *DT) {
185 if (BB->hasAddressTaken())
186 return false;
187
188 // Can't merge if there are multiple predecessors, or no predecessors.
189 BasicBlock *PredBB = BB->getUniquePredecessor();
190 if (!PredBB) return false;
191
192 // Don't break self-loops.
193 if (PredBB == BB) return false;
194
195 // Don't break unwinding instructions or terminators with other side-effects.
196 Instruction *PTI = PredBB->getTerminator();
197 if (PTI->isSpecialTerminator() || PTI->mayHaveSideEffects())
198 return false;
199
200 // Can't merge if there are multiple distinct successors.
201 if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
202 return false;
203
204 // Currently only allow PredBB to have two predecessors, one being BB.
205 // Update BI to branch to BB's only successor instead of BB.
206 BranchInst *PredBB_BI;
207 BasicBlock *NewSucc = nullptr;
208 unsigned FallThruPath;
209 if (PredecessorWithTwoSuccessors) {
210 if (!(PredBB_BI = dyn_cast<BranchInst>(PTI)))
211 return false;
212 BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator());
213 if (!BB_JmpI || !BB_JmpI->isUnconditional())
214 return false;
215 NewSucc = BB_JmpI->getSuccessor(0);
216 FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
217 }
218
219 // Can't merge if there is PHI loop.
220 for (PHINode &PN : BB->phis())
221 if (llvm::is_contained(PN.incoming_values(), &PN))
222 return false;
223
224 LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
225 << PredBB->getName() << "\n");
226
227 // Begin by getting rid of unneeded PHIs.
228 SmallVector<AssertingVH<Value>, 4> IncomingValues;
229 if (isa<PHINode>(BB->front())) {
230 for (PHINode &PN : BB->phis())
231 if (!isa<PHINode>(PN.getIncomingValue(0)) ||
232 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
233 IncomingValues.push_back(PN.getIncomingValue(0));
234 FoldSingleEntryPHINodes(BB, MemDep);
235 }
236
237 if (DT) {
238 assert(!DTU && "cannot use both DT and DTU for updates");
239 DomTreeNode *PredNode = DT->getNode(PredBB);
240 DomTreeNode *BBNode = DT->getNode(BB);
241 if (PredNode) {
242 assert(BBNode && "PredNode unreachable but BBNode reachable?");
243 for (DomTreeNode *C : to_vector(BBNode->children()))
244 C->setIDom(PredNode);
245 }
246 }
247 // DTU update: Collect all the edges that exit BB.
248 // These dominator edges will be redirected from Pred.
249 std::vector<DominatorTree::UpdateType> Updates;
250 if (DTU) {
251 assert(!DT && "cannot use both DT and DTU for updates");
252 // To avoid processing the same predecessor more than once.
254 SmallPtrSet<BasicBlock *, 2> SuccsOfPredBB(succ_begin(PredBB),
255 succ_end(PredBB));
256 Updates.reserve(Updates.size() + 2 * succ_size(BB) + 1);
257 // Add insert edges first. Experimentally, for the particular case of two
258 // blocks that can be merged, with a single successor and single predecessor
259 // respectively, it is beneficial to have all insert updates first. Deleting
260 // edges first may lead to unreachable blocks, followed by inserting edges
261 // making the blocks reachable again. Such DT updates lead to high compile
262 // times. We add inserts before deletes here to reduce compile time.
263 for (BasicBlock *SuccOfBB : successors(BB))
264 // This successor of BB may already be a PredBB's successor.
265 if (!SuccsOfPredBB.contains(SuccOfBB))
266 if (SeenSuccs.insert(SuccOfBB).second)
267 Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
268 SeenSuccs.clear();
269 for (BasicBlock *SuccOfBB : successors(BB))
270 if (SeenSuccs.insert(SuccOfBB).second)
271 Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
272 Updates.push_back({DominatorTree::Delete, PredBB, BB});
273 }
274
275 Instruction *STI = BB->getTerminator();
276 Instruction *Start = &*BB->begin();
277 // If there's nothing to move, mark the starting instruction as the last
278 // instruction in the block. Terminator instruction is handled separately.
279 if (Start == STI)
280 Start = PTI;
281
282 // Move all definitions in the successor to the predecessor...
283 PredBB->splice(PTI->getIterator(), BB, BB->begin(), STI->getIterator());
284
285 if (MSSAU)
286 MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
287
288 // Make all PHI nodes that referred to BB now refer to Pred as their
289 // source...
290 BB->replaceAllUsesWith(PredBB);
291
292 if (PredecessorWithTwoSuccessors) {
293 // Delete the unconditional branch from BB.
294 BB->back().eraseFromParent();
295
296 // Update branch in the predecessor.
297 PredBB_BI->setSuccessor(FallThruPath, NewSucc);
298 } else {
299 // Delete the unconditional branch from the predecessor.
300 PredBB->back().eraseFromParent();
301
302 // Move terminator instruction.
303 BB->back().moveBeforePreserving(*PredBB, PredBB->end());
304
305 // Terminator may be a memory accessing instruction too.
306 if (MSSAU)
307 if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>(
308 MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
309 MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
310 }
311 // Add unreachable to now empty BB.
312 new UnreachableInst(BB->getContext(), BB);
313
314 // Inherit predecessors name if it exists.
315 if (!PredBB->hasName())
316 PredBB->takeName(BB);
317
318 if (LI)
319 LI->removeBlock(BB);
320
321 if (MemDep)
323
324 if (DTU)
325 DTU->applyUpdates(Updates);
326
327 if (DT) {
328 assert(succ_empty(BB) &&
329 "successors should have been transferred to PredBB");
330 DT->eraseNode(BB);
331 }
332
333 // Finally, erase the old block and update dominator info.
334 DeleteDeadBlock(BB, DTU);
335
336 return true;
337}
338
341 LoopInfo *LI) {
342 assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
343
344 bool BlocksHaveBeenMerged = false;
345 while (!MergeBlocks.empty()) {
346 BasicBlock *BB = *MergeBlocks.begin();
347 BasicBlock *Dest = BB->getSingleSuccessor();
348 if (Dest && (!L || L->contains(Dest))) {
349 BasicBlock *Fold = Dest->getUniquePredecessor();
350 (void)Fold;
351 if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
352 assert(Fold == BB &&
353 "Expecting BB to be unique predecessor of the Dest block");
354 MergeBlocks.erase(Dest);
355 BlocksHaveBeenMerged = true;
356 } else
357 MergeBlocks.erase(BB);
358 } else
359 MergeBlocks.erase(BB);
360 }
361 return BlocksHaveBeenMerged;
362}
363
364/// Remove redundant instructions within sequences of consecutive dbg.value
365/// instructions. This is done using a backward scan to keep the last dbg.value
366/// describing a specific variable/fragment.
367///
368/// BackwardScan strategy:
369/// ----------------------
370/// Given a sequence of consecutive DbgValueInst like this
371///
372/// dbg.value ..., "x", FragmentX1 (*)
373/// dbg.value ..., "y", FragmentY1
374/// dbg.value ..., "x", FragmentX2
375/// dbg.value ..., "x", FragmentX1 (**)
376///
377/// then the instruction marked with (*) can be removed (it is guaranteed to be
378/// obsoleted by the instruction marked with (**) as the latter instruction is
379/// describing the same variable using the same fragment info).
380///
381/// Possible improvements:
382/// - Check fully overlapping fragments and not only identical fragments.
383/// - Support dbg.declare. dbg.label, and possibly other meta instructions being
384/// part of the sequence of consecutive instructions.
385static bool
389 for (auto &I : reverse(*BB)) {
390 for (DbgRecord &DR : reverse(I.getDbgRecordRange())) {
391 if (isa<DbgLabelRecord>(DR)) {
392 // Emulate existing behaviour (see comment below for dbg.declares).
393 // FIXME: Don't do this.
394 VariableSet.clear();
395 continue;
396 }
397
398 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
399 // Skip declare-type records, as the debug intrinsic method only works
400 // on dbg.value intrinsics.
401 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
402 // The debug intrinsic method treats dbg.declares are "non-debug"
403 // instructions (i.e., a break in a consecutive range of debug
404 // intrinsics). Emulate that to create identical outputs. See
405 // "Possible improvements" above.
406 // FIXME: Delete the line below.
407 VariableSet.clear();
408 continue;
409 }
410
411 DebugVariable Key(DVR.getVariable(), DVR.getExpression(),
412 DVR.getDebugLoc()->getInlinedAt());
413 auto R = VariableSet.insert(Key);
414 // If the same variable fragment is described more than once it is enough
415 // to keep the last one (i.e. the first found since we for reverse
416 // iteration).
417 if (R.second)
418 continue;
419
420 if (DVR.isDbgAssign()) {
421 // Don't delete dbg.assign intrinsics that are linked to instructions.
422 if (!at::getAssignmentInsts(&DVR).empty())
423 continue;
424 // Unlinked dbg.assign intrinsics can be treated like dbg.values.
425 }
426
427 ToBeRemoved.push_back(&DVR);
428 continue;
429 }
430 // Sequence with consecutive dbg.value instrs ended. Clear the map to
431 // restart identifying redundant instructions if case we find another
432 // dbg.value sequence.
433 VariableSet.clear();
434 }
435
436 for (auto &DVR : ToBeRemoved)
437 DVR->eraseFromParent();
438
439 return !ToBeRemoved.empty();
440}
441
443 if (BB->IsNewDbgInfoFormat)
445
448 for (auto &I : reverse(*BB)) {
449 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
450 DebugVariable Key(DVI->getVariable(),
451 DVI->getExpression(),
452 DVI->getDebugLoc()->getInlinedAt());
453 auto R = VariableSet.insert(Key);
454 // If the variable fragment hasn't been seen before then we don't want
455 // to remove this dbg intrinsic.
456 if (R.second)
457 continue;
458
459 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI)) {
460 // Don't delete dbg.assign intrinsics that are linked to instructions.
461 if (!at::getAssignmentInsts(DAI).empty())
462 continue;
463 // Unlinked dbg.assign intrinsics can be treated like dbg.values.
464 }
465
466 // If the same variable fragment is described more than once it is enough
467 // to keep the last one (i.e. the first found since we for reverse
468 // iteration).
469 ToBeRemoved.push_back(DVI);
470 continue;
471 }
472 // Sequence with consecutive dbg.value instrs ended. Clear the map to
473 // restart identifying redundant instructions if case we find another
474 // dbg.value sequence.
475 VariableSet.clear();
476 }
477
478 for (auto &Instr : ToBeRemoved)
479 Instr->eraseFromParent();
480
481 return !ToBeRemoved.empty();
482}
483
484/// Remove redundant dbg.value instructions using a forward scan. This can
485/// remove a dbg.value instruction that is redundant due to indicating that a
486/// variable has the same value as already being indicated by an earlier
487/// dbg.value.
488///
489/// ForwardScan strategy:
490/// ---------------------
491/// Given two identical dbg.value instructions, separated by a block of
492/// instructions that isn't describing the same variable, like this
493///
494/// dbg.value X1, "x", FragmentX1 (**)
495/// <block of instructions, none being "dbg.value ..., "x", ...">
496/// dbg.value X1, "x", FragmentX1 (*)
497///
498/// then the instruction marked with (*) can be removed. Variable "x" is already
499/// described as being mapped to the SSA value X1.
500///
501/// Possible improvements:
502/// - Keep track of non-overlapping fragments.
503static bool
507 VariableMap;
508 for (auto &I : *BB) {
509 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
510 if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
511 continue;
512 DebugVariable Key(DVR.getVariable(), std::nullopt,
513 DVR.getDebugLoc()->getInlinedAt());
514 auto VMI = VariableMap.find(Key);
515 // A dbg.assign with no linked instructions can be treated like a
516 // dbg.value (i.e. can be deleted).
517 bool IsDbgValueKind =
518 (!DVR.isDbgAssign() || at::getAssignmentInsts(&DVR).empty());
519
520 // Update the map if we found a new value/expression describing the
521 // variable, or if the variable wasn't mapped already.
522 SmallVector<Value *, 4> Values(DVR.location_ops());
523 if (VMI == VariableMap.end() || VMI->second.first != Values ||
524 VMI->second.second != DVR.getExpression()) {
525 if (IsDbgValueKind)
526 VariableMap[Key] = {Values, DVR.getExpression()};
527 else
528 VariableMap[Key] = {Values, nullptr};
529 continue;
530 }
531 // Don't delete dbg.assign intrinsics that are linked to instructions.
532 if (!IsDbgValueKind)
533 continue;
534 // Found an identical mapping. Remember the instruction for later removal.
535 ToBeRemoved.push_back(&DVR);
536 }
537 }
538
539 for (auto *DVR : ToBeRemoved)
540 DVR->eraseFromParent();
541
542 return !ToBeRemoved.empty();
543}
544
545static bool
547 assert(BB->isEntryBlock() && "expected entry block");
549 DenseSet<DebugVariable> SeenDefForAggregate;
550 // Returns the DebugVariable for DVI with no fragment info.
551 auto GetAggregateVariable = [](const DbgVariableRecord &DVR) {
552 return DebugVariable(DVR.getVariable(), std::nullopt,
553 DVR.getDebugLoc().getInlinedAt());
554 };
555
556 // Remove undef dbg.assign intrinsics that are encountered before
557 // any non-undef intrinsics from the entry block.
558 for (auto &I : *BB) {
559 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
560 if (!DVR.isDbgValue() && !DVR.isDbgAssign())
561 continue;
562 bool IsDbgValueKind =
563 (DVR.isDbgValue() || at::getAssignmentInsts(&DVR).empty());
564 DebugVariable Aggregate = GetAggregateVariable(DVR);
565 if (!SeenDefForAggregate.contains(Aggregate)) {
566 bool IsKill = DVR.isKillLocation() && IsDbgValueKind;
567 if (!IsKill) {
568 SeenDefForAggregate.insert(Aggregate);
569 } else if (DVR.isDbgAssign()) {
570 ToBeRemoved.push_back(&DVR);
571 }
572 }
573 }
574 }
575
576 for (DbgVariableRecord *DVR : ToBeRemoved)
577 DVR->eraseFromParent();
578
579 return !ToBeRemoved.empty();
580}
581
583 if (BB->IsNewDbgInfoFormat)
585
588 VariableMap;
589 for (auto &I : *BB) {
590 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
591 DebugVariable Key(DVI->getVariable(), std::nullopt,
592 DVI->getDebugLoc()->getInlinedAt());
593 auto VMI = VariableMap.find(Key);
594 auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
595 // A dbg.assign with no linked instructions can be treated like a
596 // dbg.value (i.e. can be deleted).
597 bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
598
599 // Update the map if we found a new value/expression describing the
600 // variable, or if the variable wasn't mapped already.
601 SmallVector<Value *, 4> Values(DVI->getValues());
602 if (VMI == VariableMap.end() || VMI->second.first != Values ||
603 VMI->second.second != DVI->getExpression()) {
604 // Use a sentinel value (nullptr) for the DIExpression when we see a
605 // linked dbg.assign so that the next debug intrinsic will never match
606 // it (i.e. always treat linked dbg.assigns as if they're unique).
607 if (IsDbgValueKind)
608 VariableMap[Key] = {Values, DVI->getExpression()};
609 else
610 VariableMap[Key] = {Values, nullptr};
611 continue;
612 }
613
614 // Don't delete dbg.assign intrinsics that are linked to instructions.
615 if (!IsDbgValueKind)
616 continue;
617 ToBeRemoved.push_back(DVI);
618 }
619 }
620
621 for (auto &Instr : ToBeRemoved)
622 Instr->eraseFromParent();
623
624 return !ToBeRemoved.empty();
625}
626
627/// Remove redundant undef dbg.assign intrinsic from an entry block using a
628/// forward scan.
629/// Strategy:
630/// ---------------------
631/// Scanning forward, delete dbg.assign intrinsics iff they are undef, not
632/// linked to an intrinsic, and don't share an aggregate variable with a debug
633/// intrinsic that didn't meet the criteria. In other words, undef dbg.assigns
634/// that come before non-undef debug intrinsics for the variable are
635/// deleted. Given:
636///
637/// dbg.assign undef, "x", FragmentX1 (*)
638/// <block of instructions, none being "dbg.value ..., "x", ...">
639/// dbg.value %V, "x", FragmentX2
640/// <block of instructions, none being "dbg.value ..., "x", ...">
641/// dbg.assign undef, "x", FragmentX1
642///
643/// then (only) the instruction marked with (*) can be removed.
644/// Possible improvements:
645/// - Keep track of non-overlapping fragments.
647 if (BB->IsNewDbgInfoFormat)
649
650 assert(BB->isEntryBlock() && "expected entry block");
652 DenseSet<DebugVariable> SeenDefForAggregate;
653 // Returns the DebugVariable for DVI with no fragment info.
654 auto GetAggregateVariable = [](DbgValueInst *DVI) {
655 return DebugVariable(DVI->getVariable(), std::nullopt,
656 DVI->getDebugLoc()->getInlinedAt());
657 };
658
659 // Remove undef dbg.assign intrinsics that are encountered before
660 // any non-undef intrinsics from the entry block.
661 for (auto &I : *BB) {
662 DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I);
663 if (!DVI)
664 continue;
665 auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
666 bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
667 DebugVariable Aggregate = GetAggregateVariable(DVI);
668 if (!SeenDefForAggregate.contains(Aggregate)) {
669 bool IsKill = DVI->isKillLocation() && IsDbgValueKind;
670 if (!IsKill) {
671 SeenDefForAggregate.insert(Aggregate);
672 } else if (DAI) {
673 ToBeRemoved.push_back(DAI);
674 }
675 }
676 }
677
678 for (DbgAssignIntrinsic *DAI : ToBeRemoved)
679 DAI->eraseFromParent();
680
681 return !ToBeRemoved.empty();
682}
683
685 bool MadeChanges = false;
686 // By using the "backward scan" strategy before the "forward scan" strategy we
687 // can remove both dbg.value (2) and (3) in a situation like this:
688 //
689 // (1) dbg.value V1, "x", DIExpression()
690 // ...
691 // (2) dbg.value V2, "x", DIExpression()
692 // (3) dbg.value V1, "x", DIExpression()
693 //
694 // The backward scan will remove (2), it is made obsolete by (3). After
695 // getting (2) out of the way, the foward scan will remove (3) since "x"
696 // already is described as having the value V1 at (1).
698 if (BB->isEntryBlock() &&
700 MadeChanges |= removeUndefDbgAssignsFromEntryBlock(BB);
702
703 if (MadeChanges)
704 LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
705 << BB->getName() << "\n");
706 return MadeChanges;
707}
708
710 Instruction &I = *BI;
711 // Replaces all of the uses of the instruction with uses of the value
712 I.replaceAllUsesWith(V);
713
714 // Make sure to propagate a name if there is one already.
715 if (I.hasName() && !V->hasName())
716 V->takeName(&I);
717
718 // Delete the unnecessary instruction now...
719 BI = BI->eraseFromParent();
720}
721
723 Instruction *I) {
724 assert(I->getParent() == nullptr &&
725 "ReplaceInstWithInst: Instruction already inserted into basic block!");
726
727 // Copy debug location to newly added instruction, if it wasn't already set
728 // by the caller.
729 if (!I->getDebugLoc())
730 I->setDebugLoc(BI->getDebugLoc());
731
732 // Insert the new instruction into the basic block...
733 BasicBlock::iterator New = I->insertInto(BB, BI);
734
735 // Replace all uses of the old instruction, and delete it.
737
738 // Move BI back to point to the newly inserted instruction
739 BI = New;
740}
741
743 // Remember visited blocks to avoid infinite loop
745 unsigned Depth = 0;
747 VisitedBlocks.insert(BB).second) {
748 if (isa<UnreachableInst>(BB->getTerminator()) ||
750 return true;
751 BB = BB->getUniqueSuccessor();
752 }
753 return false;
754}
755
758 ReplaceInstWithInst(From->getParent(), BI, To);
759}
760
762 LoopInfo *LI, MemorySSAUpdater *MSSAU,
763 const Twine &BBName) {
764 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
765
766 Instruction *LatchTerm = BB->getTerminator();
767
770
771 if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
772 // If it is a critical edge, and the succesor is an exception block, handle
773 // the split edge logic in this specific function
774 if (Succ->isEHPad())
775 return ehAwareSplitEdge(BB, Succ, nullptr, nullptr, Options, BBName);
776
777 // If this is a critical edge, let SplitKnownCriticalEdge do it.
778 return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
779 }
780
781 // If the edge isn't critical, then BB has a single successor or Succ has a
782 // single pred. Split the block.
783 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
784 // If the successor only has a single pred, split the top of the successor
785 // block.
786 assert(SP == BB && "CFG broken");
787 SP = nullptr;
788 return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName,
789 /*Before=*/true);
790 }
791
792 // Otherwise, if BB has a single successor, split it at the bottom of the
793 // block.
794 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
795 "Should have a single succ!");
796 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
797}
798
800 if (auto *II = dyn_cast<InvokeInst>(TI))
801 II->setUnwindDest(Succ);
802 else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
803 CS->setUnwindDest(Succ);
804 else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
805 CR->setUnwindDest(Succ);
806 else
807 llvm_unreachable("unexpected terminator instruction");
808}
809
811 BasicBlock *NewPred, PHINode *Until) {
812 int BBIdx = 0;
813 for (PHINode &PN : DestBB->phis()) {
814 // We manually update the LandingPadReplacement PHINode and it is the last
815 // PHI Node. So, if we find it, we are done.
816 if (Until == &PN)
817 break;
818
819 // Reuse the previous value of BBIdx if it lines up. In cases where we
820 // have multiple phi nodes with *lots* of predecessors, this is a speed
821 // win because we don't have to scan the PHI looking for TIBB. This
822 // happens because the BB list of PHI nodes are usually in the same
823 // order.
824 if (PN.getIncomingBlock(BBIdx) != OldPred)
825 BBIdx = PN.getBasicBlockIndex(OldPred);
826
827 assert(BBIdx != -1 && "Invalid PHI Index!");
828 PN.setIncomingBlock(BBIdx, NewPred);
829 }
830}
831
833 LandingPadInst *OriginalPad,
834 PHINode *LandingPadReplacement,
836 const Twine &BBName) {
837
838 auto *PadInst = Succ->getFirstNonPHI();
839 if (!LandingPadReplacement && !PadInst->isEHPad())
840 return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
841
842 auto *LI = Options.LI;
844 // Check if extra modifications will be required to preserve loop-simplify
845 // form after splitting. If it would require splitting blocks with IndirectBr
846 // terminators, bail out if preserving loop-simplify form is requested.
847 if (Options.PreserveLoopSimplify && LI) {
848 if (Loop *BBLoop = LI->getLoopFor(BB)) {
849
850 // The only way that we can break LoopSimplify form by splitting a
851 // critical edge is when there exists some edge from BBLoop to Succ *and*
852 // the only edge into Succ from outside of BBLoop is that of NewBB after
853 // the split. If the first isn't true, then LoopSimplify still holds,
854 // NewBB is the new exit block and it has no non-loop predecessors. If the
855 // second isn't true, then Succ was not in LoopSimplify form prior to
856 // the split as it had a non-loop predecessor. In both of these cases,
857 // the predecessor must be directly in BBLoop, not in a subloop, or again
858 // LoopSimplify doesn't hold.
859 for (BasicBlock *P : predecessors(Succ)) {
860 if (P == BB)
861 continue; // The new block is known.
862 if (LI->getLoopFor(P) != BBLoop) {
863 // Loop is not in LoopSimplify form, no need to re simplify after
864 // splitting edge.
865 LoopPreds.clear();
866 break;
867 }
868 LoopPreds.push_back(P);
869 }
870 // Loop-simplify form can be preserved, if we can split all in-loop
871 // predecessors.
872 if (any_of(LoopPreds, [](BasicBlock *Pred) {
873 return isa<IndirectBrInst>(Pred->getTerminator());
874 })) {
875 return nullptr;
876 }
877 }
878 }
879
880 auto *NewBB =
881 BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
882 setUnwindEdgeTo(BB->getTerminator(), NewBB);
883 updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
884
885 if (LandingPadReplacement) {
886 auto *NewLP = OriginalPad->clone();
887 auto *Terminator = BranchInst::Create(Succ, NewBB);
888 NewLP->insertBefore(Terminator);
889 LandingPadReplacement->addIncoming(NewLP, NewBB);
890 } else {
891 Value *ParentPad = nullptr;
892 if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
893 ParentPad = FuncletPad->getParentPad();
894 else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
895 ParentPad = CatchSwitch->getParentPad();
896 else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
897 ParentPad = CleanupPad->getParentPad();
898 else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
899 ParentPad = LandingPad->getParent();
900 else
901 llvm_unreachable("handling for other EHPads not implemented yet");
902
903 auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
904 CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
905 }
906
907 auto *DT = Options.DT;
908 auto *MSSAU = Options.MSSAU;
909 if (!DT && !LI)
910 return NewBB;
911
912 if (DT) {
913 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
915
916 Updates.push_back({DominatorTree::Insert, BB, NewBB});
917 Updates.push_back({DominatorTree::Insert, NewBB, Succ});
918 Updates.push_back({DominatorTree::Delete, BB, Succ});
919
920 DTU.applyUpdates(Updates);
921 DTU.flush();
922
923 if (MSSAU) {
924 MSSAU->applyUpdates(Updates, *DT);
925 if (VerifyMemorySSA)
926 MSSAU->getMemorySSA()->verifyMemorySSA();
927 }
928 }
929
930 if (LI) {
931 if (Loop *BBLoop = LI->getLoopFor(BB)) {
932 // If one or the other blocks were not in a loop, the new block is not
933 // either, and thus LI doesn't need to be updated.
934 if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
935 if (BBLoop == SuccLoop) {
936 // Both in the same loop, the NewBB joins loop.
937 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
938 } else if (BBLoop->contains(SuccLoop)) {
939 // Edge from an outer loop to an inner loop. Add to the outer loop.
940 BBLoop->addBasicBlockToLoop(NewBB, *LI);
941 } else if (SuccLoop->contains(BBLoop)) {
942 // Edge from an inner loop to an outer loop. Add to the outer loop.
943 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
944 } else {
945 // Edge from two loops with no containment relation. Because these
946 // are natural loops, we know that the destination block must be the
947 // header of its loop (adding a branch into a loop elsewhere would
948 // create an irreducible loop).
949 assert(SuccLoop->getHeader() == Succ &&
950 "Should not create irreducible loops!");
951 if (Loop *P = SuccLoop->getParentLoop())
952 P->addBasicBlockToLoop(NewBB, *LI);
953 }
954 }
955
956 // If BB is in a loop and Succ is outside of that loop, we may need to
957 // update LoopSimplify form and LCSSA form.
958 if (!BBLoop->contains(Succ)) {
959 assert(!BBLoop->contains(NewBB) &&
960 "Split point for loop exit is contained in loop!");
961
962 // Update LCSSA form in the newly created exit block.
963 if (Options.PreserveLCSSA) {
964 createPHIsForSplitLoopExit(BB, NewBB, Succ);
965 }
966
967 if (!LoopPreds.empty()) {
969 Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
970 if (Options.PreserveLCSSA)
971 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
972 }
973 }
974 }
975 }
976
977 return NewBB;
978}
979
981 BasicBlock *SplitBB, BasicBlock *DestBB) {
982 // SplitBB shouldn't have anything non-trivial in it yet.
983 assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
984 SplitBB->isLandingPad()) &&
985 "SplitBB has non-PHI nodes!");
986
987 // For each PHI in the destination block.
988 for (PHINode &PN : DestBB->phis()) {
989 int Idx = PN.getBasicBlockIndex(SplitBB);
990 assert(Idx >= 0 && "Invalid Block Index");
991 Value *V = PN.getIncomingValue(Idx);
992
993 // If the input is a PHI which already satisfies LCSSA, don't create
994 // a new one.
995 if (const PHINode *VP = dyn_cast<PHINode>(V))
996 if (VP->getParent() == SplitBB)
997 continue;
998
999 // Otherwise a new PHI is needed. Create one and populate it.
1000 PHINode *NewPN = PHINode::Create(PN.getType(), Preds.size(), "split");
1001 BasicBlock::iterator InsertPos =
1002 SplitBB->isLandingPad() ? SplitBB->begin()
1003 : SplitBB->getTerminator()->getIterator();
1004 NewPN->insertBefore(InsertPos);
1005 for (BasicBlock *BB : Preds)
1006 NewPN->addIncoming(V, BB);
1007
1008 // Update the original PHI.
1009 PN.setIncomingValue(Idx, NewPN);
1010 }
1011}
1012
1013unsigned
1016 unsigned NumBroken = 0;
1017 for (BasicBlock &BB : F) {
1018 Instruction *TI = BB.getTerminator();
1019 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
1020 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1021 if (SplitCriticalEdge(TI, i, Options))
1022 ++NumBroken;
1023 }
1024 return NumBroken;
1025}
1026
1028 DomTreeUpdater *DTU, DominatorTree *DT,
1029 LoopInfo *LI, MemorySSAUpdater *MSSAU,
1030 const Twine &BBName, bool Before) {
1031 if (Before) {
1032 DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1033 return splitBlockBefore(Old, SplitPt,
1034 DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU,
1035 BBName);
1036 }
1037 BasicBlock::iterator SplitIt = SplitPt;
1038 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
1039 ++SplitIt;
1040 assert(SplitIt != SplitPt->getParent()->end());
1041 }
1042 std::string Name = BBName.str();
1043 BasicBlock *New = Old->splitBasicBlock(
1044 SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
1045
1046 // The new block lives in whichever loop the old one did. This preserves
1047 // LCSSA as well, because we force the split point to be after any PHI nodes.
1048 if (LI)
1049 if (Loop *L = LI->getLoopFor(Old))
1050 L->addBasicBlockToLoop(New, *LI);
1051
1052 if (DTU) {
1054 // Old dominates New. New node dominates all other nodes dominated by Old.
1055 SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld;
1056 Updates.push_back({DominatorTree::Insert, Old, New});
1057 Updates.reserve(Updates.size() + 2 * succ_size(New));
1058 for (BasicBlock *SuccessorOfOld : successors(New))
1059 if (UniqueSuccessorsOfOld.insert(SuccessorOfOld).second) {
1060 Updates.push_back({DominatorTree::Insert, New, SuccessorOfOld});
1061 Updates.push_back({DominatorTree::Delete, Old, SuccessorOfOld});
1062 }
1063
1064 DTU->applyUpdates(Updates);
1065 } else if (DT)
1066 // Old dominates New. New node dominates all other nodes dominated by Old.
1067 if (DomTreeNode *OldNode = DT->getNode(Old)) {
1068 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1069
1070 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
1071 for (DomTreeNode *I : Children)
1072 DT->changeImmediateDominator(I, NewNode);
1073 }
1074
1075 // Move MemoryAccesses still tracked in Old, but part of New now.
1076 // Update accesses in successor blocks accordingly.
1077 if (MSSAU)
1078 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
1079
1080 return New;
1081}
1082
1084 DominatorTree *DT, LoopInfo *LI,
1085 MemorySSAUpdater *MSSAU, const Twine &BBName,
1086 bool Before) {
1087 return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName,
1088 Before);
1089}
1091 DomTreeUpdater *DTU, LoopInfo *LI,
1092 MemorySSAUpdater *MSSAU, const Twine &BBName,
1093 bool Before) {
1094 return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName,
1095 Before);
1096}
1097
1099 DomTreeUpdater *DTU, LoopInfo *LI,
1100 MemorySSAUpdater *MSSAU,
1101 const Twine &BBName) {
1102
1103 BasicBlock::iterator SplitIt = SplitPt;
1104 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
1105 ++SplitIt;
1106 std::string Name = BBName.str();
1107 BasicBlock *New = Old->splitBasicBlock(
1108 SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
1109 /* Before=*/true);
1110
1111 // The new block lives in whichever loop the old one did. This preserves
1112 // LCSSA as well, because we force the split point to be after any PHI nodes.
1113 if (LI)
1114 if (Loop *L = LI->getLoopFor(Old))
1115 L->addBasicBlockToLoop(New, *LI);
1116
1117 if (DTU) {
1119 // New dominates Old. The predecessor nodes of the Old node dominate
1120 // New node.
1121 SmallPtrSet<BasicBlock *, 8> UniquePredecessorsOfOld;
1122 DTUpdates.push_back({DominatorTree::Insert, New, Old});
1123 DTUpdates.reserve(DTUpdates.size() + 2 * pred_size(New));
1124 for (BasicBlock *PredecessorOfOld : predecessors(New))
1125 if (UniquePredecessorsOfOld.insert(PredecessorOfOld).second) {
1126 DTUpdates.push_back({DominatorTree::Insert, PredecessorOfOld, New});
1127 DTUpdates.push_back({DominatorTree::Delete, PredecessorOfOld, Old});
1128 }
1129
1130 DTU->applyUpdates(DTUpdates);
1131
1132 // Move MemoryAccesses still tracked in Old, but part of New now.
1133 // Update accesses in successor blocks accordingly.
1134 if (MSSAU) {
1135 MSSAU->applyUpdates(DTUpdates, DTU->getDomTree());
1136 if (VerifyMemorySSA)
1137 MSSAU->getMemorySSA()->verifyMemorySSA();
1138 }
1139 }
1140 return New;
1141}
1142
1143/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
1146 DomTreeUpdater *DTU, DominatorTree *DT,
1147 LoopInfo *LI, MemorySSAUpdater *MSSAU,
1148 bool PreserveLCSSA, bool &HasLoopExit) {
1149 // Update dominator tree if available.
1150 if (DTU) {
1151 // Recalculation of DomTree is needed when updating a forward DomTree and
1152 // the Entry BB is replaced.
1153 if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
1154 // The entry block was removed and there is no external interface for
1155 // the dominator tree to be notified of this change. In this corner-case
1156 // we recalculate the entire tree.
1157 DTU->recalculate(*NewBB->getParent());
1158 } else {
1159 // Split block expects NewBB to have a non-empty set of predecessors.
1161 SmallPtrSet<BasicBlock *, 8> UniquePreds;
1162 Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
1163 Updates.reserve(Updates.size() + 2 * Preds.size());
1164 for (auto *Pred : Preds)
1165 if (UniquePreds.insert(Pred).second) {
1166 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
1167 Updates.push_back({DominatorTree::Delete, Pred, OldBB});
1168 }
1169 DTU->applyUpdates(Updates);
1170 }
1171 } else if (DT) {
1172 if (OldBB == DT->getRootNode()->getBlock()) {
1173 assert(NewBB->isEntryBlock());
1174 DT->setNewRoot(NewBB);
1175 } else {
1176 // Split block expects NewBB to have a non-empty set of predecessors.
1177 DT->splitBlock(NewBB);
1178 }
1179 }
1180
1181 // Update MemoryPhis after split if MemorySSA is available
1182 if (MSSAU)
1183 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
1184
1185 // The rest of the logic is only relevant for updating the loop structures.
1186 if (!LI)
1187 return;
1188
1189 if (DTU && DTU->hasDomTree())
1190 DT = &DTU->getDomTree();
1191 assert(DT && "DT should be available to update LoopInfo!");
1192 Loop *L = LI->getLoopFor(OldBB);
1193
1194 // If we need to preserve loop analyses, collect some information about how
1195 // this split will affect loops.
1196 bool IsLoopEntry = !!L;
1197 bool SplitMakesNewLoopHeader = false;
1198 for (BasicBlock *Pred : Preds) {
1199 // Preds that are not reachable from entry should not be used to identify if
1200 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
1201 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
1202 // as true and make the NewBB the header of some loop. This breaks LI.
1203 if (!DT->isReachableFromEntry(Pred))
1204 continue;
1205 // If we need to preserve LCSSA, determine if any of the preds is a loop
1206 // exit.
1207 if (PreserveLCSSA)
1208 if (Loop *PL = LI->getLoopFor(Pred))
1209 if (!PL->contains(OldBB))
1210 HasLoopExit = true;
1211
1212 // If we need to preserve LoopInfo, note whether any of the preds crosses
1213 // an interesting loop boundary.
1214 if (!L)
1215 continue;
1216 if (L->contains(Pred))
1217 IsLoopEntry = false;
1218 else
1219 SplitMakesNewLoopHeader = true;
1220 }
1221
1222 // Unless we have a loop for OldBB, nothing else to do here.
1223 if (!L)
1224 return;
1225
1226 if (IsLoopEntry) {
1227 // Add the new block to the nearest enclosing loop (and not an adjacent
1228 // loop). To find this, examine each of the predecessors and determine which
1229 // loops enclose them, and select the most-nested loop which contains the
1230 // loop containing the block being split.
1231 Loop *InnermostPredLoop = nullptr;
1232 for (BasicBlock *Pred : Preds) {
1233 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
1234 // Seek a loop which actually contains the block being split (to avoid
1235 // adjacent loops).
1236 while (PredLoop && !PredLoop->contains(OldBB))
1237 PredLoop = PredLoop->getParentLoop();
1238
1239 // Select the most-nested of these loops which contains the block.
1240 if (PredLoop && PredLoop->contains(OldBB) &&
1241 (!InnermostPredLoop ||
1242 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
1243 InnermostPredLoop = PredLoop;
1244 }
1245 }
1246
1247 if (InnermostPredLoop)
1248 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
1249 } else {
1250 L->addBasicBlockToLoop(NewBB, *LI);
1251 if (SplitMakesNewLoopHeader)
1252 L->moveToHeader(NewBB);
1253 }
1254}
1255
1256/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
1257/// This also updates AliasAnalysis, if available.
1258static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
1260 bool HasLoopExit) {
1261 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
1262 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
1263 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
1264 PHINode *PN = cast<PHINode>(I++);
1265
1266 // Check to see if all of the values coming in are the same. If so, we
1267 // don't need to create a new PHI node, unless it's needed for LCSSA.
1268 Value *InVal = nullptr;
1269 if (!HasLoopExit) {
1270 InVal = PN->getIncomingValueForBlock(Preds[0]);
1271 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1272 if (!PredSet.count(PN->getIncomingBlock(i)))
1273 continue;
1274 if (!InVal)
1275 InVal = PN->getIncomingValue(i);
1276 else if (InVal != PN->getIncomingValue(i)) {
1277 InVal = nullptr;
1278 break;
1279 }
1280 }
1281 }
1282
1283 if (InVal) {
1284 // If all incoming values for the new PHI would be the same, just don't
1285 // make a new PHI. Instead, just remove the incoming values from the old
1286 // PHI.
1288 [&](unsigned Idx) {
1289 return PredSet.contains(PN->getIncomingBlock(Idx));
1290 },
1291 /* DeletePHIIfEmpty */ false);
1292
1293 // Add an incoming value to the PHI node in the loop for the preheader
1294 // edge.
1295 PN->addIncoming(InVal, NewBB);
1296 continue;
1297 }
1298
1299 // If the values coming into the block are not the same, we need a new
1300 // PHI.
1301 // Create the new PHI node, insert it into NewBB at the end of the block
1302 PHINode *NewPHI =
1303 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI->getIterator());
1304
1305 // NOTE! This loop walks backwards for a reason! First off, this minimizes
1306 // the cost of removal if we end up removing a large number of values, and
1307 // second off, this ensures that the indices for the incoming values aren't
1308 // invalidated when we remove one.
1309 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
1310 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
1311 if (PredSet.count(IncomingBB)) {
1312 Value *V = PN->removeIncomingValue(i, false);
1313 NewPHI->addIncoming(V, IncomingBB);
1314 }
1315 }
1316
1317 PN->addIncoming(NewPHI, NewBB);
1318 }
1319}
1320
1322 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1323 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1324 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1325 MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
1326
1327static BasicBlock *
1329 const char *Suffix, DomTreeUpdater *DTU,
1330 DominatorTree *DT, LoopInfo *LI,
1331 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1332 // Do not attempt to split that which cannot be split.
1333 if (!BB->canSplitPredecessors())
1334 return nullptr;
1335
1336 // For the landingpads we need to act a bit differently.
1337 // Delegate this work to the SplitLandingPadPredecessors.
1338 if (BB->isLandingPad()) {
1340 std::string NewName = std::string(Suffix) + ".split-lp";
1341
1342 SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
1343 DTU, DT, LI, MSSAU, PreserveLCSSA);
1344 return NewBBs[0];
1345 }
1346
1347 // Create new basic block, insert right before the original block.
1349 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
1350
1351 // The new block unconditionally branches to the old block.
1352 BranchInst *BI = BranchInst::Create(BB, NewBB);
1353
1354 Loop *L = nullptr;
1355 BasicBlock *OldLatch = nullptr;
1356 // Splitting the predecessors of a loop header creates a preheader block.
1357 if (LI && LI->isLoopHeader(BB)) {
1358 L = LI->getLoopFor(BB);
1359 // Using the loop start line number prevents debuggers stepping into the
1360 // loop body for this instruction.
1361 BI->setDebugLoc(L->getStartLoc());
1362
1363 // If BB is the header of the Loop, it is possible that the loop is
1364 // modified, such that the current latch does not remain the latch of the
1365 // loop. If that is the case, the loop metadata from the current latch needs
1366 // to be applied to the new latch.
1367 OldLatch = L->getLoopLatch();
1368 } else
1370
1371 // Move the edges from Preds to point to NewBB instead of BB.
1372 for (BasicBlock *Pred : Preds) {
1373 // This is slightly more strict than necessary; the minimum requirement
1374 // is that there be no more than one indirectbr branching to BB. And
1375 // all BlockAddress uses would need to be updated.
1376 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1377 "Cannot split an edge from an IndirectBrInst");
1378 Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
1379 }
1380
1381 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
1382 // node becomes an incoming value for BB's phi node. However, if the Preds
1383 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
1384 // account for the newly created predecessor.
1385 if (Preds.empty()) {
1386 // Insert dummy values as the incoming value.
1387 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
1388 cast<PHINode>(I)->addIncoming(PoisonValue::get(I->getType()), NewBB);
1389 }
1390
1391 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
1392 bool HasLoopExit = false;
1393 UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
1394 HasLoopExit);
1395
1396 if (!Preds.empty()) {
1397 // Update the PHI nodes in BB with the values coming from NewBB.
1398 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
1399 }
1400
1401 if (OldLatch) {
1402 BasicBlock *NewLatch = L->getLoopLatch();
1403 if (NewLatch != OldLatch) {
1404 MDNode *MD = OldLatch->getTerminator()->getMetadata("llvm.loop");
1405 NewLatch->getTerminator()->setMetadata("llvm.loop", MD);
1406 // It's still possible that OldLatch is the latch of another inner loop,
1407 // in which case we do not remove the metadata.
1408 Loop *IL = LI->getLoopFor(OldLatch);
1409 if (IL && IL->getLoopLatch() != OldLatch)
1410 OldLatch->getTerminator()->setMetadata("llvm.loop", nullptr);
1411 }
1412 }
1413
1414 return NewBB;
1415}
1416
1419 const char *Suffix, DominatorTree *DT,
1420 LoopInfo *LI, MemorySSAUpdater *MSSAU,
1421 bool PreserveLCSSA) {
1422 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI,
1423 MSSAU, PreserveLCSSA);
1424}
1427 const char *Suffix,
1428 DomTreeUpdater *DTU, LoopInfo *LI,
1429 MemorySSAUpdater *MSSAU,
1430 bool PreserveLCSSA) {
1431 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
1432 /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA);
1433}
1434
1436 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1437 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1438 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1439 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1440 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
1441
1442 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
1443 // it right before the original block.
1444 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
1445 OrigBB->getName() + Suffix1,
1446 OrigBB->getParent(), OrigBB);
1447 NewBBs.push_back(NewBB1);
1448
1449 // The new block unconditionally branches to the old block.
1450 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
1451 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
1452
1453 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
1454 for (BasicBlock *Pred : Preds) {
1455 // This is slightly more strict than necessary; the minimum requirement
1456 // is that there be no more than one indirectbr branching to BB. And
1457 // all BlockAddress uses would need to be updated.
1458 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1459 "Cannot split an edge from an IndirectBrInst");
1460 Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
1461 }
1462
1463 bool HasLoopExit = false;
1464 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
1465 PreserveLCSSA, HasLoopExit);
1466
1467 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
1468 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
1469
1470 // Move the remaining edges from OrigBB to point to NewBB2.
1471 SmallVector<BasicBlock*, 8> NewBB2Preds;
1472 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
1473 i != e; ) {
1474 BasicBlock *Pred = *i++;
1475 if (Pred == NewBB1) continue;
1476 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1477 "Cannot split an edge from an IndirectBrInst");
1478 NewBB2Preds.push_back(Pred);
1479 e = pred_end(OrigBB);
1480 }
1481
1482 BasicBlock *NewBB2 = nullptr;
1483 if (!NewBB2Preds.empty()) {
1484 // Create another basic block for the rest of OrigBB's predecessors.
1485 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
1486 OrigBB->getName() + Suffix2,
1487 OrigBB->getParent(), OrigBB);
1488 NewBBs.push_back(NewBB2);
1489
1490 // The new block unconditionally branches to the old block.
1491 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
1492 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
1493
1494 // Move the remaining edges from OrigBB to point to NewBB2.
1495 for (BasicBlock *NewBB2Pred : NewBB2Preds)
1496 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
1497
1498 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
1499 HasLoopExit = false;
1500 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
1501 PreserveLCSSA, HasLoopExit);
1502
1503 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
1504 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
1505 }
1506
1507 LandingPadInst *LPad = OrigBB->getLandingPadInst();
1508 Instruction *Clone1 = LPad->clone();
1509 Clone1->setName(Twine("lpad") + Suffix1);
1510 Clone1->insertInto(NewBB1, NewBB1->getFirstInsertionPt());
1511
1512 if (NewBB2) {
1513 Instruction *Clone2 = LPad->clone();
1514 Clone2->setName(Twine("lpad") + Suffix2);
1515 Clone2->insertInto(NewBB2, NewBB2->getFirstInsertionPt());
1516
1517 // Create a PHI node for the two cloned landingpad instructions only
1518 // if the original landingpad instruction has some uses.
1519 if (!LPad->use_empty()) {
1520 assert(!LPad->getType()->isTokenTy() &&
1521 "Split cannot be applied if LPad is token type. Otherwise an "
1522 "invalid PHINode of token type would be created.");
1523 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad->getIterator());
1524 PN->addIncoming(Clone1, NewBB1);
1525 PN->addIncoming(Clone2, NewBB2);
1526 LPad->replaceAllUsesWith(PN);
1527 }
1528 LPad->eraseFromParent();
1529 } else {
1530 // There is no second clone. Just replace the landing pad with the first
1531 // clone.
1532 LPad->replaceAllUsesWith(Clone1);
1533 LPad->eraseFromParent();
1534 }
1535}
1536
1539 const char *Suffix1, const char *Suffix2,
1541 DomTreeUpdater *DTU, LoopInfo *LI,
1542 MemorySSAUpdater *MSSAU,
1543 bool PreserveLCSSA) {
1544 return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
1545 NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU,
1546 PreserveLCSSA);
1547}
1548
1550 BasicBlock *Pred,
1551 DomTreeUpdater *DTU) {
1552 Instruction *UncondBranch = Pred->getTerminator();
1553 // Clone the return and add it to the end of the predecessor.
1554 Instruction *NewRet = RI->clone();
1555 NewRet->insertInto(Pred, Pred->end());
1556
1557 // If the return instruction returns a value, and if the value was a
1558 // PHI node in "BB", propagate the right value into the return.
1559 for (Use &Op : NewRet->operands()) {
1560 Value *V = Op;
1561 Instruction *NewBC = nullptr;
1562 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
1563 // Return value might be bitcasted. Clone and insert it before the
1564 // return instruction.
1565 V = BCI->getOperand(0);
1566 NewBC = BCI->clone();
1567 NewBC->insertInto(Pred, NewRet->getIterator());
1568 Op = NewBC;
1569 }
1570
1571 Instruction *NewEV = nullptr;
1572 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
1573 V = EVI->getOperand(0);
1574 NewEV = EVI->clone();
1575 if (NewBC) {
1576 NewBC->setOperand(0, NewEV);
1577 NewEV->insertInto(Pred, NewBC->getIterator());
1578 } else {
1579 NewEV->insertInto(Pred, NewRet->getIterator());
1580 Op = NewEV;
1581 }
1582 }
1583
1584 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1585 if (PN->getParent() == BB) {
1586 if (NewEV) {
1587 NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
1588 } else if (NewBC)
1589 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
1590 else
1591 Op = PN->getIncomingValueForBlock(Pred);
1592 }
1593 }
1594 }
1595
1596 // Update any PHI nodes in the returning block to realize that we no
1597 // longer branch to them.
1598 BB->removePredecessor(Pred);
1599 UncondBranch->eraseFromParent();
1600
1601 if (DTU)
1602 DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
1603
1604 return cast<ReturnInst>(NewRet);
1605}
1606
1608 BasicBlock::iterator SplitBefore,
1609 bool Unreachable,
1610 MDNode *BranchWeights,
1611 DomTreeUpdater *DTU, LoopInfo *LI,
1612 BasicBlock *ThenBlock) {
1614 Cond, SplitBefore, &ThenBlock, /* ElseBlock */ nullptr,
1615 /* UnreachableThen */ Unreachable,
1616 /* UnreachableElse */ false, BranchWeights, DTU, LI);
1617 return ThenBlock->getTerminator();
1618}
1619
1621 BasicBlock::iterator SplitBefore,
1622 bool Unreachable,
1623 MDNode *BranchWeights,
1624 DomTreeUpdater *DTU, LoopInfo *LI,
1625 BasicBlock *ElseBlock) {
1627 Cond, SplitBefore, /* ThenBlock */ nullptr, &ElseBlock,
1628 /* UnreachableThen */ false,
1629 /* UnreachableElse */ Unreachable, BranchWeights, DTU, LI);
1630 return ElseBlock->getTerminator();
1631}
1632
1634 Instruction **ThenTerm,
1635 Instruction **ElseTerm,
1636 MDNode *BranchWeights,
1637 DomTreeUpdater *DTU, LoopInfo *LI) {
1638 BasicBlock *ThenBlock = nullptr;
1639 BasicBlock *ElseBlock = nullptr;
1641 Cond, SplitBefore, &ThenBlock, &ElseBlock, /* UnreachableThen */ false,
1642 /* UnreachableElse */ false, BranchWeights, DTU, LI);
1643
1644 *ThenTerm = ThenBlock->getTerminator();
1645 *ElseTerm = ElseBlock->getTerminator();
1646}
1647
1649 Value *Cond, BasicBlock::iterator SplitBefore, BasicBlock **ThenBlock,
1650 BasicBlock **ElseBlock, bool UnreachableThen, bool UnreachableElse,
1651 MDNode *BranchWeights, DomTreeUpdater *DTU, LoopInfo *LI) {
1652 assert((ThenBlock || ElseBlock) &&
1653 "At least one branch block must be created");
1654 assert((!UnreachableThen || !UnreachableElse) &&
1655 "Split block tail must be reachable");
1656
1658 SmallPtrSet<BasicBlock *, 8> UniqueOrigSuccessors;
1659 BasicBlock *Head = SplitBefore->getParent();
1660 if (DTU) {
1661 UniqueOrigSuccessors.insert(succ_begin(Head), succ_end(Head));
1662 Updates.reserve(4 + 2 * UniqueOrigSuccessors.size());
1663 }
1664
1665 LLVMContext &C = Head->getContext();
1666 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
1667 BasicBlock *TrueBlock = Tail;
1668 BasicBlock *FalseBlock = Tail;
1669 bool ThenToTailEdge = false;
1670 bool ElseToTailEdge = false;
1671
1672 // Encapsulate the logic around creation/insertion/etc of a new block.
1673 auto handleBlock = [&](BasicBlock **PBB, bool Unreachable, BasicBlock *&BB,
1674 bool &ToTailEdge) {
1675 if (PBB == nullptr)
1676 return; // Do not create/insert a block.
1677
1678 if (*PBB)
1679 BB = *PBB; // Caller supplied block, use it.
1680 else {
1681 // Create a new block.
1682 BB = BasicBlock::Create(C, "", Head->getParent(), Tail);
1683 if (Unreachable)
1684 (void)new UnreachableInst(C, BB);
1685 else {
1686 (void)BranchInst::Create(Tail, BB);
1687 ToTailEdge = true;
1688 }
1689 BB->getTerminator()->setDebugLoc(SplitBefore->getDebugLoc());
1690 // Pass the new block back to the caller.
1691 *PBB = BB;
1692 }
1693 };
1694
1695 handleBlock(ThenBlock, UnreachableThen, TrueBlock, ThenToTailEdge);
1696 handleBlock(ElseBlock, UnreachableElse, FalseBlock, ElseToTailEdge);
1697
1698 Instruction *HeadOldTerm = Head->getTerminator();
1699 BranchInst *HeadNewTerm =
1700 BranchInst::Create(/*ifTrue*/ TrueBlock, /*ifFalse*/ FalseBlock, Cond);
1701 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
1702 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
1703
1704 if (DTU) {
1705 Updates.emplace_back(DominatorTree::Insert, Head, TrueBlock);
1706 Updates.emplace_back(DominatorTree::Insert, Head, FalseBlock);
1707 if (ThenToTailEdge)
1708 Updates.emplace_back(DominatorTree::Insert, TrueBlock, Tail);
1709 if (ElseToTailEdge)
1710 Updates.emplace_back(DominatorTree::Insert, FalseBlock, Tail);
1711 for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1712 Updates.emplace_back(DominatorTree::Insert, Tail, UniqueOrigSuccessor);
1713 for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1714 Updates.emplace_back(DominatorTree::Delete, Head, UniqueOrigSuccessor);
1715 DTU->applyUpdates(Updates);
1716 }
1717
1718 if (LI) {
1719 if (Loop *L = LI->getLoopFor(Head); L) {
1720 if (ThenToTailEdge)
1721 L->addBasicBlockToLoop(TrueBlock, *LI);
1722 if (ElseToTailEdge)
1723 L->addBasicBlockToLoop(FalseBlock, *LI);
1724 L->addBasicBlockToLoop(Tail, *LI);
1725 }
1726 }
1727}
1728
1729std::pair<Instruction*, Value*>
1731 BasicBlock *LoopPred = SplitBefore->getParent();
1732 BasicBlock *LoopBody = SplitBlock(SplitBefore->getParent(), SplitBefore);
1733 BasicBlock *LoopExit = SplitBlock(SplitBefore->getParent(), SplitBefore);
1734
1735 auto *Ty = End->getType();
1736 auto &DL = SplitBefore->getModule()->getDataLayout();
1737 const unsigned Bitwidth = DL.getTypeSizeInBits(Ty);
1738
1739 IRBuilder<> Builder(LoopBody->getTerminator());
1740 auto *IV = Builder.CreatePHI(Ty, 2, "iv");
1741 auto *IVNext =
1742 Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
1743 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
1744 auto *IVCheck = Builder.CreateICmpEQ(IVNext, End,
1745 IV->getName() + ".check");
1746 Builder.CreateCondBr(IVCheck, LoopExit, LoopBody);
1747 LoopBody->getTerminator()->eraseFromParent();
1748
1749 // Populate the IV PHI.
1750 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPred);
1751 IV->addIncoming(IVNext, LoopBody);
1752
1753 return std::make_pair(LoopBody->getFirstNonPHI(), IV);
1754}
1755
1757 Type *IndexTy, Instruction *InsertBefore,
1758 std::function<void(IRBuilderBase&, Value*)> Func) {
1759
1760 IRBuilder<> IRB(InsertBefore);
1761
1762 if (EC.isScalable()) {
1763 Value *NumElements = IRB.CreateElementCount(IndexTy, EC);
1764
1765 auto [BodyIP, Index] =
1766 SplitBlockAndInsertSimpleForLoop(NumElements, InsertBefore);
1767
1768 IRB.SetInsertPoint(BodyIP);
1769 Func(IRB, Index);
1770 return;
1771 }
1772
1773 unsigned Num = EC.getFixedValue();
1774 for (unsigned Idx = 0; Idx < Num; ++Idx) {
1775 IRB.SetInsertPoint(InsertBefore);
1776 Func(IRB, ConstantInt::get(IndexTy, Idx));
1777 }
1778}
1779
1781 Value *EVL, Instruction *InsertBefore,
1782 std::function<void(IRBuilderBase &, Value *)> Func) {
1783
1784 IRBuilder<> IRB(InsertBefore);
1785 Type *Ty = EVL->getType();
1786
1787 if (!isa<ConstantInt>(EVL)) {
1788 auto [BodyIP, Index] = SplitBlockAndInsertSimpleForLoop(EVL, InsertBefore);
1789 IRB.SetInsertPoint(BodyIP);
1790 Func(IRB, Index);
1791 return;
1792 }
1793
1794 unsigned Num = cast<ConstantInt>(EVL)->getZExtValue();
1795 for (unsigned Idx = 0; Idx < Num; ++Idx) {
1796 IRB.SetInsertPoint(InsertBefore);
1797 Func(IRB, ConstantInt::get(Ty, Idx));
1798 }
1799}
1800
1802 BasicBlock *&IfFalse) {
1803 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
1804 BasicBlock *Pred1 = nullptr;
1805 BasicBlock *Pred2 = nullptr;
1806
1807 if (SomePHI) {
1808 if (SomePHI->getNumIncomingValues() != 2)
1809 return nullptr;
1810 Pred1 = SomePHI->getIncomingBlock(0);
1811 Pred2 = SomePHI->getIncomingBlock(1);
1812 } else {
1813 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1814 if (PI == PE) // No predecessor
1815 return nullptr;
1816 Pred1 = *PI++;
1817 if (PI == PE) // Only one predecessor
1818 return nullptr;
1819 Pred2 = *PI++;
1820 if (PI != PE) // More than two predecessors
1821 return nullptr;
1822 }
1823
1824 // We can only handle branches. Other control flow will be lowered to
1825 // branches if possible anyway.
1826 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
1827 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
1828 if (!Pred1Br || !Pred2Br)
1829 return nullptr;
1830
1831 // Eliminate code duplication by ensuring that Pred1Br is conditional if
1832 // either are.
1833 if (Pred2Br->isConditional()) {
1834 // If both branches are conditional, we don't have an "if statement". In
1835 // reality, we could transform this case, but since the condition will be
1836 // required anyway, we stand no chance of eliminating it, so the xform is
1837 // probably not profitable.
1838 if (Pred1Br->isConditional())
1839 return nullptr;
1840
1841 std::swap(Pred1, Pred2);
1842 std::swap(Pred1Br, Pred2Br);
1843 }
1844
1845 if (Pred1Br->isConditional()) {
1846 // The only thing we have to watch out for here is to make sure that Pred2
1847 // doesn't have incoming edges from other blocks. If it does, the condition
1848 // doesn't dominate BB.
1849 if (!Pred2->getSinglePredecessor())
1850 return nullptr;
1851
1852 // If we found a conditional branch predecessor, make sure that it branches
1853 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
1854 if (Pred1Br->getSuccessor(0) == BB &&
1855 Pred1Br->getSuccessor(1) == Pred2) {
1856 IfTrue = Pred1;
1857 IfFalse = Pred2;
1858 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
1859 Pred1Br->getSuccessor(1) == BB) {
1860 IfTrue = Pred2;
1861 IfFalse = Pred1;
1862 } else {
1863 // We know that one arm of the conditional goes to BB, so the other must
1864 // go somewhere unrelated, and this must not be an "if statement".
1865 return nullptr;
1866 }
1867
1868 return Pred1Br;
1869 }
1870
1871 // Ok, if we got here, both predecessors end with an unconditional branch to
1872 // BB. Don't panic! If both blocks only have a single (identical)
1873 // predecessor, and THAT is a conditional branch, then we're all ok!
1874 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
1875 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
1876 return nullptr;
1877
1878 // Otherwise, if this is a conditional branch, then we can use it!
1879 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
1880 if (!BI) return nullptr;
1881
1882 assert(BI->isConditional() && "Two successors but not conditional?");
1883 if (BI->getSuccessor(0) == Pred1) {
1884 IfTrue = Pred1;
1885 IfFalse = Pred2;
1886 } else {
1887 IfTrue = Pred2;
1888 IfFalse = Pred1;
1889 }
1890 return BI;
1891}
1892
1893// After creating a control flow hub, the operands of PHINodes in an outgoing
1894// block Out no longer match the predecessors of that block. Predecessors of Out
1895// that are incoming blocks to the hub are now replaced by just one edge from
1896// the hub. To match this new control flow, the corresponding values from each
1897// PHINode must now be moved a new PHINode in the first guard block of the hub.
1898//
1899// This operation cannot be performed with SSAUpdater, because it involves one
1900// new use: If the block Out is in the list of Incoming blocks, then the newly
1901// created PHI in the Hub will use itself along that edge from Out to Hub.
1902static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock,
1904 BasicBlock *FirstGuardBlock) {
1905 auto I = Out->begin();
1906 while (I != Out->end() && isa<PHINode>(I)) {
1907 auto Phi = cast<PHINode>(I);
1908 auto NewPhi =
1909 PHINode::Create(Phi->getType(), Incoming.size(),
1910 Phi->getName() + ".moved", FirstGuardBlock->begin());
1911 for (auto *In : Incoming) {
1912 Value *V = UndefValue::get(Phi->getType());
1913 if (In == Out) {
1914 V = NewPhi;
1915 } else if (Phi->getBasicBlockIndex(In) != -1) {
1916 V = Phi->removeIncomingValue(In, false);
1917 }
1918 NewPhi->addIncoming(V, In);
1919 }
1920 assert(NewPhi->getNumIncomingValues() == Incoming.size());
1921 if (Phi->getNumOperands() == 0) {
1922 Phi->replaceAllUsesWith(NewPhi);
1923 I = Phi->eraseFromParent();
1924 continue;
1925 }
1926 Phi->addIncoming(NewPhi, GuardBlock);
1927 ++I;
1928 }
1929}
1930
1933
1934// Redirects the terminator of the incoming block to the first guard
1935// block in the hub. The condition of the original terminator (if it
1936// was conditional) and its original successors are returned as a
1937// tuple <condition, succ0, succ1>. The function additionally filters
1938// out successors that are not in the set of outgoing blocks.
1939//
1940// - condition is non-null iff the branch is conditional.
1941// - Succ1 is non-null iff the sole/taken target is an outgoing block.
1942// - Succ2 is non-null iff condition is non-null and the fallthrough
1943// target is an outgoing block.
1944static std::tuple<Value *, BasicBlock *, BasicBlock *>
1946 const BBSetVector &Outgoing) {
1947 assert(isa<BranchInst>(BB->getTerminator()) &&
1948 "Only support branch terminator.");
1949 auto Branch = cast<BranchInst>(BB->getTerminator());
1950 auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr;
1951
1952 BasicBlock *Succ0 = Branch->getSuccessor(0);
1953 BasicBlock *Succ1 = nullptr;
1954 Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr;
1955
1956 if (Branch->isUnconditional()) {
1957 Branch->setSuccessor(0, FirstGuardBlock);
1958 assert(Succ0);
1959 } else {
1960 Succ1 = Branch->getSuccessor(1);
1961 Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr;
1962 assert(Succ0 || Succ1);
1963 if (Succ0 && !Succ1) {
1964 Branch->setSuccessor(0, FirstGuardBlock);
1965 } else if (Succ1 && !Succ0) {
1966 Branch->setSuccessor(1, FirstGuardBlock);
1967 } else {
1968 Branch->eraseFromParent();
1969 BranchInst::Create(FirstGuardBlock, BB);
1970 }
1971 }
1972
1973 assert(Succ0 || Succ1);
1974 return std::make_tuple(Condition, Succ0, Succ1);
1975}
1976// Setup the branch instructions for guard blocks.
1977//
1978// Each guard block terminates in a conditional branch that transfers
1979// control to the corresponding outgoing block or the next guard
1980// block. The last guard block has two outgoing blocks as successors
1981// since the condition for the final outgoing block is trivially
1982// true. So we create one less block (including the first guard block)
1983// than the number of outgoing blocks.
1985 const BBSetVector &Outgoing,
1986 BBPredicates &GuardPredicates) {
1987 // To help keep the loop simple, temporarily append the last
1988 // outgoing block to the list of guard blocks.
1989 GuardBlocks.push_back(Outgoing.back());
1990
1991 for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) {
1992 auto Out = Outgoing[i];
1993 assert(GuardPredicates.count(Out));
1994 BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out],
1995 GuardBlocks[i]);
1996 }
1997
1998 // Remove the last block from the guard list.
1999 GuardBlocks.pop_back();
2000}
2001
2002/// We are using one integer to represent the block we are branching to. Then at
2003/// each guard block, the predicate was calcuated using a simple `icmp eq`.
2005 const BBSetVector &Incoming, const BBSetVector &Outgoing,
2006 SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates) {
2007 auto &Context = Incoming.front()->getContext();
2008 auto FirstGuardBlock = GuardBlocks.front();
2009
2011 "merged.bb.idx", FirstGuardBlock);
2012
2013 for (auto In : Incoming) {
2014 Value *Condition;
2015 BasicBlock *Succ0;
2016 BasicBlock *Succ1;
2017 std::tie(Condition, Succ0, Succ1) =
2018 redirectToHub(In, FirstGuardBlock, Outgoing);
2019 Value *IncomingId = nullptr;
2020 if (Succ0 && Succ1) {
2021 // target_bb_index = Condition ? index_of_succ0 : index_of_succ1.
2022 auto Succ0Iter = find(Outgoing, Succ0);
2023 auto Succ1Iter = find(Outgoing, Succ1);
2024 Value *Id0 = ConstantInt::get(Type::getInt32Ty(Context),
2025 std::distance(Outgoing.begin(), Succ0Iter));
2026 Value *Id1 = ConstantInt::get(Type::getInt32Ty(Context),
2027 std::distance(Outgoing.begin(), Succ1Iter));
2028 IncomingId = SelectInst::Create(Condition, Id0, Id1, "target.bb.idx",
2029 In->getTerminator()->getIterator());
2030 } else {
2031 // Get the index of the non-null successor.
2032 auto SuccIter = Succ0 ? find(Outgoing, Succ0) : find(Outgoing, Succ1);
2033 IncomingId = ConstantInt::get(Type::getInt32Ty(Context),
2034 std::distance(Outgoing.begin(), SuccIter));
2035 }
2036 Phi->addIncoming(IncomingId, In);
2037 }
2038
2039 for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2040 auto Out = Outgoing[i];
2041 auto Cmp = ICmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, Phi,
2042 ConstantInt::get(Type::getInt32Ty(Context), i),
2043 Out->getName() + ".predicate", GuardBlocks[i]);
2044 GuardPredicates[Out] = Cmp;
2045 }
2046}
2047
2048/// We record the predicate of each outgoing block using a phi of boolean.
2050 const BBSetVector &Incoming, const BBSetVector &Outgoing,
2051 SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates,
2052 SmallVectorImpl<WeakVH> &DeletionCandidates) {
2053 auto &Context = Incoming.front()->getContext();
2054 auto BoolTrue = ConstantInt::getTrue(Context);
2055 auto BoolFalse = ConstantInt::getFalse(Context);
2056 auto FirstGuardBlock = GuardBlocks.front();
2057
2058 // The predicate for the last outgoing is trivially true, and so we
2059 // process only the first N-1 successors.
2060 for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2061 auto Out = Outgoing[i];
2062 LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n");
2063
2064 auto Phi =
2066 StringRef("Guard.") + Out->getName(), FirstGuardBlock);
2067 GuardPredicates[Out] = Phi;
2068 }
2069
2070 for (auto *In : Incoming) {
2071 Value *Condition;
2072 BasicBlock *Succ0;
2073 BasicBlock *Succ1;
2074 std::tie(Condition, Succ0, Succ1) =
2075 redirectToHub(In, FirstGuardBlock, Outgoing);
2076
2077 // Optimization: Consider an incoming block A with both successors
2078 // Succ0 and Succ1 in the set of outgoing blocks. The predicates
2079 // for Succ0 and Succ1 complement each other. If Succ0 is visited
2080 // first in the loop below, control will branch to Succ0 using the
2081 // corresponding predicate. But if that branch is not taken, then
2082 // control must reach Succ1, which means that the incoming value of
2083 // the predicate from `In` is true for Succ1.
2084 bool OneSuccessorDone = false;
2085 for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2086 auto Out = Outgoing[i];
2087 PHINode *Phi = cast<PHINode>(GuardPredicates[Out]);
2088 if (Out != Succ0 && Out != Succ1) {
2089 Phi->addIncoming(BoolFalse, In);
2090 } else if (!Succ0 || !Succ1 || OneSuccessorDone) {
2091 // Optimization: When only one successor is an outgoing block,
2092 // the incoming predicate from `In` is always true.
2093 Phi->addIncoming(BoolTrue, In);
2094 } else {
2095 assert(Succ0 && Succ1);
2096 if (Out == Succ0) {
2097 Phi->addIncoming(Condition, In);
2098 } else {
2099 auto Inverted = invertCondition(Condition);
2100 DeletionCandidates.push_back(Condition);
2101 Phi->addIncoming(Inverted, In);
2102 }
2103 OneSuccessorDone = true;
2104 }
2105 }
2106 }
2107}
2108
2109// Capture the existing control flow as guard predicates, and redirect
2110// control flow from \p Incoming block through the \p GuardBlocks to the
2111// \p Outgoing blocks.
2112//
2113// There is one guard predicate for each outgoing block OutBB. The
2114// predicate represents whether the hub should transfer control flow
2115// to OutBB. These predicates are NOT ORTHOGONAL. The Hub evaluates
2116// them in the same order as the Outgoing set-vector, and control
2117// branches to the first outgoing block whose predicate evaluates to true.
2118static void
2120 SmallVectorImpl<WeakVH> &DeletionCandidates,
2121 const BBSetVector &Incoming,
2122 const BBSetVector &Outgoing, const StringRef Prefix,
2123 std::optional<unsigned> MaxControlFlowBooleans) {
2124 BBPredicates GuardPredicates;
2125 auto F = Incoming.front()->getParent();
2126
2127 for (int i = 0, e = Outgoing.size() - 1; i != e; ++i)
2128 GuardBlocks.push_back(
2129 BasicBlock::Create(F->getContext(), Prefix + ".guard", F));
2130
2131 // When we are using an integer to record which target block to jump to, we
2132 // are creating less live values, actually we are using one single integer to
2133 // store the index of the target block. When we are using booleans to store
2134 // the branching information, we need (N-1) boolean values, where N is the
2135 // number of outgoing block.
2136 if (!MaxControlFlowBooleans || Outgoing.size() <= *MaxControlFlowBooleans)
2137 calcPredicateUsingBooleans(Incoming, Outgoing, GuardBlocks, GuardPredicates,
2138 DeletionCandidates);
2139 else
2140 calcPredicateUsingInteger(Incoming, Outgoing, GuardBlocks, GuardPredicates);
2141
2142 setupBranchForGuard(GuardBlocks, Outgoing, GuardPredicates);
2143}
2144
2147 const BBSetVector &Incoming, const BBSetVector &Outgoing,
2148 const StringRef Prefix, std::optional<unsigned> MaxControlFlowBooleans) {
2149 if (Outgoing.size() < 2)
2150 return Outgoing.front();
2151
2153 if (DTU) {
2154 for (auto *In : Incoming) {
2155 for (auto Succ : successors(In))
2156 if (Outgoing.count(Succ))
2157 Updates.push_back({DominatorTree::Delete, In, Succ});
2158 }
2159 }
2160
2161 SmallVector<WeakVH, 8> DeletionCandidates;
2162 convertToGuardPredicates(GuardBlocks, DeletionCandidates, Incoming, Outgoing,
2163 Prefix, MaxControlFlowBooleans);
2164 auto FirstGuardBlock = GuardBlocks.front();
2165
2166 // Update the PHINodes in each outgoing block to match the new control flow.
2167 for (int i = 0, e = GuardBlocks.size(); i != e; ++i)
2168 reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock);
2169
2170 reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock);
2171
2172 if (DTU) {
2173 int NumGuards = GuardBlocks.size();
2174 assert((int)Outgoing.size() == NumGuards + 1);
2175
2176 for (auto In : Incoming)
2177 Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock});
2178
2179 for (int i = 0; i != NumGuards - 1; ++i) {
2180 Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]});
2181 Updates.push_back(
2182 {DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]});
2183 }
2184 Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
2185 Outgoing[NumGuards - 1]});
2186 Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
2187 Outgoing[NumGuards]});
2188 DTU->applyUpdates(Updates);
2189 }
2190
2191 for (auto I : DeletionCandidates) {
2192 if (I->use_empty())
2193 if (auto Inst = dyn_cast_or_null<Instruction>(I))
2194 Inst->eraseFromParent();
2195 }
2196
2197 return FirstGuardBlock;
2198}
2199
2201 Value *NewCond = PBI->getCondition();
2202 // If this is a "cmp" instruction, only used for branching (and nowhere
2203 // else), then we can simply invert the predicate.
2204 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2205 CmpInst *CI = cast<CmpInst>(NewCond);
2207 } else
2208 NewCond = Builder.CreateNot(NewCond, NewCond->getName() + ".not");
2209
2210 PBI->setCondition(NewCond);
2211 PBI->swapSuccessors();
2212}
2213
2215 for (auto &BB : F) {
2216 auto *Term = BB.getTerminator();
2217 if (!(isa<ReturnInst>(Term) || isa<UnreachableInst>(Term) ||
2218 isa<BranchInst>(Term)))
2219 return false;
2220 }
2221 return true;
2222}
2223
2225 const BasicBlock &Dest) {
2226 assert(Src.getParent() == Dest.getParent());
2227 if (!Src.getParent()->isPresplitCoroutine())
2228 return false;
2229 if (auto *SW = dyn_cast<SwitchInst>(Src.getTerminator()))
2230 if (auto *Intr = dyn_cast<IntrinsicInst>(SW->getCondition()))
2231 return Intr->getIntrinsicID() == Intrinsic::coro_suspend &&
2232 SW->getDefaultDest() == &Dest;
2233 return false;
2234}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
unsigned Intr
static BasicBlock * SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
static void convertToGuardPredicates(SmallVectorImpl< BasicBlock * > &GuardBlocks, SmallVectorImpl< WeakVH > &DeletionCandidates, const BBSetVector &Incoming, const BBSetVector &Outgoing, const StringRef Prefix, std::optional< unsigned > MaxControlFlowBooleans)
static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB)
static BasicBlock * SplitBlockImpl(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName, bool Before)
static void calcPredicateUsingBooleans(const BBSetVector &Incoming, const BBSetVector &Outgoing, SmallVectorImpl< BasicBlock * > &GuardBlocks, BBPredicates &GuardPredicates, SmallVectorImpl< WeakVH > &DeletionCandidates)
We record the predicate of each outgoing block using a phi of boolean.
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 std::tuple< Value *, BasicBlock *, BasicBlock * > redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock, const BBSetVector &Outgoing)
static void setupBranchForGuard(SmallVectorImpl< BasicBlock * > &GuardBlocks, const BBSetVector &Outgoing, BBPredicates &GuardPredicates)
static bool DbgVariableRecordsRemoveRedundantDbgInstrsUsingForwardScan(BasicBlock *BB)
Remove redundant dbg.value instructions using a forward scan.
static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB, ArrayRef< BasicBlock * > Preds, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA, bool &HasLoopExit)
Update DominatorTree, LoopInfo, and LCCSA analysis information.
static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock, const SetVector< BasicBlock * > &Incoming, BasicBlock *FirstGuardBlock)
static bool DbgVariableRecordsRemoveUndefDbgAssignsFromEntryBlock(BasicBlock *BB)
static void calcPredicateUsingInteger(const BBSetVector &Incoming, const BBSetVector &Outgoing, SmallVectorImpl< BasicBlock * > &GuardBlocks, BBPredicates &GuardPredicates)
We are using one integer to represent the block we are branching to.
static bool DbgVariableRecordsRemoveRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB)
Remove redundant instructions within sequences of consecutive dbg.value instructions.
static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB)
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"))
BlockVerifier::State From
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
std::string Name
bool End
Definition: ELF_riscv.cpp:480
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
LLVMContext & Context
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static const uint32_t IV[8]
Definition: blake3_impl.h:78
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:154
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
iterator begin() const
Definition: ArrayRef.h:153
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
iterator end()
Definition: BasicBlock.h:442
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:429
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:498
const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
Definition: BasicBlock.cpp:665
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:398
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition: BasicBlock.h:639
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:349
const Instruction & front() const
Definition: BasicBlock.h:452
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:198
bool isEntryBlock() const
Return true if this is the entry block of the containing function.
Definition: BasicBlock.cpp:553
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="", bool Before=false)
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:559
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
Definition: BasicBlock.cpp:479
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:441
const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
Definition: BasicBlock.cpp:313
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Definition: BasicBlock.cpp:449
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:471
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:205
const Instruction * getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
Definition: BasicBlock.cpp:368
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:164
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:157
bool IsNewDbgInfoFormat
Flag recording whether or not this block stores debug-info in the form of intrinsic instructions (fal...
Definition: BasicBlock.h:65
bool isLandingPad() const
Return true if this basic block is a landing pad.
Definition: BasicBlock.cpp:661
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition: BasicBlock.h:656
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:220
bool canSplitPredecessors() const
Definition: BasicBlock.cpp:527
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition: BasicBlock.h:612
const Instruction & back() const
Definition: BasicBlock.h:454
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Definition: BasicBlock.cpp:498
This class represents a no-op cast from one type to another.
Conditional or Unconditional Branch instruction.
void setCondition(Value *V)
void swapSuccessors()
Swap the successors of this branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, BasicBlock::iterator InsertBefore)
bool isConditional() const
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
Value * getCondition() const
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB, BasicBlock::iterator InsertBefore)
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:950
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition: InstrTypes.h:1075
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition: InstrTypes.h:1096
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:849
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:856
DWARF expression.
This class represents an Operation in the Expression.
This represents the llvm.dbg.assign instruction.
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
This represents the llvm.dbg.value instruction.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
DIExpression * getExpression() const
DILocalVariable * getVariable() const
Identifies a unique instance of a variable.
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:151
iterator end()
Definition: DenseMap.h:84
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
iterator_range< iterator > children()
NodeT * getBlock() const
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
void recalculate(Function &F)
Notify DTU that the entry block was replaced.
bool hasDomTree() const
Returns true if it holds a DominatorTree.
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
void deleteBB(BasicBlock *DelBB)
Delete DelBB.
DominatorTree & getDomTree()
Flush DomTree updates and return DomTree.
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:162
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:321
This instruction extracts a struct member or array element value from an aggregate value.
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:655
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:94
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:2375
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1743
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2219
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition: IRBuilder.h:1114
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1321
Value * CreateElementCount(Type *DstType, ElementCount EC)
Create an expression which evaluates to the number of elements in EC at runtime.
Definition: IRBuilder.cpp:99
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2644
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
void moveBeforePreserving(Instruction *MovePos)
Perform a moveBefore operation, while signalling that the caller intends to preserve the original ord...
unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:454
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:80
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Definition: Instruction.h:802
const BasicBlock * getParent() const
Definition: Instruction.h:152
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.
Definition: Instruction.h:359
bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1636
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:451
bool isSpecialTerminator() const
Definition: Instruction.h:262
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:67
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.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
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:44
Metadata node.
Definition: Metadata.h:1067
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.
void moveAllAfterSpliceBlocks(BasicBlock *From, BasicBlock *To, Instruction *Start)
From block was spliced into From and To.
void applyUpdates(ArrayRef< CFGUpdate > Updates, DominatorTree &DT, bool UpdateDTFirst=false)
Apply CFG updates, analogous with the DT edge updates.
void moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To, Instruction *Start)
From block was merged into To.
void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
void wireOldPredecessorsToNewImmediatePredecessor(BasicBlock *Old, BasicBlock *New, ArrayRef< BasicBlock * > Preds, bool IdenticalEdgesWereMerged=true)
A new empty BasicBlock (New) now branches directly to Old.
void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
Definition: MemorySSA.cpp:1857
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition: MemorySSA.h:717
Class that has the common methods + fields of memory uses/defs.
Definition: MemorySSA.h:252
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:287
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
void removeIncomingValueIf(function_ref< bool(unsigned)> Predicate, bool DeletePHIIfEmpty=true)
Remove all incoming values for which the predicate returns true.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr, BasicBlock::iterator InsertBefore)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
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 PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1827
Return a value (possibly void), from a function.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr, BasicBlock::iterator InsertBefore, Instruction *MDFrom=nullptr)
A vector that has set insertion semantics.
Definition: SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:98
const value_type & front() const
Return the first element of the SetVector.
Definition: SetVector.h:143
const value_type & back() const
Return the last element of the SetVector.
Definition: SetVector.h:149
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition: SetVector.h:264
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition: SetVector.h:103
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:290
size_type size() const
Definition: SmallPtrSet.h:94
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:321
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false.
Definition: SmallPtrSet.h:356
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:360
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
iterator begin() const
Definition: SmallPtrSet.h:380
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:366
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void reserve(size_type N)
Definition: SmallVector.h:676
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
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:81
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
static IntegerType * getInt1Ty(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
bool isTokenTy() const
Return true if this is 'token'.
Definition: Type.h:225
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1808
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
op_range operands()
Definition: User.h:242
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
bool use_empty() const
Definition: Value.h:344
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:185
self_iterator getIterator()
Definition: ilist_node.h:109
#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
AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
Definition: DebugInfo.cpp:1845
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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)
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:102
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1751
bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
bool succ_empty(const Instruction *I)
Definition: CFG.h:255
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 @...
BranchInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
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:79
void detachDeadBlocks(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs=false)
Replace contents of every block in BBs with single unreachable instruction.
bool hasOnlySimpleTerminator(const Function &F)
auto successors(const MachineBasicBlock *BB)
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...
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.
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.
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:99
void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
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...
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,...
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:112
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:1738
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:428
void InvertBranch(BranchInst *PBI, IRBuilderBase &Builder)
bool EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete all basic blocks from F that are not reachable from its entry node.
bool MergeBlockSuccessorsIntoGivenBlocks(SmallPtrSetImpl< BasicBlock * > &MergeBlocks, Loop *L=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
Merge block(s) sucessors, if possible.
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...
void SplitBlockAndInsertForEachLane(ElementCount EC, Type *IndexTy, Instruction *InsertBefore, std::function< void(IRBuilderBase &, Value *)> Func)
Utility function for performing a given action on each lane of a vector with EC elements.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:109
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.
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...
Definition: SmallVector.h:1312
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...
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...
bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition: MemorySSA.cpp:83
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.
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.
bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
Definition: DebugInfo.cpp:2392
BasicBlock * CreateControlFlowHub(DomTreeUpdater *DTU, SmallVectorImpl< BasicBlock * > &GuardBlocks, const SetVector< BasicBlock * > &Predecessors, const SetVector< BasicBlock * > &Successors, const StringRef Prefix, std::optional< unsigned > MaxControlFlowBooleans=std::nullopt)
Given a set of incoming and outgoing blocks, create a "hub" such that every edge from an incoming blo...
std::pair< Instruction *, Value * > SplitBlockAndInsertSimpleForLoop(Value *End, Instruction *SplitBefore)
Insert a for (int i = 0; i < End; i++) loop structure (with the exception that End is assumed > 0,...
DWARFExpression::Operation Op
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.
bool FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition: CFG.cpp:95
unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found.
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.
bool isPresplitCoroSuspendExitEdge(const BasicBlock &Src, const BasicBlock &Dest)
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)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1888
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:644
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 ...
unsigned succ_size(const MachineBasicBlock *BB)
Value * invertCondition(Value *Condition)
Invert the given true/false value, possibly reusing an existing copy.
Definition: Local.cpp:4115
void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
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...
void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ)
Sets the unwind edge of an instruction to a particular successor.
unsigned pred_size(const MachineBasicBlock *BB)
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
Option class for critical edge splitting.
CriticalEdgeSplittingOptions & setPreserveLCSSA()
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...