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