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
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"
36
37 using namespace llvm;
38 using namespace llvm::PatternMatch;
39
40 #define DEBUG_TYPE "iv-descriptors"
41
areAllUsesIn(Instruction * I,SmallPtrSetImpl<Instruction * > & Set)42 bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
43 SmallPtrSetImpl<Instruction *> &Set) {
44 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
45 if (!Set.count(dyn_cast<Instruction>(*Use)))
46 return false;
47 return true;
48 }
49
isIntegerRecurrenceKind(RecurrenceKind Kind)50 bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
51 switch (Kind) {
52 default:
53 break;
54 case RK_IntegerAdd:
55 case RK_IntegerMult:
56 case RK_IntegerOr:
57 case RK_IntegerAnd:
58 case RK_IntegerXor:
59 case RK_IntegerMinMax:
60 return true;
61 }
62 return false;
63 }
64
isFloatingPointRecurrenceKind(RecurrenceKind Kind)65 bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
66 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
67 }
68
isArithmeticRecurrenceKind(RecurrenceKind Kind)69 bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
70 switch (Kind) {
71 default:
72 break;
73 case RK_IntegerAdd:
74 case RK_IntegerMult:
75 case RK_FloatAdd:
76 case RK_FloatMult:
77 return true;
78 }
79 return false;
80 }
81
82 /// Determines if Phi may have been type-promoted. If Phi has a single user
83 /// that ANDs the Phi with a type mask, return the user. RT is updated to
84 /// account for the narrower bit width represented by the mask, and the AND
85 /// instruction is added to CI.
lookThroughAnd(PHINode * Phi,Type * & RT,SmallPtrSetImpl<Instruction * > & Visited,SmallPtrSetImpl<Instruction * > & CI)86 static Instruction *lookThroughAnd(PHINode *Phi, Type *&RT,
87 SmallPtrSetImpl<Instruction *> &Visited,
88 SmallPtrSetImpl<Instruction *> &CI) {
89 if (!Phi->hasOneUse())
90 return Phi;
91
92 const APInt *M = nullptr;
93 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
94
95 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
96 // with a new integer type of the corresponding bit width.
97 if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) {
98 int32_t Bits = (*M + 1).exactLogBase2();
99 if (Bits > 0) {
100 RT = IntegerType::get(Phi->getContext(), Bits);
101 Visited.insert(Phi);
102 CI.insert(J);
103 return J;
104 }
105 }
106 return Phi;
107 }
108
109 /// Compute the minimal bit width needed to represent a reduction whose exit
110 /// instruction is given by Exit.
computeRecurrenceType(Instruction * Exit,DemandedBits * DB,AssumptionCache * AC,DominatorTree * DT)111 static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
112 DemandedBits *DB,
113 AssumptionCache *AC,
114 DominatorTree *DT) {
115 bool IsSigned = false;
116 const DataLayout &DL = Exit->getModule()->getDataLayout();
117 uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
118
119 if (DB) {
120 // Use the demanded bits analysis to determine the bits that are live out
121 // of the exit instruction, rounding up to the nearest power of two. If the
122 // use of demanded bits results in a smaller bit width, we know the value
123 // must be positive (i.e., IsSigned = false), because if this were not the
124 // case, the sign bit would have been demanded.
125 auto Mask = DB->getDemandedBits(Exit);
126 MaxBitWidth = Mask.getBitWidth() - Mask.countLeadingZeros();
127 }
128
129 if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) {
130 // If demanded bits wasn't able to limit the bit width, we can try to use
131 // value tracking instead. This can be the case, for example, if the value
132 // may be negative.
133 auto NumSignBits = ComputeNumSignBits(Exit, DL, 0, AC, nullptr, DT);
134 auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType());
135 MaxBitWidth = NumTypeBits - NumSignBits;
136 KnownBits Bits = computeKnownBits(Exit, DL);
137 if (!Bits.isNonNegative()) {
138 // If the value is not known to be non-negative, we set IsSigned to true,
139 // meaning that we will use sext instructions instead of zext
140 // instructions to restore the original type.
141 IsSigned = true;
142 if (!Bits.isNegative())
143 // If the value is not known to be negative, we don't known what the
144 // upper bit is, and therefore, we don't know what kind of extend we
145 // will need. In this case, just increase the bit width by one bit and
146 // use sext.
147 ++MaxBitWidth;
148 }
149 }
150 if (!isPowerOf2_64(MaxBitWidth))
151 MaxBitWidth = NextPowerOf2(MaxBitWidth);
152
153 return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth),
154 IsSigned);
155 }
156
157 /// Collect cast instructions that can be ignored in the vectorizer's cost
158 /// model, given a reduction exit value and the minimal type in which the
159 /// reduction can be represented.
collectCastsToIgnore(Loop * TheLoop,Instruction * Exit,Type * RecurrenceType,SmallPtrSetImpl<Instruction * > & Casts)160 static void collectCastsToIgnore(Loop *TheLoop, Instruction *Exit,
161 Type *RecurrenceType,
162 SmallPtrSetImpl<Instruction *> &Casts) {
163
164 SmallVector<Instruction *, 8> Worklist;
165 SmallPtrSet<Instruction *, 8> Visited;
166 Worklist.push_back(Exit);
167
168 while (!Worklist.empty()) {
169 Instruction *Val = Worklist.pop_back_val();
170 Visited.insert(Val);
171 if (auto *Cast = dyn_cast<CastInst>(Val))
172 if (Cast->getSrcTy() == RecurrenceType) {
173 // If the source type of a cast instruction is equal to the recurrence
174 // type, it will be eliminated, and should be ignored in the vectorizer
175 // cost model.
176 Casts.insert(Cast);
177 continue;
178 }
179
180 // Add all operands to the work list if they are loop-varying values that
181 // we haven't yet visited.
182 for (Value *O : cast<User>(Val)->operands())
183 if (auto *I = dyn_cast<Instruction>(O))
184 if (TheLoop->contains(I) && !Visited.count(I))
185 Worklist.push_back(I);
186 }
187 }
188
AddReductionVar(PHINode * Phi,RecurrenceKind Kind,Loop * TheLoop,bool HasFunNoNaNAttr,RecurrenceDescriptor & RedDes,DemandedBits * DB,AssumptionCache * AC,DominatorTree * DT)189 bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
190 Loop *TheLoop, bool HasFunNoNaNAttr,
191 RecurrenceDescriptor &RedDes,
192 DemandedBits *DB,
193 AssumptionCache *AC,
194 DominatorTree *DT) {
195 if (Phi->getNumIncomingValues() != 2)
196 return false;
197
198 // Reduction variables are only found in the loop header block.
199 if (Phi->getParent() != TheLoop->getHeader())
200 return false;
201
202 // Obtain the reduction start value from the value that comes from the loop
203 // preheader.
204 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
205
206 // ExitInstruction is the single value which is used outside the loop.
207 // We only allow for a single reduction value to be used outside the loop.
208 // This includes users of the reduction, variables (which form a cycle
209 // which ends in the phi node).
210 Instruction *ExitInstruction = nullptr;
211 // Indicates that we found a reduction operation in our scan.
212 bool FoundReduxOp = false;
213
214 // We start with the PHI node and scan for all of the users of this
215 // instruction. All users must be instructions that can be used as reduction
216 // variables (such as ADD). We must have a single out-of-block user. The cycle
217 // must include the original PHI.
218 bool FoundStartPHI = false;
219
220 // To recognize min/max patterns formed by a icmp select sequence, we store
221 // the number of instruction we saw from the recognized min/max pattern,
222 // to make sure we only see exactly the two instructions.
223 unsigned NumCmpSelectPatternInst = 0;
224 InstDesc ReduxDesc(false, nullptr);
225
226 // Data used for determining if the recurrence has been type-promoted.
227 Type *RecurrenceType = Phi->getType();
228 SmallPtrSet<Instruction *, 4> CastInsts;
229 Instruction *Start = Phi;
230 bool IsSigned = false;
231
232 SmallPtrSet<Instruction *, 8> VisitedInsts;
233 SmallVector<Instruction *, 8> Worklist;
234
235 // Return early if the recurrence kind does not match the type of Phi. If the
236 // recurrence kind is arithmetic, we attempt to look through AND operations
237 // resulting from the type promotion performed by InstCombine. Vector
238 // operations are not limited to the legal integer widths, so we may be able
239 // to evaluate the reduction in the narrower width.
240 if (RecurrenceType->isFloatingPointTy()) {
241 if (!isFloatingPointRecurrenceKind(Kind))
242 return false;
243 } else {
244 if (!isIntegerRecurrenceKind(Kind))
245 return false;
246 if (isArithmeticRecurrenceKind(Kind))
247 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
248 }
249
250 Worklist.push_back(Start);
251 VisitedInsts.insert(Start);
252
253 // Start with all flags set because we will intersect this with the reduction
254 // flags from all the reduction operations.
255 FastMathFlags FMF = FastMathFlags::getFast();
256
257 // A value in the reduction can be used:
258 // - By the reduction:
259 // - Reduction operation:
260 // - One use of reduction value (safe).
261 // - Multiple use of reduction value (not safe).
262 // - PHI:
263 // - All uses of the PHI must be the reduction (safe).
264 // - Otherwise, not safe.
265 // - By instructions outside of the loop (safe).
266 // * One value may have several outside users, but all outside
267 // uses must be of the same value.
268 // - By an instruction that is not part of the reduction (not safe).
269 // This is either:
270 // * An instruction type other than PHI or the reduction operation.
271 // * A PHI in the header other than the initial PHI.
272 while (!Worklist.empty()) {
273 Instruction *Cur = Worklist.back();
274 Worklist.pop_back();
275
276 // No Users.
277 // If the instruction has no users then this is a broken chain and can't be
278 // a reduction variable.
279 if (Cur->use_empty())
280 return false;
281
282 bool IsAPhi = isa<PHINode>(Cur);
283
284 // A header PHI use other than the original PHI.
285 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
286 return false;
287
288 // Reductions of instructions such as Div, and Sub is only possible if the
289 // LHS is the reduction variable.
290 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
291 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
292 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
293 return false;
294
295 // Any reduction instruction must be of one of the allowed kinds. We ignore
296 // the starting value (the Phi or an AND instruction if the Phi has been
297 // type-promoted).
298 if (Cur != Start) {
299 ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
300 if (!ReduxDesc.isRecurrence())
301 return false;
302 // FIXME: FMF is allowed on phi, but propagation is not handled correctly.
303 if (isa<FPMathOperator>(ReduxDesc.getPatternInst()) && !IsAPhi)
304 FMF &= ReduxDesc.getPatternInst()->getFastMathFlags();
305 }
306
307 bool IsASelect = isa<SelectInst>(Cur);
308
309 // A conditional reduction operation must only have 2 or less uses in
310 // VisitedInsts.
311 if (IsASelect && (Kind == RK_FloatAdd || Kind == RK_FloatMult) &&
312 hasMultipleUsesOf(Cur, VisitedInsts, 2))
313 return false;
314
315 // A reduction operation must only have one use of the reduction value.
316 if (!IsAPhi && !IsASelect && Kind != RK_IntegerMinMax &&
317 Kind != RK_FloatMinMax && hasMultipleUsesOf(Cur, VisitedInsts, 1))
318 return false;
319
320 // All inputs to a PHI node must be a reduction value.
321 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
322 return false;
323
324 if (Kind == RK_IntegerMinMax &&
325 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
326 ++NumCmpSelectPatternInst;
327 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
328 ++NumCmpSelectPatternInst;
329
330 // Check whether we found a reduction operator.
331 FoundReduxOp |= !IsAPhi && Cur != Start;
332
333 // Process users of current instruction. Push non-PHI nodes after PHI nodes
334 // onto the stack. This way we are going to have seen all inputs to PHI
335 // nodes once we get to them.
336 SmallVector<Instruction *, 8> NonPHIs;
337 SmallVector<Instruction *, 8> PHIs;
338 for (User *U : Cur->users()) {
339 Instruction *UI = cast<Instruction>(U);
340
341 // Check if we found the exit user.
342 BasicBlock *Parent = UI->getParent();
343 if (!TheLoop->contains(Parent)) {
344 // If we already know this instruction is used externally, move on to
345 // the next user.
346 if (ExitInstruction == Cur)
347 continue;
348
349 // Exit if you find multiple values used outside or if the header phi
350 // node is being used. In this case the user uses the value of the
351 // previous iteration, in which case we would loose "VF-1" iterations of
352 // the reduction operation if we vectorize.
353 if (ExitInstruction != nullptr || Cur == Phi)
354 return false;
355
356 // The instruction used by an outside user must be the last instruction
357 // before we feed back to the reduction phi. Otherwise, we loose VF-1
358 // operations on the value.
359 if (!is_contained(Phi->operands(), Cur))
360 return false;
361
362 ExitInstruction = Cur;
363 continue;
364 }
365
366 // Process instructions only once (termination). Each reduction cycle
367 // value must only be used once, except by phi nodes and min/max
368 // reductions which are represented as a cmp followed by a select.
369 InstDesc IgnoredVal(false, nullptr);
370 if (VisitedInsts.insert(UI).second) {
371 if (isa<PHINode>(UI))
372 PHIs.push_back(UI);
373 else
374 NonPHIs.push_back(UI);
375 } else if (!isa<PHINode>(UI) &&
376 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
377 !isa<SelectInst>(UI)) ||
378 (!isConditionalRdxPattern(Kind, UI).isRecurrence() &&
379 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence())))
380 return false;
381
382 // Remember that we completed the cycle.
383 if (UI == Phi)
384 FoundStartPHI = true;
385 }
386 Worklist.append(PHIs.begin(), PHIs.end());
387 Worklist.append(NonPHIs.begin(), NonPHIs.end());
388 }
389
390 // This means we have seen one but not the other instruction of the
391 // pattern or more than just a select and cmp.
392 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
393 NumCmpSelectPatternInst != 2)
394 return false;
395
396 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
397 return false;
398
399 if (Start != Phi) {
400 // If the starting value is not the same as the phi node, we speculatively
401 // looked through an 'and' instruction when evaluating a potential
402 // arithmetic reduction to determine if it may have been type-promoted.
403 //
404 // We now compute the minimal bit width that is required to represent the
405 // reduction. If this is the same width that was indicated by the 'and', we
406 // can represent the reduction in the smaller type. The 'and' instruction
407 // will be eliminated since it will essentially be a cast instruction that
408 // can be ignore in the cost model. If we compute a different type than we
409 // did when evaluating the 'and', the 'and' will not be eliminated, and we
410 // will end up with different kinds of operations in the recurrence
411 // expression (e.g., RK_IntegerAND, RK_IntegerADD). We give up if this is
412 // the case.
413 //
414 // The vectorizer relies on InstCombine to perform the actual
415 // type-shrinking. It does this by inserting instructions to truncate the
416 // exit value of the reduction to the width indicated by RecurrenceType and
417 // then extend this value back to the original width. If IsSigned is false,
418 // a 'zext' instruction will be generated; otherwise, a 'sext' will be
419 // used.
420 //
421 // TODO: We should not rely on InstCombine to rewrite the reduction in the
422 // smaller type. We should just generate a correctly typed expression
423 // to begin with.
424 Type *ComputedType;
425 std::tie(ComputedType, IsSigned) =
426 computeRecurrenceType(ExitInstruction, DB, AC, DT);
427 if (ComputedType != RecurrenceType)
428 return false;
429
430 // The recurrence expression will be represented in a narrower type. If
431 // there are any cast instructions that will be unnecessary, collect them
432 // in CastInsts. Note that the 'and' instruction was already included in
433 // this list.
434 //
435 // TODO: A better way to represent this may be to tag in some way all the
436 // instructions that are a part of the reduction. The vectorizer cost
437 // model could then apply the recurrence type to these instructions,
438 // without needing a white list of instructions to ignore.
439 // This may also be useful for the inloop reductions, if it can be
440 // kept simple enough.
441 collectCastsToIgnore(TheLoop, ExitInstruction, RecurrenceType, CastInsts);
442 }
443
444 // We found a reduction var if we have reached the original phi node and we
445 // only have a single instruction with out-of-loop users.
446
447 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
448 // is saved as part of the RecurrenceDescriptor.
449
450 // Save the description of this reduction variable.
451 RecurrenceDescriptor RD(
452 RdxStart, ExitInstruction, Kind, FMF, ReduxDesc.getMinMaxKind(),
453 ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
454 RedDes = RD;
455
456 return true;
457 }
458
459 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
460 /// pattern corresponding to a min(X, Y) or max(X, Y).
461 RecurrenceDescriptor::InstDesc
isMinMaxSelectCmpPattern(Instruction * I,InstDesc & Prev)462 RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
463
464 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
465 "Expect a select instruction");
466 Instruction *Cmp = nullptr;
467 SelectInst *Select = nullptr;
468
469 // We must handle the select(cmp()) as a single instruction. Advance to the
470 // select.
471 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
472 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
473 return InstDesc(false, I);
474 return InstDesc(Select, Prev.getMinMaxKind());
475 }
476
477 // Only handle single use cases for now.
478 if (!(Select = dyn_cast<SelectInst>(I)))
479 return InstDesc(false, I);
480 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
481 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
482 return InstDesc(false, I);
483 if (!Cmp->hasOneUse())
484 return InstDesc(false, I);
485
486 Value *CmpLeft;
487 Value *CmpRight;
488
489 // Look for a min/max pattern.
490 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
491 return InstDesc(Select, MRK_UIntMin);
492 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
493 return InstDesc(Select, MRK_UIntMax);
494 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
495 return InstDesc(Select, MRK_SIntMax);
496 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
497 return InstDesc(Select, MRK_SIntMin);
498 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
499 return InstDesc(Select, MRK_FloatMin);
500 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
501 return InstDesc(Select, MRK_FloatMax);
502 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
503 return InstDesc(Select, MRK_FloatMin);
504 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
505 return InstDesc(Select, MRK_FloatMax);
506
507 return InstDesc(false, I);
508 }
509
510 /// Returns true if the select instruction has users in the compare-and-add
511 /// reduction pattern below. The select instruction argument is the last one
512 /// in the sequence.
513 ///
514 /// %sum.1 = phi ...
515 /// ...
516 /// %cmp = fcmp pred %0, %CFP
517 /// %add = fadd %0, %sum.1
518 /// %sum.2 = select %cmp, %add, %sum.1
519 RecurrenceDescriptor::InstDesc
isConditionalRdxPattern(RecurrenceKind Kind,Instruction * I)520 RecurrenceDescriptor::isConditionalRdxPattern(
521 RecurrenceKind Kind, Instruction *I) {
522 SelectInst *SI = dyn_cast<SelectInst>(I);
523 if (!SI)
524 return InstDesc(false, I);
525
526 CmpInst *CI = dyn_cast<CmpInst>(SI->getCondition());
527 // Only handle single use cases for now.
528 if (!CI || !CI->hasOneUse())
529 return InstDesc(false, I);
530
531 Value *TrueVal = SI->getTrueValue();
532 Value *FalseVal = SI->getFalseValue();
533 // Handle only when either of operands of select instruction is a PHI
534 // node for now.
535 if ((isa<PHINode>(*TrueVal) && isa<PHINode>(*FalseVal)) ||
536 (!isa<PHINode>(*TrueVal) && !isa<PHINode>(*FalseVal)))
537 return InstDesc(false, I);
538
539 Instruction *I1 =
540 isa<PHINode>(*TrueVal) ? dyn_cast<Instruction>(FalseVal)
541 : dyn_cast<Instruction>(TrueVal);
542 if (!I1 || !I1->isBinaryOp())
543 return InstDesc(false, I);
544
545 Value *Op1, *Op2;
546 if ((m_FAdd(m_Value(Op1), m_Value(Op2)).match(I1) ||
547 m_FSub(m_Value(Op1), m_Value(Op2)).match(I1)) &&
548 I1->isFast())
549 return InstDesc(Kind == RK_FloatAdd, SI);
550
551 if (m_FMul(m_Value(Op1), m_Value(Op2)).match(I1) && (I1->isFast()))
552 return InstDesc(Kind == RK_FloatMult, SI);
553
554 return InstDesc(false, I);
555 }
556
557 RecurrenceDescriptor::InstDesc
isRecurrenceInstr(Instruction * I,RecurrenceKind Kind,InstDesc & Prev,bool HasFunNoNaNAttr)558 RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
559 InstDesc &Prev, bool HasFunNoNaNAttr) {
560 Instruction *UAI = Prev.getUnsafeAlgebraInst();
561 if (!UAI && isa<FPMathOperator>(I) && !I->hasAllowReassoc())
562 UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
563
564 switch (I->getOpcode()) {
565 default:
566 return InstDesc(false, I);
567 case Instruction::PHI:
568 return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
569 case Instruction::Sub:
570 case Instruction::Add:
571 return InstDesc(Kind == RK_IntegerAdd, I);
572 case Instruction::Mul:
573 return InstDesc(Kind == RK_IntegerMult, I);
574 case Instruction::And:
575 return InstDesc(Kind == RK_IntegerAnd, I);
576 case Instruction::Or:
577 return InstDesc(Kind == RK_IntegerOr, I);
578 case Instruction::Xor:
579 return InstDesc(Kind == RK_IntegerXor, I);
580 case Instruction::FDiv:
581 case Instruction::FMul:
582 return InstDesc(Kind == RK_FloatMult, I, UAI);
583 case Instruction::FSub:
584 case Instruction::FAdd:
585 return InstDesc(Kind == RK_FloatAdd, I, UAI);
586 case Instruction::Select:
587 if (Kind == RK_FloatAdd || Kind == RK_FloatMult)
588 return isConditionalRdxPattern(Kind, I);
589 LLVM_FALLTHROUGH;
590 case Instruction::FCmp:
591 case Instruction::ICmp:
592 if (Kind != RK_IntegerMinMax &&
593 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
594 return InstDesc(false, I);
595 return isMinMaxSelectCmpPattern(I, Prev);
596 }
597 }
598
hasMultipleUsesOf(Instruction * I,SmallPtrSetImpl<Instruction * > & Insts,unsigned MaxNumUses)599 bool RecurrenceDescriptor::hasMultipleUsesOf(
600 Instruction *I, SmallPtrSetImpl<Instruction *> &Insts,
601 unsigned MaxNumUses) {
602 unsigned NumUses = 0;
603 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
604 ++Use) {
605 if (Insts.count(dyn_cast<Instruction>(*Use)))
606 ++NumUses;
607 if (NumUses > MaxNumUses)
608 return true;
609 }
610
611 return false;
612 }
isReductionPHI(PHINode * Phi,Loop * TheLoop,RecurrenceDescriptor & RedDes,DemandedBits * DB,AssumptionCache * AC,DominatorTree * DT)613 bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
614 RecurrenceDescriptor &RedDes,
615 DemandedBits *DB, AssumptionCache *AC,
616 DominatorTree *DT) {
617
618 BasicBlock *Header = TheLoop->getHeader();
619 Function &F = *Header->getParent();
620 bool HasFunNoNaNAttr =
621 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
622
623 if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
624 AC, DT)) {
625 LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
626 return true;
627 }
628 if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
629 AC, DT)) {
630 LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
631 return true;
632 }
633 if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes, DB,
634 AC, DT)) {
635 LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
636 return true;
637 }
638 if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
639 AC, DT)) {
640 LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
641 return true;
642 }
643 if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes, DB,
644 AC, DT)) {
645 LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
646 return true;
647 }
648 if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr, RedDes,
649 DB, AC, DT)) {
650 LLVM_DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
651 return true;
652 }
653 if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
654 AC, DT)) {
655 LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
656 return true;
657 }
658 if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
659 AC, DT)) {
660 LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
661 return true;
662 }
663 if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes, DB,
664 AC, DT)) {
665 LLVM_DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi
666 << "\n");
667 return true;
668 }
669 // Not a reduction of known type.
670 return false;
671 }
672
isFirstOrderRecurrence(PHINode * Phi,Loop * TheLoop,DenseMap<Instruction *,Instruction * > & SinkAfter,DominatorTree * DT)673 bool RecurrenceDescriptor::isFirstOrderRecurrence(
674 PHINode *Phi, Loop *TheLoop,
675 DenseMap<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) {
676
677 // Ensure the phi node is in the loop header and has two incoming values.
678 if (Phi->getParent() != TheLoop->getHeader() ||
679 Phi->getNumIncomingValues() != 2)
680 return false;
681
682 // Ensure the loop has a preheader and a single latch block. The loop
683 // vectorizer will need the latch to set up the next iteration of the loop.
684 auto *Preheader = TheLoop->getLoopPreheader();
685 auto *Latch = TheLoop->getLoopLatch();
686 if (!Preheader || !Latch)
687 return false;
688
689 // Ensure the phi node's incoming blocks are the loop preheader and latch.
690 if (Phi->getBasicBlockIndex(Preheader) < 0 ||
691 Phi->getBasicBlockIndex(Latch) < 0)
692 return false;
693
694 // Get the previous value. The previous value comes from the latch edge while
695 // the initial value comes form the preheader edge.
696 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
697 if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) ||
698 SinkAfter.count(Previous)) // Cannot rely on dominance due to motion.
699 return false;
700
701 // Ensure every user of the phi node is dominated by the previous value.
702 // The dominance requirement ensures the loop vectorizer will not need to
703 // vectorize the initial value prior to the first iteration of the loop.
704 // TODO: Consider extending this sinking to handle memory instructions and
705 // phis with multiple users.
706
707 // Returns true, if all users of I are dominated by DominatedBy.
708 auto allUsesDominatedBy = [DT](Instruction *I, Instruction *DominatedBy) {
709 return all_of(I->uses(), [DT, DominatedBy](Use &U) {
710 return DT->dominates(DominatedBy, U);
711 });
712 };
713
714 if (Phi->hasOneUse()) {
715 Instruction *I = Phi->user_back();
716
717 // If the user of the PHI is also the incoming value, we potentially have a
718 // reduction and which cannot be handled by sinking.
719 if (Previous == I)
720 return false;
721
722 // We cannot sink terminator instructions.
723 if (I->getParent()->getTerminator() == I)
724 return false;
725
726 // Do not try to sink an instruction multiple times (if multiple operands
727 // are first order recurrences).
728 // TODO: We can support this case, by sinking the instruction after the
729 // 'deepest' previous instruction.
730 if (SinkAfter.find(I) != SinkAfter.end())
731 return false;
732
733 if (DT->dominates(Previous, I)) // We already are good w/o sinking.
734 return true;
735
736 // We can sink any instruction without side effects, as long as all users
737 // are dominated by the instruction we are sinking after.
738 if (I->getParent() == Phi->getParent() && !I->mayHaveSideEffects() &&
739 allUsesDominatedBy(I, Previous)) {
740 SinkAfter[I] = Previous;
741 return true;
742 }
743 }
744
745 return allUsesDominatedBy(Phi, Previous);
746 }
747
748 /// This function returns the identity element (or neutral element) for
749 /// the operation K.
getRecurrenceIdentity(RecurrenceKind K,MinMaxRecurrenceKind MK,Type * Tp)750 Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
751 MinMaxRecurrenceKind MK,
752 Type *Tp) {
753 switch (K) {
754 case RK_IntegerXor:
755 case RK_IntegerAdd:
756 case RK_IntegerOr:
757 // Adding, Xoring, Oring zero to a number does not change it.
758 return ConstantInt::get(Tp, 0);
759 case RK_IntegerMult:
760 // Multiplying a number by 1 does not change it.
761 return ConstantInt::get(Tp, 1);
762 case RK_IntegerAnd:
763 // AND-ing a number with an all-1 value does not change it.
764 return ConstantInt::get(Tp, -1, true);
765 case RK_FloatMult:
766 // Multiplying a number by 1 does not change it.
767 return ConstantFP::get(Tp, 1.0L);
768 case RK_FloatAdd:
769 // Adding zero to a number does not change it.
770 return ConstantFP::get(Tp, 0.0L);
771 case RK_IntegerMinMax:
772 case RK_FloatMinMax:
773 switch (MK) {
774 case MRK_UIntMin:
775 return ConstantInt::get(Tp, -1);
776 case MRK_UIntMax:
777 return ConstantInt::get(Tp, 0);
778 case MRK_SIntMin:
779 return ConstantInt::get(
780 Tp, APInt::getSignedMaxValue(Tp->getIntegerBitWidth()));
781 case MRK_SIntMax:
782 return ConstantInt::get(
783 Tp, APInt::getSignedMinValue(Tp->getIntegerBitWidth()));
784 case MRK_FloatMin:
785 return ConstantFP::getInfinity(Tp, true);
786 case MRK_FloatMax:
787 return ConstantFP::getInfinity(Tp, false);
788 default:
789 llvm_unreachable("Unknown recurrence kind");
790 }
791 default:
792 llvm_unreachable("Unknown recurrence kind");
793 }
794 }
795
796 /// This function translates the recurrence kind to an LLVM binary operator.
getRecurrenceBinOp(RecurrenceKind Kind)797 unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
798 switch (Kind) {
799 case RK_IntegerAdd:
800 return Instruction::Add;
801 case RK_IntegerMult:
802 return Instruction::Mul;
803 case RK_IntegerOr:
804 return Instruction::Or;
805 case RK_IntegerAnd:
806 return Instruction::And;
807 case RK_IntegerXor:
808 return Instruction::Xor;
809 case RK_FloatMult:
810 return Instruction::FMul;
811 case RK_FloatAdd:
812 return Instruction::FAdd;
813 case RK_IntegerMinMax:
814 return Instruction::ICmp;
815 case RK_FloatMinMax:
816 return Instruction::FCmp;
817 default:
818 llvm_unreachable("Unknown recurrence operation");
819 }
820 }
821
822 SmallVector<Instruction *, 4>
getReductionOpChain(PHINode * Phi,Loop * L) const823 RecurrenceDescriptor::getReductionOpChain(PHINode *Phi, Loop *L) const {
824 SmallVector<Instruction *, 4> ReductionOperations;
825 unsigned RedOp = getRecurrenceBinOp(Kind);
826
827 // Search down from the Phi to the LoopExitInstr, looking for instructions
828 // with a single user of the correct type for the reduction.
829
830 // Note that we check that the type of the operand is correct for each item in
831 // the chain, including the last (the loop exit value). This can come up from
832 // sub, which would otherwise be treated as an add reduction. MinMax also need
833 // to check for a pair of icmp/select, for which we use getNextInstruction and
834 // isCorrectOpcode functions to step the right number of instruction, and
835 // check the icmp/select pair.
836 // FIXME: We also do not attempt to look through Phi/Select's yet, which might
837 // be part of the reduction chain, or attempt to looks through And's to find a
838 // smaller bitwidth. Subs are also currently not allowed (which are usually
839 // treated as part of a add reduction) as they are expected to generally be
840 // more expensive than out-of-loop reductions, and need to be costed more
841 // carefully.
842 unsigned ExpectedUses = 1;
843 if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp)
844 ExpectedUses = 2;
845
846 auto getNextInstruction = [&](Instruction *Cur) {
847 if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
848 // We are expecting a icmp/select pair, which we go to the next select
849 // instruction if we can. We already know that Cur has 2 uses.
850 if (isa<SelectInst>(*Cur->user_begin()))
851 return cast<Instruction>(*Cur->user_begin());
852 else
853 return cast<Instruction>(*std::next(Cur->user_begin()));
854 }
855 return cast<Instruction>(*Cur->user_begin());
856 };
857 auto isCorrectOpcode = [&](Instruction *Cur) {
858 if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
859 Value *LHS, *RHS;
860 return SelectPatternResult::isMinOrMax(
861 matchSelectPattern(Cur, LHS, RHS).Flavor);
862 }
863 return Cur->getOpcode() == RedOp;
864 };
865
866 // The loop exit instruction we check first (as a quick test) but add last. We
867 // check the opcode is correct (and dont allow them to be Subs) and that they
868 // have expected to have the expected number of uses. They will have one use
869 // from the phi and one from a LCSSA value, no matter the type.
870 if (!isCorrectOpcode(LoopExitInstr) || !LoopExitInstr->hasNUses(2))
871 return {};
872
873 // Check that the Phi has one (or two for min/max) uses.
874 if (!Phi->hasNUses(ExpectedUses))
875 return {};
876 Instruction *Cur = getNextInstruction(Phi);
877
878 // Each other instruction in the chain should have the expected number of uses
879 // and be the correct opcode.
880 while (Cur != LoopExitInstr) {
881 if (!isCorrectOpcode(Cur) || !Cur->hasNUses(ExpectedUses))
882 return {};
883
884 ReductionOperations.push_back(Cur);
885 Cur = getNextInstruction(Cur);
886 }
887
888 ReductionOperations.push_back(Cur);
889 return ReductionOperations;
890 }
891
InductionDescriptor(Value * Start,InductionKind K,const SCEV * Step,BinaryOperator * BOp,SmallVectorImpl<Instruction * > * Casts)892 InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
893 const SCEV *Step, BinaryOperator *BOp,
894 SmallVectorImpl<Instruction *> *Casts)
895 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
896 assert(IK != IK_NoInduction && "Not an induction");
897
898 // Start value type should match the induction kind and the value
899 // itself should not be null.
900 assert(StartValue && "StartValue is null");
901 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
902 "StartValue is not a pointer for pointer induction");
903 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
904 "StartValue is not an integer for integer induction");
905
906 // Check the Step Value. It should be non-zero integer value.
907 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
908 "Step value is zero");
909
910 assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
911 "Step value should be constant for pointer induction");
912 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
913 "StepValue is not an integer");
914
915 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
916 "StepValue is not FP for FpInduction");
917 assert((IK != IK_FpInduction ||
918 (InductionBinOp &&
919 (InductionBinOp->getOpcode() == Instruction::FAdd ||
920 InductionBinOp->getOpcode() == Instruction::FSub))) &&
921 "Binary opcode should be specified for FP induction");
922
923 if (Casts) {
924 for (auto &Inst : *Casts) {
925 RedundantCasts.push_back(Inst);
926 }
927 }
928 }
929
getConsecutiveDirection() const930 int InductionDescriptor::getConsecutiveDirection() const {
931 ConstantInt *ConstStep = getConstIntStepValue();
932 if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
933 return ConstStep->getSExtValue();
934 return 0;
935 }
936
getConstIntStepValue() const937 ConstantInt *InductionDescriptor::getConstIntStepValue() const {
938 if (isa<SCEVConstant>(Step))
939 return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
940 return nullptr;
941 }
942
isFPInductionPHI(PHINode * Phi,const Loop * TheLoop,ScalarEvolution * SE,InductionDescriptor & D)943 bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
944 ScalarEvolution *SE,
945 InductionDescriptor &D) {
946
947 // Here we only handle FP induction variables.
948 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
949
950 if (TheLoop->getHeader() != Phi->getParent())
951 return false;
952
953 // The loop may have multiple entrances or multiple exits; we can analyze
954 // this phi if it has a unique entry value and a unique backedge value.
955 if (Phi->getNumIncomingValues() != 2)
956 return false;
957 Value *BEValue = nullptr, *StartValue = nullptr;
958 if (TheLoop->contains(Phi->getIncomingBlock(0))) {
959 BEValue = Phi->getIncomingValue(0);
960 StartValue = Phi->getIncomingValue(1);
961 } else {
962 assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
963 "Unexpected Phi node in the loop");
964 BEValue = Phi->getIncomingValue(1);
965 StartValue = Phi->getIncomingValue(0);
966 }
967
968 BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
969 if (!BOp)
970 return false;
971
972 Value *Addend = nullptr;
973 if (BOp->getOpcode() == Instruction::FAdd) {
974 if (BOp->getOperand(0) == Phi)
975 Addend = BOp->getOperand(1);
976 else if (BOp->getOperand(1) == Phi)
977 Addend = BOp->getOperand(0);
978 } else if (BOp->getOpcode() == Instruction::FSub)
979 if (BOp->getOperand(0) == Phi)
980 Addend = BOp->getOperand(1);
981
982 if (!Addend)
983 return false;
984
985 // The addend should be loop invariant
986 if (auto *I = dyn_cast<Instruction>(Addend))
987 if (TheLoop->contains(I))
988 return false;
989
990 // FP Step has unknown SCEV
991 const SCEV *Step = SE->getUnknown(Addend);
992 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
993 return true;
994 }
995
996 /// This function is called when we suspect that the update-chain of a phi node
997 /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
998 /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
999 /// predicate P under which the SCEV expression for the phi can be the
1000 /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
1001 /// cast instructions that are involved in the update-chain of this induction.
1002 /// A caller that adds the required runtime predicate can be free to drop these
1003 /// cast instructions, and compute the phi using \p AR (instead of some scev
1004 /// expression with casts).
1005 ///
1006 /// For example, without a predicate the scev expression can take the following
1007 /// form:
1008 /// (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
1009 ///
1010 /// It corresponds to the following IR sequence:
1011 /// %for.body:
1012 /// %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
1013 /// %casted_phi = "ExtTrunc i64 %x"
1014 /// %add = add i64 %casted_phi, %step
1015 ///
1016 /// where %x is given in \p PN,
1017 /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
1018 /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
1019 /// several forms, for example, such as:
1020 /// ExtTrunc1: %casted_phi = and %x, 2^n-1
1021 /// or:
1022 /// ExtTrunc2: %t = shl %x, m
1023 /// %casted_phi = ashr %t, m
1024 ///
1025 /// If we are able to find such sequence, we return the instructions
1026 /// we found, namely %casted_phi and the instructions on its use-def chain up
1027 /// to the phi (not including the phi).
getCastsForInductionPHI(PredicatedScalarEvolution & PSE,const SCEVUnknown * PhiScev,const SCEVAddRecExpr * AR,SmallVectorImpl<Instruction * > & CastInsts)1028 static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE,
1029 const SCEVUnknown *PhiScev,
1030 const SCEVAddRecExpr *AR,
1031 SmallVectorImpl<Instruction *> &CastInsts) {
1032
1033 assert(CastInsts.empty() && "CastInsts is expected to be empty.");
1034 auto *PN = cast<PHINode>(PhiScev->getValue());
1035 assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
1036 const Loop *L = AR->getLoop();
1037
1038 // Find any cast instructions that participate in the def-use chain of
1039 // PhiScev in the loop.
1040 // FORNOW/TODO: We currently expect the def-use chain to include only
1041 // two-operand instructions, where one of the operands is an invariant.
1042 // createAddRecFromPHIWithCasts() currently does not support anything more
1043 // involved than that, so we keep the search simple. This can be
1044 // extended/generalized as needed.
1045
1046 auto getDef = [&](const Value *Val) -> Value * {
1047 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
1048 if (!BinOp)
1049 return nullptr;
1050 Value *Op0 = BinOp->getOperand(0);
1051 Value *Op1 = BinOp->getOperand(1);
1052 Value *Def = nullptr;
1053 if (L->isLoopInvariant(Op0))
1054 Def = Op1;
1055 else if (L->isLoopInvariant(Op1))
1056 Def = Op0;
1057 return Def;
1058 };
1059
1060 // Look for the instruction that defines the induction via the
1061 // loop backedge.
1062 BasicBlock *Latch = L->getLoopLatch();
1063 if (!Latch)
1064 return false;
1065 Value *Val = PN->getIncomingValueForBlock(Latch);
1066 if (!Val)
1067 return false;
1068
1069 // Follow the def-use chain until the induction phi is reached.
1070 // If on the way we encounter a Value that has the same SCEV Expr as the
1071 // phi node, we can consider the instructions we visit from that point
1072 // as part of the cast-sequence that can be ignored.
1073 bool InCastSequence = false;
1074 auto *Inst = dyn_cast<Instruction>(Val);
1075 while (Val != PN) {
1076 // If we encountered a phi node other than PN, or if we left the loop,
1077 // we bail out.
1078 if (!Inst || !L->contains(Inst)) {
1079 return false;
1080 }
1081 auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
1082 if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
1083 InCastSequence = true;
1084 if (InCastSequence) {
1085 // Only the last instruction in the cast sequence is expected to have
1086 // uses outside the induction def-use chain.
1087 if (!CastInsts.empty())
1088 if (!Inst->hasOneUse())
1089 return false;
1090 CastInsts.push_back(Inst);
1091 }
1092 Val = getDef(Val);
1093 if (!Val)
1094 return false;
1095 Inst = dyn_cast<Instruction>(Val);
1096 }
1097
1098 return InCastSequence;
1099 }
1100
isInductionPHI(PHINode * Phi,const Loop * TheLoop,PredicatedScalarEvolution & PSE,InductionDescriptor & D,bool Assume)1101 bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
1102 PredicatedScalarEvolution &PSE,
1103 InductionDescriptor &D, bool Assume) {
1104 Type *PhiTy = Phi->getType();
1105
1106 // Handle integer and pointer inductions variables.
1107 // Now we handle also FP induction but not trying to make a
1108 // recurrent expression from the PHI node in-place.
1109
1110 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() &&
1111 !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
1112 return false;
1113
1114 if (PhiTy->isFloatingPointTy())
1115 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
1116
1117 const SCEV *PhiScev = PSE.getSCEV(Phi);
1118 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1119
1120 // We need this expression to be an AddRecExpr.
1121 if (Assume && !AR)
1122 AR = PSE.getAsAddRec(Phi);
1123
1124 if (!AR) {
1125 LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1126 return false;
1127 }
1128
1129 // Record any Cast instructions that participate in the induction update
1130 const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
1131 // If we started from an UnknownSCEV, and managed to build an addRecurrence
1132 // only after enabling Assume with PSCEV, this means we may have encountered
1133 // cast instructions that required adding a runtime check in order to
1134 // guarantee the correctness of the AddRecurrence respresentation of the
1135 // induction.
1136 if (PhiScev != AR && SymbolicPhi) {
1137 SmallVector<Instruction *, 2> Casts;
1138 if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
1139 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
1140 }
1141
1142 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
1143 }
1144
isInductionPHI(PHINode * Phi,const Loop * TheLoop,ScalarEvolution * SE,InductionDescriptor & D,const SCEV * Expr,SmallVectorImpl<Instruction * > * CastsToIgnore)1145 bool InductionDescriptor::isInductionPHI(
1146 PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
1147 InductionDescriptor &D, const SCEV *Expr,
1148 SmallVectorImpl<Instruction *> *CastsToIgnore) {
1149 Type *PhiTy = Phi->getType();
1150 // We only handle integer and pointer inductions variables.
1151 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1152 return false;
1153
1154 // Check that the PHI is consecutive.
1155 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
1156 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1157
1158 if (!AR) {
1159 LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1160 return false;
1161 }
1162
1163 if (AR->getLoop() != TheLoop) {
1164 // FIXME: We should treat this as a uniform. Unfortunately, we
1165 // don't currently know how to handled uniform PHIs.
1166 LLVM_DEBUG(
1167 dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
1168 return false;
1169 }
1170
1171 Value *StartValue =
1172 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
1173
1174 BasicBlock *Latch = AR->getLoop()->getLoopLatch();
1175 if (!Latch)
1176 return false;
1177 BinaryOperator *BOp =
1178 dyn_cast<BinaryOperator>(Phi->getIncomingValueForBlock(Latch));
1179
1180 const SCEV *Step = AR->getStepRecurrence(*SE);
1181 // Calculate the pointer stride and check if it is consecutive.
1182 // The stride may be a constant or a loop invariant integer value.
1183 const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
1184 if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
1185 return false;
1186
1187 if (PhiTy->isIntegerTy()) {
1188 D = InductionDescriptor(StartValue, IK_IntInduction, Step, BOp,
1189 CastsToIgnore);
1190 return true;
1191 }
1192
1193 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1194 // Pointer induction should be a constant.
1195 if (!ConstStep)
1196 return false;
1197
1198 ConstantInt *CV = ConstStep->getValue();
1199 Type *PointerElementType = PhiTy->getPointerElementType();
1200 // The pointer stride cannot be determined if the pointer element type is not
1201 // sized.
1202 if (!PointerElementType->isSized())
1203 return false;
1204
1205 const DataLayout &DL = Phi->getModule()->getDataLayout();
1206 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
1207 if (!Size)
1208 return false;
1209
1210 int64_t CVSize = CV->getSExtValue();
1211 if (CVSize % Size)
1212 return false;
1213 auto *StepValue =
1214 SE->getConstant(CV->getType(), CVSize / Size, true /* signed */);
1215 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue, BOp);
1216 return true;
1217 }
1218