1 //===-- LoopUtils.cpp - Loop Utility functions -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines common loop utility functions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Transforms/Utils/LoopUtils.h" 14 #include "llvm/ADT/ScopeExit.h" 15 #include "llvm/Analysis/AliasAnalysis.h" 16 #include "llvm/Analysis/BasicAliasAnalysis.h" 17 #include "llvm/Analysis/DomTreeUpdater.h" 18 #include "llvm/Analysis/GlobalsModRef.h" 19 #include "llvm/Analysis/InstructionSimplify.h" 20 #include "llvm/Analysis/LoopInfo.h" 21 #include "llvm/Analysis/LoopPass.h" 22 #include "llvm/Analysis/MemorySSA.h" 23 #include "llvm/Analysis/MemorySSAUpdater.h" 24 #include "llvm/Analysis/MustExecute.h" 25 #include "llvm/Analysis/ScalarEvolution.h" 26 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 27 #include "llvm/Analysis/ScalarEvolutionExpander.h" 28 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 29 #include "llvm/Analysis/TargetTransformInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/IR/DIBuilder.h" 32 #include "llvm/IR/Dominators.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/IR/MDBuilder.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/PatternMatch.h" 38 #include "llvm/IR/ValueHandle.h" 39 #include "llvm/InitializePasses.h" 40 #include "llvm/Pass.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/KnownBits.h" 43 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 44 #include "llvm/Transforms/Utils/Local.h" 45 46 using namespace llvm; 47 using namespace llvm::PatternMatch; 48 49 #define DEBUG_TYPE "loop-utils" 50 51 static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced"; 52 static const char *LLVMLoopDisableLICM = "llvm.licm.disable"; 53 54 bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, 55 MemorySSAUpdater *MSSAU, 56 bool PreserveLCSSA) { 57 bool Changed = false; 58 59 // We re-use a vector for the in-loop predecesosrs. 60 SmallVector<BasicBlock *, 4> InLoopPredecessors; 61 62 auto RewriteExit = [&](BasicBlock *BB) { 63 assert(InLoopPredecessors.empty() && 64 "Must start with an empty predecessors list!"); 65 auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); }); 66 67 // See if there are any non-loop predecessors of this exit block and 68 // keep track of the in-loop predecessors. 69 bool IsDedicatedExit = true; 70 for (auto *PredBB : predecessors(BB)) 71 if (L->contains(PredBB)) { 72 if (isa<IndirectBrInst>(PredBB->getTerminator())) 73 // We cannot rewrite exiting edges from an indirectbr. 74 return false; 75 if (isa<CallBrInst>(PredBB->getTerminator())) 76 // We cannot rewrite exiting edges from a callbr. 77 return false; 78 79 InLoopPredecessors.push_back(PredBB); 80 } else { 81 IsDedicatedExit = false; 82 } 83 84 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!"); 85 86 // Nothing to do if this is already a dedicated exit. 87 if (IsDedicatedExit) 88 return false; 89 90 auto *NewExitBB = SplitBlockPredecessors( 91 BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA); 92 93 if (!NewExitBB) 94 LLVM_DEBUG( 95 dbgs() << "WARNING: Can't create a dedicated exit block for loop: " 96 << *L << "\n"); 97 else 98 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block " 99 << NewExitBB->getName() << "\n"); 100 return true; 101 }; 102 103 // Walk the exit blocks directly rather than building up a data structure for 104 // them, but only visit each one once. 105 SmallPtrSet<BasicBlock *, 4> Visited; 106 for (auto *BB : L->blocks()) 107 for (auto *SuccBB : successors(BB)) { 108 // We're looking for exit blocks so skip in-loop successors. 109 if (L->contains(SuccBB)) 110 continue; 111 112 // Visit each exit block exactly once. 113 if (!Visited.insert(SuccBB).second) 114 continue; 115 116 Changed |= RewriteExit(SuccBB); 117 } 118 119 return Changed; 120 } 121 122 /// Returns the instructions that use values defined in the loop. 123 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) { 124 SmallVector<Instruction *, 8> UsedOutside; 125 126 for (auto *Block : L->getBlocks()) 127 // FIXME: I believe that this could use copy_if if the Inst reference could 128 // be adapted into a pointer. 129 for (auto &Inst : *Block) { 130 auto Users = Inst.users(); 131 if (any_of(Users, [&](User *U) { 132 auto *Use = cast<Instruction>(U); 133 return !L->contains(Use->getParent()); 134 })) 135 UsedOutside.push_back(&Inst); 136 } 137 138 return UsedOutside; 139 } 140 141 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) { 142 // By definition, all loop passes need the LoopInfo analysis and the 143 // Dominator tree it depends on. Because they all participate in the loop 144 // pass manager, they must also preserve these. 145 AU.addRequired<DominatorTreeWrapperPass>(); 146 AU.addPreserved<DominatorTreeWrapperPass>(); 147 AU.addRequired<LoopInfoWrapperPass>(); 148 AU.addPreserved<LoopInfoWrapperPass>(); 149 150 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs 151 // here because users shouldn't directly get them from this header. 152 extern char &LoopSimplifyID; 153 extern char &LCSSAID; 154 AU.addRequiredID(LoopSimplifyID); 155 AU.addPreservedID(LoopSimplifyID); 156 AU.addRequiredID(LCSSAID); 157 AU.addPreservedID(LCSSAID); 158 // This is used in the LPPassManager to perform LCSSA verification on passes 159 // which preserve lcssa form 160 AU.addRequired<LCSSAVerificationPass>(); 161 AU.addPreserved<LCSSAVerificationPass>(); 162 163 // Loop passes are designed to run inside of a loop pass manager which means 164 // that any function analyses they require must be required by the first loop 165 // pass in the manager (so that it is computed before the loop pass manager 166 // runs) and preserved by all loop pasess in the manager. To make this 167 // reasonably robust, the set needed for most loop passes is maintained here. 168 // If your loop pass requires an analysis not listed here, you will need to 169 // carefully audit the loop pass manager nesting structure that results. 170 AU.addRequired<AAResultsWrapperPass>(); 171 AU.addPreserved<AAResultsWrapperPass>(); 172 AU.addPreserved<BasicAAWrapperPass>(); 173 AU.addPreserved<GlobalsAAWrapperPass>(); 174 AU.addPreserved<SCEVAAWrapperPass>(); 175 AU.addRequired<ScalarEvolutionWrapperPass>(); 176 AU.addPreserved<ScalarEvolutionWrapperPass>(); 177 // FIXME: When all loop passes preserve MemorySSA, it can be required and 178 // preserved here instead of the individual handling in each pass. 179 } 180 181 /// Manually defined generic "LoopPass" dependency initialization. This is used 182 /// to initialize the exact set of passes from above in \c 183 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization 184 /// with: 185 /// 186 /// INITIALIZE_PASS_DEPENDENCY(LoopPass) 187 /// 188 /// As-if "LoopPass" were a pass. 189 void llvm::initializeLoopPassPass(PassRegistry &Registry) { 190 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 191 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 192 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 193 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 194 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 195 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 196 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 197 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 198 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 199 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 200 } 201 202 /// Create MDNode for input string. 203 static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) { 204 LLVMContext &Context = TheLoop->getHeader()->getContext(); 205 Metadata *MDs[] = { 206 MDString::get(Context, Name), 207 ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))}; 208 return MDNode::get(Context, MDs); 209 } 210 211 /// Set input string into loop metadata by keeping other values intact. 212 /// If the string is already in loop metadata update value if it is 213 /// different. 214 void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD, 215 unsigned V) { 216 SmallVector<Metadata *, 4> MDs(1); 217 // If the loop already has metadata, retain it. 218 MDNode *LoopID = TheLoop->getLoopID(); 219 if (LoopID) { 220 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 221 MDNode *Node = cast<MDNode>(LoopID->getOperand(i)); 222 // If it is of form key = value, try to parse it. 223 if (Node->getNumOperands() == 2) { 224 MDString *S = dyn_cast<MDString>(Node->getOperand(0)); 225 if (S && S->getString().equals(StringMD)) { 226 ConstantInt *IntMD = 227 mdconst::extract_or_null<ConstantInt>(Node->getOperand(1)); 228 if (IntMD && IntMD->getSExtValue() == V) 229 // It is already in place. Do nothing. 230 return; 231 // We need to update the value, so just skip it here and it will 232 // be added after copying other existed nodes. 233 continue; 234 } 235 } 236 MDs.push_back(Node); 237 } 238 } 239 // Add new metadata. 240 MDs.push_back(createStringMetadata(TheLoop, StringMD, V)); 241 // Replace current metadata node with new one. 242 LLVMContext &Context = TheLoop->getHeader()->getContext(); 243 MDNode *NewLoopID = MDNode::get(Context, MDs); 244 // Set operand 0 to refer to the loop id itself. 245 NewLoopID->replaceOperandWith(0, NewLoopID); 246 TheLoop->setLoopID(NewLoopID); 247 } 248 249 /// Find string metadata for loop 250 /// 251 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an 252 /// operand or null otherwise. If the string metadata is not found return 253 /// Optional's not-a-value. 254 Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop, 255 StringRef Name) { 256 MDNode *MD = findOptionMDForLoop(TheLoop, Name); 257 if (!MD) 258 return None; 259 switch (MD->getNumOperands()) { 260 case 1: 261 return nullptr; 262 case 2: 263 return &MD->getOperand(1); 264 default: 265 llvm_unreachable("loop metadata has 0 or 1 operand"); 266 } 267 } 268 269 static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop, 270 StringRef Name) { 271 MDNode *MD = findOptionMDForLoop(TheLoop, Name); 272 if (!MD) 273 return None; 274 switch (MD->getNumOperands()) { 275 case 1: 276 // When the value is absent it is interpreted as 'attribute set'. 277 return true; 278 case 2: 279 if (ConstantInt *IntMD = 280 mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get())) 281 return IntMD->getZExtValue(); 282 return true; 283 } 284 llvm_unreachable("unexpected number of options"); 285 } 286 287 static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) { 288 return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false); 289 } 290 291 llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop, 292 StringRef Name) { 293 const MDOperand *AttrMD = 294 findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr); 295 if (!AttrMD) 296 return None; 297 298 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get()); 299 if (!IntMD) 300 return None; 301 302 return IntMD->getSExtValue(); 303 } 304 305 Optional<MDNode *> llvm::makeFollowupLoopID( 306 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions, 307 const char *InheritOptionsExceptPrefix, bool AlwaysNew) { 308 if (!OrigLoopID) { 309 if (AlwaysNew) 310 return nullptr; 311 return None; 312 } 313 314 assert(OrigLoopID->getOperand(0) == OrigLoopID); 315 316 bool InheritAllAttrs = !InheritOptionsExceptPrefix; 317 bool InheritSomeAttrs = 318 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0'; 319 SmallVector<Metadata *, 8> MDs; 320 MDs.push_back(nullptr); 321 322 bool Changed = false; 323 if (InheritAllAttrs || InheritSomeAttrs) { 324 for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) { 325 MDNode *Op = cast<MDNode>(Existing.get()); 326 327 auto InheritThisAttribute = [InheritSomeAttrs, 328 InheritOptionsExceptPrefix](MDNode *Op) { 329 if (!InheritSomeAttrs) 330 return false; 331 332 // Skip malformatted attribute metadata nodes. 333 if (Op->getNumOperands() == 0) 334 return true; 335 Metadata *NameMD = Op->getOperand(0).get(); 336 if (!isa<MDString>(NameMD)) 337 return true; 338 StringRef AttrName = cast<MDString>(NameMD)->getString(); 339 340 // Do not inherit excluded attributes. 341 return !AttrName.startswith(InheritOptionsExceptPrefix); 342 }; 343 344 if (InheritThisAttribute(Op)) 345 MDs.push_back(Op); 346 else 347 Changed = true; 348 } 349 } else { 350 // Modified if we dropped at least one attribute. 351 Changed = OrigLoopID->getNumOperands() > 1; 352 } 353 354 bool HasAnyFollowup = false; 355 for (StringRef OptionName : FollowupOptions) { 356 MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName); 357 if (!FollowupNode) 358 continue; 359 360 HasAnyFollowup = true; 361 for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) { 362 MDs.push_back(Option.get()); 363 Changed = true; 364 } 365 } 366 367 // Attributes of the followup loop not specified explicity, so signal to the 368 // transformation pass to add suitable attributes. 369 if (!AlwaysNew && !HasAnyFollowup) 370 return None; 371 372 // If no attributes were added or remove, the previous loop Id can be reused. 373 if (!AlwaysNew && !Changed) 374 return OrigLoopID; 375 376 // No attributes is equivalent to having no !llvm.loop metadata at all. 377 if (MDs.size() == 1) 378 return nullptr; 379 380 // Build the new loop ID. 381 MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs); 382 FollowupLoopID->replaceOperandWith(0, FollowupLoopID); 383 return FollowupLoopID; 384 } 385 386 bool llvm::hasDisableAllTransformsHint(const Loop *L) { 387 return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced); 388 } 389 390 bool llvm::hasDisableLICMTransformsHint(const Loop *L) { 391 return getBooleanLoopAttribute(L, LLVMLoopDisableLICM); 392 } 393 394 TransformationMode llvm::hasUnrollTransformation(Loop *L) { 395 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable")) 396 return TM_SuppressedByUser; 397 398 Optional<int> Count = 399 getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count"); 400 if (Count.hasValue()) 401 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 402 403 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable")) 404 return TM_ForcedByUser; 405 406 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full")) 407 return TM_ForcedByUser; 408 409 if (hasDisableAllTransformsHint(L)) 410 return TM_Disable; 411 412 return TM_Unspecified; 413 } 414 415 TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) { 416 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable")) 417 return TM_SuppressedByUser; 418 419 Optional<int> Count = 420 getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count"); 421 if (Count.hasValue()) 422 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 423 424 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable")) 425 return TM_ForcedByUser; 426 427 if (hasDisableAllTransformsHint(L)) 428 return TM_Disable; 429 430 return TM_Unspecified; 431 } 432 433 TransformationMode llvm::hasVectorizeTransformation(Loop *L) { 434 Optional<bool> Enable = 435 getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable"); 436 437 if (Enable == false) 438 return TM_SuppressedByUser; 439 440 Optional<int> VectorizeWidth = 441 getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width"); 442 Optional<int> InterleaveCount = 443 getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count"); 444 445 // 'Forcing' vector width and interleave count to one effectively disables 446 // this tranformation. 447 if (Enable == true && VectorizeWidth == 1 && InterleaveCount == 1) 448 return TM_SuppressedByUser; 449 450 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized")) 451 return TM_Disable; 452 453 if (Enable == true) 454 return TM_ForcedByUser; 455 456 if (VectorizeWidth == 1 && InterleaveCount == 1) 457 return TM_Disable; 458 459 if (VectorizeWidth > 1 || InterleaveCount > 1) 460 return TM_Enable; 461 462 if (hasDisableAllTransformsHint(L)) 463 return TM_Disable; 464 465 return TM_Unspecified; 466 } 467 468 TransformationMode llvm::hasDistributeTransformation(Loop *L) { 469 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable")) 470 return TM_ForcedByUser; 471 472 if (hasDisableAllTransformsHint(L)) 473 return TM_Disable; 474 475 return TM_Unspecified; 476 } 477 478 TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) { 479 if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable")) 480 return TM_SuppressedByUser; 481 482 if (hasDisableAllTransformsHint(L)) 483 return TM_Disable; 484 485 return TM_Unspecified; 486 } 487 488 /// Does a BFS from a given node to all of its children inside a given loop. 489 /// The returned vector of nodes includes the starting point. 490 SmallVector<DomTreeNode *, 16> 491 llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) { 492 SmallVector<DomTreeNode *, 16> Worklist; 493 auto AddRegionToWorklist = [&](DomTreeNode *DTN) { 494 // Only include subregions in the top level loop. 495 BasicBlock *BB = DTN->getBlock(); 496 if (CurLoop->contains(BB)) 497 Worklist.push_back(DTN); 498 }; 499 500 AddRegionToWorklist(N); 501 502 for (size_t I = 0; I < Worklist.size(); I++) 503 for (DomTreeNode *Child : Worklist[I]->getChildren()) 504 AddRegionToWorklist(Child); 505 506 return Worklist; 507 } 508 509 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE, 510 LoopInfo *LI, MemorySSA *MSSA) { 511 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!"); 512 auto *Preheader = L->getLoopPreheader(); 513 assert(Preheader && "Preheader should exist!"); 514 515 std::unique_ptr<MemorySSAUpdater> MSSAU; 516 if (MSSA) 517 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 518 519 // Now that we know the removal is safe, remove the loop by changing the 520 // branch from the preheader to go to the single exit block. 521 // 522 // Because we're deleting a large chunk of code at once, the sequence in which 523 // we remove things is very important to avoid invalidation issues. 524 525 // Tell ScalarEvolution that the loop is deleted. Do this before 526 // deleting the loop so that ScalarEvolution can look at the loop 527 // to determine what it needs to clean up. 528 if (SE) 529 SE->forgetLoop(L); 530 531 auto *ExitBlock = L->getUniqueExitBlock(); 532 assert(ExitBlock && "Should have a unique exit block!"); 533 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!"); 534 535 auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator()); 536 assert(OldBr && "Preheader must end with a branch"); 537 assert(OldBr->isUnconditional() && "Preheader must have a single successor"); 538 // Connect the preheader to the exit block. Keep the old edge to the header 539 // around to perform the dominator tree update in two separate steps 540 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge 541 // preheader -> header. 542 // 543 // 544 // 0. Preheader 1. Preheader 2. Preheader 545 // | | | | 546 // V | V | 547 // Header <--\ | Header <--\ | Header <--\ 548 // | | | | | | | | | | | 549 // | V | | | V | | | V | 550 // | Body --/ | | Body --/ | | Body --/ 551 // V V V V V 552 // Exit Exit Exit 553 // 554 // By doing this is two separate steps we can perform the dominator tree 555 // update without using the batch update API. 556 // 557 // Even when the loop is never executed, we cannot remove the edge from the 558 // source block to the exit block. Consider the case where the unexecuted loop 559 // branches back to an outer loop. If we deleted the loop and removed the edge 560 // coming to this inner loop, this will break the outer loop structure (by 561 // deleting the backedge of the outer loop). If the outer loop is indeed a 562 // non-loop, it will be deleted in a future iteration of loop deletion pass. 563 IRBuilder<> Builder(OldBr); 564 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock); 565 // Remove the old branch. The conditional branch becomes a new terminator. 566 OldBr->eraseFromParent(); 567 568 // Rewrite phis in the exit block to get their inputs from the Preheader 569 // instead of the exiting block. 570 for (PHINode &P : ExitBlock->phis()) { 571 // Set the zero'th element of Phi to be from the preheader and remove all 572 // other incoming values. Given the loop has dedicated exits, all other 573 // incoming values must be from the exiting blocks. 574 int PredIndex = 0; 575 P.setIncomingBlock(PredIndex, Preheader); 576 // Removes all incoming values from all other exiting blocks (including 577 // duplicate values from an exiting block). 578 // Nuke all entries except the zero'th entry which is the preheader entry. 579 // NOTE! We need to remove Incoming Values in the reverse order as done 580 // below, to keep the indices valid for deletion (removeIncomingValues 581 // updates getNumIncomingValues and shifts all values down into the operand 582 // being deleted). 583 for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i) 584 P.removeIncomingValue(e - i, false); 585 586 assert((P.getNumIncomingValues() == 1 && 587 P.getIncomingBlock(PredIndex) == Preheader) && 588 "Should have exactly one value and that's from the preheader!"); 589 } 590 591 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 592 if (DT) { 593 DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}}); 594 if (MSSA) { 595 MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}}, *DT); 596 if (VerifyMemorySSA) 597 MSSA->verifyMemorySSA(); 598 } 599 } 600 601 // Disconnect the loop body by branching directly to its exit. 602 Builder.SetInsertPoint(Preheader->getTerminator()); 603 Builder.CreateBr(ExitBlock); 604 // Remove the old branch. 605 Preheader->getTerminator()->eraseFromParent(); 606 607 if (DT) { 608 DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}}); 609 if (MSSA) { 610 MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}}, 611 *DT); 612 if (VerifyMemorySSA) 613 MSSA->verifyMemorySSA(); 614 SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(), 615 L->block_end()); 616 MSSAU->removeBlocks(DeadBlockSet); 617 } 618 } 619 620 // Use a map to unique and a vector to guarantee deterministic ordering. 621 llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet; 622 llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst; 623 624 // Given LCSSA form is satisfied, we should not have users of instructions 625 // within the dead loop outside of the loop. However, LCSSA doesn't take 626 // unreachable uses into account. We handle them here. 627 // We could do it after drop all references (in this case all users in the 628 // loop will be already eliminated and we have less work to do but according 629 // to API doc of User::dropAllReferences only valid operation after dropping 630 // references, is deletion. So let's substitute all usages of 631 // instruction from the loop with undef value of corresponding type first. 632 for (auto *Block : L->blocks()) 633 for (Instruction &I : *Block) { 634 auto *Undef = UndefValue::get(I.getType()); 635 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) { 636 Use &U = *UI; 637 ++UI; 638 if (auto *Usr = dyn_cast<Instruction>(U.getUser())) 639 if (L->contains(Usr->getParent())) 640 continue; 641 // If we have a DT then we can check that uses outside a loop only in 642 // unreachable block. 643 if (DT) 644 assert(!DT->isReachableFromEntry(U) && 645 "Unexpected user in reachable block"); 646 U.set(Undef); 647 } 648 auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I); 649 if (!DVI) 650 continue; 651 auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()}); 652 if (Key != DeadDebugSet.end()) 653 continue; 654 DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()}); 655 DeadDebugInst.push_back(DVI); 656 } 657 658 // After the loop has been deleted all the values defined and modified 659 // inside the loop are going to be unavailable. 660 // Since debug values in the loop have been deleted, inserting an undef 661 // dbg.value truncates the range of any dbg.value before the loop where the 662 // loop used to be. This is particularly important for constant values. 663 DIBuilder DIB(*ExitBlock->getModule()); 664 Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI(); 665 assert(InsertDbgValueBefore && 666 "There should be a non-PHI instruction in exit block, else these " 667 "instructions will have no parent."); 668 for (auto *DVI : DeadDebugInst) 669 DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()), 670 DVI->getVariable(), DVI->getExpression(), 671 DVI->getDebugLoc(), InsertDbgValueBefore); 672 673 // Remove the block from the reference counting scheme, so that we can 674 // delete it freely later. 675 for (auto *Block : L->blocks()) 676 Block->dropAllReferences(); 677 678 if (MSSA && VerifyMemorySSA) 679 MSSA->verifyMemorySSA(); 680 681 if (LI) { 682 // Erase the instructions and the blocks without having to worry 683 // about ordering because we already dropped the references. 684 // NOTE: This iteration is safe because erasing the block does not remove 685 // its entry from the loop's block list. We do that in the next section. 686 for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end(); 687 LpI != LpE; ++LpI) 688 (*LpI)->eraseFromParent(); 689 690 // Finally, the blocks from loopinfo. This has to happen late because 691 // otherwise our loop iterators won't work. 692 693 SmallPtrSet<BasicBlock *, 8> blocks; 694 blocks.insert(L->block_begin(), L->block_end()); 695 for (BasicBlock *BB : blocks) 696 LI->removeBlock(BB); 697 698 // The last step is to update LoopInfo now that we've eliminated this loop. 699 // Note: LoopInfo::erase remove the given loop and relink its subloops with 700 // its parent. While removeLoop/removeChildLoop remove the given loop but 701 // not relink its subloops, which is what we want. 702 if (Loop *ParentLoop = L->getParentLoop()) { 703 Loop::iterator I = find(ParentLoop->begin(), ParentLoop->end(), L); 704 assert(I != ParentLoop->end() && "Couldn't find loop"); 705 ParentLoop->removeChildLoop(I); 706 } else { 707 Loop::iterator I = find(LI->begin(), LI->end(), L); 708 assert(I != LI->end() && "Couldn't find loop"); 709 LI->removeLoop(I); 710 } 711 LI->destroy(L); 712 } 713 } 714 715 /// Checks if \p L has single exit through latch block except possibly 716 /// "deoptimizing" exits. Returns branch instruction terminating the loop 717 /// latch if above check is successful, nullptr otherwise. 718 static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) { 719 BasicBlock *Latch = L->getLoopLatch(); 720 if (!Latch) 721 return nullptr; 722 723 BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator()); 724 if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch)) 725 return nullptr; 726 727 assert((LatchBR->getSuccessor(0) == L->getHeader() || 728 LatchBR->getSuccessor(1) == L->getHeader()) && 729 "At least one edge out of the latch must go to the header"); 730 731 SmallVector<BasicBlock *, 4> ExitBlocks; 732 L->getUniqueNonLatchExitBlocks(ExitBlocks); 733 if (any_of(ExitBlocks, [](const BasicBlock *EB) { 734 return !EB->getTerminatingDeoptimizeCall(); 735 })) 736 return nullptr; 737 738 return LatchBR; 739 } 740 741 Optional<unsigned> 742 llvm::getLoopEstimatedTripCount(Loop *L, 743 unsigned *EstimatedLoopInvocationWeight) { 744 // Support loops with an exiting latch and other existing exists only 745 // deoptimize. 746 BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L); 747 if (!LatchBranch) 748 return None; 749 750 // To estimate the number of times the loop body was executed, we want to 751 // know the number of times the backedge was taken, vs. the number of times 752 // we exited the loop. 753 uint64_t BackedgeTakenWeight, LatchExitWeight; 754 if (!LatchBranch->extractProfMetadata(BackedgeTakenWeight, LatchExitWeight)) 755 return None; 756 757 if (LatchBranch->getSuccessor(0) != L->getHeader()) 758 std::swap(BackedgeTakenWeight, LatchExitWeight); 759 760 if (!LatchExitWeight) 761 return None; 762 763 if (EstimatedLoopInvocationWeight) 764 *EstimatedLoopInvocationWeight = LatchExitWeight; 765 766 // Estimated backedge taken count is a ratio of the backedge taken weight by 767 // the weight of the edge exiting the loop, rounded to nearest. 768 uint64_t BackedgeTakenCount = 769 llvm::divideNearest(BackedgeTakenWeight, LatchExitWeight); 770 // Estimated trip count is one plus estimated backedge taken count. 771 return BackedgeTakenCount + 1; 772 } 773 774 bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, 775 unsigned EstimatedloopInvocationWeight) { 776 // Support loops with an exiting latch and other existing exists only 777 // deoptimize. 778 BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L); 779 if (!LatchBranch) 780 return false; 781 782 // Calculate taken and exit weights. 783 unsigned LatchExitWeight = 0; 784 unsigned BackedgeTakenWeight = 0; 785 786 if (EstimatedTripCount > 0) { 787 LatchExitWeight = EstimatedloopInvocationWeight; 788 BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight; 789 } 790 791 // Make a swap if back edge is taken when condition is "false". 792 if (LatchBranch->getSuccessor(0) != L->getHeader()) 793 std::swap(BackedgeTakenWeight, LatchExitWeight); 794 795 MDBuilder MDB(LatchBranch->getContext()); 796 797 // Set/Update profile metadata. 798 LatchBranch->setMetadata( 799 LLVMContext::MD_prof, 800 MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight)); 801 802 return true; 803 } 804 805 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop, 806 ScalarEvolution &SE) { 807 Loop *OuterL = InnerLoop->getParentLoop(); 808 if (!OuterL) 809 return true; 810 811 // Get the backedge taken count for the inner loop 812 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 813 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch); 814 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) || 815 !InnerLoopBECountSC->getType()->isIntegerTy()) 816 return false; 817 818 // Get whether count is invariant to the outer loop 819 ScalarEvolution::LoopDisposition LD = 820 SE.getLoopDisposition(InnerLoopBECountSC, OuterL); 821 if (LD != ScalarEvolution::LoopInvariant) 822 return false; 823 824 return true; 825 } 826 827 Value *llvm::createMinMaxOp(IRBuilderBase &Builder, 828 RecurrenceDescriptor::MinMaxRecurrenceKind RK, 829 Value *Left, Value *Right) { 830 CmpInst::Predicate P = CmpInst::ICMP_NE; 831 switch (RK) { 832 default: 833 llvm_unreachable("Unknown min/max recurrence kind"); 834 case RecurrenceDescriptor::MRK_UIntMin: 835 P = CmpInst::ICMP_ULT; 836 break; 837 case RecurrenceDescriptor::MRK_UIntMax: 838 P = CmpInst::ICMP_UGT; 839 break; 840 case RecurrenceDescriptor::MRK_SIntMin: 841 P = CmpInst::ICMP_SLT; 842 break; 843 case RecurrenceDescriptor::MRK_SIntMax: 844 P = CmpInst::ICMP_SGT; 845 break; 846 case RecurrenceDescriptor::MRK_FloatMin: 847 P = CmpInst::FCMP_OLT; 848 break; 849 case RecurrenceDescriptor::MRK_FloatMax: 850 P = CmpInst::FCMP_OGT; 851 break; 852 } 853 854 // We only match FP sequences that are 'fast', so we can unconditionally 855 // set it on any generated instructions. 856 IRBuilderBase::FastMathFlagGuard FMFG(Builder); 857 FastMathFlags FMF; 858 FMF.setFast(); 859 Builder.setFastMathFlags(FMF); 860 861 Value *Cmp; 862 if (RK == RecurrenceDescriptor::MRK_FloatMin || 863 RK == RecurrenceDescriptor::MRK_FloatMax) 864 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp"); 865 else 866 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp"); 867 868 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 869 return Select; 870 } 871 872 // Helper to generate an ordered reduction. 873 Value * 874 llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src, 875 unsigned Op, 876 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 877 ArrayRef<Value *> RedOps) { 878 unsigned VF = Src->getType()->getVectorNumElements(); 879 880 // Extract and apply reduction ops in ascending order: 881 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1] 882 Value *Result = Acc; 883 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) { 884 Value *Ext = 885 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx)); 886 887 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 888 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext, 889 "bin.rdx"); 890 } else { 891 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 892 "Invalid min/max"); 893 Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext); 894 } 895 896 if (!RedOps.empty()) 897 propagateIRFlags(Result, RedOps); 898 } 899 900 return Result; 901 } 902 903 // Helper to generate a log2 shuffle reduction. 904 Value * 905 llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src, unsigned Op, 906 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 907 ArrayRef<Value *> RedOps) { 908 unsigned VF = Src->getType()->getVectorNumElements(); 909 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 910 // and vector ops, reducing the set of values being computed by half each 911 // round. 912 assert(isPowerOf2_32(VF) && 913 "Reduction emission only supported for pow2 vectors!"); 914 Value *TmpVec = Src; 915 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr); 916 for (unsigned i = VF; i != 1; i >>= 1) { 917 // Move the upper half of the vector to the lower half. 918 for (unsigned j = 0; j != i / 2; ++j) 919 ShuffleMask[j] = Builder.getInt32(i / 2 + j); 920 921 // Fill the rest of the mask with undef. 922 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), 923 UndefValue::get(Builder.getInt32Ty())); 924 925 Value *Shuf = Builder.CreateShuffleVector( 926 TmpVec, UndefValue::get(TmpVec->getType()), 927 ConstantVector::get(ShuffleMask), "rdx.shuf"); 928 929 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 930 // The builder propagates its fast-math-flags setting. 931 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf, 932 "bin.rdx"); 933 } else { 934 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 935 "Invalid min/max"); 936 TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf); 937 } 938 if (!RedOps.empty()) 939 propagateIRFlags(TmpVec, RedOps); 940 941 // We may compute the reassociated scalar ops in a way that does not 942 // preserve nsw/nuw etc. Conservatively, drop those flags. 943 if (auto *ReductionInst = dyn_cast<Instruction>(TmpVec)) 944 ReductionInst->dropPoisonGeneratingFlags(); 945 } 946 // The result is in the first element of the vector. 947 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 948 } 949 950 /// Create a simple vector reduction specified by an opcode and some 951 /// flags (if generating min/max reductions). 952 Value *llvm::createSimpleTargetReduction( 953 IRBuilderBase &Builder, const TargetTransformInfo *TTI, unsigned Opcode, 954 Value *Src, TargetTransformInfo::ReductionFlags Flags, 955 ArrayRef<Value *> RedOps) { 956 assert(isa<VectorType>(Src->getType()) && "Type must be a vector"); 957 958 std::function<Value *()> BuildFunc; 959 using RD = RecurrenceDescriptor; 960 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid; 961 962 switch (Opcode) { 963 case Instruction::Add: 964 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); }; 965 break; 966 case Instruction::Mul: 967 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); }; 968 break; 969 case Instruction::And: 970 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); }; 971 break; 972 case Instruction::Or: 973 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); }; 974 break; 975 case Instruction::Xor: 976 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); }; 977 break; 978 case Instruction::FAdd: 979 BuildFunc = [&]() { 980 auto Rdx = Builder.CreateFAddReduce( 981 Constant::getNullValue(Src->getType()->getVectorElementType()), Src); 982 return Rdx; 983 }; 984 break; 985 case Instruction::FMul: 986 BuildFunc = [&]() { 987 Type *Ty = Src->getType()->getVectorElementType(); 988 auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src); 989 return Rdx; 990 }; 991 break; 992 case Instruction::ICmp: 993 if (Flags.IsMaxOp) { 994 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax; 995 BuildFunc = [&]() { 996 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned); 997 }; 998 } else { 999 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin; 1000 BuildFunc = [&]() { 1001 return Builder.CreateIntMinReduce(Src, Flags.IsSigned); 1002 }; 1003 } 1004 break; 1005 case Instruction::FCmp: 1006 if (Flags.IsMaxOp) { 1007 MinMaxKind = RD::MRK_FloatMax; 1008 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); }; 1009 } else { 1010 MinMaxKind = RD::MRK_FloatMin; 1011 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); }; 1012 } 1013 break; 1014 default: 1015 llvm_unreachable("Unhandled opcode"); 1016 break; 1017 } 1018 if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags)) 1019 return BuildFunc(); 1020 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps); 1021 } 1022 1023 /// Create a vector reduction using a given recurrence descriptor. 1024 Value *llvm::createTargetReduction(IRBuilderBase &B, 1025 const TargetTransformInfo *TTI, 1026 RecurrenceDescriptor &Desc, Value *Src, 1027 bool NoNaN) { 1028 // TODO: Support in-order reductions based on the recurrence descriptor. 1029 using RD = RecurrenceDescriptor; 1030 RD::RecurrenceKind RecKind = Desc.getRecurrenceKind(); 1031 TargetTransformInfo::ReductionFlags Flags; 1032 Flags.NoNaN = NoNaN; 1033 1034 // All ops in the reduction inherit fast-math-flags from the recurrence 1035 // descriptor. 1036 IRBuilderBase::FastMathFlagGuard FMFGuard(B); 1037 B.setFastMathFlags(Desc.getFastMathFlags()); 1038 1039 switch (RecKind) { 1040 case RD::RK_FloatAdd: 1041 return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags); 1042 case RD::RK_FloatMult: 1043 return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags); 1044 case RD::RK_IntegerAdd: 1045 return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags); 1046 case RD::RK_IntegerMult: 1047 return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags); 1048 case RD::RK_IntegerAnd: 1049 return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags); 1050 case RD::RK_IntegerOr: 1051 return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags); 1052 case RD::RK_IntegerXor: 1053 return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags); 1054 case RD::RK_IntegerMinMax: { 1055 RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind(); 1056 Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax); 1057 Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin); 1058 return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags); 1059 } 1060 case RD::RK_FloatMinMax: { 1061 Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax; 1062 return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags); 1063 } 1064 default: 1065 llvm_unreachable("Unhandled RecKind"); 1066 } 1067 } 1068 1069 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) { 1070 auto *VecOp = dyn_cast<Instruction>(I); 1071 if (!VecOp) 1072 return; 1073 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0]) 1074 : dyn_cast<Instruction>(OpValue); 1075 if (!Intersection) 1076 return; 1077 const unsigned Opcode = Intersection->getOpcode(); 1078 VecOp->copyIRFlags(Intersection); 1079 for (auto *V : VL) { 1080 auto *Instr = dyn_cast<Instruction>(V); 1081 if (!Instr) 1082 continue; 1083 if (OpValue == nullptr || Opcode == Instr->getOpcode()) 1084 VecOp->andIRFlags(V); 1085 } 1086 } 1087 1088 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L, 1089 ScalarEvolution &SE) { 1090 const SCEV *Zero = SE.getZero(S->getType()); 1091 return SE.isAvailableAtLoopEntry(S, L) && 1092 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero); 1093 } 1094 1095 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, 1096 ScalarEvolution &SE) { 1097 const SCEV *Zero = SE.getZero(S->getType()); 1098 return SE.isAvailableAtLoopEntry(S, L) && 1099 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero); 1100 } 1101 1102 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1103 bool Signed) { 1104 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1105 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) : 1106 APInt::getMinValue(BitWidth); 1107 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1108 return SE.isAvailableAtLoopEntry(S, L) && 1109 SE.isLoopEntryGuardedByCond(L, Predicate, S, 1110 SE.getConstant(Min)); 1111 } 1112 1113 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1114 bool Signed) { 1115 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1116 APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) : 1117 APInt::getMaxValue(BitWidth); 1118 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1119 return SE.isAvailableAtLoopEntry(S, L) && 1120 SE.isLoopEntryGuardedByCond(L, Predicate, S, 1121 SE.getConstant(Max)); 1122 } 1123 1124 //===----------------------------------------------------------------------===// 1125 // rewriteLoopExitValues - Optimize IV users outside the loop. 1126 // As a side effect, reduces the amount of IV processing within the loop. 1127 //===----------------------------------------------------------------------===// 1128 1129 // Return true if the SCEV expansion generated by the rewriter can replace the 1130 // original value. SCEV guarantees that it produces the same value, but the way 1131 // it is produced may be illegal IR. Ideally, this function will only be 1132 // called for verification. 1133 static bool isValidRewrite(ScalarEvolution *SE, Value *FromVal, Value *ToVal) { 1134 // If an SCEV expression subsumed multiple pointers, its expansion could 1135 // reassociate the GEP changing the base pointer. This is illegal because the 1136 // final address produced by a GEP chain must be inbounds relative to its 1137 // underlying object. Otherwise basic alias analysis, among other things, 1138 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid 1139 // producing an expression involving multiple pointers. Until then, we must 1140 // bail out here. 1141 // 1142 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject 1143 // because it understands lcssa phis while SCEV does not. 1144 Value *FromPtr = FromVal; 1145 Value *ToPtr = ToVal; 1146 if (auto *GEP = dyn_cast<GEPOperator>(FromVal)) 1147 FromPtr = GEP->getPointerOperand(); 1148 1149 if (auto *GEP = dyn_cast<GEPOperator>(ToVal)) 1150 ToPtr = GEP->getPointerOperand(); 1151 1152 if (FromPtr != FromVal || ToPtr != ToVal) { 1153 // Quickly check the common case 1154 if (FromPtr == ToPtr) 1155 return true; 1156 1157 // SCEV may have rewritten an expression that produces the GEP's pointer 1158 // operand. That's ok as long as the pointer operand has the same base 1159 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the 1160 // base of a recurrence. This handles the case in which SCEV expansion 1161 // converts a pointer type recurrence into a nonrecurrent pointer base 1162 // indexed by an integer recurrence. 1163 1164 // If the GEP base pointer is a vector of pointers, abort. 1165 if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy()) 1166 return false; 1167 1168 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr)); 1169 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr)); 1170 if (FromBase == ToBase) 1171 return true; 1172 1173 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: GEP rewrite bail out " 1174 << *FromBase << " != " << *ToBase << "\n"); 1175 1176 return false; 1177 } 1178 return true; 1179 } 1180 1181 static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) { 1182 SmallPtrSet<const Instruction *, 8> Visited; 1183 SmallVector<const Instruction *, 8> WorkList; 1184 Visited.insert(I); 1185 WorkList.push_back(I); 1186 while (!WorkList.empty()) { 1187 const Instruction *Curr = WorkList.pop_back_val(); 1188 // This use is outside the loop, nothing to do. 1189 if (!L->contains(Curr)) 1190 continue; 1191 // Do we assume it is a "hard" use which will not be eliminated easily? 1192 if (Curr->mayHaveSideEffects()) 1193 return true; 1194 // Otherwise, add all its users to worklist. 1195 for (auto U : Curr->users()) { 1196 auto *UI = cast<Instruction>(U); 1197 if (Visited.insert(UI).second) 1198 WorkList.push_back(UI); 1199 } 1200 } 1201 return false; 1202 } 1203 1204 // Collect information about PHI nodes which can be transformed in 1205 // rewriteLoopExitValues. 1206 struct RewritePhi { 1207 PHINode *PN; 1208 unsigned Ith; // Ith incoming value. 1209 Value *Val; // Exit value after expansion. 1210 bool HighCost; // High Cost when expansion. 1211 1212 RewritePhi(PHINode *P, unsigned I, Value *V, bool H) 1213 : PN(P), Ith(I), Val(V), HighCost(H) {} 1214 }; 1215 1216 // Check whether it is possible to delete the loop after rewriting exit 1217 // value. If it is possible, ignore ReplaceExitValue and do rewriting 1218 // aggressively. 1219 static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) { 1220 BasicBlock *Preheader = L->getLoopPreheader(); 1221 // If there is no preheader, the loop will not be deleted. 1222 if (!Preheader) 1223 return false; 1224 1225 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1. 1226 // We obviate multiple ExitingBlocks case for simplicity. 1227 // TODO: If we see testcase with multiple ExitingBlocks can be deleted 1228 // after exit value rewriting, we can enhance the logic here. 1229 SmallVector<BasicBlock *, 4> ExitingBlocks; 1230 L->getExitingBlocks(ExitingBlocks); 1231 SmallVector<BasicBlock *, 8> ExitBlocks; 1232 L->getUniqueExitBlocks(ExitBlocks); 1233 if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1) 1234 return false; 1235 1236 BasicBlock *ExitBlock = ExitBlocks[0]; 1237 BasicBlock::iterator BI = ExitBlock->begin(); 1238 while (PHINode *P = dyn_cast<PHINode>(BI)) { 1239 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); 1240 1241 // If the Incoming value of P is found in RewritePhiSet, we know it 1242 // could be rewritten to use a loop invariant value in transformation 1243 // phase later. Skip it in the loop invariant check below. 1244 bool found = false; 1245 for (const RewritePhi &Phi : RewritePhiSet) { 1246 unsigned i = Phi.Ith; 1247 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) { 1248 found = true; 1249 break; 1250 } 1251 } 1252 1253 Instruction *I; 1254 if (!found && (I = dyn_cast<Instruction>(Incoming))) 1255 if (!L->hasLoopInvariantOperands(I)) 1256 return false; 1257 1258 ++BI; 1259 } 1260 1261 for (auto *BB : L->blocks()) 1262 if (llvm::any_of(*BB, [](Instruction &I) { 1263 return I.mayHaveSideEffects(); 1264 })) 1265 return false; 1266 1267 return true; 1268 } 1269 1270 int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, 1271 TargetLibraryInfo *TLI, ScalarEvolution *SE, SCEVExpander &Rewriter, 1272 DominatorTree *DT, ReplaceExitVal ReplaceExitValue, 1273 SmallVector<WeakTrackingVH, 16> &DeadInsts) { 1274 // Check a pre-condition. 1275 assert(L->isRecursivelyLCSSAForm(*DT, *LI) && 1276 "Indvars did not preserve LCSSA!"); 1277 1278 SmallVector<BasicBlock*, 8> ExitBlocks; 1279 L->getUniqueExitBlocks(ExitBlocks); 1280 1281 SmallVector<RewritePhi, 8> RewritePhiSet; 1282 // Find all values that are computed inside the loop, but used outside of it. 1283 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan 1284 // the exit blocks of the loop to find them. 1285 for (BasicBlock *ExitBB : ExitBlocks) { 1286 // If there are no PHI nodes in this exit block, then no values defined 1287 // inside the loop are used on this path, skip it. 1288 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin()); 1289 if (!PN) continue; 1290 1291 unsigned NumPreds = PN->getNumIncomingValues(); 1292 1293 // Iterate over all of the PHI nodes. 1294 BasicBlock::iterator BBI = ExitBB->begin(); 1295 while ((PN = dyn_cast<PHINode>(BBI++))) { 1296 if (PN->use_empty()) 1297 continue; // dead use, don't replace it 1298 1299 if (!SE->isSCEVable(PN->getType())) 1300 continue; 1301 1302 // It's necessary to tell ScalarEvolution about this explicitly so that 1303 // it can walk the def-use list and forget all SCEVs, as it may not be 1304 // watching the PHI itself. Once the new exit value is in place, there 1305 // may not be a def-use connection between the loop and every instruction 1306 // which got a SCEVAddRecExpr for that loop. 1307 SE->forgetValue(PN); 1308 1309 // Iterate over all of the values in all the PHI nodes. 1310 for (unsigned i = 0; i != NumPreds; ++i) { 1311 // If the value being merged in is not integer or is not defined 1312 // in the loop, skip it. 1313 Value *InVal = PN->getIncomingValue(i); 1314 if (!isa<Instruction>(InVal)) 1315 continue; 1316 1317 // If this pred is for a subloop, not L itself, skip it. 1318 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) 1319 continue; // The Block is in a subloop, skip it. 1320 1321 // Check that InVal is defined in the loop. 1322 Instruction *Inst = cast<Instruction>(InVal); 1323 if (!L->contains(Inst)) 1324 continue; 1325 1326 // Okay, this instruction has a user outside of the current loop 1327 // and varies predictably *inside* the loop. Evaluate the value it 1328 // contains when the loop exits, if possible. We prefer to start with 1329 // expressions which are true for all exits (so as to maximize 1330 // expression reuse by the SCEVExpander), but resort to per-exit 1331 // evaluation if that fails. 1332 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop()); 1333 if (isa<SCEVCouldNotCompute>(ExitValue) || 1334 !SE->isLoopInvariant(ExitValue, L) || 1335 !isSafeToExpand(ExitValue, *SE)) { 1336 // TODO: This should probably be sunk into SCEV in some way; maybe a 1337 // getSCEVForExit(SCEV*, L, ExitingBB)? It can be generalized for 1338 // most SCEV expressions and other recurrence types (e.g. shift 1339 // recurrences). Is there existing code we can reuse? 1340 const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i)); 1341 if (isa<SCEVCouldNotCompute>(ExitCount)) 1342 continue; 1343 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst))) 1344 if (AddRec->getLoop() == L) 1345 ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE); 1346 if (isa<SCEVCouldNotCompute>(ExitValue) || 1347 !SE->isLoopInvariant(ExitValue, L) || 1348 !isSafeToExpand(ExitValue, *SE)) 1349 continue; 1350 } 1351 1352 // Computing the value outside of the loop brings no benefit if it is 1353 // definitely used inside the loop in a way which can not be optimized 1354 // away. Avoid doing so unless we know we have a value which computes 1355 // the ExitValue already. TODO: This should be merged into SCEV 1356 // expander to leverage its knowledge of existing expressions. 1357 if (ReplaceExitValue != AlwaysRepl && 1358 !isa<SCEVConstant>(ExitValue) && !isa<SCEVUnknown>(ExitValue) && 1359 hasHardUserWithinLoop(L, Inst)) 1360 continue; 1361 1362 bool HighCost = Rewriter.isHighCostExpansion(ExitValue, L, Inst); 1363 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst); 1364 1365 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " 1366 << *ExitVal << '\n' << " LoopVal = " << *Inst 1367 << "\n"); 1368 1369 if (!isValidRewrite(SE, Inst, ExitVal)) { 1370 DeadInsts.push_back(ExitVal); 1371 continue; 1372 } 1373 1374 #ifndef NDEBUG 1375 // If we reuse an instruction from a loop which is neither L nor one of 1376 // its containing loops, we end up breaking LCSSA form for this loop by 1377 // creating a new use of its instruction. 1378 if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal)) 1379 if (auto *EVL = LI->getLoopFor(ExitInsn->getParent())) 1380 if (EVL != L) 1381 assert(EVL->contains(L) && "LCSSA breach detected!"); 1382 #endif 1383 1384 // Collect all the candidate PHINodes to be rewritten. 1385 RewritePhiSet.emplace_back(PN, i, ExitVal, HighCost); 1386 } 1387 } 1388 } 1389 1390 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet); 1391 int NumReplaced = 0; 1392 1393 // Transformation. 1394 for (const RewritePhi &Phi : RewritePhiSet) { 1395 PHINode *PN = Phi.PN; 1396 Value *ExitVal = Phi.Val; 1397 1398 // Only do the rewrite when the ExitValue can be expanded cheaply. 1399 // If LoopCanBeDel is true, rewrite exit value aggressively. 1400 if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) { 1401 DeadInsts.push_back(ExitVal); 1402 continue; 1403 } 1404 1405 NumReplaced++; 1406 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith)); 1407 PN->setIncomingValue(Phi.Ith, ExitVal); 1408 1409 // If this instruction is dead now, delete it. Don't do it now to avoid 1410 // invalidating iterators. 1411 if (isInstructionTriviallyDead(Inst, TLI)) 1412 DeadInsts.push_back(Inst); 1413 1414 // Replace PN with ExitVal if that is legal and does not break LCSSA. 1415 if (PN->getNumIncomingValues() == 1 && 1416 LI->replacementPreservesLCSSAForm(PN, ExitVal)) { 1417 PN->replaceAllUsesWith(ExitVal); 1418 PN->eraseFromParent(); 1419 } 1420 } 1421 1422 // The insertion point instruction may have been deleted; clear it out 1423 // so that the rewriter doesn't trip over it later. 1424 Rewriter.clearInsertPoint(); 1425 return NumReplaced; 1426 } 1427 1428 /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for 1429 /// \p OrigLoop. 1430 void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop, 1431 Loop *RemainderLoop, uint64_t UF) { 1432 assert(UF > 0 && "Zero unrolled factor is not supported"); 1433 assert(UnrolledLoop != RemainderLoop && 1434 "Unrolled and Remainder loops are expected to distinct"); 1435 1436 // Get number of iterations in the original scalar loop. 1437 unsigned OrigLoopInvocationWeight = 0; 1438 Optional<unsigned> OrigAverageTripCount = 1439 getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight); 1440 if (!OrigAverageTripCount) 1441 return; 1442 1443 // Calculate number of iterations in unrolled loop. 1444 unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF; 1445 // Calculate number of iterations for remainder loop. 1446 unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF; 1447 1448 setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount, 1449 OrigLoopInvocationWeight); 1450 setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount, 1451 OrigLoopInvocationWeight); 1452 } 1453 1454 /// Utility that implements appending of loops onto a worklist. 1455 /// Loops are added in preorder (analogous for reverse postorder for trees), 1456 /// and the worklist is processed LIFO. 1457 template <typename RangeT> 1458 void llvm::appendReversedLoopsToWorklist( 1459 RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) { 1460 // We use an internal worklist to build up the preorder traversal without 1461 // recursion. 1462 SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist; 1463 1464 // We walk the initial sequence of loops in reverse because we generally want 1465 // to visit defs before uses and the worklist is LIFO. 1466 for (Loop *RootL : Loops) { 1467 assert(PreOrderLoops.empty() && "Must start with an empty preorder walk."); 1468 assert(PreOrderWorklist.empty() && 1469 "Must start with an empty preorder walk worklist."); 1470 PreOrderWorklist.push_back(RootL); 1471 do { 1472 Loop *L = PreOrderWorklist.pop_back_val(); 1473 PreOrderWorklist.append(L->begin(), L->end()); 1474 PreOrderLoops.push_back(L); 1475 } while (!PreOrderWorklist.empty()); 1476 1477 Worklist.insert(std::move(PreOrderLoops)); 1478 PreOrderLoops.clear(); 1479 } 1480 } 1481 1482 template <typename RangeT> 1483 void llvm::appendLoopsToWorklist(RangeT &&Loops, 1484 SmallPriorityWorklist<Loop *, 4> &Worklist) { 1485 appendReversedLoopsToWorklist(reverse(Loops), Worklist); 1486 } 1487 1488 template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>( 1489 ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist); 1490 1491 template void 1492 llvm::appendLoopsToWorklist<Loop &>(Loop &L, 1493 SmallPriorityWorklist<Loop *, 4> &Worklist); 1494 1495 void llvm::appendLoopsToWorklist(LoopInfo &LI, 1496 SmallPriorityWorklist<Loop *, 4> &Worklist) { 1497 appendReversedLoopsToWorklist(LI, Worklist); 1498 } 1499