1 //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===// 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 implements induction variable simplification. It does 10 // not define any actual pass or policy, but provides a single function to 11 // simplify a loop's induction variables based on ScalarEvolution. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/Analysis/LoopInfo.h" 19 #include "llvm/IR/Dominators.h" 20 #include "llvm/IR/IRBuilder.h" 21 #include "llvm/IR/Instructions.h" 22 #include "llvm/IR/IntrinsicInst.h" 23 #include "llvm/IR/PatternMatch.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Transforms/Utils/Local.h" 27 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 28 29 using namespace llvm; 30 31 #define DEBUG_TYPE "indvars" 32 33 STATISTIC(NumElimIdentity, "Number of IV identities eliminated"); 34 STATISTIC(NumElimOperand, "Number of IV operands folded into a use"); 35 STATISTIC(NumFoldedUser, "Number of IV users folded into a constant"); 36 STATISTIC(NumElimRem , "Number of IV remainder operations eliminated"); 37 STATISTIC( 38 NumSimplifiedSDiv, 39 "Number of IV signed division operations converted to unsigned division"); 40 STATISTIC( 41 NumSimplifiedSRem, 42 "Number of IV signed remainder operations converted to unsigned remainder"); 43 STATISTIC(NumElimCmp , "Number of IV comparisons eliminated"); 44 45 namespace { 46 /// This is a utility for simplifying induction variables 47 /// based on ScalarEvolution. It is the primary instrument of the 48 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after 49 /// other loop passes that preserve SCEV. 50 class SimplifyIndvar { 51 Loop *L; 52 LoopInfo *LI; 53 ScalarEvolution *SE; 54 DominatorTree *DT; 55 const TargetTransformInfo *TTI; 56 SCEVExpander &Rewriter; 57 SmallVectorImpl<WeakTrackingVH> &DeadInsts; 58 59 bool Changed = false; 60 61 public: 62 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT, 63 LoopInfo *LI, const TargetTransformInfo *TTI, 64 SCEVExpander &Rewriter, 65 SmallVectorImpl<WeakTrackingVH> &Dead) 66 : L(Loop), LI(LI), SE(SE), DT(DT), TTI(TTI), Rewriter(Rewriter), 67 DeadInsts(Dead) { 68 assert(LI && "IV simplification requires LoopInfo"); 69 } 70 71 bool hasChanged() const { return Changed; } 72 73 /// Iteratively perform simplification on a worklist of users of the 74 /// specified induction variable. This is the top-level driver that applies 75 /// all simplifications to users of an IV. 76 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr); 77 78 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand); 79 80 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand); 81 bool replaceIVUserWithLoopInvariant(Instruction *UseInst); 82 bool replaceFloatIVWithIntegerIV(Instruction *UseInst); 83 84 bool eliminateOverflowIntrinsic(WithOverflowInst *WO); 85 bool eliminateSaturatingIntrinsic(SaturatingInst *SI); 86 bool eliminateTrunc(TruncInst *TI); 87 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand); 88 bool makeIVComparisonInvariant(ICmpInst *ICmp, Instruction *IVOperand); 89 void eliminateIVComparison(ICmpInst *ICmp, Instruction *IVOperand); 90 void simplifyIVRemainder(BinaryOperator *Rem, Instruction *IVOperand, 91 bool IsSigned); 92 void replaceRemWithNumerator(BinaryOperator *Rem); 93 void replaceRemWithNumeratorOrZero(BinaryOperator *Rem); 94 void replaceSRemWithURem(BinaryOperator *Rem); 95 bool eliminateSDiv(BinaryOperator *SDiv); 96 bool strengthenOverflowingOperation(BinaryOperator *OBO, 97 Instruction *IVOperand); 98 bool strengthenRightShift(BinaryOperator *BO, Instruction *IVOperand); 99 }; 100 } 101 102 /// Find a point in code which dominates all given instructions. We can safely 103 /// assume that, whatever fact we can prove at the found point, this fact is 104 /// also true for each of the given instructions. 105 static Instruction *findCommonDominator(ArrayRef<Instruction *> Instructions, 106 DominatorTree &DT) { 107 Instruction *CommonDom = nullptr; 108 for (auto *Insn : Instructions) 109 if (!CommonDom || DT.dominates(Insn, CommonDom)) 110 CommonDom = Insn; 111 else if (!DT.dominates(CommonDom, Insn)) 112 // If there is no dominance relation, use common dominator. 113 CommonDom = 114 DT.findNearestCommonDominator(CommonDom->getParent(), 115 Insn->getParent())->getTerminator(); 116 assert(CommonDom && "Common dominator not found?"); 117 return CommonDom; 118 } 119 120 /// Fold an IV operand into its use. This removes increments of an 121 /// aligned IV when used by a instruction that ignores the low bits. 122 /// 123 /// IVOperand is guaranteed SCEVable, but UseInst may not be. 124 /// 125 /// Return the operand of IVOperand for this induction variable if IVOperand can 126 /// be folded (in case more folding opportunities have been exposed). 127 /// Otherwise return null. 128 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) { 129 Value *IVSrc = nullptr; 130 const unsigned OperIdx = 0; 131 const SCEV *FoldedExpr = nullptr; 132 bool MustDropExactFlag = false; 133 switch (UseInst->getOpcode()) { 134 default: 135 return nullptr; 136 case Instruction::UDiv: 137 case Instruction::LShr: 138 // We're only interested in the case where we know something about 139 // the numerator and have a constant denominator. 140 if (IVOperand != UseInst->getOperand(OperIdx) || 141 !isa<ConstantInt>(UseInst->getOperand(1))) 142 return nullptr; 143 144 // Attempt to fold a binary operator with constant operand. 145 // e.g. ((I + 1) >> 2) => I >> 2 146 if (!isa<BinaryOperator>(IVOperand) 147 || !isa<ConstantInt>(IVOperand->getOperand(1))) 148 return nullptr; 149 150 IVSrc = IVOperand->getOperand(0); 151 // IVSrc must be the (SCEVable) IV, since the other operand is const. 152 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand"); 153 154 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1)); 155 if (UseInst->getOpcode() == Instruction::LShr) { 156 // Get a constant for the divisor. See createSCEV. 157 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth(); 158 if (D->getValue().uge(BitWidth)) 159 return nullptr; 160 161 D = ConstantInt::get(UseInst->getContext(), 162 APInt::getOneBitSet(BitWidth, D->getZExtValue())); 163 } 164 const auto *LHS = SE->getSCEV(IVSrc); 165 const auto *RHS = SE->getSCEV(D); 166 FoldedExpr = SE->getUDivExpr(LHS, RHS); 167 // We might have 'exact' flag set at this point which will no longer be 168 // correct after we make the replacement. 169 if (UseInst->isExact() && LHS != SE->getMulExpr(FoldedExpr, RHS)) 170 MustDropExactFlag = true; 171 } 172 // We have something that might fold it's operand. Compare SCEVs. 173 if (!SE->isSCEVable(UseInst->getType())) 174 return nullptr; 175 176 // Bypass the operand if SCEV can prove it has no effect. 177 if (SE->getSCEV(UseInst) != FoldedExpr) 178 return nullptr; 179 180 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand 181 << " -> " << *UseInst << '\n'); 182 183 UseInst->setOperand(OperIdx, IVSrc); 184 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper"); 185 186 if (MustDropExactFlag) 187 UseInst->dropPoisonGeneratingFlags(); 188 189 ++NumElimOperand; 190 Changed = true; 191 if (IVOperand->use_empty()) 192 DeadInsts.emplace_back(IVOperand); 193 return IVSrc; 194 } 195 196 bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp, 197 Instruction *IVOperand) { 198 unsigned IVOperIdx = 0; 199 ICmpInst::Predicate Pred = ICmp->getPredicate(); 200 if (IVOperand != ICmp->getOperand(0)) { 201 // Swapped 202 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); 203 IVOperIdx = 1; 204 Pred = ICmpInst::getSwappedPredicate(Pred); 205 } 206 207 // Get the SCEVs for the ICmp operands (in the specific context of the 208 // current loop) 209 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); 210 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop); 211 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop); 212 213 auto *PN = dyn_cast<PHINode>(IVOperand); 214 if (!PN) 215 return false; 216 auto LIP = SE->getLoopInvariantPredicate(Pred, S, X, L); 217 if (!LIP) 218 return false; 219 ICmpInst::Predicate InvariantPredicate = LIP->Pred; 220 const SCEV *InvariantLHS = LIP->LHS; 221 const SCEV *InvariantRHS = LIP->RHS; 222 223 // Rewrite the comparison to a loop invariant comparison if it can be done 224 // cheaply, where cheaply means "we don't need to emit any new 225 // instructions". 226 227 SmallDenseMap<const SCEV*, Value*> CheapExpansions; 228 CheapExpansions[S] = ICmp->getOperand(IVOperIdx); 229 CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx); 230 231 // TODO: Support multiple entry loops? (We currently bail out of these in 232 // the IndVarSimplify pass) 233 if (auto *BB = L->getLoopPredecessor()) { 234 const int Idx = PN->getBasicBlockIndex(BB); 235 if (Idx >= 0) { 236 Value *Incoming = PN->getIncomingValue(Idx); 237 const SCEV *IncomingS = SE->getSCEV(Incoming); 238 CheapExpansions[IncomingS] = Incoming; 239 } 240 } 241 Value *NewLHS = CheapExpansions[InvariantLHS]; 242 Value *NewRHS = CheapExpansions[InvariantRHS]; 243 244 if (!NewLHS) 245 if (auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS)) 246 NewLHS = ConstLHS->getValue(); 247 if (!NewRHS) 248 if (auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS)) 249 NewRHS = ConstRHS->getValue(); 250 251 if (!NewLHS || !NewRHS) 252 // We could not find an existing value to replace either LHS or RHS. 253 // Generating new instructions has subtler tradeoffs, so avoid doing that 254 // for now. 255 return false; 256 257 LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n'); 258 ICmp->setPredicate(InvariantPredicate); 259 ICmp->setOperand(0, NewLHS); 260 ICmp->setOperand(1, NewRHS); 261 return true; 262 } 263 264 /// SimplifyIVUsers helper for eliminating useless 265 /// comparisons against an induction variable. 266 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, 267 Instruction *IVOperand) { 268 unsigned IVOperIdx = 0; 269 ICmpInst::Predicate Pred = ICmp->getPredicate(); 270 ICmpInst::Predicate OriginalPred = Pred; 271 if (IVOperand != ICmp->getOperand(0)) { 272 // Swapped 273 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); 274 IVOperIdx = 1; 275 Pred = ICmpInst::getSwappedPredicate(Pred); 276 } 277 278 // Get the SCEVs for the ICmp operands (in the specific context of the 279 // current loop) 280 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); 281 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop); 282 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop); 283 284 // If the condition is always true or always false in the given context, 285 // replace it with a constant value. 286 SmallVector<Instruction *, 4> Users; 287 for (auto *U : ICmp->users()) 288 Users.push_back(cast<Instruction>(U)); 289 const Instruction *CtxI = findCommonDominator(Users, *DT); 290 if (auto Ev = SE->evaluatePredicateAt(Pred, S, X, CtxI)) { 291 ICmp->replaceAllUsesWith(ConstantInt::getBool(ICmp->getContext(), *Ev)); 292 DeadInsts.emplace_back(ICmp); 293 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); 294 } else if (makeIVComparisonInvariant(ICmp, IVOperand)) { 295 // fallthrough to end of function 296 } else if (ICmpInst::isSigned(OriginalPred) && 297 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) { 298 // If we were unable to make anything above, all we can is to canonicalize 299 // the comparison hoping that it will open the doors for other 300 // optimizations. If we find out that we compare two non-negative values, 301 // we turn the instruction's predicate to its unsigned version. Note that 302 // we cannot rely on Pred here unless we check if we have swapped it. 303 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?"); 304 LLVM_DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp 305 << '\n'); 306 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred)); 307 } else 308 return; 309 310 ++NumElimCmp; 311 Changed = true; 312 } 313 314 bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) { 315 // Get the SCEVs for the ICmp operands. 316 auto *N = SE->getSCEV(SDiv->getOperand(0)); 317 auto *D = SE->getSCEV(SDiv->getOperand(1)); 318 319 // Simplify unnecessary loops away. 320 const Loop *L = LI->getLoopFor(SDiv->getParent()); 321 N = SE->getSCEVAtScope(N, L); 322 D = SE->getSCEVAtScope(D, L); 323 324 // Replace sdiv by udiv if both of the operands are non-negative 325 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) { 326 auto *UDiv = BinaryOperator::Create( 327 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1), 328 SDiv->getName() + ".udiv", SDiv); 329 UDiv->setIsExact(SDiv->isExact()); 330 SDiv->replaceAllUsesWith(UDiv); 331 LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n'); 332 ++NumSimplifiedSDiv; 333 Changed = true; 334 DeadInsts.push_back(SDiv); 335 return true; 336 } 337 338 return false; 339 } 340 341 // i %s n -> i %u n if i >= 0 and n >= 0 342 void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) { 343 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1); 344 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D, 345 Rem->getName() + ".urem", Rem); 346 Rem->replaceAllUsesWith(URem); 347 LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n'); 348 ++NumSimplifiedSRem; 349 Changed = true; 350 DeadInsts.emplace_back(Rem); 351 } 352 353 // i % n --> i if i is in [0,n). 354 void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) { 355 Rem->replaceAllUsesWith(Rem->getOperand(0)); 356 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); 357 ++NumElimRem; 358 Changed = true; 359 DeadInsts.emplace_back(Rem); 360 } 361 362 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n). 363 void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) { 364 auto *T = Rem->getType(); 365 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1); 366 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D); 367 SelectInst *Sel = 368 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem); 369 Rem->replaceAllUsesWith(Sel); 370 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); 371 ++NumElimRem; 372 Changed = true; 373 DeadInsts.emplace_back(Rem); 374 } 375 376 /// SimplifyIVUsers helper for eliminating useless remainder operations 377 /// operating on an induction variable or replacing srem by urem. 378 void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, 379 Instruction *IVOperand, 380 bool IsSigned) { 381 auto *NValue = Rem->getOperand(0); 382 auto *DValue = Rem->getOperand(1); 383 // We're only interested in the case where we know something about 384 // the numerator, unless it is a srem, because we want to replace srem by urem 385 // in general. 386 bool UsedAsNumerator = IVOperand == NValue; 387 if (!UsedAsNumerator && !IsSigned) 388 return; 389 390 const SCEV *N = SE->getSCEV(NValue); 391 392 // Simplify unnecessary loops away. 393 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent()); 394 N = SE->getSCEVAtScope(N, ICmpLoop); 395 396 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N); 397 398 // Do not proceed if the Numerator may be negative 399 if (!IsNumeratorNonNegative) 400 return; 401 402 const SCEV *D = SE->getSCEV(DValue); 403 D = SE->getSCEVAtScope(D, ICmpLoop); 404 405 if (UsedAsNumerator) { 406 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 407 if (SE->isKnownPredicate(LT, N, D)) { 408 replaceRemWithNumerator(Rem); 409 return; 410 } 411 412 auto *T = Rem->getType(); 413 const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T)); 414 if (SE->isKnownPredicate(LT, NLessOne, D)) { 415 replaceRemWithNumeratorOrZero(Rem); 416 return; 417 } 418 } 419 420 // Try to replace SRem with URem, if both N and D are known non-negative. 421 // Since we had already check N, we only need to check D now 422 if (!IsSigned || !SE->isKnownNonNegative(D)) 423 return; 424 425 replaceSRemWithURem(Rem); 426 } 427 428 bool SimplifyIndvar::eliminateOverflowIntrinsic(WithOverflowInst *WO) { 429 const SCEV *LHS = SE->getSCEV(WO->getLHS()); 430 const SCEV *RHS = SE->getSCEV(WO->getRHS()); 431 if (!SE->willNotOverflow(WO->getBinaryOp(), WO->isSigned(), LHS, RHS)) 432 return false; 433 434 // Proved no overflow, nuke the overflow check and, if possible, the overflow 435 // intrinsic as well. 436 437 BinaryOperator *NewResult = BinaryOperator::Create( 438 WO->getBinaryOp(), WO->getLHS(), WO->getRHS(), "", WO); 439 440 if (WO->isSigned()) 441 NewResult->setHasNoSignedWrap(true); 442 else 443 NewResult->setHasNoUnsignedWrap(true); 444 445 SmallVector<ExtractValueInst *, 4> ToDelete; 446 447 for (auto *U : WO->users()) { 448 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) { 449 if (EVI->getIndices()[0] == 1) 450 EVI->replaceAllUsesWith(ConstantInt::getFalse(WO->getContext())); 451 else { 452 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!"); 453 EVI->replaceAllUsesWith(NewResult); 454 } 455 ToDelete.push_back(EVI); 456 } 457 } 458 459 for (auto *EVI : ToDelete) 460 EVI->eraseFromParent(); 461 462 if (WO->use_empty()) 463 WO->eraseFromParent(); 464 465 Changed = true; 466 return true; 467 } 468 469 bool SimplifyIndvar::eliminateSaturatingIntrinsic(SaturatingInst *SI) { 470 const SCEV *LHS = SE->getSCEV(SI->getLHS()); 471 const SCEV *RHS = SE->getSCEV(SI->getRHS()); 472 if (!SE->willNotOverflow(SI->getBinaryOp(), SI->isSigned(), LHS, RHS)) 473 return false; 474 475 BinaryOperator *BO = BinaryOperator::Create( 476 SI->getBinaryOp(), SI->getLHS(), SI->getRHS(), SI->getName(), SI); 477 if (SI->isSigned()) 478 BO->setHasNoSignedWrap(); 479 else 480 BO->setHasNoUnsignedWrap(); 481 482 SI->replaceAllUsesWith(BO); 483 DeadInsts.emplace_back(SI); 484 Changed = true; 485 return true; 486 } 487 488 bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) { 489 // It is always legal to replace 490 // icmp <pred> i32 trunc(iv), n 491 // with 492 // icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate. 493 // Or with 494 // icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate. 495 // Or with either of these if pred is an equality predicate. 496 // 497 // If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for 498 // every comparison which uses trunc, it means that we can replace each of 499 // them with comparison of iv against sext/zext(n). We no longer need trunc 500 // after that. 501 // 502 // TODO: Should we do this if we can widen *some* comparisons, but not all 503 // of them? Sometimes it is enough to enable other optimizations, but the 504 // trunc instruction will stay in the loop. 505 Value *IV = TI->getOperand(0); 506 Type *IVTy = IV->getType(); 507 const SCEV *IVSCEV = SE->getSCEV(IV); 508 const SCEV *TISCEV = SE->getSCEV(TI); 509 510 // Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can 511 // get rid of trunc 512 bool DoesSExtCollapse = false; 513 bool DoesZExtCollapse = false; 514 if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy)) 515 DoesSExtCollapse = true; 516 if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy)) 517 DoesZExtCollapse = true; 518 519 // If neither sext nor zext does collapse, it is not profitable to do any 520 // transform. Bail. 521 if (!DoesSExtCollapse && !DoesZExtCollapse) 522 return false; 523 524 // Collect users of the trunc that look like comparisons against invariants. 525 // Bail if we find something different. 526 SmallVector<ICmpInst *, 4> ICmpUsers; 527 for (auto *U : TI->users()) { 528 // We don't care about users in unreachable blocks. 529 if (isa<Instruction>(U) && 530 !DT->isReachableFromEntry(cast<Instruction>(U)->getParent())) 531 continue; 532 ICmpInst *ICI = dyn_cast<ICmpInst>(U); 533 if (!ICI) return false; 534 assert(L->contains(ICI->getParent()) && "LCSSA form broken?"); 535 if (!(ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) && 536 !(ICI->getOperand(1) == TI && L->isLoopInvariant(ICI->getOperand(0)))) 537 return false; 538 // If we cannot get rid of trunc, bail. 539 if (ICI->isSigned() && !DoesSExtCollapse) 540 return false; 541 if (ICI->isUnsigned() && !DoesZExtCollapse) 542 return false; 543 // For equality, either signed or unsigned works. 544 ICmpUsers.push_back(ICI); 545 } 546 547 auto CanUseZExt = [&](ICmpInst *ICI) { 548 // Unsigned comparison can be widened as unsigned. 549 if (ICI->isUnsigned()) 550 return true; 551 // Is it profitable to do zext? 552 if (!DoesZExtCollapse) 553 return false; 554 // For equality, we can safely zext both parts. 555 if (ICI->isEquality()) 556 return true; 557 // Otherwise we can only use zext when comparing two non-negative or two 558 // negative values. But in practice, we will never pass DoesZExtCollapse 559 // check for a negative value, because zext(trunc(x)) is non-negative. So 560 // it only make sense to check for non-negativity here. 561 const SCEV *SCEVOP1 = SE->getSCEV(ICI->getOperand(0)); 562 const SCEV *SCEVOP2 = SE->getSCEV(ICI->getOperand(1)); 563 return SE->isKnownNonNegative(SCEVOP1) && SE->isKnownNonNegative(SCEVOP2); 564 }; 565 // Replace all comparisons against trunc with comparisons against IV. 566 for (auto *ICI : ICmpUsers) { 567 bool IsSwapped = L->isLoopInvariant(ICI->getOperand(0)); 568 auto *Op1 = IsSwapped ? ICI->getOperand(0) : ICI->getOperand(1); 569 Instruction *Ext = nullptr; 570 // For signed/unsigned predicate, replace the old comparison with comparison 571 // of immediate IV against sext/zext of the invariant argument. If we can 572 // use either sext or zext (i.e. we are dealing with equality predicate), 573 // then prefer zext as a more canonical form. 574 // TODO: If we see a signed comparison which can be turned into unsigned, 575 // we can do it here for canonicalization purposes. 576 ICmpInst::Predicate Pred = ICI->getPredicate(); 577 if (IsSwapped) Pred = ICmpInst::getSwappedPredicate(Pred); 578 if (CanUseZExt(ICI)) { 579 assert(DoesZExtCollapse && "Unprofitable zext?"); 580 Ext = new ZExtInst(Op1, IVTy, "zext", ICI); 581 Pred = ICmpInst::getUnsignedPredicate(Pred); 582 } else { 583 assert(DoesSExtCollapse && "Unprofitable sext?"); 584 Ext = new SExtInst(Op1, IVTy, "sext", ICI); 585 assert(Pred == ICmpInst::getSignedPredicate(Pred) && "Must be signed!"); 586 } 587 bool Changed; 588 L->makeLoopInvariant(Ext, Changed); 589 (void)Changed; 590 ICmpInst *NewICI = new ICmpInst(ICI, Pred, IV, Ext); 591 ICI->replaceAllUsesWith(NewICI); 592 DeadInsts.emplace_back(ICI); 593 } 594 595 // Trunc no longer needed. 596 TI->replaceAllUsesWith(UndefValue::get(TI->getType())); 597 DeadInsts.emplace_back(TI); 598 return true; 599 } 600 601 /// Eliminate an operation that consumes a simple IV and has no observable 602 /// side-effect given the range of IV values. IVOperand is guaranteed SCEVable, 603 /// but UseInst may not be. 604 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst, 605 Instruction *IVOperand) { 606 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) { 607 eliminateIVComparison(ICmp, IVOperand); 608 return true; 609 } 610 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) { 611 bool IsSRem = Bin->getOpcode() == Instruction::SRem; 612 if (IsSRem || Bin->getOpcode() == Instruction::URem) { 613 simplifyIVRemainder(Bin, IVOperand, IsSRem); 614 return true; 615 } 616 617 if (Bin->getOpcode() == Instruction::SDiv) 618 return eliminateSDiv(Bin); 619 } 620 621 if (auto *WO = dyn_cast<WithOverflowInst>(UseInst)) 622 if (eliminateOverflowIntrinsic(WO)) 623 return true; 624 625 if (auto *SI = dyn_cast<SaturatingInst>(UseInst)) 626 if (eliminateSaturatingIntrinsic(SI)) 627 return true; 628 629 if (auto *TI = dyn_cast<TruncInst>(UseInst)) 630 if (eliminateTrunc(TI)) 631 return true; 632 633 if (eliminateIdentitySCEV(UseInst, IVOperand)) 634 return true; 635 636 return false; 637 } 638 639 static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) { 640 if (auto *BB = L->getLoopPreheader()) 641 return BB->getTerminator(); 642 643 return Hint; 644 } 645 646 /// Replace the UseInst with a loop invariant expression if it is safe. 647 bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) { 648 if (!SE->isSCEVable(I->getType())) 649 return false; 650 651 // Get the symbolic expression for this instruction. 652 const SCEV *S = SE->getSCEV(I); 653 654 if (!SE->isLoopInvariant(S, L)) 655 return false; 656 657 // Do not generate something ridiculous even if S is loop invariant. 658 if (Rewriter.isHighCostExpansion(S, L, SCEVCheapExpansionBudget, TTI, I)) 659 return false; 660 661 auto *IP = GetLoopInvariantInsertPosition(L, I); 662 663 if (!isSafeToExpandAt(S, IP, *SE)) { 664 LLVM_DEBUG(dbgs() << "INDVARS: Can not replace IV user: " << *I 665 << " with non-speculable loop invariant: " << *S << '\n'); 666 return false; 667 } 668 669 auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP); 670 671 I->replaceAllUsesWith(Invariant); 672 LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I 673 << " with loop invariant: " << *S << '\n'); 674 ++NumFoldedUser; 675 Changed = true; 676 DeadInsts.emplace_back(I); 677 return true; 678 } 679 680 /// Eliminate redundant type cast between integer and float. 681 bool SimplifyIndvar::replaceFloatIVWithIntegerIV(Instruction *UseInst) { 682 if (UseInst->getOpcode() != CastInst::SIToFP) 683 return false; 684 685 Value *IVOperand = UseInst->getOperand(0); 686 // Get the symbolic expression for this instruction. 687 ConstantRange IVRange = SE->getSignedRange(SE->getSCEV(IVOperand)); 688 unsigned DestNumSigBits = UseInst->getType()->getFPMantissaWidth(); 689 if (IVRange.getActiveBits() <= DestNumSigBits) { 690 for (User *U : UseInst->users()) { 691 // Match for fptosi of sitofp and with same type. 692 auto *CI = dyn_cast<FPToSIInst>(U); 693 if (!CI || IVOperand->getType() != CI->getType()) 694 continue; 695 696 CI->replaceAllUsesWith(IVOperand); 697 DeadInsts.push_back(CI); 698 LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *CI 699 << " with: " << *IVOperand << '\n'); 700 701 ++NumFoldedUser; 702 Changed = true; 703 } 704 } 705 706 return Changed; 707 } 708 709 /// Eliminate any operation that SCEV can prove is an identity function. 710 bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst, 711 Instruction *IVOperand) { 712 if (!SE->isSCEVable(UseInst->getType()) || 713 (UseInst->getType() != IVOperand->getType()) || 714 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand))) 715 return false; 716 717 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the 718 // dominator tree, even if X is an operand to Y. For instance, in 719 // 720 // %iv = phi i32 {0,+,1} 721 // br %cond, label %left, label %merge 722 // 723 // left: 724 // %X = add i32 %iv, 0 725 // br label %merge 726 // 727 // merge: 728 // %M = phi (%X, %iv) 729 // 730 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and 731 // %M.replaceAllUsesWith(%X) would be incorrect. 732 733 if (isa<PHINode>(UseInst)) 734 // If UseInst is not a PHI node then we know that IVOperand dominates 735 // UseInst directly from the legality of SSA. 736 if (!DT || !DT->dominates(IVOperand, UseInst)) 737 return false; 738 739 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand)) 740 return false; 741 742 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n'); 743 744 UseInst->replaceAllUsesWith(IVOperand); 745 ++NumElimIdentity; 746 Changed = true; 747 DeadInsts.emplace_back(UseInst); 748 return true; 749 } 750 751 /// Annotate BO with nsw / nuw if it provably does not signed-overflow / 752 /// unsigned-overflow. Returns true if anything changed, false otherwise. 753 bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO, 754 Instruction *IVOperand) { 755 auto Flags = SE->getStrengthenedNoWrapFlagsFromBinOp( 756 cast<OverflowingBinaryOperator>(BO)); 757 758 if (!Flags) 759 return false; 760 761 BO->setHasNoUnsignedWrap(ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) == 762 SCEV::FlagNUW); 763 BO->setHasNoSignedWrap(ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) == 764 SCEV::FlagNSW); 765 766 // The getStrengthenedNoWrapFlagsFromBinOp() check inferred additional nowrap 767 // flags on addrecs while performing zero/sign extensions. We could call 768 // forgetValue() here to make sure those flags also propagate to any other 769 // SCEV expressions based on the addrec. However, this can have pathological 770 // compile-time impact, see https://bugs.llvm.org/show_bug.cgi?id=50384. 771 return true; 772 } 773 774 /// Annotate the Shr in (X << IVOperand) >> C as exact using the 775 /// information from the IV's range. Returns true if anything changed, false 776 /// otherwise. 777 bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO, 778 Instruction *IVOperand) { 779 using namespace llvm::PatternMatch; 780 781 if (BO->getOpcode() == Instruction::Shl) { 782 bool Changed = false; 783 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand)); 784 for (auto *U : BO->users()) { 785 const APInt *C; 786 if (match(U, 787 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) || 788 match(U, 789 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) { 790 BinaryOperator *Shr = cast<BinaryOperator>(U); 791 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) { 792 Shr->setIsExact(true); 793 Changed = true; 794 } 795 } 796 } 797 return Changed; 798 } 799 800 return false; 801 } 802 803 /// Add all uses of Def to the current IV's worklist. 804 static void pushIVUsers( 805 Instruction *Def, Loop *L, 806 SmallPtrSet<Instruction*,16> &Simplified, 807 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) { 808 809 for (User *U : Def->users()) { 810 Instruction *UI = cast<Instruction>(U); 811 812 // Avoid infinite or exponential worklist processing. 813 // Also ensure unique worklist users. 814 // If Def is a LoopPhi, it may not be in the Simplified set, so check for 815 // self edges first. 816 if (UI == Def) 817 continue; 818 819 // Only change the current Loop, do not change the other parts (e.g. other 820 // Loops). 821 if (!L->contains(UI)) 822 continue; 823 824 // Do not push the same instruction more than once. 825 if (!Simplified.insert(UI).second) 826 continue; 827 828 SimpleIVUsers.push_back(std::make_pair(UI, Def)); 829 } 830 } 831 832 /// Return true if this instruction generates a simple SCEV 833 /// expression in terms of that IV. 834 /// 835 /// This is similar to IVUsers' isInteresting() but processes each instruction 836 /// non-recursively when the operand is already known to be a simpleIVUser. 837 /// 838 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) { 839 if (!SE->isSCEVable(I->getType())) 840 return false; 841 842 // Get the symbolic expression for this instruction. 843 const SCEV *S = SE->getSCEV(I); 844 845 // Only consider affine recurrences. 846 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S); 847 if (AR && AR->getLoop() == L) 848 return true; 849 850 return false; 851 } 852 853 /// Iteratively perform simplification on a worklist of users 854 /// of the specified induction variable. Each successive simplification may push 855 /// more users which may themselves be candidates for simplification. 856 /// 857 /// This algorithm does not require IVUsers analysis. Instead, it simplifies 858 /// instructions in-place during analysis. Rather than rewriting induction 859 /// variables bottom-up from their users, it transforms a chain of IVUsers 860 /// top-down, updating the IR only when it encounters a clear optimization 861 /// opportunity. 862 /// 863 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers. 864 /// 865 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) { 866 if (!SE->isSCEVable(CurrIV->getType())) 867 return; 868 869 // Instructions processed by SimplifyIndvar for CurrIV. 870 SmallPtrSet<Instruction*,16> Simplified; 871 872 // Use-def pairs if IV users waiting to be processed for CurrIV. 873 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers; 874 875 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be 876 // called multiple times for the same LoopPhi. This is the proper thing to 877 // do for loop header phis that use each other. 878 pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers); 879 880 while (!SimpleIVUsers.empty()) { 881 std::pair<Instruction*, Instruction*> UseOper = 882 SimpleIVUsers.pop_back_val(); 883 Instruction *UseInst = UseOper.first; 884 885 // If a user of the IndVar is trivially dead, we prefer just to mark it dead 886 // rather than try to do some complex analysis or transformation (such as 887 // widening) basing on it. 888 // TODO: Propagate TLI and pass it here to handle more cases. 889 if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) { 890 DeadInsts.emplace_back(UseInst); 891 continue; 892 } 893 894 // Bypass back edges to avoid extra work. 895 if (UseInst == CurrIV) continue; 896 897 // Try to replace UseInst with a loop invariant before any other 898 // simplifications. 899 if (replaceIVUserWithLoopInvariant(UseInst)) 900 continue; 901 902 Instruction *IVOperand = UseOper.second; 903 for (unsigned N = 0; IVOperand; ++N) { 904 assert(N <= Simplified.size() && "runaway iteration"); 905 (void) N; 906 907 Value *NewOper = foldIVUser(UseInst, IVOperand); 908 if (!NewOper) 909 break; // done folding 910 IVOperand = dyn_cast<Instruction>(NewOper); 911 } 912 if (!IVOperand) 913 continue; 914 915 if (eliminateIVUser(UseInst, IVOperand)) { 916 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers); 917 continue; 918 } 919 920 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) { 921 if ((isa<OverflowingBinaryOperator>(BO) && 922 strengthenOverflowingOperation(BO, IVOperand)) || 923 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) { 924 // re-queue uses of the now modified binary operator and fall 925 // through to the checks that remain. 926 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers); 927 } 928 } 929 930 // Try to use integer induction for FPToSI of float induction directly. 931 if (replaceFloatIVWithIntegerIV(UseInst)) { 932 // Re-queue the potentially new direct uses of IVOperand. 933 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers); 934 continue; 935 } 936 937 CastInst *Cast = dyn_cast<CastInst>(UseInst); 938 if (V && Cast) { 939 V->visitCast(Cast); 940 continue; 941 } 942 if (isSimpleIVUser(UseInst, L, SE)) { 943 pushIVUsers(UseInst, L, Simplified, SimpleIVUsers); 944 } 945 } 946 } 947 948 namespace llvm { 949 950 void IVVisitor::anchor() { } 951 952 /// Simplify instructions that use this induction variable 953 /// by using ScalarEvolution to analyze the IV's recurrence. 954 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT, 955 LoopInfo *LI, const TargetTransformInfo *TTI, 956 SmallVectorImpl<WeakTrackingVH> &Dead, 957 SCEVExpander &Rewriter, IVVisitor *V) { 958 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, TTI, 959 Rewriter, Dead); 960 SIV.simplifyUsers(CurrIV, V); 961 return SIV.hasChanged(); 962 } 963 964 /// Simplify users of induction variables within this 965 /// loop. This does not actually change or add IVs. 966 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, 967 LoopInfo *LI, const TargetTransformInfo *TTI, 968 SmallVectorImpl<WeakTrackingVH> &Dead) { 969 SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars"); 970 #ifndef NDEBUG 971 Rewriter.setDebugType(DEBUG_TYPE); 972 #endif 973 bool Changed = false; 974 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 975 Changed |= 976 simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, TTI, Dead, Rewriter); 977 } 978 return Changed; 979 } 980 981 } // namespace llvm 982 983 namespace { 984 //===----------------------------------------------------------------------===// 985 // Widen Induction Variables - Extend the width of an IV to cover its 986 // widest uses. 987 //===----------------------------------------------------------------------===// 988 989 class WidenIV { 990 // Parameters 991 PHINode *OrigPhi; 992 Type *WideType; 993 994 // Context 995 LoopInfo *LI; 996 Loop *L; 997 ScalarEvolution *SE; 998 DominatorTree *DT; 999 1000 // Does the module have any calls to the llvm.experimental.guard intrinsic 1001 // at all? If not we can avoid scanning instructions looking for guards. 1002 bool HasGuards; 1003 1004 bool UsePostIncrementRanges; 1005 1006 // Statistics 1007 unsigned NumElimExt = 0; 1008 unsigned NumWidened = 0; 1009 1010 // Result 1011 PHINode *WidePhi = nullptr; 1012 Instruction *WideInc = nullptr; 1013 const SCEV *WideIncExpr = nullptr; 1014 SmallVectorImpl<WeakTrackingVH> &DeadInsts; 1015 1016 SmallPtrSet<Instruction *,16> Widened; 1017 1018 enum ExtendKind { ZeroExtended, SignExtended, Unknown }; 1019 1020 // A map tracking the kind of extension used to widen each narrow IV 1021 // and narrow IV user. 1022 // Key: pointer to a narrow IV or IV user. 1023 // Value: the kind of extension used to widen this Instruction. 1024 DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap; 1025 1026 using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>; 1027 1028 // A map with control-dependent ranges for post increment IV uses. The key is 1029 // a pair of IV def and a use of this def denoting the context. The value is 1030 // a ConstantRange representing possible values of the def at the given 1031 // context. 1032 DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos; 1033 1034 Optional<ConstantRange> getPostIncRangeInfo(Value *Def, 1035 Instruction *UseI) { 1036 DefUserPair Key(Def, UseI); 1037 auto It = PostIncRangeInfos.find(Key); 1038 return It == PostIncRangeInfos.end() 1039 ? Optional<ConstantRange>(None) 1040 : Optional<ConstantRange>(It->second); 1041 } 1042 1043 void calculatePostIncRanges(PHINode *OrigPhi); 1044 void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser); 1045 1046 void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) { 1047 DefUserPair Key(Def, UseI); 1048 auto It = PostIncRangeInfos.find(Key); 1049 if (It == PostIncRangeInfos.end()) 1050 PostIncRangeInfos.insert({Key, R}); 1051 else 1052 It->second = R.intersectWith(It->second); 1053 } 1054 1055 public: 1056 /// Record a link in the Narrow IV def-use chain along with the WideIV that 1057 /// computes the same value as the Narrow IV def. This avoids caching Use* 1058 /// pointers. 1059 struct NarrowIVDefUse { 1060 Instruction *NarrowDef = nullptr; 1061 Instruction *NarrowUse = nullptr; 1062 Instruction *WideDef = nullptr; 1063 1064 // True if the narrow def is never negative. Tracking this information lets 1065 // us use a sign extension instead of a zero extension or vice versa, when 1066 // profitable and legal. 1067 bool NeverNegative = false; 1068 1069 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD, 1070 bool NeverNegative) 1071 : NarrowDef(ND), NarrowUse(NU), WideDef(WD), 1072 NeverNegative(NeverNegative) {} 1073 }; 1074 1075 WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv, 1076 DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI, 1077 bool HasGuards, bool UsePostIncrementRanges = true); 1078 1079 PHINode *createWideIV(SCEVExpander &Rewriter); 1080 1081 unsigned getNumElimExt() { return NumElimExt; }; 1082 unsigned getNumWidened() { return NumWidened; }; 1083 1084 protected: 1085 Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned, 1086 Instruction *Use); 1087 1088 Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR); 1089 Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU, 1090 const SCEVAddRecExpr *WideAR); 1091 Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU); 1092 1093 ExtendKind getExtendKind(Instruction *I); 1094 1095 using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>; 1096 1097 WidenedRecTy getWideRecurrence(NarrowIVDefUse DU); 1098 1099 WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU); 1100 1101 const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS, 1102 unsigned OpCode) const; 1103 1104 Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter); 1105 1106 bool widenLoopCompare(NarrowIVDefUse DU); 1107 bool widenWithVariantUse(NarrowIVDefUse DU); 1108 1109 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef); 1110 1111 private: 1112 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers; 1113 }; 1114 } // namespace 1115 1116 /// Determine the insertion point for this user. By default, insert immediately 1117 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the 1118 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest 1119 /// common dominator for the incoming blocks. A nullptr can be returned if no 1120 /// viable location is found: it may happen if User is a PHI and Def only comes 1121 /// to this PHI from unreachable blocks. 1122 static Instruction *getInsertPointForUses(Instruction *User, Value *Def, 1123 DominatorTree *DT, LoopInfo *LI) { 1124 PHINode *PHI = dyn_cast<PHINode>(User); 1125 if (!PHI) 1126 return User; 1127 1128 Instruction *InsertPt = nullptr; 1129 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) { 1130 if (PHI->getIncomingValue(i) != Def) 1131 continue; 1132 1133 BasicBlock *InsertBB = PHI->getIncomingBlock(i); 1134 1135 if (!DT->isReachableFromEntry(InsertBB)) 1136 continue; 1137 1138 if (!InsertPt) { 1139 InsertPt = InsertBB->getTerminator(); 1140 continue; 1141 } 1142 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB); 1143 InsertPt = InsertBB->getTerminator(); 1144 } 1145 1146 // If we have skipped all inputs, it means that Def only comes to Phi from 1147 // unreachable blocks. 1148 if (!InsertPt) 1149 return nullptr; 1150 1151 auto *DefI = dyn_cast<Instruction>(Def); 1152 if (!DefI) 1153 return InsertPt; 1154 1155 assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses"); 1156 1157 auto *L = LI->getLoopFor(DefI->getParent()); 1158 assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent()))); 1159 1160 for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom()) 1161 if (LI->getLoopFor(DTN->getBlock()) == L) 1162 return DTN->getBlock()->getTerminator(); 1163 1164 llvm_unreachable("DefI dominates InsertPt!"); 1165 } 1166 1167 WidenIV::WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv, 1168 DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI, 1169 bool HasGuards, bool UsePostIncrementRanges) 1170 : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo), 1171 L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree), 1172 HasGuards(HasGuards), UsePostIncrementRanges(UsePostIncrementRanges), 1173 DeadInsts(DI) { 1174 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV"); 1175 ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended; 1176 } 1177 1178 Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType, 1179 bool IsSigned, Instruction *Use) { 1180 // Set the debug location and conservative insertion point. 1181 IRBuilder<> Builder(Use); 1182 // Hoist the insertion point into loop preheaders as far as possible. 1183 for (const Loop *L = LI->getLoopFor(Use->getParent()); 1184 L && L->getLoopPreheader() && L->isLoopInvariant(NarrowOper); 1185 L = L->getParentLoop()) 1186 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator()); 1187 1188 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) : 1189 Builder.CreateZExt(NarrowOper, WideType); 1190 } 1191 1192 /// Instantiate a wide operation to replace a narrow operation. This only needs 1193 /// to handle operations that can evaluation to SCEVAddRec. It can safely return 1194 /// 0 for any operation we decide not to clone. 1195 Instruction *WidenIV::cloneIVUser(WidenIV::NarrowIVDefUse DU, 1196 const SCEVAddRecExpr *WideAR) { 1197 unsigned Opcode = DU.NarrowUse->getOpcode(); 1198 switch (Opcode) { 1199 default: 1200 return nullptr; 1201 case Instruction::Add: 1202 case Instruction::Mul: 1203 case Instruction::UDiv: 1204 case Instruction::Sub: 1205 return cloneArithmeticIVUser(DU, WideAR); 1206 1207 case Instruction::And: 1208 case Instruction::Or: 1209 case Instruction::Xor: 1210 case Instruction::Shl: 1211 case Instruction::LShr: 1212 case Instruction::AShr: 1213 return cloneBitwiseIVUser(DU); 1214 } 1215 } 1216 1217 Instruction *WidenIV::cloneBitwiseIVUser(WidenIV::NarrowIVDefUse DU) { 1218 Instruction *NarrowUse = DU.NarrowUse; 1219 Instruction *NarrowDef = DU.NarrowDef; 1220 Instruction *WideDef = DU.WideDef; 1221 1222 LLVM_DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n"); 1223 1224 // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything 1225 // about the narrow operand yet so must insert a [sz]ext. It is probably loop 1226 // invariant and will be folded or hoisted. If it actually comes from a 1227 // widened IV, it should be removed during a future call to widenIVUse. 1228 bool IsSigned = getExtendKind(NarrowDef) == SignExtended; 1229 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) 1230 ? WideDef 1231 : createExtendInst(NarrowUse->getOperand(0), WideType, 1232 IsSigned, NarrowUse); 1233 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) 1234 ? WideDef 1235 : createExtendInst(NarrowUse->getOperand(1), WideType, 1236 IsSigned, NarrowUse); 1237 1238 auto *NarrowBO = cast<BinaryOperator>(NarrowUse); 1239 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS, 1240 NarrowBO->getName()); 1241 IRBuilder<> Builder(NarrowUse); 1242 Builder.Insert(WideBO); 1243 WideBO->copyIRFlags(NarrowBO); 1244 return WideBO; 1245 } 1246 1247 Instruction *WidenIV::cloneArithmeticIVUser(WidenIV::NarrowIVDefUse DU, 1248 const SCEVAddRecExpr *WideAR) { 1249 Instruction *NarrowUse = DU.NarrowUse; 1250 Instruction *NarrowDef = DU.NarrowDef; 1251 Instruction *WideDef = DU.WideDef; 1252 1253 LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n"); 1254 1255 unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1; 1256 1257 // We're trying to find X such that 1258 // 1259 // Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X 1260 // 1261 // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef), 1262 // and check using SCEV if any of them are correct. 1263 1264 // Returns true if extending NonIVNarrowDef according to `SignExt` is a 1265 // correct solution to X. 1266 auto GuessNonIVOperand = [&](bool SignExt) { 1267 const SCEV *WideLHS; 1268 const SCEV *WideRHS; 1269 1270 auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) { 1271 if (SignExt) 1272 return SE->getSignExtendExpr(S, Ty); 1273 return SE->getZeroExtendExpr(S, Ty); 1274 }; 1275 1276 if (IVOpIdx == 0) { 1277 WideLHS = SE->getSCEV(WideDef); 1278 const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1)); 1279 WideRHS = GetExtend(NarrowRHS, WideType); 1280 } else { 1281 const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0)); 1282 WideLHS = GetExtend(NarrowLHS, WideType); 1283 WideRHS = SE->getSCEV(WideDef); 1284 } 1285 1286 // WideUse is "WideDef `op.wide` X" as described in the comment. 1287 const SCEV *WideUse = 1288 getSCEVByOpCode(WideLHS, WideRHS, NarrowUse->getOpcode()); 1289 1290 return WideUse == WideAR; 1291 }; 1292 1293 bool SignExtend = getExtendKind(NarrowDef) == SignExtended; 1294 if (!GuessNonIVOperand(SignExtend)) { 1295 SignExtend = !SignExtend; 1296 if (!GuessNonIVOperand(SignExtend)) 1297 return nullptr; 1298 } 1299 1300 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) 1301 ? WideDef 1302 : createExtendInst(NarrowUse->getOperand(0), WideType, 1303 SignExtend, NarrowUse); 1304 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) 1305 ? WideDef 1306 : createExtendInst(NarrowUse->getOperand(1), WideType, 1307 SignExtend, NarrowUse); 1308 1309 auto *NarrowBO = cast<BinaryOperator>(NarrowUse); 1310 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS, 1311 NarrowBO->getName()); 1312 1313 IRBuilder<> Builder(NarrowUse); 1314 Builder.Insert(WideBO); 1315 WideBO->copyIRFlags(NarrowBO); 1316 return WideBO; 1317 } 1318 1319 WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) { 1320 auto It = ExtendKindMap.find(I); 1321 assert(It != ExtendKindMap.end() && "Instruction not yet extended!"); 1322 return It->second; 1323 } 1324 1325 const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS, 1326 unsigned OpCode) const { 1327 switch (OpCode) { 1328 case Instruction::Add: 1329 return SE->getAddExpr(LHS, RHS); 1330 case Instruction::Sub: 1331 return SE->getMinusSCEV(LHS, RHS); 1332 case Instruction::Mul: 1333 return SE->getMulExpr(LHS, RHS); 1334 case Instruction::UDiv: 1335 return SE->getUDivExpr(LHS, RHS); 1336 default: 1337 llvm_unreachable("Unsupported opcode."); 1338 }; 1339 } 1340 1341 /// No-wrap operations can transfer sign extension of their result to their 1342 /// operands. Generate the SCEV value for the widened operation without 1343 /// actually modifying the IR yet. If the expression after extending the 1344 /// operands is an AddRec for this loop, return the AddRec and the kind of 1345 /// extension used. 1346 WidenIV::WidenedRecTy 1347 WidenIV::getExtendedOperandRecurrence(WidenIV::NarrowIVDefUse DU) { 1348 // Handle the common case of add<nsw/nuw> 1349 const unsigned OpCode = DU.NarrowUse->getOpcode(); 1350 // Only Add/Sub/Mul instructions supported yet. 1351 if (OpCode != Instruction::Add && OpCode != Instruction::Sub && 1352 OpCode != Instruction::Mul) 1353 return {nullptr, Unknown}; 1354 1355 // One operand (NarrowDef) has already been extended to WideDef. Now determine 1356 // if extending the other will lead to a recurrence. 1357 const unsigned ExtendOperIdx = 1358 DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0; 1359 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU"); 1360 1361 const SCEV *ExtendOperExpr = nullptr; 1362 const OverflowingBinaryOperator *OBO = 1363 cast<OverflowingBinaryOperator>(DU.NarrowUse); 1364 ExtendKind ExtKind = getExtendKind(DU.NarrowDef); 1365 if (ExtKind == SignExtended && OBO->hasNoSignedWrap()) 1366 ExtendOperExpr = SE->getSignExtendExpr( 1367 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType); 1368 else if(ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap()) 1369 ExtendOperExpr = SE->getZeroExtendExpr( 1370 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType); 1371 else 1372 return {nullptr, Unknown}; 1373 1374 // When creating this SCEV expr, don't apply the current operations NSW or NUW 1375 // flags. This instruction may be guarded by control flow that the no-wrap 1376 // behavior depends on. Non-control-equivalent instructions can be mapped to 1377 // the same SCEV expression, and it would be incorrect to transfer NSW/NUW 1378 // semantics to those operations. 1379 const SCEV *lhs = SE->getSCEV(DU.WideDef); 1380 const SCEV *rhs = ExtendOperExpr; 1381 1382 // Let's swap operands to the initial order for the case of non-commutative 1383 // operations, like SUB. See PR21014. 1384 if (ExtendOperIdx == 0) 1385 std::swap(lhs, rhs); 1386 const SCEVAddRecExpr *AddRec = 1387 dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode)); 1388 1389 if (!AddRec || AddRec->getLoop() != L) 1390 return {nullptr, Unknown}; 1391 1392 return {AddRec, ExtKind}; 1393 } 1394 1395 /// Is this instruction potentially interesting for further simplification after 1396 /// widening it's type? In other words, can the extend be safely hoisted out of 1397 /// the loop with SCEV reducing the value to a recurrence on the same loop. If 1398 /// so, return the extended recurrence and the kind of extension used. Otherwise 1399 /// return {nullptr, Unknown}. 1400 WidenIV::WidenedRecTy WidenIV::getWideRecurrence(WidenIV::NarrowIVDefUse DU) { 1401 if (!DU.NarrowUse->getType()->isIntegerTy()) 1402 return {nullptr, Unknown}; 1403 1404 const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse); 1405 if (SE->getTypeSizeInBits(NarrowExpr->getType()) >= 1406 SE->getTypeSizeInBits(WideType)) { 1407 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow 1408 // index. So don't follow this use. 1409 return {nullptr, Unknown}; 1410 } 1411 1412 const SCEV *WideExpr; 1413 ExtendKind ExtKind; 1414 if (DU.NeverNegative) { 1415 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType); 1416 if (isa<SCEVAddRecExpr>(WideExpr)) 1417 ExtKind = SignExtended; 1418 else { 1419 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType); 1420 ExtKind = ZeroExtended; 1421 } 1422 } else if (getExtendKind(DU.NarrowDef) == SignExtended) { 1423 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType); 1424 ExtKind = SignExtended; 1425 } else { 1426 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType); 1427 ExtKind = ZeroExtended; 1428 } 1429 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr); 1430 if (!AddRec || AddRec->getLoop() != L) 1431 return {nullptr, Unknown}; 1432 return {AddRec, ExtKind}; 1433 } 1434 1435 /// This IV user cannot be widened. Replace this use of the original narrow IV 1436 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV. 1437 static void truncateIVUse(WidenIV::NarrowIVDefUse DU, DominatorTree *DT, 1438 LoopInfo *LI) { 1439 auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI); 1440 if (!InsertPt) 1441 return; 1442 LLVM_DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef << " for user " 1443 << *DU.NarrowUse << "\n"); 1444 IRBuilder<> Builder(InsertPt); 1445 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType()); 1446 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc); 1447 } 1448 1449 /// If the narrow use is a compare instruction, then widen the compare 1450 // (and possibly the other operand). The extend operation is hoisted into the 1451 // loop preheader as far as possible. 1452 bool WidenIV::widenLoopCompare(WidenIV::NarrowIVDefUse DU) { 1453 ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse); 1454 if (!Cmp) 1455 return false; 1456 1457 // We can legally widen the comparison in the following two cases: 1458 // 1459 // - The signedness of the IV extension and comparison match 1460 // 1461 // - The narrow IV is always positive (and thus its sign extension is equal 1462 // to its zero extension). For instance, let's say we're zero extending 1463 // %narrow for the following use 1464 // 1465 // icmp slt i32 %narrow, %val ... (A) 1466 // 1467 // and %narrow is always positive. Then 1468 // 1469 // (A) == icmp slt i32 sext(%narrow), sext(%val) 1470 // == icmp slt i32 zext(%narrow), sext(%val) 1471 bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended; 1472 if (!(DU.NeverNegative || IsSigned == Cmp->isSigned())) 1473 return false; 1474 1475 Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0); 1476 unsigned CastWidth = SE->getTypeSizeInBits(Op->getType()); 1477 unsigned IVWidth = SE->getTypeSizeInBits(WideType); 1478 assert(CastWidth <= IVWidth && "Unexpected width while widening compare."); 1479 1480 // Widen the compare instruction. 1481 auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI); 1482 if (!InsertPt) 1483 return false; 1484 IRBuilder<> Builder(InsertPt); 1485 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1486 1487 // Widen the other operand of the compare, if necessary. 1488 if (CastWidth < IVWidth) { 1489 Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp); 1490 DU.NarrowUse->replaceUsesOfWith(Op, ExtOp); 1491 } 1492 return true; 1493 } 1494 1495 // The widenIVUse avoids generating trunc by evaluating the use as AddRec, this 1496 // will not work when: 1497 // 1) SCEV traces back to an instruction inside the loop that SCEV can not 1498 // expand, eg. add %indvar, (load %addr) 1499 // 2) SCEV finds a loop variant, eg. add %indvar, %loopvariant 1500 // While SCEV fails to avoid trunc, we can still try to use instruction 1501 // combining approach to prove trunc is not required. This can be further 1502 // extended with other instruction combining checks, but for now we handle the 1503 // following case (sub can be "add" and "mul", "nsw + sext" can be "nus + zext") 1504 // 1505 // Src: 1506 // %c = sub nsw %b, %indvar 1507 // %d = sext %c to i64 1508 // Dst: 1509 // %indvar.ext1 = sext %indvar to i64 1510 // %m = sext %b to i64 1511 // %d = sub nsw i64 %m, %indvar.ext1 1512 // Therefore, as long as the result of add/sub/mul is extended to wide type, no 1513 // trunc is required regardless of how %b is generated. This pattern is common 1514 // when calculating address in 64 bit architecture 1515 bool WidenIV::widenWithVariantUse(WidenIV::NarrowIVDefUse DU) { 1516 Instruction *NarrowUse = DU.NarrowUse; 1517 Instruction *NarrowDef = DU.NarrowDef; 1518 Instruction *WideDef = DU.WideDef; 1519 1520 // Handle the common case of add<nsw/nuw> 1521 const unsigned OpCode = NarrowUse->getOpcode(); 1522 // Only Add/Sub/Mul instructions are supported. 1523 if (OpCode != Instruction::Add && OpCode != Instruction::Sub && 1524 OpCode != Instruction::Mul) 1525 return false; 1526 1527 // The operand that is not defined by NarrowDef of DU. Let's call it the 1528 // other operand. 1529 assert((NarrowUse->getOperand(0) == NarrowDef || 1530 NarrowUse->getOperand(1) == NarrowDef) && 1531 "bad DU"); 1532 1533 const OverflowingBinaryOperator *OBO = 1534 cast<OverflowingBinaryOperator>(NarrowUse); 1535 ExtendKind ExtKind = getExtendKind(NarrowDef); 1536 bool CanSignExtend = ExtKind == SignExtended && OBO->hasNoSignedWrap(); 1537 bool CanZeroExtend = ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap(); 1538 auto AnotherOpExtKind = ExtKind; 1539 1540 // Check that all uses are either: 1541 // - narrow def (in case of we are widening the IV increment); 1542 // - single-input LCSSA Phis; 1543 // - comparison of the chosen type; 1544 // - extend of the chosen type (raison d'etre). 1545 SmallVector<Instruction *, 4> ExtUsers; 1546 SmallVector<PHINode *, 4> LCSSAPhiUsers; 1547 SmallVector<ICmpInst *, 4> ICmpUsers; 1548 for (Use &U : NarrowUse->uses()) { 1549 Instruction *User = cast<Instruction>(U.getUser()); 1550 if (User == NarrowDef) 1551 continue; 1552 if (!L->contains(User)) { 1553 auto *LCSSAPhi = cast<PHINode>(User); 1554 // Make sure there is only 1 input, so that we don't have to split 1555 // critical edges. 1556 if (LCSSAPhi->getNumOperands() != 1) 1557 return false; 1558 LCSSAPhiUsers.push_back(LCSSAPhi); 1559 continue; 1560 } 1561 if (auto *ICmp = dyn_cast<ICmpInst>(User)) { 1562 auto Pred = ICmp->getPredicate(); 1563 // We have 3 types of predicates: signed, unsigned and equality 1564 // predicates. For equality, it's legal to widen icmp for either sign and 1565 // zero extend. For sign extend, we can also do so for signed predicates, 1566 // likeweise for zero extend we can widen icmp for unsigned predicates. 1567 if (ExtKind == ZeroExtended && ICmpInst::isSigned(Pred)) 1568 return false; 1569 if (ExtKind == SignExtended && ICmpInst::isUnsigned(Pred)) 1570 return false; 1571 ICmpUsers.push_back(ICmp); 1572 continue; 1573 } 1574 if (ExtKind == SignExtended) 1575 User = dyn_cast<SExtInst>(User); 1576 else 1577 User = dyn_cast<ZExtInst>(User); 1578 if (!User || User->getType() != WideType) 1579 return false; 1580 ExtUsers.push_back(User); 1581 } 1582 if (ExtUsers.empty()) { 1583 DeadInsts.emplace_back(NarrowUse); 1584 return true; 1585 } 1586 1587 // We'll prove some facts that should be true in the context of ext users. If 1588 // there is no users, we are done now. If there are some, pick their common 1589 // dominator as context. 1590 const Instruction *CtxI = findCommonDominator(ExtUsers, *DT); 1591 1592 if (!CanSignExtend && !CanZeroExtend) { 1593 // Because InstCombine turns 'sub nuw' to 'add' losing the no-wrap flag, we 1594 // will most likely not see it. Let's try to prove it. 1595 if (OpCode != Instruction::Add) 1596 return false; 1597 if (ExtKind != ZeroExtended) 1598 return false; 1599 const SCEV *LHS = SE->getSCEV(OBO->getOperand(0)); 1600 const SCEV *RHS = SE->getSCEV(OBO->getOperand(1)); 1601 // TODO: Support case for NarrowDef = NarrowUse->getOperand(1). 1602 if (NarrowUse->getOperand(0) != NarrowDef) 1603 return false; 1604 if (!SE->isKnownNegative(RHS)) 1605 return false; 1606 bool ProvedSubNUW = SE->isKnownPredicateAt(ICmpInst::ICMP_UGE, LHS, 1607 SE->getNegativeSCEV(RHS), CtxI); 1608 if (!ProvedSubNUW) 1609 return false; 1610 // In fact, our 'add' is 'sub nuw'. We will need to widen the 2nd operand as 1611 // neg(zext(neg(op))), which is basically sext(op). 1612 AnotherOpExtKind = SignExtended; 1613 } 1614 1615 // Verifying that Defining operand is an AddRec 1616 const SCEV *Op1 = SE->getSCEV(WideDef); 1617 const SCEVAddRecExpr *AddRecOp1 = dyn_cast<SCEVAddRecExpr>(Op1); 1618 if (!AddRecOp1 || AddRecOp1->getLoop() != L) 1619 return false; 1620 1621 LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n"); 1622 1623 // Generating a widening use instruction. 1624 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) 1625 ? WideDef 1626 : createExtendInst(NarrowUse->getOperand(0), WideType, 1627 AnotherOpExtKind, NarrowUse); 1628 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) 1629 ? WideDef 1630 : createExtendInst(NarrowUse->getOperand(1), WideType, 1631 AnotherOpExtKind, NarrowUse); 1632 1633 auto *NarrowBO = cast<BinaryOperator>(NarrowUse); 1634 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS, 1635 NarrowBO->getName()); 1636 IRBuilder<> Builder(NarrowUse); 1637 Builder.Insert(WideBO); 1638 WideBO->copyIRFlags(NarrowBO); 1639 ExtendKindMap[NarrowUse] = ExtKind; 1640 1641 for (Instruction *User : ExtUsers) { 1642 assert(User->getType() == WideType && "Checked before!"); 1643 LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *User << " replaced by " 1644 << *WideBO << "\n"); 1645 ++NumElimExt; 1646 User->replaceAllUsesWith(WideBO); 1647 DeadInsts.emplace_back(User); 1648 } 1649 1650 for (PHINode *User : LCSSAPhiUsers) { 1651 assert(User->getNumOperands() == 1 && "Checked before!"); 1652 Builder.SetInsertPoint(User); 1653 auto *WidePN = 1654 Builder.CreatePHI(WideBO->getType(), 1, User->getName() + ".wide"); 1655 BasicBlock *LoopExitingBlock = User->getParent()->getSinglePredecessor(); 1656 assert(LoopExitingBlock && L->contains(LoopExitingBlock) && 1657 "Not a LCSSA Phi?"); 1658 WidePN->addIncoming(WideBO, LoopExitingBlock); 1659 Builder.SetInsertPoint(&*User->getParent()->getFirstInsertionPt()); 1660 auto *TruncPN = Builder.CreateTrunc(WidePN, User->getType()); 1661 User->replaceAllUsesWith(TruncPN); 1662 DeadInsts.emplace_back(User); 1663 } 1664 1665 for (ICmpInst *User : ICmpUsers) { 1666 Builder.SetInsertPoint(User); 1667 auto ExtendedOp = [&](Value * V)->Value * { 1668 if (V == NarrowUse) 1669 return WideBO; 1670 if (ExtKind == ZeroExtended) 1671 return Builder.CreateZExt(V, WideBO->getType()); 1672 else 1673 return Builder.CreateSExt(V, WideBO->getType()); 1674 }; 1675 auto Pred = User->getPredicate(); 1676 auto *LHS = ExtendedOp(User->getOperand(0)); 1677 auto *RHS = ExtendedOp(User->getOperand(1)); 1678 auto *WideCmp = 1679 Builder.CreateICmp(Pred, LHS, RHS, User->getName() + ".wide"); 1680 User->replaceAllUsesWith(WideCmp); 1681 DeadInsts.emplace_back(User); 1682 } 1683 1684 return true; 1685 } 1686 1687 /// Determine whether an individual user of the narrow IV can be widened. If so, 1688 /// return the wide clone of the user. 1689 Instruction *WidenIV::widenIVUse(WidenIV::NarrowIVDefUse DU, SCEVExpander &Rewriter) { 1690 assert(ExtendKindMap.count(DU.NarrowDef) && 1691 "Should already know the kind of extension used to widen NarrowDef"); 1692 1693 // Stop traversing the def-use chain at inner-loop phis or post-loop phis. 1694 if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) { 1695 if (LI->getLoopFor(UsePhi->getParent()) != L) { 1696 // For LCSSA phis, sink the truncate outside the loop. 1697 // After SimplifyCFG most loop exit targets have a single predecessor. 1698 // Otherwise fall back to a truncate within the loop. 1699 if (UsePhi->getNumOperands() != 1) 1700 truncateIVUse(DU, DT, LI); 1701 else { 1702 // Widening the PHI requires us to insert a trunc. The logical place 1703 // for this trunc is in the same BB as the PHI. This is not possible if 1704 // the BB is terminated by a catchswitch. 1705 if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator())) 1706 return nullptr; 1707 1708 PHINode *WidePhi = 1709 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide", 1710 UsePhi); 1711 WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0)); 1712 IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt()); 1713 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType()); 1714 UsePhi->replaceAllUsesWith(Trunc); 1715 DeadInsts.emplace_back(UsePhi); 1716 LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to " 1717 << *WidePhi << "\n"); 1718 } 1719 return nullptr; 1720 } 1721 } 1722 1723 // This narrow use can be widened by a sext if it's non-negative or its narrow 1724 // def was widended by a sext. Same for zext. 1725 auto canWidenBySExt = [&]() { 1726 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended; 1727 }; 1728 auto canWidenByZExt = [&]() { 1729 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended; 1730 }; 1731 1732 // Our raison d'etre! Eliminate sign and zero extension. 1733 if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) || 1734 (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) { 1735 Value *NewDef = DU.WideDef; 1736 if (DU.NarrowUse->getType() != WideType) { 1737 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType()); 1738 unsigned IVWidth = SE->getTypeSizeInBits(WideType); 1739 if (CastWidth < IVWidth) { 1740 // The cast isn't as wide as the IV, so insert a Trunc. 1741 IRBuilder<> Builder(DU.NarrowUse); 1742 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType()); 1743 } 1744 else { 1745 // A wider extend was hidden behind a narrower one. This may induce 1746 // another round of IV widening in which the intermediate IV becomes 1747 // dead. It should be very rare. 1748 LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi 1749 << " not wide enough to subsume " << *DU.NarrowUse 1750 << "\n"); 1751 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1752 NewDef = DU.NarrowUse; 1753 } 1754 } 1755 if (NewDef != DU.NarrowUse) { 1756 LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse 1757 << " replaced by " << *DU.WideDef << "\n"); 1758 ++NumElimExt; 1759 DU.NarrowUse->replaceAllUsesWith(NewDef); 1760 DeadInsts.emplace_back(DU.NarrowUse); 1761 } 1762 // Now that the extend is gone, we want to expose it's uses for potential 1763 // further simplification. We don't need to directly inform SimplifyIVUsers 1764 // of the new users, because their parent IV will be processed later as a 1765 // new loop phi. If we preserved IVUsers analysis, we would also want to 1766 // push the uses of WideDef here. 1767 1768 // No further widening is needed. The deceased [sz]ext had done it for us. 1769 return nullptr; 1770 } 1771 1772 // Does this user itself evaluate to a recurrence after widening? 1773 WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU); 1774 if (!WideAddRec.first) 1775 WideAddRec = getWideRecurrence(DU); 1776 1777 assert((WideAddRec.first == nullptr) == (WideAddRec.second == Unknown)); 1778 if (!WideAddRec.first) { 1779 // If use is a loop condition, try to promote the condition instead of 1780 // truncating the IV first. 1781 if (widenLoopCompare(DU)) 1782 return nullptr; 1783 1784 // We are here about to generate a truncate instruction that may hurt 1785 // performance because the scalar evolution expression computed earlier 1786 // in WideAddRec.first does not indicate a polynomial induction expression. 1787 // In that case, look at the operands of the use instruction to determine 1788 // if we can still widen the use instead of truncating its operand. 1789 if (widenWithVariantUse(DU)) 1790 return nullptr; 1791 1792 // This user does not evaluate to a recurrence after widening, so don't 1793 // follow it. Instead insert a Trunc to kill off the original use, 1794 // eventually isolating the original narrow IV so it can be removed. 1795 truncateIVUse(DU, DT, LI); 1796 return nullptr; 1797 } 1798 1799 // Reuse the IV increment that SCEVExpander created as long as it dominates 1800 // NarrowUse. 1801 Instruction *WideUse = nullptr; 1802 if (WideAddRec.first == WideIncExpr && 1803 Rewriter.hoistIVInc(WideInc, DU.NarrowUse)) 1804 WideUse = WideInc; 1805 else { 1806 WideUse = cloneIVUser(DU, WideAddRec.first); 1807 if (!WideUse) 1808 return nullptr; 1809 } 1810 // Evaluation of WideAddRec ensured that the narrow expression could be 1811 // extended outside the loop without overflow. This suggests that the wide use 1812 // evaluates to the same expression as the extended narrow use, but doesn't 1813 // absolutely guarantee it. Hence the following failsafe check. In rare cases 1814 // where it fails, we simply throw away the newly created wide use. 1815 if (WideAddRec.first != SE->getSCEV(WideUse)) { 1816 LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": " 1817 << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first 1818 << "\n"); 1819 DeadInsts.emplace_back(WideUse); 1820 return nullptr; 1821 } 1822 1823 // if we reached this point then we are going to replace 1824 // DU.NarrowUse with WideUse. Reattach DbgValue then. 1825 replaceAllDbgUsesWith(*DU.NarrowUse, *WideUse, *WideUse, *DT); 1826 1827 ExtendKindMap[DU.NarrowUse] = WideAddRec.second; 1828 // Returning WideUse pushes it on the worklist. 1829 return WideUse; 1830 } 1831 1832 /// Add eligible users of NarrowDef to NarrowIVUsers. 1833 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) { 1834 const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef); 1835 bool NonNegativeDef = 1836 SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV, 1837 SE->getZero(NarrowSCEV->getType())); 1838 for (User *U : NarrowDef->users()) { 1839 Instruction *NarrowUser = cast<Instruction>(U); 1840 1841 // Handle data flow merges and bizarre phi cycles. 1842 if (!Widened.insert(NarrowUser).second) 1843 continue; 1844 1845 bool NonNegativeUse = false; 1846 if (!NonNegativeDef) { 1847 // We might have a control-dependent range information for this context. 1848 if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser)) 1849 NonNegativeUse = RangeInfo->getSignedMin().isNonNegative(); 1850 } 1851 1852 NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef, 1853 NonNegativeDef || NonNegativeUse); 1854 } 1855 } 1856 1857 /// Process a single induction variable. First use the SCEVExpander to create a 1858 /// wide induction variable that evaluates to the same recurrence as the 1859 /// original narrow IV. Then use a worklist to forward traverse the narrow IV's 1860 /// def-use chain. After widenIVUse has processed all interesting IV users, the 1861 /// narrow IV will be isolated for removal by DeleteDeadPHIs. 1862 /// 1863 /// It would be simpler to delete uses as they are processed, but we must avoid 1864 /// invalidating SCEV expressions. 1865 PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) { 1866 // Is this phi an induction variable? 1867 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi)); 1868 if (!AddRec) 1869 return nullptr; 1870 1871 // Widen the induction variable expression. 1872 const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended 1873 ? SE->getSignExtendExpr(AddRec, WideType) 1874 : SE->getZeroExtendExpr(AddRec, WideType); 1875 1876 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType && 1877 "Expect the new IV expression to preserve its type"); 1878 1879 // Can the IV be extended outside the loop without overflow? 1880 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr); 1881 if (!AddRec || AddRec->getLoop() != L) 1882 return nullptr; 1883 1884 // An AddRec must have loop-invariant operands. Since this AddRec is 1885 // materialized by a loop header phi, the expression cannot have any post-loop 1886 // operands, so they must dominate the loop header. 1887 assert( 1888 SE->properlyDominates(AddRec->getStart(), L->getHeader()) && 1889 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) && 1890 "Loop header phi recurrence inputs do not dominate the loop"); 1891 1892 // Iterate over IV uses (including transitive ones) looking for IV increments 1893 // of the form 'add nsw %iv, <const>'. For each increment and each use of 1894 // the increment calculate control-dependent range information basing on 1895 // dominating conditions inside of the loop (e.g. a range check inside of the 1896 // loop). Calculated ranges are stored in PostIncRangeInfos map. 1897 // 1898 // Control-dependent range information is later used to prove that a narrow 1899 // definition is not negative (see pushNarrowIVUsers). It's difficult to do 1900 // this on demand because when pushNarrowIVUsers needs this information some 1901 // of the dominating conditions might be already widened. 1902 if (UsePostIncrementRanges) 1903 calculatePostIncRanges(OrigPhi); 1904 1905 // The rewriter provides a value for the desired IV expression. This may 1906 // either find an existing phi or materialize a new one. Either way, we 1907 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part 1908 // of the phi-SCC dominates the loop entry. 1909 Instruction *InsertPt = &*L->getHeader()->getFirstInsertionPt(); 1910 Value *ExpandInst = Rewriter.expandCodeFor(AddRec, WideType, InsertPt); 1911 // If the wide phi is not a phi node, for example a cast node, like bitcast, 1912 // inttoptr, ptrtoint, just skip for now. 1913 if (!(WidePhi = dyn_cast<PHINode>(ExpandInst))) { 1914 // if the cast node is an inserted instruction without any user, we should 1915 // remove it to make sure the pass don't touch the function as we can not 1916 // wide the phi. 1917 if (ExpandInst->hasNUses(0) && 1918 Rewriter.isInsertedInstruction(cast<Instruction>(ExpandInst))) 1919 DeadInsts.emplace_back(ExpandInst); 1920 return nullptr; 1921 } 1922 1923 // Remembering the WideIV increment generated by SCEVExpander allows 1924 // widenIVUse to reuse it when widening the narrow IV's increment. We don't 1925 // employ a general reuse mechanism because the call above is the only call to 1926 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses. 1927 if (BasicBlock *LatchBlock = L->getLoopLatch()) { 1928 WideInc = 1929 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock)); 1930 WideIncExpr = SE->getSCEV(WideInc); 1931 // Propagate the debug location associated with the original loop increment 1932 // to the new (widened) increment. 1933 auto *OrigInc = 1934 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock)); 1935 WideInc->setDebugLoc(OrigInc->getDebugLoc()); 1936 } 1937 1938 LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n"); 1939 ++NumWidened; 1940 1941 // Traverse the def-use chain using a worklist starting at the original IV. 1942 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" ); 1943 1944 Widened.insert(OrigPhi); 1945 pushNarrowIVUsers(OrigPhi, WidePhi); 1946 1947 while (!NarrowIVUsers.empty()) { 1948 WidenIV::NarrowIVDefUse DU = NarrowIVUsers.pop_back_val(); 1949 1950 // Process a def-use edge. This may replace the use, so don't hold a 1951 // use_iterator across it. 1952 Instruction *WideUse = widenIVUse(DU, Rewriter); 1953 1954 // Follow all def-use edges from the previous narrow use. 1955 if (WideUse) 1956 pushNarrowIVUsers(DU.NarrowUse, WideUse); 1957 1958 // widenIVUse may have removed the def-use edge. 1959 if (DU.NarrowDef->use_empty()) 1960 DeadInsts.emplace_back(DU.NarrowDef); 1961 } 1962 1963 // Attach any debug information to the new PHI. 1964 replaceAllDbgUsesWith(*OrigPhi, *WidePhi, *WidePhi, *DT); 1965 1966 return WidePhi; 1967 } 1968 1969 /// Calculates control-dependent range for the given def at the given context 1970 /// by looking at dominating conditions inside of the loop 1971 void WidenIV::calculatePostIncRange(Instruction *NarrowDef, 1972 Instruction *NarrowUser) { 1973 using namespace llvm::PatternMatch; 1974 1975 Value *NarrowDefLHS; 1976 const APInt *NarrowDefRHS; 1977 if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS), 1978 m_APInt(NarrowDefRHS))) || 1979 !NarrowDefRHS->isNonNegative()) 1980 return; 1981 1982 auto UpdateRangeFromCondition = [&] (Value *Condition, 1983 bool TrueDest) { 1984 CmpInst::Predicate Pred; 1985 Value *CmpRHS; 1986 if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS), 1987 m_Value(CmpRHS)))) 1988 return; 1989 1990 CmpInst::Predicate P = 1991 TrueDest ? Pred : CmpInst::getInversePredicate(Pred); 1992 1993 auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS)); 1994 auto CmpConstrainedLHSRange = 1995 ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange); 1996 auto NarrowDefRange = CmpConstrainedLHSRange.addWithNoWrap( 1997 *NarrowDefRHS, OverflowingBinaryOperator::NoSignedWrap); 1998 1999 updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange); 2000 }; 2001 2002 auto UpdateRangeFromGuards = [&](Instruction *Ctx) { 2003 if (!HasGuards) 2004 return; 2005 2006 for (Instruction &I : make_range(Ctx->getIterator().getReverse(), 2007 Ctx->getParent()->rend())) { 2008 Value *C = nullptr; 2009 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C)))) 2010 UpdateRangeFromCondition(C, /*TrueDest=*/true); 2011 } 2012 }; 2013 2014 UpdateRangeFromGuards(NarrowUser); 2015 2016 BasicBlock *NarrowUserBB = NarrowUser->getParent(); 2017 // If NarrowUserBB is statically unreachable asking dominator queries may 2018 // yield surprising results. (e.g. the block may not have a dom tree node) 2019 if (!DT->isReachableFromEntry(NarrowUserBB)) 2020 return; 2021 2022 for (auto *DTB = (*DT)[NarrowUserBB]->getIDom(); 2023 L->contains(DTB->getBlock()); 2024 DTB = DTB->getIDom()) { 2025 auto *BB = DTB->getBlock(); 2026 auto *TI = BB->getTerminator(); 2027 UpdateRangeFromGuards(TI); 2028 2029 auto *BI = dyn_cast<BranchInst>(TI); 2030 if (!BI || !BI->isConditional()) 2031 continue; 2032 2033 auto *TrueSuccessor = BI->getSuccessor(0); 2034 auto *FalseSuccessor = BI->getSuccessor(1); 2035 2036 auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) { 2037 return BBE.isSingleEdge() && 2038 DT->dominates(BBE, NarrowUser->getParent()); 2039 }; 2040 2041 if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor))) 2042 UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true); 2043 2044 if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor))) 2045 UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false); 2046 } 2047 } 2048 2049 /// Calculates PostIncRangeInfos map for the given IV 2050 void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) { 2051 SmallPtrSet<Instruction *, 16> Visited; 2052 SmallVector<Instruction *, 6> Worklist; 2053 Worklist.push_back(OrigPhi); 2054 Visited.insert(OrigPhi); 2055 2056 while (!Worklist.empty()) { 2057 Instruction *NarrowDef = Worklist.pop_back_val(); 2058 2059 for (Use &U : NarrowDef->uses()) { 2060 auto *NarrowUser = cast<Instruction>(U.getUser()); 2061 2062 // Don't go looking outside the current loop. 2063 auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()]; 2064 if (!NarrowUserLoop || !L->contains(NarrowUserLoop)) 2065 continue; 2066 2067 if (!Visited.insert(NarrowUser).second) 2068 continue; 2069 2070 Worklist.push_back(NarrowUser); 2071 2072 calculatePostIncRange(NarrowDef, NarrowUser); 2073 } 2074 } 2075 } 2076 2077 PHINode *llvm::createWideIV(const WideIVInfo &WI, 2078 LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter, 2079 DominatorTree *DT, SmallVectorImpl<WeakTrackingVH> &DeadInsts, 2080 unsigned &NumElimExt, unsigned &NumWidened, 2081 bool HasGuards, bool UsePostIncrementRanges) { 2082 WidenIV Widener(WI, LI, SE, DT, DeadInsts, HasGuards, UsePostIncrementRanges); 2083 PHINode *WidePHI = Widener.createWideIV(Rewriter); 2084 NumElimExt = Widener.getNumElimExt(); 2085 NumWidened = Widener.getNumWidened(); 2086 return WidePHI; 2087 } 2088