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