15adb96ccSEugene Zelenko //===- LoopVersioningLICM.cpp - LICM Loop Versioning ----------------------===//
2df6763abSAshutosh Nema //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6df6763abSAshutosh Nema //
7df6763abSAshutosh Nema //===----------------------------------------------------------------------===//
8df6763abSAshutosh Nema //
9df6763abSAshutosh Nema // When alias analysis is uncertain about the aliasing between any two accesses,
10df6763abSAshutosh Nema // it will return MayAlias. This uncertainty from alias analysis restricts LICM
11df6763abSAshutosh Nema // from proceeding further. In cases where alias analysis is uncertain we might
12df6763abSAshutosh Nema // use loop versioning as an alternative.
13df6763abSAshutosh Nema //
14df6763abSAshutosh Nema // Loop Versioning will create a version of the loop with aggressive aliasing
15df6763abSAshutosh Nema // assumptions in addition to the original with conservative (default) aliasing
16df6763abSAshutosh Nema // assumptions. The version of the loop making aggressive aliasing assumptions
17df6763abSAshutosh Nema // will have all the memory accesses marked as no-alias. These two versions of
18df6763abSAshutosh Nema // loop will be preceded by a memory runtime check. This runtime check consists
19df6763abSAshutosh Nema // of bound checks for all unique memory accessed in loop, and it ensures the
20df6763abSAshutosh Nema // lack of memory aliasing. The result of the runtime check determines which of
21df6763abSAshutosh Nema // the loop versions is executed: If the runtime check detects any memory
22df6763abSAshutosh Nema // aliasing, then the original loop is executed. Otherwise, the version with
23df6763abSAshutosh Nema // aggressive aliasing assumptions is used.
24df6763abSAshutosh Nema //
25df6763abSAshutosh Nema // Following are the top level steps:
26df6763abSAshutosh Nema //
27df6763abSAshutosh Nema // a) Perform LoopVersioningLICM's feasibility check.
28df6763abSAshutosh Nema // b) If loop is a candidate for versioning then create a memory bound check,
29df6763abSAshutosh Nema //    by considering all the memory accesses in loop body.
30df6763abSAshutosh Nema // c) Clone original loop and set all memory accesses as no-alias in new loop.
31df6763abSAshutosh Nema // d) Set original loop & versioned loop as a branch target of the runtime check
32df6763abSAshutosh Nema //    result.
33df6763abSAshutosh Nema //
34df6763abSAshutosh Nema // It transforms loop as shown below:
35df6763abSAshutosh Nema //
36df6763abSAshutosh Nema //                         +----------------+
37df6763abSAshutosh Nema //                         |Runtime Memcheck|
38df6763abSAshutosh Nema //                         +----------------+
39df6763abSAshutosh Nema //                                 |
40df6763abSAshutosh Nema //              +----------+----------------+----------+
41df6763abSAshutosh Nema //              |                                      |
42df6763abSAshutosh Nema //    +---------+----------+               +-----------+----------+
43df6763abSAshutosh Nema //    |Orig Loop Preheader |               |Cloned Loop Preheader |
44df6763abSAshutosh Nema //    +--------------------+               +----------------------+
45df6763abSAshutosh Nema //              |                                      |
46df6763abSAshutosh Nema //    +--------------------+               +----------------------+
47df6763abSAshutosh Nema //    |Orig Loop Body      |               |Cloned Loop Body      |
48df6763abSAshutosh Nema //    +--------------------+               +----------------------+
49df6763abSAshutosh Nema //              |                                      |
50df6763abSAshutosh Nema //    +--------------------+               +----------------------+
512260a3a0SAshutosh Nema //    |Orig Loop Exit Block|               |Cloned Loop Exit Block|
52df6763abSAshutosh Nema //    +--------------------+               +-----------+----------+
53df6763abSAshutosh Nema //              |                                      |
54df6763abSAshutosh Nema //              +----------+--------------+-----------+
55df6763abSAshutosh Nema //                                 |
56df6763abSAshutosh Nema //                           +-----+----+
57df6763abSAshutosh Nema //                           |Join Block|
58df6763abSAshutosh Nema //                           +----------+
59df6763abSAshutosh Nema //
60df6763abSAshutosh Nema //===----------------------------------------------------------------------===//
61df6763abSAshutosh Nema 
6265a36bbcSTaWeiTu #include "llvm/Transforms/Scalar/LoopVersioningLICM.h"
635adb96ccSEugene Zelenko #include "llvm/ADT/SmallVector.h"
645adb96ccSEugene Zelenko #include "llvm/ADT/StringRef.h"
65df6763abSAshutosh Nema #include "llvm/Analysis/AliasAnalysis.h"
66df6763abSAshutosh Nema #include "llvm/Analysis/AliasSetTracker.h"
67df6763abSAshutosh Nema #include "llvm/Analysis/GlobalsModRef.h"
68df6763abSAshutosh Nema #include "llvm/Analysis/LoopAccessAnalysis.h"
69df6763abSAshutosh Nema #include "llvm/Analysis/LoopInfo.h"
70df6763abSAshutosh Nema #include "llvm/Analysis/LoopPass.h"
71007b425bSAshutosh Nema #include "llvm/Analysis/OptimizationRemarkEmitter.h"
72df6763abSAshutosh Nema #include "llvm/Analysis/ScalarEvolution.h"
73df6763abSAshutosh Nema #include "llvm/IR/Dominators.h"
745adb96ccSEugene Zelenko #include "llvm/IR/Instruction.h"
755adb96ccSEugene Zelenko #include "llvm/IR/Instructions.h"
765adb96ccSEugene Zelenko #include "llvm/IR/LLVMContext.h"
77df6763abSAshutosh Nema #include "llvm/IR/MDBuilder.h"
785adb96ccSEugene Zelenko #include "llvm/IR/Metadata.h"
795adb96ccSEugene Zelenko #include "llvm/IR/Value.h"
8005da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
815adb96ccSEugene Zelenko #include "llvm/Pass.h"
825adb96ccSEugene Zelenko #include "llvm/Support/Casting.h"
835adb96ccSEugene Zelenko #include "llvm/Support/CommandLine.h"
84df6763abSAshutosh Nema #include "llvm/Support/Debug.h"
85df6763abSAshutosh Nema #include "llvm/Support/raw_ostream.h"
86df6763abSAshutosh Nema #include "llvm/Transforms/Scalar.h"
87a373d18eSDavid Blaikie #include "llvm/Transforms/Utils.h"
88df6763abSAshutosh Nema #include "llvm/Transforms/Utils/LoopUtils.h"
89df6763abSAshutosh Nema #include "llvm/Transforms/Utils/LoopVersioning.h"
905adb96ccSEugene Zelenko #include <cassert>
915adb96ccSEugene Zelenko #include <memory>
92df6763abSAshutosh Nema 
93df6763abSAshutosh Nema using namespace llvm;
94df6763abSAshutosh Nema 
955adb96ccSEugene Zelenko #define DEBUG_TYPE "loop-versioning-licm"
965adb96ccSEugene Zelenko 
975adb96ccSEugene Zelenko static const char *LICMVersioningMetaData = "llvm.loop.licm_versioning.disable";
985adb96ccSEugene Zelenko 
99df6763abSAshutosh Nema /// Threshold minimum allowed percentage for possible
100df6763abSAshutosh Nema /// invariant instructions in a loop.
101df6763abSAshutosh Nema static cl::opt<float>
1022260a3a0SAshutosh Nema     LVInvarThreshold("licm-versioning-invariant-threshold",
103df6763abSAshutosh Nema                      cl::desc("LoopVersioningLICM's minimum allowed percentage"
104df6763abSAshutosh Nema                               "of possible invariant instructions per loop"),
105df6763abSAshutosh Nema                      cl::init(25), cl::Hidden);
106df6763abSAshutosh Nema 
107df6763abSAshutosh Nema /// Threshold for maximum allowed loop nest/depth
108df6763abSAshutosh Nema static cl::opt<unsigned> LVLoopDepthThreshold(
1092260a3a0SAshutosh Nema     "licm-versioning-max-depth-threshold",
110df6763abSAshutosh Nema     cl::desc(
111df6763abSAshutosh Nema         "LoopVersioningLICM's threshold for maximum allowed loop nest/depth"),
112df6763abSAshutosh Nema     cl::init(2), cl::Hidden);
113df6763abSAshutosh Nema 
114df6763abSAshutosh Nema namespace {
1155adb96ccSEugene Zelenko 
11665a36bbcSTaWeiTu struct LoopVersioningLICMLegacyPass : public LoopPass {
117df6763abSAshutosh Nema   static char ID;
118df6763abSAshutosh Nema 
LoopVersioningLICMLegacyPass__anonbb6e37460111::LoopVersioningLICMLegacyPass11965a36bbcSTaWeiTu   LoopVersioningLICMLegacyPass() : LoopPass(ID) {
12065a36bbcSTaWeiTu     initializeLoopVersioningLICMLegacyPassPass(
12165a36bbcSTaWeiTu         *PassRegistry::getPassRegistry());
1225adb96ccSEugene Zelenko   }
1235adb96ccSEugene Zelenko 
124df6763abSAshutosh Nema   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
125df6763abSAshutosh Nema 
getPassName__anonbb6e37460111::LoopVersioningLICMLegacyPass12665a36bbcSTaWeiTu   StringRef getPassName() const override { return "Loop Versioning for LICM"; }
12765a36bbcSTaWeiTu 
getAnalysisUsage__anonbb6e37460111::LoopVersioningLICMLegacyPass128df6763abSAshutosh Nema   void getAnalysisUsage(AnalysisUsage &AU) const override {
129df6763abSAshutosh Nema     AU.setPreservesCFG();
130df6763abSAshutosh Nema     AU.addRequired<AAResultsWrapperPass>();
131df6763abSAshutosh Nema     AU.addRequired<DominatorTreeWrapperPass>();
132df6763abSAshutosh Nema     AU.addRequiredID(LCSSAID);
1337853c1ddSXinliang David Li     AU.addRequired<LoopAccessLegacyAnalysis>();
134df6763abSAshutosh Nema     AU.addRequired<LoopInfoWrapperPass>();
135df6763abSAshutosh Nema     AU.addRequiredID(LoopSimplifyID);
136df6763abSAshutosh Nema     AU.addRequired<ScalarEvolutionWrapperPass>();
137df6763abSAshutosh Nema     AU.addPreserved<AAResultsWrapperPass>();
138df6763abSAshutosh Nema     AU.addPreserved<GlobalsAAWrapperPass>();
139007b425bSAshutosh Nema     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
140df6763abSAshutosh Nema   }
14165a36bbcSTaWeiTu };
142df6763abSAshutosh Nema 
14365a36bbcSTaWeiTu struct LoopVersioningLICM {
14465a36bbcSTaWeiTu   // We don't explicitly pass in LoopAccessInfo to the constructor since the
14565a36bbcSTaWeiTu   // loop versioning might return early due to instructions that are not safe
14665a36bbcSTaWeiTu   // for versioning. By passing the proxy instead the construction of
14765a36bbcSTaWeiTu   // LoopAccessInfo will take place only when it's necessary.
LoopVersioningLICM__anonbb6e37460111::LoopVersioningLICM14865a36bbcSTaWeiTu   LoopVersioningLICM(AliasAnalysis *AA, ScalarEvolution *SE,
14965a36bbcSTaWeiTu                      OptimizationRemarkEmitter *ORE,
15065a36bbcSTaWeiTu                      function_ref<const LoopAccessInfo &(Loop *)> GetLAI)
15165a36bbcSTaWeiTu       : AA(AA), SE(SE), GetLAI(GetLAI),
15265a36bbcSTaWeiTu         LoopDepthThreshold(LVLoopDepthThreshold),
15365a36bbcSTaWeiTu         InvariantThreshold(LVInvarThreshold), ORE(ORE) {}
15465a36bbcSTaWeiTu 
15565a36bbcSTaWeiTu   bool runOnLoop(Loop *L, LoopInfo *LI, DominatorTree *DT);
156df6763abSAshutosh Nema 
reset__anonbb6e37460111::LoopVersioningLICM15748fd87e4SEvgeny Astigeevich   void reset() {
15848fd87e4SEvgeny Astigeevich     AA = nullptr;
15948fd87e4SEvgeny Astigeevich     SE = nullptr;
16048fd87e4SEvgeny Astigeevich     CurLoop = nullptr;
16148fd87e4SEvgeny Astigeevich     LoadAndStoreCounter = 0;
16248fd87e4SEvgeny Astigeevich     InvariantCounter = 0;
16348fd87e4SEvgeny Astigeevich     IsReadOnlyLoop = true;
164007b425bSAshutosh Nema     ORE = nullptr;
16548fd87e4SEvgeny Astigeevich     CurAST.reset();
16648fd87e4SEvgeny Astigeevich   }
16748fd87e4SEvgeny Astigeevich 
16848fd87e4SEvgeny Astigeevich   class AutoResetter {
16948fd87e4SEvgeny Astigeevich   public:
AutoResetter(LoopVersioningLICM & LVLICM)17048fd87e4SEvgeny Astigeevich     AutoResetter(LoopVersioningLICM &LVLICM) : LVLICM(LVLICM) {}
~AutoResetter()17148fd87e4SEvgeny Astigeevich     ~AutoResetter() { LVLICM.reset(); }
17248fd87e4SEvgeny Astigeevich 
17348fd87e4SEvgeny Astigeevich   private:
17448fd87e4SEvgeny Astigeevich     LoopVersioningLICM &LVLICM;
17548fd87e4SEvgeny Astigeevich   };
17648fd87e4SEvgeny Astigeevich 
17748fd87e4SEvgeny Astigeevich private:
1785adb96ccSEugene Zelenko   // Current AliasAnalysis information
1795adb96ccSEugene Zelenko   AliasAnalysis *AA = nullptr;
180df6763abSAshutosh Nema 
1815adb96ccSEugene Zelenko   // Current ScalarEvolution
1825adb96ccSEugene Zelenko   ScalarEvolution *SE = nullptr;
183df6763abSAshutosh Nema 
1845adb96ccSEugene Zelenko   // Current Loop's LoopAccessInfo
1855adb96ccSEugene Zelenko   const LoopAccessInfo *LAI = nullptr;
1865adb96ccSEugene Zelenko 
18765a36bbcSTaWeiTu   // Proxy for retrieving LoopAccessInfo.
18865a36bbcSTaWeiTu   function_ref<const LoopAccessInfo &(Loop *)> GetLAI;
18965a36bbcSTaWeiTu 
1905adb96ccSEugene Zelenko   // The current loop we are working on.
1915adb96ccSEugene Zelenko   Loop *CurLoop = nullptr;
1925adb96ccSEugene Zelenko 
1935adb96ccSEugene Zelenko   // AliasSet information for the current loop.
1945adb96ccSEugene Zelenko   std::unique_ptr<AliasSetTracker> CurAST;
1955adb96ccSEugene Zelenko 
1965adb96ccSEugene Zelenko   // Maximum loop nest threshold
1975adb96ccSEugene Zelenko   unsigned LoopDepthThreshold;
1985adb96ccSEugene Zelenko 
1995adb96ccSEugene Zelenko   // Minimum invariant threshold
2005adb96ccSEugene Zelenko   float InvariantThreshold;
2015adb96ccSEugene Zelenko 
2025adb96ccSEugene Zelenko   // Counter to track num of load & store
2035adb96ccSEugene Zelenko   unsigned LoadAndStoreCounter = 0;
2045adb96ccSEugene Zelenko 
2055adb96ccSEugene Zelenko   // Counter to track num of invariant
2065adb96ccSEugene Zelenko   unsigned InvariantCounter = 0;
2075adb96ccSEugene Zelenko 
2085adb96ccSEugene Zelenko   // Read only loop marker.
2095adb96ccSEugene Zelenko   bool IsReadOnlyLoop = true;
210df6763abSAshutosh Nema 
211007b425bSAshutosh Nema   // OptimizationRemarkEmitter
212007b425bSAshutosh Nema   OptimizationRemarkEmitter *ORE;
213007b425bSAshutosh Nema 
214df6763abSAshutosh Nema   bool isLegalForVersioning();
215df6763abSAshutosh Nema   bool legalLoopStructure();
216df6763abSAshutosh Nema   bool legalLoopInstructions();
217df6763abSAshutosh Nema   bool legalLoopMemoryAccesses();
218df6763abSAshutosh Nema   bool isLoopAlreadyVisited();
2195adb96ccSEugene Zelenko   void setNoAliasToLoop(Loop *VerLoop);
2205adb96ccSEugene Zelenko   bool instructionSafeForVersioning(Instruction *I);
221df6763abSAshutosh Nema };
2225adb96ccSEugene Zelenko 
2235adb96ccSEugene Zelenko } // end anonymous namespace
224df6763abSAshutosh Nema 
2255f8f34e4SAdrian Prantl /// Check loop structure and confirms it's good for LoopVersioningLICM.
legalLoopStructure()226df6763abSAshutosh Nema bool LoopVersioningLICM::legalLoopStructure() {
2272e03213fSFlorian Hahn   // Loop must be in loop simplify form.
2282e03213fSFlorian Hahn   if (!CurLoop->isLoopSimplifyForm()) {
229d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    loop is not in loop-simplify form.\n");
230df6763abSAshutosh Nema     return false;
231df6763abSAshutosh Nema   }
232df6763abSAshutosh Nema   // Loop should be innermost loop, if not return false.
2335adb96ccSEugene Zelenko   if (!CurLoop->getSubLoops().empty()) {
234d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    loop is not innermost\n");
235df6763abSAshutosh Nema     return false;
236df6763abSAshutosh Nema   }
237df6763abSAshutosh Nema   // Loop should have a single backedge, if not return false.
238df6763abSAshutosh Nema   if (CurLoop->getNumBackEdges() != 1) {
239d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    loop has multiple backedges\n");
240df6763abSAshutosh Nema     return false;
241df6763abSAshutosh Nema   }
242df6763abSAshutosh Nema   // Loop must have a single exiting block, if not return false.
243df6763abSAshutosh Nema   if (!CurLoop->getExitingBlock()) {
244d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    loop has multiple exiting block\n");
245df6763abSAshutosh Nema     return false;
246df6763abSAshutosh Nema   }
247df6763abSAshutosh Nema   // We only handle bottom-tested loop, i.e. loop in which the condition is
248df6763abSAshutosh Nema   // checked at the end of each iteration. With that we can assume that all
249df6763abSAshutosh Nema   // instructions in the loop are executed the same number of times.
250df6763abSAshutosh Nema   if (CurLoop->getExitingBlock() != CurLoop->getLoopLatch()) {
251d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    loop is not bottom tested\n");
252df6763abSAshutosh Nema     return false;
253df6763abSAshutosh Nema   }
254df6763abSAshutosh Nema   // Parallel loops must not have aliasing loop-invariant memory accesses.
255df6763abSAshutosh Nema   // Hence we don't need to version anything in this case.
256df6763abSAshutosh Nema   if (CurLoop->isAnnotatedParallel()) {
257d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    Parallel loop is not worth versioning\n");
258df6763abSAshutosh Nema     return false;
259df6763abSAshutosh Nema   }
260df6763abSAshutosh Nema   // Loop depth more then LoopDepthThreshold are not allowed
261df6763abSAshutosh Nema   if (CurLoop->getLoopDepth() > LoopDepthThreshold) {
262d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    loop depth is more then threshold\n");
263df6763abSAshutosh Nema     return false;
264df6763abSAshutosh Nema   }
265df6763abSAshutosh Nema   // We need to be able to compute the loop trip count in order
266df6763abSAshutosh Nema   // to generate the bound checks.
267df6763abSAshutosh Nema   const SCEV *ExitCount = SE->getBackedgeTakenCount(CurLoop);
268*10ddb927SPhilip Reames   if (isa<SCEVCouldNotCompute>(ExitCount)) {
269d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    loop does not has trip count\n");
270df6763abSAshutosh Nema     return false;
271df6763abSAshutosh Nema   }
272df6763abSAshutosh Nema   return true;
273df6763abSAshutosh Nema }
274df6763abSAshutosh Nema 
2755f8f34e4SAdrian Prantl /// Check memory accesses in loop and confirms it's good for
276df6763abSAshutosh Nema /// LoopVersioningLICM.
legalLoopMemoryAccesses()277df6763abSAshutosh Nema bool LoopVersioningLICM::legalLoopMemoryAccesses() {
278df6763abSAshutosh Nema   bool HasMayAlias = false;
279df6763abSAshutosh Nema   bool TypeSafety = false;
280df6763abSAshutosh Nema   bool HasMod = false;
281df6763abSAshutosh Nema   // Memory check:
282df6763abSAshutosh Nema   // Transform phase will generate a versioned loop and also a runtime check to
283df6763abSAshutosh Nema   // ensure the pointers are independent and they don’t alias.
284df6763abSAshutosh Nema   // In version variant of loop, alias meta data asserts that all access are
285df6763abSAshutosh Nema   // mutually independent.
286df6763abSAshutosh Nema   //
287df6763abSAshutosh Nema   // Pointers aliasing in alias domain are avoided because with multiple
288df6763abSAshutosh Nema   // aliasing domains we may not be able to hoist potential loop invariant
289df6763abSAshutosh Nema   // access out of the loop.
290df6763abSAshutosh Nema   //
291df6763abSAshutosh Nema   // Iterate over alias tracker sets, and confirm AliasSets doesn't have any
292df6763abSAshutosh Nema   // must alias set.
293df6763abSAshutosh Nema   for (const auto &I : *CurAST) {
294df6763abSAshutosh Nema     const AliasSet &AS = I;
295df6763abSAshutosh Nema     // Skip Forward Alias Sets, as this should be ignored as part of
296df6763abSAshutosh Nema     // the AliasSetTracker object.
297df6763abSAshutosh Nema     if (AS.isForwardingAliasSet())
298df6763abSAshutosh Nema       continue;
299df6763abSAshutosh Nema     // With MustAlias its not worth adding runtime bound check.
300df6763abSAshutosh Nema     if (AS.isMustAlias())
301df6763abSAshutosh Nema       return false;
302df6763abSAshutosh Nema     Value *SomePtr = AS.begin()->getValue();
303df6763abSAshutosh Nema     bool TypeCheck = true;
304df6763abSAshutosh Nema     // Check for Mod & MayAlias
305df6763abSAshutosh Nema     HasMayAlias |= AS.isMayAlias();
306df6763abSAshutosh Nema     HasMod |= AS.isMod();
307df6763abSAshutosh Nema     for (const auto &A : AS) {
308df6763abSAshutosh Nema       Value *Ptr = A.getValue();
309df6763abSAshutosh Nema       // Alias tracker should have pointers of same data type.
310df6763abSAshutosh Nema       TypeCheck = (TypeCheck && (SomePtr->getType() == Ptr->getType()));
311df6763abSAshutosh Nema     }
312df6763abSAshutosh Nema     // At least one alias tracker should have pointers of same data type.
313df6763abSAshutosh Nema     TypeSafety |= TypeCheck;
314df6763abSAshutosh Nema   }
315df6763abSAshutosh Nema   // Ensure types should be of same type.
316df6763abSAshutosh Nema   if (!TypeSafety) {
317d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    Alias tracker type safety failed!\n");
318df6763abSAshutosh Nema     return false;
319df6763abSAshutosh Nema   }
320df6763abSAshutosh Nema   // Ensure loop body shouldn't be read only.
321df6763abSAshutosh Nema   if (!HasMod) {
322d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    No memory modified in loop body\n");
323df6763abSAshutosh Nema     return false;
324df6763abSAshutosh Nema   }
325df6763abSAshutosh Nema   // Make sure alias set has may alias case.
326df6763abSAshutosh Nema   // If there no alias memory ambiguity, return false.
327df6763abSAshutosh Nema   if (!HasMayAlias) {
328d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    No ambiguity in memory access.\n");
329df6763abSAshutosh Nema     return false;
330df6763abSAshutosh Nema   }
331df6763abSAshutosh Nema   return true;
332df6763abSAshutosh Nema }
333df6763abSAshutosh Nema 
3345f8f34e4SAdrian Prantl /// Check loop instructions safe for Loop versioning.
335df6763abSAshutosh Nema /// It returns true if it's safe else returns false.
336df6763abSAshutosh Nema /// Consider following:
337df6763abSAshutosh Nema /// 1) Check all load store in loop body are non atomic & non volatile.
338df6763abSAshutosh Nema /// 2) Check function call safety, by ensuring its not accessing memory.
339df6763abSAshutosh Nema /// 3) Loop body shouldn't have any may throw instruction.
34079b3ea70SMatt Arsenault /// 4) Loop body shouldn't have any convergent or noduplicate instructions.
instructionSafeForVersioning(Instruction * I)341df6763abSAshutosh Nema bool LoopVersioningLICM::instructionSafeForVersioning(Instruction *I) {
342df6763abSAshutosh Nema   assert(I != nullptr && "Null instruction found!");
343df6763abSAshutosh Nema   // Check function call safety
34479b3ea70SMatt Arsenault   if (auto *Call = dyn_cast<CallBase>(I)) {
34579b3ea70SMatt Arsenault     if (Call->isConvergent() || Call->cannotDuplicate()) {
34679b3ea70SMatt Arsenault       LLVM_DEBUG(dbgs() << "    Convergent call site found.\n");
34779b3ea70SMatt Arsenault       return false;
34879b3ea70SMatt Arsenault     }
34979b3ea70SMatt Arsenault 
350363ac683SChandler Carruth     if (!AA->doesNotAccessMemory(Call)) {
351d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "    Unsafe call site found.\n");
352df6763abSAshutosh Nema       return false;
353df6763abSAshutosh Nema     }
35479b3ea70SMatt Arsenault   }
35579b3ea70SMatt Arsenault 
356df6763abSAshutosh Nema   // Avoid loops with possiblity of throw
357df6763abSAshutosh Nema   if (I->mayThrow()) {
358d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    May throw instruction found in loop body\n");
359df6763abSAshutosh Nema     return false;
360df6763abSAshutosh Nema   }
361df6763abSAshutosh Nema   // If current instruction is load instructions
362df6763abSAshutosh Nema   // make sure it's a simple load (non atomic & non volatile)
363df6763abSAshutosh Nema   if (I->mayReadFromMemory()) {
364df6763abSAshutosh Nema     LoadInst *Ld = dyn_cast<LoadInst>(I);
365df6763abSAshutosh Nema     if (!Ld || !Ld->isSimple()) {
366d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "    Found a non-simple load.\n");
367df6763abSAshutosh Nema       return false;
368df6763abSAshutosh Nema     }
369df6763abSAshutosh Nema     LoadAndStoreCounter++;
370df6763abSAshutosh Nema     Value *Ptr = Ld->getPointerOperand();
371df6763abSAshutosh Nema     // Check loop invariant.
372df6763abSAshutosh Nema     if (SE->isLoopInvariant(SE->getSCEV(Ptr), CurLoop))
373df6763abSAshutosh Nema       InvariantCounter++;
374df6763abSAshutosh Nema   }
375df6763abSAshutosh Nema   // If current instruction is store instruction
376df6763abSAshutosh Nema   // make sure it's a simple store (non atomic & non volatile)
377df6763abSAshutosh Nema   else if (I->mayWriteToMemory()) {
378df6763abSAshutosh Nema     StoreInst *St = dyn_cast<StoreInst>(I);
379df6763abSAshutosh Nema     if (!St || !St->isSimple()) {
380d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "    Found a non-simple store.\n");
381df6763abSAshutosh Nema       return false;
382df6763abSAshutosh Nema     }
383df6763abSAshutosh Nema     LoadAndStoreCounter++;
384df6763abSAshutosh Nema     Value *Ptr = St->getPointerOperand();
385df6763abSAshutosh Nema     // Check loop invariant.
386df6763abSAshutosh Nema     if (SE->isLoopInvariant(SE->getSCEV(Ptr), CurLoop))
387df6763abSAshutosh Nema       InvariantCounter++;
388df6763abSAshutosh Nema 
389df6763abSAshutosh Nema     IsReadOnlyLoop = false;
390df6763abSAshutosh Nema   }
391df6763abSAshutosh Nema   return true;
392df6763abSAshutosh Nema }
393df6763abSAshutosh Nema 
3945f8f34e4SAdrian Prantl /// Check loop instructions and confirms it's good for
395df6763abSAshutosh Nema /// LoopVersioningLICM.
legalLoopInstructions()396df6763abSAshutosh Nema bool LoopVersioningLICM::legalLoopInstructions() {
397df6763abSAshutosh Nema   // Resetting counters.
398df6763abSAshutosh Nema   LoadAndStoreCounter = 0;
399df6763abSAshutosh Nema   InvariantCounter = 0;
400df6763abSAshutosh Nema   IsReadOnlyLoop = true;
401007b425bSAshutosh Nema   using namespace ore;
402df6763abSAshutosh Nema   // Iterate over loop blocks and instructions of each block and check
403df6763abSAshutosh Nema   // instruction safety.
404df6763abSAshutosh Nema   for (auto *Block : CurLoop->getBlocks())
405df6763abSAshutosh Nema     for (auto &Inst : *Block) {
4062260a3a0SAshutosh Nema       // If instruction is unsafe just return false.
407007b425bSAshutosh Nema       if (!instructionSafeForVersioning(&Inst)) {
408007b425bSAshutosh Nema         ORE->emit([&]() {
409007b425bSAshutosh Nema           return OptimizationRemarkMissed(DEBUG_TYPE, "IllegalLoopInst", &Inst)
410007b425bSAshutosh Nema                  << " Unsafe Loop Instruction";
411007b425bSAshutosh Nema         });
412df6763abSAshutosh Nema         return false;
413df6763abSAshutosh Nema       }
414007b425bSAshutosh Nema     }
41565a36bbcSTaWeiTu   // Get LoopAccessInfo from current loop via the proxy.
41665a36bbcSTaWeiTu   LAI = &GetLAI(CurLoop);
417df6763abSAshutosh Nema   // Check LoopAccessInfo for need of runtime check.
418df6763abSAshutosh Nema   if (LAI->getRuntimePointerChecking()->getChecks().empty()) {
419d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    LAA: Runtime check not found !!\n");
420df6763abSAshutosh Nema     return false;
421df6763abSAshutosh Nema   }
422df6763abSAshutosh Nema   // Number of runtime-checks should be less then RuntimeMemoryCheckThreshold
423df6763abSAshutosh Nema   if (LAI->getNumRuntimePointerChecks() >
424df6763abSAshutosh Nema       VectorizerParams::RuntimeMemoryCheckThreshold) {
425d34e60caSNicola Zaghen     LLVM_DEBUG(
426d34e60caSNicola Zaghen         dbgs() << "    LAA: Runtime checks are more than threshold !!\n");
427007b425bSAshutosh Nema     ORE->emit([&]() {
428007b425bSAshutosh Nema       return OptimizationRemarkMissed(DEBUG_TYPE, "RuntimeCheck",
429007b425bSAshutosh Nema                                       CurLoop->getStartLoc(),
430007b425bSAshutosh Nema                                       CurLoop->getHeader())
431007b425bSAshutosh Nema              << "Number of runtime checks "
432007b425bSAshutosh Nema              << NV("RuntimeChecks", LAI->getNumRuntimePointerChecks())
433007b425bSAshutosh Nema              << " exceeds threshold "
434007b425bSAshutosh Nema              << NV("Threshold", VectorizerParams::RuntimeMemoryCheckThreshold);
435007b425bSAshutosh Nema     });
436df6763abSAshutosh Nema     return false;
437df6763abSAshutosh Nema   }
438df6763abSAshutosh Nema   // Loop should have at least one invariant load or store instruction.
439df6763abSAshutosh Nema   if (!InvariantCounter) {
440d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    Invariant not found !!\n");
441df6763abSAshutosh Nema     return false;
442df6763abSAshutosh Nema   }
443df6763abSAshutosh Nema   // Read only loop not allowed.
444df6763abSAshutosh Nema   if (IsReadOnlyLoop) {
445d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    Found a read-only loop!\n");
446df6763abSAshutosh Nema     return false;
447df6763abSAshutosh Nema   }
448df6763abSAshutosh Nema   // Profitablity check:
449df6763abSAshutosh Nema   // Check invariant threshold, should be in limit.
450df6763abSAshutosh Nema   if (InvariantCounter * 100 < InvariantThreshold * LoadAndStoreCounter) {
451d34e60caSNicola Zaghen     LLVM_DEBUG(
452d34e60caSNicola Zaghen         dbgs()
453df6763abSAshutosh Nema         << "    Invariant load & store are less then defined threshold\n");
454d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    Invariant loads & stores: "
455d34e60caSNicola Zaghen                       << ((InvariantCounter * 100) / LoadAndStoreCounter)
456d34e60caSNicola Zaghen                       << "%\n");
457d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "    Invariant loads & store threshold: "
458df6763abSAshutosh Nema                       << InvariantThreshold << "%\n");
459007b425bSAshutosh Nema     ORE->emit([&]() {
460007b425bSAshutosh Nema       return OptimizationRemarkMissed(DEBUG_TYPE, "InvariantThreshold",
461007b425bSAshutosh Nema                                       CurLoop->getStartLoc(),
462007b425bSAshutosh Nema                                       CurLoop->getHeader())
463007b425bSAshutosh Nema              << "Invariant load & store "
464007b425bSAshutosh Nema              << NV("LoadAndStoreCounter",
465007b425bSAshutosh Nema                    ((InvariantCounter * 100) / LoadAndStoreCounter))
466007b425bSAshutosh Nema              << " are less then defined threshold "
467007b425bSAshutosh Nema              << NV("Threshold", InvariantThreshold);
468007b425bSAshutosh Nema     });
469df6763abSAshutosh Nema     return false;
470df6763abSAshutosh Nema   }
471df6763abSAshutosh Nema   return true;
472df6763abSAshutosh Nema }
473df6763abSAshutosh Nema 
4745f8f34e4SAdrian Prantl /// It checks loop is already visited or not.
4752260a3a0SAshutosh Nema /// check loop meta data, if loop revisited return true
476df6763abSAshutosh Nema /// else false.
isLoopAlreadyVisited()477df6763abSAshutosh Nema bool LoopVersioningLICM::isLoopAlreadyVisited() {
478df6763abSAshutosh Nema   // Check LoopVersioningLICM metadata into loop
479f787826bSAdam Nemet   if (findStringMetadataForLoop(CurLoop, LICMVersioningMetaData)) {
480df6763abSAshutosh Nema     return true;
481df6763abSAshutosh Nema   }
482df6763abSAshutosh Nema   return false;
483df6763abSAshutosh Nema }
484df6763abSAshutosh Nema 
4855f8f34e4SAdrian Prantl /// Checks legality for LoopVersioningLICM by considering following:
486df6763abSAshutosh Nema /// a) loop structure legality   b) loop instruction legality
487df6763abSAshutosh Nema /// c) loop memory access legality.
488df6763abSAshutosh Nema /// Return true if legal else returns false.
isLegalForVersioning()489df6763abSAshutosh Nema bool LoopVersioningLICM::isLegalForVersioning() {
490007b425bSAshutosh Nema   using namespace ore;
491d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Loop: " << *CurLoop);
492df6763abSAshutosh Nema   // Make sure not re-visiting same loop again.
493df6763abSAshutosh Nema   if (isLoopAlreadyVisited()) {
494d34e60caSNicola Zaghen     LLVM_DEBUG(
495df6763abSAshutosh Nema         dbgs() << "    Revisiting loop in LoopVersioningLICM not allowed.\n\n");
496df6763abSAshutosh Nema     return false;
497df6763abSAshutosh Nema   }
498df6763abSAshutosh Nema   // Check loop structure leagality.
499df6763abSAshutosh Nema   if (!legalLoopStructure()) {
500d34e60caSNicola Zaghen     LLVM_DEBUG(
501df6763abSAshutosh Nema         dbgs() << "    Loop structure not suitable for LoopVersioningLICM\n\n");
502007b425bSAshutosh Nema     ORE->emit([&]() {
503007b425bSAshutosh Nema       return OptimizationRemarkMissed(DEBUG_TYPE, "IllegalLoopStruct",
504007b425bSAshutosh Nema                                       CurLoop->getStartLoc(),
505007b425bSAshutosh Nema                                       CurLoop->getHeader())
506007b425bSAshutosh Nema              << " Unsafe Loop structure";
507007b425bSAshutosh Nema     });
508df6763abSAshutosh Nema     return false;
509df6763abSAshutosh Nema   }
510df6763abSAshutosh Nema   // Check loop instruction leagality.
511df6763abSAshutosh Nema   if (!legalLoopInstructions()) {
512d34e60caSNicola Zaghen     LLVM_DEBUG(
513d34e60caSNicola Zaghen         dbgs()
514df6763abSAshutosh Nema         << "    Loop instructions not suitable for LoopVersioningLICM\n\n");
515df6763abSAshutosh Nema     return false;
516df6763abSAshutosh Nema   }
517df6763abSAshutosh Nema   // Check loop memory access leagality.
518df6763abSAshutosh Nema   if (!legalLoopMemoryAccesses()) {
519d34e60caSNicola Zaghen     LLVM_DEBUG(
520d34e60caSNicola Zaghen         dbgs()
521df6763abSAshutosh Nema         << "    Loop memory access not suitable for LoopVersioningLICM\n\n");
522007b425bSAshutosh Nema     ORE->emit([&]() {
523007b425bSAshutosh Nema       return OptimizationRemarkMissed(DEBUG_TYPE, "IllegalLoopMemoryAccess",
524007b425bSAshutosh Nema                                       CurLoop->getStartLoc(),
525007b425bSAshutosh Nema                                       CurLoop->getHeader())
526007b425bSAshutosh Nema              << " Unsafe Loop memory access";
527007b425bSAshutosh Nema     });
528df6763abSAshutosh Nema     return false;
529df6763abSAshutosh Nema   }
530df6763abSAshutosh Nema   // Loop versioning is feasible, return true.
531d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "    Loop Versioning found to be beneficial\n\n");
532007b425bSAshutosh Nema   ORE->emit([&]() {
533007b425bSAshutosh Nema     return OptimizationRemark(DEBUG_TYPE, "IsLegalForVersioning",
534007b425bSAshutosh Nema                               CurLoop->getStartLoc(), CurLoop->getHeader())
535007b425bSAshutosh Nema            << " Versioned loop for LICM."
536007b425bSAshutosh Nema            << " Number of runtime checks we had to insert "
537007b425bSAshutosh Nema            << NV("RuntimeChecks", LAI->getNumRuntimePointerChecks());
538007b425bSAshutosh Nema   });
539df6763abSAshutosh Nema   return true;
540df6763abSAshutosh Nema }
541df6763abSAshutosh Nema 
5425f8f34e4SAdrian Prantl /// Update loop with aggressive aliasing assumptions.
543df6763abSAshutosh Nema /// It marks no-alias to any pairs of memory operations by assuming
544df6763abSAshutosh Nema /// loop should not have any must-alias memory accesses pairs.
545df6763abSAshutosh Nema /// During LoopVersioningLICM legality we ignore loops having must
546df6763abSAshutosh Nema /// aliasing memory accesses.
setNoAliasToLoop(Loop * VerLoop)547df6763abSAshutosh Nema void LoopVersioningLICM::setNoAliasToLoop(Loop *VerLoop) {
548df6763abSAshutosh Nema   // Get latch terminator instruction.
549df6763abSAshutosh Nema   Instruction *I = VerLoop->getLoopLatch()->getTerminator();
550df6763abSAshutosh Nema   // Create alias scope domain.
551df6763abSAshutosh Nema   MDBuilder MDB(I->getContext());
552df6763abSAshutosh Nema   MDNode *NewDomain = MDB.createAnonymousAliasScopeDomain("LVDomain");
553df6763abSAshutosh Nema   StringRef Name = "LVAliasScope";
554df6763abSAshutosh Nema   MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
5556713332fSNikita Popov   SmallVector<Metadata *, 4> Scopes{NewScope}, NoAliases{NewScope};
556df6763abSAshutosh Nema   // Iterate over each instruction of loop.
557df6763abSAshutosh Nema   // set no-alias for all load & store instructions.
558df6763abSAshutosh Nema   for (auto *Block : CurLoop->getBlocks()) {
559df6763abSAshutosh Nema     for (auto &Inst : *Block) {
560df6763abSAshutosh Nema       // Only interested in instruction that may modify or read memory.
561df6763abSAshutosh Nema       if (!Inst.mayReadFromMemory() && !Inst.mayWriteToMemory())
562df6763abSAshutosh Nema         continue;
563df6763abSAshutosh Nema       // Set no-alias for current instruction.
564df6763abSAshutosh Nema       Inst.setMetadata(
565df6763abSAshutosh Nema           LLVMContext::MD_noalias,
566df6763abSAshutosh Nema           MDNode::concatenate(Inst.getMetadata(LLVMContext::MD_noalias),
567df6763abSAshutosh Nema                               MDNode::get(Inst.getContext(), NoAliases)));
568df6763abSAshutosh Nema       // set alias-scope for current instruction.
569df6763abSAshutosh Nema       Inst.setMetadata(
570df6763abSAshutosh Nema           LLVMContext::MD_alias_scope,
571df6763abSAshutosh Nema           MDNode::concatenate(Inst.getMetadata(LLVMContext::MD_alias_scope),
572df6763abSAshutosh Nema                               MDNode::get(Inst.getContext(), Scopes)));
573df6763abSAshutosh Nema     }
574df6763abSAshutosh Nema   }
575df6763abSAshutosh Nema }
576df6763abSAshutosh Nema 
runOnLoop(Loop * L,LPPassManager & LPM)57765a36bbcSTaWeiTu bool LoopVersioningLICMLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
57865a36bbcSTaWeiTu   if (skipLoop(L))
57965a36bbcSTaWeiTu     return false;
58065a36bbcSTaWeiTu 
58165a36bbcSTaWeiTu   AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
58265a36bbcSTaWeiTu   ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
58365a36bbcSTaWeiTu   OptimizationRemarkEmitter *ORE =
58465a36bbcSTaWeiTu       &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
58565a36bbcSTaWeiTu   LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
58665a36bbcSTaWeiTu   DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
58765a36bbcSTaWeiTu 
58865a36bbcSTaWeiTu   auto GetLAI = [&](Loop *L) -> const LoopAccessInfo & {
58965a36bbcSTaWeiTu     return getAnalysis<LoopAccessLegacyAnalysis>().getInfo(L);
59065a36bbcSTaWeiTu   };
59165a36bbcSTaWeiTu 
59265a36bbcSTaWeiTu   return LoopVersioningLICM(AA, SE, ORE, GetLAI).runOnLoop(L, LI, DT);
59365a36bbcSTaWeiTu }
59465a36bbcSTaWeiTu 
runOnLoop(Loop * L,LoopInfo * LI,DominatorTree * DT)59565a36bbcSTaWeiTu bool LoopVersioningLICM::runOnLoop(Loop *L, LoopInfo *LI, DominatorTree *DT) {
59648fd87e4SEvgeny Astigeevich   // This will automatically release all resources hold by the current
59748fd87e4SEvgeny Astigeevich   // LoopVersioningLICM object.
59848fd87e4SEvgeny Astigeevich   AutoResetter Resetter(*this);
59948fd87e4SEvgeny Astigeevich 
60072448525SMichael Kruse   // Do not do the transformation if disabled by metadata.
60172448525SMichael Kruse   if (hasLICMVersioningTransformation(L) & TM_Disable)
60272448525SMichael Kruse     return false;
60372448525SMichael Kruse 
604df6763abSAshutosh Nema   // Set Current Loop
605df6763abSAshutosh Nema   CurLoop = L;
60648fd87e4SEvgeny Astigeevich   CurAST.reset(new AliasSetTracker(*AA));
607df6763abSAshutosh Nema 
608df6763abSAshutosh Nema   // Loop over the body of this loop, construct AST.
609df6763abSAshutosh Nema   for (auto *Block : L->getBlocks()) {
610df6763abSAshutosh Nema     if (LI->getLoopFor(Block) == L) // Ignore blocks in subloop.
611df6763abSAshutosh Nema       CurAST->add(*Block);          // Incorporate the specified basic block
612df6763abSAshutosh Nema   }
61348fd87e4SEvgeny Astigeevich 
61448fd87e4SEvgeny Astigeevich   bool Changed = false;
61548fd87e4SEvgeny Astigeevich 
616df6763abSAshutosh Nema   // Check feasiblity of LoopVersioningLICM.
617df6763abSAshutosh Nema   // If versioning found to be feasible and beneficial then proceed
618df6763abSAshutosh Nema   // else simply return, by cleaning up memory.
619df6763abSAshutosh Nema   if (isLegalForVersioning()) {
620df6763abSAshutosh Nema     // Do loop versioning.
621df6763abSAshutosh Nema     // Create memcheck for memory accessed inside loop.
622df6763abSAshutosh Nema     // Clone original loop, and set blocks properly.
62389c01242SFlorian Hahn     LoopVersioning LVer(*LAI, LAI->getRuntimePointerChecking()->getChecks(),
62489c01242SFlorian Hahn                         CurLoop, LI, DT, SE);
625df6763abSAshutosh Nema     LVer.versionLoop();
626df6763abSAshutosh Nema     // Set Loop Versioning metaData for original loop.
6272260a3a0SAshutosh Nema     addStringMetadataToLoop(LVer.getNonVersionedLoop(), LICMVersioningMetaData);
628df6763abSAshutosh Nema     // Set Loop Versioning metaData for version loop.
6292260a3a0SAshutosh Nema     addStringMetadataToLoop(LVer.getVersionedLoop(), LICMVersioningMetaData);
630df6763abSAshutosh Nema     // Set "llvm.mem.parallel_loop_access" metaData to versioned loop.
631978ba615SMichael Kruse     // FIXME: "llvm.mem.parallel_loop_access" annotates memory access
632978ba615SMichael Kruse     // instructions, not loops.
633df6763abSAshutosh Nema     addStringMetadataToLoop(LVer.getVersionedLoop(),
634df6763abSAshutosh Nema                             "llvm.mem.parallel_loop_access");
635df6763abSAshutosh Nema     // Update version loop with aggressive aliasing assumption.
636df6763abSAshutosh Nema     setNoAliasToLoop(LVer.getVersionedLoop());
637df6763abSAshutosh Nema     Changed = true;
638df6763abSAshutosh Nema   }
639df6763abSAshutosh Nema   return Changed;
640df6763abSAshutosh Nema }
641df6763abSAshutosh Nema 
64265a36bbcSTaWeiTu char LoopVersioningLICMLegacyPass::ID = 0;
6435adb96ccSEugene Zelenko 
64465a36bbcSTaWeiTu INITIALIZE_PASS_BEGIN(LoopVersioningLICMLegacyPass, "loop-versioning-licm",
645df6763abSAshutosh Nema                       "Loop Versioning For LICM", false, false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)646df6763abSAshutosh Nema INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
647df6763abSAshutosh Nema INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
648df6763abSAshutosh Nema INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
649e12c487bSEaswaran Raman INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
6507853c1ddSXinliang David Li INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
651df6763abSAshutosh Nema INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
652df6763abSAshutosh Nema INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
653df6763abSAshutosh Nema INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
654007b425bSAshutosh Nema INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
65565a36bbcSTaWeiTu INITIALIZE_PASS_END(LoopVersioningLICMLegacyPass, "loop-versioning-licm",
656df6763abSAshutosh Nema                     "Loop Versioning For LICM", false, false)
657df6763abSAshutosh Nema 
65865a36bbcSTaWeiTu Pass *llvm::createLoopVersioningLICMPass() {
65965a36bbcSTaWeiTu   return new LoopVersioningLICMLegacyPass();
66065a36bbcSTaWeiTu }
66165a36bbcSTaWeiTu 
66265a36bbcSTaWeiTu namespace llvm {
66365a36bbcSTaWeiTu 
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & LAR,LPMUpdater & U)66465a36bbcSTaWeiTu PreservedAnalyses LoopVersioningLICMPass::run(Loop &L, LoopAnalysisManager &AM,
66565a36bbcSTaWeiTu                                               LoopStandardAnalysisResults &LAR,
66665a36bbcSTaWeiTu                                               LPMUpdater &U) {
66765a36bbcSTaWeiTu   AliasAnalysis *AA = &LAR.AA;
66865a36bbcSTaWeiTu   ScalarEvolution *SE = &LAR.SE;
66965a36bbcSTaWeiTu   DominatorTree *DT = &LAR.DT;
67065a36bbcSTaWeiTu   LoopInfo *LI = &LAR.LI;
67165a36bbcSTaWeiTu   const Function *F = L.getHeader()->getParent();
67265a36bbcSTaWeiTu   OptimizationRemarkEmitter ORE(F);
67365a36bbcSTaWeiTu 
67465a36bbcSTaWeiTu   auto GetLAI = [&](Loop *L) -> const LoopAccessInfo & {
67565a36bbcSTaWeiTu     return AM.getResult<LoopAccessAnalysis>(*L, LAR);
67665a36bbcSTaWeiTu   };
67765a36bbcSTaWeiTu 
67865a36bbcSTaWeiTu   if (!LoopVersioningLICM(AA, SE, &ORE, GetLAI).runOnLoop(&L, LI, DT))
67965a36bbcSTaWeiTu     return PreservedAnalyses::all();
68065a36bbcSTaWeiTu   return getLoopPassPreservedAnalyses();
68165a36bbcSTaWeiTu }
68265a36bbcSTaWeiTu } // namespace llvm
683