1009b1c42SEd Schouten //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This pass performs several transformations to transform natural loops into a
10009b1c42SEd Schouten // simpler form, which makes subsequent analyses and transformations simpler and
11009b1c42SEd Schouten // more effective.
12009b1c42SEd Schouten //
13009b1c42SEd Schouten // Loop pre-header insertion guarantees that there is a single, non-critical
14009b1c42SEd Schouten // entry edge from outside of the loop to the loop header. This simplifies a
15009b1c42SEd Schouten // number of analyses and transformations, such as LICM.
16009b1c42SEd Schouten //
17009b1c42SEd Schouten // Loop exit-block insertion guarantees that all exit blocks from the loop
18009b1c42SEd Schouten // (blocks which are outside of the loop that have predecessors inside of the
19009b1c42SEd Schouten // loop) only have predecessors from inside of the loop (and are thus dominated
20009b1c42SEd Schouten // by the loop header). This simplifies transformations such as store-sinking
21009b1c42SEd Schouten // that are built into LICM.
22009b1c42SEd Schouten //
23009b1c42SEd Schouten // This pass also guarantees that loops will have exactly one backedge.
24009b1c42SEd Schouten //
25907da171SRoman Divacky // Indirectbr instructions introduce several complications. If the loop
26907da171SRoman Divacky // contains or is entered by an indirectbr instruction, it may not be possible
27907da171SRoman Divacky // to transform the loop and make these guarantees. Client code should check
28907da171SRoman Divacky // that these conditions are true before relying on them.
29907da171SRoman Divacky //
30e6d15924SDimitry Andric // Similar complications arise from callbr instructions, particularly in
31e6d15924SDimitry Andric // asm-goto where blockaddress expressions are used.
32e6d15924SDimitry Andric //
33009b1c42SEd Schouten // Note that the simplifycfg pass will clean up blocks which are split out but
34009b1c42SEd Schouten // end up being unnecessary, so usage of this pass should not pessimize
35009b1c42SEd Schouten // generated code.
36009b1c42SEd Schouten //
37009b1c42SEd Schouten // This pass obviously modifies the CFG, but updates loop information and
38009b1c42SEd Schouten // dominator information.
39009b1c42SEd Schouten //
40009b1c42SEd Schouten //===----------------------------------------------------------------------===//
41009b1c42SEd Schouten
4201095a5dSDimitry Andric #include "llvm/Transforms/Utils/LoopSimplify.h"
434a16efa3SDimitry Andric #include "llvm/ADT/SetVector.h"
445ca98fd9SDimitry Andric #include "llvm/ADT/SmallVector.h"
454a16efa3SDimitry Andric #include "llvm/ADT/Statistic.h"
46009b1c42SEd Schouten #include "llvm/Analysis/AliasAnalysis.h"
4767c32a98SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
487ab83427SDimitry Andric #include "llvm/Analysis/BasicAliasAnalysis.h"
49e6d15924SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
50522600a2SDimitry Andric #include "llvm/Analysis/DependenceAnalysis.h"
51dd58ef01SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
52cf099d11SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
535ca98fd9SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
54e6d15924SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
55e6d15924SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
56cf099d11SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
57dd58ef01SDimitry Andric #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
585ca98fd9SDimitry Andric #include "llvm/IR/CFG.h"
594a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
605ca98fd9SDimitry Andric #include "llvm/IR/Dominators.h"
614a16efa3SDimitry Andric #include "llvm/IR/Function.h"
624a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
634a16efa3SDimitry Andric #include "llvm/IR/LLVMContext.h"
645a5ac124SDimitry Andric #include "llvm/IR/Module.h"
65706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
6667a71b31SRoman Divacky #include "llvm/Support/Debug.h"
675a5ac124SDimitry Andric #include "llvm/Support/raw_ostream.h"
68eb11fae6SDimitry Andric #include "llvm/Transforms/Utils.h"
694a16efa3SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
70e6d15924SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
71f8af5cf6SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
72009b1c42SEd Schouten using namespace llvm;
73009b1c42SEd Schouten
745ca98fd9SDimitry Andric #define DEBUG_TYPE "loop-simplify"
755ca98fd9SDimitry Andric
76009b1c42SEd Schouten STATISTIC(NumNested , "Number of nested loops split out");
77009b1c42SEd Schouten
785ca98fd9SDimitry Andric // If the block isn't already, move the new block to right after some 'outside
795ca98fd9SDimitry Andric // block' block. This prevents the preheader from being placed inside the loop
805ca98fd9SDimitry Andric // body, e.g. when the loop hasn't been rotated.
placeSplitBlockCarefully(BasicBlock * NewBB,SmallVectorImpl<BasicBlock * > & SplitPreds,Loop * L)815ca98fd9SDimitry Andric static void placeSplitBlockCarefully(BasicBlock *NewBB,
82f8af5cf6SDimitry Andric SmallVectorImpl<BasicBlock *> &SplitPreds,
835ca98fd9SDimitry Andric Loop *L) {
845ca98fd9SDimitry Andric // Check to see if NewBB is already well placed.
85dd58ef01SDimitry Andric Function::iterator BBI = --NewBB->getIterator();
86ac9a064cSDimitry Andric for (BasicBlock *Pred : SplitPreds) {
87ac9a064cSDimitry Andric if (&*BBI == Pred)
885ca98fd9SDimitry Andric return;
89009b1c42SEd Schouten }
90009b1c42SEd Schouten
915ca98fd9SDimitry Andric // If it isn't already after an outside block, move it after one. This is
925ca98fd9SDimitry Andric // always good as it makes the uncond branch from the outside block into a
935ca98fd9SDimitry Andric // fall-through.
945ca98fd9SDimitry Andric
955ca98fd9SDimitry Andric // Figure out *which* outside block to put this after. Prefer an outside
965ca98fd9SDimitry Andric // block that neighbors a BB actually in the loop.
975ca98fd9SDimitry Andric BasicBlock *FoundBB = nullptr;
98ac9a064cSDimitry Andric for (BasicBlock *Pred : SplitPreds) {
99ac9a064cSDimitry Andric Function::iterator BBI = Pred->getIterator();
100dd58ef01SDimitry Andric if (++BBI != NewBB->getParent()->end() && L->contains(&*BBI)) {
101ac9a064cSDimitry Andric FoundBB = Pred;
1025ca98fd9SDimitry Andric break;
1035ca98fd9SDimitry Andric }
1045ca98fd9SDimitry Andric }
1055ca98fd9SDimitry Andric
1065ca98fd9SDimitry Andric // If our heuristic for a *good* bb to place this after doesn't find
1075ca98fd9SDimitry Andric // anything, just pick something. It's likely better than leaving it within
1085ca98fd9SDimitry Andric // the loop.
1095ca98fd9SDimitry Andric if (!FoundBB)
1105ca98fd9SDimitry Andric FoundBB = SplitPreds[0];
1115ca98fd9SDimitry Andric NewBB->moveAfter(FoundBB);
1125ca98fd9SDimitry Andric }
1135ca98fd9SDimitry Andric
1145ca98fd9SDimitry Andric /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
1155ca98fd9SDimitry Andric /// preheader, this method is called to insert one. This method has two phases:
1165ca98fd9SDimitry Andric /// preheader insertion and analysis updating.
117009b1c42SEd Schouten ///
InsertPreheaderForLoop(Loop * L,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)118dd58ef01SDimitry Andric BasicBlock *llvm::InsertPreheaderForLoop(Loop *L, DominatorTree *DT,
119e6d15924SDimitry Andric LoopInfo *LI, MemorySSAUpdater *MSSAU,
120e6d15924SDimitry Andric bool PreserveLCSSA) {
1215ca98fd9SDimitry Andric BasicBlock *Header = L->getHeader();
1225ca98fd9SDimitry Andric
1235ca98fd9SDimitry Andric // Compute the set of predecessors of the loop that are not in the loop.
1245ca98fd9SDimitry Andric SmallVector<BasicBlock*, 8> OutsideBlocks;
125344a3780SDimitry Andric for (BasicBlock *P : predecessors(Header)) {
1265ca98fd9SDimitry Andric if (!L->contains(P)) { // Coming in from outside the loop?
127e6d15924SDimitry Andric // If the loop is branched to from an indirect terminator, we won't
1285ca98fd9SDimitry Andric // be able to fully transform the loop, because it prohibits
1295ca98fd9SDimitry Andric // edge splitting.
1304b4fe385SDimitry Andric if (isa<IndirectBrInst>(P->getTerminator()))
131e6d15924SDimitry Andric return nullptr;
1325ca98fd9SDimitry Andric
1335ca98fd9SDimitry Andric // Keep track of it.
1345ca98fd9SDimitry Andric OutsideBlocks.push_back(P);
1355ca98fd9SDimitry Andric }
1365ca98fd9SDimitry Andric }
1375ca98fd9SDimitry Andric
1385ca98fd9SDimitry Andric // Split out the loop pre-header.
1395ca98fd9SDimitry Andric BasicBlock *PreheaderBB;
140dd58ef01SDimitry Andric PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader", DT,
141e6d15924SDimitry Andric LI, MSSAU, PreserveLCSSA);
142dd58ef01SDimitry Andric if (!PreheaderBB)
143dd58ef01SDimitry Andric return nullptr;
1445ca98fd9SDimitry Andric
145eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "LoopSimplify: Creating pre-header "
1465ca98fd9SDimitry Andric << PreheaderBB->getName() << "\n");
1475ca98fd9SDimitry Andric
1485ca98fd9SDimitry Andric // Make sure that NewBB is put someplace intelligent, which doesn't mess up
1495ca98fd9SDimitry Andric // code layout too horribly.
1505ca98fd9SDimitry Andric placeSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
1515ca98fd9SDimitry Andric
1525ca98fd9SDimitry Andric return PreheaderBB;
1535ca98fd9SDimitry Andric }
1545ca98fd9SDimitry Andric
1555ca98fd9SDimitry Andric /// Add the specified block, and all of its predecessors, to the specified set,
1565ca98fd9SDimitry Andric /// if it's not already in there. Stop predecessor traversal when we reach
1575ca98fd9SDimitry Andric /// StopBlock.
addBlockAndPredsToSet(BasicBlock * InputBB,BasicBlock * StopBlock,SmallPtrSetImpl<BasicBlock * > & Blocks)1585ca98fd9SDimitry Andric static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
159b60736ecSDimitry Andric SmallPtrSetImpl<BasicBlock *> &Blocks) {
1605ca98fd9SDimitry Andric SmallVector<BasicBlock *, 8> Worklist;
1615ca98fd9SDimitry Andric Worklist.push_back(InputBB);
1625ca98fd9SDimitry Andric do {
1635ca98fd9SDimitry Andric BasicBlock *BB = Worklist.pop_back_val();
1645ca98fd9SDimitry Andric if (Blocks.insert(BB).second && BB != StopBlock)
1655ca98fd9SDimitry Andric // If BB is not already processed and it is not a stop block then
1665ca98fd9SDimitry Andric // insert its predecessor in the work list
167b60736ecSDimitry Andric append_range(Worklist, predecessors(BB));
1685ca98fd9SDimitry Andric } while (!Worklist.empty());
1695ca98fd9SDimitry Andric }
1705ca98fd9SDimitry Andric
171eb11fae6SDimitry Andric /// The first part of loop-nestification is to find a PHI node that tells
1725ca98fd9SDimitry Andric /// us how to partition the loops.
findPHIToPartitionLoops(Loop * L,DominatorTree * DT,AssumptionCache * AC)173dd58ef01SDimitry Andric static PHINode *findPHIToPartitionLoops(Loop *L, DominatorTree *DT,
17467c32a98SDimitry Andric AssumptionCache *AC) {
175ac9a064cSDimitry Andric const DataLayout &DL = L->getHeader()->getDataLayout();
1765ca98fd9SDimitry Andric for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
1775ca98fd9SDimitry Andric PHINode *PN = cast<PHINode>(I);
1785ca98fd9SDimitry Andric ++I;
179145449b1SDimitry Andric if (Value *V = simplifyInstruction(PN, {DL, nullptr, DT, AC})) {
1805ca98fd9SDimitry Andric // This is a degenerate PHI already, don't modify it!
1815ca98fd9SDimitry Andric PN->replaceAllUsesWith(V);
1825ca98fd9SDimitry Andric PN->eraseFromParent();
1835ca98fd9SDimitry Andric continue;
1845ca98fd9SDimitry Andric }
1855ca98fd9SDimitry Andric
1865ca98fd9SDimitry Andric // Scan this PHI node looking for a use of the PHI node by itself.
1875ca98fd9SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1885ca98fd9SDimitry Andric if (PN->getIncomingValue(i) == PN &&
1895ca98fd9SDimitry Andric L->contains(PN->getIncomingBlock(i)))
1905ca98fd9SDimitry Andric // We found something tasty to remove.
1915ca98fd9SDimitry Andric return PN;
1925ca98fd9SDimitry Andric }
1935ca98fd9SDimitry Andric return nullptr;
1945ca98fd9SDimitry Andric }
1955ca98fd9SDimitry Andric
196eb11fae6SDimitry Andric /// If this loop has multiple backedges, try to pull one of them out into
1975ca98fd9SDimitry Andric /// a nested loop.
1985ca98fd9SDimitry Andric ///
1995ca98fd9SDimitry Andric /// This is important for code that looks like
2005ca98fd9SDimitry Andric /// this:
2015ca98fd9SDimitry Andric ///
2025ca98fd9SDimitry Andric /// Loop:
2035ca98fd9SDimitry Andric /// ...
2045ca98fd9SDimitry Andric /// br cond, Loop, Next
2055ca98fd9SDimitry Andric /// ...
2065ca98fd9SDimitry Andric /// br cond2, Loop, Out
2075ca98fd9SDimitry Andric ///
2085ca98fd9SDimitry Andric /// To identify this common case, we look at the PHI nodes in the header of the
2095ca98fd9SDimitry Andric /// loop. PHI nodes with unchanging values on one backedge correspond to values
2105ca98fd9SDimitry Andric /// that change in the "outer" loop, but not in the "inner" loop.
2115ca98fd9SDimitry Andric ///
2125ca98fd9SDimitry Andric /// If we are able to separate out a loop, return the new outer loop that was
2135ca98fd9SDimitry Andric /// created.
2145ca98fd9SDimitry Andric ///
separateNestedLoop(Loop * L,BasicBlock * Preheader,DominatorTree * DT,LoopInfo * LI,ScalarEvolution * SE,bool PreserveLCSSA,AssumptionCache * AC,MemorySSAUpdater * MSSAU)2155ca98fd9SDimitry Andric static Loop *separateNestedLoop(Loop *L, BasicBlock *Preheader,
216dd58ef01SDimitry Andric DominatorTree *DT, LoopInfo *LI,
217dd58ef01SDimitry Andric ScalarEvolution *SE, bool PreserveLCSSA,
218e6d15924SDimitry Andric AssumptionCache *AC, MemorySSAUpdater *MSSAU) {
2195ca98fd9SDimitry Andric // Don't try to separate loops without a preheader.
2205ca98fd9SDimitry Andric if (!Preheader)
2215ca98fd9SDimitry Andric return nullptr;
2225ca98fd9SDimitry Andric
223cfca06d7SDimitry Andric // Treat the presence of convergent functions conservatively. The
224cfca06d7SDimitry Andric // transformation is invalid if calls to certain convergent
225cfca06d7SDimitry Andric // functions (like an AMDGPU barrier) get included in the resulting
226cfca06d7SDimitry Andric // inner loop. But blocks meant for the inner loop will be
227cfca06d7SDimitry Andric // identified later at a point where it's too late to abort the
228cfca06d7SDimitry Andric // transformation. Also, the convergent attribute is not really
229cfca06d7SDimitry Andric // sufficient to express the semantics of functions that are
230cfca06d7SDimitry Andric // affected by this transformation. So we choose to back off if such
231cfca06d7SDimitry Andric // a function call is present until a better alternative becomes
232cfca06d7SDimitry Andric // available. This is similar to the conservative treatment of
233cfca06d7SDimitry Andric // convergent function calls in GVNHoist and JumpThreading.
234e3b55780SDimitry Andric for (auto *BB : L->blocks()) {
235cfca06d7SDimitry Andric for (auto &II : *BB) {
236cfca06d7SDimitry Andric if (auto CI = dyn_cast<CallBase>(&II)) {
237cfca06d7SDimitry Andric if (CI->isConvergent()) {
238cfca06d7SDimitry Andric return nullptr;
239cfca06d7SDimitry Andric }
240cfca06d7SDimitry Andric }
241cfca06d7SDimitry Andric }
242cfca06d7SDimitry Andric }
243cfca06d7SDimitry Andric
2445ca98fd9SDimitry Andric // The header is not a landing pad; preheader insertion should ensure this.
245dd58ef01SDimitry Andric BasicBlock *Header = L->getHeader();
246dd58ef01SDimitry Andric assert(!Header->isEHPad() && "Can't insert backedge to EH pad");
2475ca98fd9SDimitry Andric
248dd58ef01SDimitry Andric PHINode *PN = findPHIToPartitionLoops(L, DT, AC);
2495ca98fd9SDimitry Andric if (!PN) return nullptr; // No known way to partition.
2505ca98fd9SDimitry Andric
2515ca98fd9SDimitry Andric // Pull out all predecessors that have varying values in the loop. This
2525ca98fd9SDimitry Andric // handles the case when a PHI node has multiple instances of itself as
2535ca98fd9SDimitry Andric // arguments.
2545ca98fd9SDimitry Andric SmallVector<BasicBlock*, 8> OuterLoopPreds;
2555ca98fd9SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2565ca98fd9SDimitry Andric if (PN->getIncomingValue(i) != PN ||
2575ca98fd9SDimitry Andric !L->contains(PN->getIncomingBlock(i))) {
258e6d15924SDimitry Andric // We can't split indirect control flow edges.
2594b4fe385SDimitry Andric if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
2605ca98fd9SDimitry Andric return nullptr;
2615ca98fd9SDimitry Andric OuterLoopPreds.push_back(PN->getIncomingBlock(i));
2625ca98fd9SDimitry Andric }
2635ca98fd9SDimitry Andric }
264eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n");
2655ca98fd9SDimitry Andric
2665ca98fd9SDimitry Andric // If ScalarEvolution is around and knows anything about values in
2675ca98fd9SDimitry Andric // this loop, tell it to forget them, because we're about to
2685ca98fd9SDimitry Andric // substantially change it.
2695ca98fd9SDimitry Andric if (SE)
2705ca98fd9SDimitry Andric SE->forgetLoop(L);
2715ca98fd9SDimitry Andric
2725a5ac124SDimitry Andric BasicBlock *NewBB = SplitBlockPredecessors(Header, OuterLoopPreds, ".outer",
273e6d15924SDimitry Andric DT, LI, MSSAU, PreserveLCSSA);
2745ca98fd9SDimitry Andric
2755ca98fd9SDimitry Andric // Make sure that NewBB is put someplace intelligent, which doesn't mess up
2765ca98fd9SDimitry Andric // code layout too horribly.
2775ca98fd9SDimitry Andric placeSplitBlockCarefully(NewBB, OuterLoopPreds, L);
2785ca98fd9SDimitry Andric
2795ca98fd9SDimitry Andric // Create the new outer loop.
280044eb2f6SDimitry Andric Loop *NewOuter = LI->AllocateLoop();
2815ca98fd9SDimitry Andric
2825ca98fd9SDimitry Andric // Change the parent loop to use the outer loop as its child now.
2835ca98fd9SDimitry Andric if (Loop *Parent = L->getParentLoop())
2845ca98fd9SDimitry Andric Parent->replaceChildLoopWith(L, NewOuter);
2855ca98fd9SDimitry Andric else
2865ca98fd9SDimitry Andric LI->changeTopLevelLoop(L, NewOuter);
2875ca98fd9SDimitry Andric
2885ca98fd9SDimitry Andric // L is now a subloop of our outer loop.
2895ca98fd9SDimitry Andric NewOuter->addChildLoop(L);
2905ca98fd9SDimitry Andric
291846a2208SDimitry Andric for (BasicBlock *BB : L->blocks())
292846a2208SDimitry Andric NewOuter->addBlockEntry(BB);
2935ca98fd9SDimitry Andric
2945ca98fd9SDimitry Andric // Now reset the header in L, which had been moved by
2955ca98fd9SDimitry Andric // SplitBlockPredecessors for the outer loop.
2965ca98fd9SDimitry Andric L->moveToHeader(Header);
2975ca98fd9SDimitry Andric
2985ca98fd9SDimitry Andric // Determine which blocks should stay in L and which should be moved out to
2995ca98fd9SDimitry Andric // the Outer loop now.
300b60736ecSDimitry Andric SmallPtrSet<BasicBlock *, 4> BlocksInL;
301b60736ecSDimitry Andric for (BasicBlock *P : predecessors(Header)) {
3025ca98fd9SDimitry Andric if (DT->dominates(Header, P))
3035ca98fd9SDimitry Andric addBlockAndPredsToSet(P, Header, BlocksInL);
3045ca98fd9SDimitry Andric }
3055ca98fd9SDimitry Andric
3065ca98fd9SDimitry Andric // Scan all of the loop children of L, moving them to OuterLoop if they are
3075ca98fd9SDimitry Andric // not part of the inner loop.
3085ca98fd9SDimitry Andric const std::vector<Loop*> &SubLoops = L->getSubLoops();
3095ca98fd9SDimitry Andric for (size_t I = 0; I != SubLoops.size(); )
3105ca98fd9SDimitry Andric if (BlocksInL.count(SubLoops[I]->getHeader()))
3115ca98fd9SDimitry Andric ++I; // Loop remains in L
3125ca98fd9SDimitry Andric else
3135ca98fd9SDimitry Andric NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
3145ca98fd9SDimitry Andric
315a7fe922bSDimitry Andric SmallVector<BasicBlock *, 8> OuterLoopBlocks;
316a7fe922bSDimitry Andric OuterLoopBlocks.push_back(NewBB);
3175ca98fd9SDimitry Andric // Now that we know which blocks are in L and which need to be moved to
3185ca98fd9SDimitry Andric // OuterLoop, move any blocks that need it.
3195ca98fd9SDimitry Andric for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
3205ca98fd9SDimitry Andric BasicBlock *BB = L->getBlocks()[i];
3215ca98fd9SDimitry Andric if (!BlocksInL.count(BB)) {
3225ca98fd9SDimitry Andric // Move this block to the parent, updating the exit blocks sets
3235ca98fd9SDimitry Andric L->removeBlockFromLoop(BB);
324a7fe922bSDimitry Andric if ((*LI)[BB] == L) {
3255ca98fd9SDimitry Andric LI->changeLoopFor(BB, NewOuter);
326a7fe922bSDimitry Andric OuterLoopBlocks.push_back(BB);
327a7fe922bSDimitry Andric }
3285ca98fd9SDimitry Andric --i;
3295ca98fd9SDimitry Andric }
3305ca98fd9SDimitry Andric }
3315ca98fd9SDimitry Andric
332a7fe922bSDimitry Andric // Split edges to exit blocks from the inner loop, if they emerged in the
333a7fe922bSDimitry Andric // process of separating the outer one.
334e6d15924SDimitry Andric formDedicatedExitBlocks(L, DT, LI, MSSAU, PreserveLCSSA);
335a7fe922bSDimitry Andric
336a7fe922bSDimitry Andric if (PreserveLCSSA) {
337a7fe922bSDimitry Andric // Fix LCSSA form for L. Some values, which previously were only used inside
338a7fe922bSDimitry Andric // L, can now be used in NewOuter loop. We need to insert phi-nodes for them
339a7fe922bSDimitry Andric // in corresponding exit blocks.
340b915e9e0SDimitry Andric // We don't need to form LCSSA recursively, because there cannot be uses
341b915e9e0SDimitry Andric // inside a newly created loop of defs from inner loops as those would
342b915e9e0SDimitry Andric // already be a use of an LCSSA phi node.
343b915e9e0SDimitry Andric formLCSSA(*L, *DT, LI, SE);
344a7fe922bSDimitry Andric
345b915e9e0SDimitry Andric assert(NewOuter->isRecursivelyLCSSAForm(*DT, *LI) &&
346a7fe922bSDimitry Andric "LCSSA is broken after separating nested loops!");
347a7fe922bSDimitry Andric }
348a7fe922bSDimitry Andric
3495ca98fd9SDimitry Andric return NewOuter;
3505ca98fd9SDimitry Andric }
3515ca98fd9SDimitry Andric
352eb11fae6SDimitry Andric /// This method is called when the specified loop has more than one
3535ca98fd9SDimitry Andric /// backedge in it.
3545ca98fd9SDimitry Andric ///
3555ca98fd9SDimitry Andric /// If this occurs, revector all of these backedges to target a new basic block
3565ca98fd9SDimitry Andric /// and have that block branch to the loop header. This ensures that loops
3575ca98fd9SDimitry Andric /// have exactly one backedge.
insertUniqueBackedgeBlock(Loop * L,BasicBlock * Preheader,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU)3585ca98fd9SDimitry Andric static BasicBlock *insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader,
359e6d15924SDimitry Andric DominatorTree *DT, LoopInfo *LI,
360e6d15924SDimitry Andric MemorySSAUpdater *MSSAU) {
3615ca98fd9SDimitry Andric assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
3625ca98fd9SDimitry Andric
3635ca98fd9SDimitry Andric // Get information about the loop
3645ca98fd9SDimitry Andric BasicBlock *Header = L->getHeader();
3655ca98fd9SDimitry Andric Function *F = Header->getParent();
3665ca98fd9SDimitry Andric
3675ca98fd9SDimitry Andric // Unique backedge insertion currently depends on having a preheader.
3685ca98fd9SDimitry Andric if (!Preheader)
3695ca98fd9SDimitry Andric return nullptr;
3705ca98fd9SDimitry Andric
371dd58ef01SDimitry Andric // The header is not an EH pad; preheader insertion should ensure this.
372dd58ef01SDimitry Andric assert(!Header->isEHPad() && "Can't insert backedge to EH pad");
3735ca98fd9SDimitry Andric
3745ca98fd9SDimitry Andric // Figure out which basic blocks contain back-edges to the loop header.
3755ca98fd9SDimitry Andric std::vector<BasicBlock*> BackedgeBlocks;
376344a3780SDimitry Andric for (BasicBlock *P : predecessors(Header)) {
377e6d15924SDimitry Andric // Indirect edges cannot be split, so we must fail if we find one.
3784b4fe385SDimitry Andric if (isa<IndirectBrInst>(P->getTerminator()))
3795ca98fd9SDimitry Andric return nullptr;
3805ca98fd9SDimitry Andric
3815ca98fd9SDimitry Andric if (P != Preheader) BackedgeBlocks.push_back(P);
3825ca98fd9SDimitry Andric }
3835ca98fd9SDimitry Andric
3845ca98fd9SDimitry Andric // Create and insert the new backedge block...
3855ca98fd9SDimitry Andric BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
3865ca98fd9SDimitry Andric Header->getName() + ".backedge", F);
3875ca98fd9SDimitry Andric BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
3881a82d4c0SDimitry Andric BETerminator->setDebugLoc(Header->getFirstNonPHI()->getDebugLoc());
3895ca98fd9SDimitry Andric
390eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block "
3915ca98fd9SDimitry Andric << BEBlock->getName() << "\n");
3925ca98fd9SDimitry Andric
3935ca98fd9SDimitry Andric // Move the new backedge block to right after the last backedge block.
394dd58ef01SDimitry Andric Function::iterator InsertPos = ++BackedgeBlocks.back()->getIterator();
395e3b55780SDimitry Andric F->splice(InsertPos, F, BEBlock->getIterator());
3965ca98fd9SDimitry Andric
3975ca98fd9SDimitry Andric // Now that the block has been inserted into the function, create PHI nodes in
3985ca98fd9SDimitry Andric // the backedge block which correspond to any PHI nodes in the header block.
3995ca98fd9SDimitry Andric for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
4005ca98fd9SDimitry Andric PHINode *PN = cast<PHINode>(I);
4015ca98fd9SDimitry Andric PHINode *NewPN = PHINode::Create(PN->getType(), BackedgeBlocks.size(),
402ac9a064cSDimitry Andric PN->getName()+".be", BETerminator->getIterator());
4035ca98fd9SDimitry Andric
4045ca98fd9SDimitry Andric // Loop over the PHI node, moving all entries except the one for the
4055ca98fd9SDimitry Andric // preheader over to the new PHI node.
4065ca98fd9SDimitry Andric unsigned PreheaderIdx = ~0U;
4075ca98fd9SDimitry Andric bool HasUniqueIncomingValue = true;
4085ca98fd9SDimitry Andric Value *UniqueValue = nullptr;
4095ca98fd9SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4105ca98fd9SDimitry Andric BasicBlock *IBB = PN->getIncomingBlock(i);
4115ca98fd9SDimitry Andric Value *IV = PN->getIncomingValue(i);
4125ca98fd9SDimitry Andric if (IBB == Preheader) {
4135ca98fd9SDimitry Andric PreheaderIdx = i;
4145ca98fd9SDimitry Andric } else {
4155ca98fd9SDimitry Andric NewPN->addIncoming(IV, IBB);
4165ca98fd9SDimitry Andric if (HasUniqueIncomingValue) {
4175ca98fd9SDimitry Andric if (!UniqueValue)
4185ca98fd9SDimitry Andric UniqueValue = IV;
4195ca98fd9SDimitry Andric else if (UniqueValue != IV)
4205ca98fd9SDimitry Andric HasUniqueIncomingValue = false;
4215ca98fd9SDimitry Andric }
4225ca98fd9SDimitry Andric }
4235ca98fd9SDimitry Andric }
4245ca98fd9SDimitry Andric
4255ca98fd9SDimitry Andric // Delete all of the incoming values from the old PN except the preheader's
4265ca98fd9SDimitry Andric assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
4275ca98fd9SDimitry Andric if (PreheaderIdx != 0) {
4285ca98fd9SDimitry Andric PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
4295ca98fd9SDimitry Andric PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
4305ca98fd9SDimitry Andric }
4315ca98fd9SDimitry Andric // Nuke all entries except the zero'th.
432b1c73532SDimitry Andric PN->removeIncomingValueIf([](unsigned Idx) { return Idx != 0; },
433b1c73532SDimitry Andric /* DeletePHIIfEmpty */ false);
4345ca98fd9SDimitry Andric
4355ca98fd9SDimitry Andric // Finally, add the newly constructed PHI node as the entry for the BEBlock.
4365ca98fd9SDimitry Andric PN->addIncoming(NewPN, BEBlock);
4375ca98fd9SDimitry Andric
4385ca98fd9SDimitry Andric // As an optimization, if all incoming values in the new PhiNode (which is a
4395ca98fd9SDimitry Andric // subset of the incoming values of the old PHI node) have the same value,
4405ca98fd9SDimitry Andric // eliminate the PHI Node.
4415ca98fd9SDimitry Andric if (HasUniqueIncomingValue) {
4425ca98fd9SDimitry Andric NewPN->replaceAllUsesWith(UniqueValue);
443e3b55780SDimitry Andric NewPN->eraseFromParent();
4445ca98fd9SDimitry Andric }
4455ca98fd9SDimitry Andric }
4465ca98fd9SDimitry Andric
4475ca98fd9SDimitry Andric // Now that all of the PHI nodes have been inserted and adjusted, modify the
448b915e9e0SDimitry Andric // backedge blocks to jump to the BEBlock instead of the header.
449b915e9e0SDimitry Andric // If one of the backedges has llvm.loop metadata attached, we remove
450b915e9e0SDimitry Andric // it from the backedge and add it to BEBlock.
451b915e9e0SDimitry Andric MDNode *LoopMD = nullptr;
452e3b55780SDimitry Andric for (BasicBlock *BB : BackedgeBlocks) {
453e3b55780SDimitry Andric Instruction *TI = BB->getTerminator();
454b915e9e0SDimitry Andric if (!LoopMD)
4557fa27ce4SDimitry Andric LoopMD = TI->getMetadata(LLVMContext::MD_loop);
4567fa27ce4SDimitry Andric TI->setMetadata(LLVMContext::MD_loop, nullptr);
457e6d15924SDimitry Andric TI->replaceSuccessorWith(Header, BEBlock);
4585ca98fd9SDimitry Andric }
4597fa27ce4SDimitry Andric BEBlock->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopMD);
4605ca98fd9SDimitry Andric
4615ca98fd9SDimitry Andric //===--- Update all analyses which we must preserve now -----------------===//
4625ca98fd9SDimitry Andric
4635ca98fd9SDimitry Andric // Update Loop Information - we know that this block is now in the current
4645ca98fd9SDimitry Andric // loop and all parent loops.
4655a5ac124SDimitry Andric L->addBasicBlockToLoop(BEBlock, *LI);
4665ca98fd9SDimitry Andric
4675ca98fd9SDimitry Andric // Update dominator information
4685ca98fd9SDimitry Andric DT->splitBlock(BEBlock);
4695ca98fd9SDimitry Andric
470e6d15924SDimitry Andric if (MSSAU)
471e6d15924SDimitry Andric MSSAU->updatePhisWhenInsertingUniqueBackedgeBlock(Header, Preheader,
472e6d15924SDimitry Andric BEBlock);
473e6d15924SDimitry Andric
4745ca98fd9SDimitry Andric return BEBlock;
4755ca98fd9SDimitry Andric }
4765ca98fd9SDimitry Andric
477eb11fae6SDimitry Andric /// Simplify one loop and queue further loops for simplification.
simplifyOneLoop(Loop * L,SmallVectorImpl<Loop * > & Worklist,DominatorTree * DT,LoopInfo * LI,ScalarEvolution * SE,AssumptionCache * AC,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)4785ca98fd9SDimitry Andric static bool simplifyOneLoop(Loop *L, SmallVectorImpl<Loop *> &Worklist,
479dd58ef01SDimitry Andric DominatorTree *DT, LoopInfo *LI,
480dd58ef01SDimitry Andric ScalarEvolution *SE, AssumptionCache *AC,
481e6d15924SDimitry Andric MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
482009b1c42SEd Schouten bool Changed = false;
483e6d15924SDimitry Andric if (MSSAU && VerifyMemorySSA)
484e6d15924SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
485e6d15924SDimitry Andric
486009b1c42SEd Schouten ReprocessLoop:
487009b1c42SEd Schouten
488ea5b2dd1SRoman Divacky // Check to see that no blocks (other than the header) in this loop have
48959850d08SRoman Divacky // predecessors that are not in the loop. This is not valid for natural
49059850d08SRoman Divacky // loops, but can occur if the blocks are unreachable. Since they are
49159850d08SRoman Divacky // unreachable we can just shamelessly delete those CFG edges!
492846a2208SDimitry Andric for (BasicBlock *BB : L->blocks()) {
493846a2208SDimitry Andric if (BB == L->getHeader())
494846a2208SDimitry Andric continue;
495009b1c42SEd Schouten
49659850d08SRoman Divacky SmallPtrSet<BasicBlock*, 4> BadPreds;
497846a2208SDimitry Andric for (BasicBlock *P : predecessors(BB))
49866e41e3cSRoman Divacky if (!L->contains(P))
49966e41e3cSRoman Divacky BadPreds.insert(P);
50059850d08SRoman Divacky
50159850d08SRoman Divacky // Delete each unique out-of-loop (and thus dead) predecessor.
50267c32a98SDimitry Andric for (BasicBlock *P : BadPreds) {
50367a71b31SRoman Divacky
504eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor "
50567c32a98SDimitry Andric << P->getName() << "\n");
50667a71b31SRoman Divacky
50759850d08SRoman Divacky // Zap the dead pred's terminator and replace it with unreachable.
508d8e91e46SDimitry Andric Instruction *TI = P->getTerminator();
509344a3780SDimitry Andric changeToUnreachable(TI, PreserveLCSSA,
510e6d15924SDimitry Andric /*DTU=*/nullptr, MSSAU);
51159850d08SRoman Divacky Changed = true;
51259850d08SRoman Divacky }
51359850d08SRoman Divacky }
514009b1c42SEd Schouten
515e6d15924SDimitry Andric if (MSSAU && VerifyMemorySSA)
516e6d15924SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
517e6d15924SDimitry Andric
51867a71b31SRoman Divacky // If there are exiting blocks with branches on undef, resolve the undef in
51967a71b31SRoman Divacky // the direction which will exit the loop. This will help simplify loop
52067a71b31SRoman Divacky // trip count computations.
52167a71b31SRoman Divacky SmallVector<BasicBlock*, 8> ExitingBlocks;
52267a71b31SRoman Divacky L->getExitingBlocks(ExitingBlocks);
52301095a5dSDimitry Andric for (BasicBlock *ExitingBlock : ExitingBlocks)
52401095a5dSDimitry Andric if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
52567a71b31SRoman Divacky if (BI->isConditional()) {
52667a71b31SRoman Divacky if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
52767a71b31SRoman Divacky
528eb11fae6SDimitry Andric LLVM_DEBUG(dbgs()
529eb11fae6SDimitry Andric << "LoopSimplify: Resolving \"br i1 undef\" to exit in "
53001095a5dSDimitry Andric << ExitingBlock->getName() << "\n");
53167a71b31SRoman Divacky
53267a71b31SRoman Divacky BI->setCondition(ConstantInt::get(Cond->getType(),
53367a71b31SRoman Divacky !L->contains(BI->getSuccessor(0))));
534522600a2SDimitry Andric
53567a71b31SRoman Divacky Changed = true;
53667a71b31SRoman Divacky }
53767a71b31SRoman Divacky }
53867a71b31SRoman Divacky
539009b1c42SEd Schouten // Does the loop already have a preheader? If so, don't insert one.
54059850d08SRoman Divacky BasicBlock *Preheader = L->getLoopPreheader();
54159850d08SRoman Divacky if (!Preheader) {
542e6d15924SDimitry Andric Preheader = InsertPreheaderForLoop(L, DT, LI, MSSAU, PreserveLCSSA);
54308bbd35aSDimitry Andric if (Preheader)
544009b1c42SEd Schouten Changed = true;
545009b1c42SEd Schouten }
546009b1c42SEd Schouten
547009b1c42SEd Schouten // Next, check to make sure that all exit nodes of the loop only have
548009b1c42SEd Schouten // predecessors that are inside of the loop. This check guarantees that the
549009b1c42SEd Schouten // loop preheader/header will dominate the exit blocks. If the exit block has
550009b1c42SEd Schouten // predecessors from outside of the loop, split the edge now.
551e6d15924SDimitry Andric if (formDedicatedExitBlocks(L, DT, LI, MSSAU, PreserveLCSSA))
552009b1c42SEd Schouten Changed = true;
553009b1c42SEd Schouten
554e6d15924SDimitry Andric if (MSSAU && VerifyMemorySSA)
555e6d15924SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
556e6d15924SDimitry Andric
557009b1c42SEd Schouten // If the header has more than two predecessors at this point (from the
558009b1c42SEd Schouten // preheader and from multiple backedges), we must adjust the loop.
559907da171SRoman Divacky BasicBlock *LoopLatch = L->getLoopLatch();
560907da171SRoman Divacky if (!LoopLatch) {
561009b1c42SEd Schouten // If this is really a nested loop, rip it out into a child loop. Don't do
562009b1c42SEd Schouten // this for loops with a giant number of backedges, just factor them into a
563009b1c42SEd Schouten // common backedge instead.
564907da171SRoman Divacky if (L->getNumBackEdges() < 8) {
565e6d15924SDimitry Andric if (Loop *OuterL = separateNestedLoop(L, Preheader, DT, LI, SE,
566e6d15924SDimitry Andric PreserveLCSSA, AC, MSSAU)) {
567009b1c42SEd Schouten ++NumNested;
5685ca98fd9SDimitry Andric // Enqueue the outer loop as it should be processed next in our
5695ca98fd9SDimitry Andric // depth-first nest walk.
5705ca98fd9SDimitry Andric Worklist.push_back(OuterL);
5715ca98fd9SDimitry Andric
572009b1c42SEd Schouten // This is a big restructuring change, reprocess the whole loop.
573009b1c42SEd Schouten Changed = true;
574009b1c42SEd Schouten // GCC doesn't tail recursion eliminate this.
5755ca98fd9SDimitry Andric // FIXME: It isn't clear we can't rely on LLVM to TRE this.
576009b1c42SEd Schouten goto ReprocessLoop;
577009b1c42SEd Schouten }
578009b1c42SEd Schouten }
579009b1c42SEd Schouten
580009b1c42SEd Schouten // If we either couldn't, or didn't want to, identify nesting of the loops,
581009b1c42SEd Schouten // insert a new block that all backedges target, then make it jump to the
582009b1c42SEd Schouten // loop header.
583e6d15924SDimitry Andric LoopLatch = insertUniqueBackedgeBlock(L, Preheader, DT, LI, MSSAU);
58408bbd35aSDimitry Andric if (LoopLatch)
585009b1c42SEd Schouten Changed = true;
586009b1c42SEd Schouten }
587009b1c42SEd Schouten
588e6d15924SDimitry Andric if (MSSAU && VerifyMemorySSA)
589e6d15924SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
590e6d15924SDimitry Andric
591ac9a064cSDimitry Andric const DataLayout &DL = L->getHeader()->getDataLayout();
5925a5ac124SDimitry Andric
593009b1c42SEd Schouten // Scan over the PHI nodes in the loop header. Since they now have only two
594009b1c42SEd Schouten // incoming values (the loop is canonicalized), we may have simplified the PHI
595009b1c42SEd Schouten // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
596009b1c42SEd Schouten PHINode *PN;
597009b1c42SEd Schouten for (BasicBlock::iterator I = L->getHeader()->begin();
598009b1c42SEd Schouten (PN = dyn_cast<PHINode>(I++)); )
599145449b1SDimitry Andric if (Value *V = simplifyInstruction(PN, {DL, nullptr, DT, AC})) {
600cf099d11SDimitry Andric if (SE) SE->forgetValue(PN);
601b915e9e0SDimitry Andric if (!PreserveLCSSA || LI->replacementPreservesLCSSAForm(PN, V)) {
602009b1c42SEd Schouten PN->replaceAllUsesWith(V);
603009b1c42SEd Schouten PN->eraseFromParent();
604cfca06d7SDimitry Andric Changed = true;
605009b1c42SEd Schouten }
606b915e9e0SDimitry Andric }
607009b1c42SEd Schouten
608989df958SRoman Divacky // If this loop has multiple exits and the exits all go to the same
60918f153bdSEd Schouten // block, attempt to merge the exits. This helps several passes, such
61018f153bdSEd Schouten // as LoopRotation, which do not support loops with multiple exits.
61118f153bdSEd Schouten // SimplifyCFG also does this (and this code uses the same utility
61218f153bdSEd Schouten // function), however this code is loop-aware, where SimplifyCFG is
61318f153bdSEd Schouten // not. That gives it the advantage of being able to hoist
61418f153bdSEd Schouten // loop-invariant instructions out of the way to open up more
61518f153bdSEd Schouten // opportunities, and the disadvantage of having the responsibility
61618f153bdSEd Schouten // to preserve dominator information.
61708bbd35aSDimitry Andric auto HasUniqueExitBlock = [&]() {
61808bbd35aSDimitry Andric BasicBlock *UniqueExit = nullptr;
61908bbd35aSDimitry Andric for (auto *ExitingBB : ExitingBlocks)
62008bbd35aSDimitry Andric for (auto *SuccBB : successors(ExitingBB)) {
62108bbd35aSDimitry Andric if (L->contains(SuccBB))
62208bbd35aSDimitry Andric continue;
62308bbd35aSDimitry Andric
62408bbd35aSDimitry Andric if (!UniqueExit)
62508bbd35aSDimitry Andric UniqueExit = SuccBB;
62608bbd35aSDimitry Andric else if (UniqueExit != SuccBB)
62708bbd35aSDimitry Andric return false;
62808bbd35aSDimitry Andric }
62908bbd35aSDimitry Andric
63008bbd35aSDimitry Andric return true;
63108bbd35aSDimitry Andric };
63208bbd35aSDimitry Andric if (HasUniqueExitBlock()) {
633ac9a064cSDimitry Andric for (BasicBlock *ExitingBlock : ExitingBlocks) {
63418f153bdSEd Schouten if (!ExitingBlock->getSinglePredecessor()) continue;
63518f153bdSEd Schouten BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
63618f153bdSEd Schouten if (!BI || !BI->isConditional()) continue;
63718f153bdSEd Schouten CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
63818f153bdSEd Schouten if (!CI || CI->getParent() != ExitingBlock) continue;
63918f153bdSEd Schouten
64018f153bdSEd Schouten // Attempt to hoist out all instructions except for the
64118f153bdSEd Schouten // comparison and the branch.
64218f153bdSEd Schouten bool AllInvariant = true;
6435ca98fd9SDimitry Andric bool AnyInvariant = false;
644eb11fae6SDimitry Andric for (auto I = ExitingBlock->instructionsWithoutDebug().begin(); &*I != BI; ) {
645dd58ef01SDimitry Andric Instruction *Inst = &*I++;
64618f153bdSEd Schouten if (Inst == CI)
64718f153bdSEd Schouten continue;
648e6d15924SDimitry Andric if (!L->makeLoopInvariant(
649e6d15924SDimitry Andric Inst, AnyInvariant,
650e3b55780SDimitry Andric Preheader ? Preheader->getTerminator() : nullptr, MSSAU, SE)) {
65118f153bdSEd Schouten AllInvariant = false;
65218f153bdSEd Schouten break;
65318f153bdSEd Schouten }
65418f153bdSEd Schouten }
655e3b55780SDimitry Andric if (AnyInvariant)
6565ca98fd9SDimitry Andric Changed = true;
65718f153bdSEd Schouten if (!AllInvariant) continue;
65818f153bdSEd Schouten
65918f153bdSEd Schouten // The block has now been cleared of all instructions except for
66018f153bdSEd Schouten // a comparison and a conditional branch. SimplifyCFG may be able
66118f153bdSEd Schouten // to fold it now.
662b60736ecSDimitry Andric if (!FoldBranchToCommonDest(BI, /*DTU=*/nullptr, MSSAU))
6635a5ac124SDimitry Andric continue;
66418f153bdSEd Schouten
66518f153bdSEd Schouten // Success. The block is now dead, so remove it from the loop,
666cf099d11SDimitry Andric // update the dominator tree and delete it.
667eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block "
668cf099d11SDimitry Andric << ExitingBlock->getName() << "\n");
66967a71b31SRoman Divacky
670b60736ecSDimitry Andric assert(pred_empty(ExitingBlock));
67118f153bdSEd Schouten Changed = true;
67218f153bdSEd Schouten LI->removeBlock(ExitingBlock);
67318f153bdSEd Schouten
67418f153bdSEd Schouten DomTreeNode *Node = DT->getNode(ExitingBlock);
675cfca06d7SDimitry Andric while (!Node->isLeaf()) {
676cfca06d7SDimitry Andric DomTreeNode *Child = Node->back();
67759850d08SRoman Divacky DT->changeImmediateDominator(Child, Node->getIDom());
67818f153bdSEd Schouten }
67918f153bdSEd Schouten DT->eraseNode(ExitingBlock);
680e6d15924SDimitry Andric if (MSSAU) {
681e6d15924SDimitry Andric SmallSetVector<BasicBlock *, 8> ExitBlockSet;
682e6d15924SDimitry Andric ExitBlockSet.insert(ExitingBlock);
683e6d15924SDimitry Andric MSSAU->removeBlocks(ExitBlockSet);
684e6d15924SDimitry Andric }
68518f153bdSEd Schouten
68601095a5dSDimitry Andric BI->getSuccessor(0)->removePredecessor(
687e6d15924SDimitry Andric ExitingBlock, /* KeepOneInputPHIs */ PreserveLCSSA);
68801095a5dSDimitry Andric BI->getSuccessor(1)->removePredecessor(
689e6d15924SDimitry Andric ExitingBlock, /* KeepOneInputPHIs */ PreserveLCSSA);
69018f153bdSEd Schouten ExitingBlock->eraseFromParent();
69118f153bdSEd Schouten }
69218f153bdSEd Schouten }
69318f153bdSEd Schouten
694e6d15924SDimitry Andric if (MSSAU && VerifyMemorySSA)
695e6d15924SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
696e6d15924SDimitry Andric
697009b1c42SEd Schouten return Changed;
698009b1c42SEd Schouten }
699009b1c42SEd Schouten
simplifyLoop(Loop * L,DominatorTree * DT,LoopInfo * LI,ScalarEvolution * SE,AssumptionCache * AC,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)700dd58ef01SDimitry Andric bool llvm::simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI,
701dd58ef01SDimitry Andric ScalarEvolution *SE, AssumptionCache *AC,
702e6d15924SDimitry Andric MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
7035ca98fd9SDimitry Andric bool Changed = false;
7045ca98fd9SDimitry Andric
70571d5a254SDimitry Andric #ifndef NDEBUG
70671d5a254SDimitry Andric // If we're asked to preserve LCSSA, the loop nest needs to start in LCSSA
70771d5a254SDimitry Andric // form.
70871d5a254SDimitry Andric if (PreserveLCSSA) {
70971d5a254SDimitry Andric assert(DT && "DT not available.");
71071d5a254SDimitry Andric assert(LI && "LI not available.");
71171d5a254SDimitry Andric assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
71271d5a254SDimitry Andric "Requested to preserve LCSSA, but it's already broken.");
71371d5a254SDimitry Andric }
71471d5a254SDimitry Andric #endif
71571d5a254SDimitry Andric
7165ca98fd9SDimitry Andric // Worklist maintains our depth-first queue of loops in this nest to process.
7175ca98fd9SDimitry Andric SmallVector<Loop *, 4> Worklist;
7185ca98fd9SDimitry Andric Worklist.push_back(L);
7195ca98fd9SDimitry Andric
7205ca98fd9SDimitry Andric // Walk the worklist from front to back, pushing newly found sub loops onto
7215ca98fd9SDimitry Andric // the back. This will let us process loops from back to front in depth-first
7225ca98fd9SDimitry Andric // order. We can use this simple process because loops form a tree.
7235ca98fd9SDimitry Andric for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
7245ca98fd9SDimitry Andric Loop *L2 = Worklist[Idx];
7255a5ac124SDimitry Andric Worklist.append(L2->begin(), L2->end());
7265ca98fd9SDimitry Andric }
7275ca98fd9SDimitry Andric
7285ca98fd9SDimitry Andric while (!Worklist.empty())
729dd58ef01SDimitry Andric Changed |= simplifyOneLoop(Worklist.pop_back_val(), Worklist, DT, LI, SE,
730e6d15924SDimitry Andric AC, MSSAU, PreserveLCSSA);
7315ca98fd9SDimitry Andric
7327fa27ce4SDimitry Andric // Changing exit conditions for blocks may affect exit counts of this loop and
7337fa27ce4SDimitry Andric // any of its parents, so we must invalidate the entire subtree if we've made
7347fa27ce4SDimitry Andric // any changes. Do this here rather than in simplifyOneLoop() as the top-most
7357fa27ce4SDimitry Andric // loop is going to be the same for all child loops.
7367fa27ce4SDimitry Andric if (Changed && SE)
7377fa27ce4SDimitry Andric SE->forgetTopmostLoop(L);
7387fa27ce4SDimitry Andric
7395ca98fd9SDimitry Andric return Changed;
7405ca98fd9SDimitry Andric }
7415ca98fd9SDimitry Andric
7425ca98fd9SDimitry Andric namespace {
7435ca98fd9SDimitry Andric struct LoopSimplify : public FunctionPass {
7445ca98fd9SDimitry Andric static char ID; // Pass identification, replacement for typeid
LoopSimplify__anon06e5c5ea0311::LoopSimplify7455ca98fd9SDimitry Andric LoopSimplify() : FunctionPass(ID) {
7465ca98fd9SDimitry Andric initializeLoopSimplifyPass(*PassRegistry::getPassRegistry());
7475ca98fd9SDimitry Andric }
7485ca98fd9SDimitry Andric
7495ca98fd9SDimitry Andric bool runOnFunction(Function &F) override;
7505ca98fd9SDimitry Andric
getAnalysisUsage__anon06e5c5ea0311::LoopSimplify7515ca98fd9SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
75267c32a98SDimitry Andric AU.addRequired<AssumptionCacheTracker>();
75367c32a98SDimitry Andric
7545ca98fd9SDimitry Andric // We need loop information to identify the loops...
7555ca98fd9SDimitry Andric AU.addRequired<DominatorTreeWrapperPass>();
7565ca98fd9SDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>();
7575ca98fd9SDimitry Andric
7585a5ac124SDimitry Andric AU.addRequired<LoopInfoWrapperPass>();
7595a5ac124SDimitry Andric AU.addPreserved<LoopInfoWrapperPass>();
7605ca98fd9SDimitry Andric
761dd58ef01SDimitry Andric AU.addPreserved<BasicAAWrapperPass>();
762dd58ef01SDimitry Andric AU.addPreserved<AAResultsWrapperPass>();
763dd58ef01SDimitry Andric AU.addPreserved<GlobalsAAWrapperPass>();
764dd58ef01SDimitry Andric AU.addPreserved<ScalarEvolutionWrapperPass>();
765dd58ef01SDimitry Andric AU.addPreserved<SCEVAAWrapperPass>();
76601095a5dSDimitry Andric AU.addPreservedID(LCSSAID);
76701095a5dSDimitry Andric AU.addPreserved<DependenceAnalysisWrapperPass>();
7685ca98fd9SDimitry Andric AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
769e6d15924SDimitry Andric AU.addPreserved<BranchProbabilityInfoWrapperPass>();
770e6d15924SDimitry Andric AU.addPreserved<MemorySSAWrapperPass>();
7715ca98fd9SDimitry Andric }
7725ca98fd9SDimitry Andric
7735ca98fd9SDimitry Andric /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees.
7745ca98fd9SDimitry Andric void verifyAnalysis() const override;
7755ca98fd9SDimitry Andric };
7761a82d4c0SDimitry Andric }
7775ca98fd9SDimitry Andric
7785ca98fd9SDimitry Andric char LoopSimplify::ID = 0;
7795ca98fd9SDimitry Andric INITIALIZE_PASS_BEGIN(LoopSimplify, "loop-simplify",
78067c32a98SDimitry Andric "Canonicalize natural loops", false, false)
78167c32a98SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7825ca98fd9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7835a5ac124SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7845ca98fd9SDimitry Andric INITIALIZE_PASS_END(LoopSimplify, "loop-simplify",
78567c32a98SDimitry Andric "Canonicalize natural loops", false, false)
7865ca98fd9SDimitry Andric
7875ca98fd9SDimitry Andric // Publicly exposed interface to pass...
7885ca98fd9SDimitry Andric char &llvm::LoopSimplifyID = LoopSimplify::ID;
createLoopSimplifyPass()7895ca98fd9SDimitry Andric Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
7905ca98fd9SDimitry Andric
7915ca98fd9SDimitry Andric /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
7925ca98fd9SDimitry Andric /// it in any convenient order) inserting preheaders...
793009b1c42SEd Schouten ///
runOnFunction(Function & F)7945ca98fd9SDimitry Andric bool LoopSimplify::runOnFunction(Function &F) {
7955ca98fd9SDimitry Andric bool Changed = false;
79601095a5dSDimitry Andric LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
79701095a5dSDimitry Andric DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
798dd58ef01SDimitry Andric auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
79901095a5dSDimitry Andric ScalarEvolution *SE = SEWP ? &SEWP->getSE() : nullptr;
80001095a5dSDimitry Andric AssumptionCache *AC =
80101095a5dSDimitry Andric &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
802e6d15924SDimitry Andric MemorySSA *MSSA = nullptr;
803e6d15924SDimitry Andric std::unique_ptr<MemorySSAUpdater> MSSAU;
804e6d15924SDimitry Andric auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
805e6d15924SDimitry Andric if (MSSAAnalysis) {
806e6d15924SDimitry Andric MSSA = &MSSAAnalysis->getMSSA();
8071d5ae102SDimitry Andric MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
808e6d15924SDimitry Andric }
80901095a5dSDimitry Andric
810dd58ef01SDimitry Andric bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
811009b1c42SEd Schouten
8125ca98fd9SDimitry Andric // Simplify each loop nest in the function.
813b60736ecSDimitry Andric for (auto *L : *LI)
814b60736ecSDimitry Andric Changed |= simplifyLoop(L, DT, LI, SE, AC, MSSAU.get(), PreserveLCSSA);
815907da171SRoman Divacky
81601095a5dSDimitry Andric #ifndef NDEBUG
81701095a5dSDimitry Andric if (PreserveLCSSA) {
818b915e9e0SDimitry Andric bool InLCSSA = all_of(
819b915e9e0SDimitry Andric *LI, [&](Loop *L) { return L->isRecursivelyLCSSAForm(*DT, *LI); });
82001095a5dSDimitry Andric assert(InLCSSA && "LCSSA is broken after loop-simplify.");
82101095a5dSDimitry Andric }
82201095a5dSDimitry Andric #endif
8235ca98fd9SDimitry Andric return Changed;
824907da171SRoman Divacky }
825009b1c42SEd Schouten
run(Function & F,FunctionAnalysisManager & AM)82601095a5dSDimitry Andric PreservedAnalyses LoopSimplifyPass::run(Function &F,
827b915e9e0SDimitry Andric FunctionAnalysisManager &AM) {
82801095a5dSDimitry Andric bool Changed = false;
82901095a5dSDimitry Andric LoopInfo *LI = &AM.getResult<LoopAnalysis>(F);
83001095a5dSDimitry Andric DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
83101095a5dSDimitry Andric ScalarEvolution *SE = AM.getCachedResult<ScalarEvolutionAnalysis>(F);
83201095a5dSDimitry Andric AssumptionCache *AC = &AM.getResult<AssumptionAnalysis>(F);
8331d5ae102SDimitry Andric auto *MSSAAnalysis = AM.getCachedResult<MemorySSAAnalysis>(F);
8341d5ae102SDimitry Andric std::unique_ptr<MemorySSAUpdater> MSSAU;
8351d5ae102SDimitry Andric if (MSSAAnalysis) {
8361d5ae102SDimitry Andric auto *MSSA = &MSSAAnalysis->getMSSA();
8371d5ae102SDimitry Andric MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
8381d5ae102SDimitry Andric }
8391d5ae102SDimitry Andric
84001095a5dSDimitry Andric
84171d5a254SDimitry Andric // Note that we don't preserve LCSSA in the new PM, if you need it run LCSSA
8421d5ae102SDimitry Andric // after simplifying the loops. MemorySSA is preserved if it exists.
843b60736ecSDimitry Andric for (auto *L : *LI)
844e6d15924SDimitry Andric Changed |=
845b60736ecSDimitry Andric simplifyLoop(L, DT, LI, SE, AC, MSSAU.get(), /*PreserveLCSSA*/ false);
846b915e9e0SDimitry Andric
84701095a5dSDimitry Andric if (!Changed)
84801095a5dSDimitry Andric return PreservedAnalyses::all();
84971d5a254SDimitry Andric
85001095a5dSDimitry Andric PreservedAnalyses PA;
85101095a5dSDimitry Andric PA.preserve<DominatorTreeAnalysis>();
85201095a5dSDimitry Andric PA.preserve<LoopAnalysis>();
85301095a5dSDimitry Andric PA.preserve<ScalarEvolutionAnalysis>();
85401095a5dSDimitry Andric PA.preserve<DependenceAnalysis>();
8551d5ae102SDimitry Andric if (MSSAAnalysis)
8561d5ae102SDimitry Andric PA.preserve<MemorySSAAnalysis>();
857e6d15924SDimitry Andric // BPI maps conditional terminators to probabilities, LoopSimplify can insert
858e6d15924SDimitry Andric // blocks, but it does so only by splitting existing blocks and edges. This
859e6d15924SDimitry Andric // results in the interesting property that all new terminators inserted are
860e6d15924SDimitry Andric // unconditional branches which do not appear in BPI. All deletions are
861e6d15924SDimitry Andric // handled via ValueHandle callbacks w/in BPI.
862e6d15924SDimitry Andric PA.preserve<BranchProbabilityAnalysis>();
86301095a5dSDimitry Andric return PA;
86401095a5dSDimitry Andric }
86501095a5dSDimitry Andric
8665ca98fd9SDimitry Andric // FIXME: Restore this code when we re-enable verification in verifyAnalysis
8675ca98fd9SDimitry Andric // below.
8685ca98fd9SDimitry Andric #if 0
8695ca98fd9SDimitry Andric static void verifyLoop(Loop *L) {
8705ca98fd9SDimitry Andric // Verify subloops.
8715ca98fd9SDimitry Andric for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
8725ca98fd9SDimitry Andric verifyLoop(*I);
873009b1c42SEd Schouten
874907da171SRoman Divacky // It used to be possible to just assert L->isLoopSimplifyForm(), however
875907da171SRoman Divacky // with the introduction of indirectbr, there are now cases where it's
876907da171SRoman Divacky // not possible to transform a loop as necessary. We can at least check
877907da171SRoman Divacky // that there is an indirectbr near any time there's trouble.
878907da171SRoman Divacky
879907da171SRoman Divacky // Indirectbr can interfere with preheader and unique backedge insertion.
880907da171SRoman Divacky if (!L->getLoopPreheader() || !L->getLoopLatch()) {
881907da171SRoman Divacky bool HasIndBrPred = false;
882344a3780SDimitry Andric for (BasicBlock *Pred : predecessors(L->getHeader()))
883344a3780SDimitry Andric if (isa<IndirectBrInst>(Pred->getTerminator())) {
884907da171SRoman Divacky HasIndBrPred = true;
885907da171SRoman Divacky break;
886907da171SRoman Divacky }
887907da171SRoman Divacky assert(HasIndBrPred &&
888907da171SRoman Divacky "LoopSimplify has no excuse for missing loop header info!");
88930815c53SDimitry Andric (void)HasIndBrPred;
890907da171SRoman Divacky }
891907da171SRoman Divacky
892907da171SRoman Divacky // Indirectbr can interfere with exit block canonicalization.
893907da171SRoman Divacky if (!L->hasDedicatedExits()) {
894907da171SRoman Divacky bool HasIndBrExiting = false;
895907da171SRoman Divacky SmallVector<BasicBlock*, 8> ExitingBlocks;
896907da171SRoman Divacky L->getExitingBlocks(ExitingBlocks);
89730815c53SDimitry Andric for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
898907da171SRoman Divacky if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
899907da171SRoman Divacky HasIndBrExiting = true;
900907da171SRoman Divacky break;
901907da171SRoman Divacky }
90230815c53SDimitry Andric }
90330815c53SDimitry Andric
904907da171SRoman Divacky assert(HasIndBrExiting &&
905907da171SRoman Divacky "LoopSimplify has no excuse for missing exit block info!");
90630815c53SDimitry Andric (void)HasIndBrExiting;
907907da171SRoman Divacky }
908009b1c42SEd Schouten }
9095ca98fd9SDimitry Andric #endif
9105ca98fd9SDimitry Andric
verifyAnalysis() const9115ca98fd9SDimitry Andric void LoopSimplify::verifyAnalysis() const {
9125ca98fd9SDimitry Andric // FIXME: This routine is being called mid-way through the loop pass manager
9135ca98fd9SDimitry Andric // as loop passes destroy this analysis. That's actually fine, but we have no
9145ca98fd9SDimitry Andric // way of expressing that here. Once all of the passes that destroy this are
9155ca98fd9SDimitry Andric // hoisted out of the loop pass manager we can add back verification here.
9165ca98fd9SDimitry Andric #if 0
9175ca98fd9SDimitry Andric for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
9185ca98fd9SDimitry Andric verifyLoop(*I);
9195ca98fd9SDimitry Andric #endif
9205ca98fd9SDimitry Andric }
921