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