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
42#include "llvm/Transforms/Utils/LoopSimplify.h"
43#include "llvm/ADT/SetVector.h"
44#include "llvm/ADT/SmallVector.h"
45#include "llvm/ADT/Statistic.h"
46#include "llvm/Analysis/AliasAnalysis.h"
47#include "llvm/Analysis/AssumptionCache.h"
48#include "llvm/Analysis/BasicAliasAnalysis.h"
49#include "llvm/Analysis/BranchProbabilityInfo.h"
50#include "llvm/Analysis/GlobalsModRef.h"
51#include "llvm/Analysis/InstructionSimplify.h"
52#include "llvm/Analysis/LoopInfo.h"
53#include "llvm/Analysis/MemorySSA.h"
54#include "llvm/Analysis/MemorySSAUpdater.h"
55#include "llvm/Analysis/ScalarEvolution.h"
56#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
57#include "llvm/IR/CFG.h"
58#include "llvm/IR/Constants.h"
59#include "llvm/IR/Dominators.h"
60#include "llvm/IR/Function.h"
61#include "llvm/IR/Instructions.h"
62#include "llvm/IR/LLVMContext.h"
63#include "llvm/IR/Module.h"
64#include "llvm/InitializePasses.h"
65#include "llvm/Support/Debug.h"
66#include "llvm/Support/raw_ostream.h"
67#include "llvm/Transforms/Utils.h"
68#include "llvm/Transforms/Utils/BasicBlockUtils.h"
69#include "llvm/Transforms/Utils/Local.h"
70#include "llvm/Transforms/Utils/LoopUtils.h"
71using namespace llvm;
72
73#define DEBUG_TYPE "loop-simplify"
74
75STATISTIC(NumNested , "Number of nested loops split out");
76
77// If the block isn't already, move the new block to right after some 'outside
78// block' block. This prevents the preheader from being placed inside the loop
79// body, e.g. when the loop hasn't been rotated.
80static void placeSplitBlockCarefully(BasicBlock *NewBB,
81 SmallVectorImpl<BasicBlock *> &SplitPreds,
82 Loop *L) {
83 // Check to see if NewBB is already well placed.
84 Function::iterator BBI = --NewBB->getIterator();
85 if (llvm::is_contained(Range&: SplitPreds, Element: &*BBI))
86 return;
87
88 // If it isn't already after an outside block, move it after one. This is
89 // always good as it makes the uncond branch from the outside block into a
90 // fall-through.
91
92 // Figure out *which* outside block to put this after. Prefer an outside
93 // block that neighbors a BB actually in the loop.
94 BasicBlock *FoundBB = nullptr;
95 for (BasicBlock *Pred : SplitPreds) {
96 Function::iterator BBI = Pred->getIterator();
97 if (++BBI != NewBB->getParent()->end() && L->contains(BB: &*BBI)) {
98 FoundBB = Pred;
99 break;
100 }
101 }
102
103 // If our heuristic for a *good* bb to place this after doesn't find
104 // anything, just pick something. It's likely better than leaving it within
105 // the loop.
106 if (!FoundBB)
107 FoundBB = SplitPreds[0];
108 NewBB->moveAfter(MovePos: FoundBB);
109}
110
111/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
112/// preheader, this method is called to insert one. This method has two phases:
113/// preheader insertion and analysis updating.
114///
115BasicBlock *llvm::InsertPreheaderForLoop(Loop *L, DominatorTree *DT,
116 LoopInfo *LI, MemorySSAUpdater *MSSAU,
117 bool PreserveLCSSA) {
118 BasicBlock *Header = L->getHeader();
119
120 // Compute the set of predecessors of the loop that are not in the loop.
121 SmallVector<BasicBlock*, 8> OutsideBlocks;
122 for (BasicBlock *P : predecessors(BB: Header)) {
123 if (!L->contains(BB: P)) { // Coming in from outside the loop?
124 // If the loop is branched to from an indirect terminator, we won't
125 // be able to fully transform the loop, because it prohibits
126 // edge splitting.
127 if (isa<IndirectBrInst>(Val: P->getTerminator()))
128 return nullptr;
129
130 // Keep track of it.
131 OutsideBlocks.push_back(Elt: P);
132 }
133 }
134
135 // Split out the loop pre-header.
136 BasicBlock *PreheaderBB;
137 PreheaderBB = SplitBlockPredecessors(BB: Header, Preds: OutsideBlocks, Suffix: ".preheader", DT,
138 LI, MSSAU, PreserveLCSSA);
139 if (!PreheaderBB)
140 return nullptr;
141
142 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating pre-header "
143 << PreheaderBB->getName() << "\n");
144
145 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
146 // code layout too horribly.
147 placeSplitBlockCarefully(NewBB: PreheaderBB, SplitPreds&: OutsideBlocks, L);
148
149 return PreheaderBB;
150}
151
152/// Add the specified block, and all of its predecessors, to the specified set,
153/// if it's not already in there. Stop predecessor traversal when we reach
154/// StopBlock.
155static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
156 SmallPtrSetImpl<BasicBlock *> &Blocks) {
157 SmallVector<BasicBlock *, 8> Worklist;
158 Worklist.push_back(Elt: InputBB);
159 do {
160 BasicBlock *BB = Worklist.pop_back_val();
161 if (Blocks.insert(Ptr: BB).second && BB != StopBlock)
162 // If BB is not already processed and it is not a stop block then
163 // insert its predecessor in the work list
164 append_range(C&: Worklist, R: predecessors(BB));
165 } while (!Worklist.empty());
166}
167
168/// The first part of loop-nestification is to find a PHI node that tells
169/// us how to partition the loops.
170static PHINode *findPHIToPartitionLoops(Loop *L, DominatorTree *DT,
171 AssumptionCache *AC) {
172 const DataLayout &DL = L->getHeader()->getDataLayout();
173 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(Val: I); ) {
174 PHINode *PN = cast<PHINode>(Val&: I);
175 ++I;
176 if (Value *V = simplifyInstruction(I: PN, Q: {DL, nullptr, DT, AC})) {
177 // This is a degenerate PHI already, don't modify it!
178 PN->replaceAllUsesWith(V);
179 PN->eraseFromParent();
180 continue;
181 }
182
183 // Scan this PHI node looking for a use of the PHI node by itself.
184 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
185 if (PN->getIncomingValue(i) == PN &&
186 L->contains(BB: PN->getIncomingBlock(i)))
187 // We found something tasty to remove.
188 return PN;
189 }
190 return nullptr;
191}
192
193/// If this loop has multiple backedges, try to pull one of them out into
194/// a nested loop.
195///
196/// This is important for code that looks like
197/// this:
198///
199/// Loop:
200/// ...
201/// br cond, Loop, Next
202/// ...
203/// br cond2, Loop, Out
204///
205/// To identify this common case, we look at the PHI nodes in the header of the
206/// loop. PHI nodes with unchanging values on one backedge correspond to values
207/// that change in the "outer" loop, but not in the "inner" loop.
208///
209/// If we are able to separate out a loop, return the new outer loop that was
210/// created.
211///
212static Loop *separateNestedLoop(Loop *L, BasicBlock *Preheader,
213 DominatorTree *DT, LoopInfo *LI,
214 ScalarEvolution *SE, bool PreserveLCSSA,
215 AssumptionCache *AC, MemorySSAUpdater *MSSAU) {
216 // Don't try to separate loops without a preheader.
217 if (!Preheader)
218 return nullptr;
219
220 // Treat the presence of convergent functions conservatively. The
221 // transformation is invalid if calls to certain convergent
222 // functions (like an AMDGPU barrier) get included in the resulting
223 // inner loop. But blocks meant for the inner loop will be
224 // identified later at a point where it's too late to abort the
225 // transformation. Also, the convergent attribute is not really
226 // sufficient to express the semantics of functions that are
227 // affected by this transformation. So we choose to back off if such
228 // a function call is present until a better alternative becomes
229 // available. This is similar to the conservative treatment of
230 // convergent function calls in GVNHoist and JumpThreading.
231 for (auto *BB : L->blocks()) {
232 for (auto &II : *BB) {
233 if (auto CI = dyn_cast<CallBase>(Val: &II)) {
234 if (CI->isConvergent()) {
235 return nullptr;
236 }
237 }
238 }
239 }
240
241 // The header is not a landing pad; preheader insertion should ensure this.
242 BasicBlock *Header = L->getHeader();
243 assert(!Header->isEHPad() && "Can't insert backedge to EH pad");
244
245 PHINode *PN = findPHIToPartitionLoops(L, DT, AC);
246 if (!PN) return nullptr; // No known way to partition.
247
248 // Pull out all predecessors that have varying values in the loop. This
249 // handles the case when a PHI node has multiple instances of itself as
250 // arguments.
251 SmallVector<BasicBlock*, 8> OuterLoopPreds;
252 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
253 if (PN->getIncomingValue(i) != PN ||
254 !L->contains(BB: PN->getIncomingBlock(i))) {
255 // We can't split indirect control flow edges.
256 if (isa<IndirectBrInst>(Val: PN->getIncomingBlock(i)->getTerminator()))
257 return nullptr;
258 OuterLoopPreds.push_back(Elt: PN->getIncomingBlock(i));
259 }
260 }
261 LLVM_DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n");
262
263 // If ScalarEvolution is around and knows anything about values in
264 // this loop, tell it to forget them, because we're about to
265 // substantially change it.
266 if (SE)
267 SE->forgetLoop(L);
268
269 BasicBlock *NewBB = SplitBlockPredecessors(BB: Header, Preds: OuterLoopPreds, Suffix: ".outer",
270 DT, LI, MSSAU, PreserveLCSSA);
271
272 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
273 // code layout too horribly.
274 placeSplitBlockCarefully(NewBB, SplitPreds&: OuterLoopPreds, L);
275
276 // Create the new outer loop.
277 Loop *NewOuter = LI->AllocateLoop();
278
279 // Change the parent loop to use the outer loop as its child now.
280 LI->replaceLoop(Old: L, New: NewOuter);
281
282 // L is now a subloop of our outer loop.
283 NewOuter->addChildLoop(NewChild: L);
284
285 for (BasicBlock *BB : L->blocks())
286 NewOuter->addBlockEntry(BB);
287
288 // Now reset the header in L, which had been moved by
289 // SplitBlockPredecessors for the outer loop.
290 L->moveToHeader(BB: Header);
291
292 // Determine which blocks should stay in L and which should be moved out to
293 // the Outer loop now.
294 SmallPtrSet<BasicBlock *, 4> BlocksInL;
295 for (BasicBlock *P : predecessors(BB: Header)) {
296 if (DT->dominates(A: Header, B: P))
297 addBlockAndPredsToSet(InputBB: P, StopBlock: Header, Blocks&: BlocksInL);
298 }
299
300 // Scan all of the loop children of L, moving them to OuterLoop if they are
301 // not part of the inner loop.
302 const std::vector<Loop*> &SubLoops = L->getSubLoops();
303 for (size_t I = 0; I != SubLoops.size(); )
304 if (BlocksInL.count(Ptr: SubLoops[I]->getHeader()))
305 ++I; // Loop remains in L
306 else
307 NewOuter->addChildLoop(NewChild: L->removeChildLoop(I: SubLoops.begin() + I));
308
309 SmallVector<BasicBlock *, 8> OuterLoopBlocks;
310 OuterLoopBlocks.push_back(Elt: NewBB);
311 // Now that we know which blocks are in L and which need to be moved to
312 // OuterLoop, move any blocks that need it.
313 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
314 BasicBlock *BB = L->getBlocks()[i];
315 if (!BlocksInL.count(Ptr: BB)) {
316 // Move this block to the parent, updating the exit blocks sets
317 L->removeBlockFromLoop(BB);
318 if ((*LI)[BB] == L) {
319 LI->changeLoopFor(BB, L: NewOuter);
320 OuterLoopBlocks.push_back(Elt: BB);
321 }
322 --i;
323 }
324 }
325
326 // Split edges to exit blocks from the inner loop, if they emerged in the
327 // process of separating the outer one.
328 formDedicatedExitBlocks(L, DT, LI, MSSAU, PreserveLCSSA);
329
330 if (PreserveLCSSA) {
331 // Fix LCSSA form for L. Some values, which previously were only used inside
332 // L, can now be used in NewOuter loop. We need to insert phi-nodes for them
333 // in corresponding exit blocks.
334 // We don't need to form LCSSA recursively, because there cannot be uses
335 // inside a newly created loop of defs from inner loops as those would
336 // already be a use of an LCSSA phi node.
337 formLCSSA(L&: *L, DT: *DT, LI, SE);
338
339 assert(NewOuter->isRecursivelyLCSSAForm(*DT, *LI) &&
340 "LCSSA is broken after separating nested loops!");
341 }
342
343 return NewOuter;
344}
345
346/// This method is called when the specified loop has more than one
347/// backedge in it.
348///
349/// If this occurs, revector all of these backedges to target a new basic block
350/// and have that block branch to the loop header. This ensures that loops
351/// have exactly one backedge.
352static BasicBlock *insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader,
353 DominatorTree *DT, LoopInfo *LI,
354 MemorySSAUpdater *MSSAU) {
355 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
356
357 // Get information about the loop
358 BasicBlock *Header = L->getHeader();
359 Function *F = Header->getParent();
360
361 // Unique backedge insertion currently depends on having a preheader.
362 if (!Preheader)
363 return nullptr;
364
365 // The header is not an EH pad; preheader insertion should ensure this.
366 assert(!Header->isEHPad() && "Can't insert backedge to EH pad");
367
368 // Figure out which basic blocks contain back-edges to the loop header.
369 std::vector<BasicBlock*> BackedgeBlocks;
370 for (BasicBlock *P : predecessors(BB: Header)) {
371 // Indirect edges cannot be split, so we must fail if we find one.
372 if (isa<IndirectBrInst>(Val: P->getTerminator()))
373 return nullptr;
374
375 if (P != Preheader) BackedgeBlocks.push_back(x: P);
376 }
377
378 // Create and insert the new backedge block.
379 BasicBlock *BEBlock = BasicBlock::Create(Context&: Header->getContext(),
380 Name: Header->getName() + ".backedge", Parent: F);
381 UncondBrInst *BETerminator = UncondBrInst::Create(Target: Header, InsertBefore: BEBlock);
382 BETerminator->setDebugLoc(Header->getFirstNonPHIIt()->getDebugLoc());
383
384 LLVM_DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block "
385 << BEBlock->getName() << "\n");
386
387 // Move the new backedge block to right after the last backedge block.
388 Function::iterator InsertPos = ++BackedgeBlocks.back()->getIterator();
389 F->splice(ToIt: InsertPos, FromF: F, FromIt: BEBlock->getIterator());
390
391 // Now that the block has been inserted into the function, create PHI nodes in
392 // the backedge block which correspond to any PHI nodes in the header block.
393 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(Val: I); ++I) {
394 PHINode *PN = cast<PHINode>(Val&: I);
395 PHINode *NewPN = PHINode::Create(Ty: PN->getType(), NumReservedValues: BackedgeBlocks.size(),
396 NameStr: PN->getName()+".be", InsertBefore: BETerminator->getIterator());
397
398 // Loop over the PHI node, moving all entries except the one for the
399 // preheader over to the new PHI node.
400 unsigned PreheaderIdx = ~0U;
401 bool HasUniqueIncomingValue = true;
402 Value *UniqueValue = nullptr;
403 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
404 BasicBlock *IBB = PN->getIncomingBlock(i);
405 Value *IV = PN->getIncomingValue(i);
406 if (IBB == Preheader) {
407 PreheaderIdx = i;
408 } else {
409 NewPN->addIncoming(V: IV, BB: IBB);
410 if (HasUniqueIncomingValue) {
411 if (!UniqueValue)
412 UniqueValue = IV;
413 else if (UniqueValue != IV)
414 HasUniqueIncomingValue = false;
415 }
416 }
417 }
418
419 // Delete all of the incoming values from the old PN except the preheader's
420 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
421 if (PreheaderIdx != 0) {
422 PN->setIncomingValue(i: 0, V: PN->getIncomingValue(i: PreheaderIdx));
423 PN->setIncomingBlock(i: 0, BB: PN->getIncomingBlock(i: PreheaderIdx));
424 }
425 // Nuke all entries except the zero'th.
426 PN->removeIncomingValueIf(Predicate: [](unsigned Idx) { return Idx != 0; },
427 /* DeletePHIIfEmpty */ false);
428
429 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
430 PN->addIncoming(V: NewPN, BB: BEBlock);
431
432 // As an optimization, if all incoming values in the new PhiNode (which is a
433 // subset of the incoming values of the old PHI node) have the same value,
434 // eliminate the PHI Node.
435 if (HasUniqueIncomingValue) {
436 NewPN->replaceAllUsesWith(V: UniqueValue);
437 NewPN->eraseFromParent();
438 }
439 }
440
441 // Now that all of the PHI nodes have been inserted and adjusted, modify the
442 // backedge blocks to jump to the BEBlock instead of the header.
443 // If one of the backedges has llvm.loop metadata attached, we remove
444 // it from the backedge and add it to BEBlock.
445 MDNode *LoopMD = nullptr;
446 for (BasicBlock *BB : BackedgeBlocks) {
447 Instruction *TI = BB->getTerminator();
448 if (!LoopMD)
449 LoopMD = TI->getMetadata(KindID: LLVMContext::MD_loop);
450 TI->setMetadata(KindID: LLVMContext::MD_loop, Node: nullptr);
451 TI->replaceSuccessorWith(OldBB: Header, NewBB: BEBlock);
452 }
453 BEBlock->getTerminator()->setMetadata(KindID: LLVMContext::MD_loop, Node: LoopMD);
454
455 //===--- Update all analyses which we must preserve now -----------------===//
456
457 // Update Loop Information - we know that this block is now in the current
458 // loop and all parent loops.
459 L->addBasicBlockToLoop(NewBB: BEBlock, LI&: *LI);
460
461 // Update dominator information
462 DT->splitBlock(NewBB: BEBlock);
463
464 if (MSSAU)
465 MSSAU->updatePhisWhenInsertingUniqueBackedgeBlock(LoopHeader: Header, LoopPreheader: Preheader,
466 BackedgeBlock: BEBlock);
467
468 return BEBlock;
469}
470
471/// Simplify one loop and queue further loops for simplification.
472static bool simplifyOneLoop(Loop *L, SmallVectorImpl<Loop *> &Worklist,
473 DominatorTree *DT, LoopInfo *LI,
474 ScalarEvolution *SE, AssumptionCache *AC,
475 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
476 bool Changed = false;
477 if (MSSAU && VerifyMemorySSA)
478 MSSAU->getMemorySSA()->verifyMemorySSA();
479
480ReprocessLoop:
481
482 // Check to see that no blocks (other than the header) in this loop have
483 // predecessors that are not in the loop. This is not valid for natural
484 // loops, but can occur if the blocks are unreachable. Since they are
485 // unreachable we can just shamelessly delete those CFG edges!
486 for (BasicBlock *BB : L->blocks()) {
487 if (BB == L->getHeader())
488 continue;
489
490 SmallPtrSet<BasicBlock*, 4> BadPreds;
491 for (BasicBlock *P : predecessors(BB))
492 if (!L->contains(BB: P))
493 BadPreds.insert(Ptr: P);
494
495 // Delete each unique out-of-loop (and thus dead) predecessor.
496 for (BasicBlock *P : BadPreds) {
497
498 LLVM_DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor "
499 << P->getName() << "\n");
500
501 // Zap the dead pred's terminator and replace it with unreachable.
502 Instruction *TI = P->getTerminator();
503 changeToUnreachable(I: TI, PreserveLCSSA,
504 /*DTU=*/nullptr, MSSAU);
505 Changed = true;
506 }
507 }
508
509 if (MSSAU && VerifyMemorySSA)
510 MSSAU->getMemorySSA()->verifyMemorySSA();
511
512 // If there are exiting blocks with branches on undef, resolve the undef in
513 // the direction which will exit the loop. This will help simplify loop
514 // trip count computations.
515 SmallVector<BasicBlock*, 8> ExitingBlocks;
516 L->getExitingBlocks(ExitingBlocks);
517 for (BasicBlock *ExitingBlock : ExitingBlocks)
518 if (CondBrInst *BI = dyn_cast<CondBrInst>(Val: ExitingBlock->getTerminator())) {
519 if (UndefValue *Cond = dyn_cast<UndefValue>(Val: BI->getCondition())) {
520
521 LLVM_DEBUG(
522 dbgs() << "LoopSimplify: Resolving \"br i1 undef\" to exit in "
523 << ExitingBlock->getName() << "\n");
524
525 BI->setCondition(ConstantInt::get(Ty: Cond->getType(),
526 V: !L->contains(BB: BI->getSuccessor(i: 0))));
527
528 Changed = true;
529 }
530 }
531
532 // Does the loop already have a preheader? If so, don't insert one.
533 BasicBlock *Preheader = L->getLoopPreheader();
534 if (!Preheader) {
535 Preheader = InsertPreheaderForLoop(L, DT, LI, MSSAU, PreserveLCSSA);
536 if (Preheader)
537 Changed = true;
538 }
539
540 // Next, check to make sure that all exit nodes of the loop only have
541 // predecessors that are inside of the loop. This check guarantees that the
542 // loop preheader/header will dominate the exit blocks. If the exit block has
543 // predecessors from outside of the loop, split the edge now.
544 if (formDedicatedExitBlocks(L, DT, LI, MSSAU, PreserveLCSSA))
545 Changed = true;
546
547 if (MSSAU && VerifyMemorySSA)
548 MSSAU->getMemorySSA()->verifyMemorySSA();
549
550 // If the header has more than two predecessors at this point (from the
551 // preheader and from multiple backedges), we must adjust the loop.
552 BasicBlock *LoopLatch = L->getLoopLatch();
553 if (!LoopLatch) {
554 // If this is really a nested loop, rip it out into a child loop. Don't do
555 // this for loops with a giant number of backedges, just factor them into a
556 // common backedge instead.
557 if (L->getNumBackEdges() < 8) {
558 if (Loop *OuterL = separateNestedLoop(L, Preheader, DT, LI, SE,
559 PreserveLCSSA, AC, MSSAU)) {
560 ++NumNested;
561 // Enqueue the outer loop as it should be processed next in our
562 // depth-first nest walk.
563 Worklist.push_back(Elt: OuterL);
564
565 // This is a big restructuring change, reprocess the whole loop.
566 Changed = true;
567 // GCC doesn't tail recursion eliminate this.
568 // FIXME: It isn't clear we can't rely on LLVM to TRE this.
569 goto ReprocessLoop;
570 }
571 }
572
573 // If we either couldn't, or didn't want to, identify nesting of the loops,
574 // insert a new block that all backedges target, then make it jump to the
575 // loop header.
576 LoopLatch = insertUniqueBackedgeBlock(L, Preheader, DT, LI, MSSAU);
577 if (LoopLatch)
578 Changed = true;
579 }
580
581 if (MSSAU && VerifyMemorySSA)
582 MSSAU->getMemorySSA()->verifyMemorySSA();
583
584 const DataLayout &DL = L->getHeader()->getDataLayout();
585
586 // Scan over the PHI nodes in the loop header. Since they now have only two
587 // incoming values (the loop is canonicalized), we may have simplified the PHI
588 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
589 PHINode *PN;
590 for (BasicBlock::iterator I = L->getHeader()->begin();
591 (PN = dyn_cast<PHINode>(Val: I++)); )
592 if (Value *V = simplifyInstruction(I: PN, Q: {DL, nullptr, DT, AC})) {
593 if (SE) SE->forgetValue(V: PN);
594 if (!PreserveLCSSA || LI->replacementPreservesLCSSAForm(From: PN, To: V)) {
595 PN->replaceAllUsesWith(V);
596 PN->eraseFromParent();
597 Changed = true;
598 }
599 }
600
601 // If this loop has multiple exits and the exits all go to the same
602 // block, attempt to merge the exits. This helps several passes, such
603 // as LoopRotation, which do not support loops with multiple exits.
604 // SimplifyCFG also does this (and this code uses the same utility
605 // function), however this code is loop-aware, where SimplifyCFG is
606 // not. That gives it the advantage of being able to hoist
607 // loop-invariant instructions out of the way to open up more
608 // opportunities, and the disadvantage of having the responsibility
609 // to preserve dominator information.
610 auto HasUniqueExitBlock = [&]() {
611 BasicBlock *UniqueExit = nullptr;
612 for (auto *ExitingBB : ExitingBlocks)
613 for (auto *SuccBB : successors(BB: ExitingBB)) {
614 if (L->contains(BB: SuccBB))
615 continue;
616
617 if (!UniqueExit)
618 UniqueExit = SuccBB;
619 else if (UniqueExit != SuccBB)
620 return false;
621 }
622
623 return true;
624 };
625 if (HasUniqueExitBlock()) {
626 for (BasicBlock *ExitingBlock : ExitingBlocks) {
627 if (!ExitingBlock->getSinglePredecessor()) continue;
628 CondBrInst *BI = dyn_cast<CondBrInst>(Val: ExitingBlock->getTerminator());
629 if (!BI)
630 continue;
631 CmpInst *CI = dyn_cast<CmpInst>(Val: BI->getCondition());
632 if (!CI || CI->getParent() != ExitingBlock) continue;
633
634 // Attempt to hoist out all instructions except for the
635 // comparison and the branch.
636 bool AllInvariant = true;
637 bool AnyInvariant = false;
638 for (auto I = ExitingBlock->begin(); &*I != BI;) {
639 Instruction *Inst = &*I++;
640 if (Inst == CI)
641 continue;
642 if (!L->makeLoopInvariant(
643 I: Inst, Changed&: AnyInvariant,
644 InsertPt: Preheader ? Preheader->getTerminator() : nullptr, MSSAU, SE)) {
645 AllInvariant = false;
646 break;
647 }
648 }
649 if (AnyInvariant)
650 Changed = true;
651 if (!AllInvariant) continue;
652
653 // The block has now been cleared of all instructions except for
654 // a comparison and a conditional branch. SimplifyCFG may be able
655 // to fold it now.
656 if (!foldBranchToCommonDest(BI, /*DTU=*/nullptr, MSSAU))
657 continue;
658
659 // Success. The block is now dead, so remove it from the loop,
660 // update the dominator tree and delete it.
661 LLVM_DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block "
662 << ExitingBlock->getName() << "\n");
663
664 assert(pred_empty(ExitingBlock));
665 Changed = true;
666 LI->removeBlock(BB: ExitingBlock);
667
668 DomTreeNode *Node = DT->getNode(BB: ExitingBlock);
669 while (!Node->isLeaf())
670 DT->changeImmediateDominator(N: *Node->begin(), NewIDom: Node->getIDom());
671 DT->eraseNode(BB: ExitingBlock);
672 if (MSSAU) {
673 SmallSetVector<BasicBlock *, 8> ExitBlockSet;
674 ExitBlockSet.insert(X: ExitingBlock);
675 MSSAU->removeBlocks(DeadBlocks: ExitBlockSet);
676 }
677
678 BI->getSuccessor(i: 0)->removePredecessor(
679 Pred: ExitingBlock, /* KeepOneInputPHIs */ PreserveLCSSA);
680 BI->getSuccessor(i: 1)->removePredecessor(
681 Pred: ExitingBlock, /* KeepOneInputPHIs */ PreserveLCSSA);
682 ExitingBlock->eraseFromParent();
683 }
684 }
685
686 if (MSSAU && VerifyMemorySSA)
687 MSSAU->getMemorySSA()->verifyMemorySSA();
688
689 return Changed;
690}
691
692bool llvm::simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI,
693 ScalarEvolution *SE, AssumptionCache *AC,
694 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
695 bool Changed = false;
696
697#ifndef NDEBUG
698 // If we're asked to preserve LCSSA, the loop nest needs to start in LCSSA
699 // form.
700 if (PreserveLCSSA) {
701 assert(DT && "DT not available.");
702 assert(LI && "LI not available.");
703 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
704 "Requested to preserve LCSSA, but it's already broken.");
705 }
706#endif
707
708 // Worklist maintains our depth-first queue of loops in this nest to process.
709 SmallVector<Loop *, 4> Worklist;
710 Worklist.push_back(Elt: L);
711
712 // Walk the worklist from front to back, pushing newly found sub loops onto
713 // the back. This will let us process loops from back to front in depth-first
714 // order. We can use this simple process because loops form a tree.
715 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
716 Loop *L2 = Worklist[Idx];
717 Worklist.append(in_start: L2->begin(), in_end: L2->end());
718 }
719
720 while (!Worklist.empty())
721 Changed |= simplifyOneLoop(L: Worklist.pop_back_val(), Worklist, DT, LI, SE,
722 AC, MSSAU, PreserveLCSSA);
723
724 // Changing exit conditions for blocks may affect exit counts of this loop and
725 // any of its parents, so we must invalidate the entire subtree if we've made
726 // any changes. Do this here rather than in simplifyOneLoop() as the top-most
727 // loop is going to be the same for all child loops.
728 if (Changed && SE)
729 SE->forgetTopmostLoop(L);
730
731 return Changed;
732}
733
734namespace {
735struct LoopSimplify : public FunctionPass {
736 static char ID; // Pass identification, replacement for typeid
737 LoopSimplify() : FunctionPass(ID) {
738 initializeLoopSimplifyPass(*PassRegistry::getPassRegistry());
739 }
740
741 bool runOnFunction(Function &F) override;
742
743 void getAnalysisUsage(AnalysisUsage &AU) const override {
744 AU.addRequired<AssumptionCacheTracker>();
745
746 // We need loop information to identify the loops.
747 AU.addRequired<DominatorTreeWrapperPass>();
748 AU.addPreserved<DominatorTreeWrapperPass>();
749
750 AU.addRequired<LoopInfoWrapperPass>();
751 AU.addPreserved<LoopInfoWrapperPass>();
752
753 AU.addPreserved<BasicAAWrapperPass>();
754 AU.addPreserved<AAResultsWrapperPass>();
755 AU.addPreserved<GlobalsAAWrapperPass>();
756 AU.addPreserved<ScalarEvolutionWrapperPass>();
757 AU.addPreserved<SCEVAAWrapperPass>();
758 AU.addPreservedID(ID&: LCSSAID);
759 AU.addPreservedID(ID&: BreakCriticalEdgesID); // No critical edges added.
760 AU.addPreserved<BranchProbabilityInfoWrapperPass>();
761 AU.addPreserved<MemorySSAWrapperPass>();
762 }
763
764 /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees.
765 void verifyAnalysis() const override;
766};
767} // namespace
768
769char LoopSimplify::ID = 0;
770INITIALIZE_PASS_BEGIN(LoopSimplify, "loop-simplify",
771 "Canonicalize natural loops", false, false)
772INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
773INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
774INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
775INITIALIZE_PASS_END(LoopSimplify, "loop-simplify", "Canonicalize natural loops",
776 false, false)
777
778// Publicly exposed interface to pass.
779char &llvm::LoopSimplifyID = LoopSimplify::ID;
780Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
781
782/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
783/// it in any convenient order) inserting preheaders.
784///
785bool LoopSimplify::runOnFunction(Function &F) {
786 bool Changed = false;
787 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
788 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
789 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
790 ScalarEvolution *SE = SEWP ? &SEWP->getSE() : nullptr;
791 AssumptionCache *AC =
792 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
793 MemorySSA *MSSA = nullptr;
794 std::unique_ptr<MemorySSAUpdater> MSSAU;
795 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
796 if (MSSAAnalysis) {
797 MSSA = &MSSAAnalysis->getMSSA();
798 MSSAU = std::make_unique<MemorySSAUpdater>(args&: MSSA);
799 }
800
801 bool PreserveLCSSA = mustPreserveAnalysisID(AID&: LCSSAID);
802
803 // Simplify each loop nest in the function.
804 for (auto *L : *LI)
805 Changed |= simplifyLoop(L, DT, LI, SE, AC, MSSAU: MSSAU.get(), PreserveLCSSA);
806
807#ifndef NDEBUG
808 if (PreserveLCSSA) {
809 bool InLCSSA = all_of(
810 *LI, [&](Loop *L) { return L->isRecursivelyLCSSAForm(*DT, *LI); });
811 assert(InLCSSA && "LCSSA is broken after loop-simplify.");
812 }
813#endif
814 return Changed;
815}
816
817PreservedAnalyses LoopSimplifyPass::run(Function &F,
818 FunctionAnalysisManager &AM) {
819 bool Changed = false;
820 LoopInfo *LI = &AM.getResult<LoopAnalysis>(IR&: F);
821 DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(IR&: F);
822 ScalarEvolution *SE = AM.getCachedResult<ScalarEvolutionAnalysis>(IR&: F);
823 AssumptionCache *AC = &AM.getResult<AssumptionAnalysis>(IR&: F);
824 auto *MSSAAnalysis = AM.getCachedResult<MemorySSAAnalysis>(IR&: F);
825 std::unique_ptr<MemorySSAUpdater> MSSAU;
826 if (MSSAAnalysis) {
827 auto *MSSA = &MSSAAnalysis->getMSSA();
828 MSSAU = std::make_unique<MemorySSAUpdater>(args&: MSSA);
829 }
830
831
832 // Note that we don't preserve LCSSA in the new PM, if you need it run LCSSA
833 // after simplifying the loops. MemorySSA is preserved if it exists.
834 for (auto *L : *LI)
835 Changed |=
836 simplifyLoop(L, DT, LI, SE, AC, MSSAU: MSSAU.get(), /*PreserveLCSSA*/ false);
837
838 if (!Changed)
839 return PreservedAnalyses::all();
840
841 PreservedAnalyses PA;
842 PA.preserve<DominatorTreeAnalysis>();
843 PA.preserve<LoopAnalysis>();
844 PA.preserve<ScalarEvolutionAnalysis>();
845 if (MSSAAnalysis)
846 PA.preserve<MemorySSAAnalysis>();
847 // BPI maps conditional terminators to probabilities, LoopSimplify can insert
848 // blocks, but it does so only by splitting existing blocks and edges. This
849 // results in the interesting property that all new terminators inserted are
850 // unconditional branches which do not appear in BPI. All deletions are
851 // handled via ValueHandle callbacks w/in BPI.
852 PA.preserve<BranchProbabilityAnalysis>();
853 return PA;
854}
855
856// FIXME: Restore this code when we re-enable verification in verifyAnalysis
857// below.
858#if 0
859static void verifyLoop(Loop *L) {
860 // Verify subloops.
861 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
862 verifyLoop(*I);
863
864 // It used to be possible to just assert L->isLoopSimplifyForm(), however
865 // with the introduction of indirectbr, there are now cases where it's
866 // not possible to transform a loop as necessary. We can at least check
867 // that there is an indirectbr near any time there's trouble.
868
869 // Indirectbr can interfere with preheader and unique backedge insertion.
870 if (!L->getLoopPreheader() || !L->getLoopLatch()) {
871 bool HasIndBrPred = false;
872 for (BasicBlock *Pred : predecessors(L->getHeader()))
873 if (isa<IndirectBrInst>(Pred->getTerminator())) {
874 HasIndBrPred = true;
875 break;
876 }
877 assert(HasIndBrPred &&
878 "LoopSimplify has no excuse for missing loop header info!");
879 (void)HasIndBrPred;
880 }
881
882 // Indirectbr can interfere with exit block canonicalization.
883 if (!L->hasDedicatedExits()) {
884 bool HasIndBrExiting = false;
885 SmallVector<BasicBlock*, 8> ExitingBlocks;
886 L->getExitingBlocks(ExitingBlocks);
887 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
888 if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
889 HasIndBrExiting = true;
890 break;
891 }
892 }
893
894 assert(HasIndBrExiting &&
895 "LoopSimplify has no excuse for missing exit block info!");
896 (void)HasIndBrExiting;
897 }
898}
899#endif
900
901void LoopSimplify::verifyAnalysis() const {
902 // FIXME: This routine is being called mid-way through the loop pass manager
903 // as loop passes destroy this analysis. That's actually fine, but we have no
904 // way of expressing that here. Once all of the passes that destroy this are
905 // hoisted out of the loop pass manager we can add back verification here.
906#if 0
907 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
908 verifyLoop(*I);
909#endif
910}
911