LLVM 24.0.0git
LoopSimplify.cpp
Go to the documentation of this file.
1//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
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 pass performs several transformations to transform natural loops into a
10// simpler form, which makes subsequent analyses and transformations simpler and
11// more effective.
12//
13// Loop pre-header insertion guarantees that there is a single, non-critical
14// entry edge from outside of the loop to the loop header. This simplifies a
15// number of analyses and transformations, such as LICM.
16//
17// Loop exit-block insertion guarantees that all exit blocks from the loop
18// (blocks which are outside of the loop that have predecessors inside of the
19// loop) only have predecessors from inside of the loop (and are thus dominated
20// by the loop header). This simplifies transformations such as store-sinking
21// that are built into LICM.
22//
23// This pass also guarantees that loops will have exactly one backedge.
24//
25// Indirectbr instructions introduce several complications. If the loop
26// contains or is entered by an indirectbr instruction, it may not be possible
27// to transform the loop and make these guarantees. Client code should check
28// that these conditions are true before relying on them.
29//
30// Similar complications arise from callbr instructions, particularly in
31// asm-goto where blockaddress expressions are used.
32//
33// Note that the simplifycfg pass will clean up blocks which are split out but
34// end up being unnecessary, so usage of this pass should not pessimize
35// generated code.
36//
37// This pass obviously modifies the CFG, but updates loop information and
38// dominator information.
39//
40//===----------------------------------------------------------------------===//
41
43#include "llvm/ADT/SetVector.h"
45#include "llvm/ADT/Statistic.h"
58#include "llvm/IR/CFG.h"
59#include "llvm/IR/Constants.h"
60#include "llvm/IR/Dominators.h"
61#include "llvm/IR/Function.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Module.h"
66#include "llvm/Support/Debug.h"
72using namespace llvm;
73
74#define DEBUG_TYPE "loop-simplify"
75
76STATISTIC(NumNested , "Number of nested loops split out");
77
78// If the block isn't already, move the new block to right after some 'outside
79// block' block. This prevents the preheader from being placed inside the loop
80// body, e.g. when the loop hasn't been rotated.
83 Loop *L) {
84 // Check to see if NewBB is already well placed.
85 Function::iterator BBI = --NewBB->getIterator();
86 if (llvm::is_contained(SplitPreds, &*BBI))
87 return;
88
89 // If it isn't already after an outside block, move it after one. This is
90 // always good as it makes the uncond branch from the outside block into a
91 // fall-through.
92
93 // Figure out *which* outside block to put this after. Prefer an outside
94 // block that neighbors a BB actually in the loop.
95 BasicBlock *FoundBB = nullptr;
96 for (BasicBlock *Pred : SplitPreds) {
97 Function::iterator BBI = Pred->getIterator();
98 if (++BBI != NewBB->getParent()->end() && L->contains(&*BBI)) {
99 FoundBB = Pred;
100 break;
101 }
102 }
103
104 // If our heuristic for a *good* bb to place this after doesn't find
105 // anything, just pick something. It's likely better than leaving it within
106 // the loop.
107 if (!FoundBB)
108 FoundBB = SplitPreds[0];
109 NewBB->moveAfter(FoundBB);
110}
111
112/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
113/// preheader, this method is called to insert one. This method has two phases:
114/// preheader insertion and analysis updating.
115///
117 LoopInfo *LI, MemorySSAUpdater *MSSAU,
118 bool PreserveLCSSA) {
119 BasicBlock *Header = L->getHeader();
120
121 // Compute the set of predecessors of the loop that are not in the loop.
122 SmallVector<BasicBlock*, 8> OutsideBlocks;
123 for (BasicBlock *P : predecessors(Header)) {
124 if (!L->contains(P)) { // Coming in from outside the loop?
125 // If the loop is branched to from an indirect terminator, we won't
126 // be able to fully transform the loop, because it prohibits
127 // edge splitting.
128 if (isa<IndirectBrInst>(P->getTerminator()))
129 return nullptr;
130
131 // Keep track of it.
132 OutsideBlocks.push_back(P);
133 }
134 }
135
136 // Split out the loop pre-header.
137 BasicBlock *PreheaderBB;
138 PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader", DT,
139 LI, MSSAU, PreserveLCSSA);
140 if (!PreheaderBB)
141 return nullptr;
142
143 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating pre-header "
144 << PreheaderBB->getName() << "\n");
145
146 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
147 // code layout too horribly.
148 placeSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
149
150 return PreheaderBB;
151}
152
153/// Add the specified block, and all of its predecessors, to the specified set,
154/// if it's not already in there. Stop predecessor traversal when we reach
155/// StopBlock.
156static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
159 Worklist.push_back(InputBB);
160 do {
161 BasicBlock *BB = Worklist.pop_back_val();
162 if (Blocks.insert(BB).second && BB != StopBlock)
163 // If BB is not already processed and it is not a stop block then
164 // insert its predecessor in the work list
165 append_range(Worklist, predecessors(BB));
166 } while (!Worklist.empty());
167}
168
169/// The first part of loop-nestification is to find a PHI node that tells
170/// us how to partition the loops.
172 AssumptionCache *AC) {
173 const DataLayout &DL = L->getHeader()->getDataLayout();
174 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
175 PHINode *PN = cast<PHINode>(I);
176 ++I;
177 if (Value *V = simplifyInstruction(PN, {DL, nullptr, DT, AC})) {
178 // This is a degenerate PHI already, don't modify it!
180 PN->eraseFromParent();
181 continue;
182 }
183
184 // Scan this PHI node looking for a use of the PHI node by itself.
185 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
186 if (PN->getIncomingValue(i) == PN &&
187 L->contains(PN->getIncomingBlock(i)))
188 // We found something tasty to remove.
189 return PN;
190 }
191 return nullptr;
192}
193
194/// If this loop has multiple backedges, try to pull one of them out into
195/// a nested loop.
196///
197/// This is important for code that looks like
198/// this:
199///
200/// Loop:
201/// ...
202/// br cond, Loop, Next
203/// ...
204/// br cond2, Loop, Out
205///
206/// To identify this common case, we look at the PHI nodes in the header of the
207/// loop. PHI nodes with unchanging values on one backedge correspond to values
208/// that change in the "outer" loop, but not in the "inner" loop.
209///
210/// If we are able to separate out a loop, return the new outer loop that was
211/// created.
212///
213static Loop *separateNestedLoop(Loop *L, BasicBlock *Preheader,
214 DominatorTree *DT, LoopInfo *LI,
215 ScalarEvolution *SE, bool PreserveLCSSA,
216 AssumptionCache *AC, MemorySSAUpdater *MSSAU) {
217 // Don't try to separate loops without a preheader.
218 if (!Preheader)
219 return nullptr;
220
221 // Treat the presence of convergent functions conservatively. The
222 // transformation is invalid if calls to certain convergent
223 // functions (like an AMDGPU barrier) get included in the resulting
224 // inner loop. But blocks meant for the inner loop will be
225 // identified later at a point where it's too late to abort the
226 // transformation. Also, the convergent attribute is not really
227 // sufficient to express the semantics of functions that are
228 // affected by this transformation. So we choose to back off if such
229 // a function call is present until a better alternative becomes
230 // available. This is similar to the conservative treatment of
231 // convergent function calls in GVNHoist and JumpThreading.
232 for (auto *BB : L->blocks()) {
233 for (auto &II : *BB) {
234 if (auto CI = dyn_cast<CallBase>(&II)) {
235 if (CI->isConvergent()) {
236 return nullptr;
237 }
238 }
239 }
240 }
241
242 // The header is not a landing pad; preheader insertion should ensure this.
243 BasicBlock *Header = L->getHeader();
244 assert(!Header->isEHPad() && "Can't insert backedge to EH pad");
245
246 PHINode *PN = findPHIToPartitionLoops(L, DT, AC);
247 if (!PN) return nullptr; // No known way to partition.
248
249 // Pull out all predecessors that have varying values in the loop. This
250 // handles the case when a PHI node has multiple instances of itself as
251 // arguments.
252 SmallVector<BasicBlock*, 8> OuterLoopPreds;
253 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
254 if (PN->getIncomingValue(i) != PN ||
255 !L->contains(PN->getIncomingBlock(i))) {
256 // We can't split indirect control flow edges.
258 return nullptr;
259 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
260 }
261 }
262 LLVM_DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n");
263
264 // If ScalarEvolution is around and knows anything about values in
265 // this loop, tell it to forget them, because we're about to
266 // substantially change it.
267 if (SE)
268 SE->forgetLoop(L);
269
270 BasicBlock *NewBB = SplitBlockPredecessors(Header, OuterLoopPreds, ".outer",
271 DT, LI, MSSAU, PreserveLCSSA);
272
273 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
274 // code layout too horribly.
275 placeSplitBlockCarefully(NewBB, OuterLoopPreds, L);
276
277 // Create the new outer loop.
278 Loop *NewOuter = LI->AllocateLoop();
279
280 // Change the parent loop to use the outer loop as its child now.
281 LI->replaceLoop(L, NewOuter);
282
283 // L is now a subloop of our outer loop.
284 NewOuter->addChildLoop(L);
285
286 for (BasicBlock *BB : L->blocks())
287 NewOuter->addBlockEntry(BB);
288
289 // Now reset the header in L, which had been moved by
290 // SplitBlockPredecessors for the outer loop.
291 L->moveToHeader(Header);
292
293 // Determine which blocks should stay in L and which should be moved out to
294 // the Outer loop now.
296 for (BasicBlock *P : predecessors(Header)) {
297 if (DT->dominates(Header, P))
298 addBlockAndPredsToSet(P, Header, BlocksInL);
299 }
300
301 // Scan all of the loop children of L, moving them to OuterLoop if they are
302 // not part of the inner loop.
303 const std::vector<Loop*> &SubLoops = L->getSubLoops();
304 for (size_t I = 0; I != SubLoops.size(); )
305 if (BlocksInL.count(SubLoops[I]->getHeader()))
306 ++I; // Loop remains in L
307 else
308 NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
309
310 SmallVector<BasicBlock *, 8> OuterLoopBlocks;
311 OuterLoopBlocks.push_back(NewBB);
312 // Now that we know which blocks are in L and which need to be moved to
313 // OuterLoop, move any blocks that need it.
314 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
315 BasicBlock *BB = L->getBlocks()[i];
316 if (!BlocksInL.count(BB)) {
317 // Move this block to the parent, updating the exit blocks sets
318 L->removeBlockFromLoop(BB);
319 if ((*LI)[BB] == L) {
320 LI->changeLoopFor(BB, NewOuter);
321 OuterLoopBlocks.push_back(BB);
322 }
323 --i;
324 }
325 }
326
327 // Split edges to exit blocks from the inner loop, if they emerged in the
328 // process of separating the outer one.
329 formDedicatedExitBlocks(L, DT, LI, MSSAU, PreserveLCSSA);
330
331 if (PreserveLCSSA) {
332 // Fix LCSSA form for L. Some values, which previously were only used inside
333 // L, can now be used in NewOuter loop. We need to insert phi-nodes for them
334 // in corresponding exit blocks.
335 // We don't need to form LCSSA recursively, because there cannot be uses
336 // inside a newly created loop of defs from inner loops as those would
337 // already be a use of an LCSSA phi node.
338 formLCSSA(*L, *DT, LI, SE);
339
340 assert(NewOuter->isRecursivelyLCSSAForm(*DT, *LI) &&
341 "LCSSA is broken after separating nested loops!");
342 }
343
344 return NewOuter;
345}
346
347/// This method is called when the specified loop has more than one
348/// backedge in it.
349///
350/// If this occurs, revector all of these backedges to target a new basic block
351/// and have that block branch to the loop header. This ensures that loops
352/// have exactly one backedge.
354 DominatorTree *DT, LoopInfo *LI,
355 MemorySSAUpdater *MSSAU) {
356 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
357
358 // Get information about the loop
359 BasicBlock *Header = L->getHeader();
360 Function *F = Header->getParent();
361
362 // Unique backedge insertion currently depends on having a preheader.
363 if (!Preheader)
364 return nullptr;
365
366 // The header is not an EH pad; preheader insertion should ensure this.
367 assert(!Header->isEHPad() && "Can't insert backedge to EH pad");
368
369 // Only keep llvm.loop metadata that is shared by all backedges. Backedges
370 // with different metadata may come from different source loops.
371 MDNode *LoopMD = L->getLoopID();
372
373 // Figure out which basic blocks contain back-edges to the loop header.
374 std::vector<BasicBlock*> BackedgeBlocks;
375 for (BasicBlock *P : predecessors(Header)) {
376 // Indirect edges cannot be split, so we must fail if we find one.
377 if (isa<IndirectBrInst>(P->getTerminator()))
378 return nullptr;
379
380 if (P != Preheader) BackedgeBlocks.push_back(P);
381 }
382
383 // Create and insert the new backedge block.
384 BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
385 Header->getName() + ".backedge", F);
386 UncondBrInst *BETerminator = UncondBrInst::Create(Header, BEBlock);
387 BETerminator->setDebugLoc(Header->getFirstNonPHIIt()->getDebugLoc());
388
389 LLVM_DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block "
390 << BEBlock->getName() << "\n");
391
392 // Move the new backedge block to right after the last backedge block.
393 Function::iterator InsertPos = ++BackedgeBlocks.back()->getIterator();
394 F->splice(InsertPos, F, BEBlock->getIterator());
395
396 // Now that the block has been inserted into the function, create PHI nodes in
397 // the backedge block which correspond to any PHI nodes in the header block.
398 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
399 PHINode *PN = cast<PHINode>(I);
400 PHINode *NewPN = PHINode::Create(PN->getType(), BackedgeBlocks.size(),
401 PN->getName()+".be", BETerminator->getIterator());
402
403 // Loop over the PHI node, moving all entries except the one for the
404 // preheader over to the new PHI node.
405 unsigned PreheaderIdx = ~0U;
406 bool HasUniqueIncomingValue = true;
407 Value *UniqueValue = nullptr;
408 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
409 BasicBlock *IBB = PN->getIncomingBlock(i);
410 Value *IV = PN->getIncomingValue(i);
411 if (IBB == Preheader) {
412 PreheaderIdx = i;
413 } else {
414 NewPN->addIncoming(IV, IBB);
415 if (HasUniqueIncomingValue) {
416 if (!UniqueValue)
417 UniqueValue = IV;
418 else if (UniqueValue != IV)
419 HasUniqueIncomingValue = false;
420 }
421 }
422 }
423
424 // Delete all of the incoming values from the old PN except the preheader's
425 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
426 if (PreheaderIdx != 0) {
427 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
428 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
429 }
430 // Nuke all entries except the zero'th.
431 PN->removeIncomingValueIf([](unsigned Idx) { return Idx != 0; },
432 /* DeletePHIIfEmpty */ false);
433
434 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
435 PN->addIncoming(NewPN, BEBlock);
436
437 // As an optimization, if all incoming values in the new PhiNode (which is a
438 // subset of the incoming values of the old PHI node) have the same value,
439 // eliminate the PHI Node.
440 if (HasUniqueIncomingValue) {
441 NewPN->replaceAllUsesWith(UniqueValue);
442 NewPN->eraseFromParent();
443 }
444 }
445
446 // Now that all of the PHI nodes have been inserted and adjusted, modify the
447 // backedge blocks to jump to the BEBlock instead of the header.
448 // The llvm.loop metadata is moved from the backedges to BEBlock.
449 for (BasicBlock *BB : BackedgeBlocks) {
450 Instruction *TI = BB->getTerminator();
451 TI->setMetadata(LLVMContext::MD_loop, nullptr);
452 TI->replaceSuccessorWith(Header, BEBlock);
453 }
454 BEBlock->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopMD);
455
456 //===--- Update all analyses which we must preserve now -----------------===//
457
458 // Update Loop Information - we know that this block is now in the current
459 // loop and all parent loops.
460 L->addBasicBlockToLoop(BEBlock, *LI);
461
462 // Update dominator information
463 DT->splitBlock(BEBlock);
464
465 if (MSSAU)
466 MSSAU->updatePhisWhenInsertingUniqueBackedgeBlock(Header, Preheader,
467 BEBlock);
468
469 return BEBlock;
470}
471
472/// Replace PHI nodes in the loop header that simplify to a single value.
475 bool PreserveLCSSA) {
476 bool Changed = false;
477 const DataLayout &DL = L->getHeader()->getDataLayout();
478 PHINode *PN;
479 for (BasicBlock::iterator I = L->getHeader()->begin();
480 (PN = dyn_cast<PHINode>(I++));)
481 if (Value *V = simplifyInstruction(PN, {DL, nullptr, DT, AC})) {
482 if (SE)
483 SE->forgetValue(PN);
484 if (!PreserveLCSSA || LI->replacementPreservesLCSSAForm(PN, V)) {
486 PN->eraseFromParent();
487 Changed = true;
488 }
489 }
490 return Changed;
491}
492
493/// Simplify one loop and queue further loops for simplification.
495 DominatorTree *DT, LoopInfo *LI,
497 MemorySSAUpdater *MSSAU, bool PreserveLCSSA,
498 const TargetTransformInfo *TTI) {
499 bool Changed = false;
500 if (MSSAU && VerifyMemorySSA)
501 MSSAU->getMemorySSA()->verifyMemorySSA();
502
503ReprocessLoop:
504
505 // Check to see that no blocks (other than the header) in this loop have
506 // predecessors that are not in the loop. This is not valid for natural
507 // loops, but can occur if the blocks are unreachable. Since they are
508 // unreachable we can just shamelessly delete those CFG edges!
509 for (BasicBlock *BB : L->blocks()) {
510 if (BB == L->getHeader())
511 continue;
512
514 for (BasicBlock *P : predecessors(BB))
515 if (!L->contains(P))
516 BadPreds.insert(P);
517
518 // Delete each unique out-of-loop (and thus dead) predecessor.
519 for (BasicBlock *P : BadPreds) {
520
521 LLVM_DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor "
522 << P->getName() << "\n");
523
524 // Zap the dead pred's terminator and replace it with unreachable.
525 Instruction *TI = P->getTerminator();
526 changeToUnreachable(TI, PreserveLCSSA,
527 /*DTU=*/nullptr, MSSAU);
528 Changed = true;
529 }
530 }
531
532 if (MSSAU && VerifyMemorySSA)
533 MSSAU->getMemorySSA()->verifyMemorySSA();
534
535 // If there are exiting blocks with branches on undef, resolve the undef in
536 // the direction which will exit the loop. This will help simplify loop
537 // trip count computations.
538 SmallVector<BasicBlock*, 8> ExitingBlocks;
539 L->getExitingBlocks(ExitingBlocks);
540 for (BasicBlock *ExitingBlock : ExitingBlocks)
541 if (CondBrInst *BI = dyn_cast<CondBrInst>(ExitingBlock->getTerminator())) {
542 if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
543
545 dbgs() << "LoopSimplify: Resolving \"br i1 undef\" to exit in "
546 << ExitingBlock->getName() << "\n");
547
548 BI->setCondition(ConstantInt::get(Cond->getType(),
549 !L->contains(BI->getSuccessor(0))));
550
551 Changed = true;
552 }
553 }
554
555 // Does the loop already have a preheader? If so, don't insert one.
556 BasicBlock *Preheader = L->getLoopPreheader();
557 if (!Preheader) {
558 Preheader = InsertPreheaderForLoop(L, DT, LI, MSSAU, PreserveLCSSA);
559 if (Preheader)
560 Changed = true;
561 }
562
563 // Next, check to make sure that all exit nodes of the loop only have
564 // predecessors that are inside of the loop. This check guarantees that the
565 // loop preheader/header will dominate the exit blocks. If the exit block has
566 // predecessors from outside of the loop, split the edge now.
567 if (formDedicatedExitBlocks(L, DT, LI, MSSAU, PreserveLCSSA))
568 Changed = true;
569
570 if (MSSAU && VerifyMemorySSA)
571 MSSAU->getMemorySSA()->verifyMemorySSA();
572
573 // If the header has more than two predecessors at this point (from the
574 // preheader and from multiple backedges), we must adjust the loop.
575 BasicBlock *LoopLatch = L->getLoopLatch();
576 if (!LoopLatch) {
577 // If this is really a nested loop, rip it out into a child loop. Don't do
578 // this for loops with a giant number of backedges, just factor them into a
579 // common backedge instead.
580 // On targets with branch divergence, a backedge taken by only some threads
581 // (e.g. a divergent "continue") would become a divergent inner loop, which
582 // can turn otherwise uniform loop state into per-thread state.
583 bool AllowSeparate =
584 !TTI || !TTI->hasBranchDivergence(L->getHeader()->getParent());
585 if (AllowSeparate && L->getNumBackEdges() < 8) {
586 if (Loop *OuterL = separateNestedLoop(L, Preheader, DT, LI, SE,
587 PreserveLCSSA, AC, MSSAU)) {
588 ++NumNested;
589 // Enqueue the outer loop as it should be processed next in our
590 // depth-first nest walk.
591 Worklist.push_back(OuterL);
592
593 // This is a big restructuring change, reprocess the whole loop.
594 Changed = true;
595 // GCC doesn't tail recursion eliminate this.
596 // FIXME: It isn't clear we can't rely on LLVM to TRE this.
597 goto ReprocessLoop;
598 }
599 }
600
601 // If we either couldn't, or didn't want to, identify nesting of the loops,
602 // insert a new block that all backedges target, then make it jump to the
603 // loop header. Fold degenerate header PHIs first, so they don't turn into
604 // a PHI cycle through the new backedge block.
605 if (simplifyHeaderPHIs(L, DT, LI, SE, AC, PreserveLCSSA))
606 Changed = true;
607 LoopLatch = insertUniqueBackedgeBlock(L, Preheader, DT, LI, MSSAU);
608 if (LoopLatch)
609 Changed = true;
610 }
611
612 if (MSSAU && VerifyMemorySSA)
613 MSSAU->getMemorySSA()->verifyMemorySSA();
614
615 // Scan over the PHI nodes in the loop header. Since they now have only two
616 // incoming values (the loop is canonicalized), we may have simplified the PHI
617 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
618 if (simplifyHeaderPHIs(L, DT, LI, SE, AC, PreserveLCSSA))
619 Changed = true;
620
621 // If this loop has multiple exits and the exits all go to the same
622 // block, attempt to merge the exits. This helps several passes, such
623 // as LoopRotation, which do not support loops with multiple exits.
624 // SimplifyCFG also does this (and this code uses the same utility
625 // function), however this code is loop-aware, where SimplifyCFG is
626 // not. That gives it the advantage of being able to hoist
627 // loop-invariant instructions out of the way to open up more
628 // opportunities, and the disadvantage of having the responsibility
629 // to preserve dominator information.
630 auto HasUniqueExitBlock = [&]() {
631 BasicBlock *UniqueExit = nullptr;
632 for (auto *ExitingBB : ExitingBlocks)
633 for (auto *SuccBB : successors(ExitingBB)) {
634 if (L->contains(SuccBB))
635 continue;
636
637 if (!UniqueExit)
638 UniqueExit = SuccBB;
639 else if (UniqueExit != SuccBB)
640 return false;
641 }
642
643 return true;
644 };
645 if (HasUniqueExitBlock()) {
646 for (BasicBlock *ExitingBlock : ExitingBlocks) {
647 if (!ExitingBlock->getSinglePredecessor()) continue;
648 CondBrInst *BI = dyn_cast<CondBrInst>(ExitingBlock->getTerminator());
649 if (!BI)
650 continue;
652 if (!CI || CI->getParent() != ExitingBlock) continue;
653
654 // Attempt to hoist out all instructions except for the
655 // comparison and the branch.
656 bool AllInvariant = true;
657 bool AnyInvariant = false;
658 for (auto I = ExitingBlock->begin(); &*I != BI;) {
659 Instruction *Inst = &*I++;
660 if (Inst == CI)
661 continue;
662 if (!L->makeLoopInvariant(
663 Inst, AnyInvariant,
664 Preheader ? Preheader->getTerminator() : nullptr, MSSAU, SE)) {
665 AllInvariant = false;
666 break;
667 }
668 }
669 if (AnyInvariant)
670 Changed = true;
671 if (!AllInvariant) continue;
672
673 // The block has now been cleared of all instructions except for
674 // a comparison and a conditional branch. SimplifyCFG may be able
675 // to fold it now.
676 if (!foldBranchToCommonDest(BI, /*DTU=*/nullptr, MSSAU))
677 continue;
678
679 // Success. The block is now dead, so remove it from the loop,
680 // update the dominator tree and delete it.
681 LLVM_DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block "
682 << ExitingBlock->getName() << "\n");
683
684 assert(pred_empty(ExitingBlock));
685 Changed = true;
686 LI->removeBlock(ExitingBlock);
687
688 DomTreeNode *Node = DT->getNode(ExitingBlock);
689 while (!Node->isLeaf())
690 DT->changeImmediateDominator(*Node->begin(), Node->getIDom());
691 DT->eraseNode(ExitingBlock);
692 if (MSSAU) {
694 ExitBlockSet.insert(ExitingBlock);
695 MSSAU->removeBlocks(ExitBlockSet);
696 }
697
699 ExitingBlock, /* KeepOneInputPHIs */ PreserveLCSSA);
701 ExitingBlock, /* KeepOneInputPHIs */ PreserveLCSSA);
702 ExitingBlock->eraseFromParent();
703 }
704 }
705
706 if (MSSAU && VerifyMemorySSA)
707 MSSAU->getMemorySSA()->verifyMemorySSA();
708
709 return Changed;
710}
711
714 MemorySSAUpdater *MSSAU, bool PreserveLCSSA,
715 const TargetTransformInfo *TTI) {
716 bool Changed = false;
717
718#ifndef NDEBUG
719 // If we're asked to preserve LCSSA, the loop nest needs to start in LCSSA
720 // form.
721 if (PreserveLCSSA) {
722 assert(DT && "DT not available.");
723 assert(LI && "LI not available.");
724 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
725 "Requested to preserve LCSSA, but it's already broken.");
726 }
727#endif
728
729 // Worklist maintains our depth-first queue of loops in this nest to process.
730 SmallVector<Loop *, 4> Worklist;
731 Worklist.push_back(L);
732
733 // Walk the worklist from front to back, pushing newly found sub loops onto
734 // the back. This will let us process loops from back to front in depth-first
735 // order. We can use this simple process because loops form a tree.
736 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
737 Loop *L2 = Worklist[Idx];
738 Worklist.append(L2->begin(), L2->end());
739 }
740
741 while (!Worklist.empty())
742 Changed |= simplifyOneLoop(Worklist.pop_back_val(), Worklist, DT, LI, SE,
743 AC, MSSAU, PreserveLCSSA, TTI);
744
745 // Changing exit conditions for blocks may affect exit counts of this loop and
746 // any of its parents, so we must invalidate the entire subtree if we've made
747 // any changes. Do this here rather than in simplifyOneLoop() as the top-most
748 // loop is going to be the same for all child loops.
749 if (Changed && SE)
750 SE->forgetTopmostLoop(L);
751
752 return Changed;
753}
754
755namespace {
756struct LoopSimplify : public FunctionPass {
757 static char ID; // Pass identification, replacement for typeid
758 LoopSimplify() : FunctionPass(ID) {
760 }
761
762 bool runOnFunction(Function &F) override;
763
764 void getAnalysisUsage(AnalysisUsage &AU) const override {
765 AU.addRequired<AssumptionCacheTracker>();
766
767 // We need loop information to identify the loops.
768 AU.addRequired<DominatorTreeWrapperPass>();
769 AU.addPreserved<DominatorTreeWrapperPass>();
770
771 AU.addRequired<LoopInfoWrapperPass>();
772 AU.addPreserved<LoopInfoWrapperPass>();
773
774 AU.addPreserved<BasicAAWrapperPass>();
775 AU.addPreserved<AAResultsWrapperPass>();
776 AU.addPreserved<GlobalsAAWrapperPass>();
777 AU.addPreserved<ScalarEvolutionWrapperPass>();
778 AU.addPreserved<SCEVAAWrapperPass>();
780 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
781 AU.addPreserved<BranchProbabilityInfoWrapperPass>();
782 AU.addPreserved<MemorySSAWrapperPass>();
783 }
784
785 /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees.
786 void verifyAnalysis() const override;
787};
788} // namespace
789
790char LoopSimplify::ID = 0;
791INITIALIZE_PASS_BEGIN(LoopSimplify, "loop-simplify",
792 "Canonicalize natural loops", false, false)
796INITIALIZE_PASS_END(LoopSimplify, "loop-simplify", "Canonicalize natural loops",
798
799// Publicly exposed interface to pass.
800char &llvm::LoopSimplifyID = LoopSimplify::ID;
801Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
802
803/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
804/// it in any convenient order) inserting preheaders.
805///
806bool LoopSimplify::runOnFunction(Function &F) {
807 bool Changed = false;
808 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
809 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
810 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
811 ScalarEvolution *SE = SEWP ? &SEWP->getSE() : nullptr;
812 AssumptionCache *AC =
813 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
814 MemorySSA *MSSA = nullptr;
815 std::unique_ptr<MemorySSAUpdater> MSSAU;
816 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
817 if (MSSAAnalysis) {
818 MSSA = &MSSAAnalysis->getMSSA();
819 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
820 }
821
822 auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
823 const TargetTransformInfo *TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;
824
825 bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
826
827 // Simplify each loop nest in the function.
828 for (auto *L : *LI)
829 Changed |= simplifyLoop(L, DT, LI, SE, AC, MSSAU.get(), PreserveLCSSA, TTI);
830
831#ifndef NDEBUG
832 if (PreserveLCSSA) {
833 bool InLCSSA = all_of(
834 *LI, [&](Loop *L) { return L->isRecursivelyLCSSAForm(*DT, *LI); });
835 assert(InLCSSA && "LCSSA is broken after loop-simplify.");
836 }
837#endif
838 return Changed;
839}
840
843 bool Changed = false;
844 LoopInfo *LI = &AM.getResult<LoopAnalysis>(F);
849 auto *MSSAAnalysis = AM.getCachedResult<MemorySSAAnalysis>(F);
850 std::unique_ptr<MemorySSAUpdater> MSSAU;
851 if (MSSAAnalysis) {
852 auto *MSSA = &MSSAAnalysis->getMSSA();
853 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
854 }
855
856
857 // Note that we don't preserve LCSSA in the new PM, if you need it run LCSSA
858 // after simplifying the loops. MemorySSA is preserved if it exists.
859 for (auto *L : *LI)
860 Changed |= simplifyLoop(L, DT, LI, SE, AC, MSSAU.get(),
861 /*PreserveLCSSA*/ false, TTI);
862
863 if (!Changed)
864 return PreservedAnalyses::all();
865
870 if (MSSAAnalysis)
872 // BPI maps conditional terminators to probabilities, LoopSimplify can insert
873 // blocks, but it does so only by splitting existing blocks and edges. This
874 // results in the interesting property that all new terminators inserted are
875 // unconditional branches which do not appear in BPI. All deletions are
876 // handled via ValueHandle callbacks w/in BPI.
878 return PA;
879}
880
881// FIXME: Restore this code when we re-enable verification in verifyAnalysis
882// below.
883#if 0
884static void verifyLoop(Loop *L) {
885 // Verify subloops.
886 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
887 verifyLoop(*I);
888
889 // It used to be possible to just assert L->isLoopSimplifyForm(), however
890 // with the introduction of indirectbr, there are now cases where it's
891 // not possible to transform a loop as necessary. We can at least check
892 // that there is an indirectbr near any time there's trouble.
893
894 // Indirectbr can interfere with preheader and unique backedge insertion.
895 if (!L->getLoopPreheader() || !L->getLoopLatch()) {
896 bool HasIndBrPred = false;
897 for (BasicBlock *Pred : predecessors(L->getHeader()))
898 if (isa<IndirectBrInst>(Pred->getTerminator())) {
899 HasIndBrPred = true;
900 break;
901 }
902 assert(HasIndBrPred &&
903 "LoopSimplify has no excuse for missing loop header info!");
904 (void)HasIndBrPred;
905 }
906
907 // Indirectbr can interfere with exit block canonicalization.
908 if (!L->hasDedicatedExits()) {
909 bool HasIndBrExiting = false;
910 SmallVector<BasicBlock*, 8> ExitingBlocks;
911 L->getExitingBlocks(ExitingBlocks);
912 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
913 if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
914 HasIndBrExiting = true;
915 break;
916 }
917 }
918
919 assert(HasIndBrExiting &&
920 "LoopSimplify has no excuse for missing exit block info!");
921 (void)HasIndBrExiting;
922 }
923}
924#endif
925
926void LoopSimplify::verifyAnalysis() const {
927 // FIXME: This routine is being called mid-way through the loop pass manager
928 // as loop passes destroy this analysis. That's actually fine, but we have no
929 // way of expressing that here. Once all of the passes that destroy this are
930 // hoisted out of the loop pass manager we can add back verification here.
931#if 0
932 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
933 verifyLoop(*I);
934#endif
935}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
static void placeSplitBlockCarefully(BasicBlock *NewBB, SmallVectorImpl< BasicBlock * > &SplitPreds, Loop *L)
static bool simplifyHeaderPHIs(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, bool PreserveLCSSA)
Replace PHI nodes in the loop header that simplify to a single value.
static PHINode * findPHIToPartitionLoops(Loop *L, DominatorTree *DT, AssumptionCache *AC)
The first part of loop-nestification is to find a PHI node that tells us how to partition the loops.
static bool simplifyOneLoop(Loop *L, SmallVectorImpl< Loop * > &Worklist, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA, const TargetTransformInfo *TTI)
Simplify one loop and queue further loops for simplification.
static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock, SmallPtrSetImpl< BasicBlock * > &Blocks)
Add the specified block, and all of its predecessors, to the specified set, if it's not already in th...
static Loop * separateNestedLoop(Loop *L, BasicBlock *Preheader, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, bool PreserveLCSSA, AssumptionCache *AC, MemorySSAUpdater *MSSAU)
If this loop has multiple backedges, try to pull one of them out into a nested loop.
static BasicBlock * insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU)
This method is called when the specified loop has more than one backedge in it.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
SmallVector< MachineOperand, 4 > Cond
This is the interface for a SCEV-based alias analysis.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
static const uint32_t IV[8]
Definition blake3_impl.h:83
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addPreservedID(const void *ID)
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Analysis pass which computes BranchProbabilityInfo.
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
void splitBlock(NodeT *NewBB)
splitBlock - BB is split and now it has one successor.
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.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
BasicBlockListType::iterator iterator
Definition Function.h:70
iterator end()
Definition Function.h:840
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
typename std::vector< Loop * >::const_iterator iterator
iterator end() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
iterator begin() const
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
void replaceLoop(LoopT *Old, LoopT *New)
Replace a loop among its siblings (a parent loop's child list or the top-level list) with a new loop.
void changeLoopFor(const BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:623
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:470
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI bool isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI, bool IgnoreTokens=true) const
Return true if this Loop and all inner subloops are in LCSSA form.
Definition LoopInfo.cpp:500
Metadata node.
Definition Metadata.h:1081
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:918
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI void updatePhisWhenInsertingUniqueBackedgeBlock(BasicBlock *LoopHeader, BasicBlock *LoopPreheader, BasicBlock *BackedgeBlock)
Update MemorySSA when inserting a unique backedge block for a loop.
LLVM_ABI void removeBlocks(const SmallSetVector< BasicBlock *, 8 > &DeadBlocks)
Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:689
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
LLVM_ABI void removeIncomingValueIf(function_ref< bool(unsigned)> Predicate, bool DeletePHIIfEmpty=true)
Remove all incoming values for which the predicate returns true.
void setIncomingBlock(unsigned i, BasicBlock *BB)
void setIncomingValue(unsigned i, Value *V)
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
'undef' values are things that do not have specified contents.
Definition Constants.h:1657
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
LLVM_ABI Instruction * getTerminator() const
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool foldBranchToCommonDest(CondBrInst *BI, llvm::DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, const TargetTransformInfo *TTI=nullptr, AssumptionCache *AC=nullptr, unsigned BonusInstThreshold=1)
If this basic block is ONLY a setcc and a branch, and if a predecessor branches to us and one of our ...
LLVM_ABI BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI void initializeLoopSimplifyPass(PassRegistry &)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
LLVM_ABI char & LCSSAID
Definition LCSSA.cpp:545
LLVM_ABI char & LoopSimplifyID
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA, const TargetTransformInfo *TTI=nullptr)
Simplify each loop in a loop nest recursively.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI char & BreakCriticalEdgesID
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:76
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Definition Local.cpp:2592
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
TargetTransformInfo TTI
LLVM_ABI bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
Definition LoopUtils.cpp:59
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool formLCSSA(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put loop into LCSSA form.
Definition LCSSA.cpp:447
LLVM_ABI Pass * createLoopSimplifyPass()