blob: 7ccf2271e62496b38aca80ffb33536a5daa0987f [file] [log] [blame]
Ashutosh Nemadf6763a2016-02-06 07:47:48 +00001//===----------- LoopVersioningLICM.cpp - LICM Loop Versioning ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// When alias analysis is uncertain about the aliasing between any two accesses,
11// it will return MayAlias. This uncertainty from alias analysis restricts LICM
12// from proceeding further. In cases where alias analysis is uncertain we might
13// use loop versioning as an alternative.
14//
15// Loop Versioning will create a version of the loop with aggressive aliasing
16// assumptions in addition to the original with conservative (default) aliasing
17// assumptions. The version of the loop making aggressive aliasing assumptions
18// will have all the memory accesses marked as no-alias. These two versions of
19// loop will be preceded by a memory runtime check. This runtime check consists
20// of bound checks for all unique memory accessed in loop, and it ensures the
21// lack of memory aliasing. The result of the runtime check determines which of
22// the loop versions is executed: If the runtime check detects any memory
23// aliasing, then the original loop is executed. Otherwise, the version with
24// aggressive aliasing assumptions is used.
25//
26// Following are the top level steps:
27//
28// a) Perform LoopVersioningLICM's feasibility check.
29// b) If loop is a candidate for versioning then create a memory bound check,
30// by considering all the memory accesses in loop body.
31// c) Clone original loop and set all memory accesses as no-alias in new loop.
32// d) Set original loop & versioned loop as a branch target of the runtime check
33// result.
34//
35// It transforms loop as shown below:
36//
37// +----------------+
38// |Runtime Memcheck|
39// +----------------+
40// |
41// +----------+----------------+----------+
42// | |
43// +---------+----------+ +-----------+----------+
44// |Orig Loop Preheader | |Cloned Loop Preheader |
45// +--------------------+ +----------------------+
46// | |
47// +--------------------+ +----------------------+
48// |Orig Loop Body | |Cloned Loop Body |
49// +--------------------+ +----------------------+
50// | |
51// +--------------------+ +----------------------+
Ashutosh Nema2260a3a2016-02-11 09:23:53 +000052// |Orig Loop Exit Block| |Cloned Loop Exit Block|
Ashutosh Nemadf6763a2016-02-06 07:47:48 +000053// +--------------------+ +-----------+----------+
54// | |
55// +----------+--------------+-----------+
56// |
57// +-----+----+
58// |Join Block|
59// +----------+
60//
61//===----------------------------------------------------------------------===//
62
63#include "llvm/ADT/MapVector.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/Statistic.h"
66#include "llvm/ADT/StringExtras.h"
67#include "llvm/Analysis/AliasAnalysis.h"
68#include "llvm/Analysis/AliasSetTracker.h"
69#include "llvm/Analysis/ConstantFolding.h"
70#include "llvm/Analysis/GlobalsModRef.h"
71#include "llvm/Analysis/LoopAccessAnalysis.h"
72#include "llvm/Analysis/LoopInfo.h"
73#include "llvm/Analysis/LoopPass.h"
74#include "llvm/Analysis/ScalarEvolution.h"
75#include "llvm/Analysis/ScalarEvolutionExpander.h"
76#include "llvm/Analysis/TargetLibraryInfo.h"
77#include "llvm/Analysis/ValueTracking.h"
78#include "llvm/Analysis/VectorUtils.h"
79#include "llvm/IR/Dominators.h"
80#include "llvm/IR/IntrinsicInst.h"
81#include "llvm/IR/MDBuilder.h"
82#include "llvm/IR/PatternMatch.h"
83#include "llvm/IR/PredIteratorCache.h"
84#include "llvm/IR/Type.h"
85#include "llvm/Support/Debug.h"
86#include "llvm/Support/raw_ostream.h"
87#include "llvm/Transforms/Scalar.h"
88#include "llvm/Transforms/Utils/BasicBlockUtils.h"
89#include "llvm/Transforms/Utils/Cloning.h"
90#include "llvm/Transforms/Utils/LoopUtils.h"
91#include "llvm/Transforms/Utils/LoopVersioning.h"
92#include "llvm/Transforms/Utils/ValueMapper.h"
93
94#define DEBUG_TYPE "loop-versioning-licm"
Tamas Berghammerd12f3152016-02-11 11:27:51 +000095static const char* LICMVersioningMetaData =
Ashutosh Nema2260a3a2016-02-11 09:23:53 +000096 "llvm.loop.licm_versioning.disable";
Ashutosh Nemadf6763a2016-02-06 07:47:48 +000097
98using namespace llvm;
99
100/// Threshold minimum allowed percentage for possible
101/// invariant instructions in a loop.
102static cl::opt<float>
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000103 LVInvarThreshold("licm-versioning-invariant-threshold",
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000104 cl::desc("LoopVersioningLICM's minimum allowed percentage"
105 "of possible invariant instructions per loop"),
106 cl::init(25), cl::Hidden);
107
108/// Threshold for maximum allowed loop nest/depth
109static cl::opt<unsigned> LVLoopDepthThreshold(
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000110 "licm-versioning-max-depth-threshold",
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000111 cl::desc(
112 "LoopVersioningLICM's threshold for maximum allowed loop nest/depth"),
113 cl::init(2), cl::Hidden);
114
115/// \brief Create MDNode for input string.
116static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
117 LLVMContext &Context = TheLoop->getHeader()->getContext();
118 Metadata *MDs[] = {
119 MDString::get(Context, Name),
120 ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
121 return MDNode::get(Context, MDs);
122}
123
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000124/// \brief Set input string into loop metadata by keeping other values intact.
125void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *MDString,
126 unsigned V) {
127 SmallVector<Metadata *, 4> MDs(1);
128 // If the loop already has metadata, retain it.
129 MDNode *LoopID = TheLoop->getLoopID();
130 if (LoopID) {
131 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
132 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
133 MDs.push_back(Node);
134 }
135 }
136 // Add new metadata.
137 MDs.push_back(createStringMetadata(TheLoop, MDString, V));
138 // Replace current metadata node with new one.
139 LLVMContext &Context = TheLoop->getHeader()->getContext();
140 MDNode *NewLoopID = MDNode::get(Context, MDs);
141 // Set operand 0 to refer to the loop id itself.
142 NewLoopID->replaceOperandWith(0, NewLoopID);
143 TheLoop->setLoopID(NewLoopID);
144}
145
146namespace {
147struct LoopVersioningLICM : public LoopPass {
148 static char ID;
149
150 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
151
152 void getAnalysisUsage(AnalysisUsage &AU) const override {
153 AU.setPreservesCFG();
154 AU.addRequired<AAResultsWrapperPass>();
155 AU.addRequired<DominatorTreeWrapperPass>();
156 AU.addRequiredID(LCSSAID);
157 AU.addRequired<LoopAccessAnalysis>();
158 AU.addRequired<LoopInfoWrapperPass>();
159 AU.addRequiredID(LoopSimplifyID);
160 AU.addRequired<ScalarEvolutionWrapperPass>();
161 AU.addRequired<TargetLibraryInfoWrapperPass>();
162 AU.addPreserved<AAResultsWrapperPass>();
163 AU.addPreserved<GlobalsAAWrapperPass>();
164 }
165
166 using llvm::Pass::doFinalization;
167
168 bool doFinalization() override { return false; }
169
170 LoopVersioningLICM()
171 : LoopPass(ID), AA(nullptr), SE(nullptr), LI(nullptr), DT(nullptr),
172 TLI(nullptr), LAA(nullptr), LAI(nullptr), Changed(false),
173 Preheader(nullptr), CurLoop(nullptr), CurAST(nullptr),
174 LoopDepthThreshold(LVLoopDepthThreshold),
175 InvariantThreshold(LVInvarThreshold), LoadAndStoreCounter(0),
176 InvariantCounter(0), IsReadOnlyLoop(true) {
177 initializeLoopVersioningLICMPass(*PassRegistry::getPassRegistry());
178 }
179
180 AliasAnalysis *AA; // Current AliasAnalysis information
181 ScalarEvolution *SE; // Current ScalarEvolution
182 LoopInfo *LI; // Current LoopInfo
183 DominatorTree *DT; // Dominator Tree for the current Loop.
184 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding.
185 LoopAccessAnalysis *LAA; // Current LoopAccessAnalysis
186 const LoopAccessInfo *LAI; // Current Loop's LoopAccessInfo
187
188 bool Changed; // Set to true when we change anything.
189 BasicBlock *Preheader; // The preheader block of the current loop.
190 Loop *CurLoop; // The current loop we are working on.
191 AliasSetTracker *CurAST; // AliasSet information for the current loop.
192 ValueToValueMap Strides;
193
194 unsigned LoopDepthThreshold; // Maximum loop nest threshold
195 float InvariantThreshold; // Minimum invariant threshold
196 unsigned LoadAndStoreCounter; // Counter to track num of load & store
197 unsigned InvariantCounter; // Counter to track num of invariant
198 bool IsReadOnlyLoop; // Read only loop marker.
199
200 bool isLegalForVersioning();
201 bool legalLoopStructure();
202 bool legalLoopInstructions();
203 bool legalLoopMemoryAccesses();
204 void collectStridedAccess(Value *LoadOrStoreInst);
205 bool isLoopAlreadyVisited();
206 void setNoAliasToLoop(Loop *);
207 bool instructionSafeForVersioning(Instruction *);
208 const char *getPassName() const override { return "Loop Versioning"; }
209};
210}
211
212/// \brief Collects stride access from a given value.
213void LoopVersioningLICM::collectStridedAccess(Value *MemAccess) {
214 Value *Ptr = nullptr;
215 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
216 Ptr = LI->getPointerOperand();
217 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
218 Ptr = SI->getPointerOperand();
219 else
220 return;
221
222 Value *Stride = getStrideFromPointer(Ptr, SE, CurLoop);
223 if (!Stride)
224 return;
225
226 DEBUG(dbgs() << "Found a strided access that we can version");
227 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
228 Strides[Ptr] = Stride;
229}
230
231/// \brief Check loop structure and confirms it's good for LoopVersioningLICM.
232bool LoopVersioningLICM::legalLoopStructure() {
233 // Loop must have a preheader, if not return false.
234 if (!CurLoop->getLoopPreheader()) {
235 DEBUG(dbgs() << " loop preheader is missing\n");
236 return false;
237 }
238 // Loop should be innermost loop, if not return false.
239 if (CurLoop->getSubLoops().size()) {
240 DEBUG(dbgs() << " loop is not innermost\n");
241 return false;
242 }
243 // Loop should have a single backedge, if not return false.
244 if (CurLoop->getNumBackEdges() != 1) {
245 DEBUG(dbgs() << " loop has multiple backedges\n");
246 return false;
247 }
248 // Loop must have a single exiting block, if not return false.
249 if (!CurLoop->getExitingBlock()) {
250 DEBUG(dbgs() << " loop has multiple exiting block\n");
251 return false;
252 }
253 // We only handle bottom-tested loop, i.e. loop in which the condition is
254 // checked at the end of each iteration. With that we can assume that all
255 // instructions in the loop are executed the same number of times.
256 if (CurLoop->getExitingBlock() != CurLoop->getLoopLatch()) {
257 DEBUG(dbgs() << " loop is not bottom tested\n");
258 return false;
259 }
260 // Parallel loops must not have aliasing loop-invariant memory accesses.
261 // Hence we don't need to version anything in this case.
262 if (CurLoop->isAnnotatedParallel()) {
263 DEBUG(dbgs() << " Parallel loop is not worth versioning\n");
264 return false;
265 }
266 // Loop depth more then LoopDepthThreshold are not allowed
267 if (CurLoop->getLoopDepth() > LoopDepthThreshold) {
268 DEBUG(dbgs() << " loop depth is more then threshold\n");
269 return false;
270 }
271 // Loop should have a dedicated exit block, if not return false.
272 if (!CurLoop->hasDedicatedExits()) {
273 DEBUG(dbgs() << " loop does not has dedicated exit blocks\n");
274 return false;
275 }
276 // We need to be able to compute the loop trip count in order
277 // to generate the bound checks.
278 const SCEV *ExitCount = SE->getBackedgeTakenCount(CurLoop);
279 if (ExitCount == SE->getCouldNotCompute()) {
280 DEBUG(dbgs() << " loop does not has trip count\n");
281 return false;
282 }
283 return true;
284}
285
286/// \brief Check memory accesses in loop and confirms it's good for
287/// LoopVersioningLICM.
288bool LoopVersioningLICM::legalLoopMemoryAccesses() {
289 bool HasMayAlias = false;
290 bool TypeSafety = false;
291 bool HasMod = false;
292 // Memory check:
293 // Transform phase will generate a versioned loop and also a runtime check to
294 // ensure the pointers are independent and they don’t alias.
295 // In version variant of loop, alias meta data asserts that all access are
296 // mutually independent.
297 //
298 // Pointers aliasing in alias domain are avoided because with multiple
299 // aliasing domains we may not be able to hoist potential loop invariant
300 // access out of the loop.
301 //
302 // Iterate over alias tracker sets, and confirm AliasSets doesn't have any
303 // must alias set.
304 for (const auto &I : *CurAST) {
305 const AliasSet &AS = I;
306 // Skip Forward Alias Sets, as this should be ignored as part of
307 // the AliasSetTracker object.
308 if (AS.isForwardingAliasSet())
309 continue;
310 // With MustAlias its not worth adding runtime bound check.
311 if (AS.isMustAlias())
312 return false;
313 Value *SomePtr = AS.begin()->getValue();
314 bool TypeCheck = true;
315 // Check for Mod & MayAlias
316 HasMayAlias |= AS.isMayAlias();
317 HasMod |= AS.isMod();
318 for (const auto &A : AS) {
319 Value *Ptr = A.getValue();
320 // Alias tracker should have pointers of same data type.
321 TypeCheck = (TypeCheck && (SomePtr->getType() == Ptr->getType()));
322 }
323 // At least one alias tracker should have pointers of same data type.
324 TypeSafety |= TypeCheck;
325 }
326 // Ensure types should be of same type.
327 if (!TypeSafety) {
328 DEBUG(dbgs() << " Alias tracker type safety failed!\n");
329 return false;
330 }
331 // Ensure loop body shouldn't be read only.
332 if (!HasMod) {
333 DEBUG(dbgs() << " No memory modified in loop body\n");
334 return false;
335 }
336 // Make sure alias set has may alias case.
337 // If there no alias memory ambiguity, return false.
338 if (!HasMayAlias) {
339 DEBUG(dbgs() << " No ambiguity in memory access.\n");
340 return false;
341 }
342 return true;
343}
344
345/// \brief Check loop instructions safe for Loop versioning.
346/// It returns true if it's safe else returns false.
347/// Consider following:
348/// 1) Check all load store in loop body are non atomic & non volatile.
349/// 2) Check function call safety, by ensuring its not accessing memory.
350/// 3) Loop body shouldn't have any may throw instruction.
351bool LoopVersioningLICM::instructionSafeForVersioning(Instruction *I) {
352 assert(I != nullptr && "Null instruction found!");
353 // Check function call safety
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000354 if (isa<CallInst>(I) && !AA->doesNotAccessMemory(CallSite(I))) {
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000355 DEBUG(dbgs() << " Unsafe call site found.\n");
356 return false;
357 }
358 // Avoid loops with possiblity of throw
359 if (I->mayThrow()) {
360 DEBUG(dbgs() << " May throw instruction found in loop body\n");
361 return false;
362 }
363 // If current instruction is load instructions
364 // make sure it's a simple load (non atomic & non volatile)
365 if (I->mayReadFromMemory()) {
366 LoadInst *Ld = dyn_cast<LoadInst>(I);
367 if (!Ld || !Ld->isSimple()) {
368 DEBUG(dbgs() << " Found a non-simple load.\n");
369 return false;
370 }
371 LoadAndStoreCounter++;
372 collectStridedAccess(Ld);
373 Value *Ptr = Ld->getPointerOperand();
374 // Check loop invariant.
375 if (SE->isLoopInvariant(SE->getSCEV(Ptr), CurLoop))
376 InvariantCounter++;
377 }
378 // If current instruction is store instruction
379 // make sure it's a simple store (non atomic & non volatile)
380 else if (I->mayWriteToMemory()) {
381 StoreInst *St = dyn_cast<StoreInst>(I);
382 if (!St || !St->isSimple()) {
383 DEBUG(dbgs() << " Found a non-simple store.\n");
384 return false;
385 }
386 LoadAndStoreCounter++;
387 collectStridedAccess(St);
388 Value *Ptr = St->getPointerOperand();
389 // Check loop invariant.
390 if (SE->isLoopInvariant(SE->getSCEV(Ptr), CurLoop))
391 InvariantCounter++;
392
393 IsReadOnlyLoop = false;
394 }
395 return true;
396}
397
398/// \brief Check loop instructions and confirms it's good for
399/// LoopVersioningLICM.
400bool LoopVersioningLICM::legalLoopInstructions() {
401 // Resetting counters.
402 LoadAndStoreCounter = 0;
403 InvariantCounter = 0;
404 IsReadOnlyLoop = true;
405 // Iterate over loop blocks and instructions of each block and check
406 // instruction safety.
407 for (auto *Block : CurLoop->getBlocks())
408 for (auto &Inst : *Block) {
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000409 // If instruction is unsafe just return false.
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000410 if (!instructionSafeForVersioning(&Inst))
411 return false;
412 }
413 // Get LoopAccessInfo from current loop.
Xinliang David Liecde1c72016-06-09 03:22:39 +0000414 LAI = &LAA->getInfo(CurLoop, Strides);
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000415 // Check LoopAccessInfo for need of runtime check.
416 if (LAI->getRuntimePointerChecking()->getChecks().empty()) {
417 DEBUG(dbgs() << " LAA: Runtime check not found !!\n");
418 return false;
419 }
420 // Number of runtime-checks should be less then RuntimeMemoryCheckThreshold
421 if (LAI->getNumRuntimePointerChecks() >
422 VectorizerParams::RuntimeMemoryCheckThreshold) {
423 DEBUG(dbgs() << " LAA: Runtime checks are more than threshold !!\n");
424 return false;
425 }
426 // Loop should have at least one invariant load or store instruction.
427 if (!InvariantCounter) {
428 DEBUG(dbgs() << " Invariant not found !!\n");
429 return false;
430 }
431 // Read only loop not allowed.
432 if (IsReadOnlyLoop) {
433 DEBUG(dbgs() << " Found a read-only loop!\n");
434 return false;
435 }
436 // Profitablity check:
437 // Check invariant threshold, should be in limit.
438 if (InvariantCounter * 100 < InvariantThreshold * LoadAndStoreCounter) {
439 DEBUG(dbgs()
440 << " Invariant load & store are less then defined threshold\n");
441 DEBUG(dbgs() << " Invariant loads & stores: "
442 << ((InvariantCounter * 100) / LoadAndStoreCounter) << "%\n");
443 DEBUG(dbgs() << " Invariant loads & store threshold: "
444 << InvariantThreshold << "%\n");
445 return false;
446 }
447 return true;
448}
449
450/// \brief It checks loop is already visited or not.
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000451/// check loop meta data, if loop revisited return true
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000452/// else false.
453bool LoopVersioningLICM::isLoopAlreadyVisited() {
454 // Check LoopVersioningLICM metadata into loop
Adam Nemetf7878262016-04-21 17:33:12 +0000455 if (findStringMetadataForLoop(CurLoop, LICMVersioningMetaData)) {
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000456 return true;
457 }
458 return false;
459}
460
461/// \brief Checks legality for LoopVersioningLICM by considering following:
462/// a) loop structure legality b) loop instruction legality
463/// c) loop memory access legality.
464/// Return true if legal else returns false.
465bool LoopVersioningLICM::isLegalForVersioning() {
466 DEBUG(dbgs() << "Loop: " << *CurLoop);
467 // Make sure not re-visiting same loop again.
468 if (isLoopAlreadyVisited()) {
469 DEBUG(
470 dbgs() << " Revisiting loop in LoopVersioningLICM not allowed.\n\n");
471 return false;
472 }
473 // Check loop structure leagality.
474 if (!legalLoopStructure()) {
475 DEBUG(
476 dbgs() << " Loop structure not suitable for LoopVersioningLICM\n\n");
477 return false;
478 }
479 // Check loop instruction leagality.
480 if (!legalLoopInstructions()) {
481 DEBUG(dbgs()
482 << " Loop instructions not suitable for LoopVersioningLICM\n\n");
483 return false;
484 }
485 // Check loop memory access leagality.
486 if (!legalLoopMemoryAccesses()) {
487 DEBUG(dbgs()
488 << " Loop memory access not suitable for LoopVersioningLICM\n\n");
489 return false;
490 }
491 // Loop versioning is feasible, return true.
492 DEBUG(dbgs() << " Loop Versioning found to be beneficial\n\n");
493 return true;
494}
495
496/// \brief Update loop with aggressive aliasing assumptions.
497/// It marks no-alias to any pairs of memory operations by assuming
498/// loop should not have any must-alias memory accesses pairs.
499/// During LoopVersioningLICM legality we ignore loops having must
500/// aliasing memory accesses.
501void LoopVersioningLICM::setNoAliasToLoop(Loop *VerLoop) {
502 // Get latch terminator instruction.
503 Instruction *I = VerLoop->getLoopLatch()->getTerminator();
504 // Create alias scope domain.
505 MDBuilder MDB(I->getContext());
506 MDNode *NewDomain = MDB.createAnonymousAliasScopeDomain("LVDomain");
507 StringRef Name = "LVAliasScope";
508 SmallVector<Metadata *, 4> Scopes, NoAliases;
509 MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
510 // Iterate over each instruction of loop.
511 // set no-alias for all load & store instructions.
512 for (auto *Block : CurLoop->getBlocks()) {
513 for (auto &Inst : *Block) {
514 // Only interested in instruction that may modify or read memory.
515 if (!Inst.mayReadFromMemory() && !Inst.mayWriteToMemory())
516 continue;
517 Scopes.push_back(NewScope);
518 NoAliases.push_back(NewScope);
519 // Set no-alias for current instruction.
520 Inst.setMetadata(
521 LLVMContext::MD_noalias,
522 MDNode::concatenate(Inst.getMetadata(LLVMContext::MD_noalias),
523 MDNode::get(Inst.getContext(), NoAliases)));
524 // set alias-scope for current instruction.
525 Inst.setMetadata(
526 LLVMContext::MD_alias_scope,
527 MDNode::concatenate(Inst.getMetadata(LLVMContext::MD_alias_scope),
528 MDNode::get(Inst.getContext(), Scopes)));
529 }
530 }
531}
532
533bool LoopVersioningLICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000534 if (skipLoop(L))
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000535 return false;
536 Changed = false;
537 // Get Analysis information.
538 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
539 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
540 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
541 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
542 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
543 LAA = &getAnalysis<LoopAccessAnalysis>();
544 LAI = nullptr;
545 // Set Current Loop
546 CurLoop = L;
547 // Get the preheader block.
548 Preheader = L->getLoopPreheader();
549 // Initial allocation
550 CurAST = new AliasSetTracker(*AA);
551
552 // Loop over the body of this loop, construct AST.
553 for (auto *Block : L->getBlocks()) {
554 if (LI->getLoopFor(Block) == L) // Ignore blocks in subloop.
555 CurAST->add(*Block); // Incorporate the specified basic block
556 }
557 // Check feasiblity of LoopVersioningLICM.
558 // If versioning found to be feasible and beneficial then proceed
559 // else simply return, by cleaning up memory.
560 if (isLegalForVersioning()) {
561 // Do loop versioning.
562 // Create memcheck for memory accessed inside loop.
563 // Clone original loop, and set blocks properly.
564 LoopVersioning LVer(*LAI, CurLoop, LI, DT, SE, true);
565 LVer.versionLoop();
566 // Set Loop Versioning metaData for original loop.
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000567 addStringMetadataToLoop(LVer.getNonVersionedLoop(), LICMVersioningMetaData);
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000568 // Set Loop Versioning metaData for version loop.
Ashutosh Nema2260a3a2016-02-11 09:23:53 +0000569 addStringMetadataToLoop(LVer.getVersionedLoop(), LICMVersioningMetaData);
Ashutosh Nemadf6763a2016-02-06 07:47:48 +0000570 // Set "llvm.mem.parallel_loop_access" metaData to versioned loop.
571 addStringMetadataToLoop(LVer.getVersionedLoop(),
572 "llvm.mem.parallel_loop_access");
573 // Update version loop with aggressive aliasing assumption.
574 setNoAliasToLoop(LVer.getVersionedLoop());
575 Changed = true;
576 }
577 // Delete allocated memory.
578 delete CurAST;
579 return Changed;
580}
581
582char LoopVersioningLICM::ID = 0;
583INITIALIZE_PASS_BEGIN(LoopVersioningLICM, "loop-versioning-licm",
584 "Loop Versioning For LICM", false, false)
585INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
586INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
587INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
588INITIALIZE_PASS_DEPENDENCY(LCSSA)
589INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
590INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
591INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
592INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
593INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
594INITIALIZE_PASS_END(LoopVersioningLICM, "loop-versioning-licm",
595 "Loop Versioning For LICM", false, false)
596
597Pass *llvm::createLoopVersioningLICMPass() { return new LoopVersioningLICM(); }