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/DenseSet.h" 15 #include "llvm/ADT/PriorityWorklist.h" 16 #include "llvm/ADT/ScopeExit.h" 17 #include "llvm/ADT/SetVector.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/BasicAliasAnalysis.h" 22 #include "llvm/Analysis/DomTreeUpdater.h" 23 #include "llvm/Analysis/GlobalsModRef.h" 24 #include "llvm/Analysis/InstSimplifyFolder.h" 25 #include "llvm/Analysis/LoopAccessAnalysis.h" 26 #include "llvm/Analysis/LoopInfo.h" 27 #include "llvm/Analysis/LoopPass.h" 28 #include "llvm/Analysis/MemorySSA.h" 29 #include "llvm/Analysis/MemorySSAUpdater.h" 30 #include "llvm/Analysis/ScalarEvolution.h" 31 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 32 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 33 #include "llvm/IR/DIBuilder.h" 34 #include "llvm/IR/Dominators.h" 35 #include "llvm/IR/Instructions.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/IR/MDBuilder.h" 38 #include "llvm/IR/Module.h" 39 #include "llvm/IR/PatternMatch.h" 40 #include "llvm/IR/ProfDataUtils.h" 41 #include "llvm/IR/ValueHandle.h" 42 #include "llvm/InitializePasses.h" 43 #include "llvm/Pass.h" 44 #include "llvm/Support/Debug.h" 45 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 46 #include "llvm/Transforms/Utils/Local.h" 47 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 48 49 using namespace llvm; 50 using namespace llvm::PatternMatch; 51 52 #define DEBUG_TYPE "loop-utils" 53 54 static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced"; 55 static const char *LLVMLoopDisableLICM = "llvm.licm.disable"; 56 57 bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, 58 MemorySSAUpdater *MSSAU, 59 bool PreserveLCSSA) { 60 bool Changed = false; 61 62 // We re-use a vector for the in-loop predecesosrs. 63 SmallVector<BasicBlock *, 4> InLoopPredecessors; 64 65 auto RewriteExit = [&](BasicBlock *BB) { 66 assert(InLoopPredecessors.empty() && 67 "Must start with an empty predecessors list!"); 68 auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); }); 69 70 // See if there are any non-loop predecessors of this exit block and 71 // keep track of the in-loop predecessors. 72 bool IsDedicatedExit = true; 73 for (auto *PredBB : predecessors(BB)) 74 if (L->contains(PredBB)) { 75 if (isa<IndirectBrInst>(PredBB->getTerminator())) 76 // We cannot rewrite exiting edges from an indirectbr. 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 std::optional<ElementCount> 250 llvm::getOptionalElementCountLoopAttribute(const Loop *TheLoop) { 251 std::optional<int> Width = 252 getOptionalIntLoopAttribute(TheLoop, "llvm.loop.vectorize.width"); 253 254 if (Width) { 255 std::optional<int> IsScalable = getOptionalIntLoopAttribute( 256 TheLoop, "llvm.loop.vectorize.scalable.enable"); 257 return ElementCount::get(*Width, IsScalable.value_or(false)); 258 } 259 260 return std::nullopt; 261 } 262 263 std::optional<MDNode *> llvm::makeFollowupLoopID( 264 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions, 265 const char *InheritOptionsExceptPrefix, bool AlwaysNew) { 266 if (!OrigLoopID) { 267 if (AlwaysNew) 268 return nullptr; 269 return std::nullopt; 270 } 271 272 assert(OrigLoopID->getOperand(0) == OrigLoopID); 273 274 bool InheritAllAttrs = !InheritOptionsExceptPrefix; 275 bool InheritSomeAttrs = 276 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0'; 277 SmallVector<Metadata *, 8> MDs; 278 MDs.push_back(nullptr); 279 280 bool Changed = false; 281 if (InheritAllAttrs || InheritSomeAttrs) { 282 for (const MDOperand &Existing : drop_begin(OrigLoopID->operands())) { 283 MDNode *Op = cast<MDNode>(Existing.get()); 284 285 auto InheritThisAttribute = [InheritSomeAttrs, 286 InheritOptionsExceptPrefix](MDNode *Op) { 287 if (!InheritSomeAttrs) 288 return false; 289 290 // Skip malformatted attribute metadata nodes. 291 if (Op->getNumOperands() == 0) 292 return true; 293 Metadata *NameMD = Op->getOperand(0).get(); 294 if (!isa<MDString>(NameMD)) 295 return true; 296 StringRef AttrName = cast<MDString>(NameMD)->getString(); 297 298 // Do not inherit excluded attributes. 299 return !AttrName.startswith(InheritOptionsExceptPrefix); 300 }; 301 302 if (InheritThisAttribute(Op)) 303 MDs.push_back(Op); 304 else 305 Changed = true; 306 } 307 } else { 308 // Modified if we dropped at least one attribute. 309 Changed = OrigLoopID->getNumOperands() > 1; 310 } 311 312 bool HasAnyFollowup = false; 313 for (StringRef OptionName : FollowupOptions) { 314 MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName); 315 if (!FollowupNode) 316 continue; 317 318 HasAnyFollowup = true; 319 for (const MDOperand &Option : drop_begin(FollowupNode->operands())) { 320 MDs.push_back(Option.get()); 321 Changed = true; 322 } 323 } 324 325 // Attributes of the followup loop not specified explicity, so signal to the 326 // transformation pass to add suitable attributes. 327 if (!AlwaysNew && !HasAnyFollowup) 328 return std::nullopt; 329 330 // If no attributes were added or remove, the previous loop Id can be reused. 331 if (!AlwaysNew && !Changed) 332 return OrigLoopID; 333 334 // No attributes is equivalent to having no !llvm.loop metadata at all. 335 if (MDs.size() == 1) 336 return nullptr; 337 338 // Build the new loop ID. 339 MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs); 340 FollowupLoopID->replaceOperandWith(0, FollowupLoopID); 341 return FollowupLoopID; 342 } 343 344 bool llvm::hasDisableAllTransformsHint(const Loop *L) { 345 return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced); 346 } 347 348 bool llvm::hasDisableLICMTransformsHint(const Loop *L) { 349 return getBooleanLoopAttribute(L, LLVMLoopDisableLICM); 350 } 351 352 TransformationMode llvm::hasUnrollTransformation(const Loop *L) { 353 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable")) 354 return TM_SuppressedByUser; 355 356 std::optional<int> Count = 357 getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count"); 358 if (Count) 359 return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 360 361 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable")) 362 return TM_ForcedByUser; 363 364 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full")) 365 return TM_ForcedByUser; 366 367 if (hasDisableAllTransformsHint(L)) 368 return TM_Disable; 369 370 return TM_Unspecified; 371 } 372 373 TransformationMode llvm::hasUnrollAndJamTransformation(const Loop *L) { 374 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable")) 375 return TM_SuppressedByUser; 376 377 std::optional<int> Count = 378 getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count"); 379 if (Count) 380 return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 381 382 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable")) 383 return TM_ForcedByUser; 384 385 if (hasDisableAllTransformsHint(L)) 386 return TM_Disable; 387 388 return TM_Unspecified; 389 } 390 391 TransformationMode llvm::hasVectorizeTransformation(const Loop *L) { 392 std::optional<bool> Enable = 393 getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable"); 394 395 if (Enable == false) 396 return TM_SuppressedByUser; 397 398 std::optional<ElementCount> VectorizeWidth = 399 getOptionalElementCountLoopAttribute(L); 400 std::optional<int> InterleaveCount = 401 getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count"); 402 403 // 'Forcing' vector width and interleave count to one effectively disables 404 // this tranformation. 405 if (Enable == true && VectorizeWidth && VectorizeWidth->isScalar() && 406 InterleaveCount == 1) 407 return TM_SuppressedByUser; 408 409 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized")) 410 return TM_Disable; 411 412 if (Enable == true) 413 return TM_ForcedByUser; 414 415 if ((VectorizeWidth && VectorizeWidth->isScalar()) && InterleaveCount == 1) 416 return TM_Disable; 417 418 if ((VectorizeWidth && VectorizeWidth->isVector()) || InterleaveCount > 1) 419 return TM_Enable; 420 421 if (hasDisableAllTransformsHint(L)) 422 return TM_Disable; 423 424 return TM_Unspecified; 425 } 426 427 TransformationMode llvm::hasDistributeTransformation(const Loop *L) { 428 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable")) 429 return TM_ForcedByUser; 430 431 if (hasDisableAllTransformsHint(L)) 432 return TM_Disable; 433 434 return TM_Unspecified; 435 } 436 437 TransformationMode llvm::hasLICMVersioningTransformation(const Loop *L) { 438 if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable")) 439 return TM_SuppressedByUser; 440 441 if (hasDisableAllTransformsHint(L)) 442 return TM_Disable; 443 444 return TM_Unspecified; 445 } 446 447 /// Does a BFS from a given node to all of its children inside a given loop. 448 /// The returned vector of nodes includes the starting point. 449 SmallVector<DomTreeNode *, 16> 450 llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) { 451 SmallVector<DomTreeNode *, 16> Worklist; 452 auto AddRegionToWorklist = [&](DomTreeNode *DTN) { 453 // Only include subregions in the top level loop. 454 BasicBlock *BB = DTN->getBlock(); 455 if (CurLoop->contains(BB)) 456 Worklist.push_back(DTN); 457 }; 458 459 AddRegionToWorklist(N); 460 461 for (size_t I = 0; I < Worklist.size(); I++) { 462 for (DomTreeNode *Child : Worklist[I]->children()) 463 AddRegionToWorklist(Child); 464 } 465 466 return Worklist; 467 } 468 469 bool llvm::isAlmostDeadIV(PHINode *PN, BasicBlock *LatchBlock, Value *Cond) { 470 int LatchIdx = PN->getBasicBlockIndex(LatchBlock); 471 Value *IncV = PN->getIncomingValue(LatchIdx); 472 473 for (User *U : PN->users()) 474 if (U != Cond && U != IncV) return false; 475 476 for (User *U : IncV->users()) 477 if (U != Cond && U != PN) return false; 478 return true; 479 } 480 481 482 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE, 483 LoopInfo *LI, MemorySSA *MSSA) { 484 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!"); 485 auto *Preheader = L->getLoopPreheader(); 486 assert(Preheader && "Preheader should exist!"); 487 488 std::unique_ptr<MemorySSAUpdater> MSSAU; 489 if (MSSA) 490 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 491 492 // Now that we know the removal is safe, remove the loop by changing the 493 // branch from the preheader to go to the single exit block. 494 // 495 // Because we're deleting a large chunk of code at once, the sequence in which 496 // we remove things is very important to avoid invalidation issues. 497 498 // Tell ScalarEvolution that the loop is deleted. Do this before 499 // deleting the loop so that ScalarEvolution can look at the loop 500 // to determine what it needs to clean up. 501 if (SE) { 502 SE->forgetLoop(L); 503 SE->forgetBlockAndLoopDispositions(); 504 } 505 506 Instruction *OldTerm = Preheader->getTerminator(); 507 assert(!OldTerm->mayHaveSideEffects() && 508 "Preheader must end with a side-effect-free terminator"); 509 assert(OldTerm->getNumSuccessors() == 1 && 510 "Preheader must have a single successor"); 511 // Connect the preheader to the exit block. Keep the old edge to the header 512 // around to perform the dominator tree update in two separate steps 513 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge 514 // preheader -> header. 515 // 516 // 517 // 0. Preheader 1. Preheader 2. Preheader 518 // | | | | 519 // V | V | 520 // Header <--\ | Header <--\ | Header <--\ 521 // | | | | | | | | | | | 522 // | V | | | V | | | V | 523 // | Body --/ | | Body --/ | | Body --/ 524 // V V V V V 525 // Exit Exit Exit 526 // 527 // By doing this is two separate steps we can perform the dominator tree 528 // update without using the batch update API. 529 // 530 // Even when the loop is never executed, we cannot remove the edge from the 531 // source block to the exit block. Consider the case where the unexecuted loop 532 // branches back to an outer loop. If we deleted the loop and removed the edge 533 // coming to this inner loop, this will break the outer loop structure (by 534 // deleting the backedge of the outer loop). If the outer loop is indeed a 535 // non-loop, it will be deleted in a future iteration of loop deletion pass. 536 IRBuilder<> Builder(OldTerm); 537 538 auto *ExitBlock = L->getUniqueExitBlock(); 539 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 540 if (ExitBlock) { 541 assert(ExitBlock && "Should have a unique exit block!"); 542 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!"); 543 544 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock); 545 // Remove the old branch. The conditional branch becomes a new terminator. 546 OldTerm->eraseFromParent(); 547 548 // Rewrite phis in the exit block to get their inputs from the Preheader 549 // instead of the exiting block. 550 for (PHINode &P : ExitBlock->phis()) { 551 // Set the zero'th element of Phi to be from the preheader and remove all 552 // other incoming values. Given the loop has dedicated exits, all other 553 // incoming values must be from the exiting blocks. 554 int PredIndex = 0; 555 P.setIncomingBlock(PredIndex, Preheader); 556 // Removes all incoming values from all other exiting blocks (including 557 // duplicate values from an exiting block). 558 // Nuke all entries except the zero'th entry which is the preheader entry. 559 // NOTE! We need to remove Incoming Values in the reverse order as done 560 // below, to keep the indices valid for deletion (removeIncomingValues 561 // updates getNumIncomingValues and shifts all values down into the 562 // operand being deleted). 563 for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i) 564 P.removeIncomingValue(e - i, false); 565 566 assert((P.getNumIncomingValues() == 1 && 567 P.getIncomingBlock(PredIndex) == Preheader) && 568 "Should have exactly one value and that's from the preheader!"); 569 } 570 571 if (DT) { 572 DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}}); 573 if (MSSA) { 574 MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}}, 575 *DT); 576 if (VerifyMemorySSA) 577 MSSA->verifyMemorySSA(); 578 } 579 } 580 581 // Disconnect the loop body by branching directly to its exit. 582 Builder.SetInsertPoint(Preheader->getTerminator()); 583 Builder.CreateBr(ExitBlock); 584 // Remove the old branch. 585 Preheader->getTerminator()->eraseFromParent(); 586 } else { 587 assert(L->hasNoExitBlocks() && 588 "Loop should have either zero or one exit blocks."); 589 590 Builder.SetInsertPoint(OldTerm); 591 Builder.CreateUnreachable(); 592 Preheader->getTerminator()->eraseFromParent(); 593 } 594 595 if (DT) { 596 DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}}); 597 if (MSSA) { 598 MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}}, 599 *DT); 600 SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(), 601 L->block_end()); 602 MSSAU->removeBlocks(DeadBlockSet); 603 if (VerifyMemorySSA) 604 MSSA->verifyMemorySSA(); 605 } 606 } 607 608 // Use a map to unique and a vector to guarantee deterministic ordering. 609 llvm::SmallDenseSet<DebugVariable, 4> DeadDebugSet; 610 llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst; 611 612 if (ExitBlock) { 613 // Given LCSSA form is satisfied, we should not have users of instructions 614 // within the dead loop outside of the loop. However, LCSSA doesn't take 615 // unreachable uses into account. We handle them here. 616 // We could do it after drop all references (in this case all users in the 617 // loop will be already eliminated and we have less work to do but according 618 // to API doc of User::dropAllReferences only valid operation after dropping 619 // references, is deletion. So let's substitute all usages of 620 // instruction from the loop with poison value of corresponding type first. 621 for (auto *Block : L->blocks()) 622 for (Instruction &I : *Block) { 623 auto *Poison = PoisonValue::get(I.getType()); 624 for (Use &U : llvm::make_early_inc_range(I.uses())) { 625 if (auto *Usr = dyn_cast<Instruction>(U.getUser())) 626 if (L->contains(Usr->getParent())) 627 continue; 628 // If we have a DT then we can check that uses outside a loop only in 629 // unreachable block. 630 if (DT) 631 assert(!DT->isReachableFromEntry(U) && 632 "Unexpected user in reachable block"); 633 U.set(Poison); 634 } 635 auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I); 636 if (!DVI) 637 continue; 638 if (!DeadDebugSet.insert(DebugVariable(DVI)).second) 639 continue; 640 DeadDebugInst.push_back(DVI); 641 } 642 643 // After the loop has been deleted all the values defined and modified 644 // inside the loop are going to be unavailable. Values computed in the 645 // loop will have been deleted, automatically causing their debug uses 646 // be be replaced with undef. Loop invariant values will still be available. 647 // Move dbg.values out the loop so that earlier location ranges are still 648 // terminated and loop invariant assignments are preserved. 649 Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI(); 650 assert(InsertDbgValueBefore && 651 "There should be a non-PHI instruction in exit block, else these " 652 "instructions will have no parent."); 653 for (auto *DVI : DeadDebugInst) 654 DVI->moveBefore(InsertDbgValueBefore); 655 } 656 657 // Remove the block from the reference counting scheme, so that we can 658 // delete it freely later. 659 for (auto *Block : L->blocks()) 660 Block->dropAllReferences(); 661 662 if (MSSA && VerifyMemorySSA) 663 MSSA->verifyMemorySSA(); 664 665 if (LI) { 666 // Erase the instructions and the blocks without having to worry 667 // about ordering because we already dropped the references. 668 // NOTE: This iteration is safe because erasing the block does not remove 669 // its entry from the loop's block list. We do that in the next section. 670 for (BasicBlock *BB : L->blocks()) 671 BB->eraseFromParent(); 672 673 // Finally, the blocks from loopinfo. This has to happen late because 674 // otherwise our loop iterators won't work. 675 676 SmallPtrSet<BasicBlock *, 8> blocks; 677 blocks.insert(L->block_begin(), L->block_end()); 678 for (BasicBlock *BB : blocks) 679 LI->removeBlock(BB); 680 681 // The last step is to update LoopInfo now that we've eliminated this loop. 682 // Note: LoopInfo::erase remove the given loop and relink its subloops with 683 // its parent. While removeLoop/removeChildLoop remove the given loop but 684 // not relink its subloops, which is what we want. 685 if (Loop *ParentLoop = L->getParentLoop()) { 686 Loop::iterator I = find(*ParentLoop, L); 687 assert(I != ParentLoop->end() && "Couldn't find loop"); 688 ParentLoop->removeChildLoop(I); 689 } else { 690 Loop::iterator I = find(*LI, L); 691 assert(I != LI->end() && "Couldn't find loop"); 692 LI->removeLoop(I); 693 } 694 LI->destroy(L); 695 } 696 } 697 698 void llvm::breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE, 699 LoopInfo &LI, MemorySSA *MSSA) { 700 auto *Latch = L->getLoopLatch(); 701 assert(Latch && "multiple latches not yet supported"); 702 auto *Header = L->getHeader(); 703 Loop *OutermostLoop = L->getOutermostLoop(); 704 705 SE.forgetLoop(L); 706 SE.forgetBlockAndLoopDispositions(); 707 708 std::unique_ptr<MemorySSAUpdater> MSSAU; 709 if (MSSA) 710 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 711 712 // Update the CFG and domtree. We chose to special case a couple of 713 // of common cases for code quality and test readability reasons. 714 [&]() -> void { 715 if (auto *BI = dyn_cast<BranchInst>(Latch->getTerminator())) { 716 if (!BI->isConditional()) { 717 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager); 718 (void)changeToUnreachable(BI, /*PreserveLCSSA*/ true, &DTU, 719 MSSAU.get()); 720 return; 721 } 722 723 // Conditional latch/exit - note that latch can be shared by inner 724 // and outer loop so the other target doesn't need to an exit 725 if (L->isLoopExiting(Latch)) { 726 // TODO: Generalize ConstantFoldTerminator so that it can be used 727 // here without invalidating LCSSA or MemorySSA. (Tricky case for 728 // LCSSA: header is an exit block of a preceeding sibling loop w/o 729 // dedicated exits.) 730 const unsigned ExitIdx = L->contains(BI->getSuccessor(0)) ? 1 : 0; 731 BasicBlock *ExitBB = BI->getSuccessor(ExitIdx); 732 733 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager); 734 Header->removePredecessor(Latch, true); 735 736 IRBuilder<> Builder(BI); 737 auto *NewBI = Builder.CreateBr(ExitBB); 738 // Transfer the metadata to the new branch instruction (minus the 739 // loop info since this is no longer a loop) 740 NewBI->copyMetadata(*BI, {LLVMContext::MD_dbg, 741 LLVMContext::MD_annotation}); 742 743 BI->eraseFromParent(); 744 DTU.applyUpdates({{DominatorTree::Delete, Latch, Header}}); 745 if (MSSA) 746 MSSAU->applyUpdates({{DominatorTree::Delete, Latch, Header}}, DT); 747 return; 748 } 749 } 750 751 // General case. By splitting the backedge, and then explicitly making it 752 // unreachable we gracefully handle corner cases such as switch and invoke 753 // termiantors. 754 auto *BackedgeBB = SplitEdge(Latch, Header, &DT, &LI, MSSAU.get()); 755 756 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager); 757 (void)changeToUnreachable(BackedgeBB->getTerminator(), 758 /*PreserveLCSSA*/ true, &DTU, MSSAU.get()); 759 }(); 760 761 // Erase (and destroy) this loop instance. Handles relinking sub-loops 762 // and blocks within the loop as needed. 763 LI.erase(L); 764 765 // If the loop we broke had a parent, then changeToUnreachable might have 766 // caused a block to be removed from the parent loop (see loop_nest_lcssa 767 // test case in zero-btc.ll for an example), thus changing the parent's 768 // exit blocks. If that happened, we need to rebuild LCSSA on the outermost 769 // loop which might have a had a block removed. 770 if (OutermostLoop != L) 771 formLCSSARecursively(*OutermostLoop, DT, &LI, &SE); 772 } 773 774 775 /// Checks if \p L has an exiting latch branch. There may also be other 776 /// exiting blocks. Returns branch instruction terminating the loop 777 /// latch if above check is successful, nullptr otherwise. 778 static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) { 779 BasicBlock *Latch = L->getLoopLatch(); 780 if (!Latch) 781 return nullptr; 782 783 BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator()); 784 if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch)) 785 return nullptr; 786 787 assert((LatchBR->getSuccessor(0) == L->getHeader() || 788 LatchBR->getSuccessor(1) == L->getHeader()) && 789 "At least one edge out of the latch must go to the header"); 790 791 return LatchBR; 792 } 793 794 /// Return the estimated trip count for any exiting branch which dominates 795 /// the loop latch. 796 static std::optional<uint64_t> getEstimatedTripCount(BranchInst *ExitingBranch, 797 Loop *L, 798 uint64_t &OrigExitWeight) { 799 // To estimate the number of times the loop body was executed, we want to 800 // know the number of times the backedge was taken, vs. the number of times 801 // we exited the loop. 802 uint64_t LoopWeight, ExitWeight; 803 if (!extractBranchWeights(*ExitingBranch, LoopWeight, ExitWeight)) 804 return std::nullopt; 805 806 if (L->contains(ExitingBranch->getSuccessor(1))) 807 std::swap(LoopWeight, ExitWeight); 808 809 if (!ExitWeight) 810 // Don't have a way to return predicated infinite 811 return std::nullopt; 812 813 OrigExitWeight = ExitWeight; 814 815 // Estimated exit count is a ratio of the loop weight by the weight of the 816 // edge exiting the loop, rounded to nearest. 817 uint64_t ExitCount = llvm::divideNearest(LoopWeight, ExitWeight); 818 // Estimated trip count is one plus estimated exit count. 819 return ExitCount + 1; 820 } 821 822 std::optional<unsigned> 823 llvm::getLoopEstimatedTripCount(Loop *L, 824 unsigned *EstimatedLoopInvocationWeight) { 825 // Currently we take the estimate exit count only from the loop latch, 826 // ignoring other exiting blocks. This can overestimate the trip count 827 // if we exit through another exit, but can never underestimate it. 828 // TODO: incorporate information from other exits 829 if (BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L)) { 830 uint64_t ExitWeight; 831 if (std::optional<uint64_t> EstTripCount = 832 getEstimatedTripCount(LatchBranch, L, ExitWeight)) { 833 if (EstimatedLoopInvocationWeight) 834 *EstimatedLoopInvocationWeight = ExitWeight; 835 return *EstTripCount; 836 } 837 } 838 return std::nullopt; 839 } 840 841 bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, 842 unsigned EstimatedloopInvocationWeight) { 843 // At the moment, we currently support changing the estimate trip count of 844 // the latch branch only. We could extend this API to manipulate estimated 845 // trip counts for any exit. 846 BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L); 847 if (!LatchBranch) 848 return false; 849 850 // Calculate taken and exit weights. 851 unsigned LatchExitWeight = 0; 852 unsigned BackedgeTakenWeight = 0; 853 854 if (EstimatedTripCount > 0) { 855 LatchExitWeight = EstimatedloopInvocationWeight; 856 BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight; 857 } 858 859 // Make a swap if back edge is taken when condition is "false". 860 if (LatchBranch->getSuccessor(0) != L->getHeader()) 861 std::swap(BackedgeTakenWeight, LatchExitWeight); 862 863 MDBuilder MDB(LatchBranch->getContext()); 864 865 // Set/Update profile metadata. 866 LatchBranch->setMetadata( 867 LLVMContext::MD_prof, 868 MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight)); 869 870 return true; 871 } 872 873 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop, 874 ScalarEvolution &SE) { 875 Loop *OuterL = InnerLoop->getParentLoop(); 876 if (!OuterL) 877 return true; 878 879 // Get the backedge taken count for the inner loop 880 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 881 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch); 882 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) || 883 !InnerLoopBECountSC->getType()->isIntegerTy()) 884 return false; 885 886 // Get whether count is invariant to the outer loop 887 ScalarEvolution::LoopDisposition LD = 888 SE.getLoopDisposition(InnerLoopBECountSC, OuterL); 889 if (LD != ScalarEvolution::LoopInvariant) 890 return false; 891 892 return true; 893 } 894 895 Intrinsic::ID llvm::getMinMaxReductionIntrinsicOp(RecurKind RK) { 896 switch (RK) { 897 default: 898 llvm_unreachable("Unknown min/max recurrence kind"); 899 case RecurKind::UMin: 900 return Intrinsic::umin; 901 case RecurKind::UMax: 902 return Intrinsic::umax; 903 case RecurKind::SMin: 904 return Intrinsic::smin; 905 case RecurKind::SMax: 906 return Intrinsic::smax; 907 case RecurKind::FMin: 908 return Intrinsic::minnum; 909 case RecurKind::FMax: 910 return Intrinsic::maxnum; 911 case RecurKind::FMinimum: 912 return Intrinsic::minimum; 913 case RecurKind::FMaximum: 914 return Intrinsic::maximum; 915 } 916 } 917 918 CmpInst::Predicate llvm::getMinMaxReductionPredicate(RecurKind RK) { 919 switch (RK) { 920 default: 921 llvm_unreachable("Unknown min/max recurrence kind"); 922 case RecurKind::UMin: 923 return CmpInst::ICMP_ULT; 924 case RecurKind::UMax: 925 return CmpInst::ICMP_UGT; 926 case RecurKind::SMin: 927 return CmpInst::ICMP_SLT; 928 case RecurKind::SMax: 929 return CmpInst::ICMP_SGT; 930 case RecurKind::FMin: 931 return CmpInst::FCMP_OLT; 932 case RecurKind::FMax: 933 return CmpInst::FCMP_OGT; 934 // We do not add FMinimum/FMaximum recurrence kind here since there is no 935 // equivalent predicate which compares signed zeroes according to the 936 // semantics of the intrinsics (llvm.minimum/maximum). 937 } 938 } 939 940 Value *llvm::createSelectCmpOp(IRBuilderBase &Builder, Value *StartVal, 941 RecurKind RK, Value *Left, Value *Right) { 942 if (auto VTy = dyn_cast<VectorType>(Left->getType())) 943 StartVal = Builder.CreateVectorSplat(VTy->getElementCount(), StartVal); 944 Value *Cmp = 945 Builder.CreateCmp(CmpInst::ICMP_NE, Left, StartVal, "rdx.select.cmp"); 946 return Builder.CreateSelect(Cmp, Left, Right, "rdx.select"); 947 } 948 949 Value *llvm::createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left, 950 Value *Right) { 951 Type *Ty = Left->getType(); 952 if (Ty->isIntOrIntVectorTy() || 953 (RK == RecurKind::FMinimum || RK == RecurKind::FMaximum)) { 954 // TODO: Add float minnum/maxnum support when FMF nnan is set. 955 Intrinsic::ID Id = getMinMaxReductionIntrinsicOp(RK); 956 return Builder.CreateIntrinsic(Ty, Id, {Left, Right}, nullptr, 957 "rdx.minmax"); 958 } 959 CmpInst::Predicate Pred = getMinMaxReductionPredicate(RK); 960 Value *Cmp = Builder.CreateCmp(Pred, Left, Right, "rdx.minmax.cmp"); 961 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 962 return Select; 963 } 964 965 // Helper to generate an ordered reduction. 966 Value *llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src, 967 unsigned Op, RecurKind RdxKind) { 968 unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements(); 969 970 // Extract and apply reduction ops in ascending order: 971 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1] 972 Value *Result = Acc; 973 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) { 974 Value *Ext = 975 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx)); 976 977 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 978 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext, 979 "bin.rdx"); 980 } else { 981 assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) && 982 "Invalid min/max"); 983 Result = createMinMaxOp(Builder, RdxKind, Result, Ext); 984 } 985 } 986 987 return Result; 988 } 989 990 // Helper to generate a log2 shuffle reduction. 991 Value *llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src, 992 unsigned Op, RecurKind RdxKind) { 993 unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements(); 994 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 995 // and vector ops, reducing the set of values being computed by half each 996 // round. 997 assert(isPowerOf2_32(VF) && 998 "Reduction emission only supported for pow2 vectors!"); 999 // Note: fast-math-flags flags are controlled by the builder configuration 1000 // and are assumed to apply to all generated arithmetic instructions. Other 1001 // poison generating flags (nsw/nuw/inbounds/inrange/exact) are not part 1002 // of the builder configuration, and since they're not passed explicitly, 1003 // will never be relevant here. Note that it would be generally unsound to 1004 // propagate these from an intrinsic call to the expansion anyways as we/ 1005 // change the order of operations. 1006 Value *TmpVec = Src; 1007 SmallVector<int, 32> ShuffleMask(VF); 1008 for (unsigned i = VF; i != 1; i >>= 1) { 1009 // Move the upper half of the vector to the lower half. 1010 for (unsigned j = 0; j != i / 2; ++j) 1011 ShuffleMask[j] = i / 2 + j; 1012 1013 // Fill the rest of the mask with undef. 1014 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1); 1015 1016 Value *Shuf = Builder.CreateShuffleVector(TmpVec, ShuffleMask, "rdx.shuf"); 1017 1018 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 1019 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf, 1020 "bin.rdx"); 1021 } else { 1022 assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) && 1023 "Invalid min/max"); 1024 TmpVec = createMinMaxOp(Builder, RdxKind, TmpVec, Shuf); 1025 } 1026 } 1027 // The result is in the first element of the vector. 1028 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 1029 } 1030 1031 Value *llvm::createSelectCmpTargetReduction(IRBuilderBase &Builder, 1032 const TargetTransformInfo *TTI, 1033 Value *Src, 1034 const RecurrenceDescriptor &Desc, 1035 PHINode *OrigPhi) { 1036 assert(RecurrenceDescriptor::isSelectCmpRecurrenceKind( 1037 Desc.getRecurrenceKind()) && 1038 "Unexpected reduction kind"); 1039 Value *InitVal = Desc.getRecurrenceStartValue(); 1040 Value *NewVal = nullptr; 1041 1042 // First use the original phi to determine the new value we're trying to 1043 // select from in the loop. 1044 SelectInst *SI = nullptr; 1045 for (auto *U : OrigPhi->users()) { 1046 if ((SI = dyn_cast<SelectInst>(U))) 1047 break; 1048 } 1049 assert(SI && "One user of the original phi should be a select"); 1050 1051 if (SI->getTrueValue() == OrigPhi) 1052 NewVal = SI->getFalseValue(); 1053 else { 1054 assert(SI->getFalseValue() == OrigPhi && 1055 "At least one input to the select should be the original Phi"); 1056 NewVal = SI->getTrueValue(); 1057 } 1058 1059 // Create a splat vector with the new value and compare this to the vector 1060 // we want to reduce. 1061 ElementCount EC = cast<VectorType>(Src->getType())->getElementCount(); 1062 Value *Right = Builder.CreateVectorSplat(EC, InitVal); 1063 Value *Cmp = 1064 Builder.CreateCmp(CmpInst::ICMP_NE, Src, Right, "rdx.select.cmp"); 1065 1066 // If any predicate is true it means that we want to select the new value. 1067 Cmp = Builder.CreateOrReduce(Cmp); 1068 return Builder.CreateSelect(Cmp, NewVal, InitVal, "rdx.select"); 1069 } 1070 1071 Value *llvm::createSimpleTargetReduction(IRBuilderBase &Builder, 1072 const TargetTransformInfo *TTI, 1073 Value *Src, RecurKind RdxKind) { 1074 auto *SrcVecEltTy = cast<VectorType>(Src->getType())->getElementType(); 1075 switch (RdxKind) { 1076 case RecurKind::Add: 1077 return Builder.CreateAddReduce(Src); 1078 case RecurKind::Mul: 1079 return Builder.CreateMulReduce(Src); 1080 case RecurKind::And: 1081 return Builder.CreateAndReduce(Src); 1082 case RecurKind::Or: 1083 return Builder.CreateOrReduce(Src); 1084 case RecurKind::Xor: 1085 return Builder.CreateXorReduce(Src); 1086 case RecurKind::FMulAdd: 1087 case RecurKind::FAdd: 1088 return Builder.CreateFAddReduce(ConstantFP::getNegativeZero(SrcVecEltTy), 1089 Src); 1090 case RecurKind::FMul: 1091 return Builder.CreateFMulReduce(ConstantFP::get(SrcVecEltTy, 1.0), Src); 1092 case RecurKind::SMax: 1093 return Builder.CreateIntMaxReduce(Src, true); 1094 case RecurKind::SMin: 1095 return Builder.CreateIntMinReduce(Src, true); 1096 case RecurKind::UMax: 1097 return Builder.CreateIntMaxReduce(Src, false); 1098 case RecurKind::UMin: 1099 return Builder.CreateIntMinReduce(Src, false); 1100 case RecurKind::FMax: 1101 return Builder.CreateFPMaxReduce(Src); 1102 case RecurKind::FMin: 1103 return Builder.CreateFPMinReduce(Src); 1104 case RecurKind::FMinimum: 1105 return Builder.CreateFPMinimumReduce(Src); 1106 case RecurKind::FMaximum: 1107 return Builder.CreateFPMaximumReduce(Src); 1108 default: 1109 llvm_unreachable("Unhandled opcode"); 1110 } 1111 } 1112 1113 Value *llvm::createTargetReduction(IRBuilderBase &B, 1114 const TargetTransformInfo *TTI, 1115 const RecurrenceDescriptor &Desc, Value *Src, 1116 PHINode *OrigPhi) { 1117 // TODO: Support in-order reductions based on the recurrence descriptor. 1118 // All ops in the reduction inherit fast-math-flags from the recurrence 1119 // descriptor. 1120 IRBuilderBase::FastMathFlagGuard FMFGuard(B); 1121 B.setFastMathFlags(Desc.getFastMathFlags()); 1122 1123 RecurKind RK = Desc.getRecurrenceKind(); 1124 if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK)) 1125 return createSelectCmpTargetReduction(B, TTI, Src, Desc, OrigPhi); 1126 1127 return createSimpleTargetReduction(B, TTI, Src, RK); 1128 } 1129 1130 Value *llvm::createOrderedReduction(IRBuilderBase &B, 1131 const RecurrenceDescriptor &Desc, 1132 Value *Src, Value *Start) { 1133 assert((Desc.getRecurrenceKind() == RecurKind::FAdd || 1134 Desc.getRecurrenceKind() == RecurKind::FMulAdd) && 1135 "Unexpected reduction kind"); 1136 assert(Src->getType()->isVectorTy() && "Expected a vector type"); 1137 assert(!Start->getType()->isVectorTy() && "Expected a scalar type"); 1138 1139 return B.CreateFAddReduce(Start, Src); 1140 } 1141 1142 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue, 1143 bool IncludeWrapFlags) { 1144 auto *VecOp = dyn_cast<Instruction>(I); 1145 if (!VecOp) 1146 return; 1147 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0]) 1148 : dyn_cast<Instruction>(OpValue); 1149 if (!Intersection) 1150 return; 1151 const unsigned Opcode = Intersection->getOpcode(); 1152 VecOp->copyIRFlags(Intersection, IncludeWrapFlags); 1153 for (auto *V : VL) { 1154 auto *Instr = dyn_cast<Instruction>(V); 1155 if (!Instr) 1156 continue; 1157 if (OpValue == nullptr || Opcode == Instr->getOpcode()) 1158 VecOp->andIRFlags(V); 1159 } 1160 } 1161 1162 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L, 1163 ScalarEvolution &SE) { 1164 const SCEV *Zero = SE.getZero(S->getType()); 1165 return SE.isAvailableAtLoopEntry(S, L) && 1166 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero); 1167 } 1168 1169 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, 1170 ScalarEvolution &SE) { 1171 const SCEV *Zero = SE.getZero(S->getType()); 1172 return SE.isAvailableAtLoopEntry(S, L) && 1173 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero); 1174 } 1175 1176 bool llvm::isKnownPositiveInLoop(const SCEV *S, const Loop *L, 1177 ScalarEvolution &SE) { 1178 const SCEV *Zero = SE.getZero(S->getType()); 1179 return SE.isAvailableAtLoopEntry(S, L) && 1180 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, S, Zero); 1181 } 1182 1183 bool llvm::isKnownNonPositiveInLoop(const SCEV *S, const Loop *L, 1184 ScalarEvolution &SE) { 1185 const SCEV *Zero = SE.getZero(S->getType()); 1186 return SE.isAvailableAtLoopEntry(S, L) && 1187 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLE, S, Zero); 1188 } 1189 1190 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1191 bool Signed) { 1192 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1193 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) : 1194 APInt::getMinValue(BitWidth); 1195 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1196 return SE.isAvailableAtLoopEntry(S, L) && 1197 SE.isLoopEntryGuardedByCond(L, Predicate, S, 1198 SE.getConstant(Min)); 1199 } 1200 1201 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1202 bool Signed) { 1203 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1204 APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) : 1205 APInt::getMaxValue(BitWidth); 1206 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1207 return SE.isAvailableAtLoopEntry(S, L) && 1208 SE.isLoopEntryGuardedByCond(L, Predicate, S, 1209 SE.getConstant(Max)); 1210 } 1211 1212 //===----------------------------------------------------------------------===// 1213 // rewriteLoopExitValues - Optimize IV users outside the loop. 1214 // As a side effect, reduces the amount of IV processing within the loop. 1215 //===----------------------------------------------------------------------===// 1216 1217 static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) { 1218 SmallPtrSet<const Instruction *, 8> Visited; 1219 SmallVector<const Instruction *, 8> WorkList; 1220 Visited.insert(I); 1221 WorkList.push_back(I); 1222 while (!WorkList.empty()) { 1223 const Instruction *Curr = WorkList.pop_back_val(); 1224 // This use is outside the loop, nothing to do. 1225 if (!L->contains(Curr)) 1226 continue; 1227 // Do we assume it is a "hard" use which will not be eliminated easily? 1228 if (Curr->mayHaveSideEffects()) 1229 return true; 1230 // Otherwise, add all its users to worklist. 1231 for (const auto *U : Curr->users()) { 1232 auto *UI = cast<Instruction>(U); 1233 if (Visited.insert(UI).second) 1234 WorkList.push_back(UI); 1235 } 1236 } 1237 return false; 1238 } 1239 1240 // Collect information about PHI nodes which can be transformed in 1241 // rewriteLoopExitValues. 1242 struct RewritePhi { 1243 PHINode *PN; // For which PHI node is this replacement? 1244 unsigned Ith; // For which incoming value? 1245 const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting. 1246 Instruction *ExpansionPoint; // Where we'd like to expand that SCEV? 1247 bool HighCost; // Is this expansion a high-cost? 1248 1249 RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt, 1250 bool H) 1251 : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt), 1252 HighCost(H) {} 1253 }; 1254 1255 // Check whether it is possible to delete the loop after rewriting exit 1256 // value. If it is possible, ignore ReplaceExitValue and do rewriting 1257 // aggressively. 1258 static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) { 1259 BasicBlock *Preheader = L->getLoopPreheader(); 1260 // If there is no preheader, the loop will not be deleted. 1261 if (!Preheader) 1262 return false; 1263 1264 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1. 1265 // We obviate multiple ExitingBlocks case for simplicity. 1266 // TODO: If we see testcase with multiple ExitingBlocks can be deleted 1267 // after exit value rewriting, we can enhance the logic here. 1268 SmallVector<BasicBlock *, 4> ExitingBlocks; 1269 L->getExitingBlocks(ExitingBlocks); 1270 SmallVector<BasicBlock *, 8> ExitBlocks; 1271 L->getUniqueExitBlocks(ExitBlocks); 1272 if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1) 1273 return false; 1274 1275 BasicBlock *ExitBlock = ExitBlocks[0]; 1276 BasicBlock::iterator BI = ExitBlock->begin(); 1277 while (PHINode *P = dyn_cast<PHINode>(BI)) { 1278 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); 1279 1280 // If the Incoming value of P is found in RewritePhiSet, we know it 1281 // could be rewritten to use a loop invariant value in transformation 1282 // phase later. Skip it in the loop invariant check below. 1283 bool found = false; 1284 for (const RewritePhi &Phi : RewritePhiSet) { 1285 unsigned i = Phi.Ith; 1286 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) { 1287 found = true; 1288 break; 1289 } 1290 } 1291 1292 Instruction *I; 1293 if (!found && (I = dyn_cast<Instruction>(Incoming))) 1294 if (!L->hasLoopInvariantOperands(I)) 1295 return false; 1296 1297 ++BI; 1298 } 1299 1300 for (auto *BB : L->blocks()) 1301 if (llvm::any_of(*BB, [](Instruction &I) { 1302 return I.mayHaveSideEffects(); 1303 })) 1304 return false; 1305 1306 return true; 1307 } 1308 1309 /// Checks if it is safe to call InductionDescriptor::isInductionPHI for \p Phi, 1310 /// and returns true if this Phi is an induction phi in the loop. When 1311 /// isInductionPHI returns true, \p ID will be also be set by isInductionPHI. 1312 static bool checkIsIndPhi(PHINode *Phi, Loop *L, ScalarEvolution *SE, 1313 InductionDescriptor &ID) { 1314 if (!Phi) 1315 return false; 1316 if (!L->getLoopPreheader()) 1317 return false; 1318 if (Phi->getParent() != L->getHeader()) 1319 return false; 1320 return InductionDescriptor::isInductionPHI(Phi, L, SE, ID); 1321 } 1322 1323 int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI, 1324 ScalarEvolution *SE, 1325 const TargetTransformInfo *TTI, 1326 SCEVExpander &Rewriter, DominatorTree *DT, 1327 ReplaceExitVal ReplaceExitValue, 1328 SmallVector<WeakTrackingVH, 16> &DeadInsts) { 1329 // Check a pre-condition. 1330 assert(L->isRecursivelyLCSSAForm(*DT, *LI) && 1331 "Indvars did not preserve LCSSA!"); 1332 1333 SmallVector<BasicBlock*, 8> ExitBlocks; 1334 L->getUniqueExitBlocks(ExitBlocks); 1335 1336 SmallVector<RewritePhi, 8> RewritePhiSet; 1337 // Find all values that are computed inside the loop, but used outside of it. 1338 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan 1339 // the exit blocks of the loop to find them. 1340 for (BasicBlock *ExitBB : ExitBlocks) { 1341 // If there are no PHI nodes in this exit block, then no values defined 1342 // inside the loop are used on this path, skip it. 1343 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin()); 1344 if (!PN) continue; 1345 1346 unsigned NumPreds = PN->getNumIncomingValues(); 1347 1348 // Iterate over all of the PHI nodes. 1349 BasicBlock::iterator BBI = ExitBB->begin(); 1350 while ((PN = dyn_cast<PHINode>(BBI++))) { 1351 if (PN->use_empty()) 1352 continue; // dead use, don't replace it 1353 1354 if (!SE->isSCEVable(PN->getType())) 1355 continue; 1356 1357 // Iterate over all of the values in all the PHI nodes. 1358 for (unsigned i = 0; i != NumPreds; ++i) { 1359 // If the value being merged in is not integer or is not defined 1360 // in the loop, skip it. 1361 Value *InVal = PN->getIncomingValue(i); 1362 if (!isa<Instruction>(InVal)) 1363 continue; 1364 1365 // If this pred is for a subloop, not L itself, skip it. 1366 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) 1367 continue; // The Block is in a subloop, skip it. 1368 1369 // Check that InVal is defined in the loop. 1370 Instruction *Inst = cast<Instruction>(InVal); 1371 if (!L->contains(Inst)) 1372 continue; 1373 1374 // Find exit values which are induction variables in the loop, and are 1375 // unused in the loop, with the only use being the exit block PhiNode, 1376 // and the induction variable update binary operator. 1377 // The exit value can be replaced with the final value when it is cheap 1378 // to do so. 1379 if (ReplaceExitValue == UnusedIndVarInLoop) { 1380 InductionDescriptor ID; 1381 PHINode *IndPhi = dyn_cast<PHINode>(Inst); 1382 if (IndPhi) { 1383 if (!checkIsIndPhi(IndPhi, L, SE, ID)) 1384 continue; 1385 // This is an induction PHI. Check that the only users are PHI 1386 // nodes, and induction variable update binary operators. 1387 if (llvm::any_of(Inst->users(), [&](User *U) { 1388 if (!isa<PHINode>(U) && !isa<BinaryOperator>(U)) 1389 return true; 1390 BinaryOperator *B = dyn_cast<BinaryOperator>(U); 1391 if (B && B != ID.getInductionBinOp()) 1392 return true; 1393 return false; 1394 })) 1395 continue; 1396 } else { 1397 // If it is not an induction phi, it must be an induction update 1398 // binary operator with an induction phi user. 1399 BinaryOperator *B = dyn_cast<BinaryOperator>(Inst); 1400 if (!B) 1401 continue; 1402 if (llvm::any_of(Inst->users(), [&](User *U) { 1403 PHINode *Phi = dyn_cast<PHINode>(U); 1404 if (Phi != PN && !checkIsIndPhi(Phi, L, SE, ID)) 1405 return true; 1406 return false; 1407 })) 1408 continue; 1409 if (B != ID.getInductionBinOp()) 1410 continue; 1411 } 1412 } 1413 1414 // Okay, this instruction has a user outside of the current loop 1415 // and varies predictably *inside* the loop. Evaluate the value it 1416 // contains when the loop exits, if possible. We prefer to start with 1417 // expressions which are true for all exits (so as to maximize 1418 // expression reuse by the SCEVExpander), but resort to per-exit 1419 // evaluation if that fails. 1420 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop()); 1421 if (isa<SCEVCouldNotCompute>(ExitValue) || 1422 !SE->isLoopInvariant(ExitValue, L) || 1423 !Rewriter.isSafeToExpand(ExitValue)) { 1424 // TODO: This should probably be sunk into SCEV in some way; maybe a 1425 // getSCEVForExit(SCEV*, L, ExitingBB)? It can be generalized for 1426 // most SCEV expressions and other recurrence types (e.g. shift 1427 // recurrences). Is there existing code we can reuse? 1428 const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i)); 1429 if (isa<SCEVCouldNotCompute>(ExitCount)) 1430 continue; 1431 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst))) 1432 if (AddRec->getLoop() == L) 1433 ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE); 1434 if (isa<SCEVCouldNotCompute>(ExitValue) || 1435 !SE->isLoopInvariant(ExitValue, L) || 1436 !Rewriter.isSafeToExpand(ExitValue)) 1437 continue; 1438 } 1439 1440 // Computing the value outside of the loop brings no benefit if it is 1441 // definitely used inside the loop in a way which can not be optimized 1442 // away. Avoid doing so unless we know we have a value which computes 1443 // the ExitValue already. TODO: This should be merged into SCEV 1444 // expander to leverage its knowledge of existing expressions. 1445 if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) && 1446 !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst)) 1447 continue; 1448 1449 // Check if expansions of this SCEV would count as being high cost. 1450 bool HighCost = Rewriter.isHighCostExpansion( 1451 ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst); 1452 1453 // Note that we must not perform expansions until after 1454 // we query *all* the costs, because if we perform temporary expansion 1455 // inbetween, one that we might not intend to keep, said expansion 1456 // *may* affect cost calculation of the the next SCEV's we'll query, 1457 // and next SCEV may errneously get smaller cost. 1458 1459 // Collect all the candidate PHINodes to be rewritten. 1460 Instruction *InsertPt = 1461 (isa<PHINode>(Inst) || isa<LandingPadInst>(Inst)) ? 1462 &*Inst->getParent()->getFirstInsertionPt() : Inst; 1463 RewritePhiSet.emplace_back(PN, i, ExitValue, InsertPt, HighCost); 1464 } 1465 } 1466 } 1467 1468 // TODO: evaluate whether it is beneficial to change how we calculate 1469 // high-cost: if we have SCEV 'A' which we know we will expand, should we 1470 // calculate the cost of other SCEV's after expanding SCEV 'A', thus 1471 // potentially giving cost bonus to those other SCEV's? 1472 1473 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet); 1474 int NumReplaced = 0; 1475 1476 // Transformation. 1477 for (const RewritePhi &Phi : RewritePhiSet) { 1478 PHINode *PN = Phi.PN; 1479 1480 // Only do the rewrite when the ExitValue can be expanded cheaply. 1481 // If LoopCanBeDel is true, rewrite exit value aggressively. 1482 if ((ReplaceExitValue == OnlyCheapRepl || 1483 ReplaceExitValue == UnusedIndVarInLoop) && 1484 !LoopCanBeDel && Phi.HighCost) 1485 continue; 1486 1487 Value *ExitVal = Rewriter.expandCodeFor( 1488 Phi.ExpansionSCEV, Phi.PN->getType(), Phi.ExpansionPoint); 1489 1490 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " << *ExitVal 1491 << '\n' 1492 << " LoopVal = " << *(Phi.ExpansionPoint) << "\n"); 1493 1494 #ifndef NDEBUG 1495 // If we reuse an instruction from a loop which is neither L nor one of 1496 // its containing loops, we end up breaking LCSSA form for this loop by 1497 // creating a new use of its instruction. 1498 if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal)) 1499 if (auto *EVL = LI->getLoopFor(ExitInsn->getParent())) 1500 if (EVL != L) 1501 assert(EVL->contains(L) && "LCSSA breach detected!"); 1502 #endif 1503 1504 NumReplaced++; 1505 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith)); 1506 PN->setIncomingValue(Phi.Ith, ExitVal); 1507 // It's necessary to tell ScalarEvolution about this explicitly so that 1508 // it can walk the def-use list and forget all SCEVs, as it may not be 1509 // watching the PHI itself. Once the new exit value is in place, there 1510 // may not be a def-use connection between the loop and every instruction 1511 // which got a SCEVAddRecExpr for that loop. 1512 SE->forgetValue(PN); 1513 1514 // If this instruction is dead now, delete it. Don't do it now to avoid 1515 // invalidating iterators. 1516 if (isInstructionTriviallyDead(Inst, TLI)) 1517 DeadInsts.push_back(Inst); 1518 1519 // Replace PN with ExitVal if that is legal and does not break LCSSA. 1520 if (PN->getNumIncomingValues() == 1 && 1521 LI->replacementPreservesLCSSAForm(PN, ExitVal)) { 1522 PN->replaceAllUsesWith(ExitVal); 1523 PN->eraseFromParent(); 1524 } 1525 } 1526 1527 // The insertion point instruction may have been deleted; clear it out 1528 // so that the rewriter doesn't trip over it later. 1529 Rewriter.clearInsertPoint(); 1530 return NumReplaced; 1531 } 1532 1533 /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for 1534 /// \p OrigLoop. 1535 void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop, 1536 Loop *RemainderLoop, uint64_t UF) { 1537 assert(UF > 0 && "Zero unrolled factor is not supported"); 1538 assert(UnrolledLoop != RemainderLoop && 1539 "Unrolled and Remainder loops are expected to distinct"); 1540 1541 // Get number of iterations in the original scalar loop. 1542 unsigned OrigLoopInvocationWeight = 0; 1543 std::optional<unsigned> OrigAverageTripCount = 1544 getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight); 1545 if (!OrigAverageTripCount) 1546 return; 1547 1548 // Calculate number of iterations in unrolled loop. 1549 unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF; 1550 // Calculate number of iterations for remainder loop. 1551 unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF; 1552 1553 setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount, 1554 OrigLoopInvocationWeight); 1555 setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount, 1556 OrigLoopInvocationWeight); 1557 } 1558 1559 /// Utility that implements appending of loops onto a worklist. 1560 /// Loops are added in preorder (analogous for reverse postorder for trees), 1561 /// and the worklist is processed LIFO. 1562 template <typename RangeT> 1563 void llvm::appendReversedLoopsToWorklist( 1564 RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) { 1565 // We use an internal worklist to build up the preorder traversal without 1566 // recursion. 1567 SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist; 1568 1569 // We walk the initial sequence of loops in reverse because we generally want 1570 // to visit defs before uses and the worklist is LIFO. 1571 for (Loop *RootL : Loops) { 1572 assert(PreOrderLoops.empty() && "Must start with an empty preorder walk."); 1573 assert(PreOrderWorklist.empty() && 1574 "Must start with an empty preorder walk worklist."); 1575 PreOrderWorklist.push_back(RootL); 1576 do { 1577 Loop *L = PreOrderWorklist.pop_back_val(); 1578 PreOrderWorklist.append(L->begin(), L->end()); 1579 PreOrderLoops.push_back(L); 1580 } while (!PreOrderWorklist.empty()); 1581 1582 Worklist.insert(std::move(PreOrderLoops)); 1583 PreOrderLoops.clear(); 1584 } 1585 } 1586 1587 template <typename RangeT> 1588 void llvm::appendLoopsToWorklist(RangeT &&Loops, 1589 SmallPriorityWorklist<Loop *, 4> &Worklist) { 1590 appendReversedLoopsToWorklist(reverse(Loops), Worklist); 1591 } 1592 1593 template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>( 1594 ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist); 1595 1596 template void 1597 llvm::appendLoopsToWorklist<Loop &>(Loop &L, 1598 SmallPriorityWorklist<Loop *, 4> &Worklist); 1599 1600 void llvm::appendLoopsToWorklist(LoopInfo &LI, 1601 SmallPriorityWorklist<Loop *, 4> &Worklist) { 1602 appendReversedLoopsToWorklist(LI, Worklist); 1603 } 1604 1605 Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, 1606 LoopInfo *LI, LPPassManager *LPM) { 1607 Loop &New = *LI->AllocateLoop(); 1608 if (PL) 1609 PL->addChildLoop(&New); 1610 else 1611 LI->addTopLevelLoop(&New); 1612 1613 if (LPM) 1614 LPM->addLoop(New); 1615 1616 // Add all of the blocks in L to the new loop. 1617 for (BasicBlock *BB : L->blocks()) 1618 if (LI->getLoopFor(BB) == L) 1619 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), *LI); 1620 1621 // Add all of the subloops to the new loop. 1622 for (Loop *I : *L) 1623 cloneLoop(I, &New, VM, LI, LPM); 1624 1625 return &New; 1626 } 1627 1628 /// IR Values for the lower and upper bounds of a pointer evolution. We 1629 /// need to use value-handles because SCEV expansion can invalidate previously 1630 /// expanded values. Thus expansion of a pointer can invalidate the bounds for 1631 /// a previous one. 1632 struct PointerBounds { 1633 TrackingVH<Value> Start; 1634 TrackingVH<Value> End; 1635 }; 1636 1637 /// Expand code for the lower and upper bound of the pointer group \p CG 1638 /// in \p TheLoop. \return the values for the bounds. 1639 static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG, 1640 Loop *TheLoop, Instruction *Loc, 1641 SCEVExpander &Exp) { 1642 LLVMContext &Ctx = Loc->getContext(); 1643 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, CG->AddressSpace); 1644 1645 Value *Start = nullptr, *End = nullptr; 1646 LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n"); 1647 Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc); 1648 End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc); 1649 if (CG->NeedsFreeze) { 1650 IRBuilder<> Builder(Loc); 1651 Start = Builder.CreateFreeze(Start, Start->getName() + ".fr"); 1652 End = Builder.CreateFreeze(End, End->getName() + ".fr"); 1653 } 1654 LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n"); 1655 return {Start, End}; 1656 } 1657 1658 /// Turns a collection of checks into a collection of expanded upper and 1659 /// lower bounds for both pointers in the check. 1660 static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> 1661 expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L, 1662 Instruction *Loc, SCEVExpander &Exp) { 1663 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds; 1664 1665 // Here we're relying on the SCEV Expander's cache to only emit code for the 1666 // same bounds once. 1667 transform(PointerChecks, std::back_inserter(ChecksWithBounds), 1668 [&](const RuntimePointerCheck &Check) { 1669 PointerBounds First = expandBounds(Check.first, L, Loc, Exp), 1670 Second = expandBounds(Check.second, L, Loc, Exp); 1671 return std::make_pair(First, Second); 1672 }); 1673 1674 return ChecksWithBounds; 1675 } 1676 1677 Value *llvm::addRuntimeChecks( 1678 Instruction *Loc, Loop *TheLoop, 1679 const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, 1680 SCEVExpander &Exp) { 1681 // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible. 1682 // TODO: Pass RtPtrChecking instead of PointerChecks and SE separately, if possible 1683 auto ExpandedChecks = expandBounds(PointerChecks, TheLoop, Loc, Exp); 1684 1685 LLVMContext &Ctx = Loc->getContext(); 1686 IRBuilder<InstSimplifyFolder> ChkBuilder(Ctx, 1687 Loc->getModule()->getDataLayout()); 1688 ChkBuilder.SetInsertPoint(Loc); 1689 // Our instructions might fold to a constant. 1690 Value *MemoryRuntimeCheck = nullptr; 1691 1692 for (const auto &Check : ExpandedChecks) { 1693 const PointerBounds &A = Check.first, &B = Check.second; 1694 // Check if two pointers (A and B) conflict where conflict is computed as: 1695 // start(A) <= end(B) && start(B) <= end(A) 1696 unsigned AS0 = A.Start->getType()->getPointerAddressSpace(); 1697 unsigned AS1 = B.Start->getType()->getPointerAddressSpace(); 1698 1699 assert((AS0 == B.End->getType()->getPointerAddressSpace()) && 1700 (AS1 == A.End->getType()->getPointerAddressSpace()) && 1701 "Trying to bounds check pointers with different address spaces"); 1702 1703 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0); 1704 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1); 1705 1706 Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc"); 1707 Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc"); 1708 Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc"); 1709 Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc"); 1710 1711 // [A|B].Start points to the first accessed byte under base [A|B]. 1712 // [A|B].End points to the last accessed byte, plus one. 1713 // There is no conflict when the intervals are disjoint: 1714 // NoConflict = (B.Start >= A.End) || (A.Start >= B.End) 1715 // 1716 // bound0 = (B.Start < A.End) 1717 // bound1 = (A.Start < B.End) 1718 // IsConflict = bound0 & bound1 1719 Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0"); 1720 Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1"); 1721 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict"); 1722 if (MemoryRuntimeCheck) { 1723 IsConflict = 1724 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx"); 1725 } 1726 MemoryRuntimeCheck = IsConflict; 1727 } 1728 1729 return MemoryRuntimeCheck; 1730 } 1731 1732 Value *llvm::addDiffRuntimeChecks( 1733 Instruction *Loc, ArrayRef<PointerDiffInfo> Checks, SCEVExpander &Expander, 1734 function_ref<Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC) { 1735 1736 LLVMContext &Ctx = Loc->getContext(); 1737 IRBuilder<InstSimplifyFolder> ChkBuilder(Ctx, 1738 Loc->getModule()->getDataLayout()); 1739 ChkBuilder.SetInsertPoint(Loc); 1740 // Our instructions might fold to a constant. 1741 Value *MemoryRuntimeCheck = nullptr; 1742 1743 for (const auto &C : Checks) { 1744 Type *Ty = C.SinkStart->getType(); 1745 // Compute VF * IC * AccessSize. 1746 auto *VFTimesUFTimesSize = 1747 ChkBuilder.CreateMul(GetVF(ChkBuilder, Ty->getScalarSizeInBits()), 1748 ConstantInt::get(Ty, IC * C.AccessSize)); 1749 Value *Sink = Expander.expandCodeFor(C.SinkStart, Ty, Loc); 1750 Value *Src = Expander.expandCodeFor(C.SrcStart, Ty, Loc); 1751 if (C.NeedsFreeze) { 1752 IRBuilder<> Builder(Loc); 1753 Sink = Builder.CreateFreeze(Sink, Sink->getName() + ".fr"); 1754 Src = Builder.CreateFreeze(Src, Src->getName() + ".fr"); 1755 } 1756 Value *Diff = ChkBuilder.CreateSub(Sink, Src); 1757 Value *IsConflict = 1758 ChkBuilder.CreateICmpULT(Diff, VFTimesUFTimesSize, "diff.check"); 1759 1760 if (MemoryRuntimeCheck) { 1761 IsConflict = 1762 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx"); 1763 } 1764 MemoryRuntimeCheck = IsConflict; 1765 } 1766 1767 return MemoryRuntimeCheck; 1768 } 1769 1770 std::optional<IVConditionInfo> 1771 llvm::hasPartialIVCondition(const Loop &L, unsigned MSSAThreshold, 1772 const MemorySSA &MSSA, AAResults &AA) { 1773 auto *TI = dyn_cast<BranchInst>(L.getHeader()->getTerminator()); 1774 if (!TI || !TI->isConditional()) 1775 return {}; 1776 1777 auto *CondI = dyn_cast<CmpInst>(TI->getCondition()); 1778 // The case with the condition outside the loop should already be handled 1779 // earlier. 1780 if (!CondI || !L.contains(CondI)) 1781 return {}; 1782 1783 SmallVector<Instruction *> InstToDuplicate; 1784 InstToDuplicate.push_back(CondI); 1785 1786 SmallVector<Value *, 4> WorkList; 1787 WorkList.append(CondI->op_begin(), CondI->op_end()); 1788 1789 SmallVector<MemoryAccess *, 4> AccessesToCheck; 1790 SmallVector<MemoryLocation, 4> AccessedLocs; 1791 while (!WorkList.empty()) { 1792 Instruction *I = dyn_cast<Instruction>(WorkList.pop_back_val()); 1793 if (!I || !L.contains(I)) 1794 continue; 1795 1796 // TODO: support additional instructions. 1797 if (!isa<LoadInst>(I) && !isa<GetElementPtrInst>(I)) 1798 return {}; 1799 1800 // Do not duplicate volatile and atomic loads. 1801 if (auto *LI = dyn_cast<LoadInst>(I)) 1802 if (LI->isVolatile() || LI->isAtomic()) 1803 return {}; 1804 1805 InstToDuplicate.push_back(I); 1806 if (MemoryAccess *MA = MSSA.getMemoryAccess(I)) { 1807 if (auto *MemUse = dyn_cast_or_null<MemoryUse>(MA)) { 1808 // Queue the defining access to check for alias checks. 1809 AccessesToCheck.push_back(MemUse->getDefiningAccess()); 1810 AccessedLocs.push_back(MemoryLocation::get(I)); 1811 } else { 1812 // MemoryDefs may clobber the location or may be atomic memory 1813 // operations. Bail out. 1814 return {}; 1815 } 1816 } 1817 WorkList.append(I->op_begin(), I->op_end()); 1818 } 1819 1820 if (InstToDuplicate.empty()) 1821 return {}; 1822 1823 SmallVector<BasicBlock *, 4> ExitingBlocks; 1824 L.getExitingBlocks(ExitingBlocks); 1825 auto HasNoClobbersOnPath = 1826 [&L, &AA, &AccessedLocs, &ExitingBlocks, &InstToDuplicate, 1827 MSSAThreshold](BasicBlock *Succ, BasicBlock *Header, 1828 SmallVector<MemoryAccess *, 4> AccessesToCheck) 1829 -> std::optional<IVConditionInfo> { 1830 IVConditionInfo Info; 1831 // First, collect all blocks in the loop that are on a patch from Succ 1832 // to the header. 1833 SmallVector<BasicBlock *, 4> WorkList; 1834 WorkList.push_back(Succ); 1835 WorkList.push_back(Header); 1836 SmallPtrSet<BasicBlock *, 4> Seen; 1837 Seen.insert(Header); 1838 Info.PathIsNoop &= 1839 all_of(*Header, [](Instruction &I) { return !I.mayHaveSideEffects(); }); 1840 1841 while (!WorkList.empty()) { 1842 BasicBlock *Current = WorkList.pop_back_val(); 1843 if (!L.contains(Current)) 1844 continue; 1845 const auto &SeenIns = Seen.insert(Current); 1846 if (!SeenIns.second) 1847 continue; 1848 1849 Info.PathIsNoop &= all_of( 1850 *Current, [](Instruction &I) { return !I.mayHaveSideEffects(); }); 1851 WorkList.append(succ_begin(Current), succ_end(Current)); 1852 } 1853 1854 // Require at least 2 blocks on a path through the loop. This skips 1855 // paths that directly exit the loop. 1856 if (Seen.size() < 2) 1857 return {}; 1858 1859 // Next, check if there are any MemoryDefs that are on the path through 1860 // the loop (in the Seen set) and they may-alias any of the locations in 1861 // AccessedLocs. If that is the case, they may modify the condition and 1862 // partial unswitching is not possible. 1863 SmallPtrSet<MemoryAccess *, 4> SeenAccesses; 1864 while (!AccessesToCheck.empty()) { 1865 MemoryAccess *Current = AccessesToCheck.pop_back_val(); 1866 auto SeenI = SeenAccesses.insert(Current); 1867 if (!SeenI.second || !Seen.contains(Current->getBlock())) 1868 continue; 1869 1870 // Bail out if exceeded the threshold. 1871 if (SeenAccesses.size() >= MSSAThreshold) 1872 return {}; 1873 1874 // MemoryUse are read-only accesses. 1875 if (isa<MemoryUse>(Current)) 1876 continue; 1877 1878 // For a MemoryDef, check if is aliases any of the location feeding 1879 // the original condition. 1880 if (auto *CurrentDef = dyn_cast<MemoryDef>(Current)) { 1881 if (any_of(AccessedLocs, [&AA, CurrentDef](MemoryLocation &Loc) { 1882 return isModSet( 1883 AA.getModRefInfo(CurrentDef->getMemoryInst(), Loc)); 1884 })) 1885 return {}; 1886 } 1887 1888 for (Use &U : Current->uses()) 1889 AccessesToCheck.push_back(cast<MemoryAccess>(U.getUser())); 1890 } 1891 1892 // We could also allow loops with known trip counts without mustprogress, 1893 // but ScalarEvolution may not be available. 1894 Info.PathIsNoop &= isMustProgress(&L); 1895 1896 // If the path is considered a no-op so far, check if it reaches a 1897 // single exit block without any phis. This ensures no values from the 1898 // loop are used outside of the loop. 1899 if (Info.PathIsNoop) { 1900 for (auto *Exiting : ExitingBlocks) { 1901 if (!Seen.contains(Exiting)) 1902 continue; 1903 for (auto *Succ : successors(Exiting)) { 1904 if (L.contains(Succ)) 1905 continue; 1906 1907 Info.PathIsNoop &= Succ->phis().empty() && 1908 (!Info.ExitForPath || Info.ExitForPath == Succ); 1909 if (!Info.PathIsNoop) 1910 break; 1911 assert((!Info.ExitForPath || Info.ExitForPath == Succ) && 1912 "cannot have multiple exit blocks"); 1913 Info.ExitForPath = Succ; 1914 } 1915 } 1916 } 1917 if (!Info.ExitForPath) 1918 Info.PathIsNoop = false; 1919 1920 Info.InstToDuplicate = InstToDuplicate; 1921 return Info; 1922 }; 1923 1924 // If we branch to the same successor, partial unswitching will not be 1925 // beneficial. 1926 if (TI->getSuccessor(0) == TI->getSuccessor(1)) 1927 return {}; 1928 1929 if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(0), L.getHeader(), 1930 AccessesToCheck)) { 1931 Info->KnownValue = ConstantInt::getTrue(TI->getContext()); 1932 return Info; 1933 } 1934 if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(1), L.getHeader(), 1935 AccessesToCheck)) { 1936 Info->KnownValue = ConstantInt::getFalse(TI->getContext()); 1937 return Info; 1938 } 1939 1940 return {}; 1941 } 1942