1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===// 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 contains the implementation of the scalar evolution expander, 10 // which is used to generate the code corresponding to a given scalar evolution 11 // expression. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/ScopeExit.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/Analysis/InstructionSimplify.h" 20 #include "llvm/Analysis/LoopInfo.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/Dominators.h" 25 #include "llvm/IR/IntrinsicInst.h" 26 #include "llvm/IR/PatternMatch.h" 27 #include "llvm/Support/CommandLine.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include "llvm/Transforms/Utils/LoopUtils.h" 30 31 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS 32 #define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X) 33 #else 34 #define SCEV_DEBUG_WITH_TYPE(TYPE, X) 35 #endif 36 37 using namespace llvm; 38 39 cl::opt<unsigned> llvm::SCEVCheapExpansionBudget( 40 "scev-cheap-expansion-budget", cl::Hidden, cl::init(4), 41 cl::desc("When performing SCEV expansion only if it is cheap to do, this " 42 "controls the budget that is considered cheap (default = 4)")); 43 44 using namespace PatternMatch; 45 46 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP, 47 /// reusing an existing cast if a suitable one (= dominating IP) exists, or 48 /// creating a new one. 49 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty, 50 Instruction::CastOps Op, 51 BasicBlock::iterator IP) { 52 // This function must be called with the builder having a valid insertion 53 // point. It doesn't need to be the actual IP where the uses of the returned 54 // cast will be added, but it must dominate such IP. 55 // We use this precondition to produce a cast that will dominate all its 56 // uses. In particular, this is crucial for the case where the builder's 57 // insertion point *is* the point where we were asked to put the cast. 58 // Since we don't know the builder's insertion point is actually 59 // where the uses will be added (only that it dominates it), we are 60 // not allowed to move it. 61 BasicBlock::iterator BIP = Builder.GetInsertPoint(); 62 63 Value *Ret = nullptr; 64 65 // Check to see if there is already a cast! 66 for (User *U : V->users()) { 67 if (U->getType() != Ty) 68 continue; 69 CastInst *CI = dyn_cast<CastInst>(U); 70 if (!CI || CI->getOpcode() != Op) 71 continue; 72 73 // Found a suitable cast that is at IP or comes before IP. Use it. Note that 74 // the cast must also properly dominate the Builder's insertion point. 75 if (IP->getParent() == CI->getParent() && &*BIP != CI && 76 (&*IP == CI || CI->comesBefore(&*IP))) { 77 Ret = CI; 78 break; 79 } 80 } 81 82 // Create a new cast. 83 if (!Ret) { 84 SCEVInsertPointGuard Guard(Builder, this); 85 Builder.SetInsertPoint(&*IP); 86 Ret = Builder.CreateCast(Op, V, Ty, V->getName()); 87 } 88 89 // We assert at the end of the function since IP might point to an 90 // instruction with different dominance properties than a cast 91 // (an invoke for example) and not dominate BIP (but the cast does). 92 assert(!isa<Instruction>(Ret) || 93 SE.DT.dominates(cast<Instruction>(Ret), &*BIP)); 94 95 return Ret; 96 } 97 98 BasicBlock::iterator 99 SCEVExpander::findInsertPointAfter(Instruction *I, 100 Instruction *MustDominate) const { 101 BasicBlock::iterator IP = ++I->getIterator(); 102 if (auto *II = dyn_cast<InvokeInst>(I)) 103 IP = II->getNormalDest()->begin(); 104 105 while (isa<PHINode>(IP)) 106 ++IP; 107 108 if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) { 109 ++IP; 110 } else if (isa<CatchSwitchInst>(IP)) { 111 IP = MustDominate->getParent()->getFirstInsertionPt(); 112 } else { 113 assert(!IP->isEHPad() && "unexpected eh pad!"); 114 } 115 116 // Adjust insert point to be after instructions inserted by the expander, so 117 // we can re-use already inserted instructions. Avoid skipping past the 118 // original \p MustDominate, in case it is an inserted instruction. 119 while (isInsertedInstruction(&*IP) && &*IP != MustDominate) 120 ++IP; 121 122 return IP; 123 } 124 125 BasicBlock::iterator 126 SCEVExpander::GetOptimalInsertionPointForCastOf(Value *V) const { 127 // Cast the argument at the beginning of the entry block, after 128 // any bitcasts of other arguments. 129 if (Argument *A = dyn_cast<Argument>(V)) { 130 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin(); 131 while ((isa<BitCastInst>(IP) && 132 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) && 133 cast<BitCastInst>(IP)->getOperand(0) != A) || 134 isa<DbgInfoIntrinsic>(IP)) 135 ++IP; 136 return IP; 137 } 138 139 // Cast the instruction immediately after the instruction. 140 if (Instruction *I = dyn_cast<Instruction>(V)) 141 return findInsertPointAfter(I, &*Builder.GetInsertPoint()); 142 143 // Otherwise, this must be some kind of a constant, 144 // so let's plop this cast into the function's entry block. 145 assert(isa<Constant>(V) && 146 "Expected the cast argument to be a global/constant"); 147 return Builder.GetInsertBlock() 148 ->getParent() 149 ->getEntryBlock() 150 .getFirstInsertionPt(); 151 } 152 153 /// InsertNoopCastOfTo - Insert a cast of V to the specified type, 154 /// which must be possible with a noop cast, doing what we can to share 155 /// the casts. 156 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) { 157 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false); 158 assert((Op == Instruction::BitCast || 159 Op == Instruction::PtrToInt || 160 Op == Instruction::IntToPtr) && 161 "InsertNoopCastOfTo cannot perform non-noop casts!"); 162 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) && 163 "InsertNoopCastOfTo cannot change sizes!"); 164 165 // inttoptr only works for integral pointers. For non-integral pointers, we 166 // can create a GEP on null with the integral value as index. Note that 167 // it is safe to use GEP of null instead of inttoptr here, because only 168 // expressions already based on a GEP of null should be converted to pointers 169 // during expansion. 170 if (Op == Instruction::IntToPtr) { 171 auto *PtrTy = cast<PointerType>(Ty); 172 if (DL.isNonIntegralPointerType(PtrTy)) { 173 assert(DL.getTypeAllocSize(Builder.getInt8Ty()) == 1 && 174 "alloc size of i8 must by 1 byte for the GEP to be correct"); 175 return Builder.CreateGEP( 176 Builder.getInt8Ty(), Constant::getNullValue(PtrTy), V, "scevgep"); 177 } 178 } 179 // Short-circuit unnecessary bitcasts. 180 if (Op == Instruction::BitCast) { 181 if (V->getType() == Ty) 182 return V; 183 if (CastInst *CI = dyn_cast<CastInst>(V)) { 184 if (CI->getOperand(0)->getType() == Ty) 185 return CI->getOperand(0); 186 } 187 } 188 // Short-circuit unnecessary inttoptr<->ptrtoint casts. 189 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) && 190 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) { 191 if (CastInst *CI = dyn_cast<CastInst>(V)) 192 if ((CI->getOpcode() == Instruction::PtrToInt || 193 CI->getOpcode() == Instruction::IntToPtr) && 194 SE.getTypeSizeInBits(CI->getType()) == 195 SE.getTypeSizeInBits(CI->getOperand(0)->getType())) 196 return CI->getOperand(0); 197 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 198 if ((CE->getOpcode() == Instruction::PtrToInt || 199 CE->getOpcode() == Instruction::IntToPtr) && 200 SE.getTypeSizeInBits(CE->getType()) == 201 SE.getTypeSizeInBits(CE->getOperand(0)->getType())) 202 return CE->getOperand(0); 203 } 204 205 // Fold a cast of a constant. 206 if (Constant *C = dyn_cast<Constant>(V)) 207 return ConstantExpr::getCast(Op, C, Ty); 208 209 // Try to reuse existing cast, or insert one. 210 return ReuseOrCreateCast(V, Ty, Op, GetOptimalInsertionPointForCastOf(V)); 211 } 212 213 /// InsertBinop - Insert the specified binary operator, doing a small amount 214 /// of work to avoid inserting an obviously redundant operation, and hoisting 215 /// to an outer loop when the opportunity is there and it is safe. 216 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, 217 Value *LHS, Value *RHS, 218 SCEV::NoWrapFlags Flags, bool IsSafeToHoist) { 219 // Fold a binop with constant operands. 220 if (Constant *CLHS = dyn_cast<Constant>(LHS)) 221 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 222 if (Constant *Res = ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, DL)) 223 return Res; 224 225 // Do a quick scan to see if we have this binop nearby. If so, reuse it. 226 unsigned ScanLimit = 6; 227 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin(); 228 // Scanning starts from the last instruction before the insertion point. 229 BasicBlock::iterator IP = Builder.GetInsertPoint(); 230 if (IP != BlockBegin) { 231 --IP; 232 for (; ScanLimit; --IP, --ScanLimit) { 233 // Don't count dbg.value against the ScanLimit, to avoid perturbing the 234 // generated code. 235 if (isa<DbgInfoIntrinsic>(IP)) 236 ScanLimit++; 237 238 auto canGenerateIncompatiblePoison = [&Flags](Instruction *I) { 239 // Ensure that no-wrap flags match. 240 if (isa<OverflowingBinaryOperator>(I)) { 241 if (I->hasNoSignedWrap() != (Flags & SCEV::FlagNSW)) 242 return true; 243 if (I->hasNoUnsignedWrap() != (Flags & SCEV::FlagNUW)) 244 return true; 245 } 246 // Conservatively, do not use any instruction which has any of exact 247 // flags installed. 248 if (isa<PossiblyExactOperator>(I) && I->isExact()) 249 return true; 250 return false; 251 }; 252 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS && 253 IP->getOperand(1) == RHS && !canGenerateIncompatiblePoison(&*IP)) 254 return &*IP; 255 if (IP == BlockBegin) break; 256 } 257 } 258 259 // Save the original insertion point so we can restore it when we're done. 260 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc(); 261 SCEVInsertPointGuard Guard(Builder, this); 262 263 if (IsSafeToHoist) { 264 // Move the insertion point out of as many loops as we can. 265 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) { 266 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break; 267 BasicBlock *Preheader = L->getLoopPreheader(); 268 if (!Preheader) break; 269 270 // Ok, move up a level. 271 Builder.SetInsertPoint(Preheader->getTerminator()); 272 } 273 } 274 275 // If we haven't found this binop, insert it. 276 // TODO: Use the Builder, which will make CreateBinOp below fold with 277 // InstSimplifyFolder. 278 Instruction *BO = Builder.Insert(BinaryOperator::Create(Opcode, LHS, RHS)); 279 BO->setDebugLoc(Loc); 280 if (Flags & SCEV::FlagNUW) 281 BO->setHasNoUnsignedWrap(); 282 if (Flags & SCEV::FlagNSW) 283 BO->setHasNoSignedWrap(); 284 285 return BO; 286 } 287 288 /// expandAddToGEP - Expand an addition expression with a pointer type into 289 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps 290 /// BasicAliasAnalysis and other passes analyze the result. See the rules 291 /// for getelementptr vs. inttoptr in 292 /// http://llvm.org/docs/LangRef.html#pointeraliasing 293 /// for details. 294 /// 295 /// Design note: The correctness of using getelementptr here depends on 296 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as 297 /// they may introduce pointer arithmetic which may not be safely converted 298 /// into getelementptr. 299 /// 300 /// Design note: It might seem desirable for this function to be more 301 /// loop-aware. If some of the indices are loop-invariant while others 302 /// aren't, it might seem desirable to emit multiple GEPs, keeping the 303 /// loop-invariant portions of the overall computation outside the loop. 304 /// However, there are a few reasons this is not done here. Hoisting simple 305 /// arithmetic is a low-level optimization that often isn't very 306 /// important until late in the optimization process. In fact, passes 307 /// like InstructionCombining will combine GEPs, even if it means 308 /// pushing loop-invariant computation down into loops, so even if the 309 /// GEPs were split here, the work would quickly be undone. The 310 /// LoopStrengthReduction pass, which is usually run quite late (and 311 /// after the last InstructionCombining pass), takes care of hoisting 312 /// loop-invariant portions of expressions, after considering what 313 /// can be folded using target addressing modes. 314 /// 315 Value *SCEVExpander::expandAddToGEP(const SCEV *Offset, Type *Ty, Value *V) { 316 assert(!isa<Instruction>(V) || 317 SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint())); 318 319 Value *Idx = expandCodeFor(Offset, Ty); 320 321 // Fold a GEP with constant operands. 322 if (Constant *CLHS = dyn_cast<Constant>(V)) 323 if (Constant *CRHS = dyn_cast<Constant>(Idx)) 324 return Builder.CreateGEP(Builder.getInt8Ty(), CLHS, CRHS); 325 326 // Do a quick scan to see if we have this GEP nearby. If so, reuse it. 327 unsigned ScanLimit = 6; 328 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin(); 329 // Scanning starts from the last instruction before the insertion point. 330 BasicBlock::iterator IP = Builder.GetInsertPoint(); 331 if (IP != BlockBegin) { 332 --IP; 333 for (; ScanLimit; --IP, --ScanLimit) { 334 // Don't count dbg.value against the ScanLimit, to avoid perturbing the 335 // generated code. 336 if (isa<DbgInfoIntrinsic>(IP)) 337 ScanLimit++; 338 if (IP->getOpcode() == Instruction::GetElementPtr && 339 IP->getOperand(0) == V && IP->getOperand(1) == Idx && 340 cast<GEPOperator>(&*IP)->getSourceElementType() == 341 Type::getInt8Ty(Ty->getContext())) 342 return &*IP; 343 if (IP == BlockBegin) break; 344 } 345 } 346 347 // Save the original insertion point so we can restore it when we're done. 348 SCEVInsertPointGuard Guard(Builder, this); 349 350 // Move the insertion point out of as many loops as we can. 351 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) { 352 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break; 353 BasicBlock *Preheader = L->getLoopPreheader(); 354 if (!Preheader) break; 355 356 // Ok, move up a level. 357 Builder.SetInsertPoint(Preheader->getTerminator()); 358 } 359 360 // Emit a GEP. 361 return Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "scevgep"); 362 } 363 364 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for 365 /// SCEV expansion. If they are nested, this is the most nested. If they are 366 /// neighboring, pick the later. 367 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B, 368 DominatorTree &DT) { 369 if (!A) return B; 370 if (!B) return A; 371 if (A->contains(B)) return B; 372 if (B->contains(A)) return A; 373 if (DT.dominates(A->getHeader(), B->getHeader())) return B; 374 if (DT.dominates(B->getHeader(), A->getHeader())) return A; 375 return A; // Arbitrarily break the tie. 376 } 377 378 /// getRelevantLoop - Get the most relevant loop associated with the given 379 /// expression, according to PickMostRelevantLoop. 380 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) { 381 // Test whether we've already computed the most relevant loop for this SCEV. 382 auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr)); 383 if (!Pair.second) 384 return Pair.first->second; 385 386 switch (S->getSCEVType()) { 387 case scConstant: 388 case scVScale: 389 return nullptr; // A constant has no relevant loops. 390 case scTruncate: 391 case scZeroExtend: 392 case scSignExtend: 393 case scPtrToInt: 394 case scAddExpr: 395 case scMulExpr: 396 case scUDivExpr: 397 case scAddRecExpr: 398 case scUMaxExpr: 399 case scSMaxExpr: 400 case scUMinExpr: 401 case scSMinExpr: 402 case scSequentialUMinExpr: { 403 const Loop *L = nullptr; 404 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 405 L = AR->getLoop(); 406 for (const SCEV *Op : S->operands()) 407 L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT); 408 return RelevantLoops[S] = L; 409 } 410 case scUnknown: { 411 const SCEVUnknown *U = cast<SCEVUnknown>(S); 412 if (const Instruction *I = dyn_cast<Instruction>(U->getValue())) 413 return Pair.first->second = SE.LI.getLoopFor(I->getParent()); 414 // A non-instruction has no relevant loops. 415 return nullptr; 416 } 417 case scCouldNotCompute: 418 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 419 } 420 llvm_unreachable("Unexpected SCEV type!"); 421 } 422 423 namespace { 424 425 /// LoopCompare - Compare loops by PickMostRelevantLoop. 426 class LoopCompare { 427 DominatorTree &DT; 428 public: 429 explicit LoopCompare(DominatorTree &dt) : DT(dt) {} 430 431 bool operator()(std::pair<const Loop *, const SCEV *> LHS, 432 std::pair<const Loop *, const SCEV *> RHS) const { 433 // Keep pointer operands sorted at the end. 434 if (LHS.second->getType()->isPointerTy() != 435 RHS.second->getType()->isPointerTy()) 436 return LHS.second->getType()->isPointerTy(); 437 438 // Compare loops with PickMostRelevantLoop. 439 if (LHS.first != RHS.first) 440 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first; 441 442 // If one operand is a non-constant negative and the other is not, 443 // put the non-constant negative on the right so that a sub can 444 // be used instead of a negate and add. 445 if (LHS.second->isNonConstantNegative()) { 446 if (!RHS.second->isNonConstantNegative()) 447 return false; 448 } else if (RHS.second->isNonConstantNegative()) 449 return true; 450 451 // Otherwise they are equivalent according to this comparison. 452 return false; 453 } 454 }; 455 456 } 457 458 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) { 459 // Collect all the add operands in a loop, along with their associated loops. 460 // Iterate in reverse so that constants are emitted last, all else equal, and 461 // so that pointer operands are inserted first, which the code below relies on 462 // to form more involved GEPs. 463 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops; 464 for (const SCEV *Op : reverse(S->operands())) 465 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op)); 466 467 // Sort by loop. Use a stable sort so that constants follow non-constants and 468 // pointer operands precede non-pointer operands. 469 llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT)); 470 471 // Emit instructions to add all the operands. Hoist as much as possible 472 // out of loops, and form meaningful getelementptrs where possible. 473 Value *Sum = nullptr; 474 for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) { 475 const Loop *CurLoop = I->first; 476 const SCEV *Op = I->second; 477 if (!Sum) { 478 // This is the first operand. Just expand it. 479 Sum = expand(Op); 480 ++I; 481 continue; 482 } 483 484 assert(!Op->getType()->isPointerTy() && "Only first op can be pointer"); 485 if (isa<PointerType>(Sum->getType())) { 486 // The running sum expression is a pointer. Try to form a getelementptr 487 // at this level with that as the base. 488 SmallVector<const SCEV *, 4> NewOps; 489 for (; I != E && I->first == CurLoop; ++I) { 490 // If the operand is SCEVUnknown and not instructions, peek through 491 // it, to enable more of it to be folded into the GEP. 492 const SCEV *X = I->second; 493 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X)) 494 if (!isa<Instruction>(U->getValue())) 495 X = SE.getSCEV(U->getValue()); 496 NewOps.push_back(X); 497 } 498 Type *Ty = SE.getEffectiveSCEVType(S->getType()); 499 Sum = expandAddToGEP(SE.getAddExpr(NewOps), Ty, Sum); 500 } else if (Op->isNonConstantNegative()) { 501 // Instead of doing a negate and add, just do a subtract. 502 Value *W = expand(SE.getNegativeSCEV(Op)); 503 Sum = InsertBinop(Instruction::Sub, Sum, W, SCEV::FlagAnyWrap, 504 /*IsSafeToHoist*/ true); 505 ++I; 506 } else { 507 // A simple add. 508 Value *W = expand(Op); 509 // Canonicalize a constant to the RHS. 510 if (isa<Constant>(Sum)) 511 std::swap(Sum, W); 512 Sum = InsertBinop(Instruction::Add, Sum, W, S->getNoWrapFlags(), 513 /*IsSafeToHoist*/ true); 514 ++I; 515 } 516 } 517 518 return Sum; 519 } 520 521 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) { 522 Type *Ty = S->getType(); 523 524 // Collect all the mul operands in a loop, along with their associated loops. 525 // Iterate in reverse so that constants are emitted last, all else equal. 526 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops; 527 for (const SCEV *Op : reverse(S->operands())) 528 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op)); 529 530 // Sort by loop. Use a stable sort so that constants follow non-constants. 531 llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT)); 532 533 // Emit instructions to mul all the operands. Hoist as much as possible 534 // out of loops. 535 Value *Prod = nullptr; 536 auto I = OpsAndLoops.begin(); 537 538 // Expand the calculation of X pow N in the following manner: 539 // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then: 540 // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK). 541 const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops]() { 542 auto E = I; 543 // Calculate how many times the same operand from the same loop is included 544 // into this power. 545 uint64_t Exponent = 0; 546 const uint64_t MaxExponent = UINT64_MAX >> 1; 547 // No one sane will ever try to calculate such huge exponents, but if we 548 // need this, we stop on UINT64_MAX / 2 because we need to exit the loop 549 // below when the power of 2 exceeds our Exponent, and we want it to be 550 // 1u << 31 at most to not deal with unsigned overflow. 551 while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) { 552 ++Exponent; 553 ++E; 554 } 555 assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?"); 556 557 // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them 558 // that are needed into the result. 559 Value *P = expand(I->second); 560 Value *Result = nullptr; 561 if (Exponent & 1) 562 Result = P; 563 for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) { 564 P = InsertBinop(Instruction::Mul, P, P, SCEV::FlagAnyWrap, 565 /*IsSafeToHoist*/ true); 566 if (Exponent & BinExp) 567 Result = Result ? InsertBinop(Instruction::Mul, Result, P, 568 SCEV::FlagAnyWrap, 569 /*IsSafeToHoist*/ true) 570 : P; 571 } 572 573 I = E; 574 assert(Result && "Nothing was expanded?"); 575 return Result; 576 }; 577 578 while (I != OpsAndLoops.end()) { 579 if (!Prod) { 580 // This is the first operand. Just expand it. 581 Prod = ExpandOpBinPowN(); 582 } else if (I->second->isAllOnesValue()) { 583 // Instead of doing a multiply by negative one, just do a negate. 584 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod, 585 SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true); 586 ++I; 587 } else { 588 // A simple mul. 589 Value *W = ExpandOpBinPowN(); 590 // Canonicalize a constant to the RHS. 591 if (isa<Constant>(Prod)) std::swap(Prod, W); 592 const APInt *RHS; 593 if (match(W, m_Power2(RHS))) { 594 // Canonicalize Prod*(1<<C) to Prod<<C. 595 assert(!Ty->isVectorTy() && "vector types are not SCEVable"); 596 auto NWFlags = S->getNoWrapFlags(); 597 // clear nsw flag if shl will produce poison value. 598 if (RHS->logBase2() == RHS->getBitWidth() - 1) 599 NWFlags = ScalarEvolution::clearFlags(NWFlags, SCEV::FlagNSW); 600 Prod = InsertBinop(Instruction::Shl, Prod, 601 ConstantInt::get(Ty, RHS->logBase2()), NWFlags, 602 /*IsSafeToHoist*/ true); 603 } else { 604 Prod = InsertBinop(Instruction::Mul, Prod, W, S->getNoWrapFlags(), 605 /*IsSafeToHoist*/ true); 606 } 607 } 608 } 609 610 return Prod; 611 } 612 613 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) { 614 Value *LHS = expand(S->getLHS()); 615 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) { 616 const APInt &RHS = SC->getAPInt(); 617 if (RHS.isPowerOf2()) 618 return InsertBinop(Instruction::LShr, LHS, 619 ConstantInt::get(SC->getType(), RHS.logBase2()), 620 SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true); 621 } 622 623 Value *RHS = expand(S->getRHS()); 624 return InsertBinop(Instruction::UDiv, LHS, RHS, SCEV::FlagAnyWrap, 625 /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS())); 626 } 627 628 /// Determine if this is a well-behaved chain of instructions leading back to 629 /// the PHI. If so, it may be reused by expanded expressions. 630 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV, 631 const Loop *L) { 632 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) || 633 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV))) 634 return false; 635 // If any of the operands don't dominate the insert position, bail. 636 // Addrec operands are always loop-invariant, so this can only happen 637 // if there are instructions which haven't been hoisted. 638 if (L == IVIncInsertLoop) { 639 for (Use &Op : llvm::drop_begin(IncV->operands())) 640 if (Instruction *OInst = dyn_cast<Instruction>(Op)) 641 if (!SE.DT.dominates(OInst, IVIncInsertPos)) 642 return false; 643 } 644 // Advance to the next instruction. 645 IncV = dyn_cast<Instruction>(IncV->getOperand(0)); 646 if (!IncV) 647 return false; 648 649 if (IncV->mayHaveSideEffects()) 650 return false; 651 652 if (IncV == PN) 653 return true; 654 655 return isNormalAddRecExprPHI(PN, IncV, L); 656 } 657 658 /// getIVIncOperand returns an induction variable increment's induction 659 /// variable operand. 660 /// 661 /// If allowScale is set, any type of GEP is allowed as long as the nonIV 662 /// operands dominate InsertPos. 663 /// 664 /// If allowScale is not set, ensure that a GEP increment conforms to one of the 665 /// simple patterns generated by getAddRecExprPHILiterally and 666 /// expandAddtoGEP. If the pattern isn't recognized, return NULL. 667 Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV, 668 Instruction *InsertPos, 669 bool allowScale) { 670 if (IncV == InsertPos) 671 return nullptr; 672 673 switch (IncV->getOpcode()) { 674 default: 675 return nullptr; 676 // Check for a simple Add/Sub or GEP of a loop invariant step. 677 case Instruction::Add: 678 case Instruction::Sub: { 679 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1)); 680 if (!OInst || SE.DT.dominates(OInst, InsertPos)) 681 return dyn_cast<Instruction>(IncV->getOperand(0)); 682 return nullptr; 683 } 684 case Instruction::BitCast: 685 return dyn_cast<Instruction>(IncV->getOperand(0)); 686 case Instruction::GetElementPtr: 687 for (Use &U : llvm::drop_begin(IncV->operands())) { 688 if (isa<Constant>(U)) 689 continue; 690 if (Instruction *OInst = dyn_cast<Instruction>(U)) { 691 if (!SE.DT.dominates(OInst, InsertPos)) 692 return nullptr; 693 } 694 if (allowScale) { 695 // allow any kind of GEP as long as it can be hoisted. 696 continue; 697 } 698 // GEPs produced by SCEVExpander use i8 element type. 699 if (!cast<GEPOperator>(IncV)->getSourceElementType()->isIntegerTy(8)) 700 return nullptr; 701 break; 702 } 703 return dyn_cast<Instruction>(IncV->getOperand(0)); 704 } 705 } 706 707 /// If the insert point of the current builder or any of the builders on the 708 /// stack of saved builders has 'I' as its insert point, update it to point to 709 /// the instruction after 'I'. This is intended to be used when the instruction 710 /// 'I' is being moved. If this fixup is not done and 'I' is moved to a 711 /// different block, the inconsistent insert point (with a mismatched 712 /// Instruction and Block) can lead to an instruction being inserted in a block 713 /// other than its parent. 714 void SCEVExpander::fixupInsertPoints(Instruction *I) { 715 BasicBlock::iterator It(*I); 716 BasicBlock::iterator NewInsertPt = std::next(It); 717 if (Builder.GetInsertPoint() == It) 718 Builder.SetInsertPoint(&*NewInsertPt); 719 for (auto *InsertPtGuard : InsertPointGuards) 720 if (InsertPtGuard->GetInsertPoint() == It) 721 InsertPtGuard->SetInsertPoint(NewInsertPt); 722 } 723 724 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make 725 /// it available to other uses in this loop. Recursively hoist any operands, 726 /// until we reach a value that dominates InsertPos. 727 bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos, 728 bool RecomputePoisonFlags) { 729 auto FixupPoisonFlags = [this](Instruction *I) { 730 // Drop flags that are potentially inferred from old context and infer flags 731 // in new context. 732 I->dropPoisonGeneratingFlags(); 733 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I)) 734 if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) { 735 auto *BO = cast<BinaryOperator>(I); 736 BO->setHasNoUnsignedWrap( 737 ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) == SCEV::FlagNUW); 738 BO->setHasNoSignedWrap( 739 ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) == SCEV::FlagNSW); 740 } 741 }; 742 743 if (SE.DT.dominates(IncV, InsertPos)) { 744 if (RecomputePoisonFlags) 745 FixupPoisonFlags(IncV); 746 return true; 747 } 748 749 // InsertPos must itself dominate IncV so that IncV's new position satisfies 750 // its existing users. 751 if (isa<PHINode>(InsertPos) || 752 !SE.DT.dominates(InsertPos->getParent(), IncV->getParent())) 753 return false; 754 755 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos)) 756 return false; 757 758 // Check that the chain of IV operands leading back to Phi can be hoisted. 759 SmallVector<Instruction*, 4> IVIncs; 760 for(;;) { 761 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true); 762 if (!Oper) 763 return false; 764 // IncV is safe to hoist. 765 IVIncs.push_back(IncV); 766 IncV = Oper; 767 if (SE.DT.dominates(IncV, InsertPos)) 768 break; 769 } 770 for (Instruction *I : llvm::reverse(IVIncs)) { 771 fixupInsertPoints(I); 772 I->moveBefore(InsertPos); 773 if (RecomputePoisonFlags) 774 FixupPoisonFlags(I); 775 } 776 return true; 777 } 778 779 /// Determine if this cyclic phi is in a form that would have been generated by 780 /// LSR. We don't care if the phi was actually expanded in this pass, as long 781 /// as it is in a low-cost form, for example, no implied multiplication. This 782 /// should match any patterns generated by getAddRecExprPHILiterally and 783 /// expandAddtoGEP. 784 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV, 785 const Loop *L) { 786 for(Instruction *IVOper = IncV; 787 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(), 788 /*allowScale=*/false));) { 789 if (IVOper == PN) 790 return true; 791 } 792 return false; 793 } 794 795 /// expandIVInc - Expand an IV increment at Builder's current InsertPos. 796 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may 797 /// need to materialize IV increments elsewhere to handle difficult situations. 798 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L, 799 Type *ExpandTy, Type *IntTy, 800 bool useSubtract) { 801 Value *IncV; 802 // If the PHI is a pointer, use a GEP, otherwise use an add or sub. 803 if (ExpandTy->isPointerTy()) { 804 IncV = expandAddToGEP(SE.getSCEV(StepV), IntTy, PN); 805 } else { 806 IncV = useSubtract ? 807 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") : 808 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next"); 809 } 810 return IncV; 811 } 812 813 /// Check whether we can cheaply express the requested SCEV in terms of 814 /// the available PHI SCEV by truncation and/or inversion of the step. 815 static bool canBeCheaplyTransformed(ScalarEvolution &SE, 816 const SCEVAddRecExpr *Phi, 817 const SCEVAddRecExpr *Requested, 818 bool &InvertStep) { 819 // We can't transform to match a pointer PHI. 820 if (Phi->getType()->isPointerTy()) 821 return false; 822 823 Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType()); 824 Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType()); 825 826 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth()) 827 return false; 828 829 // Try truncate it if necessary. 830 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy)); 831 if (!Phi) 832 return false; 833 834 // Check whether truncation will help. 835 if (Phi == Requested) { 836 InvertStep = false; 837 return true; 838 } 839 840 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}. 841 if (SE.getMinusSCEV(Requested->getStart(), Requested) == Phi) { 842 InvertStep = true; 843 return true; 844 } 845 846 return false; 847 } 848 849 static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) { 850 if (!isa<IntegerType>(AR->getType())) 851 return false; 852 853 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth(); 854 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2); 855 const SCEV *Step = AR->getStepRecurrence(SE); 856 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy), 857 SE.getSignExtendExpr(AR, WideTy)); 858 const SCEV *ExtendAfterOp = 859 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy); 860 return ExtendAfterOp == OpAfterExtend; 861 } 862 863 static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) { 864 if (!isa<IntegerType>(AR->getType())) 865 return false; 866 867 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth(); 868 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2); 869 const SCEV *Step = AR->getStepRecurrence(SE); 870 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy), 871 SE.getZeroExtendExpr(AR, WideTy)); 872 const SCEV *ExtendAfterOp = 873 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy); 874 return ExtendAfterOp == OpAfterExtend; 875 } 876 877 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand 878 /// the base addrec, which is the addrec without any non-loop-dominating 879 /// values, and return the PHI. 880 PHINode * 881 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized, 882 const Loop *L, 883 Type *ExpandTy, 884 Type *IntTy, 885 Type *&TruncTy, 886 bool &InvertStep) { 887 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position"); 888 889 // Reuse a previously-inserted PHI, if present. 890 BasicBlock *LatchBlock = L->getLoopLatch(); 891 if (LatchBlock) { 892 PHINode *AddRecPhiMatch = nullptr; 893 Instruction *IncV = nullptr; 894 TruncTy = nullptr; 895 InvertStep = false; 896 897 // Only try partially matching scevs that need truncation and/or 898 // step-inversion if we know this loop is outside the current loop. 899 bool TryNonMatchingSCEV = 900 IVIncInsertLoop && 901 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader()); 902 903 for (PHINode &PN : L->getHeader()->phis()) { 904 if (!SE.isSCEVable(PN.getType())) 905 continue; 906 907 // We should not look for a incomplete PHI. Getting SCEV for a incomplete 908 // PHI has no meaning at all. 909 if (!PN.isComplete()) { 910 SCEV_DEBUG_WITH_TYPE( 911 DebugType, dbgs() << "One incomplete PHI is found: " << PN << "\n"); 912 continue; 913 } 914 915 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN)); 916 if (!PhiSCEV) 917 continue; 918 919 bool IsMatchingSCEV = PhiSCEV == Normalized; 920 // We only handle truncation and inversion of phi recurrences for the 921 // expanded expression if the expanded expression's loop dominates the 922 // loop we insert to. Check now, so we can bail out early. 923 if (!IsMatchingSCEV && !TryNonMatchingSCEV) 924 continue; 925 926 // TODO: this possibly can be reworked to avoid this cast at all. 927 Instruction *TempIncV = 928 dyn_cast<Instruction>(PN.getIncomingValueForBlock(LatchBlock)); 929 if (!TempIncV) 930 continue; 931 932 // Check whether we can reuse this PHI node. 933 if (LSRMode) { 934 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L)) 935 continue; 936 } else { 937 if (!isNormalAddRecExprPHI(&PN, TempIncV, L)) 938 continue; 939 } 940 941 // Stop if we have found an exact match SCEV. 942 if (IsMatchingSCEV) { 943 IncV = TempIncV; 944 TruncTy = nullptr; 945 InvertStep = false; 946 AddRecPhiMatch = &PN; 947 break; 948 } 949 950 // Try whether the phi can be translated into the requested form 951 // (truncated and/or offset by a constant). 952 if ((!TruncTy || InvertStep) && 953 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) { 954 // Record the phi node. But don't stop we might find an exact match 955 // later. 956 AddRecPhiMatch = &PN; 957 IncV = TempIncV; 958 TruncTy = SE.getEffectiveSCEVType(Normalized->getType()); 959 } 960 } 961 962 if (AddRecPhiMatch) { 963 // Ok, the add recurrence looks usable. 964 // Remember this PHI, even in post-inc mode. 965 InsertedValues.insert(AddRecPhiMatch); 966 // Remember the increment. 967 rememberInstruction(IncV); 968 // Those values were not actually inserted but re-used. 969 ReusedValues.insert(AddRecPhiMatch); 970 ReusedValues.insert(IncV); 971 return AddRecPhiMatch; 972 } 973 } 974 975 // Save the original insertion point so we can restore it when we're done. 976 SCEVInsertPointGuard Guard(Builder, this); 977 978 // Another AddRec may need to be recursively expanded below. For example, if 979 // this AddRec is quadratic, the StepV may itself be an AddRec in this 980 // loop. Remove this loop from the PostIncLoops set before expanding such 981 // AddRecs. Otherwise, we cannot find a valid position for the step 982 // (i.e. StepV can never dominate its loop header). Ideally, we could do 983 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element, 984 // so it's not worth implementing SmallPtrSet::swap. 985 PostIncLoopSet SavedPostIncLoops = PostIncLoops; 986 PostIncLoops.clear(); 987 988 // Expand code for the start value into the loop preheader. 989 assert(L->getLoopPreheader() && 990 "Can't expand add recurrences without a loop preheader!"); 991 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy, 992 L->getLoopPreheader()->getTerminator()); 993 994 // StartV must have been be inserted into L's preheader to dominate the new 995 // phi. 996 assert(!isa<Instruction>(StartV) || 997 SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(), 998 L->getHeader())); 999 1000 // Expand code for the step value. Do this before creating the PHI so that PHI 1001 // reuse code doesn't see an incomplete PHI. 1002 const SCEV *Step = Normalized->getStepRecurrence(SE); 1003 // If the stride is negative, insert a sub instead of an add for the increment 1004 // (unless it's a constant, because subtracts of constants are canonicalized 1005 // to adds). 1006 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative(); 1007 if (useSubtract) 1008 Step = SE.getNegativeSCEV(Step); 1009 // Expand the step somewhere that dominates the loop header. 1010 Value *StepV = 1011 expandCodeFor(Step, IntTy, L->getHeader()->getFirstInsertionPt()); 1012 1013 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if 1014 // we actually do emit an addition. It does not apply if we emit a 1015 // subtraction. 1016 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized); 1017 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized); 1018 1019 // Create the PHI. 1020 BasicBlock *Header = L->getHeader(); 1021 Builder.SetInsertPoint(Header, Header->begin()); 1022 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header); 1023 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE), 1024 Twine(IVName) + ".iv"); 1025 1026 // Create the step instructions and populate the PHI. 1027 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) { 1028 BasicBlock *Pred = *HPI; 1029 1030 // Add a start value. 1031 if (!L->contains(Pred)) { 1032 PN->addIncoming(StartV, Pred); 1033 continue; 1034 } 1035 1036 // Create a step value and add it to the PHI. 1037 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the 1038 // instructions at IVIncInsertPos. 1039 Instruction *InsertPos = L == IVIncInsertLoop ? 1040 IVIncInsertPos : Pred->getTerminator(); 1041 Builder.SetInsertPoint(InsertPos); 1042 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract); 1043 1044 if (isa<OverflowingBinaryOperator>(IncV)) { 1045 if (IncrementIsNUW) 1046 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap(); 1047 if (IncrementIsNSW) 1048 cast<BinaryOperator>(IncV)->setHasNoSignedWrap(); 1049 } 1050 PN->addIncoming(IncV, Pred); 1051 } 1052 1053 // After expanding subexpressions, restore the PostIncLoops set so the caller 1054 // can ensure that IVIncrement dominates the current uses. 1055 PostIncLoops = SavedPostIncLoops; 1056 1057 // Remember this PHI, even in post-inc mode. LSR SCEV-based salvaging is most 1058 // effective when we are able to use an IV inserted here, so record it. 1059 InsertedValues.insert(PN); 1060 InsertedIVs.push_back(PN); 1061 return PN; 1062 } 1063 1064 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) { 1065 Type *STy = S->getType(); 1066 Type *IntTy = SE.getEffectiveSCEVType(STy); 1067 const Loop *L = S->getLoop(); 1068 1069 // Determine a normalized form of this expression, which is the expression 1070 // before any post-inc adjustment is made. 1071 const SCEVAddRecExpr *Normalized = S; 1072 if (PostIncLoops.count(L)) { 1073 PostIncLoopSet Loops; 1074 Loops.insert(L); 1075 Normalized = cast<SCEVAddRecExpr>( 1076 normalizeForPostIncUse(S, Loops, SE, /*CheckInvertible=*/false)); 1077 } 1078 1079 // Strip off any non-loop-dominating component from the addrec start. 1080 const SCEV *Start = Normalized->getStart(); 1081 const SCEV *PostLoopOffset = nullptr; 1082 if (!SE.properlyDominates(Start, L->getHeader())) { 1083 PostLoopOffset = Start; 1084 Start = SE.getConstant(Normalized->getType(), 0); 1085 Normalized = cast<SCEVAddRecExpr>( 1086 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE), 1087 Normalized->getLoop(), 1088 Normalized->getNoWrapFlags(SCEV::FlagNW))); 1089 } 1090 1091 // Strip off any non-loop-dominating component from the addrec step. 1092 const SCEV *Step = Normalized->getStepRecurrence(SE); 1093 const SCEV *PostLoopScale = nullptr; 1094 if (!SE.dominates(Step, L->getHeader())) { 1095 PostLoopScale = Step; 1096 Step = SE.getConstant(Normalized->getType(), 1); 1097 if (!Start->isZero()) { 1098 // The normalization below assumes that Start is constant zero, so if 1099 // it isn't re-associate Start to PostLoopOffset. 1100 assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?"); 1101 PostLoopOffset = Start; 1102 Start = SE.getConstant(Normalized->getType(), 0); 1103 } 1104 Normalized = 1105 cast<SCEVAddRecExpr>(SE.getAddRecExpr( 1106 Start, Step, Normalized->getLoop(), 1107 Normalized->getNoWrapFlags(SCEV::FlagNW))); 1108 } 1109 1110 // Expand the core addrec. If we need post-loop scaling, force it to 1111 // expand to an integer type to avoid the need for additional casting. 1112 Type *ExpandTy = PostLoopScale ? IntTy : STy; 1113 // We can't use a pointer type for the addrec if the pointer type is 1114 // non-integral. 1115 Type *AddRecPHIExpandTy = 1116 DL.isNonIntegralPointerType(STy) ? Normalized->getType() : ExpandTy; 1117 1118 // In some cases, we decide to reuse an existing phi node but need to truncate 1119 // it and/or invert the step. 1120 Type *TruncTy = nullptr; 1121 bool InvertStep = false; 1122 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, AddRecPHIExpandTy, 1123 IntTy, TruncTy, InvertStep); 1124 1125 // Accommodate post-inc mode, if necessary. 1126 Value *Result; 1127 if (!PostIncLoops.count(L)) 1128 Result = PN; 1129 else { 1130 // In PostInc mode, use the post-incremented value. 1131 BasicBlock *LatchBlock = L->getLoopLatch(); 1132 assert(LatchBlock && "PostInc mode requires a unique loop latch!"); 1133 Result = PN->getIncomingValueForBlock(LatchBlock); 1134 1135 // We might be introducing a new use of the post-inc IV that is not poison 1136 // safe, in which case we should drop poison generating flags. Only keep 1137 // those flags for which SCEV has proven that they always hold. 1138 if (isa<OverflowingBinaryOperator>(Result)) { 1139 auto *I = cast<Instruction>(Result); 1140 if (!S->hasNoUnsignedWrap()) 1141 I->setHasNoUnsignedWrap(false); 1142 if (!S->hasNoSignedWrap()) 1143 I->setHasNoSignedWrap(false); 1144 } 1145 1146 // For an expansion to use the postinc form, the client must call 1147 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop 1148 // or dominated by IVIncInsertPos. 1149 if (isa<Instruction>(Result) && 1150 !SE.DT.dominates(cast<Instruction>(Result), 1151 &*Builder.GetInsertPoint())) { 1152 // The induction variable's postinc expansion does not dominate this use. 1153 // IVUsers tries to prevent this case, so it is rare. However, it can 1154 // happen when an IVUser outside the loop is not dominated by the latch 1155 // block. Adjusting IVIncInsertPos before expansion begins cannot handle 1156 // all cases. Consider a phi outside whose operand is replaced during 1157 // expansion with the value of the postinc user. Without fundamentally 1158 // changing the way postinc users are tracked, the only remedy is 1159 // inserting an extra IV increment. StepV might fold into PostLoopOffset, 1160 // but hopefully expandCodeFor handles that. 1161 bool useSubtract = 1162 !ExpandTy->isPointerTy() && Step->isNonConstantNegative(); 1163 if (useSubtract) 1164 Step = SE.getNegativeSCEV(Step); 1165 Value *StepV; 1166 { 1167 // Expand the step somewhere that dominates the loop header. 1168 SCEVInsertPointGuard Guard(Builder, this); 1169 StepV = 1170 expandCodeFor(Step, IntTy, L->getHeader()->getFirstInsertionPt()); 1171 } 1172 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract); 1173 } 1174 } 1175 1176 // We have decided to reuse an induction variable of a dominating loop. Apply 1177 // truncation and/or inversion of the step. 1178 if (TruncTy) { 1179 Type *ResTy = Result->getType(); 1180 // Normalize the result type. 1181 if (ResTy != SE.getEffectiveSCEVType(ResTy)) 1182 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy)); 1183 // Truncate the result. 1184 if (TruncTy != Result->getType()) 1185 Result = Builder.CreateTrunc(Result, TruncTy); 1186 1187 // Invert the result. 1188 if (InvertStep) 1189 Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy), 1190 Result); 1191 } 1192 1193 // Re-apply any non-loop-dominating scale. 1194 if (PostLoopScale) { 1195 assert(S->isAffine() && "Can't linearly scale non-affine recurrences."); 1196 Result = InsertNoopCastOfTo(Result, IntTy); 1197 Result = Builder.CreateMul(Result, expandCodeFor(PostLoopScale, IntTy)); 1198 } 1199 1200 // Re-apply any non-loop-dominating offset. 1201 if (PostLoopOffset) { 1202 if (isa<PointerType>(ExpandTy)) { 1203 if (Result->getType()->isIntegerTy()) { 1204 Value *Base = expandCodeFor(PostLoopOffset, ExpandTy); 1205 Result = expandAddToGEP(SE.getUnknown(Result), IntTy, Base); 1206 } else { 1207 Result = expandAddToGEP(PostLoopOffset, IntTy, Result); 1208 } 1209 } else { 1210 Result = InsertNoopCastOfTo(Result, IntTy); 1211 Result = Builder.CreateAdd(Result, expandCodeFor(PostLoopOffset, IntTy)); 1212 } 1213 } 1214 1215 return Result; 1216 } 1217 1218 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) { 1219 // In canonical mode we compute the addrec as an expression of a canonical IV 1220 // using evaluateAtIteration and expand the resulting SCEV expression. This 1221 // way we avoid introducing new IVs to carry on the computation of the addrec 1222 // throughout the loop. 1223 // 1224 // For nested addrecs evaluateAtIteration might need a canonical IV of a 1225 // type wider than the addrec itself. Emitting a canonical IV of the 1226 // proper type might produce non-legal types, for example expanding an i64 1227 // {0,+,2,+,1} addrec would need an i65 canonical IV. To avoid this just fall 1228 // back to non-canonical mode for nested addrecs. 1229 if (!CanonicalMode || (S->getNumOperands() > 2)) 1230 return expandAddRecExprLiterally(S); 1231 1232 Type *Ty = SE.getEffectiveSCEVType(S->getType()); 1233 const Loop *L = S->getLoop(); 1234 1235 // First check for an existing canonical IV in a suitable type. 1236 PHINode *CanonicalIV = nullptr; 1237 if (PHINode *PN = L->getCanonicalInductionVariable()) 1238 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty)) 1239 CanonicalIV = PN; 1240 1241 // Rewrite an AddRec in terms of the canonical induction variable, if 1242 // its type is more narrow. 1243 if (CanonicalIV && 1244 SE.getTypeSizeInBits(CanonicalIV->getType()) > SE.getTypeSizeInBits(Ty) && 1245 !S->getType()->isPointerTy()) { 1246 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands()); 1247 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i) 1248 NewOps[i] = SE.getAnyExtendExpr(S->getOperand(i), CanonicalIV->getType()); 1249 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(), 1250 S->getNoWrapFlags(SCEV::FlagNW))); 1251 BasicBlock::iterator NewInsertPt = 1252 findInsertPointAfter(cast<Instruction>(V), &*Builder.GetInsertPoint()); 1253 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr, 1254 NewInsertPt); 1255 return V; 1256 } 1257 1258 // {X,+,F} --> X + {0,+,F} 1259 if (!S->getStart()->isZero()) { 1260 if (isa<PointerType>(S->getType())) { 1261 Value *StartV = expand(SE.getPointerBase(S)); 1262 return expandAddToGEP(SE.removePointerBase(S), Ty, StartV); 1263 } 1264 1265 SmallVector<const SCEV *, 4> NewOps(S->operands()); 1266 NewOps[0] = SE.getConstant(Ty, 0); 1267 const SCEV *Rest = SE.getAddRecExpr(NewOps, L, 1268 S->getNoWrapFlags(SCEV::FlagNW)); 1269 1270 // Just do a normal add. Pre-expand the operands to suppress folding. 1271 // 1272 // The LHS and RHS values are factored out of the expand call to make the 1273 // output independent of the argument evaluation order. 1274 const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart())); 1275 const SCEV *AddExprRHS = SE.getUnknown(expand(Rest)); 1276 return expand(SE.getAddExpr(AddExprLHS, AddExprRHS)); 1277 } 1278 1279 // If we don't yet have a canonical IV, create one. 1280 if (!CanonicalIV) { 1281 // Create and insert the PHI node for the induction variable in the 1282 // specified loop. 1283 BasicBlock *Header = L->getHeader(); 1284 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header); 1285 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar"); 1286 CanonicalIV->insertBefore(Header->begin()); 1287 rememberInstruction(CanonicalIV); 1288 1289 SmallSet<BasicBlock *, 4> PredSeen; 1290 Constant *One = ConstantInt::get(Ty, 1); 1291 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) { 1292 BasicBlock *HP = *HPI; 1293 if (!PredSeen.insert(HP).second) { 1294 // There must be an incoming value for each predecessor, even the 1295 // duplicates! 1296 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP); 1297 continue; 1298 } 1299 1300 if (L->contains(HP)) { 1301 // Insert a unit add instruction right before the terminator 1302 // corresponding to the back-edge. 1303 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One, 1304 "indvar.next", 1305 HP->getTerminator()); 1306 Add->setDebugLoc(HP->getTerminator()->getDebugLoc()); 1307 rememberInstruction(Add); 1308 CanonicalIV->addIncoming(Add, HP); 1309 } else { 1310 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP); 1311 } 1312 } 1313 } 1314 1315 // {0,+,1} --> Insert a canonical induction variable into the loop! 1316 if (S->isAffine() && S->getOperand(1)->isOne()) { 1317 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) && 1318 "IVs with types different from the canonical IV should " 1319 "already have been handled!"); 1320 return CanonicalIV; 1321 } 1322 1323 // {0,+,F} --> {0,+,1} * F 1324 1325 // If this is a simple linear addrec, emit it now as a special case. 1326 if (S->isAffine()) // {0,+,F} --> i*F 1327 return 1328 expand(SE.getTruncateOrNoop( 1329 SE.getMulExpr(SE.getUnknown(CanonicalIV), 1330 SE.getNoopOrAnyExtend(S->getOperand(1), 1331 CanonicalIV->getType())), 1332 Ty)); 1333 1334 // If this is a chain of recurrences, turn it into a closed form, using the 1335 // folders, then expandCodeFor the closed form. This allows the folders to 1336 // simplify the expression without having to build a bunch of special code 1337 // into this folder. 1338 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV. 1339 1340 // Promote S up to the canonical IV type, if the cast is foldable. 1341 const SCEV *NewS = S; 1342 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType()); 1343 if (isa<SCEVAddRecExpr>(Ext)) 1344 NewS = Ext; 1345 1346 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE); 1347 1348 // Truncate the result down to the original type, if needed. 1349 const SCEV *T = SE.getTruncateOrNoop(V, Ty); 1350 return expand(T); 1351 } 1352 1353 Value *SCEVExpander::visitPtrToIntExpr(const SCEVPtrToIntExpr *S) { 1354 Value *V = expand(S->getOperand()); 1355 return ReuseOrCreateCast(V, S->getType(), CastInst::PtrToInt, 1356 GetOptimalInsertionPointForCastOf(V)); 1357 } 1358 1359 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) { 1360 Value *V = expand(S->getOperand()); 1361 return Builder.CreateTrunc(V, S->getType()); 1362 } 1363 1364 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) { 1365 Value *V = expand(S->getOperand()); 1366 return Builder.CreateZExt(V, S->getType()); 1367 } 1368 1369 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) { 1370 Value *V = expand(S->getOperand()); 1371 return Builder.CreateSExt(V, S->getType()); 1372 } 1373 1374 Value *SCEVExpander::expandMinMaxExpr(const SCEVNAryExpr *S, 1375 Intrinsic::ID IntrinID, Twine Name, 1376 bool IsSequential) { 1377 Value *LHS = expand(S->getOperand(S->getNumOperands() - 1)); 1378 Type *Ty = LHS->getType(); 1379 if (IsSequential) 1380 LHS = Builder.CreateFreeze(LHS); 1381 for (int i = S->getNumOperands() - 2; i >= 0; --i) { 1382 Value *RHS = expandCodeFor(S->getOperand(i), Ty); 1383 if (IsSequential && i != 0) 1384 RHS = Builder.CreateFreeze(RHS); 1385 Value *Sel; 1386 if (Ty->isIntegerTy()) 1387 Sel = Builder.CreateIntrinsic(IntrinID, {Ty}, {LHS, RHS}, 1388 /*FMFSource=*/nullptr, Name); 1389 else { 1390 Value *ICmp = 1391 Builder.CreateICmp(MinMaxIntrinsic::getPredicate(IntrinID), LHS, RHS); 1392 Sel = Builder.CreateSelect(ICmp, LHS, RHS, Name); 1393 } 1394 LHS = Sel; 1395 } 1396 return LHS; 1397 } 1398 1399 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) { 1400 return expandMinMaxExpr(S, Intrinsic::smax, "smax"); 1401 } 1402 1403 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) { 1404 return expandMinMaxExpr(S, Intrinsic::umax, "umax"); 1405 } 1406 1407 Value *SCEVExpander::visitSMinExpr(const SCEVSMinExpr *S) { 1408 return expandMinMaxExpr(S, Intrinsic::smin, "smin"); 1409 } 1410 1411 Value *SCEVExpander::visitUMinExpr(const SCEVUMinExpr *S) { 1412 return expandMinMaxExpr(S, Intrinsic::umin, "umin"); 1413 } 1414 1415 Value *SCEVExpander::visitSequentialUMinExpr(const SCEVSequentialUMinExpr *S) { 1416 return expandMinMaxExpr(S, Intrinsic::umin, "umin", /*IsSequential*/true); 1417 } 1418 1419 Value *SCEVExpander::visitVScale(const SCEVVScale *S) { 1420 return Builder.CreateVScale(ConstantInt::get(S->getType(), 1)); 1421 } 1422 1423 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty, 1424 BasicBlock::iterator IP) { 1425 setInsertPoint(IP); 1426 Value *V = expandCodeFor(SH, Ty); 1427 return V; 1428 } 1429 1430 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) { 1431 // Expand the code for this SCEV. 1432 Value *V = expand(SH); 1433 1434 if (Ty) { 1435 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) && 1436 "non-trivial casts should be done with the SCEVs directly!"); 1437 V = InsertNoopCastOfTo(V, Ty); 1438 } 1439 return V; 1440 } 1441 1442 static bool 1443 canReuseInstruction(ScalarEvolution &SE, const SCEV *S, Instruction *I, 1444 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) { 1445 // If the instruction cannot be poison, it's always safe to reuse. 1446 if (programUndefinedIfPoison(I)) 1447 return true; 1448 1449 // Otherwise, it is possible that I is more poisonous that S. Collect the 1450 // poison-contributors of S, and then check whether I has any additional 1451 // poison-contributors. Poison that is contributed through poison-generating 1452 // flags is handled by dropping those flags instead. 1453 SmallPtrSet<const Value *, 8> PoisonVals; 1454 SE.getPoisonGeneratingValues(PoisonVals, S); 1455 1456 SmallVector<Value *> Worklist; 1457 SmallPtrSet<Value *, 8> Visited; 1458 Worklist.push_back(I); 1459 while (!Worklist.empty()) { 1460 Value *V = Worklist.pop_back_val(); 1461 if (!Visited.insert(V).second) 1462 continue; 1463 1464 // Avoid walking large instruction graphs. 1465 if (Visited.size() > 16) 1466 return false; 1467 1468 // Either the value can't be poison, or the S would also be poison if it 1469 // is. 1470 if (PoisonVals.contains(V) || isGuaranteedNotToBePoison(V)) 1471 continue; 1472 1473 auto *I = dyn_cast<Instruction>(V); 1474 if (!I) 1475 return false; 1476 1477 // FIXME: Ignore vscale, even though it technically could be poison. Do this 1478 // because SCEV currently assumes it can't be poison. Remove this special 1479 // case once we proper model when vscale can be poison. 1480 if (auto *II = dyn_cast<IntrinsicInst>(I); 1481 II && II->getIntrinsicID() == Intrinsic::vscale) 1482 continue; 1483 1484 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false)) 1485 return false; 1486 1487 // If the instruction can't create poison, we can recurse to its operands. 1488 if (I->hasPoisonGeneratingFlagsOrMetadata()) 1489 DropPoisonGeneratingInsts.push_back(I); 1490 1491 for (Value *Op : I->operands()) 1492 Worklist.push_back(Op); 1493 } 1494 return true; 1495 } 1496 1497 Value *SCEVExpander::FindValueInExprValueMap( 1498 const SCEV *S, const Instruction *InsertPt, 1499 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) { 1500 // If the expansion is not in CanonicalMode, and the SCEV contains any 1501 // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally. 1502 if (!CanonicalMode && SE.containsAddRecurrence(S)) 1503 return nullptr; 1504 1505 // If S is a constant, it may be worse to reuse an existing Value. 1506 if (isa<SCEVConstant>(S)) 1507 return nullptr; 1508 1509 for (Value *V : SE.getSCEVValues(S)) { 1510 Instruction *EntInst = dyn_cast<Instruction>(V); 1511 if (!EntInst) 1512 continue; 1513 1514 // Choose a Value from the set which dominates the InsertPt. 1515 // InsertPt should be inside the Value's parent loop so as not to break 1516 // the LCSSA form. 1517 assert(EntInst->getFunction() == InsertPt->getFunction()); 1518 if (S->getType() != V->getType() || !SE.DT.dominates(EntInst, InsertPt) || 1519 !(SE.LI.getLoopFor(EntInst->getParent()) == nullptr || 1520 SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt))) 1521 continue; 1522 1523 // Make sure reusing the instruction is poison-safe. 1524 if (canReuseInstruction(SE, S, EntInst, DropPoisonGeneratingInsts)) 1525 return V; 1526 DropPoisonGeneratingInsts.clear(); 1527 } 1528 return nullptr; 1529 } 1530 1531 // The expansion of SCEV will either reuse a previous Value in ExprValueMap, 1532 // or expand the SCEV literally. Specifically, if the expansion is in LSRMode, 1533 // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded 1534 // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise, 1535 // the expansion will try to reuse Value from ExprValueMap, and only when it 1536 // fails, expand the SCEV literally. 1537 Value *SCEVExpander::expand(const SCEV *S) { 1538 // Compute an insertion point for this SCEV object. Hoist the instructions 1539 // as far out in the loop nest as possible. 1540 BasicBlock::iterator InsertPt = Builder.GetInsertPoint(); 1541 1542 // We can move insertion point only if there is no div or rem operations 1543 // otherwise we are risky to move it over the check for zero denominator. 1544 auto SafeToHoist = [](const SCEV *S) { 1545 return !SCEVExprContains(S, [](const SCEV *S) { 1546 if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) { 1547 if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS())) 1548 // Division by non-zero constants can be hoisted. 1549 return SC->getValue()->isZero(); 1550 // All other divisions should not be moved as they may be 1551 // divisions by zero and should be kept within the 1552 // conditions of the surrounding loops that guard their 1553 // execution (see PR35406). 1554 return true; 1555 } 1556 return false; 1557 }); 1558 }; 1559 if (SafeToHoist(S)) { 1560 for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());; 1561 L = L->getParentLoop()) { 1562 if (SE.isLoopInvariant(S, L)) { 1563 if (!L) break; 1564 if (BasicBlock *Preheader = L->getLoopPreheader()) { 1565 InsertPt = Preheader->getTerminator()->getIterator(); 1566 } else { 1567 // LSR sets the insertion point for AddRec start/step values to the 1568 // block start to simplify value reuse, even though it's an invalid 1569 // position. SCEVExpander must correct for this in all cases. 1570 InsertPt = L->getHeader()->getFirstInsertionPt(); 1571 } 1572 } else { 1573 // If the SCEV is computable at this level, insert it into the header 1574 // after the PHIs (and after any other instructions that we've inserted 1575 // there) so that it is guaranteed to dominate any user inside the loop. 1576 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L)) 1577 InsertPt = L->getHeader()->getFirstInsertionPt(); 1578 1579 while (InsertPt != Builder.GetInsertPoint() && 1580 (isInsertedInstruction(&*InsertPt) || 1581 isa<DbgInfoIntrinsic>(&*InsertPt))) { 1582 InsertPt = std::next(InsertPt); 1583 } 1584 break; 1585 } 1586 } 1587 } 1588 1589 // Check to see if we already expanded this here. 1590 auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt)); 1591 if (I != InsertedExpressions.end()) 1592 return I->second; 1593 1594 SCEVInsertPointGuard Guard(Builder, this); 1595 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt); 1596 1597 // Expand the expression into instructions. 1598 SmallVector<Instruction *> DropPoisonGeneratingInsts; 1599 Value *V = FindValueInExprValueMap(S, &*InsertPt, DropPoisonGeneratingInsts); 1600 if (!V) { 1601 V = visit(S); 1602 V = fixupLCSSAFormFor(V); 1603 } else { 1604 for (Instruction *I : DropPoisonGeneratingInsts) 1605 I->dropPoisonGeneratingFlagsAndMetadata(); 1606 } 1607 // Remember the expanded value for this SCEV at this location. 1608 // 1609 // This is independent of PostIncLoops. The mapped value simply materializes 1610 // the expression at this insertion point. If the mapped value happened to be 1611 // a postinc expansion, it could be reused by a non-postinc user, but only if 1612 // its insertion point was already at the head of the loop. 1613 InsertedExpressions[std::make_pair(S, &*InsertPt)] = V; 1614 return V; 1615 } 1616 1617 void SCEVExpander::rememberInstruction(Value *I) { 1618 auto DoInsert = [this](Value *V) { 1619 if (!PostIncLoops.empty()) 1620 InsertedPostIncValues.insert(V); 1621 else 1622 InsertedValues.insert(V); 1623 }; 1624 DoInsert(I); 1625 } 1626 1627 /// replaceCongruentIVs - Check for congruent phis in this loop header and 1628 /// replace them with their most canonical representative. Return the number of 1629 /// phis eliminated. 1630 /// 1631 /// This does not depend on any SCEVExpander state but should be used in 1632 /// the same context that SCEVExpander is used. 1633 unsigned 1634 SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT, 1635 SmallVectorImpl<WeakTrackingVH> &DeadInsts, 1636 const TargetTransformInfo *TTI) { 1637 // Find integer phis in order of increasing width. 1638 SmallVector<PHINode*, 8> Phis; 1639 for (PHINode &PN : L->getHeader()->phis()) 1640 Phis.push_back(&PN); 1641 1642 if (TTI) 1643 // Use stable_sort to preserve order of equivalent PHIs, so the order 1644 // of the sorted Phis is the same from run to run on the same loop. 1645 llvm::stable_sort(Phis, [](Value *LHS, Value *RHS) { 1646 // Put pointers at the back and make sure pointer < pointer = false. 1647 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy()) 1648 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy(); 1649 return RHS->getType()->getPrimitiveSizeInBits().getFixedValue() < 1650 LHS->getType()->getPrimitiveSizeInBits().getFixedValue(); 1651 }); 1652 1653 unsigned NumElim = 0; 1654 DenseMap<const SCEV *, PHINode *> ExprToIVMap; 1655 // Process phis from wide to narrow. Map wide phis to their truncation 1656 // so narrow phis can reuse them. 1657 for (PHINode *Phi : Phis) { 1658 auto SimplifyPHINode = [&](PHINode *PN) -> Value * { 1659 if (Value *V = simplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC})) 1660 return V; 1661 if (!SE.isSCEVable(PN->getType())) 1662 return nullptr; 1663 auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN)); 1664 if (!Const) 1665 return nullptr; 1666 return Const->getValue(); 1667 }; 1668 1669 // Fold constant phis. They may be congruent to other constant phis and 1670 // would confuse the logic below that expects proper IVs. 1671 if (Value *V = SimplifyPHINode(Phi)) { 1672 if (V->getType() != Phi->getType()) 1673 continue; 1674 SE.forgetValue(Phi); 1675 Phi->replaceAllUsesWith(V); 1676 DeadInsts.emplace_back(Phi); 1677 ++NumElim; 1678 SCEV_DEBUG_WITH_TYPE(DebugType, 1679 dbgs() << "INDVARS: Eliminated constant iv: " << *Phi 1680 << '\n'); 1681 continue; 1682 } 1683 1684 if (!SE.isSCEVable(Phi->getType())) 1685 continue; 1686 1687 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)]; 1688 if (!OrigPhiRef) { 1689 OrigPhiRef = Phi; 1690 if (Phi->getType()->isIntegerTy() && TTI && 1691 TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) { 1692 // Make sure we only rewrite using simple induction variables; 1693 // otherwise, we can make the trip count of a loop unanalyzable 1694 // to SCEV. 1695 const SCEV *PhiExpr = SE.getSCEV(Phi); 1696 if (isa<SCEVAddRecExpr>(PhiExpr)) { 1697 // This phi can be freely truncated to the narrowest phi type. Map the 1698 // truncated expression to it so it will be reused for narrow types. 1699 const SCEV *TruncExpr = 1700 SE.getTruncateExpr(PhiExpr, Phis.back()->getType()); 1701 ExprToIVMap[TruncExpr] = Phi; 1702 } 1703 } 1704 continue; 1705 } 1706 1707 // Replacing a pointer phi with an integer phi or vice-versa doesn't make 1708 // sense. 1709 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy()) 1710 continue; 1711 1712 if (BasicBlock *LatchBlock = L->getLoopLatch()) { 1713 Instruction *OrigInc = dyn_cast<Instruction>( 1714 OrigPhiRef->getIncomingValueForBlock(LatchBlock)); 1715 Instruction *IsomorphicInc = 1716 dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock)); 1717 1718 if (OrigInc && IsomorphicInc) { 1719 // If this phi has the same width but is more canonical, replace the 1720 // original with it. As part of the "more canonical" determination, 1721 // respect a prior decision to use an IV chain. 1722 if (OrigPhiRef->getType() == Phi->getType() && 1723 !(ChainedPhis.count(Phi) || 1724 isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) && 1725 (ChainedPhis.count(Phi) || 1726 isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) { 1727 std::swap(OrigPhiRef, Phi); 1728 std::swap(OrigInc, IsomorphicInc); 1729 } 1730 // Replacing the congruent phi is sufficient because acyclic 1731 // redundancy elimination, CSE/GVN, should handle the 1732 // rest. However, once SCEV proves that a phi is congruent, 1733 // it's often the head of an IV user cycle that is isomorphic 1734 // with the original phi. It's worth eagerly cleaning up the 1735 // common case of a single IV increment so that DeleteDeadPHIs 1736 // can remove cycles that had postinc uses. 1737 // Because we may potentially introduce a new use of OrigIV that didn't 1738 // exist before at this point, its poison flags need readjustment. 1739 const SCEV *TruncExpr = 1740 SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType()); 1741 if (OrigInc != IsomorphicInc && 1742 TruncExpr == SE.getSCEV(IsomorphicInc) && 1743 SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) && 1744 hoistIVInc(OrigInc, IsomorphicInc, /*RecomputePoisonFlags*/ true)) { 1745 SCEV_DEBUG_WITH_TYPE( 1746 DebugType, dbgs() << "INDVARS: Eliminated congruent iv.inc: " 1747 << *IsomorphicInc << '\n'); 1748 Value *NewInc = OrigInc; 1749 if (OrigInc->getType() != IsomorphicInc->getType()) { 1750 BasicBlock::iterator IP; 1751 if (PHINode *PN = dyn_cast<PHINode>(OrigInc)) 1752 IP = PN->getParent()->getFirstInsertionPt(); 1753 else 1754 IP = OrigInc->getNextNonDebugInstruction()->getIterator(); 1755 1756 IRBuilder<> Builder(IP->getParent(), IP); 1757 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc()); 1758 NewInc = Builder.CreateTruncOrBitCast( 1759 OrigInc, IsomorphicInc->getType(), IVName); 1760 } 1761 IsomorphicInc->replaceAllUsesWith(NewInc); 1762 DeadInsts.emplace_back(IsomorphicInc); 1763 } 1764 } 1765 } 1766 SCEV_DEBUG_WITH_TYPE(DebugType, 1767 dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi 1768 << '\n'); 1769 SCEV_DEBUG_WITH_TYPE( 1770 DebugType, dbgs() << "INDVARS: Original iv: " << *OrigPhiRef << '\n'); 1771 ++NumElim; 1772 Value *NewIV = OrigPhiRef; 1773 if (OrigPhiRef->getType() != Phi->getType()) { 1774 IRBuilder<> Builder(L->getHeader(), 1775 L->getHeader()->getFirstInsertionPt()); 1776 Builder.SetCurrentDebugLocation(Phi->getDebugLoc()); 1777 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName); 1778 } 1779 Phi->replaceAllUsesWith(NewIV); 1780 DeadInsts.emplace_back(Phi); 1781 } 1782 return NumElim; 1783 } 1784 1785 bool SCEVExpander::hasRelatedExistingExpansion(const SCEV *S, 1786 const Instruction *At, 1787 Loop *L) { 1788 using namespace llvm::PatternMatch; 1789 1790 SmallVector<BasicBlock *, 4> ExitingBlocks; 1791 L->getExitingBlocks(ExitingBlocks); 1792 1793 // Look for suitable value in simple conditions at the loop exits. 1794 for (BasicBlock *BB : ExitingBlocks) { 1795 ICmpInst::Predicate Pred; 1796 Instruction *LHS, *RHS; 1797 1798 if (!match(BB->getTerminator(), 1799 m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)), 1800 m_BasicBlock(), m_BasicBlock()))) 1801 continue; 1802 1803 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At)) 1804 return true; 1805 1806 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At)) 1807 return true; 1808 } 1809 1810 // Use expand's logic which is used for reusing a previous Value in 1811 // ExprValueMap. Note that we don't currently model the cost of 1812 // needing to drop poison generating flags on the instruction if we 1813 // want to reuse it. We effectively assume that has zero cost. 1814 SmallVector<Instruction *> DropPoisonGeneratingInsts; 1815 return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) != nullptr; 1816 } 1817 1818 template<typename T> static InstructionCost costAndCollectOperands( 1819 const SCEVOperand &WorkItem, const TargetTransformInfo &TTI, 1820 TargetTransformInfo::TargetCostKind CostKind, 1821 SmallVectorImpl<SCEVOperand> &Worklist) { 1822 1823 const T *S = cast<T>(WorkItem.S); 1824 InstructionCost Cost = 0; 1825 // Object to help map SCEV operands to expanded IR instructions. 1826 struct OperationIndices { 1827 OperationIndices(unsigned Opc, size_t min, size_t max) : 1828 Opcode(Opc), MinIdx(min), MaxIdx(max) { } 1829 unsigned Opcode; 1830 size_t MinIdx; 1831 size_t MaxIdx; 1832 }; 1833 1834 // Collect the operations of all the instructions that will be needed to 1835 // expand the SCEVExpr. This is so that when we come to cost the operands, 1836 // we know what the generated user(s) will be. 1837 SmallVector<OperationIndices, 2> Operations; 1838 1839 auto CastCost = [&](unsigned Opcode) -> InstructionCost { 1840 Operations.emplace_back(Opcode, 0, 0); 1841 return TTI.getCastInstrCost(Opcode, S->getType(), 1842 S->getOperand(0)->getType(), 1843 TTI::CastContextHint::None, CostKind); 1844 }; 1845 1846 auto ArithCost = [&](unsigned Opcode, unsigned NumRequired, 1847 unsigned MinIdx = 0, 1848 unsigned MaxIdx = 1) -> InstructionCost { 1849 Operations.emplace_back(Opcode, MinIdx, MaxIdx); 1850 return NumRequired * 1851 TTI.getArithmeticInstrCost(Opcode, S->getType(), CostKind); 1852 }; 1853 1854 auto CmpSelCost = [&](unsigned Opcode, unsigned NumRequired, unsigned MinIdx, 1855 unsigned MaxIdx) -> InstructionCost { 1856 Operations.emplace_back(Opcode, MinIdx, MaxIdx); 1857 Type *OpType = S->getType(); 1858 return NumRequired * TTI.getCmpSelInstrCost( 1859 Opcode, OpType, CmpInst::makeCmpResultType(OpType), 1860 CmpInst::BAD_ICMP_PREDICATE, CostKind); 1861 }; 1862 1863 switch (S->getSCEVType()) { 1864 case scCouldNotCompute: 1865 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 1866 case scUnknown: 1867 case scConstant: 1868 case scVScale: 1869 return 0; 1870 case scPtrToInt: 1871 Cost = CastCost(Instruction::PtrToInt); 1872 break; 1873 case scTruncate: 1874 Cost = CastCost(Instruction::Trunc); 1875 break; 1876 case scZeroExtend: 1877 Cost = CastCost(Instruction::ZExt); 1878 break; 1879 case scSignExtend: 1880 Cost = CastCost(Instruction::SExt); 1881 break; 1882 case scUDivExpr: { 1883 unsigned Opcode = Instruction::UDiv; 1884 if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1))) 1885 if (SC->getAPInt().isPowerOf2()) 1886 Opcode = Instruction::LShr; 1887 Cost = ArithCost(Opcode, 1); 1888 break; 1889 } 1890 case scAddExpr: 1891 Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1); 1892 break; 1893 case scMulExpr: 1894 // TODO: this is a very pessimistic cost modelling for Mul, 1895 // because of Bin Pow algorithm actually used by the expander, 1896 // see SCEVExpander::visitMulExpr(), ExpandOpBinPowN(). 1897 Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1); 1898 break; 1899 case scSMaxExpr: 1900 case scUMaxExpr: 1901 case scSMinExpr: 1902 case scUMinExpr: 1903 case scSequentialUMinExpr: { 1904 // FIXME: should this ask the cost for Intrinsic's? 1905 // The reduction tree. 1906 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1); 1907 Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2); 1908 switch (S->getSCEVType()) { 1909 case scSequentialUMinExpr: { 1910 // The safety net against poison. 1911 // FIXME: this is broken. 1912 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0); 1913 Cost += ArithCost(Instruction::Or, 1914 S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0); 1915 Cost += CmpSelCost(Instruction::Select, 1, 0, 1); 1916 break; 1917 } 1918 default: 1919 assert(!isa<SCEVSequentialMinMaxExpr>(S) && 1920 "Unhandled SCEV expression type?"); 1921 break; 1922 } 1923 break; 1924 } 1925 case scAddRecExpr: { 1926 // In this polynominal, we may have some zero operands, and we shouldn't 1927 // really charge for those. So how many non-zero coefficients are there? 1928 int NumTerms = llvm::count_if(S->operands(), [](const SCEV *Op) { 1929 return !Op->isZero(); 1930 }); 1931 1932 assert(NumTerms >= 1 && "Polynominal should have at least one term."); 1933 assert(!(*std::prev(S->operands().end()))->isZero() && 1934 "Last operand should not be zero"); 1935 1936 // Ignoring constant term (operand 0), how many of the coefficients are u> 1? 1937 int NumNonZeroDegreeNonOneTerms = 1938 llvm::count_if(S->operands(), [](const SCEV *Op) { 1939 auto *SConst = dyn_cast<SCEVConstant>(Op); 1940 return !SConst || SConst->getAPInt().ugt(1); 1941 }); 1942 1943 // Much like with normal add expr, the polynominal will require 1944 // one less addition than the number of it's terms. 1945 InstructionCost AddCost = ArithCost(Instruction::Add, NumTerms - 1, 1946 /*MinIdx*/ 1, /*MaxIdx*/ 1); 1947 // Here, *each* one of those will require a multiplication. 1948 InstructionCost MulCost = 1949 ArithCost(Instruction::Mul, NumNonZeroDegreeNonOneTerms); 1950 Cost = AddCost + MulCost; 1951 1952 // What is the degree of this polynominal? 1953 int PolyDegree = S->getNumOperands() - 1; 1954 assert(PolyDegree >= 1 && "Should be at least affine."); 1955 1956 // The final term will be: 1957 // Op_{PolyDegree} * x ^ {PolyDegree} 1958 // Where x ^ {PolyDegree} will again require PolyDegree-1 mul operations. 1959 // Note that x ^ {PolyDegree} = x * x ^ {PolyDegree-1} so charging for 1960 // x ^ {PolyDegree} will give us x ^ {2} .. x ^ {PolyDegree-1} for free. 1961 // FIXME: this is conservatively correct, but might be overly pessimistic. 1962 Cost += MulCost * (PolyDegree - 1); 1963 break; 1964 } 1965 } 1966 1967 for (auto &CostOp : Operations) { 1968 for (auto SCEVOp : enumerate(S->operands())) { 1969 // Clamp the index to account for multiple IR operations being chained. 1970 size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx); 1971 size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx); 1972 Worklist.emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value()); 1973 } 1974 } 1975 return Cost; 1976 } 1977 1978 bool SCEVExpander::isHighCostExpansionHelper( 1979 const SCEVOperand &WorkItem, Loop *L, const Instruction &At, 1980 InstructionCost &Cost, unsigned Budget, const TargetTransformInfo &TTI, 1981 SmallPtrSetImpl<const SCEV *> &Processed, 1982 SmallVectorImpl<SCEVOperand> &Worklist) { 1983 if (Cost > Budget) 1984 return true; // Already run out of budget, give up. 1985 1986 const SCEV *S = WorkItem.S; 1987 // Was the cost of expansion of this expression already accounted for? 1988 if (!isa<SCEVConstant>(S) && !Processed.insert(S).second) 1989 return false; // We have already accounted for this expression. 1990 1991 // If we can find an existing value for this scev available at the point "At" 1992 // then consider the expression cheap. 1993 if (hasRelatedExistingExpansion(S, &At, L)) 1994 return false; // Consider the expression to be free. 1995 1996 TargetTransformInfo::TargetCostKind CostKind = 1997 L->getHeader()->getParent()->hasMinSize() 1998 ? TargetTransformInfo::TCK_CodeSize 1999 : TargetTransformInfo::TCK_RecipThroughput; 2000 2001 switch (S->getSCEVType()) { 2002 case scCouldNotCompute: 2003 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 2004 case scUnknown: 2005 case scVScale: 2006 // Assume to be zero-cost. 2007 return false; 2008 case scConstant: { 2009 // Only evalulate the costs of constants when optimizing for size. 2010 if (CostKind != TargetTransformInfo::TCK_CodeSize) 2011 return false; 2012 const APInt &Imm = cast<SCEVConstant>(S)->getAPInt(); 2013 Type *Ty = S->getType(); 2014 Cost += TTI.getIntImmCostInst( 2015 WorkItem.ParentOpcode, WorkItem.OperandIdx, Imm, Ty, CostKind); 2016 return Cost > Budget; 2017 } 2018 case scTruncate: 2019 case scPtrToInt: 2020 case scZeroExtend: 2021 case scSignExtend: { 2022 Cost += 2023 costAndCollectOperands<SCEVCastExpr>(WorkItem, TTI, CostKind, Worklist); 2024 return false; // Will answer upon next entry into this function. 2025 } 2026 case scUDivExpr: { 2027 // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or 2028 // HowManyLessThans produced to compute a precise expression, rather than a 2029 // UDiv from the user's code. If we can't find a UDiv in the code with some 2030 // simple searching, we need to account for it's cost. 2031 2032 // At the beginning of this function we already tried to find existing 2033 // value for plain 'S'. Now try to lookup 'S + 1' since it is common 2034 // pattern involving division. This is just a simple search heuristic. 2035 if (hasRelatedExistingExpansion( 2036 SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), &At, L)) 2037 return false; // Consider it to be free. 2038 2039 Cost += 2040 costAndCollectOperands<SCEVUDivExpr>(WorkItem, TTI, CostKind, Worklist); 2041 return false; // Will answer upon next entry into this function. 2042 } 2043 case scAddExpr: 2044 case scMulExpr: 2045 case scUMaxExpr: 2046 case scSMaxExpr: 2047 case scUMinExpr: 2048 case scSMinExpr: 2049 case scSequentialUMinExpr: { 2050 assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 && 2051 "Nary expr should have more than 1 operand."); 2052 // The simple nary expr will require one less op (or pair of ops) 2053 // than the number of it's terms. 2054 Cost += 2055 costAndCollectOperands<SCEVNAryExpr>(WorkItem, TTI, CostKind, Worklist); 2056 return Cost > Budget; 2057 } 2058 case scAddRecExpr: { 2059 assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 && 2060 "Polynomial should be at least linear"); 2061 Cost += costAndCollectOperands<SCEVAddRecExpr>( 2062 WorkItem, TTI, CostKind, Worklist); 2063 return Cost > Budget; 2064 } 2065 } 2066 llvm_unreachable("Unknown SCEV kind!"); 2067 } 2068 2069 Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred, 2070 Instruction *IP) { 2071 assert(IP); 2072 switch (Pred->getKind()) { 2073 case SCEVPredicate::P_Union: 2074 return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP); 2075 case SCEVPredicate::P_Compare: 2076 return expandComparePredicate(cast<SCEVComparePredicate>(Pred), IP); 2077 case SCEVPredicate::P_Wrap: { 2078 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred); 2079 return expandWrapPredicate(AddRecPred, IP); 2080 } 2081 } 2082 llvm_unreachable("Unknown SCEV predicate type"); 2083 } 2084 2085 Value *SCEVExpander::expandComparePredicate(const SCEVComparePredicate *Pred, 2086 Instruction *IP) { 2087 Value *Expr0 = expandCodeFor(Pred->getLHS(), Pred->getLHS()->getType(), IP); 2088 Value *Expr1 = expandCodeFor(Pred->getRHS(), Pred->getRHS()->getType(), IP); 2089 2090 Builder.SetInsertPoint(IP); 2091 auto InvPred = ICmpInst::getInversePredicate(Pred->getPredicate()); 2092 auto *I = Builder.CreateICmp(InvPred, Expr0, Expr1, "ident.check"); 2093 return I; 2094 } 2095 2096 Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR, 2097 Instruction *Loc, bool Signed) { 2098 assert(AR->isAffine() && "Cannot generate RT check for " 2099 "non-affine expression"); 2100 2101 // FIXME: It is highly suspicious that we're ignoring the predicates here. 2102 SmallVector<const SCEVPredicate *, 4> Pred; 2103 const SCEV *ExitCount = 2104 SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred); 2105 2106 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Invalid loop count"); 2107 2108 const SCEV *Step = AR->getStepRecurrence(SE); 2109 const SCEV *Start = AR->getStart(); 2110 2111 Type *ARTy = AR->getType(); 2112 unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType()); 2113 unsigned DstBits = SE.getTypeSizeInBits(ARTy); 2114 2115 // The expression {Start,+,Step} has nusw/nssw if 2116 // Step < 0, Start - |Step| * Backedge <= Start 2117 // Step >= 0, Start + |Step| * Backedge > Start 2118 // and |Step| * Backedge doesn't unsigned overflow. 2119 2120 IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits); 2121 Builder.SetInsertPoint(Loc); 2122 Value *TripCountVal = expandCodeFor(ExitCount, CountTy, Loc); 2123 2124 IntegerType *Ty = 2125 IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy)); 2126 2127 Value *StepValue = expandCodeFor(Step, Ty, Loc); 2128 Value *NegStepValue = expandCodeFor(SE.getNegativeSCEV(Step), Ty, Loc); 2129 Value *StartValue = expandCodeFor(Start, ARTy, Loc); 2130 2131 ConstantInt *Zero = 2132 ConstantInt::get(Loc->getContext(), APInt::getZero(DstBits)); 2133 2134 Builder.SetInsertPoint(Loc); 2135 // Compute |Step| 2136 Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero); 2137 Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue); 2138 2139 // Compute |Step| * Backedge 2140 // Compute: 2141 // 1. Start + |Step| * Backedge < Start 2142 // 2. Start - |Step| * Backedge > Start 2143 // 2144 // And select either 1. or 2. depending on whether step is positive or 2145 // negative. If Step is known to be positive or negative, only create 2146 // either 1. or 2. 2147 auto ComputeEndCheck = [&]() -> Value * { 2148 // Checking <u 0 is always false. 2149 if (!Signed && Start->isZero() && SE.isKnownPositive(Step)) 2150 return ConstantInt::getFalse(Loc->getContext()); 2151 2152 // Get the backedge taken count and truncate or extended to the AR type. 2153 Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty); 2154 2155 Value *MulV, *OfMul; 2156 if (Step->isOne()) { 2157 // Special-case Step of one. Potentially-costly `umul_with_overflow` isn't 2158 // needed, there is never an overflow, so to avoid artificially inflating 2159 // the cost of the check, directly emit the optimized IR. 2160 MulV = TruncTripCount; 2161 OfMul = ConstantInt::getFalse(MulV->getContext()); 2162 } else { 2163 auto *MulF = Intrinsic::getDeclaration(Loc->getModule(), 2164 Intrinsic::umul_with_overflow, Ty); 2165 CallInst *Mul = 2166 Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul"); 2167 MulV = Builder.CreateExtractValue(Mul, 0, "mul.result"); 2168 OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow"); 2169 } 2170 2171 Value *Add = nullptr, *Sub = nullptr; 2172 bool NeedPosCheck = !SE.isKnownNegative(Step); 2173 bool NeedNegCheck = !SE.isKnownPositive(Step); 2174 2175 if (PointerType *ARPtrTy = dyn_cast<PointerType>(ARTy)) { 2176 StartValue = InsertNoopCastOfTo(StartValue, ARPtrTy); 2177 Value *NegMulV = Builder.CreateNeg(MulV); 2178 if (NeedPosCheck) 2179 Add = Builder.CreateGEP(Builder.getInt8Ty(), StartValue, MulV); 2180 if (NeedNegCheck) 2181 Sub = Builder.CreateGEP(Builder.getInt8Ty(), StartValue, NegMulV); 2182 } else { 2183 if (NeedPosCheck) 2184 Add = Builder.CreateAdd(StartValue, MulV); 2185 if (NeedNegCheck) 2186 Sub = Builder.CreateSub(StartValue, MulV); 2187 } 2188 2189 Value *EndCompareLT = nullptr; 2190 Value *EndCompareGT = nullptr; 2191 Value *EndCheck = nullptr; 2192 if (NeedPosCheck) 2193 EndCheck = EndCompareLT = Builder.CreateICmp( 2194 Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue); 2195 if (NeedNegCheck) 2196 EndCheck = EndCompareGT = Builder.CreateICmp( 2197 Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue); 2198 if (NeedPosCheck && NeedNegCheck) { 2199 // Select the answer based on the sign of Step. 2200 EndCheck = Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT); 2201 } 2202 return Builder.CreateOr(EndCheck, OfMul); 2203 }; 2204 Value *EndCheck = ComputeEndCheck(); 2205 2206 // If the backedge taken count type is larger than the AR type, 2207 // check that we don't drop any bits by truncating it. If we are 2208 // dropping bits, then we have overflow (unless the step is zero). 2209 if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) { 2210 auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits); 2211 auto *BackedgeCheck = 2212 Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal, 2213 ConstantInt::get(Loc->getContext(), MaxVal)); 2214 BackedgeCheck = Builder.CreateAnd( 2215 BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero)); 2216 2217 EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck); 2218 } 2219 2220 return EndCheck; 2221 } 2222 2223 Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred, 2224 Instruction *IP) { 2225 const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr()); 2226 Value *NSSWCheck = nullptr, *NUSWCheck = nullptr; 2227 2228 // Add a check for NUSW 2229 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW) 2230 NUSWCheck = generateOverflowCheck(A, IP, false); 2231 2232 // Add a check for NSSW 2233 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW) 2234 NSSWCheck = generateOverflowCheck(A, IP, true); 2235 2236 if (NUSWCheck && NSSWCheck) 2237 return Builder.CreateOr(NUSWCheck, NSSWCheck); 2238 2239 if (NUSWCheck) 2240 return NUSWCheck; 2241 2242 if (NSSWCheck) 2243 return NSSWCheck; 2244 2245 return ConstantInt::getFalse(IP->getContext()); 2246 } 2247 2248 Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union, 2249 Instruction *IP) { 2250 // Loop over all checks in this set. 2251 SmallVector<Value *> Checks; 2252 for (const auto *Pred : Union->getPredicates()) { 2253 Checks.push_back(expandCodeForPredicate(Pred, IP)); 2254 Builder.SetInsertPoint(IP); 2255 } 2256 2257 if (Checks.empty()) 2258 return ConstantInt::getFalse(IP->getContext()); 2259 return Builder.CreateOr(Checks); 2260 } 2261 2262 Value *SCEVExpander::fixupLCSSAFormFor(Value *V) { 2263 auto *DefI = dyn_cast<Instruction>(V); 2264 if (!PreserveLCSSA || !DefI) 2265 return V; 2266 2267 Instruction *InsertPt = &*Builder.GetInsertPoint(); 2268 Loop *DefLoop = SE.LI.getLoopFor(DefI->getParent()); 2269 Loop *UseLoop = SE.LI.getLoopFor(InsertPt->getParent()); 2270 if (!DefLoop || UseLoop == DefLoop || DefLoop->contains(UseLoop)) 2271 return V; 2272 2273 // Create a temporary instruction to at the current insertion point, so we 2274 // can hand it off to the helper to create LCSSA PHIs if required for the 2275 // new use. 2276 // FIXME: Ideally formLCSSAForInstructions (used in fixupLCSSAFormFor) 2277 // would accept a insertion point and return an LCSSA phi for that 2278 // insertion point, so there is no need to insert & remove the temporary 2279 // instruction. 2280 Type *ToTy; 2281 if (DefI->getType()->isIntegerTy()) 2282 ToTy = PointerType::get(DefI->getContext(), 0); 2283 else 2284 ToTy = Type::getInt32Ty(DefI->getContext()); 2285 Instruction *User = 2286 CastInst::CreateBitOrPointerCast(DefI, ToTy, "tmp.lcssa.user", InsertPt); 2287 auto RemoveUserOnExit = 2288 make_scope_exit([User]() { User->eraseFromParent(); }); 2289 2290 SmallVector<Instruction *, 1> ToUpdate; 2291 ToUpdate.push_back(DefI); 2292 SmallVector<PHINode *, 16> PHIsToRemove; 2293 SmallVector<PHINode *, 16> InsertedPHIs; 2294 formLCSSAForInstructions(ToUpdate, SE.DT, SE.LI, &SE, &PHIsToRemove, 2295 &InsertedPHIs); 2296 for (PHINode *PN : InsertedPHIs) 2297 rememberInstruction(PN); 2298 for (PHINode *PN : PHIsToRemove) { 2299 if (!PN->use_empty()) 2300 continue; 2301 InsertedValues.erase(PN); 2302 InsertedPostIncValues.erase(PN); 2303 PN->eraseFromParent(); 2304 } 2305 2306 return User->getOperand(0); 2307 } 2308 2309 namespace { 2310 // Search for a SCEV subexpression that is not safe to expand. Any expression 2311 // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely 2312 // UDiv expressions. We don't know if the UDiv is derived from an IR divide 2313 // instruction, but the important thing is that we prove the denominator is 2314 // nonzero before expansion. 2315 // 2316 // IVUsers already checks that IV-derived expressions are safe. So this check is 2317 // only needed when the expression includes some subexpression that is not IV 2318 // derived. 2319 // 2320 // Currently, we only allow division by a value provably non-zero here. 2321 // 2322 // We cannot generally expand recurrences unless the step dominates the loop 2323 // header. The expander handles the special case of affine recurrences by 2324 // scaling the recurrence outside the loop, but this technique isn't generally 2325 // applicable. Expanding a nested recurrence outside a loop requires computing 2326 // binomial coefficients. This could be done, but the recurrence has to be in a 2327 // perfectly reduced form, which can't be guaranteed. 2328 struct SCEVFindUnsafe { 2329 ScalarEvolution &SE; 2330 bool CanonicalMode; 2331 bool IsUnsafe = false; 2332 2333 SCEVFindUnsafe(ScalarEvolution &SE, bool CanonicalMode) 2334 : SE(SE), CanonicalMode(CanonicalMode) {} 2335 2336 bool follow(const SCEV *S) { 2337 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) { 2338 if (!SE.isKnownNonZero(D->getRHS())) { 2339 IsUnsafe = true; 2340 return false; 2341 } 2342 } 2343 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 2344 const SCEV *Step = AR->getStepRecurrence(SE); 2345 if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) { 2346 IsUnsafe = true; 2347 return false; 2348 } 2349 2350 // For non-affine addrecs or in non-canonical mode we need a preheader 2351 // to insert into. 2352 if (!AR->getLoop()->getLoopPreheader() && 2353 (!CanonicalMode || !AR->isAffine())) { 2354 IsUnsafe = true; 2355 return false; 2356 } 2357 } 2358 return true; 2359 } 2360 bool isDone() const { return IsUnsafe; } 2361 }; 2362 } // namespace 2363 2364 bool SCEVExpander::isSafeToExpand(const SCEV *S) const { 2365 SCEVFindUnsafe Search(SE, CanonicalMode); 2366 visitAll(S, Search); 2367 return !Search.IsUnsafe; 2368 } 2369 2370 bool SCEVExpander::isSafeToExpandAt(const SCEV *S, 2371 const Instruction *InsertionPoint) const { 2372 if (!isSafeToExpand(S)) 2373 return false; 2374 // We have to prove that the expanded site of S dominates InsertionPoint. 2375 // This is easy when not in the same block, but hard when S is an instruction 2376 // to be expanded somewhere inside the same block as our insertion point. 2377 // What we really need here is something analogous to an OrderedBasicBlock, 2378 // but for the moment, we paper over the problem by handling two common and 2379 // cheap to check cases. 2380 if (SE.properlyDominates(S, InsertionPoint->getParent())) 2381 return true; 2382 if (SE.dominates(S, InsertionPoint->getParent())) { 2383 if (InsertionPoint->getParent()->getTerminator() == InsertionPoint) 2384 return true; 2385 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) 2386 if (llvm::is_contained(InsertionPoint->operand_values(), U->getValue())) 2387 return true; 2388 } 2389 return false; 2390 } 2391 2392 void SCEVExpanderCleaner::cleanup() { 2393 // Result is used, nothing to remove. 2394 if (ResultUsed) 2395 return; 2396 2397 auto InsertedInstructions = Expander.getAllInsertedInstructions(); 2398 #ifndef NDEBUG 2399 SmallPtrSet<Instruction *, 8> InsertedSet(InsertedInstructions.begin(), 2400 InsertedInstructions.end()); 2401 (void)InsertedSet; 2402 #endif 2403 // Remove sets with value handles. 2404 Expander.clear(); 2405 2406 // Remove all inserted instructions. 2407 for (Instruction *I : reverse(InsertedInstructions)) { 2408 #ifndef NDEBUG 2409 assert(all_of(I->users(), 2410 [&InsertedSet](Value *U) { 2411 return InsertedSet.contains(cast<Instruction>(U)); 2412 }) && 2413 "removed instruction should only be used by instructions inserted " 2414 "during expansion"); 2415 #endif 2416 assert(!I->getType()->isVoidTy() && 2417 "inserted instruction should have non-void types"); 2418 I->replaceAllUsesWith(PoisonValue::get(I->getType())); 2419 I->eraseFromParent(); 2420 } 2421 } 2422