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