1 //===-- LoopUtils.cpp - Loop Utility functions -------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines common loop utility functions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Utils/LoopUtils.h" 15 #include "llvm/Analysis/AliasAnalysis.h" 16 #include "llvm/Analysis/BasicAliasAnalysis.h" 17 #include "llvm/Analysis/GlobalsModRef.h" 18 #include "llvm/Analysis/GlobalsModRef.h" 19 #include "llvm/Analysis/LoopInfo.h" 20 #include "llvm/Analysis/ScalarEvolution.h" 21 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 22 #include "llvm/Analysis/ScalarEvolutionExpander.h" 23 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 24 #include "llvm/IR/Dominators.h" 25 #include "llvm/IR/Instructions.h" 26 #include "llvm/IR/Module.h" 27 #include "llvm/IR/PatternMatch.h" 28 #include "llvm/IR/ValueHandle.h" 29 #include "llvm/Pass.h" 30 #include "llvm/Support/Debug.h" 31 32 using namespace llvm; 33 using namespace llvm::PatternMatch; 34 35 #define DEBUG_TYPE "loop-utils" 36 37 bool RecurrenceDescriptor::areAllUsesIn(Instruction *I, 38 SmallPtrSetImpl<Instruction *> &Set) { 39 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) 40 if (!Set.count(dyn_cast<Instruction>(*Use))) 41 return false; 42 return true; 43 } 44 45 bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) { 46 switch (Kind) { 47 default: 48 break; 49 case RK_IntegerAdd: 50 case RK_IntegerMult: 51 case RK_IntegerOr: 52 case RK_IntegerAnd: 53 case RK_IntegerXor: 54 case RK_IntegerMinMax: 55 return true; 56 } 57 return false; 58 } 59 60 bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) { 61 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind); 62 } 63 64 bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) { 65 switch (Kind) { 66 default: 67 break; 68 case RK_IntegerAdd: 69 case RK_IntegerMult: 70 case RK_FloatAdd: 71 case RK_FloatMult: 72 return true; 73 } 74 return false; 75 } 76 77 Instruction * 78 RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT, 79 SmallPtrSetImpl<Instruction *> &Visited, 80 SmallPtrSetImpl<Instruction *> &CI) { 81 if (!Phi->hasOneUse()) 82 return Phi; 83 84 const APInt *M = nullptr; 85 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser()); 86 87 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT 88 // with a new integer type of the corresponding bit width. 89 if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)), 90 m_And(m_APInt(M), m_Instruction(I))))) { 91 int32_t Bits = (*M + 1).exactLogBase2(); 92 if (Bits > 0) { 93 RT = IntegerType::get(Phi->getContext(), Bits); 94 Visited.insert(Phi); 95 CI.insert(J); 96 return J; 97 } 98 } 99 return Phi; 100 } 101 102 bool RecurrenceDescriptor::getSourceExtensionKind( 103 Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned, 104 SmallPtrSetImpl<Instruction *> &Visited, 105 SmallPtrSetImpl<Instruction *> &CI) { 106 107 SmallVector<Instruction *, 8> Worklist; 108 bool FoundOneOperand = false; 109 unsigned DstSize = RT->getPrimitiveSizeInBits(); 110 Worklist.push_back(Exit); 111 112 // Traverse the instructions in the reduction expression, beginning with the 113 // exit value. 114 while (!Worklist.empty()) { 115 Instruction *I = Worklist.pop_back_val(); 116 for (Use &U : I->operands()) { 117 118 // Terminate the traversal if the operand is not an instruction, or we 119 // reach the starting value. 120 Instruction *J = dyn_cast<Instruction>(U.get()); 121 if (!J || J == Start) 122 continue; 123 124 // Otherwise, investigate the operation if it is also in the expression. 125 if (Visited.count(J)) { 126 Worklist.push_back(J); 127 continue; 128 } 129 130 // If the operand is not in Visited, it is not a reduction operation, but 131 // it does feed into one. Make sure it is either a single-use sign- or 132 // zero-extend instruction. 133 CastInst *Cast = dyn_cast<CastInst>(J); 134 bool IsSExtInst = isa<SExtInst>(J); 135 if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst)) 136 return false; 137 138 // Ensure the source type of the extend is no larger than the reduction 139 // type. It is not necessary for the types to be identical. 140 unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits(); 141 if (SrcSize > DstSize) 142 return false; 143 144 // Furthermore, ensure that all such extends are of the same kind. 145 if (FoundOneOperand) { 146 if (IsSigned != IsSExtInst) 147 return false; 148 } else { 149 FoundOneOperand = true; 150 IsSigned = IsSExtInst; 151 } 152 153 // Lastly, if the source type of the extend matches the reduction type, 154 // add the extend to CI so that we can avoid accounting for it in the 155 // cost model. 156 if (SrcSize == DstSize) 157 CI.insert(Cast); 158 } 159 } 160 return true; 161 } 162 163 bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind, 164 Loop *TheLoop, bool HasFunNoNaNAttr, 165 RecurrenceDescriptor &RedDes) { 166 if (Phi->getNumIncomingValues() != 2) 167 return false; 168 169 // Reduction variables are only found in the loop header block. 170 if (Phi->getParent() != TheLoop->getHeader()) 171 return false; 172 173 // Obtain the reduction start value from the value that comes from the loop 174 // preheader. 175 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()); 176 177 // ExitInstruction is the single value which is used outside the loop. 178 // We only allow for a single reduction value to be used outside the loop. 179 // This includes users of the reduction, variables (which form a cycle 180 // which ends in the phi node). 181 Instruction *ExitInstruction = nullptr; 182 // Indicates that we found a reduction operation in our scan. 183 bool FoundReduxOp = false; 184 185 // We start with the PHI node and scan for all of the users of this 186 // instruction. All users must be instructions that can be used as reduction 187 // variables (such as ADD). We must have a single out-of-block user. The cycle 188 // must include the original PHI. 189 bool FoundStartPHI = false; 190 191 // To recognize min/max patterns formed by a icmp select sequence, we store 192 // the number of instruction we saw from the recognized min/max pattern, 193 // to make sure we only see exactly the two instructions. 194 unsigned NumCmpSelectPatternInst = 0; 195 InstDesc ReduxDesc(false, nullptr); 196 197 // Data used for determining if the recurrence has been type-promoted. 198 Type *RecurrenceType = Phi->getType(); 199 SmallPtrSet<Instruction *, 4> CastInsts; 200 Instruction *Start = Phi; 201 bool IsSigned = false; 202 203 SmallPtrSet<Instruction *, 8> VisitedInsts; 204 SmallVector<Instruction *, 8> Worklist; 205 206 // Return early if the recurrence kind does not match the type of Phi. If the 207 // recurrence kind is arithmetic, we attempt to look through AND operations 208 // resulting from the type promotion performed by InstCombine. Vector 209 // operations are not limited to the legal integer widths, so we may be able 210 // to evaluate the reduction in the narrower width. 211 if (RecurrenceType->isFloatingPointTy()) { 212 if (!isFloatingPointRecurrenceKind(Kind)) 213 return false; 214 } else { 215 if (!isIntegerRecurrenceKind(Kind)) 216 return false; 217 if (isArithmeticRecurrenceKind(Kind)) 218 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts); 219 } 220 221 Worklist.push_back(Start); 222 VisitedInsts.insert(Start); 223 224 // A value in the reduction can be used: 225 // - By the reduction: 226 // - Reduction operation: 227 // - One use of reduction value (safe). 228 // - Multiple use of reduction value (not safe). 229 // - PHI: 230 // - All uses of the PHI must be the reduction (safe). 231 // - Otherwise, not safe. 232 // - By one instruction outside of the loop (safe). 233 // - By further instructions outside of the loop (not safe). 234 // - By an instruction that is not part of the reduction (not safe). 235 // This is either: 236 // * An instruction type other than PHI or the reduction operation. 237 // * A PHI in the header other than the initial PHI. 238 while (!Worklist.empty()) { 239 Instruction *Cur = Worklist.back(); 240 Worklist.pop_back(); 241 242 // No Users. 243 // If the instruction has no users then this is a broken chain and can't be 244 // a reduction variable. 245 if (Cur->use_empty()) 246 return false; 247 248 bool IsAPhi = isa<PHINode>(Cur); 249 250 // A header PHI use other than the original PHI. 251 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent()) 252 return false; 253 254 // Reductions of instructions such as Div, and Sub is only possible if the 255 // LHS is the reduction variable. 256 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) && 257 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) && 258 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0)))) 259 return false; 260 261 // Any reduction instruction must be of one of the allowed kinds. We ignore 262 // the starting value (the Phi or an AND instruction if the Phi has been 263 // type-promoted). 264 if (Cur != Start) { 265 ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr); 266 if (!ReduxDesc.isRecurrence()) 267 return false; 268 } 269 270 // A reduction operation must only have one use of the reduction value. 271 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax && 272 hasMultipleUsesOf(Cur, VisitedInsts)) 273 return false; 274 275 // All inputs to a PHI node must be a reduction value. 276 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts)) 277 return false; 278 279 if (Kind == RK_IntegerMinMax && 280 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur))) 281 ++NumCmpSelectPatternInst; 282 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur))) 283 ++NumCmpSelectPatternInst; 284 285 // Check whether we found a reduction operator. 286 FoundReduxOp |= !IsAPhi && Cur != Start; 287 288 // Process users of current instruction. Push non-PHI nodes after PHI nodes 289 // onto the stack. This way we are going to have seen all inputs to PHI 290 // nodes once we get to them. 291 SmallVector<Instruction *, 8> NonPHIs; 292 SmallVector<Instruction *, 8> PHIs; 293 for (User *U : Cur->users()) { 294 Instruction *UI = cast<Instruction>(U); 295 296 // Check if we found the exit user. 297 BasicBlock *Parent = UI->getParent(); 298 if (!TheLoop->contains(Parent)) { 299 // Exit if you find multiple outside users or if the header phi node is 300 // being used. In this case the user uses the value of the previous 301 // iteration, in which case we would loose "VF-1" iterations of the 302 // reduction operation if we vectorize. 303 if (ExitInstruction != nullptr || Cur == Phi) 304 return false; 305 306 // The instruction used by an outside user must be the last instruction 307 // before we feed back to the reduction phi. Otherwise, we loose VF-1 308 // operations on the value. 309 if (!is_contained(Phi->operands(), Cur)) 310 return false; 311 312 ExitInstruction = Cur; 313 continue; 314 } 315 316 // Process instructions only once (termination). Each reduction cycle 317 // value must only be used once, except by phi nodes and min/max 318 // reductions which are represented as a cmp followed by a select. 319 InstDesc IgnoredVal(false, nullptr); 320 if (VisitedInsts.insert(UI).second) { 321 if (isa<PHINode>(UI)) 322 PHIs.push_back(UI); 323 else 324 NonPHIs.push_back(UI); 325 } else if (!isa<PHINode>(UI) && 326 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) && 327 !isa<SelectInst>(UI)) || 328 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence())) 329 return false; 330 331 // Remember that we completed the cycle. 332 if (UI == Phi) 333 FoundStartPHI = true; 334 } 335 Worklist.append(PHIs.begin(), PHIs.end()); 336 Worklist.append(NonPHIs.begin(), NonPHIs.end()); 337 } 338 339 // This means we have seen one but not the other instruction of the 340 // pattern or more than just a select and cmp. 341 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) && 342 NumCmpSelectPatternInst != 2) 343 return false; 344 345 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction) 346 return false; 347 348 // If we think Phi may have been type-promoted, we also need to ensure that 349 // all source operands of the reduction are either SExtInsts or ZEstInsts. If 350 // so, we will be able to evaluate the reduction in the narrower bit width. 351 if (Start != Phi) 352 if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType, 353 IsSigned, VisitedInsts, CastInsts)) 354 return false; 355 356 // We found a reduction var if we have reached the original phi node and we 357 // only have a single instruction with out-of-loop users. 358 359 // The ExitInstruction(Instruction which is allowed to have out-of-loop users) 360 // is saved as part of the RecurrenceDescriptor. 361 362 // Save the description of this reduction variable. 363 RecurrenceDescriptor RD( 364 RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(), 365 ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts); 366 RedDes = RD; 367 368 return true; 369 } 370 371 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction 372 /// pattern corresponding to a min(X, Y) or max(X, Y). 373 RecurrenceDescriptor::InstDesc 374 RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) { 375 376 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) && 377 "Expect a select instruction"); 378 Instruction *Cmp = nullptr; 379 SelectInst *Select = nullptr; 380 381 // We must handle the select(cmp()) as a single instruction. Advance to the 382 // select. 383 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) { 384 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin()))) 385 return InstDesc(false, I); 386 return InstDesc(Select, Prev.getMinMaxKind()); 387 } 388 389 // Only handle single use cases for now. 390 if (!(Select = dyn_cast<SelectInst>(I))) 391 return InstDesc(false, I); 392 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) && 393 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0)))) 394 return InstDesc(false, I); 395 if (!Cmp->hasOneUse()) 396 return InstDesc(false, I); 397 398 Value *CmpLeft; 399 Value *CmpRight; 400 401 // Look for a min/max pattern. 402 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 403 return InstDesc(Select, MRK_UIntMin); 404 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 405 return InstDesc(Select, MRK_UIntMax); 406 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 407 return InstDesc(Select, MRK_SIntMax); 408 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 409 return InstDesc(Select, MRK_SIntMin); 410 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 411 return InstDesc(Select, MRK_FloatMin); 412 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 413 return InstDesc(Select, MRK_FloatMax); 414 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 415 return InstDesc(Select, MRK_FloatMin); 416 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 417 return InstDesc(Select, MRK_FloatMax); 418 419 return InstDesc(false, I); 420 } 421 422 RecurrenceDescriptor::InstDesc 423 RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind, 424 InstDesc &Prev, bool HasFunNoNaNAttr) { 425 bool FP = I->getType()->isFloatingPointTy(); 426 Instruction *UAI = Prev.getUnsafeAlgebraInst(); 427 if (!UAI && FP && !I->hasUnsafeAlgebra()) 428 UAI = I; // Found an unsafe (unvectorizable) algebra instruction. 429 430 switch (I->getOpcode()) { 431 default: 432 return InstDesc(false, I); 433 case Instruction::PHI: 434 return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst()); 435 case Instruction::Sub: 436 case Instruction::Add: 437 return InstDesc(Kind == RK_IntegerAdd, I); 438 case Instruction::Mul: 439 return InstDesc(Kind == RK_IntegerMult, I); 440 case Instruction::And: 441 return InstDesc(Kind == RK_IntegerAnd, I); 442 case Instruction::Or: 443 return InstDesc(Kind == RK_IntegerOr, I); 444 case Instruction::Xor: 445 return InstDesc(Kind == RK_IntegerXor, I); 446 case Instruction::FMul: 447 return InstDesc(Kind == RK_FloatMult, I, UAI); 448 case Instruction::FSub: 449 case Instruction::FAdd: 450 return InstDesc(Kind == RK_FloatAdd, I, UAI); 451 case Instruction::FCmp: 452 case Instruction::ICmp: 453 case Instruction::Select: 454 if (Kind != RK_IntegerMinMax && 455 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax)) 456 return InstDesc(false, I); 457 return isMinMaxSelectCmpPattern(I, Prev); 458 } 459 } 460 461 bool RecurrenceDescriptor::hasMultipleUsesOf( 462 Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) { 463 unsigned NumUses = 0; 464 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; 465 ++Use) { 466 if (Insts.count(dyn_cast<Instruction>(*Use))) 467 ++NumUses; 468 if (NumUses > 1) 469 return true; 470 } 471 472 return false; 473 } 474 bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop, 475 RecurrenceDescriptor &RedDes) { 476 477 BasicBlock *Header = TheLoop->getHeader(); 478 Function &F = *Header->getParent(); 479 bool HasFunNoNaNAttr = 480 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true"; 481 482 if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) { 483 DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n"); 484 return true; 485 } 486 if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) { 487 DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n"); 488 return true; 489 } 490 if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) { 491 DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n"); 492 return true; 493 } 494 if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) { 495 DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n"); 496 return true; 497 } 498 if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) { 499 DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n"); 500 return true; 501 } 502 if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr, 503 RedDes)) { 504 DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n"); 505 return true; 506 } 507 if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) { 508 DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n"); 509 return true; 510 } 511 if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) { 512 DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n"); 513 return true; 514 } 515 if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) { 516 DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n"); 517 return true; 518 } 519 // Not a reduction of known type. 520 return false; 521 } 522 523 bool RecurrenceDescriptor::isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop, 524 DominatorTree *DT) { 525 526 // Ensure the phi node is in the loop header and has two incoming values. 527 if (Phi->getParent() != TheLoop->getHeader() || 528 Phi->getNumIncomingValues() != 2) 529 return false; 530 531 // Ensure the loop has a preheader and a single latch block. The loop 532 // vectorizer will need the latch to set up the next iteration of the loop. 533 auto *Preheader = TheLoop->getLoopPreheader(); 534 auto *Latch = TheLoop->getLoopLatch(); 535 if (!Preheader || !Latch) 536 return false; 537 538 // Ensure the phi node's incoming blocks are the loop preheader and latch. 539 if (Phi->getBasicBlockIndex(Preheader) < 0 || 540 Phi->getBasicBlockIndex(Latch) < 0) 541 return false; 542 543 // Get the previous value. The previous value comes from the latch edge while 544 // the initial value comes form the preheader edge. 545 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch)); 546 if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous)) 547 return false; 548 549 // Ensure every user of the phi node is dominated by the previous value. The 550 // dominance requirement ensures the loop vectorizer will not need to 551 // vectorize the initial value prior to the first iteration of the loop. 552 for (User *U : Phi->users()) 553 if (auto *I = dyn_cast<Instruction>(U)) 554 if (!DT->dominates(Previous, I)) 555 return false; 556 557 return true; 558 } 559 560 /// This function returns the identity element (or neutral element) for 561 /// the operation K. 562 Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K, 563 Type *Tp) { 564 switch (K) { 565 case RK_IntegerXor: 566 case RK_IntegerAdd: 567 case RK_IntegerOr: 568 // Adding, Xoring, Oring zero to a number does not change it. 569 return ConstantInt::get(Tp, 0); 570 case RK_IntegerMult: 571 // Multiplying a number by 1 does not change it. 572 return ConstantInt::get(Tp, 1); 573 case RK_IntegerAnd: 574 // AND-ing a number with an all-1 value does not change it. 575 return ConstantInt::get(Tp, -1, true); 576 case RK_FloatMult: 577 // Multiplying a number by 1 does not change it. 578 return ConstantFP::get(Tp, 1.0L); 579 case RK_FloatAdd: 580 // Adding zero to a number does not change it. 581 return ConstantFP::get(Tp, 0.0L); 582 default: 583 llvm_unreachable("Unknown recurrence kind"); 584 } 585 } 586 587 /// This function translates the recurrence kind to an LLVM binary operator. 588 unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) { 589 switch (Kind) { 590 case RK_IntegerAdd: 591 return Instruction::Add; 592 case RK_IntegerMult: 593 return Instruction::Mul; 594 case RK_IntegerOr: 595 return Instruction::Or; 596 case RK_IntegerAnd: 597 return Instruction::And; 598 case RK_IntegerXor: 599 return Instruction::Xor; 600 case RK_FloatMult: 601 return Instruction::FMul; 602 case RK_FloatAdd: 603 return Instruction::FAdd; 604 case RK_IntegerMinMax: 605 return Instruction::ICmp; 606 case RK_FloatMinMax: 607 return Instruction::FCmp; 608 default: 609 llvm_unreachable("Unknown recurrence operation"); 610 } 611 } 612 613 Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder, 614 MinMaxRecurrenceKind RK, 615 Value *Left, Value *Right) { 616 CmpInst::Predicate P = CmpInst::ICMP_NE; 617 switch (RK) { 618 default: 619 llvm_unreachable("Unknown min/max recurrence kind"); 620 case MRK_UIntMin: 621 P = CmpInst::ICMP_ULT; 622 break; 623 case MRK_UIntMax: 624 P = CmpInst::ICMP_UGT; 625 break; 626 case MRK_SIntMin: 627 P = CmpInst::ICMP_SLT; 628 break; 629 case MRK_SIntMax: 630 P = CmpInst::ICMP_SGT; 631 break; 632 case MRK_FloatMin: 633 P = CmpInst::FCMP_OLT; 634 break; 635 case MRK_FloatMax: 636 P = CmpInst::FCMP_OGT; 637 break; 638 } 639 640 // We only match FP sequences with unsafe algebra, so we can unconditionally 641 // set it on any generated instructions. 642 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 643 FastMathFlags FMF; 644 FMF.setUnsafeAlgebra(); 645 Builder.setFastMathFlags(FMF); 646 647 Value *Cmp; 648 if (RK == MRK_FloatMin || RK == MRK_FloatMax) 649 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp"); 650 else 651 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp"); 652 653 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 654 return Select; 655 } 656 657 InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K, 658 const SCEV *Step, BinaryOperator *BOp) 659 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) { 660 assert(IK != IK_NoInduction && "Not an induction"); 661 662 // Start value type should match the induction kind and the value 663 // itself should not be null. 664 assert(StartValue && "StartValue is null"); 665 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) && 666 "StartValue is not a pointer for pointer induction"); 667 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) && 668 "StartValue is not an integer for integer induction"); 669 670 // Check the Step Value. It should be non-zero integer value. 671 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) && 672 "Step value is zero"); 673 674 assert((IK != IK_PtrInduction || getConstIntStepValue()) && 675 "Step value should be constant for pointer induction"); 676 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) && 677 "StepValue is not an integer"); 678 679 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) && 680 "StepValue is not FP for FpInduction"); 681 assert((IK != IK_FpInduction || (InductionBinOp && 682 (InductionBinOp->getOpcode() == Instruction::FAdd || 683 InductionBinOp->getOpcode() == Instruction::FSub))) && 684 "Binary opcode should be specified for FP induction"); 685 } 686 687 int InductionDescriptor::getConsecutiveDirection() const { 688 ConstantInt *ConstStep = getConstIntStepValue(); 689 if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne())) 690 return ConstStep->getSExtValue(); 691 return 0; 692 } 693 694 ConstantInt *InductionDescriptor::getConstIntStepValue() const { 695 if (isa<SCEVConstant>(Step)) 696 return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue()); 697 return nullptr; 698 } 699 700 Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index, 701 ScalarEvolution *SE, 702 const DataLayout& DL) const { 703 704 SCEVExpander Exp(*SE, DL, "induction"); 705 assert(Index->getType() == Step->getType() && 706 "Index type does not match StepValue type"); 707 switch (IK) { 708 case IK_IntInduction: { 709 assert(Index->getType() == StartValue->getType() && 710 "Index type does not match StartValue type"); 711 712 // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution 713 // and calculate (Start + Index * Step) for all cases, without 714 // special handling for "isOne" and "isMinusOne". 715 // But in the real life the result code getting worse. We mix SCEV 716 // expressions and ADD/SUB operations and receive redundant 717 // intermediate values being calculated in different ways and 718 // Instcombine is unable to reduce them all. 719 720 if (getConstIntStepValue() && 721 getConstIntStepValue()->isMinusOne()) 722 return B.CreateSub(StartValue, Index); 723 if (getConstIntStepValue() && 724 getConstIntStepValue()->isOne()) 725 return B.CreateAdd(StartValue, Index); 726 const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue), 727 SE->getMulExpr(Step, SE->getSCEV(Index))); 728 return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint()); 729 } 730 case IK_PtrInduction: { 731 assert(isa<SCEVConstant>(Step) && 732 "Expected constant step for pointer induction"); 733 const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step); 734 Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint()); 735 return B.CreateGEP(nullptr, StartValue, Index); 736 } 737 case IK_FpInduction: { 738 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value"); 739 assert(InductionBinOp && 740 (InductionBinOp->getOpcode() == Instruction::FAdd || 741 InductionBinOp->getOpcode() == Instruction::FSub) && 742 "Original bin op should be defined for FP induction"); 743 744 Value *StepValue = cast<SCEVUnknown>(Step)->getValue(); 745 746 // Floating point operations had to be 'fast' to enable the induction. 747 FastMathFlags Flags; 748 Flags.setUnsafeAlgebra(); 749 750 Value *MulExp = B.CreateFMul(StepValue, Index); 751 if (isa<Instruction>(MulExp)) 752 // We have to check, the MulExp may be a constant. 753 cast<Instruction>(MulExp)->setFastMathFlags(Flags); 754 755 Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue, 756 MulExp, "induction"); 757 if (isa<Instruction>(BOp)) 758 cast<Instruction>(BOp)->setFastMathFlags(Flags); 759 760 return BOp; 761 } 762 case IK_NoInduction: 763 return nullptr; 764 } 765 llvm_unreachable("invalid enum"); 766 } 767 768 bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop, 769 ScalarEvolution *SE, 770 InductionDescriptor &D) { 771 772 // Here we only handle FP induction variables. 773 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type"); 774 775 if (TheLoop->getHeader() != Phi->getParent()) 776 return false; 777 778 // The loop may have multiple entrances or multiple exits; we can analyze 779 // this phi if it has a unique entry value and a unique backedge value. 780 if (Phi->getNumIncomingValues() != 2) 781 return false; 782 Value *BEValue = nullptr, *StartValue = nullptr; 783 if (TheLoop->contains(Phi->getIncomingBlock(0))) { 784 BEValue = Phi->getIncomingValue(0); 785 StartValue = Phi->getIncomingValue(1); 786 } else { 787 assert(TheLoop->contains(Phi->getIncomingBlock(1)) && 788 "Unexpected Phi node in the loop"); 789 BEValue = Phi->getIncomingValue(1); 790 StartValue = Phi->getIncomingValue(0); 791 } 792 793 BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue); 794 if (!BOp) 795 return false; 796 797 Value *Addend = nullptr; 798 if (BOp->getOpcode() == Instruction::FAdd) { 799 if (BOp->getOperand(0) == Phi) 800 Addend = BOp->getOperand(1); 801 else if (BOp->getOperand(1) == Phi) 802 Addend = BOp->getOperand(0); 803 } else if (BOp->getOpcode() == Instruction::FSub) 804 if (BOp->getOperand(0) == Phi) 805 Addend = BOp->getOperand(1); 806 807 if (!Addend) 808 return false; 809 810 // The addend should be loop invariant 811 if (auto *I = dyn_cast<Instruction>(Addend)) 812 if (TheLoop->contains(I)) 813 return false; 814 815 // FP Step has unknown SCEV 816 const SCEV *Step = SE->getUnknown(Addend); 817 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp); 818 return true; 819 } 820 821 bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop, 822 PredicatedScalarEvolution &PSE, 823 InductionDescriptor &D, 824 bool Assume) { 825 Type *PhiTy = Phi->getType(); 826 827 // Handle integer and pointer inductions variables. 828 // Now we handle also FP induction but not trying to make a 829 // recurrent expression from the PHI node in-place. 830 831 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && 832 !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy()) 833 return false; 834 835 if (PhiTy->isFloatingPointTy()) 836 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D); 837 838 const SCEV *PhiScev = PSE.getSCEV(Phi); 839 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 840 841 // We need this expression to be an AddRecExpr. 842 if (Assume && !AR) 843 AR = PSE.getAsAddRec(Phi); 844 845 if (!AR) { 846 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n"); 847 return false; 848 } 849 850 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR); 851 } 852 853 bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop, 854 ScalarEvolution *SE, 855 InductionDescriptor &D, 856 const SCEV *Expr) { 857 Type *PhiTy = Phi->getType(); 858 // We only handle integer and pointer inductions variables. 859 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy()) 860 return false; 861 862 // Check that the PHI is consecutive. 863 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi); 864 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 865 866 if (!AR) { 867 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n"); 868 return false; 869 } 870 871 assert(TheLoop->getHeader() == Phi->getParent() && 872 "PHI is an AddRec for a different loop?!"); 873 Value *StartValue = 874 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader()); 875 const SCEV *Step = AR->getStepRecurrence(*SE); 876 // Calculate the pointer stride and check if it is consecutive. 877 // The stride may be a constant or a loop invariant integer value. 878 const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step); 879 if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop)) 880 return false; 881 882 if (PhiTy->isIntegerTy()) { 883 D = InductionDescriptor(StartValue, IK_IntInduction, Step); 884 return true; 885 } 886 887 assert(PhiTy->isPointerTy() && "The PHI must be a pointer"); 888 // Pointer induction should be a constant. 889 if (!ConstStep) 890 return false; 891 892 ConstantInt *CV = ConstStep->getValue(); 893 Type *PointerElementType = PhiTy->getPointerElementType(); 894 // The pointer stride cannot be determined if the pointer element type is not 895 // sized. 896 if (!PointerElementType->isSized()) 897 return false; 898 899 const DataLayout &DL = Phi->getModule()->getDataLayout(); 900 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType)); 901 if (!Size) 902 return false; 903 904 int64_t CVSize = CV->getSExtValue(); 905 if (CVSize % Size) 906 return false; 907 auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size, 908 true /* signed */); 909 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue); 910 return true; 911 } 912 913 /// \brief Returns the instructions that use values defined in the loop. 914 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) { 915 SmallVector<Instruction *, 8> UsedOutside; 916 917 for (auto *Block : L->getBlocks()) 918 // FIXME: I believe that this could use copy_if if the Inst reference could 919 // be adapted into a pointer. 920 for (auto &Inst : *Block) { 921 auto Users = Inst.users(); 922 if (any_of(Users, [&](User *U) { 923 auto *Use = cast<Instruction>(U); 924 return !L->contains(Use->getParent()); 925 })) 926 UsedOutside.push_back(&Inst); 927 } 928 929 return UsedOutside; 930 } 931 932 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) { 933 // By definition, all loop passes need the LoopInfo analysis and the 934 // Dominator tree it depends on. Because they all participate in the loop 935 // pass manager, they must also preserve these. 936 AU.addRequired<DominatorTreeWrapperPass>(); 937 AU.addPreserved<DominatorTreeWrapperPass>(); 938 AU.addRequired<LoopInfoWrapperPass>(); 939 AU.addPreserved<LoopInfoWrapperPass>(); 940 941 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs 942 // here because users shouldn't directly get them from this header. 943 extern char &LoopSimplifyID; 944 extern char &LCSSAID; 945 AU.addRequiredID(LoopSimplifyID); 946 AU.addPreservedID(LoopSimplifyID); 947 AU.addRequiredID(LCSSAID); 948 AU.addPreservedID(LCSSAID); 949 950 // Loop passes are designed to run inside of a loop pass manager which means 951 // that any function analyses they require must be required by the first loop 952 // pass in the manager (so that it is computed before the loop pass manager 953 // runs) and preserved by all loop pasess in the manager. To make this 954 // reasonably robust, the set needed for most loop passes is maintained here. 955 // If your loop pass requires an analysis not listed here, you will need to 956 // carefully audit the loop pass manager nesting structure that results. 957 AU.addRequired<AAResultsWrapperPass>(); 958 AU.addPreserved<AAResultsWrapperPass>(); 959 AU.addPreserved<BasicAAWrapperPass>(); 960 AU.addPreserved<GlobalsAAWrapperPass>(); 961 AU.addPreserved<SCEVAAWrapperPass>(); 962 AU.addRequired<ScalarEvolutionWrapperPass>(); 963 AU.addPreserved<ScalarEvolutionWrapperPass>(); 964 } 965 966 /// Manually defined generic "LoopPass" dependency initialization. This is used 967 /// to initialize the exact set of passes from above in \c 968 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization 969 /// with: 970 /// 971 /// INITIALIZE_PASS_DEPENDENCY(LoopPass) 972 /// 973 /// As-if "LoopPass" were a pass. 974 void llvm::initializeLoopPassPass(PassRegistry &Registry) { 975 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 976 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 977 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 978 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 979 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 980 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 981 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 982 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 983 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 984 } 985 986 /// \brief Find string metadata for loop 987 /// 988 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an 989 /// operand or null otherwise. If the string metadata is not found return 990 /// Optional's not-a-value. 991 Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop, 992 StringRef Name) { 993 MDNode *LoopID = TheLoop->getLoopID(); 994 // Return none if LoopID is false. 995 if (!LoopID) 996 return None; 997 998 // First operand should refer to the loop id itself. 999 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 1000 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 1001 1002 // Iterate over LoopID operands and look for MDString Metadata 1003 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { 1004 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 1005 if (!MD) 1006 continue; 1007 MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 1008 if (!S) 1009 continue; 1010 // Return true if MDString holds expected MetaData. 1011 if (Name.equals(S->getString())) 1012 switch (MD->getNumOperands()) { 1013 case 1: 1014 return nullptr; 1015 case 2: 1016 return &MD->getOperand(1); 1017 default: 1018 llvm_unreachable("loop metadata has 0 or 1 operand"); 1019 } 1020 } 1021 return None; 1022 } 1023 1024 /// Returns true if the instruction in a loop is guaranteed to execute at least 1025 /// once. 1026 bool llvm::isGuaranteedToExecute(const Instruction &Inst, 1027 const DominatorTree *DT, const Loop *CurLoop, 1028 const LoopSafetyInfo *SafetyInfo) { 1029 // We have to check to make sure that the instruction dominates all 1030 // of the exit blocks. If it doesn't, then there is a path out of the loop 1031 // which does not execute this instruction, so we can't hoist it. 1032 1033 // If the instruction is in the header block for the loop (which is very 1034 // common), it is always guaranteed to dominate the exit blocks. Since this 1035 // is a common case, and can save some work, check it now. 1036 if (Inst.getParent() == CurLoop->getHeader()) 1037 // If there's a throw in the header block, we can't guarantee we'll reach 1038 // Inst. 1039 return !SafetyInfo->HeaderMayThrow; 1040 1041 // Somewhere in this loop there is an instruction which may throw and make us 1042 // exit the loop. 1043 if (SafetyInfo->MayThrow) 1044 return false; 1045 1046 // Get the exit blocks for the current loop. 1047 SmallVector<BasicBlock *, 8> ExitBlocks; 1048 CurLoop->getExitBlocks(ExitBlocks); 1049 1050 // Verify that the block dominates each of the exit blocks of the loop. 1051 for (BasicBlock *ExitBlock : ExitBlocks) 1052 if (!DT->dominates(Inst.getParent(), ExitBlock)) 1053 return false; 1054 1055 // As a degenerate case, if the loop is statically infinite then we haven't 1056 // proven anything since there are no exit blocks. 1057 if (ExitBlocks.empty()) 1058 return false; 1059 1060 // FIXME: In general, we have to prove that the loop isn't an infinite loop. 1061 // See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is 1062 // just a special case of this.) 1063 return true; 1064 } 1065