1 //===-- LoopReroll.cpp - Loop rerolling pass ------------------------------===// 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 pass implements a simple loop reroller. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Scalar.h" 15 #include "llvm/ADT/MapVector.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallBitVector.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/AliasSetTracker.h" 22 #include "llvm/Analysis/LoopPass.h" 23 #include "llvm/Analysis/ScalarEvolution.h" 24 #include "llvm/Analysis/ScalarEvolutionExpander.h" 25 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 26 #include "llvm/Analysis/TargetLibraryInfo.h" 27 #include "llvm/Analysis/ValueTracking.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/Dominators.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 35 #include "llvm/Transforms/Utils/Local.h" 36 #include "llvm/Transforms/Utils/LoopUtils.h" 37 38 using namespace llvm; 39 40 #define DEBUG_TYPE "loop-reroll" 41 42 STATISTIC(NumRerolledLoops, "Number of rerolled loops"); 43 44 static cl::opt<unsigned> 45 MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden, 46 cl::desc("The maximum increment for loop rerolling")); 47 48 static cl::opt<unsigned> 49 NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400), 50 cl::Hidden, 51 cl::desc("The maximum number of failures to tolerate" 52 " during fuzzy matching. (default: 400)")); 53 54 // This loop re-rolling transformation aims to transform loops like this: 55 // 56 // int foo(int a); 57 // void bar(int *x) { 58 // for (int i = 0; i < 500; i += 3) { 59 // foo(i); 60 // foo(i+1); 61 // foo(i+2); 62 // } 63 // } 64 // 65 // into a loop like this: 66 // 67 // void bar(int *x) { 68 // for (int i = 0; i < 500; ++i) 69 // foo(i); 70 // } 71 // 72 // It does this by looking for loops that, besides the latch code, are composed 73 // of isomorphic DAGs of instructions, with each DAG rooted at some increment 74 // to the induction variable, and where each DAG is isomorphic to the DAG 75 // rooted at the induction variable (excepting the sub-DAGs which root the 76 // other induction-variable increments). In other words, we're looking for loop 77 // bodies of the form: 78 // 79 // %iv = phi [ (preheader, ...), (body, %iv.next) ] 80 // f(%iv) 81 // %iv.1 = add %iv, 1 <-- a root increment 82 // f(%iv.1) 83 // %iv.2 = add %iv, 2 <-- a root increment 84 // f(%iv.2) 85 // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment 86 // f(%iv.scale_m_1) 87 // ... 88 // %iv.next = add %iv, scale 89 // %cmp = icmp(%iv, ...) 90 // br %cmp, header, exit 91 // 92 // where each f(i) is a set of instructions that, collectively, are a function 93 // only of i (and other loop-invariant values). 94 // 95 // As a special case, we can also reroll loops like this: 96 // 97 // int foo(int); 98 // void bar(int *x) { 99 // for (int i = 0; i < 500; ++i) { 100 // x[3*i] = foo(0); 101 // x[3*i+1] = foo(0); 102 // x[3*i+2] = foo(0); 103 // } 104 // } 105 // 106 // into this: 107 // 108 // void bar(int *x) { 109 // for (int i = 0; i < 1500; ++i) 110 // x[i] = foo(0); 111 // } 112 // 113 // in which case, we're looking for inputs like this: 114 // 115 // %iv = phi [ (preheader, ...), (body, %iv.next) ] 116 // %scaled.iv = mul %iv, scale 117 // f(%scaled.iv) 118 // %scaled.iv.1 = add %scaled.iv, 1 119 // f(%scaled.iv.1) 120 // %scaled.iv.2 = add %scaled.iv, 2 121 // f(%scaled.iv.2) 122 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1 123 // f(%scaled.iv.scale_m_1) 124 // ... 125 // %iv.next = add %iv, 1 126 // %cmp = icmp(%iv, ...) 127 // br %cmp, header, exit 128 129 namespace { 130 enum IterationLimits { 131 /// The maximum number of iterations that we'll try and reroll. This 132 /// has to be less than 25 in order to fit into a SmallBitVector. 133 IL_MaxRerollIterations = 16, 134 /// The bitvector index used by loop induction variables and other 135 /// instructions that belong to all iterations. 136 IL_All, 137 IL_End 138 }; 139 140 class LoopReroll : public LoopPass { 141 public: 142 static char ID; // Pass ID, replacement for typeid 143 LoopReroll() : LoopPass(ID) { 144 initializeLoopRerollPass(*PassRegistry::getPassRegistry()); 145 } 146 147 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 148 149 void getAnalysisUsage(AnalysisUsage &AU) const override { 150 AU.addRequired<AAResultsWrapperPass>(); 151 AU.addRequired<LoopInfoWrapperPass>(); 152 AU.addPreserved<LoopInfoWrapperPass>(); 153 AU.addRequired<DominatorTreeWrapperPass>(); 154 AU.addPreserved<DominatorTreeWrapperPass>(); 155 AU.addRequired<ScalarEvolutionWrapperPass>(); 156 AU.addRequired<TargetLibraryInfoWrapperPass>(); 157 } 158 159 protected: 160 AliasAnalysis *AA; 161 LoopInfo *LI; 162 ScalarEvolution *SE; 163 TargetLibraryInfo *TLI; 164 DominatorTree *DT; 165 166 typedef SmallVector<Instruction *, 16> SmallInstructionVector; 167 typedef SmallSet<Instruction *, 16> SmallInstructionSet; 168 169 // Map between induction variable and its increment 170 DenseMap<Instruction *, int64_t> IVToIncMap; 171 172 // A chain of isomorphic instructions, identified by a single-use PHI 173 // representing a reduction. Only the last value may be used outside the 174 // loop. 175 struct SimpleLoopReduction { 176 SimpleLoopReduction(Instruction *P, Loop *L) 177 : Valid(false), Instructions(1, P) { 178 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI"); 179 add(L); 180 } 181 182 bool valid() const { 183 return Valid; 184 } 185 186 Instruction *getPHI() const { 187 assert(Valid && "Using invalid reduction"); 188 return Instructions.front(); 189 } 190 191 Instruction *getReducedValue() const { 192 assert(Valid && "Using invalid reduction"); 193 return Instructions.back(); 194 } 195 196 Instruction *get(size_t i) const { 197 assert(Valid && "Using invalid reduction"); 198 return Instructions[i+1]; 199 } 200 201 Instruction *operator [] (size_t i) const { return get(i); } 202 203 // The size, ignoring the initial PHI. 204 size_t size() const { 205 assert(Valid && "Using invalid reduction"); 206 return Instructions.size()-1; 207 } 208 209 typedef SmallInstructionVector::iterator iterator; 210 typedef SmallInstructionVector::const_iterator const_iterator; 211 212 iterator begin() { 213 assert(Valid && "Using invalid reduction"); 214 return std::next(Instructions.begin()); 215 } 216 217 const_iterator begin() const { 218 assert(Valid && "Using invalid reduction"); 219 return std::next(Instructions.begin()); 220 } 221 222 iterator end() { return Instructions.end(); } 223 const_iterator end() const { return Instructions.end(); } 224 225 protected: 226 bool Valid; 227 SmallInstructionVector Instructions; 228 229 void add(Loop *L); 230 }; 231 232 // The set of all reductions, and state tracking of possible reductions 233 // during loop instruction processing. 234 struct ReductionTracker { 235 typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector; 236 237 // Add a new possible reduction. 238 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); } 239 240 // Setup to track possible reductions corresponding to the provided 241 // rerolling scale. Only reductions with a number of non-PHI instructions 242 // that is divisible by the scale are considered. Three instructions sets 243 // are filled in: 244 // - A set of all possible instructions in eligible reductions. 245 // - A set of all PHIs in eligible reductions 246 // - A set of all reduced values (last instructions) in eligible 247 // reductions. 248 void restrictToScale(uint64_t Scale, 249 SmallInstructionSet &PossibleRedSet, 250 SmallInstructionSet &PossibleRedPHISet, 251 SmallInstructionSet &PossibleRedLastSet) { 252 PossibleRedIdx.clear(); 253 PossibleRedIter.clear(); 254 Reds.clear(); 255 256 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i) 257 if (PossibleReds[i].size() % Scale == 0) { 258 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue()); 259 PossibleRedPHISet.insert(PossibleReds[i].getPHI()); 260 261 PossibleRedSet.insert(PossibleReds[i].getPHI()); 262 PossibleRedIdx[PossibleReds[i].getPHI()] = i; 263 for (Instruction *J : PossibleReds[i]) { 264 PossibleRedSet.insert(J); 265 PossibleRedIdx[J] = i; 266 } 267 } 268 } 269 270 // The functions below are used while processing the loop instructions. 271 272 // Are the two instructions both from reductions, and furthermore, from 273 // the same reduction? 274 bool isPairInSame(Instruction *J1, Instruction *J2) { 275 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1); 276 if (J1I != PossibleRedIdx.end()) { 277 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2); 278 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second) 279 return true; 280 } 281 282 return false; 283 } 284 285 // The two provided instructions, the first from the base iteration, and 286 // the second from iteration i, form a matched pair. If these are part of 287 // a reduction, record that fact. 288 void recordPair(Instruction *J1, Instruction *J2, unsigned i) { 289 if (PossibleRedIdx.count(J1)) { 290 assert(PossibleRedIdx.count(J2) && 291 "Recording reduction vs. non-reduction instruction?"); 292 293 PossibleRedIter[J1] = 0; 294 PossibleRedIter[J2] = i; 295 296 int Idx = PossibleRedIdx[J1]; 297 assert(Idx == PossibleRedIdx[J2] && 298 "Recording pair from different reductions?"); 299 Reds.insert(Idx); 300 } 301 } 302 303 // The functions below can be called after we've finished processing all 304 // instructions in the loop, and we know which reductions were selected. 305 306 // Is the provided instruction the PHI of a reduction selected for 307 // rerolling? 308 bool isSelectedPHI(Instruction *J) { 309 if (!isa<PHINode>(J)) 310 return false; 311 312 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end(); 313 RI != RIE; ++RI) { 314 int i = *RI; 315 if (cast<Instruction>(J) == PossibleReds[i].getPHI()) 316 return true; 317 } 318 319 return false; 320 } 321 322 bool validateSelected(); 323 void replaceSelected(); 324 325 protected: 326 // The vector of all possible reductions (for any scale). 327 SmallReductionVector PossibleReds; 328 329 DenseMap<Instruction *, int> PossibleRedIdx; 330 DenseMap<Instruction *, int> PossibleRedIter; 331 DenseSet<int> Reds; 332 }; 333 334 // A DAGRootSet models an induction variable being used in a rerollable 335 // loop. For example, 336 // 337 // x[i*3+0] = y1 338 // x[i*3+1] = y2 339 // x[i*3+2] = y3 340 // 341 // Base instruction -> i*3 342 // +---+----+ 343 // / | \ 344 // ST[y1] +1 +2 <-- Roots 345 // | | 346 // ST[y2] ST[y3] 347 // 348 // There may be multiple DAGRoots, for example: 349 // 350 // x[i*2+0] = ... (1) 351 // x[i*2+1] = ... (1) 352 // x[i*2+4] = ... (2) 353 // x[i*2+5] = ... (2) 354 // x[(i+1234)*2+5678] = ... (3) 355 // x[(i+1234)*2+5679] = ... (3) 356 // 357 // The loop will be rerolled by adding a new loop induction variable, 358 // one for the Base instruction in each DAGRootSet. 359 // 360 struct DAGRootSet { 361 Instruction *BaseInst; 362 SmallInstructionVector Roots; 363 // The instructions between IV and BaseInst (but not including BaseInst). 364 SmallInstructionSet SubsumedInsts; 365 }; 366 367 // The set of all DAG roots, and state tracking of all roots 368 // for a particular induction variable. 369 struct DAGRootTracker { 370 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV, 371 ScalarEvolution *SE, AliasAnalysis *AA, 372 TargetLibraryInfo *TLI, 373 DenseMap<Instruction *, int64_t> &IncrMap) 374 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), IV(IV), 375 IVToIncMap(IncrMap) {} 376 377 /// Stage 1: Find all the DAG roots for the induction variable. 378 bool findRoots(); 379 /// Stage 2: Validate if the found roots are valid. 380 bool validate(ReductionTracker &Reductions); 381 /// Stage 3: Assuming validate() returned true, perform the 382 /// replacement. 383 /// @param IterCount The maximum iteration count of L. 384 void replace(const SCEV *IterCount); 385 386 protected: 387 typedef MapVector<Instruction*, SmallBitVector> UsesTy; 388 389 bool findRootsRecursive(Instruction *IVU, 390 SmallInstructionSet SubsumedInsts); 391 bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts); 392 bool collectPossibleRoots(Instruction *Base, 393 std::map<int64_t,Instruction*> &Roots); 394 395 bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet); 396 void collectInLoopUserSet(const SmallInstructionVector &Roots, 397 const SmallInstructionSet &Exclude, 398 const SmallInstructionSet &Final, 399 DenseSet<Instruction *> &Users); 400 void collectInLoopUserSet(Instruction *Root, 401 const SmallInstructionSet &Exclude, 402 const SmallInstructionSet &Final, 403 DenseSet<Instruction *> &Users); 404 405 UsesTy::iterator nextInstr(int Val, UsesTy &In, 406 const SmallInstructionSet &Exclude, 407 UsesTy::iterator *StartI=nullptr); 408 bool isBaseInst(Instruction *I); 409 bool isRootInst(Instruction *I); 410 bool instrDependsOn(Instruction *I, 411 UsesTy::iterator Start, 412 UsesTy::iterator End); 413 414 LoopReroll *Parent; 415 416 // Members of Parent, replicated here for brevity. 417 Loop *L; 418 ScalarEvolution *SE; 419 AliasAnalysis *AA; 420 TargetLibraryInfo *TLI; 421 422 // The loop induction variable. 423 Instruction *IV; 424 // Loop step amount. 425 int64_t Inc; 426 // Loop reroll count; if Inc == 1, this records the scaling applied 427 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ; 428 // If Inc is not 1, Scale = Inc. 429 uint64_t Scale; 430 // The roots themselves. 431 SmallVector<DAGRootSet,16> RootSets; 432 // All increment instructions for IV. 433 SmallInstructionVector LoopIncs; 434 // Map of all instructions in the loop (in order) to the iterations 435 // they are used in (or specially, IL_All for instructions 436 // used in the loop increment mechanism). 437 UsesTy Uses; 438 // Map between induction variable and its increment 439 DenseMap<Instruction *, int64_t> &IVToIncMap; 440 }; 441 442 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs); 443 void collectPossibleReductions(Loop *L, 444 ReductionTracker &Reductions); 445 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount, 446 ReductionTracker &Reductions); 447 }; 448 } 449 450 char LoopReroll::ID = 0; 451 INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false) 452 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 453 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 454 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 455 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 456 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 457 INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false) 458 459 Pass *llvm::createLoopRerollPass() { 460 return new LoopReroll; 461 } 462 463 // Returns true if the provided instruction is used outside the given loop. 464 // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in 465 // non-loop blocks to be outside the loop. 466 static bool hasUsesOutsideLoop(Instruction *I, Loop *L) { 467 for (User *U : I->users()) { 468 if (!L->contains(cast<Instruction>(U))) 469 return true; 470 } 471 return false; 472 } 473 474 // Collect the list of loop induction variables with respect to which it might 475 // be possible to reroll the loop. 476 void LoopReroll::collectPossibleIVs(Loop *L, 477 SmallInstructionVector &PossibleIVs) { 478 BasicBlock *Header = L->getHeader(); 479 for (BasicBlock::iterator I = Header->begin(), 480 IE = Header->getFirstInsertionPt(); I != IE; ++I) { 481 if (!isa<PHINode>(I)) 482 continue; 483 if (!I->getType()->isIntegerTy()) 484 continue; 485 486 if (const SCEVAddRecExpr *PHISCEV = 487 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) { 488 if (PHISCEV->getLoop() != L) 489 continue; 490 if (!PHISCEV->isAffine()) 491 continue; 492 if (const SCEVConstant *IncSCEV = 493 dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) { 494 const APInt &AInt = IncSCEV->getValue()->getValue().abs(); 495 if (IncSCEV->getValue()->isZero() || AInt.uge(MaxInc)) 496 continue; 497 IVToIncMap[I] = IncSCEV->getValue()->getSExtValue(); 498 DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV 499 << "\n"); 500 PossibleIVs.push_back(I); 501 } 502 } 503 } 504 } 505 506 // Add the remainder of the reduction-variable chain to the instruction vector 507 // (the initial PHINode has already been added). If successful, the object is 508 // marked as valid. 509 void LoopReroll::SimpleLoopReduction::add(Loop *L) { 510 assert(!Valid && "Cannot add to an already-valid chain"); 511 512 // The reduction variable must be a chain of single-use instructions 513 // (including the PHI), except for the last value (which is used by the PHI 514 // and also outside the loop). 515 Instruction *C = Instructions.front(); 516 if (C->user_empty()) 517 return; 518 519 do { 520 C = cast<Instruction>(*C->user_begin()); 521 if (C->hasOneUse()) { 522 if (!C->isBinaryOp()) 523 return; 524 525 if (!(isa<PHINode>(Instructions.back()) || 526 C->isSameOperationAs(Instructions.back()))) 527 return; 528 529 Instructions.push_back(C); 530 } 531 } while (C->hasOneUse()); 532 533 if (Instructions.size() < 2 || 534 !C->isSameOperationAs(Instructions.back()) || 535 C->use_empty()) 536 return; 537 538 // C is now the (potential) last instruction in the reduction chain. 539 for (User *U : C->users()) { 540 // The only in-loop user can be the initial PHI. 541 if (L->contains(cast<Instruction>(U))) 542 if (cast<Instruction>(U) != Instructions.front()) 543 return; 544 } 545 546 Instructions.push_back(C); 547 Valid = true; 548 } 549 550 // Collect the vector of possible reduction variables. 551 void LoopReroll::collectPossibleReductions(Loop *L, 552 ReductionTracker &Reductions) { 553 BasicBlock *Header = L->getHeader(); 554 for (BasicBlock::iterator I = Header->begin(), 555 IE = Header->getFirstInsertionPt(); I != IE; ++I) { 556 if (!isa<PHINode>(I)) 557 continue; 558 if (!I->getType()->isSingleValueType()) 559 continue; 560 561 SimpleLoopReduction SLR(I, L); 562 if (!SLR.valid()) 563 continue; 564 565 DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " << 566 SLR.size() << " chained instructions)\n"); 567 Reductions.addSLR(SLR); 568 } 569 } 570 571 // Collect the set of all users of the provided root instruction. This set of 572 // users contains not only the direct users of the root instruction, but also 573 // all users of those users, and so on. There are two exceptions: 574 // 575 // 1. Instructions in the set of excluded instructions are never added to the 576 // use set (even if they are users). This is used, for example, to exclude 577 // including root increments in the use set of the primary IV. 578 // 579 // 2. Instructions in the set of final instructions are added to the use set 580 // if they are users, but their users are not added. This is used, for 581 // example, to prevent a reduction update from forcing all later reduction 582 // updates into the use set. 583 void LoopReroll::DAGRootTracker::collectInLoopUserSet( 584 Instruction *Root, const SmallInstructionSet &Exclude, 585 const SmallInstructionSet &Final, 586 DenseSet<Instruction *> &Users) { 587 SmallInstructionVector Queue(1, Root); 588 while (!Queue.empty()) { 589 Instruction *I = Queue.pop_back_val(); 590 if (!Users.insert(I).second) 591 continue; 592 593 if (!Final.count(I)) 594 for (Use &U : I->uses()) { 595 Instruction *User = cast<Instruction>(U.getUser()); 596 if (PHINode *PN = dyn_cast<PHINode>(User)) { 597 // Ignore "wrap-around" uses to PHIs of this loop's header. 598 if (PN->getIncomingBlock(U) == L->getHeader()) 599 continue; 600 } 601 602 if (L->contains(User) && !Exclude.count(User)) { 603 Queue.push_back(User); 604 } 605 } 606 607 // We also want to collect single-user "feeder" values. 608 for (User::op_iterator OI = I->op_begin(), 609 OIE = I->op_end(); OI != OIE; ++OI) { 610 if (Instruction *Op = dyn_cast<Instruction>(*OI)) 611 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) && 612 !Final.count(Op)) 613 Queue.push_back(Op); 614 } 615 } 616 } 617 618 // Collect all of the users of all of the provided root instructions (combined 619 // into a single set). 620 void LoopReroll::DAGRootTracker::collectInLoopUserSet( 621 const SmallInstructionVector &Roots, 622 const SmallInstructionSet &Exclude, 623 const SmallInstructionSet &Final, 624 DenseSet<Instruction *> &Users) { 625 for (SmallInstructionVector::const_iterator I = Roots.begin(), 626 IE = Roots.end(); I != IE; ++I) 627 collectInLoopUserSet(*I, Exclude, Final, Users); 628 } 629 630 static bool isSimpleLoadStore(Instruction *I) { 631 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 632 return LI->isSimple(); 633 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 634 return SI->isSimple(); 635 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) 636 return !MI->isVolatile(); 637 return false; 638 } 639 640 /// Return true if IVU is a "simple" arithmetic operation. 641 /// This is used for narrowing the search space for DAGRoots; only arithmetic 642 /// and GEPs can be part of a DAGRoot. 643 static bool isSimpleArithmeticOp(User *IVU) { 644 if (Instruction *I = dyn_cast<Instruction>(IVU)) { 645 switch (I->getOpcode()) { 646 default: return false; 647 case Instruction::Add: 648 case Instruction::Sub: 649 case Instruction::Mul: 650 case Instruction::Shl: 651 case Instruction::AShr: 652 case Instruction::LShr: 653 case Instruction::GetElementPtr: 654 case Instruction::Trunc: 655 case Instruction::ZExt: 656 case Instruction::SExt: 657 return true; 658 } 659 } 660 return false; 661 } 662 663 static bool isLoopIncrement(User *U, Instruction *IV) { 664 BinaryOperator *BO = dyn_cast<BinaryOperator>(U); 665 if (!BO || BO->getOpcode() != Instruction::Add) 666 return false; 667 668 for (auto *UU : BO->users()) { 669 PHINode *PN = dyn_cast<PHINode>(UU); 670 if (PN && PN == IV) 671 return true; 672 } 673 return false; 674 } 675 676 bool LoopReroll::DAGRootTracker:: 677 collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) { 678 SmallInstructionVector BaseUsers; 679 680 for (auto *I : Base->users()) { 681 ConstantInt *CI = nullptr; 682 683 if (isLoopIncrement(I, IV)) { 684 LoopIncs.push_back(cast<Instruction>(I)); 685 continue; 686 } 687 688 // The root nodes must be either GEPs, ORs or ADDs. 689 if (auto *BO = dyn_cast<BinaryOperator>(I)) { 690 if (BO->getOpcode() == Instruction::Add || 691 BO->getOpcode() == Instruction::Or) 692 CI = dyn_cast<ConstantInt>(BO->getOperand(1)); 693 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { 694 Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1); 695 CI = dyn_cast<ConstantInt>(LastOperand); 696 } 697 698 if (!CI) { 699 if (Instruction *II = dyn_cast<Instruction>(I)) { 700 BaseUsers.push_back(II); 701 continue; 702 } else { 703 DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n"); 704 return false; 705 } 706 } 707 708 int64_t V = std::abs(CI->getValue().getSExtValue()); 709 if (Roots.find(V) != Roots.end()) 710 // No duplicates, please. 711 return false; 712 713 Roots[V] = cast<Instruction>(I); 714 } 715 716 if (Roots.empty()) 717 return false; 718 719 // If we found non-loop-inc, non-root users of Base, assume they are 720 // for the zeroth root index. This is because "add %a, 0" gets optimized 721 // away. 722 if (BaseUsers.size()) { 723 if (Roots.find(0) != Roots.end()) { 724 DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n"); 725 return false; 726 } 727 Roots[0] = Base; 728 } 729 730 // Calculate the number of users of the base, or lowest indexed, iteration. 731 unsigned NumBaseUses = BaseUsers.size(); 732 if (NumBaseUses == 0) 733 NumBaseUses = Roots.begin()->second->getNumUses(); 734 735 // Check that every node has the same number of users. 736 for (auto &KV : Roots) { 737 if (KV.first == 0) 738 continue; 739 if (KV.second->getNumUses() != NumBaseUses) { 740 DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: " 741 << "#Base=" << NumBaseUses << ", #Root=" << 742 KV.second->getNumUses() << "\n"); 743 return false; 744 } 745 } 746 747 return true; 748 } 749 750 bool LoopReroll::DAGRootTracker:: 751 findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) { 752 // Does the user look like it could be part of a root set? 753 // All its users must be simple arithmetic ops. 754 if (I->getNumUses() > IL_MaxRerollIterations) 755 return false; 756 757 if ((I->getOpcode() == Instruction::Mul || 758 I->getOpcode() == Instruction::PHI) && 759 I != IV && 760 findRootsBase(I, SubsumedInsts)) 761 return true; 762 763 SubsumedInsts.insert(I); 764 765 for (User *V : I->users()) { 766 Instruction *I = dyn_cast<Instruction>(V); 767 if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end()) 768 continue; 769 770 if (!I || !isSimpleArithmeticOp(I) || 771 !findRootsRecursive(I, SubsumedInsts)) 772 return false; 773 } 774 return true; 775 } 776 777 bool LoopReroll::DAGRootTracker:: 778 findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) { 779 780 // The base instruction needs to be a multiply so 781 // that we can erase it. 782 if (IVU->getOpcode() != Instruction::Mul && 783 IVU->getOpcode() != Instruction::PHI) 784 return false; 785 786 std::map<int64_t, Instruction*> V; 787 if (!collectPossibleRoots(IVU, V)) 788 return false; 789 790 // If we didn't get a root for index zero, then IVU must be 791 // subsumed. 792 if (V.find(0) == V.end()) 793 SubsumedInsts.insert(IVU); 794 795 // Partition the vector into monotonically increasing indexes. 796 DAGRootSet DRS; 797 DRS.BaseInst = nullptr; 798 799 for (auto &KV : V) { 800 if (!DRS.BaseInst) { 801 DRS.BaseInst = KV.second; 802 DRS.SubsumedInsts = SubsumedInsts; 803 } else if (DRS.Roots.empty()) { 804 DRS.Roots.push_back(KV.second); 805 } else if (V.find(KV.first - 1) != V.end()) { 806 DRS.Roots.push_back(KV.second); 807 } else { 808 // Linear sequence terminated. 809 RootSets.push_back(DRS); 810 DRS.BaseInst = KV.second; 811 DRS.SubsumedInsts = SubsumedInsts; 812 DRS.Roots.clear(); 813 } 814 } 815 RootSets.push_back(DRS); 816 817 return true; 818 } 819 820 bool LoopReroll::DAGRootTracker::findRoots() { 821 Inc = IVToIncMap[IV]; 822 823 assert(RootSets.empty() && "Unclean state!"); 824 if (std::abs(Inc) == 1) { 825 for (auto *IVU : IV->users()) { 826 if (isLoopIncrement(IVU, IV)) 827 LoopIncs.push_back(cast<Instruction>(IVU)); 828 } 829 if (!findRootsRecursive(IV, SmallInstructionSet())) 830 return false; 831 LoopIncs.push_back(IV); 832 } else { 833 if (!findRootsBase(IV, SmallInstructionSet())) 834 return false; 835 } 836 837 // Ensure all sets have the same size. 838 if (RootSets.empty()) { 839 DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n"); 840 return false; 841 } 842 for (auto &V : RootSets) { 843 if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) { 844 DEBUG(dbgs() 845 << "LRR: Aborting because not all root sets have the same size\n"); 846 return false; 847 } 848 } 849 850 // And ensure all loop iterations are consecutive. We rely on std::map 851 // providing ordered traversal. 852 for (auto &V : RootSets) { 853 const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst)); 854 if (!ADR) 855 return false; 856 857 // Consider a DAGRootSet with N-1 roots (so N different values including 858 // BaseInst). 859 // Define d = Roots[0] - BaseInst, which should be the same as 860 // Roots[I] - Roots[I-1] for all I in [1..N). 861 // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the 862 // loop iteration J. 863 // 864 // Now, For the loop iterations to be consecutive: 865 // D = d * N 866 867 unsigned N = V.Roots.size() + 1; 868 const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR); 869 const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N); 870 if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) { 871 DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n"); 872 return false; 873 } 874 } 875 Scale = RootSets[0].Roots.size() + 1; 876 877 if (Scale > IL_MaxRerollIterations) { 878 DEBUG(dbgs() << "LRR: Aborting - too many iterations found. " 879 << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations 880 << "\n"); 881 return false; 882 } 883 884 DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n"); 885 886 return true; 887 } 888 889 bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) { 890 // Populate the MapVector with all instructions in the block, in order first, 891 // so we can iterate over the contents later in perfect order. 892 for (auto &I : *L->getHeader()) { 893 Uses[&I].resize(IL_End); 894 } 895 896 SmallInstructionSet Exclude; 897 for (auto &DRS : RootSets) { 898 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end()); 899 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end()); 900 Exclude.insert(DRS.BaseInst); 901 } 902 Exclude.insert(LoopIncs.begin(), LoopIncs.end()); 903 904 for (auto &DRS : RootSets) { 905 DenseSet<Instruction*> VBase; 906 collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase); 907 for (auto *I : VBase) { 908 Uses[I].set(0); 909 } 910 911 unsigned Idx = 1; 912 for (auto *Root : DRS.Roots) { 913 DenseSet<Instruction*> V; 914 collectInLoopUserSet(Root, Exclude, PossibleRedSet, V); 915 916 // While we're here, check the use sets are the same size. 917 if (V.size() != VBase.size()) { 918 DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n"); 919 return false; 920 } 921 922 for (auto *I : V) { 923 Uses[I].set(Idx); 924 } 925 ++Idx; 926 } 927 928 // Make sure our subsumed instructions are remembered too. 929 for (auto *I : DRS.SubsumedInsts) { 930 Uses[I].set(IL_All); 931 } 932 } 933 934 // Make sure the loop increments are also accounted for. 935 936 Exclude.clear(); 937 for (auto &DRS : RootSets) { 938 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end()); 939 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end()); 940 Exclude.insert(DRS.BaseInst); 941 } 942 943 DenseSet<Instruction*> V; 944 collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V); 945 for (auto *I : V) { 946 Uses[I].set(IL_All); 947 } 948 949 return true; 950 951 } 952 953 /// Get the next instruction in "In" that is a member of set Val. 954 /// Start searching from StartI, and do not return anything in Exclude. 955 /// If StartI is not given, start from In.begin(). 956 LoopReroll::DAGRootTracker::UsesTy::iterator 957 LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In, 958 const SmallInstructionSet &Exclude, 959 UsesTy::iterator *StartI) { 960 UsesTy::iterator I = StartI ? *StartI : In.begin(); 961 while (I != In.end() && (I->second.test(Val) == 0 || 962 Exclude.count(I->first) != 0)) 963 ++I; 964 return I; 965 } 966 967 bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) { 968 for (auto &DRS : RootSets) { 969 if (DRS.BaseInst == I) 970 return true; 971 } 972 return false; 973 } 974 975 bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) { 976 for (auto &DRS : RootSets) { 977 if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end()) 978 return true; 979 } 980 return false; 981 } 982 983 /// Return true if instruction I depends on any instruction between 984 /// Start and End. 985 bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I, 986 UsesTy::iterator Start, 987 UsesTy::iterator End) { 988 for (auto *U : I->users()) { 989 for (auto It = Start; It != End; ++It) 990 if (U == It->first) 991 return true; 992 } 993 return false; 994 } 995 996 static bool isIgnorableInst(const Instruction *I) { 997 if (isa<DbgInfoIntrinsic>(I)) 998 return true; 999 const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I); 1000 if (!II) 1001 return false; 1002 switch (II->getIntrinsicID()) { 1003 default: 1004 return false; 1005 case llvm::Intrinsic::annotation: 1006 case Intrinsic::ptr_annotation: 1007 case Intrinsic::var_annotation: 1008 // TODO: the following intrinsics may also be whitelisted: 1009 // lifetime_start, lifetime_end, invariant_start, invariant_end 1010 return true; 1011 } 1012 return false; 1013 } 1014 1015 bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) { 1016 // We now need to check for equivalence of the use graph of each root with 1017 // that of the primary induction variable (excluding the roots). Our goal 1018 // here is not to solve the full graph isomorphism problem, but rather to 1019 // catch common cases without a lot of work. As a result, we will assume 1020 // that the relative order of the instructions in each unrolled iteration 1021 // is the same (although we will not make an assumption about how the 1022 // different iterations are intermixed). Note that while the order must be 1023 // the same, the instructions may not be in the same basic block. 1024 1025 // An array of just the possible reductions for this scale factor. When we 1026 // collect the set of all users of some root instructions, these reduction 1027 // instructions are treated as 'final' (their uses are not considered). 1028 // This is important because we don't want the root use set to search down 1029 // the reduction chain. 1030 SmallInstructionSet PossibleRedSet; 1031 SmallInstructionSet PossibleRedLastSet; 1032 SmallInstructionSet PossibleRedPHISet; 1033 Reductions.restrictToScale(Scale, PossibleRedSet, 1034 PossibleRedPHISet, PossibleRedLastSet); 1035 1036 // Populate "Uses" with where each instruction is used. 1037 if (!collectUsedInstructions(PossibleRedSet)) 1038 return false; 1039 1040 // Make sure we mark the reduction PHIs as used in all iterations. 1041 for (auto *I : PossibleRedPHISet) { 1042 Uses[I].set(IL_All); 1043 } 1044 1045 // Make sure all instructions in the loop are in one and only one 1046 // set. 1047 for (auto &KV : Uses) { 1048 if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) { 1049 DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: " 1050 << *KV.first << " (#uses=" << KV.second.count() << ")\n"); 1051 return false; 1052 } 1053 } 1054 1055 DEBUG( 1056 for (auto &KV : Uses) { 1057 dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n"; 1058 } 1059 ); 1060 1061 for (unsigned Iter = 1; Iter < Scale; ++Iter) { 1062 // In addition to regular aliasing information, we need to look for 1063 // instructions from later (future) iterations that have side effects 1064 // preventing us from reordering them past other instructions with side 1065 // effects. 1066 bool FutureSideEffects = false; 1067 AliasSetTracker AST(*AA); 1068 // The map between instructions in f(%iv.(i+1)) and f(%iv). 1069 DenseMap<Value *, Value *> BaseMap; 1070 1071 // Compare iteration Iter to the base. 1072 SmallInstructionSet Visited; 1073 auto BaseIt = nextInstr(0, Uses, Visited); 1074 auto RootIt = nextInstr(Iter, Uses, Visited); 1075 auto LastRootIt = Uses.begin(); 1076 1077 while (BaseIt != Uses.end() && RootIt != Uses.end()) { 1078 Instruction *BaseInst = BaseIt->first; 1079 Instruction *RootInst = RootIt->first; 1080 1081 // Skip over the IV or root instructions; only match their users. 1082 bool Continue = false; 1083 if (isBaseInst(BaseInst)) { 1084 Visited.insert(BaseInst); 1085 BaseIt = nextInstr(0, Uses, Visited); 1086 Continue = true; 1087 } 1088 if (isRootInst(RootInst)) { 1089 LastRootIt = RootIt; 1090 Visited.insert(RootInst); 1091 RootIt = nextInstr(Iter, Uses, Visited); 1092 Continue = true; 1093 } 1094 if (Continue) continue; 1095 1096 if (!BaseInst->isSameOperationAs(RootInst)) { 1097 // Last chance saloon. We don't try and solve the full isomorphism 1098 // problem, but try and at least catch the case where two instructions 1099 // *of different types* are round the wrong way. We won't be able to 1100 // efficiently tell, given two ADD instructions, which way around we 1101 // should match them, but given an ADD and a SUB, we can at least infer 1102 // which one is which. 1103 // 1104 // This should allow us to deal with a greater subset of the isomorphism 1105 // problem. It does however change a linear algorithm into a quadratic 1106 // one, so limit the number of probes we do. 1107 auto TryIt = RootIt; 1108 unsigned N = NumToleratedFailedMatches; 1109 while (TryIt != Uses.end() && 1110 !BaseInst->isSameOperationAs(TryIt->first) && 1111 N--) { 1112 ++TryIt; 1113 TryIt = nextInstr(Iter, Uses, Visited, &TryIt); 1114 } 1115 1116 if (TryIt == Uses.end() || TryIt == RootIt || 1117 instrDependsOn(TryIt->first, RootIt, TryIt)) { 1118 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst << 1119 " vs. " << *RootInst << "\n"); 1120 return false; 1121 } 1122 1123 RootIt = TryIt; 1124 RootInst = TryIt->first; 1125 } 1126 1127 // All instructions between the last root and this root 1128 // may belong to some other iteration. If they belong to a 1129 // future iteration, then they're dangerous to alias with. 1130 // 1131 // Note that because we allow a limited amount of flexibility in the order 1132 // that we visit nodes, LastRootIt might be *before* RootIt, in which 1133 // case we've already checked this set of instructions so we shouldn't 1134 // do anything. 1135 for (; LastRootIt < RootIt; ++LastRootIt) { 1136 Instruction *I = LastRootIt->first; 1137 if (LastRootIt->second.find_first() < (int)Iter) 1138 continue; 1139 if (I->mayWriteToMemory()) 1140 AST.add(I); 1141 // Note: This is specifically guarded by a check on isa<PHINode>, 1142 // which while a valid (somewhat arbitrary) micro-optimization, is 1143 // needed because otherwise isSafeToSpeculativelyExecute returns 1144 // false on PHI nodes. 1145 if (!isa<PHINode>(I) && !isSimpleLoadStore(I) && 1146 !isSafeToSpeculativelyExecute(I)) 1147 // Intervening instructions cause side effects. 1148 FutureSideEffects = true; 1149 } 1150 1151 // Make sure that this instruction, which is in the use set of this 1152 // root instruction, does not also belong to the base set or the set of 1153 // some other root instruction. 1154 if (RootIt->second.count() > 1) { 1155 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst << 1156 " vs. " << *RootInst << " (prev. case overlap)\n"); 1157 return false; 1158 } 1159 1160 // Make sure that we don't alias with any instruction in the alias set 1161 // tracker. If we do, then we depend on a future iteration, and we 1162 // can't reroll. 1163 if (RootInst->mayReadFromMemory()) 1164 for (auto &K : AST) { 1165 if (K.aliasesUnknownInst(RootInst, *AA)) { 1166 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst << 1167 " vs. " << *RootInst << " (depends on future store)\n"); 1168 return false; 1169 } 1170 } 1171 1172 // If we've past an instruction from a future iteration that may have 1173 // side effects, and this instruction might also, then we can't reorder 1174 // them, and this matching fails. As an exception, we allow the alias 1175 // set tracker to handle regular (simple) load/store dependencies. 1176 if (FutureSideEffects && ((!isSimpleLoadStore(BaseInst) && 1177 !isSafeToSpeculativelyExecute(BaseInst)) || 1178 (!isSimpleLoadStore(RootInst) && 1179 !isSafeToSpeculativelyExecute(RootInst)))) { 1180 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst << 1181 " vs. " << *RootInst << 1182 " (side effects prevent reordering)\n"); 1183 return false; 1184 } 1185 1186 // For instructions that are part of a reduction, if the operation is 1187 // associative, then don't bother matching the operands (because we 1188 // already know that the instructions are isomorphic, and the order 1189 // within the iteration does not matter). For non-associative reductions, 1190 // we do need to match the operands, because we need to reject 1191 // out-of-order instructions within an iteration! 1192 // For example (assume floating-point addition), we need to reject this: 1193 // x += a[i]; x += b[i]; 1194 // x += a[i+1]; x += b[i+1]; 1195 // x += b[i+2]; x += a[i+2]; 1196 bool InReduction = Reductions.isPairInSame(BaseInst, RootInst); 1197 1198 if (!(InReduction && BaseInst->isAssociative())) { 1199 bool Swapped = false, SomeOpMatched = false; 1200 for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) { 1201 Value *Op2 = RootInst->getOperand(j); 1202 1203 // If this is part of a reduction (and the operation is not 1204 // associatve), then we match all operands, but not those that are 1205 // part of the reduction. 1206 if (InReduction) 1207 if (Instruction *Op2I = dyn_cast<Instruction>(Op2)) 1208 if (Reductions.isPairInSame(RootInst, Op2I)) 1209 continue; 1210 1211 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2); 1212 if (BMI != BaseMap.end()) { 1213 Op2 = BMI->second; 1214 } else { 1215 for (auto &DRS : RootSets) { 1216 if (DRS.Roots[Iter-1] == (Instruction*) Op2) { 1217 Op2 = DRS.BaseInst; 1218 break; 1219 } 1220 } 1221 } 1222 1223 if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) { 1224 // If we've not already decided to swap the matched operands, and 1225 // we've not already matched our first operand (note that we could 1226 // have skipped matching the first operand because it is part of a 1227 // reduction above), and the instruction is commutative, then try 1228 // the swapped match. 1229 if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched && 1230 BaseInst->getOperand(!j) == Op2) { 1231 Swapped = true; 1232 } else { 1233 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst 1234 << " vs. " << *RootInst << " (operand " << j << ")\n"); 1235 return false; 1236 } 1237 } 1238 1239 SomeOpMatched = true; 1240 } 1241 } 1242 1243 if ((!PossibleRedLastSet.count(BaseInst) && 1244 hasUsesOutsideLoop(BaseInst, L)) || 1245 (!PossibleRedLastSet.count(RootInst) && 1246 hasUsesOutsideLoop(RootInst, L))) { 1247 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst << 1248 " vs. " << *RootInst << " (uses outside loop)\n"); 1249 return false; 1250 } 1251 1252 Reductions.recordPair(BaseInst, RootInst, Iter); 1253 BaseMap.insert(std::make_pair(RootInst, BaseInst)); 1254 1255 LastRootIt = RootIt; 1256 Visited.insert(BaseInst); 1257 Visited.insert(RootInst); 1258 BaseIt = nextInstr(0, Uses, Visited); 1259 RootIt = nextInstr(Iter, Uses, Visited); 1260 } 1261 assert (BaseIt == Uses.end() && RootIt == Uses.end() && 1262 "Mismatched set sizes!"); 1263 } 1264 1265 DEBUG(dbgs() << "LRR: Matched all iteration increments for " << 1266 *IV << "\n"); 1267 1268 return true; 1269 } 1270 1271 void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) { 1272 BasicBlock *Header = L->getHeader(); 1273 // Remove instructions associated with non-base iterations. 1274 for (BasicBlock::reverse_iterator J = Header->rbegin(); 1275 J != Header->rend();) { 1276 unsigned I = Uses[&*J].find_first(); 1277 if (I > 0 && I < IL_All) { 1278 Instruction *D = &*J; 1279 DEBUG(dbgs() << "LRR: removing: " << *D << "\n"); 1280 D->eraseFromParent(); 1281 continue; 1282 } 1283 1284 ++J; 1285 } 1286 bool Negative = IVToIncMap[IV] < 0; 1287 const DataLayout &DL = Header->getModule()->getDataLayout(); 1288 1289 // We need to create a new induction variable for each different BaseInst. 1290 for (auto &DRS : RootSets) { 1291 // Insert the new induction variable. 1292 const SCEVAddRecExpr *RealIVSCEV = 1293 cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst)); 1294 const SCEV *Start = RealIVSCEV->getStart(); 1295 const SCEVAddRecExpr *H = cast<SCEVAddRecExpr>(SE->getAddRecExpr( 1296 Start, SE->getConstant(RealIVSCEV->getType(), Negative ? -1 : 1), L, 1297 SCEV::FlagAnyWrap)); 1298 { // Limit the lifetime of SCEVExpander. 1299 SCEVExpander Expander(*SE, DL, "reroll"); 1300 Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin()); 1301 1302 for (auto &KV : Uses) { 1303 if (KV.second.find_first() == 0) 1304 KV.first->replaceUsesOfWith(DRS.BaseInst, NewIV); 1305 } 1306 1307 if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) { 1308 // FIXME: Why do we need this check? 1309 if (Uses[BI].find_first() == IL_All) { 1310 const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE); 1311 1312 // Iteration count SCEV minus 1 1313 const SCEV *ICMinus1SCEV = SE->getMinusSCEV( 1314 ICSCEV, SE->getConstant(ICSCEV->getType(), Negative ? -1 : 1)); 1315 1316 Value *ICMinus1; // Iteration count minus 1 1317 if (isa<SCEVConstant>(ICMinus1SCEV)) { 1318 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI); 1319 } else { 1320 BasicBlock *Preheader = L->getLoopPreheader(); 1321 if (!Preheader) 1322 Preheader = InsertPreheaderForLoop(L, Parent); 1323 1324 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), 1325 Preheader->getTerminator()); 1326 } 1327 1328 Value *Cond = 1329 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1, "exitcond"); 1330 BI->setCondition(Cond); 1331 1332 if (BI->getSuccessor(1) != Header) 1333 BI->swapSuccessors(); 1334 } 1335 } 1336 } 1337 } 1338 1339 SimplifyInstructionsInBlock(Header, TLI); 1340 DeleteDeadPHIs(Header, TLI); 1341 } 1342 1343 // Validate the selected reductions. All iterations must have an isomorphic 1344 // part of the reduction chain and, for non-associative reductions, the chain 1345 // entries must appear in order. 1346 bool LoopReroll::ReductionTracker::validateSelected() { 1347 // For a non-associative reduction, the chain entries must appear in order. 1348 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end(); 1349 RI != RIE; ++RI) { 1350 int i = *RI; 1351 int PrevIter = 0, BaseCount = 0, Count = 0; 1352 for (Instruction *J : PossibleReds[i]) { 1353 // Note that all instructions in the chain must have been found because 1354 // all instructions in the function must have been assigned to some 1355 // iteration. 1356 int Iter = PossibleRedIter[J]; 1357 if (Iter != PrevIter && Iter != PrevIter + 1 && 1358 !PossibleReds[i].getReducedValue()->isAssociative()) { 1359 DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " << 1360 J << "\n"); 1361 return false; 1362 } 1363 1364 if (Iter != PrevIter) { 1365 if (Count != BaseCount) { 1366 DEBUG(dbgs() << "LRR: Iteration " << PrevIter << 1367 " reduction use count " << Count << 1368 " is not equal to the base use count " << 1369 BaseCount << "\n"); 1370 return false; 1371 } 1372 1373 Count = 0; 1374 } 1375 1376 ++Count; 1377 if (Iter == 0) 1378 ++BaseCount; 1379 1380 PrevIter = Iter; 1381 } 1382 } 1383 1384 return true; 1385 } 1386 1387 // For all selected reductions, remove all parts except those in the first 1388 // iteration (and the PHI). Replace outside uses of the reduced value with uses 1389 // of the first-iteration reduced value (in other words, reroll the selected 1390 // reductions). 1391 void LoopReroll::ReductionTracker::replaceSelected() { 1392 // Fixup reductions to refer to the last instruction associated with the 1393 // first iteration (not the last). 1394 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end(); 1395 RI != RIE; ++RI) { 1396 int i = *RI; 1397 int j = 0; 1398 for (int e = PossibleReds[i].size(); j != e; ++j) 1399 if (PossibleRedIter[PossibleReds[i][j]] != 0) { 1400 --j; 1401 break; 1402 } 1403 1404 // Replace users with the new end-of-chain value. 1405 SmallInstructionVector Users; 1406 for (User *U : PossibleReds[i].getReducedValue()->users()) { 1407 Users.push_back(cast<Instruction>(U)); 1408 } 1409 1410 for (SmallInstructionVector::iterator J = Users.begin(), 1411 JE = Users.end(); J != JE; ++J) 1412 (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(), 1413 PossibleReds[i][j]); 1414 } 1415 } 1416 1417 // Reroll the provided loop with respect to the provided induction variable. 1418 // Generally, we're looking for a loop like this: 1419 // 1420 // %iv = phi [ (preheader, ...), (body, %iv.next) ] 1421 // f(%iv) 1422 // %iv.1 = add %iv, 1 <-- a root increment 1423 // f(%iv.1) 1424 // %iv.2 = add %iv, 2 <-- a root increment 1425 // f(%iv.2) 1426 // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment 1427 // f(%iv.scale_m_1) 1428 // ... 1429 // %iv.next = add %iv, scale 1430 // %cmp = icmp(%iv, ...) 1431 // br %cmp, header, exit 1432 // 1433 // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of 1434 // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can 1435 // be intermixed with eachother. The restriction imposed by this algorithm is 1436 // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1), 1437 // etc. be the same. 1438 // 1439 // First, we collect the use set of %iv, excluding the other increment roots. 1440 // This gives us f(%iv). Then we iterate over the loop instructions (scale-1) 1441 // times, having collected the use set of f(%iv.(i+1)), during which we: 1442 // - Ensure that the next unmatched instruction in f(%iv) is isomorphic to 1443 // the next unmatched instruction in f(%iv.(i+1)). 1444 // - Ensure that both matched instructions don't have any external users 1445 // (with the exception of last-in-chain reduction instructions). 1446 // - Track the (aliasing) write set, and other side effects, of all 1447 // instructions that belong to future iterations that come before the matched 1448 // instructions. If the matched instructions read from that write set, then 1449 // f(%iv) or f(%iv.(i+1)) has some dependency on instructions in 1450 // f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly, 1451 // if any of these future instructions had side effects (could not be 1452 // speculatively executed), and so do the matched instructions, when we 1453 // cannot reorder those side-effect-producing instructions, and rerolling 1454 // fails. 1455 // 1456 // Finally, we make sure that all loop instructions are either loop increment 1457 // roots, belong to simple latch code, parts of validated reductions, part of 1458 // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions 1459 // have been validated), then we reroll the loop. 1460 bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header, 1461 const SCEV *IterCount, 1462 ReductionTracker &Reductions) { 1463 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, IVToIncMap); 1464 1465 if (!DAGRoots.findRoots()) 1466 return false; 1467 DEBUG(dbgs() << "LRR: Found all root induction increments for: " << 1468 *IV << "\n"); 1469 1470 if (!DAGRoots.validate(Reductions)) 1471 return false; 1472 if (!Reductions.validateSelected()) 1473 return false; 1474 // At this point, we've validated the rerolling, and we're committed to 1475 // making changes! 1476 1477 Reductions.replaceSelected(); 1478 DAGRoots.replace(IterCount); 1479 1480 ++NumRerolledLoops; 1481 return true; 1482 } 1483 1484 bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) { 1485 if (skipOptnoneFunction(L)) 1486 return false; 1487 1488 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 1489 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1490 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1491 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 1492 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1493 1494 BasicBlock *Header = L->getHeader(); 1495 DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() << 1496 "] Loop %" << Header->getName() << " (" << 1497 L->getNumBlocks() << " block(s))\n"); 1498 1499 bool Changed = false; 1500 1501 // For now, we'll handle only single BB loops. 1502 if (L->getNumBlocks() > 1) 1503 return Changed; 1504 1505 if (!SE->hasLoopInvariantBackedgeTakenCount(L)) 1506 return Changed; 1507 1508 const SCEV *LIBETC = SE->getBackedgeTakenCount(L); 1509 const SCEV *IterCount = SE->getAddExpr(LIBETC, SE->getOne(LIBETC->getType())); 1510 DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n"); 1511 1512 // First, we need to find the induction variable with respect to which we can 1513 // reroll (there may be several possible options). 1514 SmallInstructionVector PossibleIVs; 1515 IVToIncMap.clear(); 1516 collectPossibleIVs(L, PossibleIVs); 1517 1518 if (PossibleIVs.empty()) { 1519 DEBUG(dbgs() << "LRR: No possible IVs found\n"); 1520 return Changed; 1521 } 1522 1523 ReductionTracker Reductions; 1524 collectPossibleReductions(L, Reductions); 1525 1526 // For each possible IV, collect the associated possible set of 'root' nodes 1527 // (i+1, i+2, etc.). 1528 for (SmallInstructionVector::iterator I = PossibleIVs.begin(), 1529 IE = PossibleIVs.end(); I != IE; ++I) 1530 if (reroll(*I, L, Header, IterCount, Reductions)) { 1531 Changed = true; 1532 break; 1533 } 1534 1535 return Changed; 1536 } 1537