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