1 //===- llvm/Analysis/IVDescriptors.cpp - IndVar Descriptors -----*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file "describes" induction and recurrence variables.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Analysis/IVDescriptors.h"
14 #include "llvm/ADT/ScopeExit.h"
15 #include "llvm/Analysis/BasicAliasAnalysis.h"
16 #include "llvm/Analysis/DemandedBits.h"
17 #include "llvm/Analysis/DomTreeUpdater.h"
18 #include "llvm/Analysis/GlobalsModRef.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/MustExecute.h"
23 #include "llvm/Analysis/ScalarEvolution.h"
24 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/KnownBits.h"
40 using namespace llvm::PatternMatch
;
42 #define DEBUG_TYPE "iv-descriptors"
44 bool RecurrenceDescriptor::areAllUsesIn(Instruction
*I
,
45 SmallPtrSetImpl
<Instruction
*> &Set
) {
46 for (User::op_iterator Use
= I
->op_begin(), E
= I
->op_end(); Use
!= E
; ++Use
)
47 if (!Set
.count(dyn_cast
<Instruction
>(*Use
)))
52 bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurKind Kind
) {
70 bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurKind Kind
) {
71 return (Kind
!= RecurKind::None
) && !isIntegerRecurrenceKind(Kind
);
74 bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurKind Kind
) {
87 /// Determines if Phi may have been type-promoted. If Phi has a single user
88 /// that ANDs the Phi with a type mask, return the user. RT is updated to
89 /// account for the narrower bit width represented by the mask, and the AND
90 /// instruction is added to CI.
91 static Instruction
*lookThroughAnd(PHINode
*Phi
, Type
*&RT
,
92 SmallPtrSetImpl
<Instruction
*> &Visited
,
93 SmallPtrSetImpl
<Instruction
*> &CI
) {
94 if (!Phi
->hasOneUse())
97 const APInt
*M
= nullptr;
98 Instruction
*I
, *J
= cast
<Instruction
>(Phi
->use_begin()->getUser());
100 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
101 // with a new integer type of the corresponding bit width.
102 if (match(J
, m_c_And(m_Instruction(I
), m_APInt(M
)))) {
103 int32_t Bits
= (*M
+ 1).exactLogBase2();
105 RT
= IntegerType::get(Phi
->getContext(), Bits
);
114 /// Compute the minimal bit width needed to represent a reduction whose exit
115 /// instruction is given by Exit.
116 static std::pair
<Type
*, bool> computeRecurrenceType(Instruction
*Exit
,
120 bool IsSigned
= false;
121 const DataLayout
&DL
= Exit
->getModule()->getDataLayout();
122 uint64_t MaxBitWidth
= DL
.getTypeSizeInBits(Exit
->getType());
125 // Use the demanded bits analysis to determine the bits that are live out
126 // of the exit instruction, rounding up to the nearest power of two. If the
127 // use of demanded bits results in a smaller bit width, we know the value
128 // must be positive (i.e., IsSigned = false), because if this were not the
129 // case, the sign bit would have been demanded.
130 auto Mask
= DB
->getDemandedBits(Exit
);
131 MaxBitWidth
= Mask
.getBitWidth() - Mask
.countLeadingZeros();
134 if (MaxBitWidth
== DL
.getTypeSizeInBits(Exit
->getType()) && AC
&& DT
) {
135 // If demanded bits wasn't able to limit the bit width, we can try to use
136 // value tracking instead. This can be the case, for example, if the value
138 auto NumSignBits
= ComputeNumSignBits(Exit
, DL
, 0, AC
, nullptr, DT
);
139 auto NumTypeBits
= DL
.getTypeSizeInBits(Exit
->getType());
140 MaxBitWidth
= NumTypeBits
- NumSignBits
;
141 KnownBits Bits
= computeKnownBits(Exit
, DL
);
142 if (!Bits
.isNonNegative()) {
143 // If the value is not known to be non-negative, we set IsSigned to true,
144 // meaning that we will use sext instructions instead of zext
145 // instructions to restore the original type.
147 if (!Bits
.isNegative())
148 // If the value is not known to be negative, we don't known what the
149 // upper bit is, and therefore, we don't know what kind of extend we
150 // will need. In this case, just increase the bit width by one bit and
155 if (!isPowerOf2_64(MaxBitWidth
))
156 MaxBitWidth
= NextPowerOf2(MaxBitWidth
);
158 return std::make_pair(Type::getIntNTy(Exit
->getContext(), MaxBitWidth
),
162 /// Collect cast instructions that can be ignored in the vectorizer's cost
163 /// model, given a reduction exit value and the minimal type in which the
164 /// reduction can be represented.
165 static void collectCastsToIgnore(Loop
*TheLoop
, Instruction
*Exit
,
166 Type
*RecurrenceType
,
167 SmallPtrSetImpl
<Instruction
*> &Casts
) {
169 SmallVector
<Instruction
*, 8> Worklist
;
170 SmallPtrSet
<Instruction
*, 8> Visited
;
171 Worklist
.push_back(Exit
);
173 while (!Worklist
.empty()) {
174 Instruction
*Val
= Worklist
.pop_back_val();
176 if (auto *Cast
= dyn_cast
<CastInst
>(Val
))
177 if (Cast
->getSrcTy() == RecurrenceType
) {
178 // If the source type of a cast instruction is equal to the recurrence
179 // type, it will be eliminated, and should be ignored in the vectorizer
185 // Add all operands to the work list if they are loop-varying values that
186 // we haven't yet visited.
187 for (Value
*O
: cast
<User
>(Val
)->operands())
188 if (auto *I
= dyn_cast
<Instruction
>(O
))
189 if (TheLoop
->contains(I
) && !Visited
.count(I
))
190 Worklist
.push_back(I
);
194 // Check if a given Phi node can be recognized as an ordered reduction for
195 // vectorizing floating point operations without unsafe math.
196 static bool checkOrderedReduction(RecurKind Kind
, Instruction
*ExactFPMathInst
,
197 Instruction
*Exit
, PHINode
*Phi
) {
198 // Currently only FAdd is supported
199 if (Kind
!= RecurKind::FAdd
)
202 if (Exit
->getOpcode() != Instruction::FAdd
|| Exit
!= ExactFPMathInst
)
205 // The only pattern accepted is the one in which the reduction PHI
206 // is used as one of the operands of the exit instruction
207 auto *LHS
= Exit
->getOperand(0);
208 auto *RHS
= Exit
->getOperand(1);
209 if (LHS
!= Phi
&& RHS
!= Phi
)
212 LLVM_DEBUG(dbgs() << "LV: Found an ordered reduction: Phi: " << *Phi
213 << ", ExitInst: " << *Exit
<< "\n");
218 bool RecurrenceDescriptor::AddReductionVar(PHINode
*Phi
, RecurKind Kind
,
219 Loop
*TheLoop
, FastMathFlags FuncFMF
,
220 RecurrenceDescriptor
&RedDes
,
224 if (Phi
->getNumIncomingValues() != 2)
227 // Reduction variables are only found in the loop header block.
228 if (Phi
->getParent() != TheLoop
->getHeader())
231 // Obtain the reduction start value from the value that comes from the loop
233 Value
*RdxStart
= Phi
->getIncomingValueForBlock(TheLoop
->getLoopPreheader());
235 // ExitInstruction is the single value which is used outside the loop.
236 // We only allow for a single reduction value to be used outside the loop.
237 // This includes users of the reduction, variables (which form a cycle
238 // which ends in the phi node).
239 Instruction
*ExitInstruction
= nullptr;
240 // Indicates that we found a reduction operation in our scan.
241 bool FoundReduxOp
= false;
243 // We start with the PHI node and scan for all of the users of this
244 // instruction. All users must be instructions that can be used as reduction
245 // variables (such as ADD). We must have a single out-of-block user. The cycle
246 // must include the original PHI.
247 bool FoundStartPHI
= false;
249 // To recognize min/max patterns formed by a icmp select sequence, we store
250 // the number of instruction we saw from the recognized min/max pattern,
251 // to make sure we only see exactly the two instructions.
252 unsigned NumCmpSelectPatternInst
= 0;
253 InstDesc
ReduxDesc(false, nullptr);
255 // Data used for determining if the recurrence has been type-promoted.
256 Type
*RecurrenceType
= Phi
->getType();
257 SmallPtrSet
<Instruction
*, 4> CastInsts
;
258 Instruction
*Start
= Phi
;
259 bool IsSigned
= false;
261 SmallPtrSet
<Instruction
*, 8> VisitedInsts
;
262 SmallVector
<Instruction
*, 8> Worklist
;
264 // Return early if the recurrence kind does not match the type of Phi. If the
265 // recurrence kind is arithmetic, we attempt to look through AND operations
266 // resulting from the type promotion performed by InstCombine. Vector
267 // operations are not limited to the legal integer widths, so we may be able
268 // to evaluate the reduction in the narrower width.
269 if (RecurrenceType
->isFloatingPointTy()) {
270 if (!isFloatingPointRecurrenceKind(Kind
))
272 } else if (RecurrenceType
->isIntegerTy()) {
273 if (!isIntegerRecurrenceKind(Kind
))
275 if (!isMinMaxRecurrenceKind(Kind
))
276 Start
= lookThroughAnd(Phi
, RecurrenceType
, VisitedInsts
, CastInsts
);
278 // Pointer min/max may exist, but it is not supported as a reduction op.
282 Worklist
.push_back(Start
);
283 VisitedInsts
.insert(Start
);
285 // Start with all flags set because we will intersect this with the reduction
286 // flags from all the reduction operations.
287 FastMathFlags FMF
= FastMathFlags::getFast();
289 // A value in the reduction can be used:
290 // - By the reduction:
291 // - Reduction operation:
292 // - One use of reduction value (safe).
293 // - Multiple use of reduction value (not safe).
295 // - All uses of the PHI must be the reduction (safe).
296 // - Otherwise, not safe.
297 // - By instructions outside of the loop (safe).
298 // * One value may have several outside users, but all outside
299 // uses must be of the same value.
300 // - By an instruction that is not part of the reduction (not safe).
302 // * An instruction type other than PHI or the reduction operation.
303 // * A PHI in the header other than the initial PHI.
304 while (!Worklist
.empty()) {
305 Instruction
*Cur
= Worklist
.pop_back_val();
308 // If the instruction has no users then this is a broken chain and can't be
309 // a reduction variable.
310 if (Cur
->use_empty())
313 bool IsAPhi
= isa
<PHINode
>(Cur
);
315 // A header PHI use other than the original PHI.
316 if (Cur
!= Phi
&& IsAPhi
&& Cur
->getParent() == Phi
->getParent())
319 // Reductions of instructions such as Div, and Sub is only possible if the
320 // LHS is the reduction variable.
321 if (!Cur
->isCommutative() && !IsAPhi
&& !isa
<SelectInst
>(Cur
) &&
322 !isa
<ICmpInst
>(Cur
) && !isa
<FCmpInst
>(Cur
) &&
323 !VisitedInsts
.count(dyn_cast
<Instruction
>(Cur
->getOperand(0))))
326 // Any reduction instruction must be of one of the allowed kinds. We ignore
327 // the starting value (the Phi or an AND instruction if the Phi has been
330 ReduxDesc
= isRecurrenceInstr(Cur
, Kind
, ReduxDesc
, FuncFMF
);
331 if (!ReduxDesc
.isRecurrence())
333 // FIXME: FMF is allowed on phi, but propagation is not handled correctly.
334 if (isa
<FPMathOperator
>(ReduxDesc
.getPatternInst()) && !IsAPhi
) {
335 FastMathFlags CurFMF
= ReduxDesc
.getPatternInst()->getFastMathFlags();
336 if (auto *Sel
= dyn_cast
<SelectInst
>(ReduxDesc
.getPatternInst())) {
337 // Accept FMF on either fcmp or select of a min/max idiom.
338 // TODO: This is a hack to work-around the fact that FMF may not be
339 // assigned/propagated correctly. If that problem is fixed or we
340 // standardize on fmin/fmax via intrinsics, this can be removed.
341 if (auto *FCmp
= dyn_cast
<FCmpInst
>(Sel
->getCondition()))
342 CurFMF
|= FCmp
->getFastMathFlags();
346 // Update this reduction kind if we matched a new instruction.
347 // TODO: Can we eliminate the need for a 2nd InstDesc by keeping 'Kind'
348 // state accurate while processing the worklist?
349 if (ReduxDesc
.getRecKind() != RecurKind::None
)
350 Kind
= ReduxDesc
.getRecKind();
353 bool IsASelect
= isa
<SelectInst
>(Cur
);
355 // A conditional reduction operation must only have 2 or less uses in
357 if (IsASelect
&& (Kind
== RecurKind::FAdd
|| Kind
== RecurKind::FMul
) &&
358 hasMultipleUsesOf(Cur
, VisitedInsts
, 2))
361 // A reduction operation must only have one use of the reduction value.
362 if (!IsAPhi
&& !IsASelect
&& !isMinMaxRecurrenceKind(Kind
) &&
363 hasMultipleUsesOf(Cur
, VisitedInsts
, 1))
366 // All inputs to a PHI node must be a reduction value.
367 if (IsAPhi
&& Cur
!= Phi
&& !areAllUsesIn(Cur
, VisitedInsts
))
370 if (isIntMinMaxRecurrenceKind(Kind
) &&
371 (isa
<ICmpInst
>(Cur
) || isa
<SelectInst
>(Cur
)))
372 ++NumCmpSelectPatternInst
;
373 if (isFPMinMaxRecurrenceKind(Kind
) &&
374 (isa
<FCmpInst
>(Cur
) || isa
<SelectInst
>(Cur
)))
375 ++NumCmpSelectPatternInst
;
377 // Check whether we found a reduction operator.
378 FoundReduxOp
|= !IsAPhi
&& Cur
!= Start
;
380 // Process users of current instruction. Push non-PHI nodes after PHI nodes
381 // onto the stack. This way we are going to have seen all inputs to PHI
382 // nodes once we get to them.
383 SmallVector
<Instruction
*, 8> NonPHIs
;
384 SmallVector
<Instruction
*, 8> PHIs
;
385 for (User
*U
: Cur
->users()) {
386 Instruction
*UI
= cast
<Instruction
>(U
);
388 // Check if we found the exit user.
389 BasicBlock
*Parent
= UI
->getParent();
390 if (!TheLoop
->contains(Parent
)) {
391 // If we already know this instruction is used externally, move on to
393 if (ExitInstruction
== Cur
)
396 // Exit if you find multiple values used outside or if the header phi
397 // node is being used. In this case the user uses the value of the
398 // previous iteration, in which case we would loose "VF-1" iterations of
399 // the reduction operation if we vectorize.
400 if (ExitInstruction
!= nullptr || Cur
== Phi
)
403 // The instruction used by an outside user must be the last instruction
404 // before we feed back to the reduction phi. Otherwise, we loose VF-1
405 // operations on the value.
406 if (!is_contained(Phi
->operands(), Cur
))
409 ExitInstruction
= Cur
;
413 // Process instructions only once (termination). Each reduction cycle
414 // value must only be used once, except by phi nodes and min/max
415 // reductions which are represented as a cmp followed by a select.
416 InstDesc
IgnoredVal(false, nullptr);
417 if (VisitedInsts
.insert(UI
).second
) {
418 if (isa
<PHINode
>(UI
))
421 NonPHIs
.push_back(UI
);
422 } else if (!isa
<PHINode
>(UI
) &&
423 ((!isa
<FCmpInst
>(UI
) && !isa
<ICmpInst
>(UI
) &&
424 !isa
<SelectInst
>(UI
)) ||
425 (!isConditionalRdxPattern(Kind
, UI
).isRecurrence() &&
426 !isMinMaxSelectCmpPattern(UI
, IgnoredVal
).isRecurrence())))
429 // Remember that we completed the cycle.
431 FoundStartPHI
= true;
433 Worklist
.append(PHIs
.begin(), PHIs
.end());
434 Worklist
.append(NonPHIs
.begin(), NonPHIs
.end());
437 // This means we have seen one but not the other instruction of the
438 // pattern or more than just a select and cmp.
439 if (isMinMaxRecurrenceKind(Kind
) && NumCmpSelectPatternInst
!= 2)
442 if (!FoundStartPHI
|| !FoundReduxOp
|| !ExitInstruction
)
445 const bool IsOrdered
= checkOrderedReduction(
446 Kind
, ReduxDesc
.getExactFPMathInst(), ExitInstruction
, Phi
);
449 // If the starting value is not the same as the phi node, we speculatively
450 // looked through an 'and' instruction when evaluating a potential
451 // arithmetic reduction to determine if it may have been type-promoted.
453 // We now compute the minimal bit width that is required to represent the
454 // reduction. If this is the same width that was indicated by the 'and', we
455 // can represent the reduction in the smaller type. The 'and' instruction
456 // will be eliminated since it will essentially be a cast instruction that
457 // can be ignore in the cost model. If we compute a different type than we
458 // did when evaluating the 'and', the 'and' will not be eliminated, and we
459 // will end up with different kinds of operations in the recurrence
460 // expression (e.g., IntegerAND, IntegerADD). We give up if this is
463 // The vectorizer relies on InstCombine to perform the actual
464 // type-shrinking. It does this by inserting instructions to truncate the
465 // exit value of the reduction to the width indicated by RecurrenceType and
466 // then extend this value back to the original width. If IsSigned is false,
467 // a 'zext' instruction will be generated; otherwise, a 'sext' will be
470 // TODO: We should not rely on InstCombine to rewrite the reduction in the
471 // smaller type. We should just generate a correctly typed expression
474 std::tie(ComputedType
, IsSigned
) =
475 computeRecurrenceType(ExitInstruction
, DB
, AC
, DT
);
476 if (ComputedType
!= RecurrenceType
)
479 // The recurrence expression will be represented in a narrower type. If
480 // there are any cast instructions that will be unnecessary, collect them
481 // in CastInsts. Note that the 'and' instruction was already included in
484 // TODO: A better way to represent this may be to tag in some way all the
485 // instructions that are a part of the reduction. The vectorizer cost
486 // model could then apply the recurrence type to these instructions,
487 // without needing a white list of instructions to ignore.
488 // This may also be useful for the inloop reductions, if it can be
489 // kept simple enough.
490 collectCastsToIgnore(TheLoop
, ExitInstruction
, RecurrenceType
, CastInsts
);
493 // We found a reduction var if we have reached the original phi node and we
494 // only have a single instruction with out-of-loop users.
496 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
497 // is saved as part of the RecurrenceDescriptor.
499 // Save the description of this reduction variable.
500 RecurrenceDescriptor
RD(RdxStart
, ExitInstruction
, Kind
, FMF
,
501 ReduxDesc
.getExactFPMathInst(), RecurrenceType
,
502 IsSigned
, IsOrdered
, CastInsts
);
508 RecurrenceDescriptor::InstDesc
509 RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction
*I
,
510 const InstDesc
&Prev
) {
511 assert((isa
<CmpInst
>(I
) || isa
<SelectInst
>(I
)) &&
512 "Expected a cmp or select instruction");
514 // We must handle the select(cmp()) as a single instruction. Advance to the
516 CmpInst::Predicate Pred
;
517 if (match(I
, m_OneUse(m_Cmp(Pred
, m_Value(), m_Value())))) {
518 if (auto *Select
= dyn_cast
<SelectInst
>(*I
->user_begin()))
519 return InstDesc(Select
, Prev
.getRecKind());
522 // Only match select with single use cmp condition.
523 if (!match(I
, m_Select(m_OneUse(m_Cmp(Pred
, m_Value(), m_Value())), m_Value(),
525 return InstDesc(false, I
);
527 // Look for a min/max pattern.
528 if (match(I
, m_UMin(m_Value(), m_Value())))
529 return InstDesc(I
, RecurKind::UMin
);
530 if (match(I
, m_UMax(m_Value(), m_Value())))
531 return InstDesc(I
, RecurKind::UMax
);
532 if (match(I
, m_SMax(m_Value(), m_Value())))
533 return InstDesc(I
, RecurKind::SMax
);
534 if (match(I
, m_SMin(m_Value(), m_Value())))
535 return InstDesc(I
, RecurKind::SMin
);
536 if (match(I
, m_OrdFMin(m_Value(), m_Value())))
537 return InstDesc(I
, RecurKind::FMin
);
538 if (match(I
, m_OrdFMax(m_Value(), m_Value())))
539 return InstDesc(I
, RecurKind::FMax
);
540 if (match(I
, m_UnordFMin(m_Value(), m_Value())))
541 return InstDesc(I
, RecurKind::FMin
);
542 if (match(I
, m_UnordFMax(m_Value(), m_Value())))
543 return InstDesc(I
, RecurKind::FMax
);
545 return InstDesc(false, I
);
548 /// Returns true if the select instruction has users in the compare-and-add
549 /// reduction pattern below. The select instruction argument is the last one
554 /// %cmp = fcmp pred %0, %CFP
555 /// %add = fadd %0, %sum.1
556 /// %sum.2 = select %cmp, %add, %sum.1
557 RecurrenceDescriptor::InstDesc
558 RecurrenceDescriptor::isConditionalRdxPattern(RecurKind Kind
, Instruction
*I
) {
559 SelectInst
*SI
= dyn_cast
<SelectInst
>(I
);
561 return InstDesc(false, I
);
563 CmpInst
*CI
= dyn_cast
<CmpInst
>(SI
->getCondition());
564 // Only handle single use cases for now.
565 if (!CI
|| !CI
->hasOneUse())
566 return InstDesc(false, I
);
568 Value
*TrueVal
= SI
->getTrueValue();
569 Value
*FalseVal
= SI
->getFalseValue();
570 // Handle only when either of operands of select instruction is a PHI
572 if ((isa
<PHINode
>(*TrueVal
) && isa
<PHINode
>(*FalseVal
)) ||
573 (!isa
<PHINode
>(*TrueVal
) && !isa
<PHINode
>(*FalseVal
)))
574 return InstDesc(false, I
);
577 isa
<PHINode
>(*TrueVal
) ? dyn_cast
<Instruction
>(FalseVal
)
578 : dyn_cast
<Instruction
>(TrueVal
);
579 if (!I1
|| !I1
->isBinaryOp())
580 return InstDesc(false, I
);
583 if ((m_FAdd(m_Value(Op1
), m_Value(Op2
)).match(I1
) ||
584 m_FSub(m_Value(Op1
), m_Value(Op2
)).match(I1
)) &&
586 return InstDesc(Kind
== RecurKind::FAdd
, SI
);
588 if (m_FMul(m_Value(Op1
), m_Value(Op2
)).match(I1
) && (I1
->isFast()))
589 return InstDesc(Kind
== RecurKind::FMul
, SI
);
591 return InstDesc(false, I
);
594 RecurrenceDescriptor::InstDesc
595 RecurrenceDescriptor::isRecurrenceInstr(Instruction
*I
, RecurKind Kind
,
596 InstDesc
&Prev
, FastMathFlags FMF
) {
597 switch (I
->getOpcode()) {
599 return InstDesc(false, I
);
600 case Instruction::PHI
:
601 return InstDesc(I
, Prev
.getRecKind(), Prev
.getExactFPMathInst());
602 case Instruction::Sub
:
603 case Instruction::Add
:
604 return InstDesc(Kind
== RecurKind::Add
, I
);
605 case Instruction::Mul
:
606 return InstDesc(Kind
== RecurKind::Mul
, I
);
607 case Instruction::And
:
608 return InstDesc(Kind
== RecurKind::And
, I
);
609 case Instruction::Or
:
610 return InstDesc(Kind
== RecurKind::Or
, I
);
611 case Instruction::Xor
:
612 return InstDesc(Kind
== RecurKind::Xor
, I
);
613 case Instruction::FDiv
:
614 case Instruction::FMul
:
615 return InstDesc(Kind
== RecurKind::FMul
, I
,
616 I
->hasAllowReassoc() ? nullptr : I
);
617 case Instruction::FSub
:
618 case Instruction::FAdd
:
619 return InstDesc(Kind
== RecurKind::FAdd
, I
,
620 I
->hasAllowReassoc() ? nullptr : I
);
621 case Instruction::Select
:
622 if (Kind
== RecurKind::FAdd
|| Kind
== RecurKind::FMul
)
623 return isConditionalRdxPattern(Kind
, I
);
625 case Instruction::FCmp
:
626 case Instruction::ICmp
:
627 if (isIntMinMaxRecurrenceKind(Kind
) ||
628 (FMF
.noNaNs() && FMF
.noSignedZeros() && isFPMinMaxRecurrenceKind(Kind
)))
629 return isMinMaxSelectCmpPattern(I
, Prev
);
630 return InstDesc(false, I
);
634 bool RecurrenceDescriptor::hasMultipleUsesOf(
635 Instruction
*I
, SmallPtrSetImpl
<Instruction
*> &Insts
,
636 unsigned MaxNumUses
) {
637 unsigned NumUses
= 0;
638 for (const Use
&U
: I
->operands()) {
639 if (Insts
.count(dyn_cast
<Instruction
>(U
)))
641 if (NumUses
> MaxNumUses
)
648 bool RecurrenceDescriptor::isReductionPHI(PHINode
*Phi
, Loop
*TheLoop
,
649 RecurrenceDescriptor
&RedDes
,
650 DemandedBits
*DB
, AssumptionCache
*AC
,
653 BasicBlock
*Header
= TheLoop
->getHeader();
654 Function
&F
= *Header
->getParent();
657 F
.getFnAttribute("no-nans-fp-math").getValueAsBool());
658 FMF
.setNoSignedZeros(
659 F
.getFnAttribute("no-signed-zeros-fp-math").getValueAsBool());
661 if (AddReductionVar(Phi
, RecurKind::Add
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
662 LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi
<< "\n");
665 if (AddReductionVar(Phi
, RecurKind::Mul
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
666 LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi
<< "\n");
669 if (AddReductionVar(Phi
, RecurKind::Or
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
670 LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi
<< "\n");
673 if (AddReductionVar(Phi
, RecurKind::And
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
674 LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi
<< "\n");
677 if (AddReductionVar(Phi
, RecurKind::Xor
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
678 LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi
<< "\n");
681 if (AddReductionVar(Phi
, RecurKind::SMax
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
682 LLVM_DEBUG(dbgs() << "Found a SMAX reduction PHI." << *Phi
<< "\n");
685 if (AddReductionVar(Phi
, RecurKind::SMin
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
686 LLVM_DEBUG(dbgs() << "Found a SMIN reduction PHI." << *Phi
<< "\n");
689 if (AddReductionVar(Phi
, RecurKind::UMax
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
690 LLVM_DEBUG(dbgs() << "Found a UMAX reduction PHI." << *Phi
<< "\n");
693 if (AddReductionVar(Phi
, RecurKind::UMin
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
694 LLVM_DEBUG(dbgs() << "Found a UMIN reduction PHI." << *Phi
<< "\n");
697 if (AddReductionVar(Phi
, RecurKind::FMul
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
698 LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi
<< "\n");
701 if (AddReductionVar(Phi
, RecurKind::FAdd
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
702 LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi
<< "\n");
705 if (AddReductionVar(Phi
, RecurKind::FMax
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
706 LLVM_DEBUG(dbgs() << "Found a float MAX reduction PHI." << *Phi
<< "\n");
709 if (AddReductionVar(Phi
, RecurKind::FMin
, TheLoop
, FMF
, RedDes
, DB
, AC
, DT
)) {
710 LLVM_DEBUG(dbgs() << "Found a float MIN reduction PHI." << *Phi
<< "\n");
713 // Not a reduction of known type.
717 bool RecurrenceDescriptor::isFirstOrderRecurrence(
718 PHINode
*Phi
, Loop
*TheLoop
,
719 MapVector
<Instruction
*, Instruction
*> &SinkAfter
, DominatorTree
*DT
) {
721 // Ensure the phi node is in the loop header and has two incoming values.
722 if (Phi
->getParent() != TheLoop
->getHeader() ||
723 Phi
->getNumIncomingValues() != 2)
726 // Ensure the loop has a preheader and a single latch block. The loop
727 // vectorizer will need the latch to set up the next iteration of the loop.
728 auto *Preheader
= TheLoop
->getLoopPreheader();
729 auto *Latch
= TheLoop
->getLoopLatch();
730 if (!Preheader
|| !Latch
)
733 // Ensure the phi node's incoming blocks are the loop preheader and latch.
734 if (Phi
->getBasicBlockIndex(Preheader
) < 0 ||
735 Phi
->getBasicBlockIndex(Latch
) < 0)
738 // Get the previous value. The previous value comes from the latch edge while
739 // the initial value comes form the preheader edge.
740 auto *Previous
= dyn_cast
<Instruction
>(Phi
->getIncomingValueForBlock(Latch
));
741 if (!Previous
|| !TheLoop
->contains(Previous
) || isa
<PHINode
>(Previous
) ||
742 SinkAfter
.count(Previous
)) // Cannot rely on dominance due to motion.
745 // Ensure every user of the phi node (recursively) is dominated by the
746 // previous value. The dominance requirement ensures the loop vectorizer will
747 // not need to vectorize the initial value prior to the first iteration of the
749 // TODO: Consider extending this sinking to handle memory instructions.
751 // We optimistically assume we can sink all users after Previous. Keep a set
752 // of instructions to sink after Previous ordered by dominance in the common
753 // basic block. It will be applied to SinkAfter if all users can be sunk.
754 auto CompareByComesBefore
= [](const Instruction
*A
, const Instruction
*B
) {
755 return A
->comesBefore(B
);
757 std::set
<Instruction
*, decltype(CompareByComesBefore
)> InstrsToSink(
758 CompareByComesBefore
);
760 BasicBlock
*PhiBB
= Phi
->getParent();
761 SmallVector
<Instruction
*, 8> WorkList
;
762 auto TryToPushSinkCandidate
= [&](Instruction
*SinkCandidate
) {
763 // Already sunk SinkCandidate.
764 if (SinkCandidate
->getParent() == PhiBB
&&
765 InstrsToSink
.find(SinkCandidate
) != InstrsToSink
.end())
768 // Cyclic dependence.
769 if (Previous
== SinkCandidate
)
772 if (DT
->dominates(Previous
,
773 SinkCandidate
)) // We already are good w/o sinking.
776 if (SinkCandidate
->getParent() != PhiBB
||
777 SinkCandidate
->mayHaveSideEffects() ||
778 SinkCandidate
->mayReadFromMemory() || SinkCandidate
->isTerminator())
781 // Do not try to sink an instruction multiple times (if multiple operands
782 // are first order recurrences).
783 // TODO: We can support this case, by sinking the instruction after the
784 // 'deepest' previous instruction.
785 if (SinkAfter
.find(SinkCandidate
) != SinkAfter
.end())
788 // If we reach a PHI node that is not dominated by Previous, we reached a
789 // header PHI. No need for sinking.
790 if (isa
<PHINode
>(SinkCandidate
))
793 // Sink User tentatively and check its users
794 InstrsToSink
.insert(SinkCandidate
);
795 WorkList
.push_back(SinkCandidate
);
799 WorkList
.push_back(Phi
);
800 // Try to recursively sink instructions and their users after Previous.
801 while (!WorkList
.empty()) {
802 Instruction
*Current
= WorkList
.pop_back_val();
803 for (User
*User
: Current
->users()) {
804 if (!TryToPushSinkCandidate(cast
<Instruction
>(User
)))
809 // We can sink all users of Phi. Update the mapping.
810 for (Instruction
*I
: InstrsToSink
) {
811 SinkAfter
[I
] = Previous
;
817 /// This function returns the identity element (or neutral element) for
819 Constant
*RecurrenceDescriptor::getRecurrenceIdentity(RecurKind K
, Type
*Tp
,
825 // Adding, Xoring, Oring zero to a number does not change it.
826 return ConstantInt::get(Tp
, 0);
828 // Multiplying a number by 1 does not change it.
829 return ConstantInt::get(Tp
, 1);
831 // AND-ing a number with an all-1 value does not change it.
832 return ConstantInt::get(Tp
, -1, true);
833 case RecurKind::FMul
:
834 // Multiplying a number by 1 does not change it.
835 return ConstantFP::get(Tp
, 1.0L);
836 case RecurKind::FAdd
:
837 // Adding zero to a number does not change it.
838 // FIXME: Ideally we should not need to check FMF for FAdd and should always
839 // use -0.0. However, this will currently result in mixed vectors of 0.0/-0.0.
840 // Instead, we should ensure that 1) the FMF from FAdd are propagated to the PHI
841 // nodes where possible, and 2) PHIs with the nsz flag + -0.0 use 0.0. This would
842 // mean we can then remove the check for noSignedZeros() below (see D98963).
843 if (FMF
.noSignedZeros())
844 return ConstantFP::get(Tp
, 0.0L);
845 return ConstantFP::get(Tp
, -0.0L);
846 case RecurKind::UMin
:
847 return ConstantInt::get(Tp
, -1);
848 case RecurKind::UMax
:
849 return ConstantInt::get(Tp
, 0);
850 case RecurKind::SMin
:
851 return ConstantInt::get(Tp
,
852 APInt::getSignedMaxValue(Tp
->getIntegerBitWidth()));
853 case RecurKind::SMax
:
854 return ConstantInt::get(Tp
,
855 APInt::getSignedMinValue(Tp
->getIntegerBitWidth()));
856 case RecurKind::FMin
:
857 return ConstantFP::getInfinity(Tp
, true);
858 case RecurKind::FMax
:
859 return ConstantFP::getInfinity(Tp
, false);
861 llvm_unreachable("Unknown recurrence kind");
865 unsigned RecurrenceDescriptor::getOpcode(RecurKind Kind
) {
868 return Instruction::Add
;
870 return Instruction::Mul
;
872 return Instruction::Or
;
874 return Instruction::And
;
876 return Instruction::Xor
;
877 case RecurKind::FMul
:
878 return Instruction::FMul
;
879 case RecurKind::FAdd
:
880 return Instruction::FAdd
;
881 case RecurKind::SMax
:
882 case RecurKind::SMin
:
883 case RecurKind::UMax
:
884 case RecurKind::UMin
:
885 return Instruction::ICmp
;
886 case RecurKind::FMax
:
887 case RecurKind::FMin
:
888 return Instruction::FCmp
;
890 llvm_unreachable("Unknown recurrence operation");
894 SmallVector
<Instruction
*, 4>
895 RecurrenceDescriptor::getReductionOpChain(PHINode
*Phi
, Loop
*L
) const {
896 SmallVector
<Instruction
*, 4> ReductionOperations
;
897 unsigned RedOp
= getOpcode(Kind
);
899 // Search down from the Phi to the LoopExitInstr, looking for instructions
900 // with a single user of the correct type for the reduction.
902 // Note that we check that the type of the operand is correct for each item in
903 // the chain, including the last (the loop exit value). This can come up from
904 // sub, which would otherwise be treated as an add reduction. MinMax also need
905 // to check for a pair of icmp/select, for which we use getNextInstruction and
906 // isCorrectOpcode functions to step the right number of instruction, and
907 // check the icmp/select pair.
908 // FIXME: We also do not attempt to look through Phi/Select's yet, which might
909 // be part of the reduction chain, or attempt to looks through And's to find a
910 // smaller bitwidth. Subs are also currently not allowed (which are usually
911 // treated as part of a add reduction) as they are expected to generally be
912 // more expensive than out-of-loop reductions, and need to be costed more
914 unsigned ExpectedUses
= 1;
915 if (RedOp
== Instruction::ICmp
|| RedOp
== Instruction::FCmp
)
918 auto getNextInstruction
= [&](Instruction
*Cur
) {
919 if (RedOp
== Instruction::ICmp
|| RedOp
== Instruction::FCmp
) {
920 // We are expecting a icmp/select pair, which we go to the next select
921 // instruction if we can. We already know that Cur has 2 uses.
922 if (isa
<SelectInst
>(*Cur
->user_begin()))
923 return cast
<Instruction
>(*Cur
->user_begin());
925 return cast
<Instruction
>(*std::next(Cur
->user_begin()));
927 return cast
<Instruction
>(*Cur
->user_begin());
929 auto isCorrectOpcode
= [&](Instruction
*Cur
) {
930 if (RedOp
== Instruction::ICmp
|| RedOp
== Instruction::FCmp
) {
932 return SelectPatternResult::isMinOrMax(
933 matchSelectPattern(Cur
, LHS
, RHS
).Flavor
);
935 return Cur
->getOpcode() == RedOp
;
938 // The loop exit instruction we check first (as a quick test) but add last. We
939 // check the opcode is correct (and dont allow them to be Subs) and that they
940 // have expected to have the expected number of uses. They will have one use
941 // from the phi and one from a LCSSA value, no matter the type.
942 if (!isCorrectOpcode(LoopExitInstr
) || !LoopExitInstr
->hasNUses(2))
945 // Check that the Phi has one (or two for min/max) uses.
946 if (!Phi
->hasNUses(ExpectedUses
))
948 Instruction
*Cur
= getNextInstruction(Phi
);
950 // Each other instruction in the chain should have the expected number of uses
951 // and be the correct opcode.
952 while (Cur
!= LoopExitInstr
) {
953 if (!isCorrectOpcode(Cur
) || !Cur
->hasNUses(ExpectedUses
))
956 ReductionOperations
.push_back(Cur
);
957 Cur
= getNextInstruction(Cur
);
960 ReductionOperations
.push_back(Cur
);
961 return ReductionOperations
;
964 InductionDescriptor::InductionDescriptor(Value
*Start
, InductionKind K
,
965 const SCEV
*Step
, BinaryOperator
*BOp
,
966 SmallVectorImpl
<Instruction
*> *Casts
)
967 : StartValue(Start
), IK(K
), Step(Step
), InductionBinOp(BOp
) {
968 assert(IK
!= IK_NoInduction
&& "Not an induction");
970 // Start value type should match the induction kind and the value
971 // itself should not be null.
972 assert(StartValue
&& "StartValue is null");
973 assert((IK
!= IK_PtrInduction
|| StartValue
->getType()->isPointerTy()) &&
974 "StartValue is not a pointer for pointer induction");
975 assert((IK
!= IK_IntInduction
|| StartValue
->getType()->isIntegerTy()) &&
976 "StartValue is not an integer for integer induction");
978 // Check the Step Value. It should be non-zero integer value.
979 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
980 "Step value is zero");
982 assert((IK
!= IK_PtrInduction
|| getConstIntStepValue()) &&
983 "Step value should be constant for pointer induction");
984 assert((IK
== IK_FpInduction
|| Step
->getType()->isIntegerTy()) &&
985 "StepValue is not an integer");
987 assert((IK
!= IK_FpInduction
|| Step
->getType()->isFloatingPointTy()) &&
988 "StepValue is not FP for FpInduction");
989 assert((IK
!= IK_FpInduction
||
991 (InductionBinOp
->getOpcode() == Instruction::FAdd
||
992 InductionBinOp
->getOpcode() == Instruction::FSub
))) &&
993 "Binary opcode should be specified for FP induction");
996 for (auto &Inst
: *Casts
) {
997 RedundantCasts
.push_back(Inst
);
1002 ConstantInt
*InductionDescriptor::getConstIntStepValue() const {
1003 if (isa
<SCEVConstant
>(Step
))
1004 return dyn_cast
<ConstantInt
>(cast
<SCEVConstant
>(Step
)->getValue());
1008 bool InductionDescriptor::isFPInductionPHI(PHINode
*Phi
, const Loop
*TheLoop
,
1009 ScalarEvolution
*SE
,
1010 InductionDescriptor
&D
) {
1012 // Here we only handle FP induction variables.
1013 assert(Phi
->getType()->isFloatingPointTy() && "Unexpected Phi type");
1015 if (TheLoop
->getHeader() != Phi
->getParent())
1018 // The loop may have multiple entrances or multiple exits; we can analyze
1019 // this phi if it has a unique entry value and a unique backedge value.
1020 if (Phi
->getNumIncomingValues() != 2)
1022 Value
*BEValue
= nullptr, *StartValue
= nullptr;
1023 if (TheLoop
->contains(Phi
->getIncomingBlock(0))) {
1024 BEValue
= Phi
->getIncomingValue(0);
1025 StartValue
= Phi
->getIncomingValue(1);
1027 assert(TheLoop
->contains(Phi
->getIncomingBlock(1)) &&
1028 "Unexpected Phi node in the loop");
1029 BEValue
= Phi
->getIncomingValue(1);
1030 StartValue
= Phi
->getIncomingValue(0);
1033 BinaryOperator
*BOp
= dyn_cast
<BinaryOperator
>(BEValue
);
1037 Value
*Addend
= nullptr;
1038 if (BOp
->getOpcode() == Instruction::FAdd
) {
1039 if (BOp
->getOperand(0) == Phi
)
1040 Addend
= BOp
->getOperand(1);
1041 else if (BOp
->getOperand(1) == Phi
)
1042 Addend
= BOp
->getOperand(0);
1043 } else if (BOp
->getOpcode() == Instruction::FSub
)
1044 if (BOp
->getOperand(0) == Phi
)
1045 Addend
= BOp
->getOperand(1);
1050 // The addend should be loop invariant
1051 if (auto *I
= dyn_cast
<Instruction
>(Addend
))
1052 if (TheLoop
->contains(I
))
1055 // FP Step has unknown SCEV
1056 const SCEV
*Step
= SE
->getUnknown(Addend
);
1057 D
= InductionDescriptor(StartValue
, IK_FpInduction
, Step
, BOp
);
1061 /// This function is called when we suspect that the update-chain of a phi node
1062 /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
1063 /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
1064 /// predicate P under which the SCEV expression for the phi can be the
1065 /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
1066 /// cast instructions that are involved in the update-chain of this induction.
1067 /// A caller that adds the required runtime predicate can be free to drop these
1068 /// cast instructions, and compute the phi using \p AR (instead of some scev
1069 /// expression with casts).
1071 /// For example, without a predicate the scev expression can take the following
1073 /// (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
1075 /// It corresponds to the following IR sequence:
1077 /// %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
1078 /// %casted_phi = "ExtTrunc i64 %x"
1079 /// %add = add i64 %casted_phi, %step
1081 /// where %x is given in \p PN,
1082 /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
1083 /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
1084 /// several forms, for example, such as:
1085 /// ExtTrunc1: %casted_phi = and %x, 2^n-1
1087 /// ExtTrunc2: %t = shl %x, m
1088 /// %casted_phi = ashr %t, m
1090 /// If we are able to find such sequence, we return the instructions
1091 /// we found, namely %casted_phi and the instructions on its use-def chain up
1092 /// to the phi (not including the phi).
1093 static bool getCastsForInductionPHI(PredicatedScalarEvolution
&PSE
,
1094 const SCEVUnknown
*PhiScev
,
1095 const SCEVAddRecExpr
*AR
,
1096 SmallVectorImpl
<Instruction
*> &CastInsts
) {
1098 assert(CastInsts
.empty() && "CastInsts is expected to be empty.");
1099 auto *PN
= cast
<PHINode
>(PhiScev
->getValue());
1100 assert(PSE
.getSCEV(PN
) == AR
&& "Unexpected phi node SCEV expression");
1101 const Loop
*L
= AR
->getLoop();
1103 // Find any cast instructions that participate in the def-use chain of
1104 // PhiScev in the loop.
1105 // FORNOW/TODO: We currently expect the def-use chain to include only
1106 // two-operand instructions, where one of the operands is an invariant.
1107 // createAddRecFromPHIWithCasts() currently does not support anything more
1108 // involved than that, so we keep the search simple. This can be
1109 // extended/generalized as needed.
1111 auto getDef
= [&](const Value
*Val
) -> Value
* {
1112 const BinaryOperator
*BinOp
= dyn_cast
<BinaryOperator
>(Val
);
1115 Value
*Op0
= BinOp
->getOperand(0);
1116 Value
*Op1
= BinOp
->getOperand(1);
1117 Value
*Def
= nullptr;
1118 if (L
->isLoopInvariant(Op0
))
1120 else if (L
->isLoopInvariant(Op1
))
1125 // Look for the instruction that defines the induction via the
1127 BasicBlock
*Latch
= L
->getLoopLatch();
1130 Value
*Val
= PN
->getIncomingValueForBlock(Latch
);
1134 // Follow the def-use chain until the induction phi is reached.
1135 // If on the way we encounter a Value that has the same SCEV Expr as the
1136 // phi node, we can consider the instructions we visit from that point
1137 // as part of the cast-sequence that can be ignored.
1138 bool InCastSequence
= false;
1139 auto *Inst
= dyn_cast
<Instruction
>(Val
);
1141 // If we encountered a phi node other than PN, or if we left the loop,
1143 if (!Inst
|| !L
->contains(Inst
)) {
1146 auto *AddRec
= dyn_cast
<SCEVAddRecExpr
>(PSE
.getSCEV(Val
));
1147 if (AddRec
&& PSE
.areAddRecsEqualWithPreds(AddRec
, AR
))
1148 InCastSequence
= true;
1149 if (InCastSequence
) {
1150 // Only the last instruction in the cast sequence is expected to have
1151 // uses outside the induction def-use chain.
1152 if (!CastInsts
.empty())
1153 if (!Inst
->hasOneUse())
1155 CastInsts
.push_back(Inst
);
1160 Inst
= dyn_cast
<Instruction
>(Val
);
1163 return InCastSequence
;
1166 bool InductionDescriptor::isInductionPHI(PHINode
*Phi
, const Loop
*TheLoop
,
1167 PredicatedScalarEvolution
&PSE
,
1168 InductionDescriptor
&D
, bool Assume
) {
1169 Type
*PhiTy
= Phi
->getType();
1171 // Handle integer and pointer inductions variables.
1172 // Now we handle also FP induction but not trying to make a
1173 // recurrent expression from the PHI node in-place.
1175 if (!PhiTy
->isIntegerTy() && !PhiTy
->isPointerTy() && !PhiTy
->isFloatTy() &&
1176 !PhiTy
->isDoubleTy() && !PhiTy
->isHalfTy())
1179 if (PhiTy
->isFloatingPointTy())
1180 return isFPInductionPHI(Phi
, TheLoop
, PSE
.getSE(), D
);
1182 const SCEV
*PhiScev
= PSE
.getSCEV(Phi
);
1183 const auto *AR
= dyn_cast
<SCEVAddRecExpr
>(PhiScev
);
1185 // We need this expression to be an AddRecExpr.
1187 AR
= PSE
.getAsAddRec(Phi
);
1190 LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1194 // Record any Cast instructions that participate in the induction update
1195 const auto *SymbolicPhi
= dyn_cast
<SCEVUnknown
>(PhiScev
);
1196 // If we started from an UnknownSCEV, and managed to build an addRecurrence
1197 // only after enabling Assume with PSCEV, this means we may have encountered
1198 // cast instructions that required adding a runtime check in order to
1199 // guarantee the correctness of the AddRecurrence respresentation of the
1201 if (PhiScev
!= AR
&& SymbolicPhi
) {
1202 SmallVector
<Instruction
*, 2> Casts
;
1203 if (getCastsForInductionPHI(PSE
, SymbolicPhi
, AR
, Casts
))
1204 return isInductionPHI(Phi
, TheLoop
, PSE
.getSE(), D
, AR
, &Casts
);
1207 return isInductionPHI(Phi
, TheLoop
, PSE
.getSE(), D
, AR
);
1210 bool InductionDescriptor::isInductionPHI(
1211 PHINode
*Phi
, const Loop
*TheLoop
, ScalarEvolution
*SE
,
1212 InductionDescriptor
&D
, const SCEV
*Expr
,
1213 SmallVectorImpl
<Instruction
*> *CastsToIgnore
) {
1214 Type
*PhiTy
= Phi
->getType();
1215 // We only handle integer and pointer inductions variables.
1216 if (!PhiTy
->isIntegerTy() && !PhiTy
->isPointerTy())
1219 // Check that the PHI is consecutive.
1220 const SCEV
*PhiScev
= Expr
? Expr
: SE
->getSCEV(Phi
);
1221 const SCEVAddRecExpr
*AR
= dyn_cast
<SCEVAddRecExpr
>(PhiScev
);
1224 LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1228 if (AR
->getLoop() != TheLoop
) {
1229 // FIXME: We should treat this as a uniform. Unfortunately, we
1230 // don't currently know how to handled uniform PHIs.
1232 dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
1237 Phi
->getIncomingValueForBlock(AR
->getLoop()->getLoopPreheader());
1239 BasicBlock
*Latch
= AR
->getLoop()->getLoopLatch();
1242 BinaryOperator
*BOp
=
1243 dyn_cast
<BinaryOperator
>(Phi
->getIncomingValueForBlock(Latch
));
1245 const SCEV
*Step
= AR
->getStepRecurrence(*SE
);
1246 // Calculate the pointer stride and check if it is consecutive.
1247 // The stride may be a constant or a loop invariant integer value.
1248 const SCEVConstant
*ConstStep
= dyn_cast
<SCEVConstant
>(Step
);
1249 if (!ConstStep
&& !SE
->isLoopInvariant(Step
, TheLoop
))
1252 if (PhiTy
->isIntegerTy()) {
1253 D
= InductionDescriptor(StartValue
, IK_IntInduction
, Step
, BOp
,
1258 assert(PhiTy
->isPointerTy() && "The PHI must be a pointer");
1259 // Pointer induction should be a constant.
1263 ConstantInt
*CV
= ConstStep
->getValue();
1264 Type
*PointerElementType
= PhiTy
->getPointerElementType();
1265 // The pointer stride cannot be determined if the pointer element type is not
1267 if (!PointerElementType
->isSized())
1270 const DataLayout
&DL
= Phi
->getModule()->getDataLayout();
1271 int64_t Size
= static_cast<int64_t>(DL
.getTypeAllocSize(PointerElementType
));
1275 int64_t CVSize
= CV
->getSExtValue();
1279 SE
->getConstant(CV
->getType(), CVSize
/ Size
, true /* signed */);
1280 D
= InductionDescriptor(StartValue
, IK_PtrInduction
, StepValue
, BOp
);