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