1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This transformation analyzes and transforms the induction variables (and 11 // computations derived from them) into simpler forms suitable for subsequent 12 // analysis and transformation. 13 // 14 // If the trip count of a loop is computable, this pass also makes the following 15 // changes: 16 // 1. The exit condition for the loop is canonicalized to compare the 17 // induction value against the exit value. This turns loops like: 18 // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)' 19 // 2. Any use outside of the loop of an expression derived from the indvar 20 // is changed to compute the derived value outside of the loop, eliminating 21 // the dependence on the exit value of the induction variable. If the only 22 // purpose of the loop is to compute the exit value of some derived 23 // expression, this transformation will make the loop dead. 24 // 25 //===----------------------------------------------------------------------===// 26 27 #include "llvm/Transforms/Scalar.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/ADT/Statistic.h" 31 #include "llvm/Analysis/LoopInfo.h" 32 #include "llvm/Analysis/LoopPass.h" 33 #include "llvm/Analysis/ScalarEvolutionExpander.h" 34 #include "llvm/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/TargetTransformInfo.h" 36 #include "llvm/IR/BasicBlock.h" 37 #include "llvm/IR/CFG.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/DataLayout.h" 40 #include "llvm/IR/Dominators.h" 41 #include "llvm/IR/Instructions.h" 42 #include "llvm/IR/IntrinsicInst.h" 43 #include "llvm/IR/LLVMContext.h" 44 #include "llvm/IR/Type.h" 45 #include "llvm/Support/CommandLine.h" 46 #include "llvm/Support/Debug.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 49 #include "llvm/Transforms/Utils/Local.h" 50 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 51 using namespace llvm; 52 53 #define DEBUG_TYPE "indvars" 54 55 STATISTIC(NumWidened , "Number of indvars widened"); 56 STATISTIC(NumReplaced , "Number of exit values replaced"); 57 STATISTIC(NumLFTR , "Number of loop exit tests replaced"); 58 STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated"); 59 STATISTIC(NumElimIV , "Number of congruent IVs eliminated"); 60 61 // Trip count verification can be enabled by default under NDEBUG if we 62 // implement a strong expression equivalence checker in SCEV. Until then, we 63 // use the verify-indvars flag, which may assert in some cases. 64 static cl::opt<bool> VerifyIndvars( 65 "verify-indvars", cl::Hidden, 66 cl::desc("Verify the ScalarEvolution result after running indvars")); 67 68 static cl::opt<bool> ReduceLiveIVs("liv-reduce", cl::Hidden, 69 cl::desc("Reduce live induction variables.")); 70 71 enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, AlwaysRepl }; 72 73 static cl::opt<ReplaceExitVal> ReplaceExitValue( 74 "replexitval", cl::Hidden, cl::init(OnlyCheapRepl), 75 cl::desc("Choose the strategy to replace exit value in IndVarSimplify"), 76 cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"), 77 clEnumValN(OnlyCheapRepl, "cheap", 78 "only replace exit value when the cost is cheap"), 79 clEnumValN(AlwaysRepl, "always", 80 "always replace exit value whenever possible"), 81 clEnumValEnd)); 82 83 namespace { 84 struct RewritePhi; 85 } 86 87 namespace { 88 class IndVarSimplify : public LoopPass { 89 LoopInfo *LI; 90 ScalarEvolution *SE; 91 DominatorTree *DT; 92 TargetLibraryInfo *TLI; 93 const TargetTransformInfo *TTI; 94 95 SmallVector<WeakVH, 16> DeadInsts; 96 bool Changed; 97 public: 98 99 static char ID; // Pass identification, replacement for typeid 100 IndVarSimplify() 101 : LoopPass(ID), LI(nullptr), SE(nullptr), DT(nullptr), Changed(false) { 102 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry()); 103 } 104 105 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 106 107 void getAnalysisUsage(AnalysisUsage &AU) const override { 108 AU.addRequired<DominatorTreeWrapperPass>(); 109 AU.addRequired<LoopInfoWrapperPass>(); 110 AU.addRequired<ScalarEvolution>(); 111 AU.addRequiredID(LoopSimplifyID); 112 AU.addRequiredID(LCSSAID); 113 AU.addPreserved<ScalarEvolution>(); 114 AU.addPreservedID(LoopSimplifyID); 115 AU.addPreservedID(LCSSAID); 116 AU.setPreservesCFG(); 117 } 118 119 private: 120 void releaseMemory() override { 121 DeadInsts.clear(); 122 } 123 124 bool isValidRewrite(Value *FromVal, Value *ToVal); 125 126 void HandleFloatingPointIV(Loop *L, PHINode *PH); 127 void RewriteNonIntegerIVs(Loop *L); 128 129 void SimplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM); 130 131 bool CanLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet); 132 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter); 133 134 Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount, 135 PHINode *IndVar, SCEVExpander &Rewriter); 136 137 void SinkUnusedInvariants(Loop *L); 138 }; 139 } 140 141 char IndVarSimplify::ID = 0; 142 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars", 143 "Induction Variable Simplification", false, false) 144 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 145 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 146 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 147 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 148 INITIALIZE_PASS_DEPENDENCY(LCSSA) 149 INITIALIZE_PASS_END(IndVarSimplify, "indvars", 150 "Induction Variable Simplification", false, false) 151 152 Pass *llvm::createIndVarSimplifyPass() { 153 return new IndVarSimplify(); 154 } 155 156 /// isValidRewrite - Return true if the SCEV expansion generated by the 157 /// rewriter can replace the original value. SCEV guarantees that it 158 /// produces the same value, but the way it is produced may be illegal IR. 159 /// Ideally, this function will only be called for verification. 160 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) { 161 // If an SCEV expression subsumed multiple pointers, its expansion could 162 // reassociate the GEP changing the base pointer. This is illegal because the 163 // final address produced by a GEP chain must be inbounds relative to its 164 // underlying object. Otherwise basic alias analysis, among other things, 165 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid 166 // producing an expression involving multiple pointers. Until then, we must 167 // bail out here. 168 // 169 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject 170 // because it understands lcssa phis while SCEV does not. 171 Value *FromPtr = FromVal; 172 Value *ToPtr = ToVal; 173 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) { 174 FromPtr = GEP->getPointerOperand(); 175 } 176 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) { 177 ToPtr = GEP->getPointerOperand(); 178 } 179 if (FromPtr != FromVal || ToPtr != ToVal) { 180 // Quickly check the common case 181 if (FromPtr == ToPtr) 182 return true; 183 184 // SCEV may have rewritten an expression that produces the GEP's pointer 185 // operand. That's ok as long as the pointer operand has the same base 186 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the 187 // base of a recurrence. This handles the case in which SCEV expansion 188 // converts a pointer type recurrence into a nonrecurrent pointer base 189 // indexed by an integer recurrence. 190 191 // If the GEP base pointer is a vector of pointers, abort. 192 if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy()) 193 return false; 194 195 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr)); 196 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr)); 197 if (FromBase == ToBase) 198 return true; 199 200 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out " 201 << *FromBase << " != " << *ToBase << "\n"); 202 203 return false; 204 } 205 return true; 206 } 207 208 /// Determine the insertion point for this user. By default, insert immediately 209 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the 210 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest 211 /// common dominator for the incoming blocks. 212 static Instruction *getInsertPointForUses(Instruction *User, Value *Def, 213 DominatorTree *DT) { 214 PHINode *PHI = dyn_cast<PHINode>(User); 215 if (!PHI) 216 return User; 217 218 Instruction *InsertPt = nullptr; 219 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) { 220 if (PHI->getIncomingValue(i) != Def) 221 continue; 222 223 BasicBlock *InsertBB = PHI->getIncomingBlock(i); 224 if (!InsertPt) { 225 InsertPt = InsertBB->getTerminator(); 226 continue; 227 } 228 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB); 229 InsertPt = InsertBB->getTerminator(); 230 } 231 assert(InsertPt && "Missing phi operand"); 232 assert((!isa<Instruction>(Def) || 233 DT->dominates(cast<Instruction>(Def), InsertPt)) && 234 "def does not dominate all uses"); 235 return InsertPt; 236 } 237 238 //===----------------------------------------------------------------------===// 239 // RewriteNonIntegerIVs and helpers. Prefer integer IVs. 240 //===----------------------------------------------------------------------===// 241 242 /// ConvertToSInt - Convert APF to an integer, if possible. 243 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) { 244 bool isExact = false; 245 // See if we can convert this to an int64_t 246 uint64_t UIntVal; 247 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero, 248 &isExact) != APFloat::opOK || !isExact) 249 return false; 250 IntVal = UIntVal; 251 return true; 252 } 253 254 /// HandleFloatingPointIV - If the loop has floating induction variable 255 /// then insert corresponding integer induction variable if possible. 256 /// For example, 257 /// for(double i = 0; i < 10000; ++i) 258 /// bar(i) 259 /// is converted into 260 /// for(int i = 0; i < 10000; ++i) 261 /// bar((double)i); 262 /// 263 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) { 264 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); 265 unsigned BackEdge = IncomingEdge^1; 266 267 // Check incoming value. 268 ConstantFP *InitValueVal = 269 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge)); 270 271 int64_t InitValue; 272 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue)) 273 return; 274 275 // Check IV increment. Reject this PN if increment operation is not 276 // an add or increment value can not be represented by an integer. 277 BinaryOperator *Incr = 278 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge)); 279 if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return; 280 281 // If this is not an add of the PHI with a constantfp, or if the constant fp 282 // is not an integer, bail out. 283 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1)); 284 int64_t IncValue; 285 if (IncValueVal == nullptr || Incr->getOperand(0) != PN || 286 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue)) 287 return; 288 289 // Check Incr uses. One user is PN and the other user is an exit condition 290 // used by the conditional terminator. 291 Value::user_iterator IncrUse = Incr->user_begin(); 292 Instruction *U1 = cast<Instruction>(*IncrUse++); 293 if (IncrUse == Incr->user_end()) return; 294 Instruction *U2 = cast<Instruction>(*IncrUse++); 295 if (IncrUse != Incr->user_end()) return; 296 297 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't 298 // only used by a branch, we can't transform it. 299 FCmpInst *Compare = dyn_cast<FCmpInst>(U1); 300 if (!Compare) 301 Compare = dyn_cast<FCmpInst>(U2); 302 if (!Compare || !Compare->hasOneUse() || 303 !isa<BranchInst>(Compare->user_back())) 304 return; 305 306 BranchInst *TheBr = cast<BranchInst>(Compare->user_back()); 307 308 // We need to verify that the branch actually controls the iteration count 309 // of the loop. If not, the new IV can overflow and no one will notice. 310 // The branch block must be in the loop and one of the successors must be out 311 // of the loop. 312 assert(TheBr->isConditional() && "Can't use fcmp if not conditional"); 313 if (!L->contains(TheBr->getParent()) || 314 (L->contains(TheBr->getSuccessor(0)) && 315 L->contains(TheBr->getSuccessor(1)))) 316 return; 317 318 319 // If it isn't a comparison with an integer-as-fp (the exit value), we can't 320 // transform it. 321 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1)); 322 int64_t ExitValue; 323 if (ExitValueVal == nullptr || 324 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue)) 325 return; 326 327 // Find new predicate for integer comparison. 328 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE; 329 switch (Compare->getPredicate()) { 330 default: return; // Unknown comparison. 331 case CmpInst::FCMP_OEQ: 332 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break; 333 case CmpInst::FCMP_ONE: 334 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break; 335 case CmpInst::FCMP_OGT: 336 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break; 337 case CmpInst::FCMP_OGE: 338 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break; 339 case CmpInst::FCMP_OLT: 340 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break; 341 case CmpInst::FCMP_OLE: 342 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break; 343 } 344 345 // We convert the floating point induction variable to a signed i32 value if 346 // we can. This is only safe if the comparison will not overflow in a way 347 // that won't be trapped by the integer equivalent operations. Check for this 348 // now. 349 // TODO: We could use i64 if it is native and the range requires it. 350 351 // The start/stride/exit values must all fit in signed i32. 352 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue)) 353 return; 354 355 // If not actually striding (add x, 0.0), avoid touching the code. 356 if (IncValue == 0) 357 return; 358 359 // Positive and negative strides have different safety conditions. 360 if (IncValue > 0) { 361 // If we have a positive stride, we require the init to be less than the 362 // exit value. 363 if (InitValue >= ExitValue) 364 return; 365 366 uint32_t Range = uint32_t(ExitValue-InitValue); 367 // Check for infinite loop, either: 368 // while (i <= Exit) or until (i > Exit) 369 if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) { 370 if (++Range == 0) return; // Range overflows. 371 } 372 373 unsigned Leftover = Range % uint32_t(IncValue); 374 375 // If this is an equality comparison, we require that the strided value 376 // exactly land on the exit value, otherwise the IV condition will wrap 377 // around and do things the fp IV wouldn't. 378 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) && 379 Leftover != 0) 380 return; 381 382 // If the stride would wrap around the i32 before exiting, we can't 383 // transform the IV. 384 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue) 385 return; 386 387 } else { 388 // If we have a negative stride, we require the init to be greater than the 389 // exit value. 390 if (InitValue <= ExitValue) 391 return; 392 393 uint32_t Range = uint32_t(InitValue-ExitValue); 394 // Check for infinite loop, either: 395 // while (i >= Exit) or until (i < Exit) 396 if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) { 397 if (++Range == 0) return; // Range overflows. 398 } 399 400 unsigned Leftover = Range % uint32_t(-IncValue); 401 402 // If this is an equality comparison, we require that the strided value 403 // exactly land on the exit value, otherwise the IV condition will wrap 404 // around and do things the fp IV wouldn't. 405 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) && 406 Leftover != 0) 407 return; 408 409 // If the stride would wrap around the i32 before exiting, we can't 410 // transform the IV. 411 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue) 412 return; 413 } 414 415 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext()); 416 417 // Insert new integer induction variable. 418 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN); 419 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue), 420 PN->getIncomingBlock(IncomingEdge)); 421 422 Value *NewAdd = 423 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue), 424 Incr->getName()+".int", Incr); 425 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge)); 426 427 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd, 428 ConstantInt::get(Int32Ty, ExitValue), 429 Compare->getName()); 430 431 // In the following deletions, PN may become dead and may be deleted. 432 // Use a WeakVH to observe whether this happens. 433 WeakVH WeakPH = PN; 434 435 // Delete the old floating point exit comparison. The branch starts using the 436 // new comparison. 437 NewCompare->takeName(Compare); 438 Compare->replaceAllUsesWith(NewCompare); 439 RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI); 440 441 // Delete the old floating point increment. 442 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType())); 443 RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI); 444 445 // If the FP induction variable still has uses, this is because something else 446 // in the loop uses its value. In order to canonicalize the induction 447 // variable, we chose to eliminate the IV and rewrite it in terms of an 448 // int->fp cast. 449 // 450 // We give preference to sitofp over uitofp because it is faster on most 451 // platforms. 452 if (WeakPH) { 453 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv", 454 PN->getParent()->getFirstInsertionPt()); 455 PN->replaceAllUsesWith(Conv); 456 RecursivelyDeleteTriviallyDeadInstructions(PN, TLI); 457 } 458 Changed = true; 459 } 460 461 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) { 462 // First step. Check to see if there are any floating-point recurrences. 463 // If there are, change them into integer recurrences, permitting analysis by 464 // the SCEV routines. 465 // 466 BasicBlock *Header = L->getHeader(); 467 468 SmallVector<WeakVH, 8> PHIs; 469 for (BasicBlock::iterator I = Header->begin(); 470 PHINode *PN = dyn_cast<PHINode>(I); ++I) 471 PHIs.push_back(PN); 472 473 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) 474 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i])) 475 HandleFloatingPointIV(L, PN); 476 477 // If the loop previously had floating-point IV, ScalarEvolution 478 // may not have been able to compute a trip count. Now that we've done some 479 // re-writing, the trip count may be computable. 480 if (Changed) 481 SE->forgetLoop(L); 482 } 483 484 namespace { 485 // Collect information about PHI nodes which can be transformed in 486 // RewriteLoopExitValues. 487 struct RewritePhi { 488 PHINode *PN; 489 unsigned Ith; // Ith incoming value. 490 Value *Val; // Exit value after expansion. 491 bool HighCost; // High Cost when expansion. 492 bool SafePhi; // LCSSASafePhiForRAUW. 493 494 RewritePhi(PHINode *P, unsigned I, Value *V, bool H, bool S) 495 : PN(P), Ith(I), Val(V), HighCost(H), SafePhi(S) {} 496 }; 497 } 498 499 //===----------------------------------------------------------------------===// 500 // RewriteLoopExitValues - Optimize IV users outside the loop. 501 // As a side effect, reduces the amount of IV processing within the loop. 502 //===----------------------------------------------------------------------===// 503 504 /// RewriteLoopExitValues - Check to see if this loop has a computable 505 /// loop-invariant execution count. If so, this means that we can compute the 506 /// final value of any expressions that are recurrent in the loop, and 507 /// substitute the exit values from the loop into any instructions outside of 508 /// the loop that use the final values of the current expressions. 509 /// 510 /// This is mostly redundant with the regular IndVarSimplify activities that 511 /// happen later, except that it's more powerful in some cases, because it's 512 /// able to brute-force evaluate arbitrary instructions as long as they have 513 /// constant operands at the beginning of the loop. 514 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) { 515 // Verify the input to the pass in already in LCSSA form. 516 assert(L->isLCSSAForm(*DT)); 517 518 SmallVector<BasicBlock*, 8> ExitBlocks; 519 L->getUniqueExitBlocks(ExitBlocks); 520 521 SmallVector<RewritePhi, 8> RewritePhiSet; 522 // Find all values that are computed inside the loop, but used outside of it. 523 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan 524 // the exit blocks of the loop to find them. 525 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 526 BasicBlock *ExitBB = ExitBlocks[i]; 527 528 // If there are no PHI nodes in this exit block, then no values defined 529 // inside the loop are used on this path, skip it. 530 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin()); 531 if (!PN) continue; 532 533 unsigned NumPreds = PN->getNumIncomingValues(); 534 535 // We would like to be able to RAUW single-incoming value PHI nodes. We 536 // have to be certain this is safe even when this is an LCSSA PHI node. 537 // While the computed exit value is no longer varying in *this* loop, the 538 // exit block may be an exit block for an outer containing loop as well, 539 // the exit value may be varying in the outer loop, and thus it may still 540 // require an LCSSA PHI node. The safe case is when this is 541 // single-predecessor PHI node (LCSSA) and the exit block containing it is 542 // part of the enclosing loop, or this is the outer most loop of the nest. 543 // In either case the exit value could (at most) be varying in the same 544 // loop body as the phi node itself. Thus if it is in turn used outside of 545 // an enclosing loop it will only be via a separate LCSSA node. 546 bool LCSSASafePhiForRAUW = 547 NumPreds == 1 && 548 (!L->getParentLoop() || L->getParentLoop() == LI->getLoopFor(ExitBB)); 549 550 // Iterate over all of the PHI nodes. 551 BasicBlock::iterator BBI = ExitBB->begin(); 552 while ((PN = dyn_cast<PHINode>(BBI++))) { 553 if (PN->use_empty()) 554 continue; // dead use, don't replace it 555 556 // SCEV only supports integer expressions for now. 557 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy()) 558 continue; 559 560 // It's necessary to tell ScalarEvolution about this explicitly so that 561 // it can walk the def-use list and forget all SCEVs, as it may not be 562 // watching the PHI itself. Once the new exit value is in place, there 563 // may not be a def-use connection between the loop and every instruction 564 // which got a SCEVAddRecExpr for that loop. 565 SE->forgetValue(PN); 566 567 // Iterate over all of the values in all the PHI nodes. 568 for (unsigned i = 0; i != NumPreds; ++i) { 569 // If the value being merged in is not integer or is not defined 570 // in the loop, skip it. 571 Value *InVal = PN->getIncomingValue(i); 572 if (!isa<Instruction>(InVal)) 573 continue; 574 575 // If this pred is for a subloop, not L itself, skip it. 576 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) 577 continue; // The Block is in a subloop, skip it. 578 579 // Check that InVal is defined in the loop. 580 Instruction *Inst = cast<Instruction>(InVal); 581 if (!L->contains(Inst)) 582 continue; 583 584 // Okay, this instruction has a user outside of the current loop 585 // and varies predictably *inside* the loop. Evaluate the value it 586 // contains when the loop exits, if possible. 587 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop()); 588 if (!SE->isLoopInvariant(ExitValue, L) || 589 !isSafeToExpand(ExitValue, *SE)) 590 continue; 591 592 // Computing the value outside of the loop brings no benefit if : 593 // - it is definitely used inside the loop in a way which can not be 594 // optimized away. 595 // - no use outside of the loop can take advantage of hoisting the 596 // computation out of the loop 597 if (ExitValue->getSCEVType()>=scMulExpr) { 598 unsigned NumHardInternalUses = 0; 599 unsigned NumSoftExternalUses = 0; 600 unsigned NumUses = 0; 601 for (auto IB = Inst->user_begin(), IE = Inst->user_end(); 602 IB != IE && NumUses <= 6; ++IB) { 603 Instruction *UseInstr = cast<Instruction>(*IB); 604 unsigned Opc = UseInstr->getOpcode(); 605 NumUses++; 606 if (L->contains(UseInstr)) { 607 if (Opc == Instruction::Call || Opc == Instruction::Ret) 608 NumHardInternalUses++; 609 } else { 610 if (Opc == Instruction::PHI) { 611 // Do not count the Phi as a use. LCSSA may have inserted 612 // plenty of trivial ones. 613 NumUses--; 614 for (auto PB = UseInstr->user_begin(), 615 PE = UseInstr->user_end(); 616 PB != PE && NumUses <= 6; ++PB, ++NumUses) { 617 unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode(); 618 if (PhiOpc != Instruction::Call && PhiOpc != Instruction::Ret) 619 NumSoftExternalUses++; 620 } 621 continue; 622 } 623 if (Opc != Instruction::Call && Opc != Instruction::Ret) 624 NumSoftExternalUses++; 625 } 626 } 627 if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses) 628 continue; 629 } 630 631 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst); 632 633 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n' 634 << " LoopVal = " << *Inst << "\n"); 635 636 if (!isValidRewrite(Inst, ExitVal)) { 637 DeadInsts.push_back(ExitVal); 638 continue; 639 } 640 bool HighCost = Rewriter.isHighCostExpansion(ExitValue, L); 641 642 // Collect all the candidate PHINodes to be rewritten. 643 RewritePhiSet.push_back( 644 RewritePhi(PN, i, ExitVal, HighCost, LCSSASafePhiForRAUW)); 645 } 646 } 647 } 648 649 bool LoopCanBeDel = CanLoopBeDeleted(L, RewritePhiSet); 650 651 // Transformation. 652 for (const RewritePhi &Phi : RewritePhiSet) { 653 PHINode *PN = Phi.PN; 654 Value *ExitVal = Phi.Val; 655 656 // Only do the rewrite when the ExitValue can be expanded cheaply. 657 // If LoopCanBeDel is true, rewrite exit value aggressively. 658 if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) { 659 DeadInsts.push_back(ExitVal); 660 continue; 661 } 662 663 Changed = true; 664 ++NumReplaced; 665 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith)); 666 PN->setIncomingValue(Phi.Ith, ExitVal); 667 668 // If this instruction is dead now, delete it. Don't do it now to avoid 669 // invalidating iterators. 670 if (isInstructionTriviallyDead(Inst, TLI)) 671 DeadInsts.push_back(Inst); 672 673 // If we determined that this PHI is safe to replace even if an LCSSA 674 // PHI, do so. 675 if (Phi.SafePhi) { 676 PN->replaceAllUsesWith(ExitVal); 677 PN->eraseFromParent(); 678 } 679 } 680 681 // The insertion point instruction may have been deleted; clear it out 682 // so that the rewriter doesn't trip over it later. 683 Rewriter.clearInsertPoint(); 684 } 685 686 /// CanLoopBeDeleted - Check whether it is possible to delete the loop after 687 /// rewriting exit value. If it is possible, ignore ReplaceExitValue and 688 /// do rewriting aggressively. 689 bool IndVarSimplify::CanLoopBeDeleted( 690 Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) { 691 692 BasicBlock *Preheader = L->getLoopPreheader(); 693 // If there is no preheader, the loop will not be deleted. 694 if (!Preheader) 695 return false; 696 697 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1. 698 // We obviate multiple ExitingBlocks case for simplicity. 699 // TODO: If we see testcase with multiple ExitingBlocks can be deleted 700 // after exit value rewriting, we can enhance the logic here. 701 SmallVector<BasicBlock *, 4> ExitingBlocks; 702 L->getExitingBlocks(ExitingBlocks); 703 SmallVector<BasicBlock *, 8> ExitBlocks; 704 L->getUniqueExitBlocks(ExitBlocks); 705 if (ExitBlocks.size() > 1 || ExitingBlocks.size() > 1) 706 return false; 707 708 BasicBlock *ExitBlock = ExitBlocks[0]; 709 BasicBlock::iterator BI = ExitBlock->begin(); 710 while (PHINode *P = dyn_cast<PHINode>(BI)) { 711 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); 712 713 // If the Incoming value of P is found in RewritePhiSet, we know it 714 // could be rewritten to use a loop invariant value in transformation 715 // phase later. Skip it in the loop invariant check below. 716 bool found = false; 717 for (const RewritePhi &Phi : RewritePhiSet) { 718 unsigned i = Phi.Ith; 719 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) { 720 found = true; 721 break; 722 } 723 } 724 725 Instruction *I; 726 if (!found && (I = dyn_cast<Instruction>(Incoming))) 727 if (!L->hasLoopInvariantOperands(I)) 728 return false; 729 730 ++BI; 731 } 732 733 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 734 LI != LE; ++LI) { 735 for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end(); BI != BE; 736 ++BI) { 737 if (BI->mayHaveSideEffects()) 738 return false; 739 } 740 } 741 742 return true; 743 } 744 745 //===----------------------------------------------------------------------===// 746 // IV Widening - Extend the width of an IV to cover its widest uses. 747 //===----------------------------------------------------------------------===// 748 749 namespace { 750 // Collect information about induction variables that are used by sign/zero 751 // extend operations. This information is recorded by CollectExtend and 752 // provides the input to WidenIV. 753 struct WideIVInfo { 754 PHINode *NarrowIV; 755 Type *WidestNativeType; // Widest integer type created [sz]ext 756 bool IsSigned; // Was a sext user seen before a zext? 757 758 WideIVInfo() : NarrowIV(nullptr), WidestNativeType(nullptr), 759 IsSigned(false) {} 760 }; 761 } 762 763 /// visitCast - Update information about the induction variable that is 764 /// extended by this sign or zero extend operation. This is used to determine 765 /// the final width of the IV before actually widening it. 766 static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE, 767 const TargetTransformInfo *TTI) { 768 bool IsSigned = Cast->getOpcode() == Instruction::SExt; 769 if (!IsSigned && Cast->getOpcode() != Instruction::ZExt) 770 return; 771 772 Type *Ty = Cast->getType(); 773 uint64_t Width = SE->getTypeSizeInBits(Ty); 774 if (!Cast->getModule()->getDataLayout().isLegalInteger(Width)) 775 return; 776 777 // Cast is either an sext or zext up to this point. 778 // We should not widen an indvar if arithmetics on the wider indvar are more 779 // expensive than those on the narrower indvar. We check only the cost of ADD 780 // because at least an ADD is required to increment the induction variable. We 781 // could compute more comprehensively the cost of all instructions on the 782 // induction variable when necessary. 783 if (TTI && 784 TTI->getArithmeticInstrCost(Instruction::Add, Ty) > 785 TTI->getArithmeticInstrCost(Instruction::Add, 786 Cast->getOperand(0)->getType())) { 787 return; 788 } 789 790 if (!WI.WidestNativeType) { 791 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty); 792 WI.IsSigned = IsSigned; 793 return; 794 } 795 796 // We extend the IV to satisfy the sign of its first user, arbitrarily. 797 if (WI.IsSigned != IsSigned) 798 return; 799 800 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType)) 801 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty); 802 } 803 804 namespace { 805 806 /// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the 807 /// WideIV that computes the same value as the Narrow IV def. This avoids 808 /// caching Use* pointers. 809 struct NarrowIVDefUse { 810 Instruction *NarrowDef; 811 Instruction *NarrowUse; 812 Instruction *WideDef; 813 814 NarrowIVDefUse(): NarrowDef(nullptr), NarrowUse(nullptr), WideDef(nullptr) {} 815 816 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD): 817 NarrowDef(ND), NarrowUse(NU), WideDef(WD) {} 818 }; 819 820 /// WidenIV - The goal of this transform is to remove sign and zero extends 821 /// without creating any new induction variables. To do this, it creates a new 822 /// phi of the wider type and redirects all users, either removing extends or 823 /// inserting truncs whenever we stop propagating the type. 824 /// 825 class WidenIV { 826 // Parameters 827 PHINode *OrigPhi; 828 Type *WideType; 829 bool IsSigned; 830 831 // Context 832 LoopInfo *LI; 833 Loop *L; 834 ScalarEvolution *SE; 835 DominatorTree *DT; 836 837 // Result 838 PHINode *WidePhi; 839 Instruction *WideInc; 840 const SCEV *WideIncExpr; 841 SmallVectorImpl<WeakVH> &DeadInsts; 842 843 SmallPtrSet<Instruction*,16> Widened; 844 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers; 845 846 public: 847 WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, 848 ScalarEvolution *SEv, DominatorTree *DTree, 849 SmallVectorImpl<WeakVH> &DI) : 850 OrigPhi(WI.NarrowIV), 851 WideType(WI.WidestNativeType), 852 IsSigned(WI.IsSigned), 853 LI(LInfo), 854 L(LI->getLoopFor(OrigPhi->getParent())), 855 SE(SEv), 856 DT(DTree), 857 WidePhi(nullptr), 858 WideInc(nullptr), 859 WideIncExpr(nullptr), 860 DeadInsts(DI) { 861 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV"); 862 } 863 864 PHINode *CreateWideIV(SCEVExpander &Rewriter); 865 866 protected: 867 Value *getExtend(Value *NarrowOper, Type *WideType, bool IsSigned, 868 Instruction *Use); 869 870 Instruction *CloneIVUser(NarrowIVDefUse DU); 871 872 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse); 873 874 const SCEVAddRecExpr* GetExtendedOperandRecurrence(NarrowIVDefUse DU); 875 876 const SCEV *GetSCEVByOpCode(const SCEV *LHS, const SCEV *RHS, 877 unsigned OpCode) const; 878 879 Instruction *WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter); 880 881 bool WidenLoopCompare(NarrowIVDefUse DU); 882 883 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef); 884 }; 885 } // anonymous namespace 886 887 /// isLoopInvariant - Perform a quick domtree based check for loop invariance 888 /// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems 889 /// gratuitous for this purpose. 890 static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) { 891 Instruction *Inst = dyn_cast<Instruction>(V); 892 if (!Inst) 893 return true; 894 895 return DT->properlyDominates(Inst->getParent(), L->getHeader()); 896 } 897 898 Value *WidenIV::getExtend(Value *NarrowOper, Type *WideType, bool IsSigned, 899 Instruction *Use) { 900 // Set the debug location and conservative insertion point. 901 IRBuilder<> Builder(Use); 902 // Hoist the insertion point into loop preheaders as far as possible. 903 for (const Loop *L = LI->getLoopFor(Use->getParent()); 904 L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT); 905 L = L->getParentLoop()) 906 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator()); 907 908 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) : 909 Builder.CreateZExt(NarrowOper, WideType); 910 } 911 912 /// CloneIVUser - Instantiate a wide operation to replace a narrow 913 /// operation. This only needs to handle operations that can evaluation to 914 /// SCEVAddRec. It can safely return 0 for any operation we decide not to clone. 915 Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) { 916 unsigned Opcode = DU.NarrowUse->getOpcode(); 917 switch (Opcode) { 918 default: 919 return nullptr; 920 case Instruction::Add: 921 case Instruction::Mul: 922 case Instruction::UDiv: 923 case Instruction::Sub: 924 case Instruction::And: 925 case Instruction::Or: 926 case Instruction::Xor: 927 case Instruction::Shl: 928 case Instruction::LShr: 929 case Instruction::AShr: 930 DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n"); 931 932 // Replace NarrowDef operands with WideDef. Otherwise, we don't know 933 // anything about the narrow operand yet so must insert a [sz]ext. It is 934 // probably loop invariant and will be folded or hoisted. If it actually 935 // comes from a widened IV, it should be removed during a future call to 936 // WidenIVUse. 937 Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef : 938 getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, DU.NarrowUse); 939 Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef : 940 getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, DU.NarrowUse); 941 942 BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse); 943 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), 944 LHS, RHS, 945 NarrowBO->getName()); 946 IRBuilder<> Builder(DU.NarrowUse); 947 Builder.Insert(WideBO); 948 if (const OverflowingBinaryOperator *OBO = 949 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) { 950 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap(); 951 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap(); 952 } 953 return WideBO; 954 } 955 } 956 957 const SCEV *WidenIV::GetSCEVByOpCode(const SCEV *LHS, const SCEV *RHS, 958 unsigned OpCode) const { 959 if (OpCode == Instruction::Add) 960 return SE->getAddExpr(LHS, RHS); 961 if (OpCode == Instruction::Sub) 962 return SE->getMinusSCEV(LHS, RHS); 963 if (OpCode == Instruction::Mul) 964 return SE->getMulExpr(LHS, RHS); 965 966 llvm_unreachable("Unsupported opcode."); 967 } 968 969 /// No-wrap operations can transfer sign extension of their result to their 970 /// operands. Generate the SCEV value for the widened operation without 971 /// actually modifying the IR yet. If the expression after extending the 972 /// operands is an AddRec for this loop, return it. 973 const SCEVAddRecExpr* WidenIV::GetExtendedOperandRecurrence(NarrowIVDefUse DU) { 974 975 // Handle the common case of add<nsw/nuw> 976 const unsigned OpCode = DU.NarrowUse->getOpcode(); 977 // Only Add/Sub/Mul instructions supported yet. 978 if (OpCode != Instruction::Add && OpCode != Instruction::Sub && 979 OpCode != Instruction::Mul) 980 return nullptr; 981 982 // One operand (NarrowDef) has already been extended to WideDef. Now determine 983 // if extending the other will lead to a recurrence. 984 const unsigned ExtendOperIdx = 985 DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0; 986 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU"); 987 988 const SCEV *ExtendOperExpr = nullptr; 989 const OverflowingBinaryOperator *OBO = 990 cast<OverflowingBinaryOperator>(DU.NarrowUse); 991 if (IsSigned && OBO->hasNoSignedWrap()) 992 ExtendOperExpr = SE->getSignExtendExpr( 993 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType); 994 else if(!IsSigned && OBO->hasNoUnsignedWrap()) 995 ExtendOperExpr = SE->getZeroExtendExpr( 996 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType); 997 else 998 return nullptr; 999 1000 // When creating this SCEV expr, don't apply the current operations NSW or NUW 1001 // flags. This instruction may be guarded by control flow that the no-wrap 1002 // behavior depends on. Non-control-equivalent instructions can be mapped to 1003 // the same SCEV expression, and it would be incorrect to transfer NSW/NUW 1004 // semantics to those operations. 1005 const SCEV *lhs = SE->getSCEV(DU.WideDef); 1006 const SCEV *rhs = ExtendOperExpr; 1007 1008 // Let's swap operands to the initial order for the case of non-commutative 1009 // operations, like SUB. See PR21014. 1010 if (ExtendOperIdx == 0) 1011 std::swap(lhs, rhs); 1012 const SCEVAddRecExpr *AddRec = 1013 dyn_cast<SCEVAddRecExpr>(GetSCEVByOpCode(lhs, rhs, OpCode)); 1014 1015 if (!AddRec || AddRec->getLoop() != L) 1016 return nullptr; 1017 return AddRec; 1018 } 1019 1020 /// GetWideRecurrence - Is this instruction potentially interesting for further 1021 /// simplification after widening it's type? In other words, can the 1022 /// extend be safely hoisted out of the loop with SCEV reducing the value to a 1023 /// recurrence on the same loop. If so, return the sign or zero extended 1024 /// recurrence. Otherwise return NULL. 1025 const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) { 1026 if (!SE->isSCEVable(NarrowUse->getType())) 1027 return nullptr; 1028 1029 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse); 1030 if (SE->getTypeSizeInBits(NarrowExpr->getType()) 1031 >= SE->getTypeSizeInBits(WideType)) { 1032 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow 1033 // index. So don't follow this use. 1034 return nullptr; 1035 } 1036 1037 const SCEV *WideExpr = IsSigned ? 1038 SE->getSignExtendExpr(NarrowExpr, WideType) : 1039 SE->getZeroExtendExpr(NarrowExpr, WideType); 1040 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr); 1041 if (!AddRec || AddRec->getLoop() != L) 1042 return nullptr; 1043 return AddRec; 1044 } 1045 1046 /// This IV user cannot be widen. Replace this use of the original narrow IV 1047 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV. 1048 static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT) { 1049 DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef 1050 << " for user " << *DU.NarrowUse << "\n"); 1051 IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT)); 1052 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType()); 1053 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc); 1054 } 1055 1056 /// If the narrow use is a compare instruction, then widen the compare 1057 // (and possibly the other operand). The extend operation is hoisted into the 1058 // loop preheader as far as possible. 1059 bool WidenIV::WidenLoopCompare(NarrowIVDefUse DU) { 1060 ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse); 1061 if (!Cmp) 1062 return false; 1063 1064 // Sign of IV user and compare must match. 1065 if (IsSigned != CmpInst::isSigned(Cmp->getPredicate())) 1066 return false; 1067 1068 Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0); 1069 unsigned CastWidth = SE->getTypeSizeInBits(Op->getType()); 1070 unsigned IVWidth = SE->getTypeSizeInBits(WideType); 1071 assert (CastWidth <= IVWidth && "Unexpected width while widening compare."); 1072 1073 // Widen the compare instruction. 1074 IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT)); 1075 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1076 1077 // Widen the other operand of the compare, if necessary. 1078 if (CastWidth < IVWidth) { 1079 Value *ExtOp = getExtend(Op, WideType, IsSigned, Cmp); 1080 DU.NarrowUse->replaceUsesOfWith(Op, ExtOp); 1081 } 1082 return true; 1083 } 1084 1085 /// WidenIVUse - Determine whether an individual user of the narrow IV can be 1086 /// widened. If so, return the wide clone of the user. 1087 Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) { 1088 1089 // Stop traversing the def-use chain at inner-loop phis or post-loop phis. 1090 if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) { 1091 if (LI->getLoopFor(UsePhi->getParent()) != L) { 1092 // For LCSSA phis, sink the truncate outside the loop. 1093 // After SimplifyCFG most loop exit targets have a single predecessor. 1094 // Otherwise fall back to a truncate within the loop. 1095 if (UsePhi->getNumOperands() != 1) 1096 truncateIVUse(DU, DT); 1097 else { 1098 PHINode *WidePhi = 1099 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide", 1100 UsePhi); 1101 WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0)); 1102 IRBuilder<> Builder(WidePhi->getParent()->getFirstInsertionPt()); 1103 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType()); 1104 UsePhi->replaceAllUsesWith(Trunc); 1105 DeadInsts.emplace_back(UsePhi); 1106 DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi 1107 << " to " << *WidePhi << "\n"); 1108 } 1109 return nullptr; 1110 } 1111 } 1112 // Our raison d'etre! Eliminate sign and zero extension. 1113 if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) { 1114 Value *NewDef = DU.WideDef; 1115 if (DU.NarrowUse->getType() != WideType) { 1116 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType()); 1117 unsigned IVWidth = SE->getTypeSizeInBits(WideType); 1118 if (CastWidth < IVWidth) { 1119 // The cast isn't as wide as the IV, so insert a Trunc. 1120 IRBuilder<> Builder(DU.NarrowUse); 1121 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType()); 1122 } 1123 else { 1124 // A wider extend was hidden behind a narrower one. This may induce 1125 // another round of IV widening in which the intermediate IV becomes 1126 // dead. It should be very rare. 1127 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi 1128 << " not wide enough to subsume " << *DU.NarrowUse << "\n"); 1129 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1130 NewDef = DU.NarrowUse; 1131 } 1132 } 1133 if (NewDef != DU.NarrowUse) { 1134 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse 1135 << " replaced by " << *DU.WideDef << "\n"); 1136 ++NumElimExt; 1137 DU.NarrowUse->replaceAllUsesWith(NewDef); 1138 DeadInsts.emplace_back(DU.NarrowUse); 1139 } 1140 // Now that the extend is gone, we want to expose it's uses for potential 1141 // further simplification. We don't need to directly inform SimplifyIVUsers 1142 // of the new users, because their parent IV will be processed later as a 1143 // new loop phi. If we preserved IVUsers analysis, we would also want to 1144 // push the uses of WideDef here. 1145 1146 // No further widening is needed. The deceased [sz]ext had done it for us. 1147 return nullptr; 1148 } 1149 1150 // Does this user itself evaluate to a recurrence after widening? 1151 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse); 1152 if (!WideAddRec) 1153 WideAddRec = GetExtendedOperandRecurrence(DU); 1154 1155 if (!WideAddRec) { 1156 // If use is a loop condition, try to promote the condition instead of 1157 // truncating the IV first. 1158 if (WidenLoopCompare(DU)) 1159 return nullptr; 1160 1161 // This user does not evaluate to a recurence after widening, so don't 1162 // follow it. Instead insert a Trunc to kill off the original use, 1163 // eventually isolating the original narrow IV so it can be removed. 1164 truncateIVUse(DU, DT); 1165 return nullptr; 1166 } 1167 // Assume block terminators cannot evaluate to a recurrence. We can't to 1168 // insert a Trunc after a terminator if there happens to be a critical edge. 1169 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() && 1170 "SCEV is not expected to evaluate a block terminator"); 1171 1172 // Reuse the IV increment that SCEVExpander created as long as it dominates 1173 // NarrowUse. 1174 Instruction *WideUse = nullptr; 1175 if (WideAddRec == WideIncExpr 1176 && Rewriter.hoistIVInc(WideInc, DU.NarrowUse)) 1177 WideUse = WideInc; 1178 else { 1179 WideUse = CloneIVUser(DU); 1180 if (!WideUse) 1181 return nullptr; 1182 } 1183 // Evaluation of WideAddRec ensured that the narrow expression could be 1184 // extended outside the loop without overflow. This suggests that the wide use 1185 // evaluates to the same expression as the extended narrow use, but doesn't 1186 // absolutely guarantee it. Hence the following failsafe check. In rare cases 1187 // where it fails, we simply throw away the newly created wide use. 1188 if (WideAddRec != SE->getSCEV(WideUse)) { 1189 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse 1190 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n"); 1191 DeadInsts.emplace_back(WideUse); 1192 return nullptr; 1193 } 1194 1195 // Returning WideUse pushes it on the worklist. 1196 return WideUse; 1197 } 1198 1199 /// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers. 1200 /// 1201 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) { 1202 for (User *U : NarrowDef->users()) { 1203 Instruction *NarrowUser = cast<Instruction>(U); 1204 1205 // Handle data flow merges and bizarre phi cycles. 1206 if (!Widened.insert(NarrowUser).second) 1207 continue; 1208 1209 NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUser, WideDef)); 1210 } 1211 } 1212 1213 /// CreateWideIV - Process a single induction variable. First use the 1214 /// SCEVExpander to create a wide induction variable that evaluates to the same 1215 /// recurrence as the original narrow IV. Then use a worklist to forward 1216 /// traverse the narrow IV's def-use chain. After WidenIVUse has processed all 1217 /// interesting IV users, the narrow IV will be isolated for removal by 1218 /// DeleteDeadPHIs. 1219 /// 1220 /// It would be simpler to delete uses as they are processed, but we must avoid 1221 /// invalidating SCEV expressions. 1222 /// 1223 PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) { 1224 // Is this phi an induction variable? 1225 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi)); 1226 if (!AddRec) 1227 return nullptr; 1228 1229 // Widen the induction variable expression. 1230 const SCEV *WideIVExpr = IsSigned ? 1231 SE->getSignExtendExpr(AddRec, WideType) : 1232 SE->getZeroExtendExpr(AddRec, WideType); 1233 1234 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType && 1235 "Expect the new IV expression to preserve its type"); 1236 1237 // Can the IV be extended outside the loop without overflow? 1238 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr); 1239 if (!AddRec || AddRec->getLoop() != L) 1240 return nullptr; 1241 1242 // An AddRec must have loop-invariant operands. Since this AddRec is 1243 // materialized by a loop header phi, the expression cannot have any post-loop 1244 // operands, so they must dominate the loop header. 1245 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) && 1246 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) 1247 && "Loop header phi recurrence inputs do not dominate the loop"); 1248 1249 // The rewriter provides a value for the desired IV expression. This may 1250 // either find an existing phi or materialize a new one. Either way, we 1251 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part 1252 // of the phi-SCC dominates the loop entry. 1253 Instruction *InsertPt = L->getHeader()->begin(); 1254 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt)); 1255 1256 // Remembering the WideIV increment generated by SCEVExpander allows 1257 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't 1258 // employ a general reuse mechanism because the call above is the only call to 1259 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses. 1260 if (BasicBlock *LatchBlock = L->getLoopLatch()) { 1261 WideInc = 1262 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock)); 1263 WideIncExpr = SE->getSCEV(WideInc); 1264 } 1265 1266 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n"); 1267 ++NumWidened; 1268 1269 // Traverse the def-use chain using a worklist starting at the original IV. 1270 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" ); 1271 1272 Widened.insert(OrigPhi); 1273 pushNarrowIVUsers(OrigPhi, WidePhi); 1274 1275 while (!NarrowIVUsers.empty()) { 1276 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val(); 1277 1278 // Process a def-use edge. This may replace the use, so don't hold a 1279 // use_iterator across it. 1280 Instruction *WideUse = WidenIVUse(DU, Rewriter); 1281 1282 // Follow all def-use edges from the previous narrow use. 1283 if (WideUse) 1284 pushNarrowIVUsers(DU.NarrowUse, WideUse); 1285 1286 // WidenIVUse may have removed the def-use edge. 1287 if (DU.NarrowDef->use_empty()) 1288 DeadInsts.emplace_back(DU.NarrowDef); 1289 } 1290 return WidePhi; 1291 } 1292 1293 //===----------------------------------------------------------------------===// 1294 // Live IV Reduction - Minimize IVs live across the loop. 1295 //===----------------------------------------------------------------------===// 1296 1297 1298 //===----------------------------------------------------------------------===// 1299 // Simplification of IV users based on SCEV evaluation. 1300 //===----------------------------------------------------------------------===// 1301 1302 namespace { 1303 class IndVarSimplifyVisitor : public IVVisitor { 1304 ScalarEvolution *SE; 1305 const TargetTransformInfo *TTI; 1306 PHINode *IVPhi; 1307 1308 public: 1309 WideIVInfo WI; 1310 1311 IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV, 1312 const TargetTransformInfo *TTI, 1313 const DominatorTree *DTree) 1314 : SE(SCEV), TTI(TTI), IVPhi(IV) { 1315 DT = DTree; 1316 WI.NarrowIV = IVPhi; 1317 if (ReduceLiveIVs) 1318 setSplitOverflowIntrinsics(); 1319 } 1320 1321 // Implement the interface used by simplifyUsersOfIV. 1322 void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); } 1323 }; 1324 } 1325 1326 /// SimplifyAndExtend - Iteratively perform simplification on a worklist of IV 1327 /// users. Each successive simplification may push more users which may 1328 /// themselves be candidates for simplification. 1329 /// 1330 /// Sign/Zero extend elimination is interleaved with IV simplification. 1331 /// 1332 void IndVarSimplify::SimplifyAndExtend(Loop *L, 1333 SCEVExpander &Rewriter, 1334 LPPassManager &LPM) { 1335 SmallVector<WideIVInfo, 8> WideIVs; 1336 1337 SmallVector<PHINode*, 8> LoopPhis; 1338 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 1339 LoopPhis.push_back(cast<PHINode>(I)); 1340 } 1341 // Each round of simplification iterates through the SimplifyIVUsers worklist 1342 // for all current phis, then determines whether any IVs can be 1343 // widened. Widening adds new phis to LoopPhis, inducing another round of 1344 // simplification on the wide IVs. 1345 while (!LoopPhis.empty()) { 1346 // Evaluate as many IV expressions as possible before widening any IVs. This 1347 // forces SCEV to set no-wrap flags before evaluating sign/zero 1348 // extension. The first time SCEV attempts to normalize sign/zero extension, 1349 // the result becomes final. So for the most predictable results, we delay 1350 // evaluation of sign/zero extend evaluation until needed, and avoid running 1351 // other SCEV based analysis prior to SimplifyAndExtend. 1352 do { 1353 PHINode *CurrIV = LoopPhis.pop_back_val(); 1354 1355 // Information about sign/zero extensions of CurrIV. 1356 IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT); 1357 1358 Changed |= simplifyUsersOfIV(CurrIV, SE, &LPM, DeadInsts, &Visitor); 1359 1360 if (Visitor.WI.WidestNativeType) { 1361 WideIVs.push_back(Visitor.WI); 1362 } 1363 } while(!LoopPhis.empty()); 1364 1365 for (; !WideIVs.empty(); WideIVs.pop_back()) { 1366 WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts); 1367 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) { 1368 Changed = true; 1369 LoopPhis.push_back(WidePhi); 1370 } 1371 } 1372 } 1373 } 1374 1375 //===----------------------------------------------------------------------===// 1376 // LinearFunctionTestReplace and its kin. Rewrite the loop exit condition. 1377 //===----------------------------------------------------------------------===// 1378 1379 /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken 1380 /// count expression can be safely and cheaply expanded into an instruction 1381 /// sequence that can be used by LinearFunctionTestReplace. 1382 /// 1383 /// TODO: This fails for pointer-type loop counters with greater than one byte 1384 /// strides, consequently preventing LFTR from running. For the purpose of LFTR 1385 /// we could skip this check in the case that the LFTR loop counter (chosen by 1386 /// FindLoopCounter) is also pointer type. Instead, we could directly convert 1387 /// the loop test to an inequality test by checking the target data's alignment 1388 /// of element types (given that the initial pointer value originates from or is 1389 /// used by ABI constrained operation, as opposed to inttoptr/ptrtoint). 1390 /// However, we don't yet have a strong motivation for converting loop tests 1391 /// into inequality tests. 1392 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE, 1393 SCEVExpander &Rewriter) { 1394 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L); 1395 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) || 1396 BackedgeTakenCount->isZero()) 1397 return false; 1398 1399 if (!L->getExitingBlock()) 1400 return false; 1401 1402 // Can't rewrite non-branch yet. 1403 if (!isa<BranchInst>(L->getExitingBlock()->getTerminator())) 1404 return false; 1405 1406 if (Rewriter.isHighCostExpansion(BackedgeTakenCount, L)) 1407 return false; 1408 1409 return true; 1410 } 1411 1412 /// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop 1413 /// invariant value to the phi. 1414 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) { 1415 Instruction *IncI = dyn_cast<Instruction>(IncV); 1416 if (!IncI) 1417 return nullptr; 1418 1419 switch (IncI->getOpcode()) { 1420 case Instruction::Add: 1421 case Instruction::Sub: 1422 break; 1423 case Instruction::GetElementPtr: 1424 // An IV counter must preserve its type. 1425 if (IncI->getNumOperands() == 2) 1426 break; 1427 default: 1428 return nullptr; 1429 } 1430 1431 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0)); 1432 if (Phi && Phi->getParent() == L->getHeader()) { 1433 if (isLoopInvariant(IncI->getOperand(1), L, DT)) 1434 return Phi; 1435 return nullptr; 1436 } 1437 if (IncI->getOpcode() == Instruction::GetElementPtr) 1438 return nullptr; 1439 1440 // Allow add/sub to be commuted. 1441 Phi = dyn_cast<PHINode>(IncI->getOperand(1)); 1442 if (Phi && Phi->getParent() == L->getHeader()) { 1443 if (isLoopInvariant(IncI->getOperand(0), L, DT)) 1444 return Phi; 1445 } 1446 return nullptr; 1447 } 1448 1449 /// Return the compare guarding the loop latch, or NULL for unrecognized tests. 1450 static ICmpInst *getLoopTest(Loop *L) { 1451 assert(L->getExitingBlock() && "expected loop exit"); 1452 1453 BasicBlock *LatchBlock = L->getLoopLatch(); 1454 // Don't bother with LFTR if the loop is not properly simplified. 1455 if (!LatchBlock) 1456 return nullptr; 1457 1458 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1459 assert(BI && "expected exit branch"); 1460 1461 return dyn_cast<ICmpInst>(BI->getCondition()); 1462 } 1463 1464 /// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show 1465 /// that the current exit test is already sufficiently canonical. 1466 static bool needsLFTR(Loop *L, DominatorTree *DT) { 1467 // Do LFTR to simplify the exit condition to an ICMP. 1468 ICmpInst *Cond = getLoopTest(L); 1469 if (!Cond) 1470 return true; 1471 1472 // Do LFTR to simplify the exit ICMP to EQ/NE 1473 ICmpInst::Predicate Pred = Cond->getPredicate(); 1474 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ) 1475 return true; 1476 1477 // Look for a loop invariant RHS 1478 Value *LHS = Cond->getOperand(0); 1479 Value *RHS = Cond->getOperand(1); 1480 if (!isLoopInvariant(RHS, L, DT)) { 1481 if (!isLoopInvariant(LHS, L, DT)) 1482 return true; 1483 std::swap(LHS, RHS); 1484 } 1485 // Look for a simple IV counter LHS 1486 PHINode *Phi = dyn_cast<PHINode>(LHS); 1487 if (!Phi) 1488 Phi = getLoopPhiForCounter(LHS, L, DT); 1489 1490 if (!Phi) 1491 return true; 1492 1493 // Do LFTR if PHI node is defined in the loop, but is *not* a counter. 1494 int Idx = Phi->getBasicBlockIndex(L->getLoopLatch()); 1495 if (Idx < 0) 1496 return true; 1497 1498 // Do LFTR if the exit condition's IV is *not* a simple counter. 1499 Value *IncV = Phi->getIncomingValue(Idx); 1500 return Phi != getLoopPhiForCounter(IncV, L, DT); 1501 } 1502 1503 /// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils 1504 /// down to checking that all operands are constant and listing instructions 1505 /// that may hide undef. 1506 static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited, 1507 unsigned Depth) { 1508 if (isa<Constant>(V)) 1509 return !isa<UndefValue>(V); 1510 1511 if (Depth >= 6) 1512 return false; 1513 1514 // Conservatively handle non-constant non-instructions. For example, Arguments 1515 // may be undef. 1516 Instruction *I = dyn_cast<Instruction>(V); 1517 if (!I) 1518 return false; 1519 1520 // Load and return values may be undef. 1521 if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I)) 1522 return false; 1523 1524 // Optimistically handle other instructions. 1525 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) { 1526 if (!Visited.insert(*OI).second) 1527 continue; 1528 if (!hasConcreteDefImpl(*OI, Visited, Depth+1)) 1529 return false; 1530 } 1531 return true; 1532 } 1533 1534 /// Return true if the given value is concrete. We must prove that undef can 1535 /// never reach it. 1536 /// 1537 /// TODO: If we decide that this is a good approach to checking for undef, we 1538 /// may factor it into a common location. 1539 static bool hasConcreteDef(Value *V) { 1540 SmallPtrSet<Value*, 8> Visited; 1541 Visited.insert(V); 1542 return hasConcreteDefImpl(V, Visited, 0); 1543 } 1544 1545 /// AlmostDeadIV - Return true if this IV has any uses other than the (soon to 1546 /// be rewritten) loop exit test. 1547 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) { 1548 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock); 1549 Value *IncV = Phi->getIncomingValue(LatchIdx); 1550 1551 for (User *U : Phi->users()) 1552 if (U != Cond && U != IncV) return false; 1553 1554 for (User *U : IncV->users()) 1555 if (U != Cond && U != Phi) return false; 1556 return true; 1557 } 1558 1559 /// FindLoopCounter - Find an affine IV in canonical form. 1560 /// 1561 /// BECount may be an i8* pointer type. The pointer difference is already 1562 /// valid count without scaling the address stride, so it remains a pointer 1563 /// expression as far as SCEV is concerned. 1564 /// 1565 /// Currently only valid for LFTR. See the comments on hasConcreteDef below. 1566 /// 1567 /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount 1568 /// 1569 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride. 1570 /// This is difficult in general for SCEV because of potential overflow. But we 1571 /// could at least handle constant BECounts. 1572 static PHINode *FindLoopCounter(Loop *L, const SCEV *BECount, 1573 ScalarEvolution *SE, DominatorTree *DT) { 1574 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType()); 1575 1576 Value *Cond = 1577 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition(); 1578 1579 // Loop over all of the PHI nodes, looking for a simple counter. 1580 PHINode *BestPhi = nullptr; 1581 const SCEV *BestInit = nullptr; 1582 BasicBlock *LatchBlock = L->getLoopLatch(); 1583 assert(LatchBlock && "needsLFTR should guarantee a loop latch"); 1584 1585 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 1586 PHINode *Phi = cast<PHINode>(I); 1587 if (!SE->isSCEVable(Phi->getType())) 1588 continue; 1589 1590 // Avoid comparing an integer IV against a pointer Limit. 1591 if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy()) 1592 continue; 1593 1594 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi)); 1595 if (!AR || AR->getLoop() != L || !AR->isAffine()) 1596 continue; 1597 1598 // AR may be a pointer type, while BECount is an integer type. 1599 // AR may be wider than BECount. With eq/ne tests overflow is immaterial. 1600 // AR may not be a narrower type, or we may never exit. 1601 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType()); 1602 if (PhiWidth < BCWidth || 1603 !L->getHeader()->getModule()->getDataLayout().isLegalInteger(PhiWidth)) 1604 continue; 1605 1606 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)); 1607 if (!Step || !Step->isOne()) 1608 continue; 1609 1610 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock); 1611 Value *IncV = Phi->getIncomingValue(LatchIdx); 1612 if (getLoopPhiForCounter(IncV, L, DT) != Phi) 1613 continue; 1614 1615 // Avoid reusing a potentially undef value to compute other values that may 1616 // have originally had a concrete definition. 1617 if (!hasConcreteDef(Phi)) { 1618 // We explicitly allow unknown phis as long as they are already used by 1619 // the loop test. In this case we assume that performing LFTR could not 1620 // increase the number of undef users. 1621 if (ICmpInst *Cond = getLoopTest(L)) { 1622 if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT) 1623 && Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) { 1624 continue; 1625 } 1626 } 1627 } 1628 const SCEV *Init = AR->getStart(); 1629 1630 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) { 1631 // Don't force a live loop counter if another IV can be used. 1632 if (AlmostDeadIV(Phi, LatchBlock, Cond)) 1633 continue; 1634 1635 // Prefer to count-from-zero. This is a more "canonical" counter form. It 1636 // also prefers integer to pointer IVs. 1637 if (BestInit->isZero() != Init->isZero()) { 1638 if (BestInit->isZero()) 1639 continue; 1640 } 1641 // If two IVs both count from zero or both count from nonzero then the 1642 // narrower is likely a dead phi that has been widened. Use the wider phi 1643 // to allow the other to be eliminated. 1644 else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType())) 1645 continue; 1646 } 1647 BestPhi = Phi; 1648 BestInit = Init; 1649 } 1650 return BestPhi; 1651 } 1652 1653 /// genLoopLimit - Help LinearFunctionTestReplace by generating a value that 1654 /// holds the RHS of the new loop test. 1655 static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L, 1656 SCEVExpander &Rewriter, ScalarEvolution *SE) { 1657 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar)); 1658 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter"); 1659 const SCEV *IVInit = AR->getStart(); 1660 1661 // IVInit may be a pointer while IVCount is an integer when FindLoopCounter 1662 // finds a valid pointer IV. Sign extend BECount in order to materialize a 1663 // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing 1664 // the existing GEPs whenever possible. 1665 if (IndVar->getType()->isPointerTy() 1666 && !IVCount->getType()->isPointerTy()) { 1667 1668 // IVOffset will be the new GEP offset that is interpreted by GEP as a 1669 // signed value. IVCount on the other hand represents the loop trip count, 1670 // which is an unsigned value. FindLoopCounter only allows induction 1671 // variables that have a positive unit stride of one. This means we don't 1672 // have to handle the case of negative offsets (yet) and just need to zero 1673 // extend IVCount. 1674 Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType()); 1675 const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy); 1676 1677 // Expand the code for the iteration count. 1678 assert(SE->isLoopInvariant(IVOffset, L) && 1679 "Computed iteration count is not loop invariant!"); 1680 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1681 Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI); 1682 1683 Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader()); 1684 assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter"); 1685 // We could handle pointer IVs other than i8*, but we need to compensate for 1686 // gep index scaling. See canExpandBackedgeTakenCount comments. 1687 assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()), 1688 cast<PointerType>(GEPBase->getType())->getElementType())->isOne() 1689 && "unit stride pointer IV must be i8*"); 1690 1691 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator()); 1692 return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit"); 1693 } 1694 else { 1695 // In any other case, convert both IVInit and IVCount to integers before 1696 // comparing. This may result in SCEV expension of pointers, but in practice 1697 // SCEV will fold the pointer arithmetic away as such: 1698 // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc). 1699 // 1700 // Valid Cases: (1) both integers is most common; (2) both may be pointers 1701 // for simple memset-style loops. 1702 // 1703 // IVInit integer and IVCount pointer would only occur if a canonical IV 1704 // were generated on top of case #2, which is not expected. 1705 1706 const SCEV *IVLimit = nullptr; 1707 // For unit stride, IVCount = Start + BECount with 2's complement overflow. 1708 // For non-zero Start, compute IVCount here. 1709 if (AR->getStart()->isZero()) 1710 IVLimit = IVCount; 1711 else { 1712 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride"); 1713 const SCEV *IVInit = AR->getStart(); 1714 1715 // For integer IVs, truncate the IV before computing IVInit + BECount. 1716 if (SE->getTypeSizeInBits(IVInit->getType()) 1717 > SE->getTypeSizeInBits(IVCount->getType())) 1718 IVInit = SE->getTruncateExpr(IVInit, IVCount->getType()); 1719 1720 IVLimit = SE->getAddExpr(IVInit, IVCount); 1721 } 1722 // Expand the code for the iteration count. 1723 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1724 IRBuilder<> Builder(BI); 1725 assert(SE->isLoopInvariant(IVLimit, L) && 1726 "Computed iteration count is not loop invariant!"); 1727 // Ensure that we generate the same type as IndVar, or a smaller integer 1728 // type. In the presence of null pointer values, we have an integer type 1729 // SCEV expression (IVInit) for a pointer type IV value (IndVar). 1730 Type *LimitTy = IVCount->getType()->isPointerTy() ? 1731 IndVar->getType() : IVCount->getType(); 1732 return Rewriter.expandCodeFor(IVLimit, LimitTy, BI); 1733 } 1734 } 1735 1736 /// LinearFunctionTestReplace - This method rewrites the exit condition of the 1737 /// loop to be a canonical != comparison against the incremented loop induction 1738 /// variable. This pass is able to rewrite the exit tests of any loop where the 1739 /// SCEV analysis can determine a loop-invariant trip count of the loop, which 1740 /// is actually a much broader range than just linear tests. 1741 Value *IndVarSimplify:: 1742 LinearFunctionTestReplace(Loop *L, 1743 const SCEV *BackedgeTakenCount, 1744 PHINode *IndVar, 1745 SCEVExpander &Rewriter) { 1746 assert(canExpandBackedgeTakenCount(L, SE, Rewriter) && "precondition"); 1747 1748 // Initialize CmpIndVar and IVCount to their preincremented values. 1749 Value *CmpIndVar = IndVar; 1750 const SCEV *IVCount = BackedgeTakenCount; 1751 1752 // If the exiting block is the same as the backedge block, we prefer to 1753 // compare against the post-incremented value, otherwise we must compare 1754 // against the preincremented value. 1755 if (L->getExitingBlock() == L->getLoopLatch()) { 1756 // Add one to the "backedge-taken" count to get the trip count. 1757 // This addition may overflow, which is valid as long as the comparison is 1758 // truncated to BackedgeTakenCount->getType(). 1759 IVCount = SE->getAddExpr(BackedgeTakenCount, 1760 SE->getConstant(BackedgeTakenCount->getType(), 1)); 1761 // The BackedgeTaken expression contains the number of times that the 1762 // backedge branches to the loop header. This is one less than the 1763 // number of times the loop executes, so use the incremented indvar. 1764 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock()); 1765 } 1766 1767 Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE); 1768 assert(ExitCnt->getType()->isPointerTy() == IndVar->getType()->isPointerTy() 1769 && "genLoopLimit missed a cast"); 1770 1771 // Insert a new icmp_ne or icmp_eq instruction before the branch. 1772 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1773 ICmpInst::Predicate P; 1774 if (L->contains(BI->getSuccessor(0))) 1775 P = ICmpInst::ICMP_NE; 1776 else 1777 P = ICmpInst::ICMP_EQ; 1778 1779 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n" 1780 << " LHS:" << *CmpIndVar << '\n' 1781 << " op:\t" 1782 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n" 1783 << " RHS:\t" << *ExitCnt << "\n" 1784 << " IVCount:\t" << *IVCount << "\n"); 1785 1786 IRBuilder<> Builder(BI); 1787 1788 // LFTR can ignore IV overflow and truncate to the width of 1789 // BECount. This avoids materializing the add(zext(add)) expression. 1790 unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType()); 1791 unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType()); 1792 if (CmpIndVarSize > ExitCntSize) { 1793 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar)); 1794 const SCEV *ARStart = AR->getStart(); 1795 const SCEV *ARStep = AR->getStepRecurrence(*SE); 1796 // For constant IVCount, avoid truncation. 1797 if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) { 1798 const APInt &Start = cast<SCEVConstant>(ARStart)->getValue()->getValue(); 1799 APInt Count = cast<SCEVConstant>(IVCount)->getValue()->getValue(); 1800 // Note that the post-inc value of BackedgeTakenCount may have overflowed 1801 // above such that IVCount is now zero. 1802 if (IVCount != BackedgeTakenCount && Count == 0) { 1803 Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize); 1804 ++Count; 1805 } 1806 else 1807 Count = Count.zext(CmpIndVarSize); 1808 APInt NewLimit; 1809 if (cast<SCEVConstant>(ARStep)->getValue()->isNegative()) 1810 NewLimit = Start - Count; 1811 else 1812 NewLimit = Start + Count; 1813 ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit); 1814 1815 DEBUG(dbgs() << " Widen RHS:\t" << *ExitCnt << "\n"); 1816 } else { 1817 CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(), 1818 "lftr.wideiv"); 1819 } 1820 } 1821 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond"); 1822 Value *OrigCond = BI->getCondition(); 1823 // It's tempting to use replaceAllUsesWith here to fully replace the old 1824 // comparison, but that's not immediately safe, since users of the old 1825 // comparison may not be dominated by the new comparison. Instead, just 1826 // update the branch to use the new comparison; in the common case this 1827 // will make old comparison dead. 1828 BI->setCondition(Cond); 1829 DeadInsts.push_back(OrigCond); 1830 1831 ++NumLFTR; 1832 Changed = true; 1833 return Cond; 1834 } 1835 1836 //===----------------------------------------------------------------------===// 1837 // SinkUnusedInvariants. A late subpass to cleanup loop preheaders. 1838 //===----------------------------------------------------------------------===// 1839 1840 /// If there's a single exit block, sink any loop-invariant values that 1841 /// were defined in the preheader but not used inside the loop into the 1842 /// exit block to reduce register pressure in the loop. 1843 void IndVarSimplify::SinkUnusedInvariants(Loop *L) { 1844 BasicBlock *ExitBlock = L->getExitBlock(); 1845 if (!ExitBlock) return; 1846 1847 BasicBlock *Preheader = L->getLoopPreheader(); 1848 if (!Preheader) return; 1849 1850 Instruction *InsertPt = ExitBlock->getFirstInsertionPt(); 1851 BasicBlock::iterator I = Preheader->getTerminator(); 1852 while (I != Preheader->begin()) { 1853 --I; 1854 // New instructions were inserted at the end of the preheader. 1855 if (isa<PHINode>(I)) 1856 break; 1857 1858 // Don't move instructions which might have side effects, since the side 1859 // effects need to complete before instructions inside the loop. Also don't 1860 // move instructions which might read memory, since the loop may modify 1861 // memory. Note that it's okay if the instruction might have undefined 1862 // behavior: LoopSimplify guarantees that the preheader dominates the exit 1863 // block. 1864 if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 1865 continue; 1866 1867 // Skip debug info intrinsics. 1868 if (isa<DbgInfoIntrinsic>(I)) 1869 continue; 1870 1871 // Skip landingpad instructions. 1872 if (isa<LandingPadInst>(I)) 1873 continue; 1874 1875 // Don't sink alloca: we never want to sink static alloca's out of the 1876 // entry block, and correctly sinking dynamic alloca's requires 1877 // checks for stacksave/stackrestore intrinsics. 1878 // FIXME: Refactor this check somehow? 1879 if (isa<AllocaInst>(I)) 1880 continue; 1881 1882 // Determine if there is a use in or before the loop (direct or 1883 // otherwise). 1884 bool UsedInLoop = false; 1885 for (Use &U : I->uses()) { 1886 Instruction *User = cast<Instruction>(U.getUser()); 1887 BasicBlock *UseBB = User->getParent(); 1888 if (PHINode *P = dyn_cast<PHINode>(User)) { 1889 unsigned i = 1890 PHINode::getIncomingValueNumForOperand(U.getOperandNo()); 1891 UseBB = P->getIncomingBlock(i); 1892 } 1893 if (UseBB == Preheader || L->contains(UseBB)) { 1894 UsedInLoop = true; 1895 break; 1896 } 1897 } 1898 1899 // If there is, the def must remain in the preheader. 1900 if (UsedInLoop) 1901 continue; 1902 1903 // Otherwise, sink it to the exit block. 1904 Instruction *ToMove = I; 1905 bool Done = false; 1906 1907 if (I != Preheader->begin()) { 1908 // Skip debug info intrinsics. 1909 do { 1910 --I; 1911 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin()); 1912 1913 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin()) 1914 Done = true; 1915 } else { 1916 Done = true; 1917 } 1918 1919 ToMove->moveBefore(InsertPt); 1920 if (Done) break; 1921 InsertPt = ToMove; 1922 } 1923 } 1924 1925 //===----------------------------------------------------------------------===// 1926 // IndVarSimplify driver. Manage several subpasses of IV simplification. 1927 //===----------------------------------------------------------------------===// 1928 1929 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) { 1930 if (skipOptnoneFunction(L)) 1931 return false; 1932 1933 // If LoopSimplify form is not available, stay out of trouble. Some notes: 1934 // - LSR currently only supports LoopSimplify-form loops. Indvars' 1935 // canonicalization can be a pessimization without LSR to "clean up" 1936 // afterwards. 1937 // - We depend on having a preheader; in particular, 1938 // Loop::getCanonicalInductionVariable only supports loops with preheaders, 1939 // and we're in trouble if we can't find the induction variable even when 1940 // we've manually inserted one. 1941 if (!L->isLoopSimplifyForm()) 1942 return false; 1943 1944 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1945 SE = &getAnalysis<ScalarEvolution>(); 1946 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1947 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 1948 TLI = TLIP ? &TLIP->getTLI() : nullptr; 1949 auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>(); 1950 TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr; 1951 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 1952 1953 DeadInsts.clear(); 1954 Changed = false; 1955 1956 // If there are any floating-point recurrences, attempt to 1957 // transform them to use integer recurrences. 1958 RewriteNonIntegerIVs(L); 1959 1960 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L); 1961 1962 // Create a rewriter object which we'll use to transform the code with. 1963 SCEVExpander Rewriter(*SE, DL, "indvars"); 1964 #ifndef NDEBUG 1965 Rewriter.setDebugType(DEBUG_TYPE); 1966 #endif 1967 1968 // Eliminate redundant IV users. 1969 // 1970 // Simplification works best when run before other consumers of SCEV. We 1971 // attempt to avoid evaluating SCEVs for sign/zero extend operations until 1972 // other expressions involving loop IVs have been evaluated. This helps SCEV 1973 // set no-wrap flags before normalizing sign/zero extension. 1974 Rewriter.disableCanonicalMode(); 1975 SimplifyAndExtend(L, Rewriter, LPM); 1976 1977 // Check to see if this loop has a computable loop-invariant execution count. 1978 // If so, this means that we can compute the final value of any expressions 1979 // that are recurrent in the loop, and substitute the exit values from the 1980 // loop into any instructions outside of the loop that use the final values of 1981 // the current expressions. 1982 // 1983 if (ReplaceExitValue != NeverRepl && 1984 !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) 1985 RewriteLoopExitValues(L, Rewriter); 1986 1987 // Eliminate redundant IV cycles. 1988 NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts); 1989 1990 // If we have a trip count expression, rewrite the loop's exit condition 1991 // using it. We can currently only handle loops with a single exit. 1992 if (canExpandBackedgeTakenCount(L, SE, Rewriter) && needsLFTR(L, DT)) { 1993 PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT); 1994 if (IndVar) { 1995 // Check preconditions for proper SCEVExpander operation. SCEV does not 1996 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any 1997 // pass that uses the SCEVExpander must do it. This does not work well for 1998 // loop passes because SCEVExpander makes assumptions about all loops, 1999 // while LoopPassManager only forces the current loop to be simplified. 2000 // 2001 // FIXME: SCEV expansion has no way to bail out, so the caller must 2002 // explicitly check any assumptions made by SCEV. Brittle. 2003 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount); 2004 if (!AR || AR->getLoop()->getLoopPreheader()) 2005 (void)LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, 2006 Rewriter); 2007 } 2008 } 2009 // Clear the rewriter cache, because values that are in the rewriter's cache 2010 // can be deleted in the loop below, causing the AssertingVH in the cache to 2011 // trigger. 2012 Rewriter.clear(); 2013 2014 // Now that we're done iterating through lists, clean up any instructions 2015 // which are now dead. 2016 while (!DeadInsts.empty()) 2017 if (Instruction *Inst = 2018 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val())) 2019 RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI); 2020 2021 // The Rewriter may not be used from this point on. 2022 2023 // Loop-invariant instructions in the preheader that aren't used in the 2024 // loop may be sunk below the loop to reduce register pressure. 2025 SinkUnusedInvariants(L); 2026 2027 // Clean up dead instructions. 2028 Changed |= DeleteDeadPHIs(L->getHeader(), TLI); 2029 // Check a post-condition. 2030 assert(L->isLCSSAForm(*DT) && 2031 "Indvars did not leave the loop in lcssa form!"); 2032 2033 // Verify that LFTR, and any other change have not interfered with SCEV's 2034 // ability to compute trip count. 2035 #ifndef NDEBUG 2036 if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) { 2037 SE->forgetLoop(L); 2038 const SCEV *NewBECount = SE->getBackedgeTakenCount(L); 2039 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) < 2040 SE->getTypeSizeInBits(NewBECount->getType())) 2041 NewBECount = SE->getTruncateOrNoop(NewBECount, 2042 BackedgeTakenCount->getType()); 2043 else 2044 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, 2045 NewBECount->getType()); 2046 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV"); 2047 } 2048 #endif 2049 2050 return Changed; 2051 } 2052