LLVM 24.0.0git
LoopInterchange.cpp
Go to the documentation of this file.
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
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
30#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/Dominators.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/IRBuilder.h"
35#include "llvm/IR/InstrTypes.h"
36#include "llvm/IR/Instruction.h"
38#include "llvm/IR/User.h"
39#include "llvm/IR/Value.h"
40#include "llvm/IR/Verifier.h"
43#include "llvm/Support/Debug.h"
50#include <cassert>
51#include <cstdint>
52#include <utility>
53#include <vector>
54
55using namespace llvm;
56
57#define DEBUG_TYPE "loop-interchange"
58
59STATISTIC(LoopsInterchanged, "Number of loops interchanged");
60
62 "loop-interchange-threshold", cl::init(0), cl::Hidden,
63 cl::desc("Interchange if you gain more than this number"));
64
66 "loop-interchange-max-mem-instr-ratio", cl::init(4), cl::Hidden,
67 cl::desc("Maximum number of load/store instructions squared in relation to "
68 "the total number of instructions. Higher value may lead to more "
69 "interchanges at the cost of compile-time"));
70
71namespace {
72
74
75/// A list of direction vectors. Each entry represents a direction vector
76/// corresponding to one or more dependencies existing in the loop nest. The
77/// length of all direction vectors is equal and is N + 1, where N is the depth
78/// of the loop nest. The first N elements correspond to the dependency
79/// direction of each N loops. The last one indicates whether this entry is
80/// forward dependency ('<') or not ('*'). The term "forward" aligns with what
81/// is defined in LoopAccessAnalysis.
82// TODO: Check if we can use a sparse matrix here.
83using CharMatrix = std::vector<std::vector<char>>;
84
85/// Types of rules used in profitability check.
86enum class RuleTy {
87 PerLoopCacheAnalysis,
88 PerInstrOrderCost,
89 ForVectorization,
90 Ignore
91};
92
93} // end anonymous namespace
94
95// Minimum loop depth supported.
97 "loop-interchange-min-loop-nest-depth", cl::init(2), cl::Hidden,
98 cl::desc("Minimum depth of loop nest considered for the transform"));
99
100// Maximum loop depth supported.
102 "loop-interchange-max-loop-nest-depth", cl::init(10), cl::Hidden,
103 cl::desc("Maximum depth of loop nest considered for the transform"));
104
105// We prefer cache cost to vectorization by default.
107 "loop-interchange-profitabilities", cl::MiscFlags::CommaSeparated,
109 cl::desc("List of profitability heuristics to be used. They are applied in "
110 "the given order"),
111 cl::list_init<RuleTy>({RuleTy::PerInstrOrderCost,
112 RuleTy::ForVectorization}),
113 cl::values(clEnumValN(RuleTy::PerLoopCacheAnalysis, "cache",
114 "Prioritize loop cache cost"),
115 clEnumValN(RuleTy::PerInstrOrderCost, "instorder",
116 "Prioritize the IVs order of each instruction"),
117 clEnumValN(RuleTy::ForVectorization, "vectorize",
118 "Prioritize vectorization"),
119 clEnumValN(RuleTy::Ignore, "ignore",
120 "Ignore profitability, force interchange (does not "
121 "work with other options)")));
122
123// Support for the inner-loop reduction pattern.
125 "loop-interchange-reduction-to-mem", cl::init(false), cl::Hidden,
126 cl::desc("Support for the inner-loop reduction pattern."));
127
128#ifndef NDEBUG
131 for (RuleTy Rule : Rules) {
132 if (!Set.insert(Rule).second)
133 return false;
134 if (Rule == RuleTy::Ignore)
135 return false;
136 }
137 return true;
138}
139
140static void printDepMatrix(CharMatrix &DepMatrix) {
141 for (auto &Row : DepMatrix) {
142 // Drop the last element because it is a flag indicating whether this is
143 // forward dependency or not, which doesn't affect the legality check.
144 for (char D : drop_end(Row))
145 LLVM_DEBUG(dbgs() << D << " ");
146 LLVM_DEBUG(dbgs() << "\n");
147 }
148}
149
150/// Return true if \p Src appears before \p Dst in the same basic block.
151/// Precondition: \p Src and \Dst are distinct instructions within the same
152/// basic block.
153static bool inThisOrder(const Instruction *Src, const Instruction *Dst) {
154 assert(Src->getParent() == Dst->getParent() && Src != Dst &&
155 "Expected Src and Dst to be different instructions in the same BB");
156
157 bool FoundSrc = false;
158 for (const Instruction &I : *(Src->getParent())) {
159 if (&I == Src) {
160 FoundSrc = true;
161 continue;
162 }
163 if (&I == Dst)
164 return FoundSrc;
165 }
166
167 llvm_unreachable("Dst not found");
168}
169#endif
170
171static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level,
172 Loop *L, DependenceInfo *DI,
173 ScalarEvolution *SE,
176
177 ValueVector MemInstr;
178 unsigned NumInsts = 0;
179
180 // For each block.
181 for (BasicBlock *BB : L->blocks()) {
182 // Scan the BB and collect legal loads and stores.
183 for (Instruction &I : *BB) {
184 NumInsts++;
185 if (auto *Ld = dyn_cast<LoadInst>(&I)) {
186 if (!Ld->isSimple())
187 return false;
188 MemInstr.push_back(&I);
189 } else if (auto *St = dyn_cast<StoreInst>(&I)) {
190 if (!St->isSimple())
191 return false;
192 MemInstr.push_back(&I);
193 }
194 }
195 }
196
197 // To populate the dependence matrix, we perform dependence test for each pair
198 // of memory instructions, which has O(NumMemInstr^2) complexity. This implies
199 // that even if the number of memory instructions is small, the analysis can
200 // still be expensive if the most of the instructions in the loop are memory
201 // instructions. On the other hand, if the number of memory instructions is
202 // not small, but the loop is large (i.e., it contains many non-memory
203 // instructions), the analysis can still be affordable.
204 unsigned NumMemInstr = MemInstr.size();
205 LLVM_DEBUG(dbgs() << "Found " << NumMemInstr
206 << " Loads and Stores to analyze\n");
207 if (static_cast<uint64_t>(MaxMemInstrRatio) * NumInsts <
208 static_cast<uint64_t>(NumMemInstr) * NumMemInstr) {
209 ORE->emit([&]() {
210 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedLoop",
211 L->getStartLoc(), L->getHeader())
212 << "Number of loads/stores exceeded, the supported maximum can be "
213 "increased with option -loop-interchange-max-mem-instr-ratio.";
214 });
215 return false;
216 }
217 ValueVector::iterator I, IE, J, JE;
218
219 // Manage direction vectors that are already seen. Map each direction vector
220 // to an index of DepMatrix at which it is stored.
222
223 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
224 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
225 std::vector<char> Dep;
228 // Ignore Input dependencies.
229 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
230 continue;
231 // Track Output, Flow, and Anti dependencies.
232 if (auto D = DI->depends(Src, Dst)) {
233 assert(D->isOrdered() && "Expected an output, flow or anti dep.");
234 // If the direction vector is negative, normalize it to
235 // make it non-negative.
236 if (D->normalize(SE))
237 LLVM_DEBUG(dbgs() << "Negative dependence vector normalized.\n");
238 LLVM_DEBUG(StringRef DepType =
239 D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output";
240 dbgs() << "Found " << DepType
241 << " dependency between Src and Dst\n"
242 << " Src:" << *Src << "\n Dst:" << *Dst << '\n');
243 unsigned Levels = D->getLevels();
244 char Direction;
245 for (unsigned II = 1; II <= Levels; ++II) {
246 // `DVEntry::LE` is converted to `*`. This is because `LE` means `<`
247 // or `=`, for which we don't have an equivalent representation, so
248 // that the conservative approximation is necessary. The same goes for
249 // `DVEntry::GE`.
250 // TODO: Use of fine-grained expressions allows for more accurate
251 // analysis.
252 unsigned Dir = D->getDirection(II);
253 if (Dir == Dependence::DVEntry::LT)
254 Direction = '<';
255 else if (Dir == Dependence::DVEntry::GT)
256 Direction = '>';
257 else if (Dir == Dependence::DVEntry::EQ)
258 Direction = '=';
259 else
260 Direction = '*';
261 Dep.push_back(Direction);
262 }
263
264 // If the Dependence object doesn't have any information, fill the
265 // dependency vector with '*'.
266 if (D->isConfused()) {
267 assert(Dep.empty() && "Expected empty dependency vector");
268 Dep.assign(L->getLoopDepth() + Level - 1, '*');
269 }
270
271 while (Dep.size() < L->getLoopDepth() + Level - 1) {
272 Dep.push_back('I');
273 }
274
275 // Dependence analysis reports levels for the full enclosing loop nest.
276 // Keep only the suffix that corresponds to the selected perfect
277 // subnest.
278 if (Dep.size() > Level)
279 Dep.erase(Dep.begin(), Dep.end() - Level);
280
281 // If all the elements of any direction vector have only '*', legality
282 // can't be proven. Exit early to save compile time.
283 if (all_of(Dep, equal_to('*'))) {
284 ORE->emit([&]() {
285 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
286 L->getStartLoc(), L->getHeader())
287 << "All loops have dependencies in all directions.";
288 });
289 return false;
290 }
291
292 // Test whether the dependency is forward or not.
293 bool IsKnownForward = true;
294 if (Src->getParent() != Dst->getParent()) {
295 // In general, when Src and Dst are in different BBs, the execution
296 // order of them within a single iteration is not guaranteed. Treat
297 // conservatively as not-forward dependency in this case.
298 IsKnownForward = false;
299 } else {
300 // Src and Dst are in the same BB. If they are the different
301 // instructions, Src should appear before Dst in the BB as they are
302 // stored to MemInstr in that order.
303 assert((Src == Dst || inThisOrder(Src, Dst)) &&
304 "Unexpected instructions");
305
306 // If the Dependence object is reversed (due to normalization), it
307 // represents the dependency from Dst to Src, meaning it is a backward
308 // dependency. Otherwise it should be a forward dependency.
309 bool IsReversed = D->getSrc() != Src;
310 if (IsReversed)
311 IsKnownForward = false;
312 }
313
314 // Initialize the last element. Assume forward dependencies only; it
315 // will be updated later if there is any non-forward dependency.
316 Dep.push_back('<');
317
318 // The last element should express the "summary" among one or more
319 // direction vectors whose first N elements are the same (where N is
320 // the depth of the loop nest). Hence we exclude the last element from
321 // the Seen map.
322 auto [Ite, Inserted] = Seen.try_emplace(
323 StringRef(Dep.data(), Dep.size() - 1), DepMatrix.size());
324
325 // Make sure we only add unique entries to the dependency matrix.
326 if (Inserted)
327 DepMatrix.push_back(Dep);
328
329 // If we cannot prove that this dependency is forward, change the last
330 // element of the corresponding entry. Since a `[... *]` dependency
331 // includes a `[... <]` dependency, we do not need to keep both and
332 // change the existing entry instead.
333 if (!IsKnownForward)
334 DepMatrix[Ite->second].back() = '*';
335 }
336 }
337 }
338
339 return true;
340}
341
342// A loop is moved from index 'from' to an index 'to'. Update the Dependence
343// matrix by exchanging the two columns.
344static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx,
345 unsigned ToIndx) {
346 for (auto &Row : DepMatrix)
347 std::swap(Row[ToIndx], Row[FromIndx]);
348}
349
350// Check if a direction vector is lexicographically positive. Return true if it
351// is positive, nullopt if it is "zero", otherwise false.
352// [Theorem] A permutation of the loops in a perfect nest is legal if and only
353// if the direction matrix, after the same permutation is applied to its
354// columns, has no ">" direction as the leftmost non-"=" direction in any row.
355static std::optional<bool>
356isLexicographicallyPositive(ArrayRef<char> DV, unsigned Begin, unsigned End) {
357 for (unsigned char Direction : DV.slice(Begin, End - Begin)) {
358 if (Direction == '<')
359 return true;
360 if (Direction == '>' || Direction == '*')
361 return false;
362 }
363 return std::nullopt;
364}
365
366// Checks if it is legal to interchange 2 loops.
367static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
368 unsigned InnerLoopId,
369 unsigned OuterLoopId) {
370 unsigned NumRows = DepMatrix.size();
371 std::vector<char> Cur;
372 // For each row check if it is valid to interchange.
373 for (unsigned Row = 0; Row < NumRows; ++Row) {
374 // Create temporary DepVector check its lexicographical order
375 // before and after swapping OuterLoop vs InnerLoop
376 Cur = DepMatrix[Row];
377
378 // If the surrounding loops already ensure that the direction vector is
379 // lexicographically positive, nothing within the loop will be able to break
380 // the dependence. In such a case we can skip the subsequent check.
381 if (isLexicographicallyPositive(Cur, 0, OuterLoopId) == true)
382 continue;
383
384 // Check if the direction vector is lexicographically positive (or zero)
385 // for both before/after exchanged. Ignore the last element because it
386 // doesn't affect the legality.
387 if (isLexicographicallyPositive(Cur, OuterLoopId, Cur.size() - 1) == false)
388 return false;
389 std::swap(Cur[InnerLoopId], Cur[OuterLoopId]);
390 if (isLexicographicallyPositive(Cur, OuterLoopId, Cur.size() - 1) == false)
391 return false;
392 }
393 return true;
394}
395
396static void populateWorklist(Loop &L, LoopVector &LoopList) {
397 LLVM_DEBUG(dbgs() << "Calling populateWorklist on Func: "
398 << L.getHeader()->getParent()->getName() << " Loop: %"
399 << L.getHeader()->getName() << '\n');
400 assert(LoopList.empty() && "LoopList should initially be empty!");
401 Loop *CurrentLoop = &L;
402 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops();
403 while (!Vec->empty()) {
404 // The current loop has multiple subloops in it hence it is not tightly
405 // nested.
406 // Discard all loops above it added into Worklist.
407 if (Vec->size() != 1) {
408 LoopList = {};
409 return;
410 }
411
412 LoopList.push_back(CurrentLoop);
413 CurrentLoop = Vec->front();
414 Vec = &CurrentLoop->getSubLoops();
415 }
416 LoopList.push_back(CurrentLoop);
417}
418
421 unsigned LoopNestDepth = LoopList.size();
422 if (LoopNestDepth < MinLoopNestDepth || LoopNestDepth > MaxLoopNestDepth) {
423 LLVM_DEBUG(dbgs() << "Unsupported depth of loop nest " << LoopNestDepth
424 << ", the supported range is [" << MinLoopNestDepth
425 << ", " << MaxLoopNestDepth << "].\n");
426 Loop *OuterLoop = LoopList.front();
427 ORE.emit([&]() {
428 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedLoopNestDepth",
429 OuterLoop->getStartLoc(),
430 OuterLoop->getHeader())
431 << "Unsupported depth of loop nest, the supported range is ["
432 << std::to_string(MinLoopNestDepth) << ", "
433 << std::to_string(MaxLoopNestDepth) << "].\n";
434 });
435 return false;
436 }
437 return true;
438}
439
441 ArrayRef<Loop *> LoopList) {
442 for (Loop *L : LoopList) {
443 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
444 if (isa<SCEVCouldNotCompute>(ExitCountOuter)) {
445 LLVM_DEBUG(dbgs() << "Couldn't compute backedge count\n");
446 return false;
447 }
448 if (L->getNumBackEdges() != 1) {
449 LLVM_DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
450 return false;
451 }
452 if (!L->getExitingBlock()) {
453 LLVM_DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
454 return false;
455 }
456 }
457 return true;
458}
459
460namespace {
461
462/// LoopInterchangeLegality checks if it is legal to interchange the loop.
463class LoopInterchangeLegality {
464public:
465 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
466 OptimizationRemarkEmitter *ORE, DominatorTree *DT)
467 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), DT(DT), ORE(ORE) {}
468
469 /// Check if the loops can be interchanged.
470 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId,
471 CharMatrix &DepMatrix);
472
473 /// Check if the loop structure is understood. We do not handle triangular
474 /// loops for now.
475 bool isLoopStructureUnderstood();
476
477 bool currentLimitations();
478
479 const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions() const {
480 return OuterInnerReductions;
481 }
482
483 const ArrayRef<PHINode *> getInnerLoopInductions() const {
484 return InnerLoopInductions;
485 }
486
487 ArrayRef<Instruction *> getHasNoWrapReductions() const {
488 return HasNoWrapReductions;
489 }
490
491 ArrayRef<Instruction *> getHasNoInfInsts() const { return HasNoInfInsts; }
492
493 /// Record reductions in the inner loop. Currently supported reductions:
494 /// - initialized from a constant.
495 /// - reduction PHI node has only one user.
496 /// - located in the innermost loop.
497 struct InnerReduction {
498 /// The reduction itself.
499 PHINode *Reduction;
500 Value *Init;
501 Value *Next;
502 /// The Lcssa PHI.
503 PHINode *LcssaPhi;
504 /// Store reduction result into memory object.
505 StoreInst *LcssaStore;
506 /// The memory Location.
507 Value *MemRef;
508 Type *ElemTy;
509 };
510
511 ArrayRef<InnerReduction> getInnerReductions() const {
512 return InnerReductions;
513 }
514
515private:
516 bool tightlyNested(Loop *Outer, Loop *Inner);
517 bool containsUnsafeInstructions(BasicBlock *BB, Instruction *Skip);
518
519 /// Traverse all PHI nodes in the header of each loop in the loop nest
520 /// starting from \p OuterLoop, and perform the following checks:
521 ///
522 /// - Identify induction variables in the child loop of \p OuterLoop.
523 /// - Check for reductions across the inner loop and \p OuterLoop.
524 /// - Detect unsupported PHI nodes.
525 ///
526 /// Return false if any unsupported PHI node is found or if no induction
527 /// variable is found in the child loop of \p OuterLoop. Otherwise return
528 /// true.
529 bool checkInductionsAndReductions(Loop *OuterLoop);
530
531 /// Detect and record the reduction of the inner loop. Add them to
532 /// InnerReductions.
533 ///
534 /// innerloop:
535 /// Re = phi<0.0, Next>
536 /// Next = Re op ...
537 /// OuterLoopLatch:
538 /// Lcssa = phi<Next> ; lcssa phi
539 /// store Lcssa, MemRef ; LcssaStore
540 ///
541 bool isInnerReduction(Loop *L, PHINode *Phi,
542 SmallVectorImpl<Instruction *> &HasNoWrapInsts);
543
544 Loop *OuterLoop;
545 Loop *InnerLoop;
546
547 ScalarEvolution *SE;
548 DominatorTree *DT;
549
550 /// Interface to emit optimization remarks.
551 OptimizationRemarkEmitter *ORE;
552
553 /// Set of reduction PHIs taking part of a reduction across the inner and
554 /// outer loop.
555 SmallPtrSet<PHINode *, 4> OuterInnerReductions;
556
557 /// Set of inner loop induction PHIs
558 SmallVector<PHINode *, 8> InnerLoopInductions;
559
560 /// Hold instructions that have nuw/nsw flags and involved in reductions,
561 /// like integer addition/multiplication. Those flags must be dropped when
562 /// interchanging the loops.
563 SmallVector<Instruction *, 4> HasNoWrapReductions;
564
565 /// Hold instructions that have ninf flags and involved in reductions. Those
566 /// flags must be dropped when interchanging the loops.
567 SmallVector<Instruction *, 4> HasNoInfInsts;
568
569 /// Vector of reductions in the inner loop.
570 SmallVector<InnerReduction, 8> InnerReductions;
571};
572
573/// Manages information utilized by the profitability check for cache. The main
574/// purpose of this class is to delay the computation of CacheCost until it is
575/// actually needed.
576class CacheCostManager {
577 Loop *OutermostLoop;
578 LoopStandardAnalysisResults *AR;
579 DependenceInfo *DI;
580
581 /// CacheCost for \ref OutermostLoop. Once it is computed, it is cached. Note
582 /// that the result can be nullptr.
583 std::optional<std::unique_ptr<CacheCost>> CC;
584
585 /// Maps each loop to an index representing the optimal position within the
586 /// loop-nest, as determined by the cache cost analysis.
587 DenseMap<const Loop *, unsigned> CostMap;
588
589 void computeIfUnitinialized();
590
591public:
592 CacheCostManager(Loop *OutermostLoop, LoopStandardAnalysisResults *AR,
593 DependenceInfo *DI)
594 : OutermostLoop(OutermostLoop), AR(AR), DI(DI) {}
595 CacheCost *getCacheCost();
596 const DenseMap<const Loop *, unsigned> &getCostMap();
597};
598
599/// LoopInterchangeProfitability checks if it is profitable to interchange the
600/// loop.
601class LoopInterchangeProfitability {
602public:
603 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
604 OptimizationRemarkEmitter *ORE)
605 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
606
607 /// Check if the loop interchange is profitable.
608 bool isProfitable(const Loop *InnerLoop, const Loop *OuterLoop,
609 unsigned InnerLoopId, unsigned OuterLoopId,
610 CharMatrix &DepMatrix, CacheCostManager &CCM);
611
612private:
613 int getInstrOrderCost();
614 std::optional<bool> isProfitablePerLoopCacheAnalysis(
615 const DenseMap<const Loop *, unsigned> &CostMap, CacheCost *CC);
616 std::optional<bool> isProfitablePerInstrOrderCost();
617 std::optional<bool> isProfitableForVectorization(unsigned InnerLoopId,
618 unsigned OuterLoopId,
619 CharMatrix &DepMatrix);
620 Loop *OuterLoop;
621 Loop *InnerLoop;
622
623 /// Scev analysis.
624 ScalarEvolution *SE;
625
626 /// Interface to emit optimization remarks.
627 OptimizationRemarkEmitter *ORE;
628};
629
630/// LoopInterchangeTransform interchanges the loop.
631class LoopInterchangeTransform {
632public:
633 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
634 LoopInfo *LI, DominatorTree *DT,
635 const LoopInterchangeLegality &LIL)
636 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), LIL(LIL) {}
637
638 /// Interchange OuterLoop and InnerLoop.
639 void transform(ArrayRef<Instruction *> DropNoWrapInsts,
640 ArrayRef<Instruction *> DropNoInfInsts);
641 void reduction2Memory();
642 void restructureLoops(Loop *NewInner, Loop *NewOuter,
643 BasicBlock *OrigInnerPreHeader,
644 BasicBlock *OrigOuterPreHeader);
645 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
646
647private:
648 void adjustLoopBranches();
649
650 Loop *OuterLoop;
651 Loop *InnerLoop;
652
653 /// Scev analysis.
654 ScalarEvolution *SE;
655
656 LoopInfo *LI;
657 DominatorTree *DT;
658
659 const LoopInterchangeLegality &LIL;
660};
661
662struct LoopInterchange {
663 ScalarEvolution *SE = nullptr;
664 LoopInfo *LI = nullptr;
665 DependenceInfo *DI = nullptr;
666 DominatorTree *DT = nullptr;
667 LoopStandardAnalysisResults *AR = nullptr;
668
669 /// Interface to emit optimization remarks.
670 OptimizationRemarkEmitter *ORE;
671
672 LoopInterchange(ScalarEvolution *SE, LoopInfo *LI, DependenceInfo *DI,
673 DominatorTree *DT, LoopStandardAnalysisResults *AR,
674 OptimizationRemarkEmitter *ORE)
675 : SE(SE), LI(LI), DI(DI), DT(DT), AR(AR), ORE(ORE) {}
676
677 bool run(Loop *L) {
678 if (L->getParentLoop())
679 return false;
680 SmallVector<Loop *, 8> LoopList;
681 populateWorklist(*L, LoopList);
682 return processLoopList(LoopList);
683 }
684
685 /// Consider below kernel:
686 /// for(int i=0; i<n; i++){ // Loop 1
687 /// for(int j=0; j<m; j++){ // Loop 2
688 /// for(int r=0; r<m; r++){ // Loop 3
689 /// // Do something
690 /// }
691 /// }
692 /// for(int k=0; k<p; k++){ // Loop 4
693 /// for(int l=0; l<p; l++){ // Loop 5
694 /// // Do something
695 /// }
696 /// }
697 /// }
698 /// Then collectPerfectNests() will return:
699 /// - [Loop2, Loop3]
700 /// - [Loop4, Loop5]
702 collectPerfectNests(LoopNest &LN) {
704 for (Loop *L : LN.getLoops()) {
705 if (!L->isInnermost())
706 continue;
707
708 SmallVector<Loop *, 8> LoopList;
709 Loop *Current = L;
710 while (true) {
711 LoopList.push_back(Current);
712 Loop *Parent = Current->getParentLoop();
713 if (!Parent || Parent->getSubLoops().size() != 1)
714 break;
715 Current = Parent;
716 }
717 std::reverse(LoopList.begin(), LoopList.end());
718 if (LoopList.size() >= 2)
719 LoopLists.push_back(std::move(LoopList));
720 }
721 return LoopLists;
722 }
723
724 bool run(LoopNest &LN) {
725 SmallVector<SmallVector<Loop *, 8>, 4> LoopLists = collectPerfectNests(LN);
726 if (LoopLists.empty()) {
727 LLVM_DEBUG(dbgs() << "No Valid candidates for loop interchange.\n");
728 return false;
729 }
730 bool Changed = false;
731 for (SmallVector<Loop *, 8> &LoopList : LoopLists) {
732 // Ensure minimum depth of the loop nest to do the interchange.
733 if (!hasSupportedLoopDepth(LoopList, *ORE))
734 continue;
735 // Ensure computable loop nest.
736 if (!isComputableLoopNest(&AR->SE, LoopList)) {
737 LLVM_DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
738 continue;
739 }
740 Changed |= processLoopList(LoopList);
741 }
742 return Changed;
743 }
744
745 unsigned selectLoopForInterchange(ArrayRef<Loop *> LoopList) {
746 // TODO: Add a better heuristic to select the loop to be interchanged based
747 // on the dependence matrix. Currently we select the innermost loop.
748 return LoopList.size() - 1;
749 }
750
751 bool processLoopList(SmallVectorImpl<Loop *> &LoopList) {
752 bool Changed = false;
753
754 // Ensure proper loop nest depth.
755 assert(hasSupportedLoopDepth(LoopList, *ORE) &&
756 "Unsupported depth of loop nest.");
757
758 unsigned LoopNestDepth = LoopList.size();
759
760 LLVM_DEBUG({
761 dbgs() << "Processing LoopList of size = " << LoopNestDepth
762 << " containing the following loops:\n";
763 for (auto *L : LoopList) {
764 dbgs() << " - ";
765 L->print(dbgs());
766 }
767 });
768
769 CharMatrix DependencyMatrix;
770 Loop *OuterMostLoop = *(LoopList.begin());
771 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
772 OuterMostLoop, DI, SE, ORE)) {
773 LLVM_DEBUG(dbgs() << "Populating dependency matrix failed\n");
774 return false;
775 }
776
777 LLVM_DEBUG(dbgs() << "Dependency matrix before interchange:\n";
778 printDepMatrix(DependencyMatrix));
779
780 // Get the Outermost loop exit.
781 BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock();
782 if (!LoopNestExit) {
783 LLVM_DEBUG(dbgs() << "OuterMostLoop '" << OuterMostLoop->getName()
784 << "' needs an unique exit block");
785 return false;
786 }
787
788 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
789 CacheCostManager CCM(LoopList[0], AR, DI);
790 // We try to achieve the globally optimal memory access for the loopnest,
791 // and do interchange based on a bubble-sort fasion. We start from
792 // the innermost loop, move it outwards to the best possible position
793 // and repeat this process.
794 for (unsigned j = SelecLoopId; j > 0; j--) {
795 bool ChangedPerIter = false;
796 for (unsigned i = SelecLoopId; i > SelecLoopId - j; i--) {
797 bool Interchanged =
798 processLoop(LoopList, i, i - 1, DependencyMatrix, CCM);
799 ChangedPerIter |= Interchanged;
800 Changed |= Interchanged;
801 }
802 // Early abort if there was no interchange during an entire round of
803 // moving loops outwards.
804 if (!ChangedPerIter)
805 break;
806 }
807 return Changed;
808 }
809
810 bool processLoop(SmallVectorImpl<Loop *> &LoopList, unsigned InnerLoopId,
811 unsigned OuterLoopId,
812 std::vector<std::vector<char>> &DependencyMatrix,
813 CacheCostManager &CCM) {
814 Loop *OuterLoop = LoopList[OuterLoopId];
815 Loop *InnerLoop = LoopList[InnerLoopId];
816 LLVM_DEBUG(dbgs() << "Processing InnerLoopId = " << InnerLoopId
817 << " and OuterLoopId = " << OuterLoopId << "\n");
818 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE, DT);
819 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
820 LLVM_DEBUG(dbgs() << "Cannot prove legality, not interchanging loops '"
821 << OuterLoop->getName() << "' and '"
822 << InnerLoop->getName() << "'\n");
823 return false;
824 }
825 LLVM_DEBUG(dbgs() << "Loops '" << OuterLoop->getName() << "' and '"
826 << InnerLoop->getName()
827 << "' are legal to interchange\n");
828 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
829 if (!LIP.isProfitable(InnerLoop, OuterLoop, InnerLoopId, OuterLoopId,
830 DependencyMatrix, CCM)) {
831 LLVM_DEBUG(dbgs() << "Interchanging loops '" << OuterLoop->getName()
832 << "' and '" << InnerLoop->getName()
833 << "' not profitable.\n");
834 return false;
835 }
836
837 ORE->emit([&]() {
838 return OptimizationRemark(DEBUG_TYPE, "Interchanged",
839 InnerLoop->getStartLoc(),
840 InnerLoop->getHeader())
841 << "Loop interchanged with enclosing loop.";
842 });
843
844 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LIL);
845 LIT.transform(LIL.getHasNoWrapReductions(), LIL.getHasNoInfInsts());
846 LLVM_DEBUG(dbgs() << "Loops interchanged: outer loop '"
847 << OuterLoop->getName() << "' and inner loop '"
848 << InnerLoop->getName() << "'\n");
849 LoopsInterchanged++;
850
851 llvm::formLCSSARecursively(*OuterLoop, *DT, LI, SE);
852
853 // Loops interchanged, update LoopList accordingly.
854 std::swap(LoopList[OuterLoopId], LoopList[InnerLoopId]);
855 // Update the DependencyMatrix
856 interChangeDependencies(DependencyMatrix, InnerLoopId, OuterLoopId);
857
858 LLVM_DEBUG(dbgs() << "Dependency matrix after interchange:\n";
859 printDepMatrix(DependencyMatrix));
860
861 return true;
862 }
863};
864
865} // end anonymous namespace
866
867bool LoopInterchangeLegality::containsUnsafeInstructions(BasicBlock *BB,
868 Instruction *Skip) {
869 return any_of(*BB, [Skip](const Instruction &I) {
870 if (&I == Skip)
871 return false;
872 return I.mayHaveSideEffects() || I.mayReadFromMemory();
873 });
874}
875
877 Loop *InnerLoop) {
878 // adjustLoopBranches swaps the preheader bodies after changing their loop
879 // roles, so the original outer-preheader body remains outside the new outer
880 // loop and retains its execution count.
881 BasicBlock *Blocks[] = {
882 OuterLoop->getHeader(),
883 OuterLoop->getLoopLatch(),
884 InnerLoop->getLoopPreheader(),
885 InnerLoop->getExitBlock(),
886 };
887 for (BasicBlock *BB : Blocks)
888 if (BB)
889 for (Instruction &I : *BB)
890 if (auto *Freeze = dyn_cast<FreezeInst>(&I))
891 return Freeze;
892 return nullptr;
893}
894
895static FreezeInst *
897 ArrayRef<PHINode *> InnerLoopInductions) {
898 // Mirror the latch-condition and induction-update operand closure cloned by
899 // MoveInstructions in LoopInterchangeTransform::transform.
901 auto IsDirectInnerLoopBlock = [InnerLoop](BasicBlock *BB) {
902 return InnerLoop->contains(BB) &&
903 none_of(InnerLoop->getSubLoops(),
904 [BB](Loop *SubLoop) { return SubLoop->contains(BB); });
905 };
906 auto *LatchBranch =
908 if (LatchBranch)
909 if (auto *Condition = dyn_cast<Instruction>(LatchBranch->getCondition()))
910 Worklist.insert(Condition);
911
912 for (PHINode *Induction : InnerLoopInductions) {
913 auto *Incoming = dyn_cast<Instruction>(
914 Induction->getIncomingValueForBlock(InnerLoop->getLoopLatch()));
915 if (Incoming && !is_contained(InnerLoopInductions, Incoming))
916 Worklist.insert(Incoming);
917 }
918
919 for (unsigned I = 0; I < Worklist.size(); ++I) {
920 Instruction *Current = Worklist[I];
921 if (auto *Freeze = dyn_cast<FreezeInst>(Current))
922 return Freeze;
923 for (Value *Operand : Current->operands()) {
924 auto *OperandI = dyn_cast<Instruction>(Operand);
925 if (!OperandI || !IsDirectInnerLoopBlock(OperandI->getParent()) ||
926 is_contained(InnerLoopInductions, OperandI))
927 continue;
928 Worklist.insert(OperandI);
929 }
930 }
931 return nullptr;
932}
933
934bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
935 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
936 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
937 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
938
939 LLVM_DEBUG(dbgs() << "Checking if loops '" << OuterLoop->getName()
940 << "' and '" << InnerLoop->getName()
941 << "' are tightly nested\n");
942
943 // In a perfectly nested loop the outer header branches only into the inner
944 // loop. If it can also reach the outer latch, it conditionally guards the
945 // inner loop (an imperfect nest), so the inner loop runs on only a subset of
946 // the outer iterations. Interchanging such a nest would run the inner loop on
947 // every outer iteration, including the guarded-off ones, which is illegal
948 // when the inner loop relies on the guard to terminate (e.g. an eq/ne exit
949 // whose trip count is degenerate once the guard is false). Reject by allowing
950 // the outer header to branch only into the inner loop.
951 //
952 // TODO: This is conservative. A guarded nest is still safe to interchange
953 // when the inner loop has a computable trip count that is empty exactly when
954 // the guard is false, e.g.:
955 // for (i = 0; i < N; i++)
956 // if (M > 0) // loop-invariant guard
957 // for (j = 0; j < M; j++) // empty when M <= 0
958 // A[j][i] = ...;
959 // Interchanging is legal here because the inner loop runs zero times on the
960 // guarded-off iterations.
961 for (BasicBlock *Succ : successors(OuterLoopHeader))
962 if (Succ != InnerLoopPreHeader && Succ != InnerLoop->getHeader())
963 return false;
964
965 LLVM_DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
966
967 // The inner loop reduction pattern requires storing the LCSSA PHI in
968 // the OuterLoop Latch. Therefore, when reduction2Memory is enabled, skip
969 // that store during checks.
970 Instruction *Skip = nullptr;
971 assert(InnerReductions.size() <= 1 &&
972 "So far we only support at most one reduction.");
973 if (InnerReductions.size() == 1)
974 Skip = InnerReductions[0].LcssaStore;
975
976 // We do not have any basic block in between now make sure the outer header
977 // and outer loop latch doesn't contain any unsafe instructions.
978 if (containsUnsafeInstructions(OuterLoopHeader, Skip) ||
979 containsUnsafeInstructions(OuterLoopLatch, Skip))
980 return false;
981
982 // Also make sure the inner loop preheader does not contain any unsafe
983 // instructions. Note that all instructions in the preheader will be moved to
984 // the outer loop header when interchanging.
985 if (InnerLoopPreHeader != OuterLoopHeader &&
986 containsUnsafeInstructions(InnerLoopPreHeader, Skip))
987 return false;
988
989 BasicBlock *InnerLoopExit = InnerLoop->getExitBlock();
990 // Ensure the inner loop exit block flows to the outer loop latch possibly
991 // through empty blocks.
992 const BasicBlock &SuccInner =
993 LoopNest::skipEmptyBlockUntil(InnerLoopExit, OuterLoopLatch);
994 if (&SuccInner != OuterLoopLatch) {
995 LLVM_DEBUG(dbgs() << "Inner loop exit block " << *InnerLoopExit
996 << " does not lead to the outer loop latch.\n";);
997 return false;
998 }
999 // The inner loop exit block does flow to the outer loop latch and not some
1000 // other BBs, now make sure it contains safe instructions, since it will be
1001 // moved into the (new) inner loop after interchange.
1002 if (containsUnsafeInstructions(InnerLoopExit, Skip))
1003 return false;
1004
1005 LLVM_DEBUG(dbgs() << "Loops are perfectly nested\n");
1006 // We have a perfect loop nest.
1007 return true;
1008}
1009
1010bool LoopInterchangeLegality::isLoopStructureUnderstood() {
1011 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
1012 for (PHINode *InnerInduction : InnerLoopInductions) {
1013 unsigned Num = InnerInduction->getNumOperands();
1014 for (unsigned i = 0; i < Num; ++i) {
1015 Value *Val = InnerInduction->getOperand(i);
1016 if (isa<Constant>(Val))
1017 continue;
1019 if (!I)
1020 return false;
1021 // TODO: Handle triangular loops.
1022 // e.g. for(int i=0;i<N;i++)
1023 // for(int j=i;j<N;j++)
1024 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
1025 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
1026 InnerLoopPreheader &&
1027 !OuterLoop->isLoopInvariant(I)) {
1028 return false;
1029 }
1030 }
1031 }
1032
1033 // TODO: Handle triangular loops of another form.
1034 // e.g. for(int i=0;i<N;i++)
1035 // for(int j=0;j<i;j++)
1036 // or,
1037 // for(int i=0;i<N;i++)
1038 // for(int j=0;j*i<N;j++)
1039 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1040 CondBrInst *InnerLoopLatchBI =
1041 dyn_cast<CondBrInst>(InnerLoopLatch->getTerminator());
1042 if (!InnerLoopLatchBI)
1043 return false;
1044
1045 CmpInst *InnerLoopCmp = dyn_cast<CmpInst>(InnerLoopLatchBI->getCondition());
1046 if (!InnerLoopCmp)
1047 return false;
1048
1049 Value *Op0 = InnerLoopCmp->getOperand(0);
1050 Value *Op1 = InnerLoopCmp->getOperand(1);
1051
1052 // LHS and RHS of the inner loop exit condition, e.g.,
1053 // in "for(int j=0;j<i;j++)", LHS is j and RHS is i.
1054 Value *Left = nullptr;
1055 Value *Right = nullptr;
1056
1057 // Check if V only involves inner loop induction variable.
1058 // Return true if V is InnerInduction, or a cast from
1059 // InnerInduction, or a binary operator that involves
1060 // InnerInduction and a constant.
1061 std::function<bool(Value *)> IsPathToInnerIndVar;
1062 IsPathToInnerIndVar = [this, &IsPathToInnerIndVar](const Value *V) -> bool {
1063 if (llvm::is_contained(InnerLoopInductions, V))
1064 return true;
1065 if (isa<Constant>(V))
1066 return true;
1068 if (!I)
1069 return false;
1070 if (isa<CastInst>(I))
1071 return IsPathToInnerIndVar(I->getOperand(0));
1073 return IsPathToInnerIndVar(I->getOperand(0)) &&
1074 IsPathToInnerIndVar(I->getOperand(1));
1075 return false;
1076 };
1077
1078 // In case of multiple inner loop indvars, it is okay if LHS and RHS
1079 // are both inner indvar related variables.
1080 if (IsPathToInnerIndVar(Op0) && IsPathToInnerIndVar(Op1))
1081 return true;
1082
1083 // Otherwise we check if the cmp instruction compares an inner indvar
1084 // related variable (Left) with a outer loop invariant (Right).
1085 if (IsPathToInnerIndVar(Op0) && !isa<Constant>(Op0)) {
1086 Left = Op0;
1087 Right = Op1;
1088 } else if (IsPathToInnerIndVar(Op1) && !isa<Constant>(Op1)) {
1089 Left = Op1;
1090 Right = Op0;
1091 }
1092
1093 if (Left == nullptr)
1094 return false;
1095
1096 const SCEV *S = SE->getSCEV(Right);
1097 if (!SE->isLoopInvariant(S, OuterLoop))
1098 return false;
1099
1100 return true;
1101}
1102
1103// If SV is a LCSSA PHI node with a single incoming value, return the incoming
1104// value.
1107 if (!PHI)
1108 return SV;
1109
1110 if (PHI->getNumIncomingValues() != 1)
1111 return SV;
1112 return followLCSSA(PHI->getIncomingValue(0));
1113}
1114
1116 SmallVectorImpl<Instruction *> &HasNoWrapInsts,
1117 SmallVectorImpl<Instruction *> &HasNoInfInsts) {
1120 // Detect floating point reduction only when it can be reordered.
1121 if (RD.getExactFPMathInst() != nullptr)
1122 return false;
1123
1124 // The extra uses of a reduction phi outside of its reduction chain make
1125 // the order in which the elements are visited observable.
1127 return false;
1128
1129 RecurKind RK = RD.getRecurrenceKind();
1130 switch (RK) {
1131 case RecurKind::Or:
1132 case RecurKind::And:
1133 case RecurKind::Xor:
1134 case RecurKind::SMin:
1135 case RecurKind::SMax:
1136 case RecurKind::UMin:
1137 case RecurKind::UMax:
1138 return true;
1139
1140 // Interchanging the loops that contain AnyOf reduction is not always legal.
1141 // Especially, when the result value of the AnyOf is not loop-invariant with
1142 // respect to the outer loop, interchanging may change the semantics. The
1143 // following is an example of such case:
1144 // int A = {{ 1, 0 }, { 0, 1 }};
1145 // int red = 0;
1146 // for (int i = 0; i < 2; i++)
1147 // for (int j = 0; j < 2; j++)
1148 // red = (A[j][i] == 0) ? i + 1 : red;
1149 //
1150 // TODO: We may be able to support interchanging loops with AnyOf reduction
1151 // by checking the operand of the reduction is loop-invariant with respect
1152 // to the outer loop as well.
1153 case RecurKind::AnyOf:
1154 return false;
1155
1156 // Changing the order of floating-point operations may alter the results. If
1157 // a certain instruction has the ninf flag, it means that reordering can
1158 // produce a poison value, which may lead to undefined behavior. To prevent
1159 // this, we must drop the ninf flags if we decide to apply the
1160 // transformation.
1161 case RecurKind::FAdd:
1162 case RecurKind::FMul:
1163 case RecurKind::FMin:
1164 case RecurKind::FMax:
1169 case RecurKind::FMulAdd:
1170 for (Instruction *I : RD.getReductionOpChain(PHI, L))
1171 if (isa<FPMathOperator>(I) && I->hasNoInfs())
1172 HasNoInfInsts.push_back(I);
1173 return true;
1174
1175 // Change the order of integer addition/multiplication may change the
1176 // semantics. Consider the following case:
1177 //
1178 // int A[2][2] = {{ INT_MAX, INT_MAX }, { INT_MIN, INT_MIN }};
1179 // int sum = 0;
1180 // for (int i = 0; i < 2; i++)
1181 // for (int j = 0; j < 2; j++)
1182 // sum += A[j][i];
1183 //
1184 // If the above loops are exchanged, the addition will cause an
1185 // overflow. To prevent this, we must drop the nuw/nsw flags from the
1186 // addition/multiplication instructions when we actually exchanges the
1187 // loops.
1188 case RecurKind::Add:
1189 case RecurKind::Mul: {
1190 unsigned OpCode = RecurrenceDescriptor::getOpcode(RK);
1192
1193 // Bail out when we fail to collect reduction instructions chain.
1194 if (Ops.empty())
1195 return false;
1196
1197 for (Instruction *I : Ops) {
1198 assert(I->getOpcode() == OpCode &&
1199 "Expected the instruction to be the reduction operation");
1200 (void)OpCode;
1201
1202 // If the instruction has nuw/nsw flags, we must drop them when the
1203 // transformation is actually performed.
1204 if (I->hasNoSignedWrap() || I->hasNoUnsignedWrap())
1205 HasNoWrapInsts.push_back(I);
1206 }
1207 return true;
1208 }
1209
1210 default:
1211 return false;
1212 }
1213 } else
1214 return false;
1215}
1216
1217// Check V's users to see if it is involved in a reduction in L.
1218static PHINode *
1220 SmallVectorImpl<Instruction *> &HasNoWrapInsts,
1221 SmallVectorImpl<Instruction *> &HasNoInfInsts) {
1222 // Reduction variables cannot be constants.
1223 if (isa<Constant>(V))
1224 return nullptr;
1225
1226 for (Value *User : V->users()) {
1228 if (PHI->getNumIncomingValues() == 1)
1229 continue;
1230
1231 if (checkReductionKind(L, PHI, HasNoWrapInsts, HasNoInfInsts))
1232 return PHI;
1233 else
1234 return nullptr;
1235 }
1236 }
1237
1238 return nullptr;
1239}
1240
1241bool LoopInterchangeLegality::isInnerReduction(
1242 Loop *L, PHINode *Phi, SmallVectorImpl<Instruction *> &HasNoWrapInsts) {
1243
1244 // Only support reduction2Mem when the loop nest to be interchanged is
1245 // the innermost two loops.
1246 if (!L->isInnermost()) {
1247 LLVM_DEBUG(dbgs() << "Only supported when the loop is the innermost.\n");
1248 ORE->emit([&]() {
1249 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerReduction",
1250 L->getStartLoc(), L->getHeader())
1251 << "Only supported when the loop is the innermost.";
1252 });
1253 return false;
1254 }
1255
1256 if (Phi->getNumIncomingValues() != 2)
1257 return false;
1258
1259 Value *Init = Phi->getIncomingValueForBlock(L->getLoopPreheader());
1260 Value *Next = Phi->getIncomingValueForBlock(L->getLoopLatch());
1261
1262 // So far only supports constant initial value.
1263 if (!isa<Constant>(Init)) {
1264 LLVM_DEBUG(
1265 dbgs()
1266 << "Only supported for the reduction with a constant initial value.\n");
1267 ORE->emit([&]() {
1268 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerReduction",
1269 L->getStartLoc(), L->getHeader())
1270 << "Only supported for the reduction with a constant initial "
1271 "value.";
1272 });
1273 return false;
1274 }
1275
1276 // The reduction result must live in the inner loop.
1277 if (Instruction *I = dyn_cast<Instruction>(Next)) {
1278 BasicBlock *BB = I->getParent();
1279 if (!L->contains(BB))
1280 return false;
1281 }
1282
1283 // The reduction should have only one user.
1284 if (!Phi->hasOneUser())
1285 return false;
1286
1287 // Check the reduction kind.
1288 if (!checkReductionKind(L, Phi, HasNoWrapInsts, HasNoInfInsts))
1289 return false;
1290
1291 // Find lcssa_phi in OuterLoop's Latch
1292 BasicBlock *ExitBlock = L->getExitBlock();
1293 if (!ExitBlock)
1294 return false;
1295
1296 PHINode *Lcssa = NULL;
1297 for (auto *U : Next->users()) {
1298 if (auto *P = dyn_cast<PHINode>(U)) {
1299 if (P == Phi)
1300 continue;
1301
1302 if (Lcssa == NULL && P->getParent() == ExitBlock &&
1303 P->getIncomingValueForBlock(L->getLoopLatch()) == Next)
1304 Lcssa = P;
1305 else
1306 return false;
1307 } else
1308 return false;
1309 }
1310 if (!Lcssa)
1311 return false;
1312
1313 if (!Lcssa->hasOneUser()) {
1314 LLVM_DEBUG(dbgs() << "Only supported when the reduction is used once in "
1315 "the outer loop.\n");
1316 ORE->emit([&]() {
1317 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerReduction",
1318 L->getStartLoc(), L->getHeader())
1319 << "Only supported when the reduction is used once in the outer "
1320 "loop.";
1321 });
1322 return false;
1323 }
1324
1325 StoreInst *LcssaStore =
1327 if (!LcssaStore || LcssaStore->getParent() != ExitBlock)
1328 return false;
1329
1330 Value *MemRef = LcssaStore->getOperand(1);
1331 Type *ElemTy = LcssaStore->getOperand(0)->getType();
1332
1333 // LcssaStore stores the reduction result in BB.
1334 // When the reduction is initialized from a constant value, we need to load
1335 // from the memory object into the target basic block of the inner loop. This
1336 // means the memory reference was used prematurely. So we must ensure that the
1337 // memory reference does not dominate the target basic block.
1338 // TODO: Move the memory reference definition into the loop header.
1339 if (!DT->dominates(dyn_cast<Instruction>(MemRef), L->getHeader())) {
1340 LLVM_DEBUG(dbgs() << "Only supported when memory reference dominate "
1341 "the inner loop.\n");
1342 ORE->emit([&]() {
1343 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerReduction",
1344 L->getStartLoc(), L->getHeader())
1345 << "Only supported when memory reference dominate the inner "
1346 "loop.";
1347 });
1348 return false;
1349 }
1350
1351 // Found a reduction in the inner loop.
1352 InnerReduction SR;
1353 SR.Reduction = Phi;
1354 SR.Init = Init;
1355 SR.Next = Next;
1356 SR.LcssaPhi = Lcssa;
1357 SR.LcssaStore = LcssaStore;
1358 SR.MemRef = MemRef;
1359 SR.ElemTy = ElemTy;
1360
1361 InnerReductions.push_back(SR);
1362 return true;
1363}
1364
1365bool LoopInterchangeLegality::checkInductionsAndReductions(Loop *OuterLoop) {
1366 auto ChildLoop = [](Loop *L) {
1367 assert(L->getSubLoops().size() <= 1 &&
1368 "Expect at most one child loop for now.");
1369 return L->getSubLoops().empty() ? nullptr : L->getSubLoops().front();
1370 };
1371
1372 Loop *InnerLoop = ChildLoop(OuterLoop);
1373 for (Loop *CurLoop = OuterLoop; CurLoop; CurLoop = ChildLoop(CurLoop)) {
1374 for (PHINode &PHI : CurLoop->getHeader()->phis()) {
1375 InductionDescriptor ID;
1376 if (InductionDescriptor::isInductionPHI(&PHI, CurLoop, SE, ID)) {
1377 if (CurLoop == InnerLoop) {
1378 const SCEV *Step = ID.getStep();
1379 if (!SE->isLoopInvariant(Step, OuterLoop))
1380 return false;
1381 InnerLoopInductions.push_back(&PHI);
1382 }
1383 continue;
1384 }
1385
1386 if (CurLoop == OuterLoop) {
1387 // PHIs in inner loops need to be part of a reduction in the outer loop,
1388 if (PHI.getNumIncomingValues() != 2) {
1389 LLVM_DEBUG(dbgs() << "Only PHI nodes in the outer loop header with 2 "
1390 "incoming values are supported.\n");
1391 return false;
1392 }
1393 // Check if we have a PHI node in the outer loop that has a reduction
1394 // result from the inner loop as an incoming value.
1395 Value *V = followLCSSA(
1396 PHI.getIncomingValueForBlock(OuterLoop->getLoopLatch()));
1397 PHINode *InnerRedPhi = findInnerReductionPhi(
1398 InnerLoop, V, HasNoWrapReductions, HasNoInfInsts);
1399
1400 // Reject if PHI has users other than InnerRedPhi. The typical case is
1401 // as follows:
1402 //
1403 // o.header:
1404 // %red.o = phi [ 0, ... ], [ %red.next, %o.latch ]
1405 // br label %i.header
1406 //
1407 // i.header:
1408 // %red.i = phi [ %red.o, %o.header ], [ %red.next, %i.latch ]
1409 // br label %i.body
1410 //
1411 // i.body:
1412 // store %red.o to %mem
1413 // ...
1414 //
1415 if (!InnerRedPhi ||
1416 !llvm::is_contained(InnerRedPhi->incoming_values(), &PHI) ||
1417 !all_of(PHI.users(),
1418 [InnerRedPhi](User *U) { return U == InnerRedPhi; })) {
1419 LLVM_DEBUG(
1420 dbgs()
1421 << "Failed to recognize PHI as an induction or reduction.\n");
1422 ORE->emit([&]() {
1423 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter",
1424 OuterLoop->getStartLoc(),
1425 OuterLoop->getHeader())
1426 << "Only outer loops with induction or reduction PHI nodes "
1427 "can be interchanged currently.";
1428 });
1429 return false;
1430 }
1431
1432 OuterInnerReductions.insert(&PHI);
1433 OuterInnerReductions.insert(InnerRedPhi);
1434 } else {
1435 if (OuterInnerReductions.count(&PHI)) {
1436 LLVM_DEBUG(dbgs() << "Found a reduction across the outer loop.\n");
1437 } else if (EnableReduction2Memory &&
1438 isInnerReduction(CurLoop, &PHI, HasNoWrapReductions)) {
1439 LLVM_DEBUG(dbgs() << "Found a reduction in the inner loop: \n"
1440 << PHI << '\n');
1441 } else {
1442 ORE->emit([&]() {
1443 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner",
1444 CurLoop->getStartLoc(),
1445 CurLoop->getHeader())
1446 << "Only inner loops with induction or reduction PHI nodes "
1447 "can be interchanged currently.";
1448 });
1449 return false;
1450 }
1451 }
1452 }
1453
1454 // For now we only support at most one reduction.
1455 if (InnerReductions.size() > 1) {
1456 LLVM_DEBUG(dbgs() << "Only supports at most one reduction.\n");
1457 ORE->emit([&]() {
1458 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerReduction",
1459 CurLoop->getStartLoc(),
1460 CurLoop->getHeader())
1461 << "Only supports at most one reduction.";
1462 });
1463 return false;
1464 }
1465 }
1466
1467 return !InnerLoopInductions.empty();
1468}
1469
1470// This function indicates the current limitations in the transform as a result
1471// of which we do not proceed.
1472bool LoopInterchangeLegality::currentLimitations() {
1473 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1474
1475 // transform currently expects the loop latches to also be the exiting
1476 // blocks.
1477 if (InnerLoop->getExitingBlock() != InnerLoopLatch ||
1478 OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() ||
1479 !isa<CondBrInst>(InnerLoopLatch->getTerminator()) ||
1480 !isa<CondBrInst>(OuterLoop->getLoopLatch()->getTerminator())) {
1481 LLVM_DEBUG(
1482 dbgs() << "Loops where the latch is not the exiting block are not"
1483 << " supported currently.\n");
1484 ORE->emit([&]() {
1485 return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch",
1486 OuterLoop->getStartLoc(),
1487 OuterLoop->getHeader())
1488 << "Loops where the latch is not the exiting block cannot be"
1489 " interchange currently.";
1490 });
1491 return true;
1492 }
1493
1494 // TODO: Triangular loops are not handled for now.
1495 if (!isLoopStructureUnderstood()) {
1496 LLVM_DEBUG(dbgs() << "Loop structure not understood by pass\n");
1497 ORE->emit([&]() {
1498 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner",
1499 InnerLoop->getStartLoc(),
1500 InnerLoop->getHeader())
1501 << "Inner loop structure not understood currently.";
1502 });
1503 return true;
1504 }
1505
1506 // Currently, we do not support loops that have a predecessor entering the
1507 // loop via an indirectbr.
1508 for (Loop *L : {OuterLoop, InnerLoop}) {
1509 BasicBlock *Header = L->getHeader();
1510 for (BasicBlock *Pred : predecessors(Header)) {
1511 if (L->contains(Pred))
1512 continue;
1513 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1514 LLVM_DEBUG(
1515 dbgs() << "Indirect branch found in the loop predecessor.\n");
1516 ORE->emit([&]() {
1517 return OptimizationRemarkMissed(DEBUG_TYPE, "IndirectBranchPreheader",
1518 L->getStartLoc(), L->getHeader())
1519 << "Indirect branch found in the loop predecessor.";
1520 });
1521 return true;
1522 }
1523 }
1524 }
1525
1526 // Currently, we do not support loops where the inner loop header has
1527 // duplicate successors.
1528 SmallPtrSet<BasicBlock *, 2> InnerLoopHeaderSuccs;
1529 for (BasicBlock *Succ : successors(InnerLoop->getHeader()))
1530 if (!InnerLoopHeaderSuccs.insert(Succ).second)
1531 return true;
1532
1533 return false;
1534}
1535
1536/// We currently only support LCSSA PHI nodes in the inner loop exit if their
1537/// users are either of the following:
1538///
1539/// - Reduction PHIs
1540/// - PHIs outside the outer loop
1541/// - PHIs belonging to the latch of the outer loop
1542///
1543/// These conditions mean that we are only interested in the final value after
1544/// the inner loop.
1545static bool
1548 PHINode *LcssaReduction) {
1549 BasicBlock *InnerExit = InnerL->getUniqueExitBlock();
1550 for (PHINode &PHI : InnerExit->phis()) {
1551 // The reduction LCSSA PHI will have only one incoming block, which comes
1552 // from the loop latch.
1553 if (PHI.getNumIncomingValues() > 1)
1554 return false;
1555 // The reduction LCSSA PHI's store user is rewritten by reduction2Memory();
1556 // skip its user-check but keep validating the remaining LCSSA PHIs.
1557 if (&PHI == LcssaReduction)
1558 continue;
1559 if (any_of(PHI.users(), [&Reductions, OuterL](User *U) {
1560 PHINode *PN = dyn_cast<PHINode>(U);
1561 if (!PN)
1562 return true;
1563 if (Reductions.count(PN))
1564 return false;
1565 BasicBlock *PB = PN->getParent();
1566 if (!OuterL->contains(PB))
1567 return false;
1568 return PB != OuterL->getLoopLatch();
1569 }))
1570 return false;
1571 }
1572 return true;
1573}
1574
1575// We currently support LCSSA PHI nodes in the outer loop exit, if their
1576// incoming values do not come from the outer loop latch or if the
1577// outer loop latch has a single predecessor. In that case, the value will
1578// be available if both the inner and outer loop conditions are true, which
1579// will still be true after interchanging. If we have multiple predecessor,
1580// that may not be the case, e.g. because the outer loop latch may be executed
1581// if the inner loop is not executed.
1582static bool areOuterLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) {
1583 BasicBlock *LoopNestExit = OuterLoop->getUniqueExitBlock();
1584 for (PHINode &PHI : LoopNestExit->phis()) {
1585 for (Value *Incoming : PHI.incoming_values()) {
1586 Instruction *IncomingI = dyn_cast<Instruction>(Incoming);
1587 if (!IncomingI || IncomingI->getParent() != OuterLoop->getLoopLatch())
1588 continue;
1589
1590 // The incoming value is defined in the outer loop latch. Currently we
1591 // only support that in case the outer loop latch has a single predecessor.
1592 // This guarantees that the outer loop latch is executed if and only if
1593 // the inner loop is executed (because tightlyNested() guarantees that the
1594 // outer loop header only branches to the inner loop or the outer loop
1595 // latch).
1596 // FIXME: We could weaken this logic and allow multiple predecessors,
1597 // if the values are produced outside the loop latch. We would need
1598 // additional logic to update the PHI nodes in the exit block as
1599 // well.
1600 if (OuterLoop->getLoopLatch()->getUniquePredecessor() == nullptr)
1601 return false;
1602 }
1603 }
1604 return true;
1605}
1606
1607/// The transform partially clones the inner loop's latch block, but PHI nodes
1608/// cannot be cloned this way. This function follows the instruction trees that
1609/// would be cloned and checks whether any PHI node other than the induction
1610/// PHIs feeds them. If such a PHI is found, the interchange is rejected.
1611///
1612/// TODO: This check strongly depends on the current implementation of the
1613/// transform. Ideally, the transform should be able to handle such PHI nodes in
1614/// the inner loop latch.
1616 ArrayRef<PHINode *> InductionPHIs) {
1617 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1618
1619 // Seed the worklist with the roots of the use-def chains the transform
1620 // clones: the latch's exit condition and the incoming values of the induction
1621 // PHIs from the latch.
1623 if (auto *LatchBI = dyn_cast<CondBrInst>(InnerLoopLatch->getTerminator()))
1624 if (auto *CondI = dyn_cast<Instruction>(LatchBI->getCondition()))
1625 Worklist.insert(CondI);
1626 for (PHINode *InductionPHI : InductionPHIs) {
1627 if (auto *IncomingI = dyn_cast<Instruction>(
1628 InductionPHI->getIncomingValueForBlock(InnerLoopLatch)))
1629 if (!is_contained(InductionPHIs, IncomingI))
1630 Worklist.insert(IncomingI);
1631 }
1632
1633 // Bail if a PHI node other than the induction PHIs feeds the cloned
1634 // instructions, walking the operand trees within the inner loop.
1635 SmallPtrSet<Instruction *, 4> InductionPHISet(InductionPHIs.begin(),
1636 InductionPHIs.end());
1637 for (unsigned I = 0; I < Worklist.size(); ++I) {
1638 Instruction *Cur = Worklist[I];
1639 if (isa<PHINode>(Cur) && !InductionPHISet.contains(Cur))
1640 return false;
1641 for (Value *Op : Cur->operands())
1642 if (auto *OpI = dyn_cast<Instruction>(Op))
1643 if (InnerLoop->contains(OpI))
1644 Worklist.insert(OpI);
1645 }
1646 return true;
1647}
1648
1649bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
1650 unsigned OuterLoopId,
1651 CharMatrix &DepMatrix) {
1652 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
1653 LLVM_DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
1654 << " and OuterLoopId = " << OuterLoopId
1655 << " due to dependence\n");
1656 ORE->emit([&]() {
1657 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
1658 InnerLoop->getStartLoc(),
1659 InnerLoop->getHeader())
1660 << "Cannot interchange loops due to dependences.";
1661 });
1662 return false;
1663 }
1664 // Check if outer and inner loop contain legal instructions only.
1665 for (auto *BB : OuterLoop->blocks())
1666 for (Instruction &I : *BB) {
1667 // Loads and stores are checked separately, so we can skip them here.
1669 continue;
1670
1671 // We cannot ignore potential memory reads, e.g., loads inside the called
1672 // function.
1673 if (!I.mayHaveSideEffects() && !I.mayReadFromMemory())
1674 continue;
1675
1676 LLVM_DEBUG(
1677 dbgs()
1678 << "Loops contain instructions that cannot be safely interchanged\n");
1679 ORE->emit([&]() {
1680 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsafeInst",
1681 I.getDebugLoc(), I.getParent())
1682 << "Cannot interchange loops due to instruction that is "
1683 "potentially unsafe to interchange.";
1684 });
1685
1686 return false;
1687 }
1688
1689 if (!checkInductionsAndReductions(OuterLoop)) {
1690 LLVM_DEBUG(dbgs() << "Failed to find inner loop inductions or found "
1691 "unsupported reductions.\n");
1692 return false;
1693 }
1694
1695 if (!areInnerLoopLatchPHIsSupported(InnerLoop, InnerLoopInductions)) {
1696 LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in inner loop latch.\n");
1697 ORE->emit([&]() {
1698 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedInnerLatchPHI",
1699 InnerLoop->getStartLoc(),
1700 InnerLoop->getHeader())
1701 << "Cannot interchange loops because unsupported PHI nodes found "
1702 "in inner loop latch.";
1703 });
1704 return false;
1705 }
1706
1707 FreezeInst *Freeze = findFreezeInReNestedBlocks(OuterLoop, InnerLoop);
1708 if (!Freeze)
1709 Freeze = findFreezeInInnerLatchCloneSet(InnerLoop, InnerLoopInductions);
1710 if (Freeze) {
1711 LLVM_DEBUG(dbgs() << "Interchange would re-nest or duplicate freeze\n");
1712 ORE->emit([&]() {
1713 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsafeInst",
1714 Freeze->getDebugLoc(),
1715 Freeze->getParent())
1716 << "Cannot interchange loops because re-nesting or duplicating "
1717 "freeze may change its sampling behavior.";
1718 });
1719 return false;
1720 }
1721
1722 // TODO: The loops could not be interchanged due to current limitations in the
1723 // transform module.
1724 if (currentLimitations()) {
1725 LLVM_DEBUG(dbgs() << "Not legal because of current transform limitation\n");
1726 return false;
1727 }
1728
1729 // Check if the loops are tightly nested.
1730 if (!tightlyNested(OuterLoop, InnerLoop)) {
1731 LLVM_DEBUG(dbgs() << "Loops not tightly nested\n");
1732 ORE->emit([&]() {
1733 return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested",
1734 InnerLoop->getStartLoc(),
1735 InnerLoop->getHeader())
1736 << "Cannot interchange loops because they are not tightly "
1737 "nested.";
1738 });
1739 return false;
1740 }
1741
1742 // The LCSSA PHI for the reduction has passed checks before; its user
1743 // is a store instruction.
1744 PHINode *LcssaReduction = nullptr;
1745 assert(InnerReductions.size() <= 1 &&
1746 "So far we only support at most one reduction.");
1747 if (InnerReductions.size() == 1)
1748 LcssaReduction = InnerReductions[0].LcssaPhi;
1749
1750 if (!areInnerLoopExitPHIsSupported(OuterLoop, InnerLoop, OuterInnerReductions,
1751 LcssaReduction)) {
1752 LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in inner loop exit.\n");
1753 ORE->emit([&]() {
1754 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI",
1755 InnerLoop->getStartLoc(),
1756 InnerLoop->getHeader())
1757 << "Found unsupported PHI node in loop exit.";
1758 });
1759 return false;
1760 }
1761
1762 if (!areOuterLoopExitPHIsSupported(OuterLoop, InnerLoop)) {
1763 LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in outer loop exit.\n");
1764 ORE->emit([&]() {
1765 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI",
1766 OuterLoop->getStartLoc(),
1767 OuterLoop->getHeader())
1768 << "Found unsupported PHI node in loop exit.";
1769 });
1770 return false;
1771 }
1772
1773 if (any_of(OuterLoop->getLoopLatch()->phis(),
1774 [](PHINode &PHI) { return PHI.getNumIncomingValues() != 1; })) {
1775 LLVM_DEBUG(dbgs() << "Only outer loop latch PHI nodes with one incoming "
1776 "value are supported.\n");
1777 ORE->emit([&]() {
1778 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedLatchPHI",
1779 OuterLoop->getStartLoc(),
1780 OuterLoop->getHeader())
1781 << "Only outer loop latch PHI nodes with one incoming value are "
1782 "supported.";
1783 });
1784 return false;
1785 }
1786
1787 // Regarding def-use chains that begin at an LCSSA PHI in the inner loop exit
1788 // and end at any instruction in the outer loop latch, we currently support
1789 // only the case where the chain contains only PHI nodes. Since we already
1790 // call `tightlyNested()`, we know that if there is a def-use chain that we
1791 // don't support (i.e., a chain that contains a non-PHI user), then the
1792 // non-PHI user must be in the outer loop latch.
1793 if (InnerLoop->getExitBlock() != OuterLoop->getLoopLatch())
1794 for (PHINode &PHI : OuterLoop->getLoopLatch()->phis())
1795 if (any_of(PHI.users(), [](const User *U) { return !isa<PHINode>(U); })) {
1796 LLVM_DEBUG(dbgs() << "Outer loop latch PHI has a non-PHI user.\n");
1797 ORE->emit([&]() {
1798 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedLatchPHI",
1799 OuterLoop->getStartLoc(),
1800 OuterLoop->getHeader())
1801 << "Cannot interchange loops because an outer loop latch PHI "
1802 "node has a non-PHI user.";
1803 });
1804 return false;
1805 }
1806
1807 return true;
1808}
1809
1810void CacheCostManager::computeIfUnitinialized() {
1811 if (CC.has_value())
1812 return;
1813
1814 LLVM_DEBUG(dbgs() << "Compute CacheCost.\n");
1815 CC = CacheCost::getCacheCost(*OutermostLoop, *AR, *DI);
1816 // Obtain the loop vector returned from loop cache analysis beforehand,
1817 // and put each <Loop, index> pair into a map for constant time query
1818 // later. Indices in loop vector reprsent the optimal order of the
1819 // corresponding loop, e.g., given a loopnest with depth N, index 0
1820 // indicates the loop should be placed as the outermost loop and index N
1821 // indicates the loop should be placed as the innermost loop.
1822 //
1823 // For the old pass manager CacheCost would be null.
1824 if (*CC != nullptr)
1825 for (const auto &[Idx, Cost] : enumerate((*CC)->getLoopCosts()))
1826 CostMap[Cost.first] = Idx;
1827}
1828
1829CacheCost *CacheCostManager::getCacheCost() {
1830 computeIfUnitinialized();
1831 return CC->get();
1832}
1833
1834const DenseMap<const Loop *, unsigned> &CacheCostManager::getCostMap() {
1835 computeIfUnitinialized();
1836 return CostMap;
1837}
1838
1839/// If \S contains an affine addrec for \p L, return the step recurrence of it.
1840/// If \S is loop invariant with respect to \p L, return nullptr. Otherwise,
1841/// return std::nullopt, which indicates we cannot determine the coefficient of
1842/// the addrec for \p L in \S.
1843/// TODO: Handle more complex cases. Maybe using SCEVTraversal is a good way to
1844/// do that.
1845static std::optional<const SCEV *>
1848 if (!AR) {
1849 if (SE.isLoopInvariant(S, L))
1850 return nullptr;
1851 return std::nullopt;
1852 }
1853
1854 if (!AR->isAffine()) {
1855 LLVM_DEBUG(dbgs() << "Unexpected non-affine addrec\n");
1856 return std::nullopt;
1857 }
1858
1859 std::optional<const SCEV *> Coeff =
1860 getAddRecCoefficient(SE, AR->getStart(), L);
1861 if (!Coeff.has_value())
1862 return std::nullopt;
1863
1864 if (AR->getLoop() == L) {
1865 assert(!*Coeff && "Found more than one addrec for the same loop");
1866 Coeff = AR->getStepRecurrence(SE);
1867 }
1868 return Coeff;
1869}
1870
1871int LoopInterchangeProfitability::getInstrOrderCost() {
1872 SmallPtrSet<const SCEV *, 4> GoodBasePtrs, BadBasePtrs;
1873 for (BasicBlock *BB : InnerLoop->blocks()) {
1874 for (Instruction &Ins : *BB) {
1875 if (!isa<LoadInst, StoreInst>(&Ins))
1876 continue;
1877 const SCEV *Access = SE->getSCEV(getLoadStorePointerOperand(&Ins));
1878 const SCEV *BasePtr = SE->getPointerBase(Access);
1879 std::optional<const SCEV *> OuterCoeff =
1880 getAddRecCoefficient(*SE, Access, OuterLoop);
1881 std::optional<const SCEV *> InnerCoeff =
1882 getAddRecCoefficient(*SE, Access, InnerLoop);
1883
1884 if (!OuterCoeff.has_value() || !*OuterCoeff || !InnerCoeff.has_value() ||
1885 !*InnerCoeff)
1886 continue;
1887
1888 // This heuristic assumes that a smaller step recurrence implies that the
1889 // induction variable corresponding to the loop is used in the inner
1890 // dimension of the array. Placing such a loop in the inner position would
1891 // be beneficial in terms of locality. If the array access is of the form
1892 // like `A[3*i + 2*j]`, this heuristic may lead to an unprofitable
1893 // interchange, but we expect such cases to be rare.
1894 const SCEV *OuterStep = SE->getAbsExpr(*OuterCoeff, /*IsNSW=*/false);
1895 const SCEV *InnerStep = SE->getAbsExpr(*InnerCoeff, /*IsNSW=*/false);
1896 // If we find the inner induction after an outer induction e.g.
1897 //
1898 // for(int i=0;i<N;i++)
1899 // for(int j=0;j<N;j++)
1900 // A[i][j] = A[i-1][j-1]+k;
1901 //
1902 //
1903 // then it is a good order. If we find the outer induction after an inner
1904 // induction e.g.
1905 //
1906 // for(int i=0;i<N;i++)
1907 // for(int j=0;j<N;j++)
1908 // A[j][i] = A[j-1][i-1]+k;
1909 //
1910 // then it is a bad order.
1911 //
1912 // To avoid counting the same base pointers multiple times, we deduplicate
1913 // them by using a set of base pointers.
1914 if (SE->isKnownPredicate(ICmpInst::ICMP_SLT, InnerStep, OuterStep))
1915 GoodBasePtrs.insert(BasePtr);
1916 else if (SE->isKnownPredicate(ICmpInst::ICMP_SLT, OuterStep, InnerStep))
1917 BadBasePtrs.insert(BasePtr);
1918 }
1919 }
1920
1921 int GoodOrder = GoodBasePtrs.size();
1922 int BadOrder = BadBasePtrs.size();
1923 return GoodOrder - BadOrder;
1924}
1925
1926std::optional<bool>
1927LoopInterchangeProfitability::isProfitablePerLoopCacheAnalysis(
1928 const DenseMap<const Loop *, unsigned> &CostMap, CacheCost *CC) {
1929 // This is the new cost model returned from loop cache analysis.
1930 // A smaller index means the loop should be placed an outer loop, and vice
1931 // versa.
1932 auto InnerLoopIt = CostMap.find(InnerLoop);
1933 if (InnerLoopIt == CostMap.end())
1934 return std::nullopt;
1935 auto OuterLoopIt = CostMap.find(OuterLoop);
1936 if (OuterLoopIt == CostMap.end())
1937 return std::nullopt;
1938
1939 if (CC->getLoopCost(*OuterLoop) == CC->getLoopCost(*InnerLoop))
1940 return std::nullopt;
1941 unsigned InnerIndex = InnerLoopIt->second;
1942 unsigned OuterIndex = OuterLoopIt->second;
1943 LLVM_DEBUG(dbgs() << "InnerIndex = " << InnerIndex
1944 << ", OuterIndex = " << OuterIndex << "\n");
1945 assert(InnerIndex != OuterIndex && "CostMap should assign unique "
1946 "numbers to each loop");
1947 return std::optional<bool>(InnerIndex < OuterIndex);
1948}
1949
1950std::optional<bool>
1951LoopInterchangeProfitability::isProfitablePerInstrOrderCost() {
1952 // Legacy cost model: this is rough cost estimation algorithm. It counts the
1953 // good and bad order of induction variables in the instruction and allows
1954 // reordering if number of bad orders is more than good.
1955 int Cost = getInstrOrderCost();
1956 LLVM_DEBUG(dbgs() << "Cost = " << Cost << "\n");
1958 return std::optional<bool>(true);
1959
1960 return std::nullopt;
1961}
1962
1963/// Return true if we can vectorize the loop specified by \p LoopId.
1964static bool canVectorize(const CharMatrix &DepMatrix, unsigned LoopId) {
1965 for (const auto &Dep : DepMatrix) {
1966 char Dir = Dep[LoopId];
1967 char DepType = Dep.back();
1968 assert((DepType == '<' || DepType == '*') &&
1969 "Unexpected element in dependency vector");
1970
1971 // There are no loop-carried dependencies.
1972 if (Dir == '=' || Dir == 'I')
1973 continue;
1974
1975 // DepType being '<' means that this direction vector represents a forward
1976 // dependency. In principle, a loop with '<' direction can be vectorized in
1977 // this case.
1978 if (Dir == '<' && DepType == '<')
1979 continue;
1980
1981 // We cannot prove that the loop is vectorizable.
1982 return false;
1983 }
1984 return true;
1985}
1986
1987std::optional<bool> LoopInterchangeProfitability::isProfitableForVectorization(
1988 unsigned InnerLoopId, unsigned OuterLoopId, CharMatrix &DepMatrix) {
1989 // If the outer loop cannot be vectorized, it is not profitable to move this
1990 // to inner position.
1991 if (!canVectorize(DepMatrix, OuterLoopId))
1992 return false;
1993
1994 // If the inner loop cannot be vectorized but the outer loop can be, then it
1995 // is profitable to interchange to enable inner loop parallelism.
1996 if (!canVectorize(DepMatrix, InnerLoopId))
1997 return true;
1998
1999 // If both the inner and the outer loop can be vectorized, it is necessary to
2000 // check the cost of each vectorized loop for profitability decision. At this
2001 // time we do not have a cost model to estimate them, so return nullopt.
2002 // TODO: Estimate the cost of vectorized loop when both the outer and the
2003 // inner loop can be vectorized.
2004 return std::nullopt;
2005}
2006
2007bool LoopInterchangeProfitability::isProfitable(
2008 const Loop *InnerLoop, const Loop *OuterLoop, unsigned InnerLoopId,
2009 unsigned OuterLoopId, CharMatrix &DepMatrix, CacheCostManager &CCM) {
2010 // Do not consider loops with a backedge that isn't taken, e.g. an
2011 // unconditional branch true/false, as candidates for interchange.
2012 // TODO: when interchange is forced, we should probably also allow
2013 // interchange for these loops, and thus this logic should be moved just
2014 // below the cost-model ignore check below. But this check is done first
2015 // to avoid the issue in #163954.
2016 const SCEV *InnerBTC = SE->getBackedgeTakenCount(InnerLoop);
2017 const SCEV *OuterBTC = SE->getBackedgeTakenCount(OuterLoop);
2018 if (InnerBTC && InnerBTC->isZero()) {
2019 LLVM_DEBUG(dbgs() << "Inner loop back-edge isn't taken, rejecting "
2020 "single iteration loop\n");
2021 return false;
2022 }
2023 if (OuterBTC && OuterBTC->isZero()) {
2024 LLVM_DEBUG(dbgs() << "Outer loop back-edge isn't taken, rejecting "
2025 "single iteration loop\n");
2026 return false;
2027 }
2028
2029 // Return true if interchange is forced and the cost-model ignored.
2030 if (Profitabilities.size() == 1 && Profitabilities[0] == RuleTy::Ignore)
2031 return true;
2033 "Duplicate rules and option 'ignore' are not allowed");
2034
2035 // isProfitable() is structured to avoid endless loop interchange. If the
2036 // highest priority rule (isProfitablePerLoopCacheAnalysis by default) could
2037 // decide the profitability then, profitability check will stop and return the
2038 // analysis result. If it failed to determine it (e.g., cache analysis failed
2039 // to analyze the loopnest due to delinearization issues) then go ahead the
2040 // second highest priority rule (isProfitablePerInstrOrderCost by default).
2041 // Likewise, if it failed to analysis the profitability then only, the last
2042 // rule (isProfitableForVectorization by default) will decide.
2043 std::optional<bool> shouldInterchange;
2044 for (RuleTy RT : Profitabilities) {
2045 switch (RT) {
2046 case RuleTy::PerLoopCacheAnalysis: {
2047 CacheCost *CC = CCM.getCacheCost();
2048 const DenseMap<const Loop *, unsigned> &CostMap = CCM.getCostMap();
2049 shouldInterchange = isProfitablePerLoopCacheAnalysis(CostMap, CC);
2050 break;
2051 }
2052 case RuleTy::PerInstrOrderCost:
2053 shouldInterchange = isProfitablePerInstrOrderCost();
2054 break;
2055 case RuleTy::ForVectorization:
2056 shouldInterchange =
2057 isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix);
2058 break;
2059 case RuleTy::Ignore:
2060 llvm_unreachable("Option 'ignore' is not supported with other options");
2061 break;
2062 }
2063
2064 // If this rule could determine the profitability, don't call subsequent
2065 // rules.
2066 if (shouldInterchange.has_value())
2067 break;
2068 }
2069
2070 if (!shouldInterchange.has_value()) {
2071 ORE->emit([&]() {
2072 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
2073 InnerLoop->getStartLoc(),
2074 InnerLoop->getHeader())
2075 << "Insufficient information to calculate the cost of loop for "
2076 "interchange.";
2077 });
2078 return false;
2079 } else if (!shouldInterchange.value()) {
2080 ORE->emit([&]() {
2081 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
2082 InnerLoop->getStartLoc(),
2083 InnerLoop->getHeader())
2084 << "Interchanging loops is not considered to improve cache "
2085 "locality nor vectorization.";
2086 });
2087 return false;
2088 }
2089 return true;
2090}
2091
2092void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
2093 Loop *InnerLoop) {
2094 for (Loop *L : *OuterLoop)
2095 if (L == InnerLoop) {
2096 OuterLoop->removeChildLoop(L);
2097 return;
2098 }
2099 llvm_unreachable("Couldn't find loop");
2100}
2101
2102/// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the
2103/// new inner and outer loop after interchanging: NewInner is the original
2104/// outer loop and NewOuter is the original inner loop.
2105///
2106/// Before interchanging, we have the following structure
2107/// Outer preheader
2108// Outer header
2109// Inner preheader
2110// Inner header
2111// Inner body
2112// Inner latch
2113// outer bbs
2114// Outer latch
2115//
2116// After interchanging:
2117// Inner preheader
2118// Inner header
2119// Outer preheader
2120// Outer header
2121// Inner body
2122// outer bbs
2123// Outer latch
2124// Inner latch
2125void LoopInterchangeTransform::restructureLoops(
2126 Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader,
2127 BasicBlock *OrigOuterPreHeader) {
2128 Loop *OuterLoopParent = OuterLoop->getParentLoop();
2129 // The original inner loop preheader moves from the new inner loop to
2130 // the parent loop, if there is one.
2131 NewInner->removeBlockFromLoop(OrigInnerPreHeader);
2132 LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent);
2133
2134 // Switch the loop levels.
2135 removeChildLoop(NewInner, NewOuter);
2136 // Replace NewInner with NewOuter in place, preserving sibling order.
2137 LI->replaceLoop(NewInner, NewOuter);
2138
2139 while (!NewOuter->isInnermost())
2140 NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin()));
2141 NewOuter->addChildLoop(NewInner);
2142
2143 // BBs from the original inner loop.
2144 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks());
2145
2146 // Add BBs from the original outer loop to the original inner loop (excluding
2147 // BBs already in inner loop)
2148 for (BasicBlock *BB : NewInner->blocks())
2149 if (LI->getLoopFor(BB) == NewInner)
2150 NewOuter->addBlockEntry(BB);
2151
2152 // Now remove inner loop header and latch from the new inner loop and move
2153 // other BBs (the loop body) to the new inner loop.
2154 BasicBlock *OuterHeader = NewOuter->getHeader();
2155 BasicBlock *OuterLatch = NewOuter->getLoopLatch();
2156 for (BasicBlock *BB : OrigInnerBBs) {
2157 // Nothing will change for BBs in child loops.
2158 if (LI->getLoopFor(BB) != NewOuter)
2159 continue;
2160 // Remove the new outer loop header and latch from the new inner loop.
2161 if (BB == OuterHeader || BB == OuterLatch)
2162 NewInner->removeBlockFromLoop(BB);
2163 else
2164 LI->changeLoopFor(BB, NewInner);
2165 }
2166
2167 // The preheader of the original outer loop becomes part of the new
2168 // outer loop.
2169 NewOuter->addBlockEntry(OrigOuterPreHeader);
2170 LI->changeLoopFor(OrigOuterPreHeader, NewOuter);
2171
2172 // Tell SE that we move the loops around.
2173 SE->forgetLoop(NewOuter);
2174}
2175
2176/// User can write, or optimizers can generate the reduction for inner loop.
2177/// To make the interchange valid, apply Reduction2Mem by moving the
2178/// initializer and store instructions into the inner loop. So far we only
2179/// handle cases where the reduction variable is initialized to a constant.
2180/// For example, below code:
2181///
2182/// loop:
2183/// re = phi<0.0, next>
2184/// next = re op ...
2185/// endloop
2186/// reduc_sum = phi<next> // lcssa phi
2187/// MEM_REF[idx] = reduc_sum // LcssaStore
2188///
2189/// is transformed into:
2190///
2191/// loop:
2192/// tmp = MEM_REF[idx];
2193/// new_var = !first_iteration ? tmp : 0.0;
2194/// next = new_var op ...
2195/// MEM_REF[idx] = next; // after moving
2196/// endloop
2197///
2198/// In this way the initial const is used in the first iteration of loop.
2199void LoopInterchangeTransform::reduction2Memory() {
2201 LIL.getInnerReductions();
2202
2203 assert(InnerReductions.size() == 1 &&
2204 "So far we only support at most one reduction.");
2205
2206 LoopInterchangeLegality::InnerReduction SR = InnerReductions[0];
2207 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
2208 IRBuilder<> Builder(InnerLoopHeader, InnerLoopHeader->getFirstNonPHIIt());
2209
2210 // Check if it's the first iteration.
2211 LLVMContext &Context = InnerLoopHeader->getContext();
2212 PHINode *FirstIter =
2213 Builder.CreatePHI(Type::getInt1Ty(Context), 2, "first.iter");
2214 FirstIter->addIncoming(ConstantInt::get(Type::getInt1Ty(Context), 1),
2215 InnerLoop->getLoopPreheader());
2216 FirstIter->addIncoming(ConstantInt::get(Type::getInt1Ty(Context), 0),
2217 InnerLoop->getLoopLatch());
2218 assert(FirstIter->isComplete() && "The FirstIter PHI node is not complete.");
2219
2220 // When the reduction is initialized from a constant value, we need to add
2221 // a stmt loading from the memory object to target basic block in inner
2222 // loop.
2223 Instruction *LoadMem = Builder.CreateLoad(SR.ElemTy, SR.MemRef);
2224
2225 // Init new_var to MEM_REF or CONST depending on if it is the first iteration.
2226 Value *NewVar = Builder.CreateSelect(FirstIter, SR.Init, LoadMem, "new.var");
2227
2228 // Replace all uses of the reduction variable with a new variable.
2229 SR.Reduction->replaceAllUsesWith(NewVar);
2230
2231 // Move store instruction into inner loop, just after reduction next's
2232 // definition.
2233 SR.LcssaStore->setOperand(0, SR.Next);
2234 SR.LcssaStore->moveAfter(dyn_cast<Instruction>(SR.Next));
2235}
2236
2237void LoopInterchangeTransform::transform(
2238 ArrayRef<Instruction *> DropNoWrapInsts,
2239 ArrayRef<Instruction *> DropNoInfInsts) {
2240
2242 LIL.getInnerReductions();
2243 if (InnerReductions.size() == 1)
2244 reduction2Memory();
2245
2246 LLVM_DEBUG(dbgs() << "Splitting the inner loop latch\n");
2247 auto &InductionPHIs = LIL.getInnerLoopInductions();
2248 assert(!InductionPHIs.empty() &&
2249 "Expected at least one induction variable in the inner loop");
2250
2251 SmallVector<Instruction *, 8> InnerIndexVarList;
2252 for (PHINode *CurInductionPHI : InductionPHIs) {
2253 Instruction *IncomingValue = dyn_cast<Instruction>(
2254 CurInductionPHI->getIncomingValueForBlock(InnerLoop->getLoopLatch()));
2255 assert(IncomingValue &&
2256 "Incoming value from loop latch isn't an instruction");
2257 if (is_contained(InductionPHIs, IncomingValue))
2258 continue;
2259 InnerIndexVarList.push_back(IncomingValue);
2260 }
2261
2262 // Create a new latch block for the inner loop. We split at the
2263 // current latch's terminator and then move the condition and all
2264 // operands that are not either loop-invariant or the induction PHI into the
2265 // new latch block.
2266 BasicBlock *NewLatch =
2267 SplitBlock(InnerLoop->getLoopLatch(),
2268 InnerLoop->getLoopLatch()->getTerminator(), DT, LI);
2269
2270 // Keep these seeds and the operand filter aligned with
2271 // findFreezeInInnerLatchCloneSet.
2272 SmallSetVector<Instruction *, 4> WorkList;
2273 unsigned i = 0;
2274 auto MoveInstructions = [&i, &WorkList, this, &InductionPHIs, NewLatch]() {
2275 for (; i < WorkList.size(); i++) {
2276 // PHI nodes cannot be cloned and moved here; the legality check
2277 // (areInnerLoopLatchPHIsSupported) ensures none reach the worklist.
2278 assert(!isa<PHINode>(WorkList[i]) &&
2279 "MoveInstructions does not support PHI nodes");
2280 // Duplicate instruction and move it to the new latch. Update uses that
2281 // have been moved.
2282 Instruction *NewI = WorkList[i]->clone();
2283 NewI->insertBefore(NewLatch->getFirstNonPHIIt());
2284 assert(!NewI->mayHaveSideEffects() &&
2285 "Moving instructions with side-effects may change behavior of "
2286 "the loop nest!");
2287 for (Use &U : llvm::make_early_inc_range(WorkList[i]->uses())) {
2288 Instruction *UserI = cast<Instruction>(U.getUser());
2289 if (!InnerLoop->contains(UserI->getParent()) ||
2290 UserI->getParent() == NewLatch ||
2291 llvm::is_contained(InductionPHIs, UserI))
2292 U.set(NewI);
2293 }
2294 // Add operands of moved instruction to the worklist, except if they are
2295 // outside the inner loop or are the induction PHI.
2296 for (Value *Op : WorkList[i]->operands()) {
2298 if (!OpI || this->LI->getLoopFor(OpI->getParent()) != this->InnerLoop ||
2299 llvm::is_contained(InductionPHIs, OpI))
2300 continue;
2301 WorkList.insert(OpI);
2302 }
2303 }
2304 };
2305
2306 // FIXME: Should we interchange when we have a constant condition?
2309 ->getCondition());
2310 if (CondI)
2311 WorkList.insert(CondI);
2312 MoveInstructions();
2313 for (Instruction *InnerIndexVar : InnerIndexVarList)
2314 WorkList.insert(cast<Instruction>(InnerIndexVar));
2315 MoveInstructions();
2316
2317 // Split the inner header so that it has a unique successor.
2318 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
2319 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHIIt(), DT, LI);
2320 LLVM_DEBUG(dbgs() << "splitting InnerLoopHeader done\n");
2321
2322 // Instructions in the original inner loop preheader may depend on values
2323 // defined in the outer loop header. Move them there, because the original
2324 // inner loop preheader will become the entry into the interchanged loop nest.
2325 // Currently we move all instructions and rely on LICM to move invariant
2326 // instructions outside the loop nest.
2327 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
2328 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
2329
2330 if (InnerLoopPreHeader != OuterLoopHeader) {
2331 // Eliminate PHIs in the inner-loop preheader.
2332 for (PHINode &P : make_early_inc_range(InnerLoopPreHeader->phis())) {
2333 assert(all_equal(P.incoming_values()) &&
2334 "Expected equivalent incoming values in inner loop preheader");
2335 P.replaceAllUsesWith(P.getIncomingValue(0));
2336 P.eraseFromParent();
2337 }
2338 for (Instruction &I :
2339 make_early_inc_range(make_range(InnerLoopPreHeader->begin(),
2340 std::prev(InnerLoopPreHeader->end()))))
2341 I.moveBeforePreserving(OuterLoopHeader->getTerminator()->getIterator());
2342 }
2343
2344 adjustLoopBranches();
2345
2346 // Finally, drop the nsw/nuw/ninf flags from the instructions for reduction
2347 // calculations.
2348 for (Instruction *Reduction : DropNoWrapInsts) {
2349 Reduction->setHasNoSignedWrap(false);
2350 Reduction->setHasNoUnsignedWrap(false);
2351 }
2352 for (Instruction *I : DropNoInfInsts)
2353 I->setHasNoInfs(false);
2354}
2355
2356/// \brief Move all instructions except the terminator from FromBB right before
2357/// InsertBefore
2358static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
2359 BasicBlock *ToBB = InsertBefore->getParent();
2360
2361 ToBB->splice(InsertBefore->getIterator(), FromBB, FromBB->begin(),
2362 FromBB->getTerminator()->getIterator());
2363}
2364
2365/// Swap instructions between \p BB1 and \p BB2 but keep terminators intact.
2366static void swapBBContents(BasicBlock *BB1, BasicBlock *BB2) {
2367 // Save all non-terminator instructions of BB1 into TempInstrs and unlink them
2368 // from BB1 afterwards.
2369 auto Iter = map_range(*BB1, [](Instruction &I) { return &I; });
2370 SmallVector<Instruction *, 4> TempInstrs(Iter.begin(), std::prev(Iter.end()));
2371 for (Instruction *I : TempInstrs)
2372 I->removeFromParent();
2373
2374 // Move instructions from BB2 to BB1.
2375 moveBBContents(BB2, BB1->getTerminator());
2376
2377 // Move instructions from TempInstrs to BB2.
2378 for (Instruction *I : TempInstrs)
2379 I->insertBefore(BB2->getTerminator()->getIterator());
2380}
2381
2382// Update BI to jump to NewBB instead of OldBB. Records updates to the
2383// dominator tree in DTUpdates. If \p MustUpdateOnce is true, assert that
2384// \p OldBB is exactly once in BI's successor list.
2385static void updateSuccessor(Instruction *Term, BasicBlock *OldBB,
2386 BasicBlock *NewBB,
2387 std::vector<DominatorTree::UpdateType> &DTUpdates,
2388 bool MustUpdateOnce = true) {
2389 assert((!MustUpdateOnce || llvm::count(successors(Term), OldBB) == 1) &&
2390 "BI must jump to OldBB exactly once.");
2391 bool Changed = false;
2392 for (Use &Op : Term->operands())
2393 if (Op == OldBB) {
2394 Op.set(NewBB);
2395 Changed = true;
2396 }
2397
2398 if (Changed) {
2399 DTUpdates.push_back(
2400 {DominatorTree::UpdateKind::Insert, Term->getParent(), NewBB});
2401 DTUpdates.push_back(
2402 {DominatorTree::UpdateKind::Delete, Term->getParent(), OldBB});
2403 }
2404 assert(Changed && "Expected a successor to be updated");
2405}
2406
2407// Move Lcssa PHIs to the right place.
2408static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader,
2409 BasicBlock *InnerLatch, BasicBlock *OuterHeader,
2410 BasicBlock *OuterLatch, BasicBlock *OuterExit,
2411 Loop *InnerLoop, LoopInfo *LI) {
2412
2413 // Deal with LCSSA PHI nodes in the exit block of the inner loop, that are
2414 // defined either in the header or latch. Those blocks will become header and
2415 // latch of the new outer loop, and the only possible users can PHI nodes
2416 // in the exit block of the loop nest or the outer loop header (reduction
2417 // PHIs, in that case, the incoming value must be defined in the inner loop
2418 // header). We can just substitute the user with the incoming value and remove
2419 // the PHI.
2420 for (PHINode &P : make_early_inc_range(InnerExit->phis())) {
2421 assert(P.getNumIncomingValues() == 1 &&
2422 "Only loops with a single exit are supported!");
2423
2424 Value *IncomingValue = P.getIncomingValueForBlock(InnerLatch);
2425 auto *IncI = dyn_cast<Instruction>(IncomingValue);
2426 if (!IncI) {
2427 // If the incoming value is not an instruction, it must be loop invariant.
2428 // In that case, we can just replace the PHI with the incoming value and
2429 // remove the PHI.
2430 assert(InnerLoop->isLoopInvariant(IncomingValue) &&
2431 "Expected non-instruction incoming value to be loop invariant");
2432 P.replaceAllUsesWith(IncomingValue);
2433 P.eraseFromParent();
2434 continue;
2435 }
2436
2437 // In case of multi-level nested loops, follow LCSSA to find the incoming
2438 // value defined from the innermost loop.
2439 auto *IncIInnerMost = dyn_cast<Instruction>(followLCSSA(IncI));
2440 // Skip phis when:
2441 // - they are not an instruction, e.g. incoming values are constants.
2442 // - Incomming values from the inner loop body, excluding the header and
2443 // latch.
2444 if (!IncIInnerMost || (IncIInnerMost->getParent() != InnerLatch &&
2445 IncIInnerMost->getParent() != InnerHeader))
2446 continue;
2447
2448 assert(all_of(P.users(),
2449 [OuterHeader, OuterExit, IncI, InnerHeader](User *U) {
2450 return (cast<PHINode>(U)->getParent() == OuterHeader &&
2451 IncI->getParent() == InnerHeader) ||
2452 cast<PHINode>(U)->getParent() == OuterExit;
2453 }) &&
2454 "Can only replace phis iff the uses are in the loop nest exit or "
2455 "the incoming value is defined in the inner header (it will "
2456 "dominate all loop blocks after interchanging)");
2457 P.replaceAllUsesWith(IncI);
2458 P.eraseFromParent();
2459 }
2460
2461 SmallVector<PHINode *, 8> LcssaInnerExit(
2462 llvm::make_pointer_range(InnerExit->phis()));
2463
2464 SmallVector<PHINode *, 8> LcssaInnerLatch(
2465 llvm::make_pointer_range(InnerLatch->phis()));
2466
2467 // Lcssa PHIs for values used outside the inner loop are in InnerExit.
2468 // If a PHI node has users outside of InnerExit, it has a use outside the
2469 // interchanged loop and we have to preserve it. We move these to
2470 // InnerLatch, which will become the new exit block for the innermost
2471 // loop after interchanging.
2472 for (PHINode *P : LcssaInnerExit)
2473 P->moveBefore(InnerLatch->getFirstNonPHIIt());
2474
2475 // If the inner loop latch contains LCSSA PHIs, those come from a child loop
2476 // and we have to move them to the new inner latch.
2477 for (PHINode *P : LcssaInnerLatch)
2478 P->moveBefore(InnerExit->getFirstNonPHIIt());
2479
2480 // Deal with LCSSA PHI nodes in the loop nest exit block. For PHIs that have
2481 // incoming values defined in the outer loop, we have to add a new PHI
2482 // in the inner loop latch, which became the exit block of the outer loop,
2483 // after interchanging.
2484 if (OuterExit) {
2485 for (PHINode &P : OuterExit->phis()) {
2486 if (P.getNumIncomingValues() != 1)
2487 continue;
2488 // Skip Phis with incoming values defined in the inner loop. Those should
2489 // already have been updated.
2490 auto I = dyn_cast<Instruction>(P.getIncomingValue(0));
2491 if (!I || LI->getLoopFor(I->getParent()) == InnerLoop)
2492 continue;
2493
2494 PHINode *NewPhi = dyn_cast<PHINode>(P.clone());
2495 NewPhi->setIncomingValue(0, P.getIncomingValue(0));
2496 NewPhi->setIncomingBlock(0, OuterLatch);
2497 // We might have incoming edges from other BBs, i.e., the original outer
2498 // header.
2499 for (auto *Pred : predecessors(InnerLatch)) {
2500 if (Pred == OuterLatch)
2501 continue;
2502 NewPhi->addIncoming(P.getIncomingValue(0), Pred);
2503 }
2504 NewPhi->insertBefore(InnerLatch->getFirstNonPHIIt());
2505 P.setIncomingValue(0, NewPhi);
2506 }
2507 }
2508
2509 // Now adjust the incoming blocks for the LCSSA PHIs.
2510 // For PHIs moved from Inner's exit block, we need to replace Inner's latch
2511 // with the new latch.
2512 InnerLatch->replacePhiUsesWith(InnerLatch, OuterLatch);
2513}
2514
2515/// This deals with a corner case when a LCSSA phi node appears in a non-exit
2516/// block: the outer loop latch block does not need to be exit block of the
2517/// inner loop. Consider a loop that was in LCSSA form, but then some
2518/// transformation like loop-unswitch comes along and creates an empty block,
2519/// where BB5 in this example is the outer loop latch block:
2520///
2521/// BB4:
2522/// br label %BB5
2523/// BB5:
2524/// %old.cond.lcssa = phi i16 [ %cond, %BB4 ]
2525/// br outer.header
2526///
2527/// Interchange then brings it in LCSSA form again resulting in this chain of
2528/// single-input phi nodes:
2529///
2530/// BB4:
2531/// %new.cond.lcssa = phi i16 [ %cond, %BB3 ]
2532/// br label %BB5
2533/// BB5:
2534/// %old.cond.lcssa = phi i16 [ %new.cond.lcssa, %BB4 ]
2535///
2536/// The problem is that interchange can reoder blocks BB4 and BB5 placing the
2537/// use before the def if we don't check this. The solution is to simplify
2538/// lcssa phi nodes (remove) if they appear in non-exit blocks.
2539///
2540static void simplifyLCSSAPhis(Loop *OuterLoop, Loop *InnerLoop) {
2541 BasicBlock *InnerLoopExit = InnerLoop->getExitBlock();
2542 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
2543
2544 // Do not modify lcssa phis where they actually belong, i.e. in exit blocks.
2545 if (OuterLoopLatch == InnerLoopExit)
2546 return;
2547
2548 // Collect and remove phis in non-exit blocks if they have 1 input.
2550 llvm::make_pointer_range(OuterLoopLatch->phis()));
2551 for (PHINode *Phi : Phis) {
2552 assert(Phi->getNumIncomingValues() == 1 && "Single input phi expected");
2553 LLVM_DEBUG(dbgs() << "Removing 1-input phi in non-exit block: " << *Phi
2554 << "\n");
2555 Phi->replaceAllUsesWith(Phi->getIncomingValue(0));
2556 Phi->eraseFromParent();
2557 }
2558}
2559
2560void LoopInterchangeTransform::adjustLoopBranches() {
2561 LLVM_DEBUG(dbgs() << "adjustLoopBranches called\n");
2562 std::vector<DominatorTree::UpdateType> DTUpdates;
2563
2564 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
2565 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
2566
2567 assert(OuterLoopPreHeader != OuterLoop->getHeader() &&
2568 InnerLoopPreHeader != InnerLoop->getHeader() && OuterLoopPreHeader &&
2569 InnerLoopPreHeader && "Guaranteed by loop-simplify form");
2570
2571 simplifyLCSSAPhis(OuterLoop, InnerLoop);
2572
2573 // Ensure that both preheaders do not contain PHI nodes and have single
2574 // predecessors. This allows us to move them easily. We use
2575 // InsertPreHeaderForLoop to create an 'extra' preheader, if the existing
2576 // preheaders do not satisfy those conditions.
2577 if (isa<PHINode>(OuterLoopPreHeader->begin()) ||
2578 !OuterLoopPreHeader->getUniquePredecessor())
2579 OuterLoopPreHeader =
2580 InsertPreheaderForLoop(OuterLoop, DT, LI, nullptr, true);
2581 if (InnerLoopPreHeader == OuterLoop->getHeader())
2582 InnerLoopPreHeader =
2583 InsertPreheaderForLoop(InnerLoop, DT, LI, nullptr, true);
2584
2585 // Adjust the loop preheader
2586 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
2587 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
2588 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
2589 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
2590 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
2591 BasicBlock *InnerLoopLatchPredecessor =
2592 InnerLoopLatch->getUniquePredecessor();
2593 BasicBlock *InnerLoopLatchSuccessor;
2594 BasicBlock *OuterLoopLatchSuccessor;
2595
2596 CondBrInst *OuterLoopLatchBI =
2597 dyn_cast<CondBrInst>(OuterLoopLatch->getTerminator());
2598 CondBrInst *InnerLoopLatchBI =
2599 dyn_cast<CondBrInst>(InnerLoopLatch->getTerminator());
2600 Instruction *OuterLoopHeaderBI = OuterLoopHeader->getTerminator();
2601 Instruction *InnerLoopHeaderBI = InnerLoopHeader->getTerminator();
2602
2603 assert(OuterLoopPredecessor && InnerLoopLatchPredecessor &&
2604 "Failed to find a unique predecessor");
2605 assert(OuterLoopLatchBI && InnerLoopLatchBI &&
2606 "Failed to find a conditional branch");
2607
2608 Instruction *InnerLoopLatchPredecessorBI =
2609 InnerLoopLatchPredecessor->getTerminator();
2610 Instruction *OuterLoopPredecessorBI = OuterLoopPredecessor->getTerminator();
2611
2612 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
2613 assert(InnerLoopHeaderSuccessor &&
2614 "Failed to find a unique successor for the inner loop header");
2615
2616 // Adjust Loop Preheader and headers.
2617 // The branches in the outer loop predecessor and the outer loop header can
2618 // be unconditional branches or conditional branches with duplicates. Consider
2619 // this when updating the successors.
2620 updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader,
2621 InnerLoopPreHeader, DTUpdates, /*MustUpdateOnce=*/false);
2622 // The outer loop header might or might not branch to the outer latch.
2623 // We are guaranteed to branch to the inner loop preheader.
2624 if (llvm::is_contained(successors(OuterLoopHeaderBI), OuterLoopLatch)) {
2625 // In this case the outerLoopHeader should branch to the InnerLoopLatch.
2626 updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, InnerLoopLatch,
2627 DTUpdates,
2628 /*MustUpdateOnce=*/false);
2629 }
2630 updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader,
2631 InnerLoopHeaderSuccessor, DTUpdates,
2632 /*MustUpdateOnce=*/false);
2633
2634 // Adjust reduction PHI's now that the incoming block has changed.
2635 InnerLoopHeaderSuccessor->replacePhiUsesWith(InnerLoopHeader,
2636 OuterLoopHeader);
2637
2638 updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor,
2639 OuterLoopPreHeader, DTUpdates);
2640
2641 // -------------Adjust loop latches-----------
2642 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
2643 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
2644 else
2645 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
2646
2647 updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch,
2648 InnerLoopLatchSuccessor, DTUpdates);
2649
2650 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
2651 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
2652 else
2653 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
2654
2655 updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor,
2656 OuterLoopLatchSuccessor, DTUpdates);
2657 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
2658 DTUpdates);
2659
2660 DT->applyUpdates(DTUpdates);
2661 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
2662 OuterLoopPreHeader);
2663
2664 moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch,
2665 OuterLoopHeader, OuterLoopLatch, InnerLoop->getExitBlock(),
2666 InnerLoop, LI);
2667 // For PHIs in the exit block of the outer loop, outer's latch has been
2668 // replaced by Inners'.
2669 OuterLoopLatchSuccessor->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch);
2670
2671 auto &OuterInnerReductions = LIL.getOuterInnerReductions();
2672 // Now update the reduction PHIs in the inner and outer loop headers.
2673 SmallVector<PHINode *, 4> InnerLoopPHIs, OuterLoopPHIs;
2674 for (PHINode &PHI : InnerLoopHeader->phis())
2675 if (OuterInnerReductions.contains(&PHI))
2676 InnerLoopPHIs.push_back(&PHI);
2677
2678 for (PHINode &PHI : OuterLoopHeader->phis())
2679 if (OuterInnerReductions.contains(&PHI))
2680 OuterLoopPHIs.push_back(&PHI);
2681
2682 // Now move the remaining reduction PHIs from outer to inner loop header and
2683 // vice versa. The PHI nodes must be part of a reduction across the inner and
2684 // outer loop and all the remains to do is and updating the incoming blocks.
2685 for (PHINode *PHI : OuterLoopPHIs) {
2686 LLVM_DEBUG(dbgs() << "Outer loop reduction PHIs:\n"; PHI->dump(););
2687 PHI->moveBefore(InnerLoopHeader->getFirstNonPHIIt());
2688 assert(OuterInnerReductions.count(PHI) && "Expected a reduction PHI node");
2689 }
2690 for (PHINode *PHI : InnerLoopPHIs) {
2691 LLVM_DEBUG(dbgs() << "Inner loop reduction PHIs:\n"; PHI->dump(););
2692 PHI->moveBefore(OuterLoopHeader->getFirstNonPHIIt());
2693 assert(OuterInnerReductions.count(PHI) && "Expected a reduction PHI node");
2694 }
2695
2696 // Update the incoming blocks for moved PHI nodes.
2697 OuterLoopHeader->replacePhiUsesWith(InnerLoopPreHeader, OuterLoopPreHeader);
2698 OuterLoopHeader->replacePhiUsesWith(InnerLoopLatch, OuterLoopLatch);
2699 InnerLoopHeader->replacePhiUsesWith(OuterLoopPreHeader, InnerLoopPreHeader);
2700 InnerLoopHeader->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch);
2701
2702 // Swap the preheader contents so each definition sits in the preheader of the
2703 // loop it now belongs to. This runs before the LCSSA rebuild below so that
2704 // any definition referenced across the interchanged levels dominates its uses
2705 // when formLCSSAForInstructions runs.
2706 swapBBContents(OuterLoop->getLoopPreheader(), InnerLoop->getLoopPreheader());
2707
2708 // Values defined in the outer loop header could be used in the inner loop
2709 // latch. In that case, we need to create LCSSA phis for them, because after
2710 // interchanging they will be defined in the new inner loop and used in the
2711 // new outer loop.
2712 SmallVector<Instruction *, 4> MayNeedLCSSAPhis;
2713 for (Instruction &I :
2714 make_range(OuterLoopHeader->begin(), std::prev(OuterLoopHeader->end())))
2715 MayNeedLCSSAPhis.push_back(&I);
2716
2717#ifndef NDEBUG
2718 assert(!verifyFunction(*OuterLoopHeader->getParent(), &errs()) &&
2719 "LoopInterchange handed dominance-broken IR to LCSSA rebuild");
2720#endif
2721
2722 formLCSSAForInstructions(MayNeedLCSSAPhis, *DT, *LI, SE);
2723}
2724
2728 LPMUpdater &U) {
2729 Function &F = *LN.getParent();
2730
2732
2733 ORE.emit([&]() {
2734 return OptimizationRemarkAnalysis(DEBUG_TYPE, "Dependence",
2737 << "Computed dependence info, invoking the transform.";
2738 });
2739
2740 DependenceInfo DI(&F, &AR.AA, &AR.SE, &AR.LI);
2741 if (!LoopInterchange(&AR.SE, &AR.LI, &DI, &AR.DT, &AR, &ORE).run(LN))
2742 return PreservedAnalyses::all();
2743 U.markLoopNestChanged(true);
2745}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
unsigned uint64_t
Rewrite undef for PHI
ReachingDefInfo InstSet InstSet & Ignore
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
DXIL Resource Access
#define DEBUG_TYPE
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file defines the interface for the loop cache analysis.
SmallVector< Loop *, 4 > LoopVector
Definition LoopFuse.cpp:362
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:253
static cl::list< RuleTy > Profitabilities("loop-interchange-profitabilities", cl::MiscFlags::CommaSeparated, cl::Hidden, cl::desc("List of profitability heuristics to be used. They are applied in " "the given order"), cl::list_init< RuleTy >({RuleTy::PerInstrOrderCost, RuleTy::ForVectorization}), cl::values(clEnumValN(RuleTy::PerLoopCacheAnalysis, "cache", "Prioritize loop cache cost"), clEnumValN(RuleTy::PerInstrOrderCost, "instorder", "Prioritize the IVs order of each instruction"), clEnumValN(RuleTy::ForVectorization, "vectorize", "Prioritize vectorization"), clEnumValN(RuleTy::Ignore, "ignore", "Ignore profitability, force interchange (does not " "work with other options)")))
static cl::opt< int > LoopInterchangeCostThreshold("loop-interchange-threshold", cl::init(0), cl::Hidden, cl::desc("Interchange if you gain more than this number"))
static FreezeInst * findFreezeInInnerLatchCloneSet(Loop *InnerLoop, ArrayRef< PHINode * > InnerLoopInductions)
static cl::opt< unsigned int > MinLoopNestDepth("loop-interchange-min-loop-nest-depth", cl::init(2), cl::Hidden, cl::desc("Minimum depth of loop nest considered for the transform"))
static void updateSuccessor(Instruction *Term, BasicBlock *OldBB, BasicBlock *NewBB, std::vector< DominatorTree::UpdateType > &DTUpdates, bool MustUpdateOnce=true)
static cl::opt< bool > EnableReduction2Memory("loop-interchange-reduction-to-mem", cl::init(false), cl::Hidden, cl::desc("Support for the inner-loop reduction pattern."))
static bool areInnerLoopLatchPHIsSupported(Loop *InnerLoop, ArrayRef< PHINode * > InductionPHIs)
The transform partially clones the inner loop's latch block, but PHI nodes cannot be cloned this way.
static bool isComputableLoopNest(ScalarEvolution *SE, ArrayRef< Loop * > LoopList)
static bool areOuterLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop)
static FreezeInst * findFreezeInReNestedBlocks(Loop *OuterLoop, Loop *InnerLoop)
static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore)
Move all instructions except the terminator from FromBB right before InsertBefore.
static void simplifyLCSSAPhis(Loop *OuterLoop, Loop *InnerLoop)
This deals with a corner case when a LCSSA phi node appears in a non-exit block: the outer loop latch...
static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, unsigned ToIndx)
static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader, BasicBlock *InnerLatch, BasicBlock *OuterHeader, BasicBlock *OuterLatch, BasicBlock *OuterExit, Loop *InnerLoop, LoopInfo *LI)
static void printDepMatrix(CharMatrix &DepMatrix)
static cl::opt< unsigned int > MaxMemInstrRatio("loop-interchange-max-mem-instr-ratio", cl::init(4), cl::Hidden, cl::desc("Maximum number of load/store instructions squared in relation to " "the total number of instructions. Higher value may lead to more " "interchanges at the cost of compile-time"))
static void swapBBContents(BasicBlock *BB1, BasicBlock *BB2)
Swap instructions between BB1 and BB2 but keep terminators intact.
static PHINode * findInnerReductionPhi(Loop *L, Value *V, SmallVectorImpl< Instruction * > &HasNoWrapInsts, SmallVectorImpl< Instruction * > &HasNoInfInsts)
static bool areInnerLoopExitPHIsSupported(Loop *OuterL, Loop *InnerL, SmallPtrSetImpl< PHINode * > &Reductions, PHINode *LcssaReduction)
We currently only support LCSSA PHI nodes in the inner loop exit if their users are either of the fol...
static cl::opt< unsigned int > MaxLoopNestDepth("loop-interchange-max-loop-nest-depth", cl::init(10), cl::Hidden, cl::desc("Maximum depth of loop nest considered for the transform"))
static bool hasSupportedLoopDepth(ArrayRef< Loop * > LoopList, OptimizationRemarkEmitter &ORE)
static bool inThisOrder(const Instruction *Src, const Instruction *Dst)
Return true if Src appears before Dst in the same basic block.
static bool canVectorize(const CharMatrix &DepMatrix, unsigned LoopId)
Return true if we can vectorize the loop specified by LoopId.
static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, unsigned InnerLoopId, unsigned OuterLoopId)
#define DEBUG_TYPE
static Value * followLCSSA(Value *SV)
static void populateWorklist(Loop &L, LoopVector &LoopList)
static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, Loop *L, DependenceInfo *DI, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
static std::optional< bool > isLexicographicallyPositive(ArrayRef< char > DV, unsigned Begin, unsigned End)
static bool checkReductionKind(Loop *L, PHINode *PHI, SmallVectorImpl< Instruction * > &HasNoWrapInsts, SmallVectorImpl< Instruction * > &HasNoInfInsts)
static std::optional< const SCEV * > getAddRecCoefficient(ScalarEvolution &SE, const SCEV *S, const Loop *L)
If \S contains an affine addrec for L, return the step recurrence of it.
static bool noDuplicateRulesAndIgnore(ArrayRef< RuleTy > Rules)
This file defines the interface for the loop nest analysis.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
loop Loop Strength Reduction
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
static bool processLoop(Loop &L, const AArch64Subtarget &ST, DataLayout DL)
SmallVector< Value *, 8 > ValueVector
This file defines the SmallSet class.
This file defines the SmallVector class.
static bool isProfitable(const StableFunctionMap::StableFunctionEntries &SFS)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:644
static LLVM_ABI std::unique_ptr< CacheCost > getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR, DependenceInfo &DI, std::optional< unsigned > TRT=std::nullopt)
Create a CacheCost for the loop nest rooted by Root.
CacheCostTy getLoopCost(const Loop &L) const
Return the estimated cost of loop L if the given loop is part of the loop nest associated with this o...
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:258
iterator end()
Definition DenseMap.h:176
DependenceInfo - This class is the main dependence-analysis driver.
LLVM_ABI std::unique_ptr< Dependence > depends(Instruction *Src, Instruction *Dst, bool UnderRuntimeAssumptions=false)
depends - Tests for a dependence between the Src and Dst instructions.
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This class represents a freeze function that returns random concrete value if an operand is either a ...
static LLVM_ABI bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, ArrayRef< const SCEVPredicate * > NoWrapPreds={}, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction * > *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate.
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
BlockT * getHeader() const
iterator_range< block_iterator > blocks() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
iterator begin() const
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
void replaceLoop(LoopT *Old, LoopT *New)
Replace a loop among its siblings (a parent loop's child list or the top-level list) with a new loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
void changeLoopFor(const BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
This class represents a loop nest and can be used to query its properties.
static const BasicBlock & skipEmptyBlockUntil(const BasicBlock *From, const BasicBlock *End, bool CheckUniquePred=false)
Recursivelly traverse all empty 'single successor' basic blocks of From (if there are any).
ArrayRef< Loop * > getLoops() const
Get the loops in the nest.
Function * getParent() const
Return the function to which the loop-nest belongs.
Loop & getOutermostLoop() const
Return the outermost loop in the loop nest.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:695
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
StringRef getName() const
Definition LoopInfo.h:415
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
bool isComplete() const
If the PHI node is complete which means all of its parent's predecessors have incoming value in this ...
op_range incoming_values()
void setIncomingBlock(unsigned i, BasicBlock *BB)
void setIncomingValue(unsigned i, Value *V)
static unsigned getIncomingValueNumForOperand(unsigned i)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Instruction * getExactFPMathInst() const
Returns 1st non-reassociative FP instruction in the PHI node's use-chain.
static LLVM_ABI bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction in TheLoop.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
LLVM_ABI SmallVector< Instruction *, 4 > getReductionOpChain(PHINode *Phi, Loop *L) const
Attempts to find a chain of operations from Phi to LoopExitInst that can be treated as a set of reduc...
RecurKind getRecurrenceKind() const
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents an analyzed expression in the program.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
The main scalar evolution driver.
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Definition StringMap.h:370
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:163
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI User * getUniqueUndroppableUser()
Return true if there is exactly one unique user of this value that cannot be dropped (that user can h...
Definition Value.cpp:185
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
list_initializer< Ty > list_init(ArrayRef< Ty > Vals)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
InstructionCost Cost
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:469
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMinimumNum
FP min with llvm.minimumnum semantics.
@ Or
Bitwise or logical OR of integers.
@ FMinimum
FP min with llvm.minimum semantics.
@ Mul
Product of integers.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ Xor
Bitwise or logical XOR of integers.
@ FMax
FP max implemented in terms of select(cmp()).
@ FMaximum
FP max with llvm.maximum semantics.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ FMul
Product of floats.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMin
FP min implemented in terms of select(cmp()).
@ Add
Sum of integers.
@ FAdd
Sum of floats.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove=nullptr, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop.
Definition LCSSA.cpp:328
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
LLVM_ABI PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...