1 //===- LoopNestAnalysis.cpp - Loop Nest Analysis --------------------------==//
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 /// \file
10 /// The implementation for the loop nest analysis.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/LoopNestAnalysis.h"
15 #include "llvm/ADT/BreadthFirstIterator.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/PostDominators.h"
18 #include "llvm/Analysis/ValueTracking.h"
19 
20 using namespace llvm;
21 
22 #define DEBUG_TYPE "loopnest"
23 #ifndef NDEBUG
24 static const char *VerboseDebug = DEBUG_TYPE "-verbose";
25 #endif
26 
27 /// Determine whether the loops structure violates basic requirements for
28 /// perfect nesting:
29 ///  - the inner loop should be the outer loop's only child
30 ///  - the outer loop header should 'flow' into the inner loop preheader
31 ///    or jump around the inner loop to the outer loop latch
32 ///  - if the inner loop latch exits the inner loop, it should 'flow' into
33 ///    the outer loop latch.
34 /// Returns true if the loop structure satisfies the basic requirements and
35 /// false otherwise.
36 static bool checkLoopsStructure(const Loop &OuterLoop, const Loop &InnerLoop,
37                                 ScalarEvolution &SE);
38 
39 //===----------------------------------------------------------------------===//
40 // LoopNest implementation
41 //
42 
43 LoopNest::LoopNest(Loop &Root, ScalarEvolution &SE)
44     : MaxPerfectDepth(getMaxPerfectDepth(Root, SE)) {
45   for (Loop *L : breadth_first(&Root))
46     Loops.push_back(L);
47 }
48 
49 std::unique_ptr<LoopNest> LoopNest::getLoopNest(Loop &Root,
50                                                 ScalarEvolution &SE) {
51   return std::make_unique<LoopNest>(Root, SE);
52 }
53 
54 bool LoopNest::arePerfectlyNested(const Loop &OuterLoop, const Loop &InnerLoop,
55                                   ScalarEvolution &SE) {
56   assert(!OuterLoop.isInnermost() && "Outer loop should have subloops");
57   assert(!InnerLoop.isOutermost() && "Inner loop should have a parent");
58   LLVM_DEBUG(dbgs() << "Checking whether loop '" << OuterLoop.getName()
59                     << "' and '" << InnerLoop.getName()
60                     << "' are perfectly nested.\n");
61 
62   // Determine whether the loops structure satisfies the following requirements:
63   //  - the inner loop should be the outer loop's only child
64   //  - the outer loop header should 'flow' into the inner loop preheader
65   //    or jump around the inner loop to the outer loop latch
66   //  - if the inner loop latch exits the inner loop, it should 'flow' into
67   //    the outer loop latch.
68   if (!checkLoopsStructure(OuterLoop, InnerLoop, SE)) {
69     LLVM_DEBUG(dbgs() << "Not perfectly nested: invalid loop structure.\n");
70     return false;
71   }
72 
73   // Bail out if we cannot retrieve the outer loop bounds.
74   auto OuterLoopLB = OuterLoop.getBounds(SE);
75   if (OuterLoopLB == None) {
76     LLVM_DEBUG(dbgs() << "Cannot compute loop bounds of OuterLoop: "
77                       << OuterLoop << "\n";);
78     return false;
79   }
80 
81   // Identify the outer loop latch comparison instruction.
82   const BasicBlock *Latch = OuterLoop.getLoopLatch();
83   assert(Latch && "Expecting a valid loop latch");
84   const BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
85   assert(BI && BI->isConditional() &&
86          "Expecting loop latch terminator to be a branch instruction");
87 
88   const CmpInst *OuterLoopLatchCmp = dyn_cast<CmpInst>(BI->getCondition());
89   DEBUG_WITH_TYPE(
90       VerboseDebug, if (OuterLoopLatchCmp) {
91         dbgs() << "Outer loop latch compare instruction: " << *OuterLoopLatchCmp
92                << "\n";
93       });
94 
95   // Identify the inner loop guard instruction.
96   BranchInst *InnerGuard = InnerLoop.getLoopGuardBranch();
97   const CmpInst *InnerLoopGuardCmp =
98       (InnerGuard) ? dyn_cast<CmpInst>(InnerGuard->getCondition()) : nullptr;
99 
100   DEBUG_WITH_TYPE(
101       VerboseDebug, if (InnerLoopGuardCmp) {
102         dbgs() << "Inner loop guard compare instruction: " << *InnerLoopGuardCmp
103                << "\n";
104       });
105 
106   // Determine whether instructions in a basic block are one of:
107   //  - the inner loop guard comparison
108   //  - the outer loop latch comparison
109   //  - the outer loop induction variable increment
110   //  - a phi node, a cast or a branch
111   auto containsOnlySafeInstructions = [&](const BasicBlock &BB) {
112     return llvm::all_of(BB, [&](const Instruction &I) {
113       bool isAllowed = isSafeToSpeculativelyExecute(&I) || isa<PHINode>(I) ||
114                        isa<BranchInst>(I);
115       if (!isAllowed) {
116         DEBUG_WITH_TYPE(VerboseDebug, {
117           dbgs() << "Instruction: " << I << "\nin basic block: " << BB
118                  << " is considered unsafe.\n";
119         });
120         return false;
121       }
122 
123       // The only binary instruction allowed is the outer loop step instruction,
124       // the only comparison instructions allowed are the inner loop guard
125       // compare instruction and the outer loop latch compare instruction.
126       if ((isa<BinaryOperator>(I) && &I != &OuterLoopLB->getStepInst()) ||
127           (isa<CmpInst>(I) && &I != OuterLoopLatchCmp &&
128            &I != InnerLoopGuardCmp)) {
129         DEBUG_WITH_TYPE(VerboseDebug, {
130           dbgs() << "Instruction: " << I << "\nin basic block:" << BB
131                  << "is unsafe.\n";
132         });
133         return false;
134       }
135       return true;
136     });
137   };
138 
139   // Check the code surrounding the inner loop for instructions that are deemed
140   // unsafe.
141   const BasicBlock *OuterLoopHeader = OuterLoop.getHeader();
142   const BasicBlock *OuterLoopLatch = OuterLoop.getLoopLatch();
143   const BasicBlock *InnerLoopPreHeader = InnerLoop.getLoopPreheader();
144 
145   if (!containsOnlySafeInstructions(*OuterLoopHeader) ||
146       !containsOnlySafeInstructions(*OuterLoopLatch) ||
147       (InnerLoopPreHeader != OuterLoopHeader &&
148        !containsOnlySafeInstructions(*InnerLoopPreHeader)) ||
149       !containsOnlySafeInstructions(*InnerLoop.getExitBlock())) {
150     LLVM_DEBUG(dbgs() << "Not perfectly nested: code surrounding inner loop is "
151                          "unsafe\n";);
152     return false;
153   }
154 
155   LLVM_DEBUG(dbgs() << "Loop '" << OuterLoop.getName() << "' and '"
156                     << InnerLoop.getName() << "' are perfectly nested.\n");
157 
158   return true;
159 }
160 
161 SmallVector<LoopVectorTy, 4>
162 LoopNest::getPerfectLoops(ScalarEvolution &SE) const {
163   SmallVector<LoopVectorTy, 4> LV;
164   LoopVectorTy PerfectNest;
165 
166   for (Loop *L : depth_first(const_cast<Loop *>(Loops.front()))) {
167     if (PerfectNest.empty())
168       PerfectNest.push_back(L);
169 
170     auto &SubLoops = L->getSubLoops();
171     if (SubLoops.size() == 1 && arePerfectlyNested(*L, *SubLoops.front(), SE)) {
172       PerfectNest.push_back(SubLoops.front());
173     } else {
174       LV.push_back(PerfectNest);
175       PerfectNest.clear();
176     }
177   }
178 
179   return LV;
180 }
181 
182 unsigned LoopNest::getMaxPerfectDepth(const Loop &Root, ScalarEvolution &SE) {
183   LLVM_DEBUG(dbgs() << "Get maximum perfect depth of loop nest rooted by loop '"
184                     << Root.getName() << "'\n");
185 
186   const Loop *CurrentLoop = &Root;
187   const auto *SubLoops = &CurrentLoop->getSubLoops();
188   unsigned CurrentDepth = 1;
189 
190   while (SubLoops->size() == 1) {
191     const Loop *InnerLoop = SubLoops->front();
192     if (!arePerfectlyNested(*CurrentLoop, *InnerLoop, SE)) {
193       LLVM_DEBUG({
194         dbgs() << "Not a perfect nest: loop '" << CurrentLoop->getName()
195                << "' is not perfectly nested with loop '"
196                << InnerLoop->getName() << "'\n";
197       });
198       break;
199     }
200 
201     CurrentLoop = InnerLoop;
202     SubLoops = &CurrentLoop->getSubLoops();
203     ++CurrentDepth;
204   }
205 
206   return CurrentDepth;
207 }
208 
209 const BasicBlock &LoopNest::skipEmptyBlockUntil(const BasicBlock *From,
210                                                 const BasicBlock *End) {
211   assert(From && "Expecting valid From");
212   assert(End && "Expecting valid End");
213 
214   if (From == End || !From->getSingleSuccessor())
215     return *From;
216 
217   auto IsEmpty = [](const BasicBlock *BB) {
218     return (BB->getInstList().size() == 1);
219   };
220 
221   // Visited is used to avoid running into an infinite loop.
222   SmallPtrSet<const BasicBlock *, 4> Visited;
223   const BasicBlock *BB = From->getSingleSuccessor();
224   const BasicBlock *PredBB = BB;
225   while (BB && BB != End && IsEmpty(BB) && !Visited.count(BB)) {
226     Visited.insert(BB);
227     PredBB = BB;
228     BB = BB->getSingleSuccessor();
229   }
230 
231   return (BB == End) ? *End : *PredBB;
232 }
233 
234 static bool checkLoopsStructure(const Loop &OuterLoop, const Loop &InnerLoop,
235                                 ScalarEvolution &SE) {
236   // The inner loop must be the only outer loop's child.
237   if ((OuterLoop.getSubLoops().size() != 1) ||
238       (InnerLoop.getParentLoop() != &OuterLoop))
239     return false;
240 
241   // We expect loops in normal form which have a preheader, header, latch...
242   if (!OuterLoop.isLoopSimplifyForm() || !InnerLoop.isLoopSimplifyForm())
243     return false;
244 
245   const BasicBlock *OuterLoopHeader = OuterLoop.getHeader();
246   const BasicBlock *OuterLoopLatch = OuterLoop.getLoopLatch();
247   const BasicBlock *InnerLoopPreHeader = InnerLoop.getLoopPreheader();
248   const BasicBlock *InnerLoopLatch = InnerLoop.getLoopLatch();
249   const BasicBlock *InnerLoopExit = InnerLoop.getExitBlock();
250 
251   // We expect rotated loops. The inner loop should have a single exit block.
252   if (OuterLoop.getExitingBlock() != OuterLoopLatch ||
253       InnerLoop.getExitingBlock() != InnerLoopLatch || !InnerLoopExit)
254     return false;
255 
256   // Returns whether the block `ExitBlock` contains at least one LCSSA Phi node.
257   auto ContainsLCSSAPhi = [](const BasicBlock &ExitBlock) {
258     return any_of(ExitBlock.phis(), [](const PHINode &PN) {
259       return PN.getNumIncomingValues() == 1;
260     });
261   };
262 
263   // Returns whether the block `BB` qualifies for being an extra Phi block. The
264   // extra Phi block is the additional block inserted after the exit block of an
265   // "guarded" inner loop which contains "only" Phi nodes corresponding to the
266   // LCSSA Phi nodes in the exit block.
267   auto IsExtraPhiBlock = [&](const BasicBlock &BB) {
268     return BB.getFirstNonPHI() == BB.getTerminator() &&
269            all_of(BB.phis(), [&](const PHINode &PN) {
270              return all_of(PN.blocks(), [&](const BasicBlock *IncomingBlock) {
271                return IncomingBlock == InnerLoopExit ||
272                       IncomingBlock == OuterLoopHeader;
273              });
274            });
275   };
276 
277   const BasicBlock *ExtraPhiBlock = nullptr;
278   // Ensure the only branch that may exist between the loops is the inner loop
279   // guard.
280   if (OuterLoopHeader != InnerLoopPreHeader) {
281     const BasicBlock &SingleSucc =
282         LoopNest::skipEmptyBlockUntil(OuterLoopHeader, InnerLoopPreHeader);
283 
284     // no conditional branch present
285     if (&SingleSucc != InnerLoopPreHeader) {
286       const BranchInst *BI = dyn_cast<BranchInst>(SingleSucc.getTerminator());
287 
288       if (!BI || BI != InnerLoop.getLoopGuardBranch())
289         return false;
290 
291       bool InnerLoopExitContainsLCSSA = ContainsLCSSAPhi(*InnerLoopExit);
292 
293       // The successors of the inner loop guard should be the inner loop
294       // preheader or the outer loop latch possibly through empty blocks.
295       for (const BasicBlock *Succ : BI->successors()) {
296         const BasicBlock *PotentialInnerPreHeader = Succ;
297         const BasicBlock *PotentialOuterLatch = Succ;
298 
299         // Ensure the inner loop guard successor is empty before skipping
300         // blocks.
301         if (Succ->getInstList().size() == 1) {
302           PotentialInnerPreHeader =
303               &LoopNest::skipEmptyBlockUntil(Succ, InnerLoopPreHeader);
304           PotentialOuterLatch =
305               &LoopNest::skipEmptyBlockUntil(Succ, OuterLoopLatch);
306         }
307 
308         if (PotentialInnerPreHeader == InnerLoopPreHeader)
309           continue;
310         if (PotentialOuterLatch == OuterLoopLatch)
311           continue;
312 
313         // If `InnerLoopExit` contains LCSSA Phi instructions, additional block
314         // may be inserted before the `OuterLoopLatch` to which `BI` jumps. The
315         // loops are still considered perfectly nested if the extra block only
316         // contains Phi instructions from InnerLoopExit and OuterLoopHeader.
317         if (InnerLoopExitContainsLCSSA && IsExtraPhiBlock(*Succ) &&
318             Succ->getSingleSuccessor() == OuterLoopLatch) {
319           // Points to the extra block so that we can reference it later in the
320           // final check. We can also conclude that the inner loop is
321           // guarded and there exists LCSSA Phi node in the exit block later if
322           // we see a non-null `ExtraPhiBlock`.
323           ExtraPhiBlock = Succ;
324           continue;
325         }
326 
327         DEBUG_WITH_TYPE(VerboseDebug, {
328           dbgs() << "Inner loop guard successor " << Succ->getName()
329                  << " doesn't lead to inner loop preheader or "
330                     "outer loop latch.\n";
331         });
332         return false;
333       }
334     }
335   }
336 
337   // Ensure the inner loop exit block lead to the outer loop latch possibly
338   // through empty blocks.
339   const BasicBlock &SuccInner =
340       LoopNest::skipEmptyBlockUntil(InnerLoop.getExitBlock(), OuterLoopLatch);
341   if (&SuccInner != OuterLoopLatch && &SuccInner != ExtraPhiBlock) {
342     DEBUG_WITH_TYPE(
343         VerboseDebug,
344         dbgs() << "Inner loop exit block " << *InnerLoopExit
345                << " does not directly lead to the outer loop latch.\n";);
346     return false;
347   }
348 
349   return true;
350 }
351 
352 AnalysisKey LoopNestAnalysis::Key;
353 
354 raw_ostream &llvm::operator<<(raw_ostream &OS, const LoopNest &LN) {
355   OS << "IsPerfect=";
356   if (LN.getMaxPerfectDepth() == LN.getNestDepth())
357     OS << "true";
358   else
359     OS << "false";
360   OS << ", Depth=" << LN.getNestDepth();
361   OS << ", OutermostLoop: " << LN.getOutermostLoop().getName();
362   OS << ", Loops: ( ";
363   for (const Loop *L : LN.getLoops())
364     OS << L->getName() << " ";
365   OS << ")";
366 
367   return OS;
368 }
369 
370 //===----------------------------------------------------------------------===//
371 // LoopNestPrinterPass implementation
372 //
373 
374 PreservedAnalyses LoopNestPrinterPass::run(Loop &L, LoopAnalysisManager &AM,
375                                            LoopStandardAnalysisResults &AR,
376                                            LPMUpdater &U) {
377   if (auto LN = LoopNest::getLoopNest(L, AR.SE))
378     OS << *LN << "\n";
379 
380   return PreservedAnalyses::all();
381 }
382