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