1 //===- LoopInterchange.cpp - Loop interchange pass-------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This Pass handles loop interchange transform.
10 // This pass interchanges loops to provide a more cache-friendly memory access
11 // patterns.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Scalar/LoopInterchange.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Analysis/DependenceAnalysis.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
24 #include "llvm/Analysis/ScalarEvolution.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/InstrTypes.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/User.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Scalar.h"
46 #include "llvm/Transforms/Utils.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/LoopUtils.h"
49 #include <cassert>
50 #include <utility>
51 #include <vector>
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "loop-interchange"
56 
57 STATISTIC(LoopsInterchanged, "Number of loops interchanged");
58 
59 static cl::opt<int> LoopInterchangeCostThreshold(
60     "loop-interchange-threshold", cl::init(0), cl::Hidden,
61     cl::desc("Interchange if you gain more than this number"));
62 
63 namespace {
64 
65 using LoopVector = SmallVector<Loop *, 8>;
66 
67 // TODO: Check if we can use a sparse matrix here.
68 using CharMatrix = std::vector<std::vector<char>>;
69 
70 } // end anonymous namespace
71 
72 // Maximum number of dependencies that can be handled in the dependency matrix.
73 static const unsigned MaxMemInstrCount = 100;
74 
75 // Maximum loop depth supported.
76 static const unsigned MaxLoopNestDepth = 10;
77 
78 #ifdef DUMP_DEP_MATRICIES
79 static void printDepMatrix(CharMatrix &DepMatrix) {
80   for (auto &Row : DepMatrix) {
81     for (auto D : Row)
82       LLVM_DEBUG(dbgs() << D << " ");
83     LLVM_DEBUG(dbgs() << "\n");
84   }
85 }
86 #endif
87 
88 static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level,
89                                      Loop *L, DependenceInfo *DI) {
90   using ValueVector = SmallVector<Value *, 16>;
91 
92   ValueVector MemInstr;
93 
94   // For each block.
95   for (BasicBlock *BB : L->blocks()) {
96     // Scan the BB and collect legal loads and stores.
97     for (Instruction &I : *BB) {
98       if (!isa<Instruction>(I))
99         return false;
100       if (auto *Ld = dyn_cast<LoadInst>(&I)) {
101         if (!Ld->isSimple())
102           return false;
103         MemInstr.push_back(&I);
104       } else if (auto *St = dyn_cast<StoreInst>(&I)) {
105         if (!St->isSimple())
106           return false;
107         MemInstr.push_back(&I);
108       }
109     }
110   }
111 
112   LLVM_DEBUG(dbgs() << "Found " << MemInstr.size()
113                     << " Loads and Stores to analyze\n");
114 
115   ValueVector::iterator I, IE, J, JE;
116 
117   for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
118     for (J = I, JE = MemInstr.end(); J != JE; ++J) {
119       std::vector<char> Dep;
120       Instruction *Src = cast<Instruction>(*I);
121       Instruction *Dst = cast<Instruction>(*J);
122       if (Src == Dst)
123         continue;
124       // Ignore Input dependencies.
125       if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
126         continue;
127       // Track Output, Flow, and Anti dependencies.
128       if (auto D = DI->depends(Src, Dst, true)) {
129         assert(D->isOrdered() && "Expected an output, flow or anti dep.");
130         LLVM_DEBUG(StringRef DepType =
131                        D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output";
132                    dbgs() << "Found " << DepType
133                           << " dependency between Src and Dst\n"
134                           << " Src:" << *Src << "\n Dst:" << *Dst << '\n');
135         unsigned Levels = D->getLevels();
136         char Direction;
137         for (unsigned II = 1; II <= Levels; ++II) {
138           const SCEV *Distance = D->getDistance(II);
139           const SCEVConstant *SCEVConst =
140               dyn_cast_or_null<SCEVConstant>(Distance);
141           if (SCEVConst) {
142             const ConstantInt *CI = SCEVConst->getValue();
143             if (CI->isNegative())
144               Direction = '<';
145             else if (CI->isZero())
146               Direction = '=';
147             else
148               Direction = '>';
149             Dep.push_back(Direction);
150           } else if (D->isScalar(II)) {
151             Direction = 'S';
152             Dep.push_back(Direction);
153           } else {
154             unsigned Dir = D->getDirection(II);
155             if (Dir == Dependence::DVEntry::LT ||
156                 Dir == Dependence::DVEntry::LE)
157               Direction = '<';
158             else if (Dir == Dependence::DVEntry::GT ||
159                      Dir == Dependence::DVEntry::GE)
160               Direction = '>';
161             else if (Dir == Dependence::DVEntry::EQ)
162               Direction = '=';
163             else
164               Direction = '*';
165             Dep.push_back(Direction);
166           }
167         }
168         while (Dep.size() != Level) {
169           Dep.push_back('I');
170         }
171 
172         DepMatrix.push_back(Dep);
173         if (DepMatrix.size() > MaxMemInstrCount) {
174           LLVM_DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount
175                             << " dependencies inside loop\n");
176           return false;
177         }
178       }
179     }
180   }
181 
182   return true;
183 }
184 
185 // A loop is moved from index 'from' to an index 'to'. Update the Dependence
186 // matrix by exchanging the two columns.
187 static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx,
188                                     unsigned ToIndx) {
189   unsigned numRows = DepMatrix.size();
190   for (unsigned i = 0; i < numRows; ++i) {
191     char TmpVal = DepMatrix[i][ToIndx];
192     DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx];
193     DepMatrix[i][FromIndx] = TmpVal;
194   }
195 }
196 
197 // Checks if outermost non '=','S'or'I' dependence in the dependence matrix is
198 // '>'
199 static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row,
200                                    unsigned Column) {
201   for (unsigned i = 0; i <= Column; ++i) {
202     if (DepMatrix[Row][i] == '<')
203       return false;
204     if (DepMatrix[Row][i] == '>')
205       return true;
206   }
207   // All dependencies were '=','S' or 'I'
208   return false;
209 }
210 
211 // Checks if no dependence exist in the dependency matrix in Row before Column.
212 static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row,
213                                  unsigned Column) {
214   for (unsigned i = 0; i < Column; ++i) {
215     if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' &&
216         DepMatrix[Row][i] != 'I')
217       return false;
218   }
219   return true;
220 }
221 
222 static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row,
223                                 unsigned OuterLoopId, char InnerDep,
224                                 char OuterDep) {
225   if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId))
226     return false;
227 
228   if (InnerDep == OuterDep)
229     return true;
230 
231   // It is legal to interchange if and only if after interchange no row has a
232   // '>' direction as the leftmost non-'='.
233 
234   if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I')
235     return true;
236 
237   if (InnerDep == '<')
238     return true;
239 
240   if (InnerDep == '>') {
241     // If OuterLoopId represents outermost loop then interchanging will make the
242     // 1st dependency as '>'
243     if (OuterLoopId == 0)
244       return false;
245 
246     // If all dependencies before OuterloopId are '=','S'or 'I'. Then
247     // interchanging will result in this row having an outermost non '='
248     // dependency of '>'
249     if (!containsNoDependence(DepMatrix, Row, OuterLoopId))
250       return true;
251   }
252 
253   return false;
254 }
255 
256 // Checks if it is legal to interchange 2 loops.
257 // [Theorem] A permutation of the loops in a perfect nest is legal if and only
258 // if the direction matrix, after the same permutation is applied to its
259 // columns, has no ">" direction as the leftmost non-"=" direction in any row.
260 static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
261                                       unsigned InnerLoopId,
262                                       unsigned OuterLoopId) {
263   unsigned NumRows = DepMatrix.size();
264   // For each row check if it is valid to interchange.
265   for (unsigned Row = 0; Row < NumRows; ++Row) {
266     char InnerDep = DepMatrix[Row][InnerLoopId];
267     char OuterDep = DepMatrix[Row][OuterLoopId];
268     if (InnerDep == '*' || OuterDep == '*')
269       return false;
270     if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep))
271       return false;
272   }
273   return true;
274 }
275 
276 static LoopVector populateWorklist(Loop &L) {
277   LLVM_DEBUG(dbgs() << "Calling populateWorklist on Func: "
278                     << L.getHeader()->getParent()->getName() << " Loop: %"
279                     << L.getHeader()->getName() << '\n');
280   LoopVector LoopList;
281   Loop *CurrentLoop = &L;
282   const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops();
283   while (!Vec->empty()) {
284     // The current loop has multiple subloops in it hence it is not tightly
285     // nested.
286     // Discard all loops above it added into Worklist.
287     if (Vec->size() != 1)
288       return {};
289 
290     LoopList.push_back(CurrentLoop);
291     CurrentLoop = Vec->front();
292     Vec = &CurrentLoop->getSubLoops();
293   }
294   LoopList.push_back(CurrentLoop);
295   return LoopList;
296 }
297 
298 static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
299   PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
300   if (InnerIndexVar)
301     return InnerIndexVar;
302   if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr)
303     return nullptr;
304   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
305     PHINode *PhiVar = cast<PHINode>(I);
306     Type *PhiTy = PhiVar->getType();
307     if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
308         !PhiTy->isPointerTy())
309       return nullptr;
310     const SCEVAddRecExpr *AddRec =
311         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
312     if (!AddRec || !AddRec->isAffine())
313       continue;
314     const SCEV *Step = AddRec->getStepRecurrence(*SE);
315     if (!isa<SCEVConstant>(Step))
316       continue;
317     // Found the induction variable.
318     // FIXME: Handle loops with more than one induction variable. Note that,
319     // currently, legality makes sure we have only one induction variable.
320     return PhiVar;
321   }
322   return nullptr;
323 }
324 
325 namespace {
326 
327 /// LoopInterchangeLegality checks if it is legal to interchange the loop.
328 class LoopInterchangeLegality {
329 public:
330   LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
331                           OptimizationRemarkEmitter *ORE)
332       : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
333 
334   /// Check if the loops can be interchanged.
335   bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId,
336                            CharMatrix &DepMatrix);
337 
338   /// Check if the loop structure is understood. We do not handle triangular
339   /// loops for now.
340   bool isLoopStructureUnderstood(PHINode *InnerInductionVar);
341 
342   bool currentLimitations();
343 
344   const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions() const {
345     return OuterInnerReductions;
346   }
347 
348 private:
349   bool tightlyNested(Loop *Outer, Loop *Inner);
350   bool containsUnsafeInstructions(BasicBlock *BB);
351 
352   /// Discover induction and reduction PHIs in the header of \p L. Induction
353   /// PHIs are added to \p Inductions, reductions are added to
354   /// OuterInnerReductions. When the outer loop is passed, the inner loop needs
355   /// to be passed as \p InnerLoop.
356   bool findInductionAndReductions(Loop *L,
357                                   SmallVector<PHINode *, 8> &Inductions,
358                                   Loop *InnerLoop);
359 
360   Loop *OuterLoop;
361   Loop *InnerLoop;
362 
363   ScalarEvolution *SE;
364 
365   /// Interface to emit optimization remarks.
366   OptimizationRemarkEmitter *ORE;
367 
368   /// Set of reduction PHIs taking part of a reduction across the inner and
369   /// outer loop.
370   SmallPtrSet<PHINode *, 4> OuterInnerReductions;
371 };
372 
373 /// LoopInterchangeProfitability checks if it is profitable to interchange the
374 /// loop.
375 class LoopInterchangeProfitability {
376 public:
377   LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
378                                OptimizationRemarkEmitter *ORE)
379       : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
380 
381   /// Check if the loop interchange is profitable.
382   bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
383                     CharMatrix &DepMatrix);
384 
385 private:
386   int getInstrOrderCost();
387 
388   Loop *OuterLoop;
389   Loop *InnerLoop;
390 
391   /// Scev analysis.
392   ScalarEvolution *SE;
393 
394   /// Interface to emit optimization remarks.
395   OptimizationRemarkEmitter *ORE;
396 };
397 
398 /// LoopInterchangeTransform interchanges the loop.
399 class LoopInterchangeTransform {
400 public:
401   LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
402                            LoopInfo *LI, DominatorTree *DT,
403                            BasicBlock *LoopNestExit,
404                            const LoopInterchangeLegality &LIL)
405       : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
406         LoopExit(LoopNestExit), LIL(LIL) {}
407 
408   /// Interchange OuterLoop and InnerLoop.
409   bool transform();
410   void restructureLoops(Loop *NewInner, Loop *NewOuter,
411                         BasicBlock *OrigInnerPreHeader,
412                         BasicBlock *OrigOuterPreHeader);
413   void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
414 
415 private:
416   bool adjustLoopLinks();
417   bool adjustLoopBranches();
418 
419   Loop *OuterLoop;
420   Loop *InnerLoop;
421 
422   /// Scev analysis.
423   ScalarEvolution *SE;
424 
425   LoopInfo *LI;
426   DominatorTree *DT;
427   BasicBlock *LoopExit;
428 
429   const LoopInterchangeLegality &LIL;
430 };
431 
432 struct LoopInterchange {
433   ScalarEvolution *SE = nullptr;
434   LoopInfo *LI = nullptr;
435   DependenceInfo *DI = nullptr;
436   DominatorTree *DT = nullptr;
437 
438   /// Interface to emit optimization remarks.
439   OptimizationRemarkEmitter *ORE;
440 
441   LoopInterchange(ScalarEvolution *SE, LoopInfo *LI, DependenceInfo *DI,
442                   DominatorTree *DT, OptimizationRemarkEmitter *ORE)
443       : SE(SE), LI(LI), DI(DI), DT(DT), ORE(ORE) {}
444 
445   bool run(Loop *L) {
446     if (L->getParentLoop())
447       return false;
448 
449     return processLoopList(populateWorklist(*L));
450   }
451 
452   bool isComputableLoopNest(LoopVector LoopList) {
453     for (Loop *L : LoopList) {
454       const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
455       if (isa<SCEVCouldNotCompute>(ExitCountOuter)) {
456         LLVM_DEBUG(dbgs() << "Couldn't compute backedge count\n");
457         return false;
458       }
459       if (L->getNumBackEdges() != 1) {
460         LLVM_DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
461         return false;
462       }
463       if (!L->getExitingBlock()) {
464         LLVM_DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
465         return false;
466       }
467     }
468     return true;
469   }
470 
471   unsigned selectLoopForInterchange(const LoopVector &LoopList) {
472     // TODO: Add a better heuristic to select the loop to be interchanged based
473     // on the dependence matrix. Currently we select the innermost loop.
474     return LoopList.size() - 1;
475   }
476 
477   bool processLoopList(LoopVector LoopList) {
478     bool Changed = false;
479     unsigned LoopNestDepth = LoopList.size();
480     if (LoopNestDepth < 2) {
481       LLVM_DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
482       return false;
483     }
484     if (LoopNestDepth > MaxLoopNestDepth) {
485       LLVM_DEBUG(dbgs() << "Cannot handle loops of depth greater than "
486                         << MaxLoopNestDepth << "\n");
487       return false;
488     }
489     if (!isComputableLoopNest(LoopList)) {
490       LLVM_DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
491       return false;
492     }
493 
494     LLVM_DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth
495                       << "\n");
496 
497     CharMatrix DependencyMatrix;
498     Loop *OuterMostLoop = *(LoopList.begin());
499     if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
500                                   OuterMostLoop, DI)) {
501       LLVM_DEBUG(dbgs() << "Populating dependency matrix failed\n");
502       return false;
503     }
504 #ifdef DUMP_DEP_MATRICIES
505     LLVM_DEBUG(dbgs() << "Dependence before interchange\n");
506     printDepMatrix(DependencyMatrix);
507 #endif
508 
509     // Get the Outermost loop exit.
510     BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock();
511     if (!LoopNestExit) {
512       LLVM_DEBUG(dbgs() << "OuterMostLoop needs an unique exit block");
513       return false;
514     }
515 
516     unsigned SelecLoopId = selectLoopForInterchange(LoopList);
517     // Move the selected loop outwards to the best possible position.
518     for (unsigned i = SelecLoopId; i > 0; i--) {
519       bool Interchanged =
520           processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
521       if (!Interchanged)
522         return Changed;
523       // Loops interchanged reflect the same in LoopList
524       std::swap(LoopList[i - 1], LoopList[i]);
525 
526       // Update the DependencyMatrix
527       interChangeDependencies(DependencyMatrix, i, i - 1);
528 #ifdef DUMP_DEP_MATRICIES
529       LLVM_DEBUG(dbgs() << "Dependence after interchange\n");
530       printDepMatrix(DependencyMatrix);
531 #endif
532       Changed |= Interchanged;
533     }
534     return Changed;
535   }
536 
537   bool processLoop(LoopVector LoopList, unsigned InnerLoopId,
538                    unsigned OuterLoopId, BasicBlock *LoopNestExit,
539                    std::vector<std::vector<char>> &DependencyMatrix) {
540     LLVM_DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId
541                       << " and OuterLoopId = " << OuterLoopId << "\n");
542     Loop *InnerLoop = LoopList[InnerLoopId];
543     Loop *OuterLoop = LoopList[OuterLoopId];
544 
545     LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE);
546     if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
547       LLVM_DEBUG(dbgs() << "Not interchanging loops. Cannot prove legality.\n");
548       return false;
549     }
550     LLVM_DEBUG(dbgs() << "Loops are legal to interchange\n");
551     LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
552     if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
553       LLVM_DEBUG(dbgs() << "Interchanging loops not profitable.\n");
554       return false;
555     }
556 
557     ORE->emit([&]() {
558       return OptimizationRemark(DEBUG_TYPE, "Interchanged",
559                                 InnerLoop->getStartLoc(),
560                                 InnerLoop->getHeader())
561              << "Loop interchanged with enclosing loop.";
562     });
563 
564     LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LoopNestExit,
565                                  LIL);
566     LIT.transform();
567     LLVM_DEBUG(dbgs() << "Loops interchanged.\n");
568     LoopsInterchanged++;
569 
570     assert(InnerLoop->isLCSSAForm(*DT) &&
571            "Inner loop not left in LCSSA form after loop interchange!");
572     assert(OuterLoop->isLCSSAForm(*DT) &&
573            "Outer loop not left in LCSSA form after loop interchange!");
574 
575     return true;
576   }
577 };
578 
579 } // end anonymous namespace
580 
581 bool LoopInterchangeLegality::containsUnsafeInstructions(BasicBlock *BB) {
582   return any_of(*BB, [](const Instruction &I) {
583     return I.mayHaveSideEffects() || I.mayReadFromMemory();
584   });
585 }
586 
587 bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
588   BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
589   BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
590   BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
591 
592   LLVM_DEBUG(dbgs() << "Checking if loops are tightly nested\n");
593 
594   // A perfectly nested loop will not have any branch in between the outer and
595   // inner block i.e. outer header will branch to either inner preheader and
596   // outerloop latch.
597   BranchInst *OuterLoopHeaderBI =
598       dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
599   if (!OuterLoopHeaderBI)
600     return false;
601 
602   for (BasicBlock *Succ : successors(OuterLoopHeaderBI))
603     if (Succ != InnerLoopPreHeader && Succ != InnerLoop->getHeader() &&
604         Succ != OuterLoopLatch)
605       return false;
606 
607   LLVM_DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
608   // We do not have any basic block in between now make sure the outer header
609   // and outer loop latch doesn't contain any unsafe instructions.
610   if (containsUnsafeInstructions(OuterLoopHeader) ||
611       containsUnsafeInstructions(OuterLoopLatch))
612     return false;
613 
614   // Also make sure the inner loop preheader does not contain any unsafe
615   // instructions. Note that all instructions in the preheader will be moved to
616   // the outer loop header when interchanging.
617   if (InnerLoopPreHeader != OuterLoopHeader &&
618       containsUnsafeInstructions(InnerLoopPreHeader))
619     return false;
620 
621   LLVM_DEBUG(dbgs() << "Loops are perfectly nested\n");
622   // We have a perfect loop nest.
623   return true;
624 }
625 
626 bool LoopInterchangeLegality::isLoopStructureUnderstood(
627     PHINode *InnerInduction) {
628   unsigned Num = InnerInduction->getNumOperands();
629   BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
630   for (unsigned i = 0; i < Num; ++i) {
631     Value *Val = InnerInduction->getOperand(i);
632     if (isa<Constant>(Val))
633       continue;
634     Instruction *I = dyn_cast<Instruction>(Val);
635     if (!I)
636       return false;
637     // TODO: Handle triangular loops.
638     // e.g. for(int i=0;i<N;i++)
639     //        for(int j=i;j<N;j++)
640     unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
641     if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
642             InnerLoopPreheader &&
643         !OuterLoop->isLoopInvariant(I)) {
644       return false;
645     }
646   }
647   return true;
648 }
649 
650 // If SV is a LCSSA PHI node with a single incoming value, return the incoming
651 // value.
652 static Value *followLCSSA(Value *SV) {
653   PHINode *PHI = dyn_cast<PHINode>(SV);
654   if (!PHI)
655     return SV;
656 
657   if (PHI->getNumIncomingValues() != 1)
658     return SV;
659   return followLCSSA(PHI->getIncomingValue(0));
660 }
661 
662 // Check V's users to see if it is involved in a reduction in L.
663 static PHINode *findInnerReductionPhi(Loop *L, Value *V) {
664   for (Value *User : V->users()) {
665     if (PHINode *PHI = dyn_cast<PHINode>(User)) {
666       if (PHI->getNumIncomingValues() == 1)
667         continue;
668       RecurrenceDescriptor RD;
669       if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD))
670         return PHI;
671       return nullptr;
672     }
673   }
674 
675   return nullptr;
676 }
677 
678 bool LoopInterchangeLegality::findInductionAndReductions(
679     Loop *L, SmallVector<PHINode *, 8> &Inductions, Loop *InnerLoop) {
680   if (!L->getLoopLatch() || !L->getLoopPredecessor())
681     return false;
682   for (PHINode &PHI : L->getHeader()->phis()) {
683     RecurrenceDescriptor RD;
684     InductionDescriptor ID;
685     if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID))
686       Inductions.push_back(&PHI);
687     else {
688       // PHIs in inner loops need to be part of a reduction in the outer loop,
689       // discovered when checking the PHIs of the outer loop earlier.
690       if (!InnerLoop) {
691         if (!OuterInnerReductions.count(&PHI)) {
692           LLVM_DEBUG(dbgs() << "Inner loop PHI is not part of reductions "
693                                "across the outer loop.\n");
694           return false;
695         }
696       } else {
697         assert(PHI.getNumIncomingValues() == 2 &&
698                "Phis in loop header should have exactly 2 incoming values");
699         // Check if we have a PHI node in the outer loop that has a reduction
700         // result from the inner loop as an incoming value.
701         Value *V = followLCSSA(PHI.getIncomingValueForBlock(L->getLoopLatch()));
702         PHINode *InnerRedPhi = findInnerReductionPhi(InnerLoop, V);
703         if (!InnerRedPhi ||
704             !llvm::is_contained(InnerRedPhi->incoming_values(), &PHI)) {
705           LLVM_DEBUG(
706               dbgs()
707               << "Failed to recognize PHI as an induction or reduction.\n");
708           return false;
709         }
710         OuterInnerReductions.insert(&PHI);
711         OuterInnerReductions.insert(InnerRedPhi);
712       }
713     }
714   }
715   return true;
716 }
717 
718 // This function indicates the current limitations in the transform as a result
719 // of which we do not proceed.
720 bool LoopInterchangeLegality::currentLimitations() {
721   BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
722   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
723 
724   // transform currently expects the loop latches to also be the exiting
725   // blocks.
726   if (InnerLoop->getExitingBlock() != InnerLoopLatch ||
727       OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() ||
728       !isa<BranchInst>(InnerLoopLatch->getTerminator()) ||
729       !isa<BranchInst>(OuterLoop->getLoopLatch()->getTerminator())) {
730     LLVM_DEBUG(
731         dbgs() << "Loops where the latch is not the exiting block are not"
732                << " supported currently.\n");
733     ORE->emit([&]() {
734       return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch",
735                                       OuterLoop->getStartLoc(),
736                                       OuterLoop->getHeader())
737              << "Loops where the latch is not the exiting block cannot be"
738                 " interchange currently.";
739     });
740     return true;
741   }
742 
743   PHINode *InnerInductionVar;
744   SmallVector<PHINode *, 8> Inductions;
745   if (!findInductionAndReductions(OuterLoop, Inductions, InnerLoop)) {
746     LLVM_DEBUG(
747         dbgs() << "Only outer loops with induction or reduction PHI nodes "
748                << "are supported currently.\n");
749     ORE->emit([&]() {
750       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter",
751                                       OuterLoop->getStartLoc(),
752                                       OuterLoop->getHeader())
753              << "Only outer loops with induction or reduction PHI nodes can be"
754                 " interchanged currently.";
755     });
756     return true;
757   }
758 
759   // TODO: Currently we handle only loops with 1 induction variable.
760   if (Inductions.size() != 1) {
761     LLVM_DEBUG(dbgs() << "Loops with more than 1 induction variables are not "
762                       << "supported currently.\n");
763     ORE->emit([&]() {
764       return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter",
765                                       OuterLoop->getStartLoc(),
766                                       OuterLoop->getHeader())
767              << "Only outer loops with 1 induction variable can be "
768                 "interchanged currently.";
769     });
770     return true;
771   }
772 
773   Inductions.clear();
774   if (!findInductionAndReductions(InnerLoop, Inductions, nullptr)) {
775     LLVM_DEBUG(
776         dbgs() << "Only inner loops with induction or reduction PHI nodes "
777                << "are supported currently.\n");
778     ORE->emit([&]() {
779       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner",
780                                       InnerLoop->getStartLoc(),
781                                       InnerLoop->getHeader())
782              << "Only inner loops with induction or reduction PHI nodes can be"
783                 " interchange currently.";
784     });
785     return true;
786   }
787 
788   // TODO: Currently we handle only loops with 1 induction variable.
789   if (Inductions.size() != 1) {
790     LLVM_DEBUG(
791         dbgs() << "We currently only support loops with 1 induction variable."
792                << "Failed to interchange due to current limitation\n");
793     ORE->emit([&]() {
794       return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner",
795                                       InnerLoop->getStartLoc(),
796                                       InnerLoop->getHeader())
797              << "Only inner loops with 1 induction variable can be "
798                 "interchanged currently.";
799     });
800     return true;
801   }
802   InnerInductionVar = Inductions.pop_back_val();
803 
804   // TODO: Triangular loops are not handled for now.
805   if (!isLoopStructureUnderstood(InnerInductionVar)) {
806     LLVM_DEBUG(dbgs() << "Loop structure not understood by pass\n");
807     ORE->emit([&]() {
808       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner",
809                                       InnerLoop->getStartLoc(),
810                                       InnerLoop->getHeader())
811              << "Inner loop structure not understood currently.";
812     });
813     return true;
814   }
815 
816   // TODO: Current limitation: Since we split the inner loop latch at the point
817   // were induction variable is incremented (induction.next); We cannot have
818   // more than 1 user of induction.next since it would result in broken code
819   // after split.
820   // e.g.
821   // for(i=0;i<N;i++) {
822   //    for(j = 0;j<M;j++) {
823   //      A[j+1][i+2] = A[j][i]+k;
824   //  }
825   // }
826   Instruction *InnerIndexVarInc = nullptr;
827   if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
828     InnerIndexVarInc =
829         dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
830   else
831     InnerIndexVarInc =
832         dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
833 
834   if (!InnerIndexVarInc) {
835     LLVM_DEBUG(
836         dbgs() << "Did not find an instruction to increment the induction "
837                << "variable.\n");
838     ORE->emit([&]() {
839       return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner",
840                                       InnerLoop->getStartLoc(),
841                                       InnerLoop->getHeader())
842              << "The inner loop does not increment the induction variable.";
843     });
844     return true;
845   }
846 
847   // Since we split the inner loop latch on this induction variable. Make sure
848   // we do not have any instruction between the induction variable and branch
849   // instruction.
850 
851   bool FoundInduction = false;
852   for (const Instruction &I :
853        llvm::reverse(InnerLoopLatch->instructionsWithoutDebug())) {
854     if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) ||
855         isa<ZExtInst>(I))
856       continue;
857 
858     // We found an instruction. If this is not induction variable then it is not
859     // safe to split this loop latch.
860     if (!I.isIdenticalTo(InnerIndexVarInc)) {
861       LLVM_DEBUG(dbgs() << "Found unsupported instructions between induction "
862                         << "variable increment and branch.\n");
863       ORE->emit([&]() {
864         return OptimizationRemarkMissed(
865                    DEBUG_TYPE, "UnsupportedInsBetweenInduction",
866                    InnerLoop->getStartLoc(), InnerLoop->getHeader())
867                << "Found unsupported instruction between induction variable "
868                   "increment and branch.";
869       });
870       return true;
871     }
872 
873     FoundInduction = true;
874     break;
875   }
876   // The loop latch ended and we didn't find the induction variable return as
877   // current limitation.
878   if (!FoundInduction) {
879     LLVM_DEBUG(dbgs() << "Did not find the induction variable.\n");
880     ORE->emit([&]() {
881       return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable",
882                                       InnerLoop->getStartLoc(),
883                                       InnerLoop->getHeader())
884              << "Did not find the induction variable.";
885     });
886     return true;
887   }
888   return false;
889 }
890 
891 // We currently only support LCSSA PHI nodes in the inner loop exit, if their
892 // users are either reduction PHIs or PHIs outside the outer loop (which means
893 // the we are only interested in the final value after the loop).
894 static bool
895 areInnerLoopExitPHIsSupported(Loop *InnerL, Loop *OuterL,
896                               SmallPtrSetImpl<PHINode *> &Reductions) {
897   BasicBlock *InnerExit = OuterL->getUniqueExitBlock();
898   for (PHINode &PHI : InnerExit->phis()) {
899     // Reduction lcssa phi will have only 1 incoming block that from loop latch.
900     if (PHI.getNumIncomingValues() > 1)
901       return false;
902     if (any_of(PHI.users(), [&Reductions, OuterL](User *U) {
903           PHINode *PN = dyn_cast<PHINode>(U);
904           return !PN ||
905                  (!Reductions.count(PN) && OuterL->contains(PN->getParent()));
906         })) {
907       return false;
908     }
909   }
910   return true;
911 }
912 
913 // We currently support LCSSA PHI nodes in the outer loop exit, if their
914 // incoming values do not come from the outer loop latch or if the
915 // outer loop latch has a single predecessor. In that case, the value will
916 // be available if both the inner and outer loop conditions are true, which
917 // will still be true after interchanging. If we have multiple predecessor,
918 // that may not be the case, e.g. because the outer loop latch may be executed
919 // if the inner loop is not executed.
920 static bool areOuterLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) {
921   BasicBlock *LoopNestExit = OuterLoop->getUniqueExitBlock();
922   for (PHINode &PHI : LoopNestExit->phis()) {
923     //  FIXME: We currently are not able to detect floating point reductions
924     //         and have to use floating point PHIs as a proxy to prevent
925     //         interchanging in the presence of floating point reductions.
926     if (PHI.getType()->isFloatingPointTy())
927       return false;
928     for (unsigned i = 0; i < PHI.getNumIncomingValues(); i++) {
929      Instruction *IncomingI = dyn_cast<Instruction>(PHI.getIncomingValue(i));
930      if (!IncomingI || IncomingI->getParent() != OuterLoop->getLoopLatch())
931        continue;
932 
933      // The incoming value is defined in the outer loop latch. Currently we
934      // only support that in case the outer loop latch has a single predecessor.
935      // This guarantees that the outer loop latch is executed if and only if
936      // the inner loop is executed (because tightlyNested() guarantees that the
937      // outer loop header only branches to the inner loop or the outer loop
938      // latch).
939      // FIXME: We could weaken this logic and allow multiple predecessors,
940      //        if the values are produced outside the loop latch. We would need
941      //        additional logic to update the PHI nodes in the exit block as
942      //        well.
943      if (OuterLoop->getLoopLatch()->getUniquePredecessor() == nullptr)
944        return false;
945     }
946   }
947   return true;
948 }
949 
950 bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
951                                                   unsigned OuterLoopId,
952                                                   CharMatrix &DepMatrix) {
953   if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
954     LLVM_DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
955                       << " and OuterLoopId = " << OuterLoopId
956                       << " due to dependence\n");
957     ORE->emit([&]() {
958       return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
959                                       InnerLoop->getStartLoc(),
960                                       InnerLoop->getHeader())
961              << "Cannot interchange loops due to dependences.";
962     });
963     return false;
964   }
965   // Check if outer and inner loop contain legal instructions only.
966   for (auto *BB : OuterLoop->blocks())
967     for (Instruction &I : BB->instructionsWithoutDebug())
968       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
969         // readnone functions do not prevent interchanging.
970         if (CI->doesNotReadMemory())
971           continue;
972         LLVM_DEBUG(
973             dbgs() << "Loops with call instructions cannot be interchanged "
974                    << "safely.");
975         ORE->emit([&]() {
976           return OptimizationRemarkMissed(DEBUG_TYPE, "CallInst",
977                                           CI->getDebugLoc(),
978                                           CI->getParent())
979                  << "Cannot interchange loops due to call instruction.";
980         });
981 
982         return false;
983       }
984 
985   // TODO: The loops could not be interchanged due to current limitations in the
986   // transform module.
987   if (currentLimitations()) {
988     LLVM_DEBUG(dbgs() << "Not legal because of current transform limitation\n");
989     return false;
990   }
991 
992   // Check if the loops are tightly nested.
993   if (!tightlyNested(OuterLoop, InnerLoop)) {
994     LLVM_DEBUG(dbgs() << "Loops not tightly nested\n");
995     ORE->emit([&]() {
996       return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested",
997                                       InnerLoop->getStartLoc(),
998                                       InnerLoop->getHeader())
999              << "Cannot interchange loops because they are not tightly "
1000                 "nested.";
1001     });
1002     return false;
1003   }
1004 
1005   if (!areInnerLoopExitPHIsSupported(OuterLoop, InnerLoop,
1006                                      OuterInnerReductions)) {
1007     LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in inner loop exit.\n");
1008     ORE->emit([&]() {
1009       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI",
1010                                       InnerLoop->getStartLoc(),
1011                                       InnerLoop->getHeader())
1012              << "Found unsupported PHI node in loop exit.";
1013     });
1014     return false;
1015   }
1016 
1017   if (!areOuterLoopExitPHIsSupported(OuterLoop, InnerLoop)) {
1018     LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in outer loop exit.\n");
1019     ORE->emit([&]() {
1020       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI",
1021                                       OuterLoop->getStartLoc(),
1022                                       OuterLoop->getHeader())
1023              << "Found unsupported PHI node in loop exit.";
1024     });
1025     return false;
1026   }
1027 
1028   return true;
1029 }
1030 
1031 int LoopInterchangeProfitability::getInstrOrderCost() {
1032   unsigned GoodOrder, BadOrder;
1033   BadOrder = GoodOrder = 0;
1034   for (BasicBlock *BB : InnerLoop->blocks()) {
1035     for (Instruction &Ins : *BB) {
1036       if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
1037         unsigned NumOp = GEP->getNumOperands();
1038         bool FoundInnerInduction = false;
1039         bool FoundOuterInduction = false;
1040         for (unsigned i = 0; i < NumOp; ++i) {
1041           // Skip operands that are not SCEV-able.
1042           if (!SE->isSCEVable(GEP->getOperand(i)->getType()))
1043             continue;
1044 
1045           const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
1046           const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
1047           if (!AR)
1048             continue;
1049 
1050           // If we find the inner induction after an outer induction e.g.
1051           // for(int i=0;i<N;i++)
1052           //   for(int j=0;j<N;j++)
1053           //     A[i][j] = A[i-1][j-1]+k;
1054           // then it is a good order.
1055           if (AR->getLoop() == InnerLoop) {
1056             // We found an InnerLoop induction after OuterLoop induction. It is
1057             // a good order.
1058             FoundInnerInduction = true;
1059             if (FoundOuterInduction) {
1060               GoodOrder++;
1061               break;
1062             }
1063           }
1064           // If we find the outer induction after an inner induction e.g.
1065           // for(int i=0;i<N;i++)
1066           //   for(int j=0;j<N;j++)
1067           //     A[j][i] = A[j-1][i-1]+k;
1068           // then it is a bad order.
1069           if (AR->getLoop() == OuterLoop) {
1070             // We found an OuterLoop induction after InnerLoop induction. It is
1071             // a bad order.
1072             FoundOuterInduction = true;
1073             if (FoundInnerInduction) {
1074               BadOrder++;
1075               break;
1076             }
1077           }
1078         }
1079       }
1080     }
1081   }
1082   return GoodOrder - BadOrder;
1083 }
1084 
1085 static bool isProfitableForVectorization(unsigned InnerLoopId,
1086                                          unsigned OuterLoopId,
1087                                          CharMatrix &DepMatrix) {
1088   // TODO: Improve this heuristic to catch more cases.
1089   // If the inner loop is loop independent or doesn't carry any dependency it is
1090   // profitable to move this to outer position.
1091   for (auto &Row : DepMatrix) {
1092     if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I')
1093       return false;
1094     // TODO: We need to improve this heuristic.
1095     if (Row[OuterLoopId] != '=')
1096       return false;
1097   }
1098   // If outer loop has dependence and inner loop is loop independent then it is
1099   // profitable to interchange to enable parallelism.
1100   // If there are no dependences, interchanging will not improve anything.
1101   return !DepMatrix.empty();
1102 }
1103 
1104 bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
1105                                                 unsigned OuterLoopId,
1106                                                 CharMatrix &DepMatrix) {
1107   // TODO: Add better profitability checks.
1108   // e.g
1109   // 1) Construct dependency matrix and move the one with no loop carried dep
1110   //    inside to enable vectorization.
1111 
1112   // This is rough cost estimation algorithm. It counts the good and bad order
1113   // of induction variables in the instruction and allows reordering if number
1114   // of bad orders is more than good.
1115   int Cost = getInstrOrderCost();
1116   LLVM_DEBUG(dbgs() << "Cost = " << Cost << "\n");
1117   if (Cost < -LoopInterchangeCostThreshold)
1118     return true;
1119 
1120   // It is not profitable as per current cache profitability model. But check if
1121   // we can move this loop outside to improve parallelism.
1122   if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix))
1123     return true;
1124 
1125   ORE->emit([&]() {
1126     return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
1127                                     InnerLoop->getStartLoc(),
1128                                     InnerLoop->getHeader())
1129            << "Interchanging loops is too costly (cost="
1130            << ore::NV("Cost", Cost) << ", threshold="
1131            << ore::NV("Threshold", LoopInterchangeCostThreshold)
1132            << ") and it does not improve parallelism.";
1133   });
1134   return false;
1135 }
1136 
1137 void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
1138                                                Loop *InnerLoop) {
1139   for (Loop *L : *OuterLoop)
1140     if (L == InnerLoop) {
1141       OuterLoop->removeChildLoop(L);
1142       return;
1143     }
1144   llvm_unreachable("Couldn't find loop");
1145 }
1146 
1147 /// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the
1148 /// new inner and outer loop after interchanging: NewInner is the original
1149 /// outer loop and NewOuter is the original inner loop.
1150 ///
1151 /// Before interchanging, we have the following structure
1152 /// Outer preheader
1153 //  Outer header
1154 //    Inner preheader
1155 //    Inner header
1156 //      Inner body
1157 //      Inner latch
1158 //   outer bbs
1159 //   Outer latch
1160 //
1161 // After interchanging:
1162 // Inner preheader
1163 // Inner header
1164 //   Outer preheader
1165 //   Outer header
1166 //     Inner body
1167 //     outer bbs
1168 //     Outer latch
1169 //   Inner latch
1170 void LoopInterchangeTransform::restructureLoops(
1171     Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader,
1172     BasicBlock *OrigOuterPreHeader) {
1173   Loop *OuterLoopParent = OuterLoop->getParentLoop();
1174   // The original inner loop preheader moves from the new inner loop to
1175   // the parent loop, if there is one.
1176   NewInner->removeBlockFromLoop(OrigInnerPreHeader);
1177   LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent);
1178 
1179   // Switch the loop levels.
1180   if (OuterLoopParent) {
1181     // Remove the loop from its parent loop.
1182     removeChildLoop(OuterLoopParent, NewInner);
1183     removeChildLoop(NewInner, NewOuter);
1184     OuterLoopParent->addChildLoop(NewOuter);
1185   } else {
1186     removeChildLoop(NewInner, NewOuter);
1187     LI->changeTopLevelLoop(NewInner, NewOuter);
1188   }
1189   while (!NewOuter->isInnermost())
1190     NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin()));
1191   NewOuter->addChildLoop(NewInner);
1192 
1193   // BBs from the original inner loop.
1194   SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks());
1195 
1196   // Add BBs from the original outer loop to the original inner loop (excluding
1197   // BBs already in inner loop)
1198   for (BasicBlock *BB : NewInner->blocks())
1199     if (LI->getLoopFor(BB) == NewInner)
1200       NewOuter->addBlockEntry(BB);
1201 
1202   // Now remove inner loop header and latch from the new inner loop and move
1203   // other BBs (the loop body) to the new inner loop.
1204   BasicBlock *OuterHeader = NewOuter->getHeader();
1205   BasicBlock *OuterLatch = NewOuter->getLoopLatch();
1206   for (BasicBlock *BB : OrigInnerBBs) {
1207     // Nothing will change for BBs in child loops.
1208     if (LI->getLoopFor(BB) != NewOuter)
1209       continue;
1210     // Remove the new outer loop header and latch from the new inner loop.
1211     if (BB == OuterHeader || BB == OuterLatch)
1212       NewInner->removeBlockFromLoop(BB);
1213     else
1214       LI->changeLoopFor(BB, NewInner);
1215   }
1216 
1217   // The preheader of the original outer loop becomes part of the new
1218   // outer loop.
1219   NewOuter->addBlockEntry(OrigOuterPreHeader);
1220   LI->changeLoopFor(OrigOuterPreHeader, NewOuter);
1221 
1222   // Tell SE that we move the loops around.
1223   SE->forgetLoop(NewOuter);
1224   SE->forgetLoop(NewInner);
1225 }
1226 
1227 bool LoopInterchangeTransform::transform() {
1228   bool Transformed = false;
1229   Instruction *InnerIndexVar;
1230 
1231   if (InnerLoop->getSubLoops().empty()) {
1232     BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1233     LLVM_DEBUG(dbgs() << "Splitting the inner loop latch\n");
1234     PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
1235     if (!InductionPHI) {
1236       LLVM_DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
1237       return false;
1238     }
1239 
1240     if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1241       InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
1242     else
1243       InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
1244 
1245     // Ensure that InductionPHI is the first Phi node.
1246     if (&InductionPHI->getParent()->front() != InductionPHI)
1247       InductionPHI->moveBefore(&InductionPHI->getParent()->front());
1248 
1249     // Create a new latch block for the inner loop. We split at the
1250     // current latch's terminator and then move the condition and all
1251     // operands that are not either loop-invariant or the induction PHI into the
1252     // new latch block.
1253     BasicBlock *NewLatch =
1254         SplitBlock(InnerLoop->getLoopLatch(),
1255                    InnerLoop->getLoopLatch()->getTerminator(), DT, LI);
1256 
1257     SmallSetVector<Instruction *, 4> WorkList;
1258     unsigned i = 0;
1259     auto MoveInstructions = [&i, &WorkList, this, InductionPHI, NewLatch]() {
1260       for (; i < WorkList.size(); i++) {
1261         // Duplicate instruction and move it the new latch. Update uses that
1262         // have been moved.
1263         Instruction *NewI = WorkList[i]->clone();
1264         NewI->insertBefore(NewLatch->getFirstNonPHI());
1265         assert(!NewI->mayHaveSideEffects() &&
1266                "Moving instructions with side-effects may change behavior of "
1267                "the loop nest!");
1268         for (auto UI = WorkList[i]->use_begin(), UE = WorkList[i]->use_end();
1269              UI != UE;) {
1270           Use &U = *UI++;
1271           Instruction *UserI = cast<Instruction>(U.getUser());
1272           if (!InnerLoop->contains(UserI->getParent()) ||
1273               UserI->getParent() == NewLatch || UserI == InductionPHI)
1274             U.set(NewI);
1275         }
1276         // Add operands of moved instruction to the worklist, except if they are
1277         // outside the inner loop or are the induction PHI.
1278         for (Value *Op : WorkList[i]->operands()) {
1279           Instruction *OpI = dyn_cast<Instruction>(Op);
1280           if (!OpI ||
1281               this->LI->getLoopFor(OpI->getParent()) != this->InnerLoop ||
1282               OpI == InductionPHI)
1283             continue;
1284           WorkList.insert(OpI);
1285         }
1286       }
1287     };
1288 
1289     // FIXME: Should we interchange when we have a constant condition?
1290     Instruction *CondI = dyn_cast<Instruction>(
1291         cast<BranchInst>(InnerLoop->getLoopLatch()->getTerminator())
1292             ->getCondition());
1293     if (CondI)
1294       WorkList.insert(CondI);
1295     MoveInstructions();
1296     WorkList.insert(cast<Instruction>(InnerIndexVar));
1297     MoveInstructions();
1298 
1299     // Splits the inner loops phi nodes out into a separate basic block.
1300     BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1301     SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
1302     LLVM_DEBUG(dbgs() << "splitting InnerLoopHeader done\n");
1303   }
1304 
1305   // Instructions in the original inner loop preheader may depend on values
1306   // defined in the outer loop header. Move them there, because the original
1307   // inner loop preheader will become the entry into the interchanged loop nest.
1308   // Currently we move all instructions and rely on LICM to move invariant
1309   // instructions outside the loop nest.
1310   BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1311   BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1312   if (InnerLoopPreHeader != OuterLoopHeader) {
1313     SmallPtrSet<Instruction *, 4> NeedsMoving;
1314     for (Instruction &I :
1315          make_early_inc_range(make_range(InnerLoopPreHeader->begin(),
1316                                          std::prev(InnerLoopPreHeader->end()))))
1317       I.moveBefore(OuterLoopHeader->getTerminator());
1318   }
1319 
1320   Transformed |= adjustLoopLinks();
1321   if (!Transformed) {
1322     LLVM_DEBUG(dbgs() << "adjustLoopLinks failed\n");
1323     return false;
1324   }
1325 
1326   return true;
1327 }
1328 
1329 /// \brief Move all instructions except the terminator from FromBB right before
1330 /// InsertBefore
1331 static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1332   auto &ToList = InsertBefore->getParent()->getInstList();
1333   auto &FromList = FromBB->getInstList();
1334 
1335   ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
1336                 FromBB->getTerminator()->getIterator());
1337 }
1338 
1339 /// Swap instructions between \p BB1 and \p BB2 but keep terminators intact.
1340 static void swapBBContents(BasicBlock *BB1, BasicBlock *BB2) {
1341   // Save all non-terminator instructions of BB1 into TempInstrs and unlink them
1342   // from BB1 afterwards.
1343   auto Iter = map_range(*BB1, [](Instruction &I) { return &I; });
1344   SmallVector<Instruction *, 4> TempInstrs(Iter.begin(), std::prev(Iter.end()));
1345   for (Instruction *I : TempInstrs)
1346     I->removeFromParent();
1347 
1348   // Move instructions from BB2 to BB1.
1349   moveBBContents(BB2, BB1->getTerminator());
1350 
1351   // Move instructions from TempInstrs to BB2.
1352   for (Instruction *I : TempInstrs)
1353     I->insertBefore(BB2->getTerminator());
1354 }
1355 
1356 // Update BI to jump to NewBB instead of OldBB. Records updates to the
1357 // dominator tree in DTUpdates. If \p MustUpdateOnce is true, assert that
1358 // \p OldBB  is exactly once in BI's successor list.
1359 static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB,
1360                             BasicBlock *NewBB,
1361                             std::vector<DominatorTree::UpdateType> &DTUpdates,
1362                             bool MustUpdateOnce = true) {
1363   assert((!MustUpdateOnce ||
1364           llvm::count_if(successors(BI),
1365                          [OldBB](BasicBlock *BB) {
1366                            return BB == OldBB;
1367                          }) == 1) && "BI must jump to OldBB exactly once.");
1368   bool Changed = false;
1369   for (Use &Op : BI->operands())
1370     if (Op == OldBB) {
1371       Op.set(NewBB);
1372       Changed = true;
1373     }
1374 
1375   if (Changed) {
1376     DTUpdates.push_back(
1377         {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB});
1378     DTUpdates.push_back(
1379         {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB});
1380   }
1381   assert(Changed && "Expected a successor to be updated");
1382 }
1383 
1384 // Move Lcssa PHIs to the right place.
1385 static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader,
1386                           BasicBlock *InnerLatch, BasicBlock *OuterHeader,
1387                           BasicBlock *OuterLatch, BasicBlock *OuterExit,
1388                           Loop *InnerLoop, LoopInfo *LI) {
1389 
1390   // Deal with LCSSA PHI nodes in the exit block of the inner loop, that are
1391   // defined either in the header or latch. Those blocks will become header and
1392   // latch of the new outer loop, and the only possible users can PHI nodes
1393   // in the exit block of the loop nest or the outer loop header (reduction
1394   // PHIs, in that case, the incoming value must be defined in the inner loop
1395   // header). We can just substitute the user with the incoming value and remove
1396   // the PHI.
1397   for (PHINode &P : make_early_inc_range(InnerExit->phis())) {
1398     assert(P.getNumIncomingValues() == 1 &&
1399            "Only loops with a single exit are supported!");
1400 
1401     // Incoming values are guaranteed be instructions currently.
1402     auto IncI = cast<Instruction>(P.getIncomingValueForBlock(InnerLatch));
1403     // Skip phis with incoming values from the inner loop body, excluding the
1404     // header and latch.
1405     if (IncI->getParent() != InnerLatch && IncI->getParent() != InnerHeader)
1406       continue;
1407 
1408     assert(all_of(P.users(),
1409                   [OuterHeader, OuterExit, IncI, InnerHeader](User *U) {
1410                     return (cast<PHINode>(U)->getParent() == OuterHeader &&
1411                             IncI->getParent() == InnerHeader) ||
1412                            cast<PHINode>(U)->getParent() == OuterExit;
1413                   }) &&
1414            "Can only replace phis iff the uses are in the loop nest exit or "
1415            "the incoming value is defined in the inner header (it will "
1416            "dominate all loop blocks after interchanging)");
1417     P.replaceAllUsesWith(IncI);
1418     P.eraseFromParent();
1419   }
1420 
1421   SmallVector<PHINode *, 8> LcssaInnerExit;
1422   for (PHINode &P : InnerExit->phis())
1423     LcssaInnerExit.push_back(&P);
1424 
1425   SmallVector<PHINode *, 8> LcssaInnerLatch;
1426   for (PHINode &P : InnerLatch->phis())
1427     LcssaInnerLatch.push_back(&P);
1428 
1429   // Lcssa PHIs for values used outside the inner loop are in InnerExit.
1430   // If a PHI node has users outside of InnerExit, it has a use outside the
1431   // interchanged loop and we have to preserve it. We move these to
1432   // InnerLatch, which will become the new exit block for the innermost
1433   // loop after interchanging.
1434   for (PHINode *P : LcssaInnerExit)
1435     P->moveBefore(InnerLatch->getFirstNonPHI());
1436 
1437   // If the inner loop latch contains LCSSA PHIs, those come from a child loop
1438   // and we have to move them to the new inner latch.
1439   for (PHINode *P : LcssaInnerLatch)
1440     P->moveBefore(InnerExit->getFirstNonPHI());
1441 
1442   // Deal with LCSSA PHI nodes in the loop nest exit block. For PHIs that have
1443   // incoming values defined in the outer loop, we have to add a new PHI
1444   // in the inner loop latch, which became the exit block of the outer loop,
1445   // after interchanging.
1446   if (OuterExit) {
1447     for (PHINode &P : OuterExit->phis()) {
1448       if (P.getNumIncomingValues() != 1)
1449         continue;
1450       // Skip Phis with incoming values defined in the inner loop. Those should
1451       // already have been updated.
1452       auto I = dyn_cast<Instruction>(P.getIncomingValue(0));
1453       if (!I || LI->getLoopFor(I->getParent()) == InnerLoop)
1454         continue;
1455 
1456       PHINode *NewPhi = dyn_cast<PHINode>(P.clone());
1457       NewPhi->setIncomingValue(0, P.getIncomingValue(0));
1458       NewPhi->setIncomingBlock(0, OuterLatch);
1459       NewPhi->insertBefore(InnerLatch->getFirstNonPHI());
1460       P.setIncomingValue(0, NewPhi);
1461     }
1462   }
1463 
1464   // Now adjust the incoming blocks for the LCSSA PHIs.
1465   // For PHIs moved from Inner's exit block, we need to replace Inner's latch
1466   // with the new latch.
1467   InnerLatch->replacePhiUsesWith(InnerLatch, OuterLatch);
1468 }
1469 
1470 bool LoopInterchangeTransform::adjustLoopBranches() {
1471   LLVM_DEBUG(dbgs() << "adjustLoopBranches called\n");
1472   std::vector<DominatorTree::UpdateType> DTUpdates;
1473 
1474   BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1475   BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1476 
1477   assert(OuterLoopPreHeader != OuterLoop->getHeader() &&
1478          InnerLoopPreHeader != InnerLoop->getHeader() && OuterLoopPreHeader &&
1479          InnerLoopPreHeader && "Guaranteed by loop-simplify form");
1480   // Ensure that both preheaders do not contain PHI nodes and have single
1481   // predecessors. This allows us to move them easily. We use
1482   // InsertPreHeaderForLoop to create an 'extra' preheader, if the existing
1483   // preheaders do not satisfy those conditions.
1484   if (isa<PHINode>(OuterLoopPreHeader->begin()) ||
1485       !OuterLoopPreHeader->getUniquePredecessor())
1486     OuterLoopPreHeader =
1487         InsertPreheaderForLoop(OuterLoop, DT, LI, nullptr, true);
1488   if (InnerLoopPreHeader == OuterLoop->getHeader())
1489     InnerLoopPreHeader =
1490         InsertPreheaderForLoop(InnerLoop, DT, LI, nullptr, true);
1491 
1492   // Adjust the loop preheader
1493   BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1494   BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1495   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1496   BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1497   BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1498   BasicBlock *InnerLoopLatchPredecessor =
1499       InnerLoopLatch->getUniquePredecessor();
1500   BasicBlock *InnerLoopLatchSuccessor;
1501   BasicBlock *OuterLoopLatchSuccessor;
1502 
1503   BranchInst *OuterLoopLatchBI =
1504       dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1505   BranchInst *InnerLoopLatchBI =
1506       dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1507   BranchInst *OuterLoopHeaderBI =
1508       dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1509   BranchInst *InnerLoopHeaderBI =
1510       dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1511 
1512   if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1513       !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1514       !InnerLoopHeaderBI)
1515     return false;
1516 
1517   BranchInst *InnerLoopLatchPredecessorBI =
1518       dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1519   BranchInst *OuterLoopPredecessorBI =
1520       dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1521 
1522   if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1523     return false;
1524   BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
1525   if (!InnerLoopHeaderSuccessor)
1526     return false;
1527 
1528   // Adjust Loop Preheader and headers.
1529   // The branches in the outer loop predecessor and the outer loop header can
1530   // be unconditional branches or conditional branches with duplicates. Consider
1531   // this when updating the successors.
1532   updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader,
1533                   InnerLoopPreHeader, DTUpdates, /*MustUpdateOnce=*/false);
1534   // The outer loop header might or might not branch to the outer latch.
1535   // We are guaranteed to branch to the inner loop preheader.
1536   if (llvm::is_contained(OuterLoopHeaderBI->successors(), OuterLoopLatch))
1537     updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates,
1538                     /*MustUpdateOnce=*/false);
1539   updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader,
1540                   InnerLoopHeaderSuccessor, DTUpdates,
1541                   /*MustUpdateOnce=*/false);
1542 
1543   // Adjust reduction PHI's now that the incoming block has changed.
1544   InnerLoopHeaderSuccessor->replacePhiUsesWith(InnerLoopHeader,
1545                                                OuterLoopHeader);
1546 
1547   updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor,
1548                   OuterLoopPreHeader, DTUpdates);
1549 
1550   // -------------Adjust loop latches-----------
1551   if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1552     InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1553   else
1554     InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1555 
1556   updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch,
1557                   InnerLoopLatchSuccessor, DTUpdates);
1558 
1559 
1560   if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1561     OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1562   else
1563     OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1564 
1565   updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor,
1566                   OuterLoopLatchSuccessor, DTUpdates);
1567   updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
1568                   DTUpdates);
1569 
1570   DT->applyUpdates(DTUpdates);
1571   restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
1572                    OuterLoopPreHeader);
1573 
1574   moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch,
1575                 OuterLoopHeader, OuterLoopLatch, InnerLoop->getExitBlock(),
1576                 InnerLoop, LI);
1577   // For PHIs in the exit block of the outer loop, outer's latch has been
1578   // replaced by Inners'.
1579   OuterLoopLatchSuccessor->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch);
1580 
1581   // Now update the reduction PHIs in the inner and outer loop headers.
1582   SmallVector<PHINode *, 4> InnerLoopPHIs, OuterLoopPHIs;
1583   for (PHINode &PHI : drop_begin(InnerLoopHeader->phis()))
1584     InnerLoopPHIs.push_back(cast<PHINode>(&PHI));
1585   for (PHINode &PHI : drop_begin(OuterLoopHeader->phis()))
1586     OuterLoopPHIs.push_back(cast<PHINode>(&PHI));
1587 
1588   auto &OuterInnerReductions = LIL.getOuterInnerReductions();
1589   (void)OuterInnerReductions;
1590 
1591   // Now move the remaining reduction PHIs from outer to inner loop header and
1592   // vice versa. The PHI nodes must be part of a reduction across the inner and
1593   // outer loop and all the remains to do is and updating the incoming blocks.
1594   for (PHINode *PHI : OuterLoopPHIs) {
1595     PHI->moveBefore(InnerLoopHeader->getFirstNonPHI());
1596     assert(OuterInnerReductions.count(PHI) && "Expected a reduction PHI node");
1597   }
1598   for (PHINode *PHI : InnerLoopPHIs) {
1599     PHI->moveBefore(OuterLoopHeader->getFirstNonPHI());
1600     assert(OuterInnerReductions.count(PHI) && "Expected a reduction PHI node");
1601   }
1602 
1603   // Update the incoming blocks for moved PHI nodes.
1604   OuterLoopHeader->replacePhiUsesWith(InnerLoopPreHeader, OuterLoopPreHeader);
1605   OuterLoopHeader->replacePhiUsesWith(InnerLoopLatch, OuterLoopLatch);
1606   InnerLoopHeader->replacePhiUsesWith(OuterLoopPreHeader, InnerLoopPreHeader);
1607   InnerLoopHeader->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch);
1608 
1609   // Values defined in the outer loop header could be used in the inner loop
1610   // latch. In that case, we need to create LCSSA phis for them, because after
1611   // interchanging they will be defined in the new inner loop and used in the
1612   // new outer loop.
1613   IRBuilder<> Builder(OuterLoopHeader->getContext());
1614   SmallVector<Instruction *, 4> MayNeedLCSSAPhis;
1615   for (Instruction &I :
1616        make_range(OuterLoopHeader->begin(), std::prev(OuterLoopHeader->end())))
1617     MayNeedLCSSAPhis.push_back(&I);
1618   formLCSSAForInstructions(MayNeedLCSSAPhis, *DT, *LI, SE, Builder);
1619 
1620   return true;
1621 }
1622 
1623 bool LoopInterchangeTransform::adjustLoopLinks() {
1624   // Adjust all branches in the inner and outer loop.
1625   bool Changed = adjustLoopBranches();
1626   if (Changed) {
1627     // We have interchanged the preheaders so we need to interchange the data in
1628     // the preheaders as well. This is because the content of the inner
1629     // preheader was previously executed inside the outer loop.
1630     BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1631     BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1632     swapBBContents(OuterLoopPreHeader, InnerLoopPreHeader);
1633   }
1634   return Changed;
1635 }
1636 
1637 /// Main LoopInterchange Pass.
1638 struct LoopInterchangeLegacyPass : public LoopPass {
1639   static char ID;
1640 
1641   LoopInterchangeLegacyPass() : LoopPass(ID) {
1642     initializeLoopInterchangeLegacyPassPass(*PassRegistry::getPassRegistry());
1643   }
1644 
1645   void getAnalysisUsage(AnalysisUsage &AU) const override {
1646     AU.addRequired<DependenceAnalysisWrapperPass>();
1647     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1648 
1649     getLoopAnalysisUsage(AU);
1650   }
1651 
1652   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
1653     if (skipLoop(L))
1654       return false;
1655 
1656     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1657     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1658     auto *DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
1659     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1660     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1661 
1662     return LoopInterchange(SE, LI, DI, DT, ORE).run(L);
1663   }
1664 };
1665 
1666 char LoopInterchangeLegacyPass::ID = 0;
1667 
1668 INITIALIZE_PASS_BEGIN(LoopInterchangeLegacyPass, "loop-interchange",
1669                       "Interchanges loops for cache reuse", false, false)
1670 INITIALIZE_PASS_DEPENDENCY(LoopPass)
1671 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
1672 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
1673 
1674 INITIALIZE_PASS_END(LoopInterchangeLegacyPass, "loop-interchange",
1675                     "Interchanges loops for cache reuse", false, false)
1676 
1677 Pass *llvm::createLoopInterchangePass() {
1678   return new LoopInterchangeLegacyPass();
1679 }
1680 
1681 PreservedAnalyses LoopInterchangePass::run(Loop &L, LoopAnalysisManager &AM,
1682                                            LoopStandardAnalysisResults &AR,
1683                                            LPMUpdater &U) {
1684   Function &F = *L.getHeader()->getParent();
1685 
1686   DependenceInfo DI(&F, &AR.AA, &AR.SE, &AR.LI);
1687   OptimizationRemarkEmitter ORE(&F);
1688   if (!LoopInterchange(&AR.SE, &AR.LI, &DI, &AR.DT, &ORE).run(&L))
1689     return PreservedAnalyses::all();
1690   return getLoopPassPreservedAnalyses();
1691 }
1692