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