LLVM 24.0.0git
IVDescriptors.cpp
Go to the documentation of this file.
1//===- llvm/Analysis/IVDescriptors.cpp - IndVar Descriptors -----*- C++ -*-===//
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 file "describes" induction and recurrence variables.
10//
11//===----------------------------------------------------------------------===//
12
20#include "llvm/IR/Dominators.h"
23#include "llvm/IR/ValueHandle.h"
24#include "llvm/Support/Debug.h"
26
27using namespace llvm;
28using namespace llvm::PatternMatch;
29using namespace llvm::SCEVPatternMatch;
30
31#define DEBUG_TYPE "iv-descriptors"
32
35 for (const Use &Use : I->operands())
36 if (!Set.count(dyn_cast<Instruction>(Use)))
37 return false;
38 return true;
39}
40
42 switch (Kind) {
43 default:
44 break;
46 case RecurKind::Sub:
47 case RecurKind::Add:
48 case RecurKind::Mul:
49 case RecurKind::Or:
50 case RecurKind::And:
51 case RecurKind::Xor:
52 case RecurKind::SMax:
53 case RecurKind::SMin:
54 case RecurKind::UMax:
55 case RecurKind::UMin:
59 return true;
60 }
61 return false;
62}
63
67
68/// Determines if Phi may have been type-promoted. If Phi has a single user
69/// that ANDs the Phi with a type mask, return the user. RT is updated to
70/// account for the narrower bit width represented by the mask, and the AND
71/// instruction is added to CI.
75 if (!Phi->hasOneUse())
76 return Phi;
77
78 const APInt *M = nullptr;
79 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
80
81 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
82 // with a new integer type of the corresponding bit width.
83 if (match(J, m_And(m_Instruction(I), m_APInt(M)))) {
84 int32_t Bits = (*M + 1).exactLogBase2();
85 if (Bits > 0) {
86 RT = IntegerType::get(Phi->getContext(), Bits);
87 Visited.insert(Phi);
88 CI.insert(J);
89 return J;
90 }
91 }
92 return Phi;
93}
94
98
99/// Compute the minimal bit width needed to represent a reduction whose exit
100/// instruction is given by Exit.
101static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
102 DemandedBits *DB,
103 AssumptionCache *AC,
104 DominatorTree *DT) {
105 bool IsSigned = false;
106 const DataLayout &DL = Exit->getDataLayout();
107 uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
108
109 if (DB) {
110 // Use the demanded bits analysis to determine the bits that are live out
111 // of the exit instruction, rounding up to the nearest power of two. If the
112 // use of demanded bits results in a smaller bit width, we know the value
113 // must be positive (i.e., IsSigned = false), because if this were not the
114 // case, the sign bit would have been demanded.
115 auto Mask = DB->getDemandedBits(Exit);
116 MaxBitWidth = Mask.getBitWidth() - Mask.countl_zero();
117 }
118
119 if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) {
120 // If demanded bits wasn't able to limit the bit width, we can try to use
121 // value tracking instead. This can be the case, for example, if the value
122 // may be negative.
123 auto NumSignBits = ComputeNumSignBits(Exit, DL, AC, nullptr, DT);
124 auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType());
125 MaxBitWidth = NumTypeBits - NumSignBits;
126 KnownBits Bits = computeKnownBits(Exit, DL);
127 if (!Bits.isNonNegative()) {
128 // If the value is not known to be non-negative, we set IsSigned to true,
129 // meaning that we will use sext instructions instead of zext
130 // instructions to restore the original type.
131 IsSigned = true;
132 // Make sure at least one sign bit is included in the result, so it
133 // will get properly sign-extended.
134 ++MaxBitWidth;
135 }
136 }
137 MaxBitWidth = llvm::bit_ceil(MaxBitWidth);
138
139 return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth),
140 IsSigned);
141}
142
143/// Collect cast instructions that can be ignored in the vectorizer's cost
144/// model, given a reduction exit value and the minimal type in which the
145// reduction can be represented. Also search casts to the recurrence type
146// to find the minimum width used by the recurrence.
147static void collectCastInstrs(Loop *TheLoop, Instruction *Exit,
148 Type *RecurrenceType,
150 unsigned &MinWidthCastToRecurTy) {
151
154 Worklist.push_back(Exit);
155 MinWidthCastToRecurTy = -1U;
156
157 while (!Worklist.empty()) {
158 Instruction *Val = Worklist.pop_back_val();
159 Visited.insert(Val);
160 if (auto *Cast = dyn_cast<CastInst>(Val)) {
161 if (Cast->getSrcTy() == RecurrenceType) {
162 // If the source type of a cast instruction is equal to the recurrence
163 // type, it will be eliminated, and should be ignored in the vectorizer
164 // cost model.
165 Casts.insert(Cast);
166 continue;
167 }
168 if (Cast->getDestTy() == RecurrenceType) {
169 // The minimum width used by the recurrence is found by checking for
170 // casts on its operands. The minimum width is used by the vectorizer
171 // when finding the widest type for in-loop reductions without any
172 // loads/stores.
173 MinWidthCastToRecurTy = std::min<unsigned>(
174 MinWidthCastToRecurTy, Cast->getSrcTy()->getScalarSizeInBits());
175 continue;
176 }
177 }
178 // Add all operands to the work list if they are loop-varying values that
179 // we haven't yet visited.
180 for (Value *O : cast<User>(Val)->operands())
181 if (auto *I = dyn_cast<Instruction>(O))
182 if (TheLoop->contains(I) && !Visited.count(I))
183 Worklist.push_back(I);
184 }
185}
186
187// Check if a given Phi node can be recognized as an ordered reduction for
188// vectorizing floating point operations without unsafe math.
189static bool checkOrderedReduction(RecurKind Kind, Instruction *ExactFPMathInst,
190 Instruction *Exit, PHINode *Phi) {
191 // Currently only FAdd and FMulAdd are supported.
192 if (Kind != RecurKind::FAdd && Kind != RecurKind::FMulAdd)
193 return false;
194
195 if (Kind == RecurKind::FAdd && Exit->getOpcode() != Instruction::FAdd)
196 return false;
197
198 if (Kind == RecurKind::FMulAdd &&
200 return false;
201
202 // Ensure the exit instruction has only one user other than the reduction PHI
203 if (Exit != ExactFPMathInst || Exit->hasNUsesOrMore(3))
204 return false;
205
206 // The only pattern accepted is the one in which the reduction PHI
207 // is used as one of the operands of the exit instruction
208 auto *Op0 = Exit->getOperand(0);
209 auto *Op1 = Exit->getOperand(1);
210 if (Kind == RecurKind::FAdd && Op0 != Phi && Op1 != Phi)
211 return false;
212 if (Kind == RecurKind::FMulAdd && Exit->getOperand(2) != Phi)
213 return false;
214
215 LLVM_DEBUG(dbgs() << "LV: Found an ordered reduction: Phi: " << *Phi
216 << ", ExitInst: " << *Exit << "\n");
217
218 return true;
219}
220
221// Collect FMF from a value and its associated fcmp in select patterns
223 FastMathFlags FMF = cast<FPMathOperator>(V)->getFastMathFlags();
224 if (auto *Sel = dyn_cast<SelectInst>(V)) {
225 // Accept FMF from either fcmp or select in a min/max idiom.
226 // TODO: Remove this when FMF propagation is fixed or we standardize on
227 // intrinsics.
228 if (auto *FCmp = dyn_cast<FCmpInst>(Sel->getCondition()))
229 FMF |= FCmp->getFastMathFlags();
230 }
231 return FMF;
232}
233
234static std::optional<FastMathFlags>
236 bool HasRequiredFMF = FPOp && FPOp->hasNoNaNs() && FPOp->hasNoSignedZeros();
237 if (HasRequiredFMF)
238 return collectMinMaxFMF(FPOp);
239
240 switch (RK) {
245 break;
246
247 case RecurKind::FMax:
249 return std::nullopt;
251 break;
252 case RecurKind::FMin:
254 return std::nullopt;
256 break;
257 default:
258 return std::nullopt;
259 }
260 return collectMinMaxFMF(FPOp);
261}
262
264 ScalarEvolution *SE) {
265 Type *Ty = Phi->getType()->getScalarType();
266 BasicBlock *Latch = TheLoop->getLoopLatch();
267 if (Phi->getNumIncomingValues() != 2 ||
268 Phi->getParent() != TheLoop->getHeader() ||
269 (!Ty->isIntegerTy() && !Ty->isFloatingPointTy()) || !Latch)
270 return {};
271
272 auto GetMinMaxRK = [](Value *V, Value *&A, Value *&B) -> RecurKind {
273 if (match(V, m_UMin(m_Value(A), m_Value(B))))
274 return RecurKind::UMin;
275 if (match(V, m_UMax(m_Value(A), m_Value(B))))
276 return RecurKind::UMax;
277 if (match(V, m_SMax(m_Value(A), m_Value(B))))
278 return RecurKind::SMax;
279 if (match(V, m_SMin(m_Value(A), m_Value(B))))
280 return RecurKind::SMin;
281 if (match(V, m_OrdOrUnordFMin(m_Value(A), m_Value(B))) ||
283 return RecurKind::FMin;
284 if (match(V, m_OrdOrUnordFMax(m_Value(A), m_Value(B))) ||
286 return RecurKind::FMax;
287 if (match(V, m_FMinimum(m_Value(A), m_Value(B))))
288 return RecurKind::FMinimum;
289 if (match(V, m_FMaximum(m_Value(A), m_Value(B))))
290 return RecurKind::FMaximum;
295 return RecurKind::None;
296 };
297
299 Value *BackedgeValue = Phi->getIncomingValueForBlock(Latch);
301 // Walk def-use chains upwards from BackedgeValue to identify min/max
302 // recurrences.
303 SmallVector<Value *> WorkList({BackedgeValue});
304 SmallPtrSet<Value *, 8> Chain({Phi});
305 while (!WorkList.empty()) {
306 Value *Cur = WorkList.pop_back_val();
307 if (!Chain.insert(Cur).second)
308 continue;
309 auto *I = dyn_cast<Instruction>(Cur);
310 if (!I || !TheLoop->contains(I))
311 return {};
312 if (auto *PN = dyn_cast<PHINode>(I)) {
313 append_range(WorkList, PN->operands());
314 continue;
315 }
316 Value *A, *B;
317 RecurKind CurRK = GetMinMaxRK(Cur, A, B);
318 if (CurRK == RecurKind::None || (RK != RecurKind::None && CurRK != RK))
319 return {};
320
321 RK = CurRK;
322 // Check required fast-math flags for FP recurrences.
324 auto CurFMF = hasRequiredFastMathFlags(cast<FPMathOperator>(Cur), RK);
325 if (!CurFMF)
326 return {};
327 FMF &= *CurFMF;
328 }
329
330 if (auto *SI = dyn_cast<SelectInst>(I))
331 Chain.insert(SI->getCondition());
332
333 if (A == Phi || B == Phi)
334 continue;
335
336 // Add operand to worklist if it matches the pattern (exactly one must
337 // match)
338 Value *X, *Y;
339 auto *IA = dyn_cast<Instruction>(A);
340 auto *IB = dyn_cast<Instruction>(B);
341 bool AMatches = IA && TheLoop->contains(IA) && GetMinMaxRK(A, X, Y) == RK;
342 bool BMatches = IB && TheLoop->contains(IB) && GetMinMaxRK(B, X, Y) == RK;
343 if (AMatches == BMatches) // Both or neither match
344 return {};
345 WorkList.push_back(AMatches ? A : B);
346 }
347
348 // Handle argmin/argmax pattern: PHI has uses outside the reduction chain
349 // that are not intermediate min/max operations (which are handled below).
350 // Requires integer min/max, and the PHI must be the only in-loop user of
351 // BackedgeValue (so vectorizer can handle both PHIs together).
352 bool PhiHasInvalidUses = any_of(Phi->users(), [&](Instruction *U) {
353 Value *A, *B;
354 return !Chain.contains(U) && TheLoop->contains(U) &&
355 GetMinMaxRK(U, A, B) == RecurKind::None;
356 });
357 if (PhiHasInvalidUses) {
359 any_of(BackedgeValue->users(), [&](User *U) {
360 auto *UI = cast<Instruction>(U);
361 return UI != Phi && TheLoop->contains(UI);
362 }))
363 return {};
365 Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()),
366 /*Exit=*/nullptr, /*Store=*/nullptr, RK, FastMathFlags(),
367 /*ExactFP=*/nullptr, Phi->getType(), /*IsMultiUse=*/true);
368 }
369
370 // Validate chain entries and collect stores from chain entries and
371 // intermediate ops.
373 for (Value *V : Chain) {
374 for (User *U : V->users()) {
375 if (Chain.contains(U))
376 continue;
377 auto *I = dyn_cast<Instruction>(U);
378 if (!I || (!TheLoop->contains(I) && V != BackedgeValue))
379 return {};
380 if (!TheLoop->contains(I))
381 continue;
382 if (auto *SI = dyn_cast<StoreInst>(I)) {
383 Stores.push_back(SI);
384 continue;
385 }
386 // Must be intermediate min/max of the same kind.
387 Value *A, *B;
388 if (GetMinMaxRK(I, A, B) != RK)
389 return {};
390 for (User *IU : I->users()) {
391 if (auto *SI = dyn_cast<StoreInst>(IU))
392 Stores.push_back(SI);
393 else if (!Chain.contains(IU))
394 return {};
395 }
396 }
397 }
398
399 // Validate all stores go to same invariant address and are in the same block.
400 StoreInst *IntermediateStore = nullptr;
401 const SCEV *StorePtrSCEV = nullptr;
402 for (StoreInst *SI : Stores) {
403 if (!SE)
404 return {};
405 const SCEV *Ptr = SE->getSCEV(SI->getPointerOperand());
406 if (!SE->isLoopInvariant(Ptr, TheLoop) ||
407 (StorePtrSCEV && StorePtrSCEV != Ptr))
408 return {};
409 StorePtrSCEV = Ptr;
410 if (!IntermediateStore)
411 IntermediateStore = SI;
412 else if (IntermediateStore->getParent() != SI->getParent())
413 return {};
414 else if (IntermediateStore->comesBefore(SI))
415 IntermediateStore = SI;
416 }
417
418 // The vectorizer replaces the per-iteration store to the invariant address
419 // with a single store of the final reduced value in the middle block. That is
420 // only correct if the store stores the reduction value itself. If it stores a
421 // value derived from it (e.g. `%other = smax(%phi, 42); store %other`), that
422 // value observes the per-iteration running min/max, so replacing it with the
423 // final reduction value would miscompile. Mirrors the check in
424 // AddReductionVar.
425 if (IntermediateStore &&
426 IntermediateStore->getValueOperand() != BackedgeValue)
427 return {};
428
430 Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()),
431 cast<Instruction>(BackedgeValue), IntermediateStore, RK, FMF, nullptr,
432 Phi->getType());
433}
434
435// This matches a phi that selects between the original value (HeaderPhi) and an
436// arbitrary non-reduction value.
437static bool isFindLastLikePhi(PHINode *Phi, PHINode *HeaderPhi,
438 SmallPtrSetImpl<Instruction *> &ReductionInstrs) {
439 unsigned NumNonReduxInputs = 0;
440 for (const Value *Op : Phi->operands()) {
441 if (!ReductionInstrs.contains(dyn_cast<Instruction>(Op))) {
442 if (++NumNonReduxInputs > 1)
443 return false;
444 } else if (Op != HeaderPhi) {
445 // TODO: Remove this restriction once chained phis are supported.
446 return false;
447 }
448 }
449 return NumNonReduxInputs == 1;
450}
451
453 PHINode *Phi, RecurKind Kind, Loop *TheLoop, RecurrenceDescriptor &RedDes,
455 ScalarEvolution *SE) {
456 if (Phi->getNumIncomingValues() != 2)
457 return false;
458
459 // Reduction variables are only found in the loop header block.
460 if (Phi->getParent() != TheLoop->getHeader())
461 return false;
462
463 // Obtain the reduction start value from the value that comes from the loop
464 // preheader.
465 if (!TheLoop->getLoopPreheader())
466 return false;
467
468 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
469 // ExitInstruction is the single value which is used outside the loop.
470 // We only allow for a single reduction value to be used outside the loop.
471 // This includes users of the reduction, variables (which form a cycle
472 // which ends in the phi node).
473 Instruction *ExitInstruction = nullptr;
474
475 // Variable to keep last visited store instruction. By the end of the
476 // algorithm this variable will be either empty or having intermediate
477 // reduction value stored in invariant address.
478 StoreInst *IntermediateStore = nullptr;
479
480 // Indicates that we found a reduction operation in our scan.
481 bool FoundReduxOp = false;
482
483 // We start with the PHI node and scan for all of the users of this
484 // instruction. All users must be instructions that can be used as reduction
485 // variables (such as ADD). We must have a single out-of-block user. The cycle
486 // must include the original PHI.
487 bool FoundStartPHI = false;
488
489 // To recognize AnyOf patterns formed by a icmp select sequence, we store
490 // the number of instruction we saw to make sure we only see one.
491 unsigned NumCmpSelectPatternInst = 0;
492 InstDesc ReduxDesc(false, nullptr);
493
494 // To recognize find-lasts of conditional operations (such as loads or
495 // divides), that need masking, we track non-phi users and if we've found a
496 // "find-last-like" phi (see isFindLastLikePhi). We currently only support
497 // find-last reduction chains with a single "find-last-like" phi and do not
498 // allow any other operations.
499 [[maybe_unused]] unsigned NumNonPHIUsers = 0;
500 bool FoundFindLastLikePhi = false;
501
502 // Data used for determining if the recurrence has been type-promoted.
503 Type *RecurrenceType = Phi->getType();
505 unsigned MinWidthCastToRecurrenceType;
506 Instruction *Start = Phi;
507 bool IsSigned = false;
508
511
512 // Return early if the recurrence kind does not match the type of Phi. If the
513 // recurrence kind is arithmetic, we attempt to look through AND operations
514 // resulting from the type promotion performed by InstCombine. Vector
515 // operations are not limited to the legal integer widths, so we may be able
516 // to evaluate the reduction in the narrower width.
517 // Check the scalar type to handle both scalar and vector types.
518 Type *ScalarTy = RecurrenceType->getScalarType();
519 if (Kind == RecurKind::FindLast) {
520 // FindLast supports all primitive scalar types.
521 if (!ScalarTy->isFloatingPointTy() && !ScalarTy->isIntegerTy() &&
522 !ScalarTy->isPointerTy())
523 return false;
524 } else if (ScalarTy->isFloatingPointTy()) {
526 return false;
527 } else if (ScalarTy->isIntegerTy()) {
528 if (!isIntegerRecurrenceKind(Kind))
529 return false;
530 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
531 } else {
532 // Pointer min/max may exist, but it is not supported as a reduction op.
533 return false;
534 }
535
536 Worklist.push_back(Start);
537 VisitedInsts.insert(Start);
538
539 // Start with all flags set because we will intersect this with the reduction
540 // flags from all the reduction operations.
542
543 // The first instruction in the use-def chain of the Phi node that requires
544 // exact floating point operations.
545 Instruction *ExactFPMathInst = nullptr;
546
547 // A value in the reduction can be used:
548 // - By the reduction:
549 // - Reduction operation:
550 // - One use of reduction value (safe).
551 // - Multiple use of reduction value (not safe).
552 // - PHI:
553 // - All uses of the PHI must be the reduction (safe).
554 // - Otherwise, not safe.
555 // - By instructions outside of the loop (safe).
556 // * One value may have several outside users, but all outside
557 // uses must be of the same value.
558 // - By store instructions with a loop invariant address (safe with
559 // the following restrictions):
560 // * If there are several stores, all must have the same address.
561 // * Final value should be stored in that loop invariant address.
562 // - By an instruction that is not part of the reduction (not safe).
563 // This is either:
564 // * An instruction type other than PHI or the reduction operation.
565 // * A PHI in the header other than the initial PHI.
566 while (!Worklist.empty()) {
567 Instruction *Cur = Worklist.pop_back_val();
568
569 // Store instructions are allowed iff it is the store of the reduction
570 // value to the same loop invariant memory location.
571 if (auto *SI = dyn_cast<StoreInst>(Cur)) {
572 if (!SE) {
573 LLVM_DEBUG(dbgs() << "Store instructions are not processed without "
574 << "Scalar Evolution Analysis\n");
575 return false;
576 }
577
578 const SCEV *PtrScev = SE->getSCEV(SI->getPointerOperand());
579 // Check it is the same address as previous stores
580 if (IntermediateStore) {
581 const SCEV *OtherScev =
582 SE->getSCEV(IntermediateStore->getPointerOperand());
583
584 if (OtherScev != PtrScev) {
585 LLVM_DEBUG(dbgs() << "Storing reduction value to different addresses "
586 << "inside the loop: " << *SI->getPointerOperand()
587 << " and "
588 << *IntermediateStore->getPointerOperand() << '\n');
589 return false;
590 }
591 }
592
593 // Check the pointer is loop invariant
594 if (!SE->isLoopInvariant(PtrScev, TheLoop)) {
595 LLVM_DEBUG(dbgs() << "Storing reduction value to non-uniform address "
596 << "inside the loop: " << *SI->getPointerOperand()
597 << '\n');
598 return false;
599 }
600
601 // IntermediateStore is always the last store in the loop.
603 continue;
604 }
605
606 // No Users.
607 // If the instruction has no users then this is a broken chain and can't be
608 // a reduction variable.
609 if (Cur->use_empty())
610 return false;
611
612 bool IsAPhi = isa<PHINode>(Cur);
613 if (!IsAPhi)
614 ++NumNonPHIUsers;
615
616 // A header PHI use other than the original PHI.
617 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
618 return false;
619
620 // Reductions of instructions such as Div, and Sub is only possible if the
621 // LHS is the reduction variable.
622 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
623 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
624 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
625 return false;
626
627 // Any reduction instruction must be of one of the allowed kinds. We ignore
628 // the starting value (the Phi or an AND instruction if the Phi has been
629 // type-promoted).
630 if (Cur != Start) {
631 ReduxDesc = isRecurrenceInstr(TheLoop, Phi, Cur, Kind, ReduxDesc, SE);
632 ExactFPMathInst = ExactFPMathInst == nullptr
633 ? ReduxDesc.getExactFPMathInst()
634 : ExactFPMathInst;
635 if (!ReduxDesc.isRecurrence())
636 return false;
637 // FIXME: FMF is allowed on phi, but propagation is not handled correctly.
638 if (isa<FPMathOperator>(ReduxDesc.getPatternInst()) && !IsAPhi)
639 FMF &= collectMinMaxFMF(ReduxDesc.getPatternInst());
640 // Update this reduction kind if we matched a new instruction.
641 // TODO: Can we eliminate the need for a 2nd InstDesc by keeping 'Kind'
642 // state accurate while processing the worklist?
643 if (ReduxDesc.getRecKind() != RecurKind::None)
644 Kind = ReduxDesc.getRecKind();
645 }
646
647 bool IsASelect = isa<SelectInst>(Cur);
648
649 // A conditional reduction operation must only have 2 or less uses in
650 // VisitedInsts.
651 if (IsASelect && (Kind == RecurKind::FAdd || Kind == RecurKind::FMul) &&
652 hasMultipleUsesOf(Cur, VisitedInsts, 2))
653 return false;
654
655 // A reduction operation must only have one use of the reduction value.
656 if (!IsAPhi && !IsASelect && !isAnyOfRecurrenceKind(Kind) &&
657 hasMultipleUsesOf(Cur, VisitedInsts, 1))
658 return false;
659
660 // All inputs to a PHI node must be a reduction value, unless the phi is a
661 // "FindLast-like" phi (described below).
662 if (IsAPhi && Cur != Phi) {
663 if (!areAllUsesIn(Cur, VisitedInsts)) {
664 // A "FindLast-like" phi acts like a conditional select between the
665 // previous reduction value, and an arbitrary value. Note: Multiple
666 // "FindLast-like" phis are not supported see:
667 // IVDescriptorsTest.UnsupportedFindLastPhi.
668 FoundFindLastLikePhi =
669 Kind == RecurKind::FindLast && !FoundFindLastLikePhi &&
670 isFindLastLikePhi(cast<PHINode>(Cur), Phi, VisitedInsts);
671 if (!FoundFindLastLikePhi)
672 return false;
673 }
674 }
675
676 if (isAnyOfRecurrenceKind(Kind) && IsASelect)
677 ++NumCmpSelectPatternInst;
678
679 // Check whether we found a reduction operator.
680 FoundReduxOp |= (!IsAPhi || FoundFindLastLikePhi) && Cur != Start;
681
682 // Process users of current instruction. Push non-PHI nodes after PHI nodes
683 // onto the stack. This way we are going to have seen all inputs to PHI
684 // nodes once we get to them.
687 for (User *U : Cur->users()) {
689
690 // If the user is a call to llvm.fmuladd then the instruction can only be
691 // the final operand.
692 if (isFMulAddIntrinsic(UI))
693 if (Cur == UI->getOperand(0) || Cur == UI->getOperand(1))
694 return false;
695
696 // Check if we found the exit user.
697 BasicBlock *Parent = UI->getParent();
698 if (!TheLoop->contains(Parent)) {
699 // If we already know this instruction is used externally, move on to
700 // the next user.
701 if (ExitInstruction == Cur)
702 continue;
703
704 // Exit if you find multiple values used outside or if the header phi
705 // node is being used. In this case the user uses the value of the
706 // previous iteration, in which case we would loose "VF-1" iterations of
707 // the reduction operation if we vectorize.
708 if (ExitInstruction != nullptr || Cur == Phi)
709 return false;
710
711 // The instruction used by an outside user must be the last instruction
712 // before we feed back to the reduction phi. Otherwise, we loose VF-1
713 // operations on the value.
714 if (!is_contained(Phi->operands(), Cur))
715 return false;
716
717 ExitInstruction = Cur;
718 continue;
719 }
720
721 // Process instructions only once (termination). Each reduction cycle
722 // value must only be used once, except by phi nodes and conditional
723 // reductions which are represented as a cmp followed by a select.
724 InstDesc IgnoredVal(false, nullptr);
725 if (VisitedInsts.insert(UI).second) {
726 if (isa<PHINode>(UI)) {
727 PHIs.push_back(UI);
728 } else {
730 if (SI && SI->getPointerOperand() == Cur) {
731 // Reduction variable chain can only be stored somewhere but it
732 // can't be used as an address.
733 return false;
734 }
735 NonPHIs.push_back(UI);
736 }
737 } else if (!isa<PHINode>(UI) &&
738 ((!isConditionalRdxPattern(UI).isRecurrence() &&
739 !isAnyOfPattern(TheLoop, Phi, UI, IgnoredVal)
740 .isRecurrence())))
741 return false;
742
743 // Remember that we completed the cycle.
744 if (UI == Phi)
745 FoundStartPHI = true;
746 }
747 Worklist.append(PHIs.begin(), PHIs.end());
748 Worklist.append(NonPHIs.begin(), NonPHIs.end());
749 }
750
751 // We only expect to match a single "find-last-like" phi per find-last
752 // reduction, with no non-phi operations in the reduction use chain.
753 assert((!FoundFindLastLikePhi ||
754 (Kind == RecurKind::FindLast && NumNonPHIUsers == 0)) &&
755 "Unexpectedly matched a 'find-last-like' phi");
756
757 if (isAnyOfRecurrenceKind(Kind) && NumCmpSelectPatternInst != 1)
758 return false;
759
760 if (IntermediateStore) {
761 // Check that stored value goes to the phi node again. This way we make sure
762 // that the value stored in IntermediateStore is indeed the final reduction
763 // value.
764 if (!is_contained(Phi->operands(), IntermediateStore->getValueOperand())) {
765 LLVM_DEBUG(dbgs() << "Not a final reduction value stored: "
766 << *IntermediateStore << '\n');
767 return false;
768 }
769
770 // If there is an exit instruction it's value should be stored in
771 // IntermediateStore
772 if (ExitInstruction &&
773 IntermediateStore->getValueOperand() != ExitInstruction) {
774 LLVM_DEBUG(dbgs() << "Last store Instruction of reduction value does not "
775 "store last calculated value of the reduction: "
776 << *IntermediateStore << '\n');
777 return false;
778 }
779
780 // If all uses are inside the loop (intermediate stores), then the
781 // reduction value after the loop will be the one used in the last store.
782 if (!ExitInstruction)
783 ExitInstruction = cast<Instruction>(IntermediateStore->getValueOperand());
784 }
785
786 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
787 return false;
788
789 const bool IsOrdered =
790 checkOrderedReduction(Kind, ExactFPMathInst, ExitInstruction, Phi);
791
792 if (Start != Phi) {
793 // If the starting value is not the same as the phi node, we speculatively
794 // looked through an 'and' instruction when evaluating a potential
795 // arithmetic reduction to determine if it may have been type-promoted.
796 //
797 // We now compute the minimal bit width that is required to represent the
798 // reduction. If this is the same width that was indicated by the 'and', we
799 // can represent the reduction in the smaller type. The 'and' instruction
800 // will be eliminated since it will essentially be a cast instruction that
801 // can be ignore in the cost model. If we compute a different type than we
802 // did when evaluating the 'and', the 'and' will not be eliminated, and we
803 // will end up with different kinds of operations in the recurrence
804 // expression (e.g., IntegerAND, IntegerADD). We give up if this is
805 // the case.
806 //
807 // The vectorizer relies on InstCombine to perform the actual
808 // type-shrinking. It does this by inserting instructions to truncate the
809 // exit value of the reduction to the width indicated by RecurrenceType and
810 // then extend this value back to the original width. If IsSigned is false,
811 // a 'zext' instruction will be generated; otherwise, a 'sext' will be
812 // used.
813 //
814 // TODO: We should not rely on InstCombine to rewrite the reduction in the
815 // smaller type. We should just generate a correctly typed expression
816 // to begin with.
817 Type *ComputedType;
818 std::tie(ComputedType, IsSigned) =
819 computeRecurrenceType(ExitInstruction, DB, AC, DT);
820 if (ComputedType != RecurrenceType)
821 return false;
822 }
823
824 // Collect cast instructions and the minimum width used by the recurrence.
825 // If the starting value is not the same as the phi node and the computed
826 // recurrence type is equal to the recurrence type, the recurrence expression
827 // will be represented in a narrower or wider type. If there are any cast
828 // instructions that will be unnecessary, collect them in CastsFromRecurTy.
829 // Note that the 'and' instruction was already included in this list.
830 //
831 // TODO: A better way to represent this may be to tag in some way all the
832 // instructions that are a part of the reduction. The vectorizer cost
833 // model could then apply the recurrence type to these instructions,
834 // without needing a white list of instructions to ignore.
835 // This may also be useful for the inloop reductions, if it can be
836 // kept simple enough.
837 collectCastInstrs(TheLoop, ExitInstruction, RecurrenceType, CastInsts,
838 MinWidthCastToRecurrenceType);
839
840 // We found a reduction var if we have reached the original phi node and we
841 // only have a single instruction with out-of-loop users.
842
843 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
844 // is saved as part of the RecurrenceDescriptor.
845
846 // Save the description of this reduction variable.
847 RedDes =
848 RecurrenceDescriptor(RdxStart, ExitInstruction, IntermediateStore, Kind,
849 FMF, ExactFPMathInst, RecurrenceType, IsSigned,
850 IsOrdered, CastInsts, MinWidthCastToRecurrenceType);
851 return true;
852}
853
854// We are looking for loops that do something like this:
855// int r = 0;
856// for (int i = 0; i < n; i++) {
857// if (src[i] > 3)
858// r = 3;
859// }
860// where the reduction value (r) only has two states, in this example 0 or 3.
861// The generated LLVM IR for this type of loop will be like this:
862// for.body:
863// %r = phi i32 [ %spec.select, %for.body ], [ 0, %entry ]
864// ...
865// %cmp = icmp sgt i32 %5, 3
866// %spec.select = select i1 %cmp, i32 3, i32 %r
867// ...
868// In general we can support vectorization of loops where 'r' flips between
869// any two non-constants, provided they are loop invariant. The only thing
870// we actually care about at the end of the loop is whether or not any lane
871// in the selected vector is different from the start value. The final
872// across-vector reduction after the loop simply involves choosing the start
873// value if nothing changed (0 in the example above) or the other selected
874// value (3 in the example above).
877 Instruction *I, InstDesc &Prev) {
878 // We must handle the select(cmp(),x,y) as a single instruction. Advance to
879 // the select.
880 if (match(I, m_OneUse(m_Cmp()))) {
881 if (auto *Select = dyn_cast<SelectInst>(*I->user_begin()))
882 return InstDesc(Select, Prev.getRecKind());
883 }
884
885 if (!match(I, m_Select(m_Cmp(), m_Value(), m_Value())))
886 return InstDesc(false, I);
887
889 Value *NonPhi = nullptr;
890
891 if (OrigPhi == dyn_cast<PHINode>(SI->getTrueValue()))
892 NonPhi = SI->getFalseValue();
893 else if (OrigPhi == dyn_cast<PHINode>(SI->getFalseValue()))
894 NonPhi = SI->getTrueValue();
895 else
896 return InstDesc(false, I);
897
898 // We are looking for selects of the form:
899 // select(cmp(), phi, loop_invariant) or
900 // select(cmp(), loop_invariant, phi)
901 if (!Loop->isLoopInvariant(NonPhi))
902 return InstDesc(false, I);
903
904 return InstDesc(I, RecurKind::AnyOf);
905}
906
907// We are looking for loops that do something like this:
908// int r = 0;
909// for (int i = 0; i < n; i++) {
910// if (src[i] > 3)
911// r = i;
912// }
913// or like this:
914// int r = 0;
915// for (int i = 0; i < n; i++) {
916// if (src[i] > 3)
917// r = <loop-varying value>;
918// }
919// The reduction value (r) is derived from either the values of an induction
920// variable (i) sequence, an arbitrary loop-varying value, or from the start
921// value (0). The LLVM IR generated for such loops would be as follows:
922// for.body:
923// %r = phi i32 [ %spec.select, %for.body ], [ 0, %entry ]
924// %i = phi i32 [ %inc, %for.body ], [ 0, %entry ]
925// ...
926// %cmp = icmp sgt i32 %5, 3
927// %spec.select = select i1 %cmp, i32 %i, i32 %r
928// %inc = add nsw i32 %i, 1
929// ...
930//
931// When searching for an arbitrary loop-varying value, the reduction value will
932// either be the initial value (0) if the condition was never met, or the value
933// of the loop-varying value in the most recent loop iteration where the
934// condition was met.
938 // TODO: Support the vectorization of FindLastIV when the reduction phi is
939 // used by more than one select instruction. This vectorization is only
940 // performed when the SCEV of each increasing induction variable used by the
941 // select instructions is identical.
942 if (!OrigPhi->hasOneUse())
943 return InstDesc(false, I);
944
945 // We are looking for selects of the form:
946 // select(cmp(), phi, value) or
947 // select(cmp(), value, phi)
948 if (!match(I, m_CombineOr(m_Select(m_Cmp(), m_Value(), m_Specific(OrigPhi)),
949 m_Select(m_Cmp(), m_Specific(OrigPhi), m_Value()))))
950 return InstDesc(false, I);
951
953}
954
955/// Returns true if the select instruction has users in the compare-and-add
956/// reduction pattern below. The select instruction argument is the last one
957/// in the sequence.
958///
959/// %sum.1 = phi ...
960/// ...
961/// %cmp = fcmp pred %0, %CFP
962/// %add = fadd %0, %sum.1
963/// %sum.2 = select %cmp, %add, %sum.1
966 Value *TrueVal, *FalseVal;
967 // Only handle single use cases for now.
968 if (!match(I,
969 m_Select(m_OneUse(m_Cmp()), m_Value(TrueVal), m_Value(FalseVal))))
970 return InstDesc(false, I);
971
972 // Handle only when either of operands of select instruction is a PHI
973 // node for now.
974 if ((isa<PHINode>(TrueVal) && isa<PHINode>(FalseVal)) ||
975 (!isa<PHINode>(TrueVal) && !isa<PHINode>(FalseVal)))
976 return InstDesc(false, I);
977
978 Instruction *I1 = isa<PHINode>(TrueVal) ? dyn_cast<Instruction>(FalseVal)
979 : dyn_cast<Instruction>(TrueVal);
980 if (!I1 || !I1->isBinaryOp())
981 return InstDesc(false, I);
982
983 Value *Op1, *Op2;
984 if (!(((m_FAdd(m_Value(Op1), m_Value(Op2)).match(I1) ||
985 m_FSub(m_Value(Op1), m_Value(Op2)).match(I1)) &&
986 I1->isFast()) ||
987 (m_FMul(m_Value(Op1), m_Value(Op2)).match(I1) && (I1->isFast())) ||
988 ((m_Add(m_Value(Op1), m_Value(Op2)).match(I1) ||
989 m_Sub(m_Value(Op1), m_Value(Op2)).match(I1))) ||
990 (m_Mul(m_Value(Op1), m_Value(Op2)).match(I1))))
991 return InstDesc(false, I);
992
995 if (!IPhi || IPhi != FalseVal)
996 return InstDesc(false, I);
997
998 return InstDesc(true, I);
999}
1000
1003 Instruction *I, RecurKind Kind,
1004 InstDesc &Prev, ScalarEvolution *SE) {
1005 assert(Prev.getRecKind() == RecurKind::None || Prev.getRecKind() == Kind);
1006 switch (I->getOpcode()) {
1007 default:
1008 return InstDesc(false, I);
1009 case Instruction::PHI:
1010 return InstDesc(I, Prev.getRecKind(), Prev.getExactFPMathInst());
1011 case Instruction::Sub:
1012 return InstDesc(
1013 Kind == RecurKind::Sub || Kind == RecurKind::AddChainWithSubs, I);
1014 case Instruction::Add:
1015 return InstDesc(
1016 Kind == RecurKind::Add || Kind == RecurKind::AddChainWithSubs, I);
1017 case Instruction::Mul:
1018 return InstDesc(Kind == RecurKind::Mul, I);
1019 case Instruction::And:
1020 return InstDesc(Kind == RecurKind::And, I);
1021 case Instruction::Or:
1022 return InstDesc(Kind == RecurKind::Or, I);
1023 case Instruction::Xor:
1024 return InstDesc(Kind == RecurKind::Xor, I);
1025 case Instruction::FDiv:
1026 case Instruction::FMul:
1027 return InstDesc(Kind == RecurKind::FMul, I,
1028 I->hasAllowReassoc() ? nullptr : I);
1029 case Instruction::FSub:
1030 return InstDesc(Kind == RecurKind::FSub ||
1032 I, I->hasAllowReassoc() ? nullptr : I);
1033 case Instruction::FAdd:
1034 return InstDesc(Kind == RecurKind::FAdd ||
1036 I, I->hasAllowReassoc() ? nullptr : I);
1037 case Instruction::Select:
1038 if (isSubRecurrenceKind(Kind) || Kind == RecurKind::FAdd ||
1039 Kind == RecurKind::FMul || Kind == RecurKind::Add ||
1040 Kind == RecurKind::Mul || Kind == RecurKind::AddChainWithSubs ||
1042 return isConditionalRdxPattern(I);
1043 if (isFindRecurrenceKind(Kind) && SE)
1044 return isFindPattern(L, OrigPhi, I, *SE);
1045 [[fallthrough]];
1046 case Instruction::FCmp:
1047 case Instruction::ICmp:
1048 case Instruction::Call:
1049 if (isAnyOfRecurrenceKind(Kind))
1050 return isAnyOfPattern(L, OrigPhi, I, Prev);
1051 if (isFMulAddIntrinsic(I))
1052 return InstDesc(Kind == RecurKind::FMulAdd, I,
1053 I->hasAllowReassoc() ? nullptr : I);
1054 return InstDesc(false, I);
1055 }
1056}
1057
1060 unsigned MaxNumUses) {
1061 unsigned NumUses = 0;
1062 for (const Use &U : I->operands()) {
1063 if (Insts.count(dyn_cast<Instruction>(U)))
1064 ++NumUses;
1065 if (NumUses > MaxNumUses)
1066 return true;
1067 }
1068
1069 return false;
1070}
1071
1073 RecurrenceDescriptor &RedDes,
1075 DominatorTree *DT,
1076 ScalarEvolution *SE) {
1077 if (AddReductionVar(Phi, RecurKind::Add, TheLoop, RedDes, DB, AC, DT, SE)) {
1078 LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
1079 return true;
1080 }
1081 if (AddReductionVar(Phi, RecurKind::Sub, TheLoop, RedDes, DB, AC, DT, SE)) {
1082 LLVM_DEBUG(dbgs() << "Found a SUB reduction PHI." << *Phi << "\n");
1083 return true;
1084 }
1085 if (AddReductionVar(Phi, RecurKind::AddChainWithSubs, TheLoop, RedDes, DB, AC,
1086 DT, SE)) {
1087 LLVM_DEBUG(dbgs() << "Found a chained ADD-SUB reduction PHI." << *Phi
1088 << "\n");
1089 return true;
1090 }
1091 if (AddReductionVar(Phi, RecurKind::Mul, TheLoop, RedDes, DB, AC, DT, SE)) {
1092 LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
1093 return true;
1094 }
1095 if (AddReductionVar(Phi, RecurKind::Or, TheLoop, RedDes, DB, AC, DT, SE)) {
1096 LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
1097 return true;
1098 }
1099 if (AddReductionVar(Phi, RecurKind::And, TheLoop, RedDes, DB, AC, DT, SE)) {
1100 LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
1101 return true;
1102 }
1103 if (AddReductionVar(Phi, RecurKind::Xor, TheLoop, RedDes, DB, AC, DT, SE)) {
1104 LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
1105 return true;
1106 }
1107 auto RD = getMinMaxRecurrence(Phi, TheLoop, SE);
1108 if (RD.getRecurrenceKind() != RecurKind::None) {
1109 assert(
1110 RecurrenceDescriptor::isMinMaxRecurrenceKind(RD.getRecurrenceKind()) &&
1111 "Expected a min/max recurrence kind");
1112 LLVM_DEBUG(dbgs() << "Found a min/max reduction PHI." << *Phi << "\n");
1113 RedDes = std::move(RD);
1114 return true;
1115 }
1116 if (AddReductionVar(Phi, RecurKind::AnyOf, TheLoop, RedDes, DB, AC, DT, SE)) {
1117 LLVM_DEBUG(dbgs() << "Found a conditional select reduction PHI." << *Phi
1118 << "\n");
1119 return true;
1120 }
1121 if (AddReductionVar(Phi, RecurKind::FindLast, TheLoop, RedDes, DB, AC, DT,
1122 SE)) {
1123 LLVM_DEBUG(dbgs() << "Found a Find reduction PHI." << *Phi << "\n");
1124 return true;
1125 }
1126 if (AddReductionVar(Phi, RecurKind::FMul, TheLoop, RedDes, DB, AC, DT, SE)) {
1127 LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
1128 return true;
1129 }
1130 if (AddReductionVar(Phi, RecurKind::FSub, TheLoop, RedDes, DB, AC, DT, SE)) {
1131 LLVM_DEBUG(dbgs() << "Found an FSub reduction PHI." << *Phi << "\n");
1132 return true;
1133 }
1134 if (AddReductionVar(Phi, RecurKind::FAdd, TheLoop, RedDes, DB, AC, DT, SE)) {
1135 LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
1136 return true;
1137 }
1138 if (AddReductionVar(Phi, RecurKind::FAddChainWithSubs, TheLoop, RedDes, DB,
1139 AC, DT, SE)) {
1140 LLVM_DEBUG(dbgs() << "Found a chained FADD-FSUB chained reduction PHI."
1141 << *Phi << "\n");
1142 return true;
1143 }
1144 if (AddReductionVar(Phi, RecurKind::FMulAdd, TheLoop, RedDes, DB, AC, DT,
1145 SE)) {
1146 LLVM_DEBUG(dbgs() << "Found an FMulAdd reduction PHI." << *Phi << "\n");
1147 return true;
1148 }
1149
1150 // Not a reduction of known type.
1151 return false;
1152}
1153
1155 DominatorTree *DT) {
1156
1157 // Ensure the phi node is in the loop header and has two incoming values.
1158 if (Phi->getParent() != TheLoop->getHeader() ||
1159 Phi->getNumIncomingValues() != 2)
1160 return false;
1161
1162 // Ensure the loop has a preheader and a single latch block. The loop
1163 // vectorizer will need the latch to set up the next iteration of the loop.
1164 auto *Preheader = TheLoop->getLoopPreheader();
1165 auto *Latch = TheLoop->getLoopLatch();
1166 if (!Preheader || !Latch)
1167 return false;
1168
1169 // Ensure the phi node's incoming blocks are the loop preheader and latch.
1170 if (Phi->getBasicBlockIndex(Preheader) < 0 ||
1171 Phi->getBasicBlockIndex(Latch) < 0)
1172 return false;
1173
1174 // Get the previous value. The previous value comes from the latch edge while
1175 // the initial value comes from the preheader edge.
1176 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
1177
1178 // If Previous is a phi in the header, go through incoming values from the
1179 // latch until we find a non-phi value. Use this as the new Previous, all uses
1180 // in the header will be dominated by the original phi, but need to be moved
1181 // after the non-phi previous value.
1183 while (auto *PrevPhi = dyn_cast_or_null<PHINode>(Previous)) {
1184 if (PrevPhi->getParent() != Phi->getParent())
1185 return false;
1186 if (!SeenPhis.insert(PrevPhi).second)
1187 return false;
1188 Previous = dyn_cast<Instruction>(PrevPhi->getIncomingValueForBlock(Latch));
1189 }
1190
1191 if (!Previous || isa<PHINode>(Previous))
1192 return false;
1193
1194 // Handle recurrences with a loop-invariant latch value.
1195 if (!TheLoop->contains(Previous)) {
1196 assert(DT->dominates(Previous, Phi) &&
1197 "loop-invariant latch value must dominate the header phi");
1198 return true;
1199 }
1200
1201 // Ensure every user of the phi node (recursively) is dominated by the
1202 // previous value. The dominance requirement ensures the loop vectorizer will
1203 // not need to vectorize the initial value prior to the first iteration of the
1204 // loop.
1205 // TODO: Consider extending this sinking to handle memory instructions.
1206
1208 BasicBlock *PhiBB = Phi->getParent();
1210 auto TryToPushSinkCandidate = [&](Instruction *SinkCandidate) {
1211 // Cyclic dependence.
1212 if (Previous == SinkCandidate)
1213 return false;
1214
1215 if (!Seen.insert(SinkCandidate).second)
1216 return true;
1217 if (DT->dominates(Previous,
1218 SinkCandidate)) // We already are good w/o sinking.
1219 return true;
1220
1221 if (SinkCandidate->getParent() != PhiBB ||
1222 SinkCandidate->mayHaveSideEffects() ||
1223 SinkCandidate->mayReadFromMemory() || SinkCandidate->isTerminator())
1224 return false;
1225
1226 // If we reach a PHI node that is not dominated by Previous, we reached a
1227 // header PHI. No need for sinking.
1228 if (isa<PHINode>(SinkCandidate))
1229 return true;
1230
1231 // Sink User tentatively and check its users
1232 WorkList.push_back(SinkCandidate);
1233 return true;
1234 };
1235
1236 WorkList.push_back(Phi);
1237 // Try to recursively sink instructions and their users after Previous.
1238 while (!WorkList.empty()) {
1239 Instruction *Current = WorkList.pop_back_val();
1240 for (User *User : Current->users()) {
1241 if (!TryToPushSinkCandidate(cast<Instruction>(User)))
1242 return false;
1243 }
1244 }
1245
1246 return true;
1247}
1248
1250 switch (Kind) {
1251 case RecurKind::Sub:
1252 return Instruction::Sub;
1254 case RecurKind::Add:
1255 return Instruction::Add;
1256 case RecurKind::Mul:
1257 return Instruction::Mul;
1258 case RecurKind::Or:
1259 return Instruction::Or;
1260 case RecurKind::And:
1261 return Instruction::And;
1262 case RecurKind::Xor:
1263 return Instruction::Xor;
1264 case RecurKind::FMul:
1265 return Instruction::FMul;
1266 case RecurKind::FMulAdd:
1268 case RecurKind::FAdd:
1269 return Instruction::FAdd;
1270 case RecurKind::FSub:
1271 return Instruction::FSub;
1272 case RecurKind::SMax:
1273 case RecurKind::SMin:
1274 case RecurKind::UMax:
1275 case RecurKind::UMin:
1276 return Instruction::ICmp;
1277 case RecurKind::FMax:
1278 case RecurKind::FMin:
1283 return Instruction::FCmp;
1285 case RecurKind::AnyOf:
1286 case RecurKind::FindIV:
1287 // TODO: Set AnyOf and FindIV to Instruction::Select once in-loop reductions
1288 // are supported.
1289 default:
1290 llvm_unreachable("Unknown recurrence operation");
1291 }
1292}
1293
1296 SmallVector<Instruction *, 4> ReductionOperations;
1297 const bool IsMinMax = isMinMaxRecurrenceKind(Kind);
1298
1299 // Search down from the Phi to the LoopExitInstr, looking for instructions
1300 // with a single user of the correct type for the reduction.
1301
1302 // Note that we check that the type of the operand is correct for each item in
1303 // the chain, including the last (the loop exit value). This can come up from
1304 // sub, which would otherwise be treated as an add reduction. MinMax also need
1305 // to check for a pair of icmp/select, for which we use getNextInstruction and
1306 // isCorrectOpcode functions to step the right number of instruction, and
1307 // check the icmp/select pair.
1308 // FIXME: We also do not attempt to look through Select's yet, which might
1309 // be part of the reduction chain, or attempt to looks through And's to find a
1310 // smaller bitwidth. Subs are also currently not allowed (which are usually
1311 // treated as part of a add reduction) as they are expected to generally be
1312 // more expensive than out-of-loop reductions, and need to be costed more
1313 // carefully.
1314 unsigned ExpectedUses = 1;
1315 if (IsMinMax)
1316 ExpectedUses = 2;
1317
1318 auto getNextInstruction = [&](Instruction *Cur) -> Instruction * {
1319 for (auto *User : Cur->users()) {
1321 if (isa<PHINode>(UI))
1322 continue;
1323 if (IsMinMax) {
1324 // We are expecting a icmp/select pair, which we go to the next select
1325 // instruction if we can. We already know that Cur has 2 uses.
1326 if (isa<SelectInst>(UI))
1327 return UI;
1328 continue;
1329 }
1330 return UI;
1331 }
1332 return nullptr;
1333 };
1334 auto isCorrectOpcode = [&](Instruction *Cur) {
1335 if (IsMinMax) {
1336 Value *LHS, *RHS;
1338 matchSelectPattern(Cur, LHS, RHS).Flavor);
1339 }
1340 // Recognize a call to the llvm.fmuladd intrinsic.
1341 if (isFMulAddIntrinsic(Cur))
1342 return true;
1343
1344 if (Cur->getOpcode() == Instruction::Sub &&
1346 return true;
1347
1348 if (Cur->getOpcode() == Instruction::FSub &&
1350 return true;
1351
1352 return Cur->getOpcode() == getOpcode();
1353 };
1354
1355 // Attempt to look through Phis which are part of the reduction chain
1356 unsigned ExtraPhiUses = 0;
1357 Instruction *RdxInstr = LoopExitInstr;
1358 if (auto ExitPhi = dyn_cast<PHINode>(LoopExitInstr)) {
1359 if (ExitPhi->getNumIncomingValues() != 2)
1360 return {};
1361
1362 Instruction *Inc0 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(0));
1363 Instruction *Inc1 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(1));
1364
1365 Instruction *Chain = nullptr;
1366 if (Inc0 == Phi)
1367 Chain = Inc1;
1368 else if (Inc1 == Phi)
1369 Chain = Inc0;
1370 else
1371 return {};
1372
1373 RdxInstr = Chain;
1374 ExtraPhiUses = 1;
1375 }
1376
1377 // The loop exit instruction we check first (as a quick test) but add last. We
1378 // check the opcode is correct (and dont allow them to be Subs) and that they
1379 // have expected to have the expected number of uses. They will have one use
1380 // from the phi and one from a LCSSA value, no matter the type.
1381 if (!isCorrectOpcode(RdxInstr) || !LoopExitInstr->hasNUses(2))
1382 return {};
1383
1384 // Check that the Phi has one (or two for min/max) uses, plus an extra use
1385 // for conditional reductions.
1386 if (!Phi->hasNUses(ExpectedUses + ExtraPhiUses))
1387 return {};
1388
1389 Instruction *Cur = getNextInstruction(Phi);
1390
1391 // Each other instruction in the chain should have the expected number of uses
1392 // and be the correct opcode.
1393 while (Cur != RdxInstr) {
1394 if (!Cur || !isCorrectOpcode(Cur) || !Cur->hasNUses(ExpectedUses))
1395 return {};
1396
1397 ReductionOperations.push_back(Cur);
1398 Cur = getNextInstruction(Cur);
1399 }
1400
1401 ReductionOperations.push_back(Cur);
1402 return ReductionOperations;
1403}
1404
1406 Value *Start, InductionKind K, const SCEV *Step, BinaryOperator *BOp,
1409 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
1410 assert(IK != IK_NoInduction && "Not an induction");
1411
1412 // Start value type should match the induction kind and the value
1413 // itself should not be null.
1414 assert(StartValue && "StartValue is null");
1415 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
1416 "StartValue is not a pointer for pointer induction");
1417 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
1418 "StartValue is not an integer for integer induction");
1419
1420 // Check the Step Value. It should be non-zero integer value.
1421 assert((!getConstStepValue() || !getConstStepValue()->isZero()) &&
1422 "Step value is zero");
1423
1424 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
1425 "StepValue is not an integer");
1426
1427 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
1428 "StepValue is not FP for FpInduction");
1429 assert((IK != IK_FpInduction ||
1430 (InductionBinOp &&
1431 (InductionBinOp->getOpcode() == Instruction::FAdd ||
1432 InductionBinOp->getOpcode() == Instruction::FSub))) &&
1433 "Binary opcode should be specified for FP induction");
1434
1435 if (Casts)
1436 llvm::append_range(RedundantCasts, *Casts);
1437 llvm::append_range(NoWrapPredicates, NoWrapPreds);
1438}
1439
1445
1446std::optional<APInt> InductionDescriptor::getConstStepValue() const {
1447 if (auto *ConstStep = dyn_cast<SCEVConstant>(Step))
1448 return ConstStep->getValue()->getValue();
1449 return {};
1450}
1451
1453 ScalarEvolution *SE,
1455
1456 // Here we only handle FP induction variables.
1457 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
1458
1459 if (TheLoop->getHeader() != Phi->getParent())
1460 return false;
1461
1462 // The loop may have multiple entrances or multiple exits; we can analyze
1463 // this phi if it has a unique entry value and a unique backedge value.
1464 if (Phi->getNumIncomingValues() != 2)
1465 return false;
1466 Value *BEValue = nullptr, *StartValue = nullptr;
1467 if (TheLoop->contains(Phi->getIncomingBlock(0))) {
1468 BEValue = Phi->getIncomingValue(0);
1469 StartValue = Phi->getIncomingValue(1);
1470 } else {
1471 assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
1472 "Unexpected Phi node in the loop");
1473 BEValue = Phi->getIncomingValue(1);
1474 StartValue = Phi->getIncomingValue(0);
1475 }
1476
1478 if (!BOp)
1479 return false;
1480
1481 Value *Addend = nullptr;
1482 if (BOp->getOpcode() == Instruction::FAdd) {
1483 if (BOp->getOperand(0) == Phi)
1484 Addend = BOp->getOperand(1);
1485 else if (BOp->getOperand(1) == Phi)
1486 Addend = BOp->getOperand(0);
1487 } else if (BOp->getOpcode() == Instruction::FSub)
1488 if (BOp->getOperand(0) == Phi)
1489 Addend = BOp->getOperand(1);
1490
1491 if (!Addend)
1492 return false;
1493
1494 // The addend should be loop invariant
1495 if (auto *I = dyn_cast<Instruction>(Addend))
1496 if (TheLoop->contains(I))
1497 return false;
1498
1499 // FP Step has unknown SCEV
1500 const SCEV *Step = SE->getUnknown(Addend);
1501 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
1502 return true;
1503}
1504
1505/// This function is called when we suspect that the update-chain of a phi node
1506/// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
1507/// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
1508/// predicate P under which the SCEV expression for the phi can be the
1509/// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
1510/// cast instructions that are involved in the update-chain of this induction.
1511/// A caller that adds the required runtime predicate can be free to drop these
1512/// cast instructions, and compute the phi using \p AR (instead of some scev
1513/// expression with casts).
1514///
1515/// For example, without a predicate the scev expression can take the following
1516/// form:
1517/// (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
1518///
1519/// It corresponds to the following IR sequence:
1520/// %for.body:
1521/// %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
1522/// %casted_phi = "ExtTrunc i64 %x"
1523/// %add = add i64 %casted_phi, %step
1524///
1525/// where %x is given in \p PN,
1526/// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
1527/// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
1528/// several forms, for example, such as:
1529/// ExtTrunc1: %casted_phi = and %x, 2^n-1
1530/// or:
1531/// ExtTrunc2: %t = shl %x, m
1532/// %casted_phi = ashr %t, m
1533///
1534/// If we are able to find such sequence, we return the instructions
1535/// we found, namely %casted_phi and the instructions on its use-def chain up
1536/// to the phi (not including the phi).
1537static bool
1539 const SCEVUnknown *PhiScev, const SCEVAddRecExpr *AR,
1541 ArrayRef<const SCEVPredicate *> NoWrapPreds) {
1542
1543 assert(CastInsts.empty() && "CastInsts is expected to be empty.");
1544 auto *PN = cast<PHINode>(PhiScev->getValue());
1545
1546 // Build a predicate to rewrite SCEVs of values in the cast chain using the
1547 // predicates needed for this induction.
1548 ScalarEvolution &SE = *PSE.getSE();
1549 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
1550 const Loop *L = AR->getLoop();
1551 assert(SE.rewriteUsingPredicate(SE.getSCEV(PN), L, NoWrapUnionPred) == AR &&
1552 "Unexpected phi node SCEV expression");
1553
1554 // Find any cast instructions that participate in the def-use chain of
1555 // PhiScev in the loop.
1556 // FORNOW/TODO: We currently expect the def-use chain to include only
1557 // two-operand instructions, where one of the operands is an invariant.
1558 // createAddRecFromPHIWithCasts() currently does not support anything more
1559 // involved than that, so we keep the search simple. This can be
1560 // extended/generalized as needed.
1561
1562 auto getDef = [&](const Value *Val) -> Value * {
1563 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
1564 if (!BinOp)
1565 return nullptr;
1566 Value *Op0 = BinOp->getOperand(0);
1567 Value *Op1 = BinOp->getOperand(1);
1568 Value *Def = nullptr;
1569 if (L->isLoopInvariant(Op0))
1570 Def = Op1;
1571 else if (L->isLoopInvariant(Op1))
1572 Def = Op0;
1573 return Def;
1574 };
1575
1576 // Look for the instruction that defines the induction via the
1577 // loop backedge.
1578 BasicBlock *Latch = L->getLoopLatch();
1579 if (!Latch)
1580 return false;
1581 Value *Val = PN->getIncomingValueForBlock(Latch);
1582 if (!Val)
1583 return false;
1584
1585 // Follow the def-use chain until the induction phi is reached.
1586 // If on the way we encounter a Value that has the same SCEV Expr as the
1587 // phi node, we can consider the instructions we visit from that point
1588 // as part of the cast-sequence that can be ignored.
1589 bool InCastSequence = false;
1590 auto *Inst = dyn_cast<Instruction>(Val);
1591 while (Val != PN) {
1592 // If we encountered a phi node other than PN, or if we left the loop,
1593 // we bail out.
1594 if (!Inst || !L->contains(Inst)) {
1595 return false;
1596 }
1597 // Create AddRec with NoWrapPredicates applied.
1598 auto *AddRec = dyn_cast<SCEVAddRecExpr>(
1599 SE.rewriteUsingPredicate(SE.getSCEV(Val), L, NoWrapUnionPred));
1600 if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR, NoWrapPreds))
1601 InCastSequence = true;
1602 if (InCastSequence) {
1603 // Only the last instruction in the cast sequence is expected to have
1604 // uses outside the induction def-use chain.
1605 if (!CastInsts.empty())
1606 if (!Inst->hasOneUse())
1607 return false;
1608 CastInsts.push_back(Inst);
1609 }
1610 Val = getDef(Val);
1611 if (!Val)
1612 return false;
1613 Inst = dyn_cast<Instruction>(Val);
1614 }
1615
1616 return InCastSequence;
1617}
1618
1621 InductionDescriptor &D, bool Assume) {
1622 Type *PhiTy = Phi->getType();
1623
1624 // Handle integer and pointer inductions variables.
1625 // Now we handle also FP induction but not trying to make a
1626 // recurrent expression from the PHI node in-place.
1627
1628 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() &&
1629 !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
1630 return false;
1631
1632 if (PhiTy->isFloatingPointTy())
1633 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
1634
1635 const SCEV *PhiScev = PSE.getSCEV(Phi);
1636 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1637
1638 // Collect predicates needed to force the SCEV into an AddRecExpr.
1640
1641 // We need this expression to be an AddRecExpr.
1642 if (Assume && !AR)
1643 AR = PSE.getAsAddRec(Phi, &Preds);
1644
1645 if (!AR) {
1646 LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1647 return false;
1648 }
1649
1650 // Record any Cast instructions that participate in the induction update
1651 const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
1652 // If we started from an UnknownSCEV, and managed to build an addRecurrence
1653 // only after enabling Assume with PSCEV, this means we may have encountered
1654 // cast instructions that required adding a runtime check in order to
1655 // guarantee the correctness of the AddRecurrence respresentation of the
1656 // induction.
1657 if (PhiScev != AR && SymbolicPhi) {
1659 if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts, Preds))
1660 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, Preds, AR, &Casts);
1661 }
1662
1663 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, Preds, AR);
1664}
1665
1667 PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
1669 const SCEV *Expr, SmallVectorImpl<Instruction *> *CastsToIgnore) {
1670 Type *PhiTy = Phi->getType();
1671 // isSCEVable returns true for integer and pointer types.
1672 if (!SE->isSCEVable(PhiTy))
1673 return false;
1674
1675 // Check that the PHI is consecutive.
1676 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
1677 const SCEV *Step;
1678
1679 // FIXME: We are currently matching the specific loop TheLoop; if it doesn't
1680 // match, we should treat it as a uniform. Unfortunately, we don't currently
1681 // know how to handled uniform PHIs.
1682 if (!match(PhiScev, m_scev_AffineAddRec(m_SCEV(), m_SCEV(Step),
1683 m_SpecificLoop(TheLoop)))) {
1684 LLVM_DEBUG(
1685 dbgs() << "LV: PHI is not a poly recurrence for requested loop.\n");
1686 return false;
1687 }
1688
1689 // This function assumes that InductionPhi is called only on Phi nodes
1690 // present inside loop headers. Check for the same, and throw an assert if
1691 // the current Phi is not present inside the loop header.
1692 assert(Phi->getParent() == TheLoop->getHeader() &&
1693 "Invalid Phi node, not present in loop header");
1694
1695 if (!TheLoop->getLoopPreheader())
1696 return false;
1697
1698 Value *StartValue =
1699 Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1700
1701 BasicBlock *Latch = TheLoop->getLoopLatch();
1702 if (!Latch)
1703 return false;
1704
1705 if (PhiTy->isIntegerTy()) {
1706 BinaryOperator *BOp =
1707 dyn_cast<BinaryOperator>(Phi->getIncomingValueForBlock(Latch));
1708 D = InductionDescriptor(StartValue, IK_IntInduction, Step, BOp,
1709 CastsToIgnore, Preds);
1710 return true;
1711 }
1712
1713 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1714
1715 // This allows induction variables w/non-constant steps.
1716 D = InductionDescriptor(StartValue, IK_PtrInduction, Step,
1717 /*InductionBinOp=*/nullptr, /*Casts=*/nullptr, Preds);
1718 return true;
1719}
1720
1721// Recognize a conditional induction PHI by matching the following pattern:
1722// loop_header:
1723// %conditional_iv = phi [ %start, %preheader ], [ %latch_phi, %latch ]
1724// br i1 %do_step, label %step_bb, label %latch
1725//
1726// step_bb:
1727// %step = add/gep %conditional_iv, %step_val
1728// br label %latch
1729//
1730// latch:
1731// %latch_phi = phi [ %conditional_iv, %loop_header ], [ %step, %step_bb ]
1732// br label %loop_header
1735 ScalarEvolution &SE) {
1736 BasicBlock *Preheader = L->getLoopPreheader();
1737 if (!Preheader)
1738 return false;
1739
1740 BasicBlock *Latch = L->getLoopLatch();
1741 if (!Latch || !PN->getType()->isIntOrPtrTy() ||
1742 PN->getParent() != L->getHeader())
1743 return false;
1744
1745 auto *BackedgePHI = dyn_cast<PHINode>(PN->getIncomingValueForBlock(Latch));
1746 if (!BackedgePHI)
1747 return false;
1748
1749 // Ensure the only users of the backedge PHI are outside the loop or the
1750 // header PHI (PN).
1751 for (User *U : BackedgePHI->users()) {
1752 auto *UI = cast<Instruction>(U);
1753 if (UI != PN && L->contains(UI))
1754 return false;
1755 }
1756
1757 // Find the step operation used to increment the conditional induction PHI.
1758 // TODO: Support chains of PHIs.
1759 Value *StepOp =
1760 find_singleton<Value>(BackedgePHI->incoming_values(),
1761 [&](Use &Incoming, bool /*AllowRepeats*/) {
1762 return Incoming != PN ? Incoming.get() : nullptr;
1763 });
1764 if (!StepOp || !StepOp->hasOneUse())
1765 return false;
1766
1767 auto *StepInst = dyn_cast<Instruction>(StepOp);
1768 if (!StepInst)
1769 return false;
1770
1771 Value *Step = nullptr;
1772 bool StepMatch =
1773 PN->getType()->isPointerTy()
1774 ? match(StepInst, m_PtrAdd(m_Specific(PN), m_Value(Step)))
1775 : match(StepInst, m_c_Add(m_Specific(PN), m_Value(Step)));
1776 if (!StepMatch || !L->isLoopInvariant(Step))
1777 return false;
1778
1779 // Ensure GEP offsets are extended to the size of the PHI.
1780 const SCEV *StepSCEV = SE.getTruncateOrSignExtend(
1781 SE.getSCEV(Step), SE.getEffectiveSCEVType(PN->getType()));
1782
1783 if (StepSCEV->isZero())
1784 return false;
1785
1786 Value *Start = PN->getIncomingValueForBlock(Preheader);
1787 const SCEV *StartSCEV = SE.getSCEV(Start);
1788
1789 SCEVFlags NoWrapFlags = SCEV::FlagNone;
1790 if (auto *GEP = dyn_cast<GEPOperator>(StepInst)) {
1791 // With NUSW, we can add NUW if the step is non-negative. We can't add NSW
1792 // as the base address is unsigned.
1793 if (GEP->hasNoUnsignedWrap() ||
1794 (GEP->hasNoUnsignedSignedWrap() && SE.isKnownNonNegative(StepSCEV)))
1795 NoWrapFlags = ScalarEvolution::setFlags(NoWrapFlags, SCEV::FlagNUW);
1796 } else if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(StepInst)) {
1797 if (OBO->hasNoUnsignedWrap())
1798 NoWrapFlags = ScalarEvolution::setFlags(NoWrapFlags, SCEV::FlagNUW);
1799 if (OBO->hasNoSignedWrap())
1800 NoWrapFlags = ScalarEvolution::setFlags(NoWrapFlags, SCEV::FlagNSW);
1801 }
1802
1803 LLVM_DEBUG(dbgs() << "LV: Found a conditional induction phi: HeaderPHI: "
1804 << *PN << ", StepInst: " << *StepInst << "\n");
1805
1806 Desc = ConditionalInductionDescriptor(PN, BackedgePHI, StepInst, StartSCEV,
1807 StepSCEV, NoWrapFlags);
1808 return true;
1809}
1810
1811const SCEV *
1813 const Loop &L) const {
1814 assert(L.contains(HeaderPHI) &&
1815 "The provided loop does not contain this conditional induction");
1817}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Hexagon Common GEP
static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE, const SCEVUnknown *PhiScev, const SCEVAddRecExpr *AR, SmallVectorImpl< Instruction * > &CastInsts, ArrayRef< const SCEVPredicate * > NoWrapPreds)
This function is called when we suspect that the update-chain of a phi node (whose symbolic SCEV expr...
static std::optional< FastMathFlags > hasRequiredFastMathFlags(FPMathOperator *FPOp, RecurKind &RK)
static void collectCastInstrs(Loop *TheLoop, Instruction *Exit, Type *RecurrenceType, SmallPtrSetImpl< Instruction * > &Casts, unsigned &MinWidthCastToRecurTy)
Collect cast instructions that can be ignored in the vectorizer's cost model, given a reduction exit ...
static bool checkOrderedReduction(RecurKind Kind, Instruction *ExactFPMathInst, Instruction *Exit, PHINode *Phi)
static bool isFindLastLikePhi(PHINode *Phi, PHINode *HeaderPhi, SmallPtrSetImpl< Instruction * > &ReductionInstrs)
static Instruction * lookThroughAnd(PHINode *Phi, Type *&RT, SmallPtrSetImpl< Instruction * > &Visited, SmallPtrSetImpl< Instruction * > &CI)
Determines if Phi may have been type-promoted.
static FastMathFlags collectMinMaxFMF(Value *V)
static RecurrenceDescriptor getMinMaxRecurrence(PHINode *Phi, Loop *TheLoop, ScalarEvolution *SE)
static std::pair< Type *, bool > computeRecurrenceType(Instruction *Exit, DemandedBits *DB, AssumptionCache *AC, DominatorTree *DT)
Compute the minimal bit width needed to represent a reduction whose exit instruction is given by Exit...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
#define I(x, y, z)
Definition MD5.cpp:57
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Class for arbitrary precision integers.
Definition APInt.h:78
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI bool isConditionalInductionPHI(PHINode *PN, const Loop *L, ConditionalInductionDescriptor &Desc, ScalarEvolution &SE)
Returns true if PN is a conditional induction variable in the loop L.
const SCEV * getStartSCEV() const
Returns a SCEV expression for the initial value of the conditional induction PHI.
LLVM_ABI const SCEV * getUnconditionalAddRec(ScalarEvolution &SE, const Loop &L) const
Returns an over-approximation of the conditional induction as a SCEVAddRec assuming the condition is ...
const SCEV * getStepSCEV() const
Returns a SCEV expression for the step of the conditional induction PHI.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
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.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
bool hasNoNaNs() const
Test if this operation's arguments and results are assumed not-NaN.
Definition Operator.h:270
bool hasNoSignedZeros() const
Test if this operation can ignore the sign of zero.
Definition Operator.h:276
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
static FastMathFlags getFast()
Definition FMF.h:50
A struct for saving information about induction variables.
static LLVM_ABI InductionDescriptor getCanonicalIntInduction(Type *Ty, ScalarEvolution &SE)
Returns the canonical integer induction for type Ty with start = 0 and step = 1.
LLVM_ABI std::optional< APInt > getConstStepValue() const
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.
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
static LLVM_ABI bool isFPInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D)
Returns true if Phi is a floating point induction in the loop L.
InductionDescriptor()=default
Default constructor - creates an invalid induction.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
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.
BlockT * getHeader() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:68
Value * getIncomingValueForBlock(const BasicBlock *BB) const
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
This POD struct holds information about a potential recurrence operation.
Instruction * getExactFPMathInst() const
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
static bool isFPMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating-point min/max kind.
static bool isFMulAddIntrinsic(Instruction *I)
Returns true if the instruction is a call to the llvm.fmuladd intrinsic.
static LLVM_ABI bool isFixedOrderRecurrence(PHINode *Phi, Loop *TheLoop, DominatorTree *DT)
Returns true if Phi is a fixed-order recurrence.
static LLVM_ABI InstDesc isConditionalRdxPattern(Instruction *I)
Returns a struct describing if the instruction is a Select(FCmp(X, Y), (Z = X op PHINode),...
static LLVM_ABI bool hasMultipleUsesOf(Instruction *I, SmallPtrSetImpl< Instruction * > &Insts, unsigned MaxNumUses)
Returns true if instruction I has multiple uses in Insts.
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.
static LLVM_ABI bool areAllUsesIn(Instruction *I, SmallPtrSetImpl< Instruction * > &Set)
Returns true if all uses of the instruction I is within the Set.
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...
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static LLVM_ABI InstDesc isAnyOfPattern(Loop *Loop, PHINode *OrigPhi, Instruction *I, InstDesc &Prev)
Returns a struct describing whether the instruction is either a Select(ICmp(A, B),...
static LLVM_ABI bool isSubRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is for a sub operation.
StoreInst * IntermediateStore
Reductions may store temporary or final result to an invariant address.
static bool isFindRecurrenceKind(RecurKind Kind)
static LLVM_ABI bool isFloatingPointRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating point kind.
static LLVM_ABI InstDesc isRecurrenceInstr(Loop *L, PHINode *Phi, Instruction *I, RecurKind Kind, InstDesc &Prev, ScalarEvolution *SE)
Returns a struct describing if the instruction 'I' can be a recurrence variable of type 'Kind' for a ...
static LLVM_ABI bool AddReductionVar(PHINode *Phi, RecurKind Kind, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction of type Kind and adds it to the RecurrenceDescriptor.
static LLVM_ABI InstDesc isFindPattern(Loop *TheLoop, PHINode *OrigPhi, Instruction *I, ScalarEvolution &SE)
Returns a struct describing whether the instruction is either a Select(ICmp(A, B),...
static LLVM_ABI bool isIntegerRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is an integer kind.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This node represents a polynomial recurrence on the trip count of the specified loop.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents an analyzed expression in the program.
static constexpr auto FlagNUW
static constexpr auto FlagNSW
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
The main scalar evolution driver.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
static SCEVFlags setFlags(SCEVFlags Flags, SCEVFlags OnFlags)
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI SCEVUse getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEVFlagsPair Flags)
Get an add recurrence expression for the specified loop.
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 bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI const SCEV * getUnknown(Value *V)
LLVM_ABI const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
This class represents the LLVM 'select' instruction.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Value * getValueOperand()
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
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
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:143
bool use_empty() const
Definition Value.h:348
const ParentTy * getParent() const
Definition ilist_node.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type.
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FMinimum(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
auto m_FMaximum(const Opnd0 &Op0, const Opnd1 &Op1)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmax_pred_ty >, FMaxMin_match< LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
specificloop_ty m_SpecificLoop(const Loop *L)
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
MachineInstr * getDef(const MachineOperand &MO, const MachineRegisterInfo *MRI)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
Op::Description Desc
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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
T * find_singleton(R &&Range, Predicate P, bool AllowRepeats=false)
Return the single value in Range that satisfies P(<member of Range> *, AllowRepeats)->T * returning n...
Definition STLExtras.h:1853
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
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.
@ FindIV
FindIV reduction with select(icmp(),x,y) where one of (x,y) is a loop induction variable (increasing ...
@ Or
Bitwise or logical OR of integers.
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ Mul
Product of integers.
@ FSub
Subtraction of floats.
@ FAddChainWithSubs
A chain of fadds and fsubs.
@ None
Not a recurrence.
@ 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.
@ FindLast
FindLast reduction with select(cmp(),x,y) where x and y.
@ 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()).
@ FMinNum
FP min with llvm.minnum semantics including NaNs.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ FAdd
Sum of floats.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
DWARFExpression::Operation Op
SCEVFlags
SCEVFlags are bitfield indices into SCEV's SubclassData.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?