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 /// Checks if \p L has single exit through latch block except possibly 766 /// "deoptimizing" exits. Returns branch instruction terminating the loop 767 /// latch if above check is successful, nullptr otherwise. 768 static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) { 769 BasicBlock *Latch = L->getLoopLatch(); 770 if (!Latch) 771 return nullptr; 772 773 BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator()); 774 if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch)) 775 return nullptr; 776 777 assert((LatchBR->getSuccessor(0) == L->getHeader() || 778 LatchBR->getSuccessor(1) == L->getHeader()) && 779 "At least one edge out of the latch must go to the header"); 780 781 SmallVector<BasicBlock *, 4> ExitBlocks; 782 L->getUniqueNonLatchExitBlocks(ExitBlocks); 783 if (any_of(ExitBlocks, [](const BasicBlock *EB) { 784 return !EB->getTerminatingDeoptimizeCall(); 785 })) 786 return nullptr; 787 788 return LatchBR; 789 } 790 791 Optional<unsigned> 792 llvm::getLoopEstimatedTripCount(Loop *L, 793 unsigned *EstimatedLoopInvocationWeight) { 794 // Support loops with an exiting latch and other existing exists only 795 // deoptimize. 796 BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L); 797 if (!LatchBranch) 798 return None; 799 800 // To estimate the number of times the loop body was executed, we want to 801 // know the number of times the backedge was taken, vs. the number of times 802 // we exited the loop. 803 uint64_t BackedgeTakenWeight, LatchExitWeight; 804 if (!LatchBranch->extractProfMetadata(BackedgeTakenWeight, LatchExitWeight)) 805 return None; 806 807 if (LatchBranch->getSuccessor(0) != L->getHeader()) 808 std::swap(BackedgeTakenWeight, LatchExitWeight); 809 810 if (!LatchExitWeight) 811 return None; 812 813 if (EstimatedLoopInvocationWeight) 814 *EstimatedLoopInvocationWeight = LatchExitWeight; 815 816 // Estimated backedge taken count is a ratio of the backedge taken weight by 817 // the weight of the edge exiting the loop, rounded to nearest. 818 uint64_t BackedgeTakenCount = 819 llvm::divideNearest(BackedgeTakenWeight, LatchExitWeight); 820 // Estimated trip count is one plus estimated backedge taken count. 821 return BackedgeTakenCount + 1; 822 } 823 824 bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, 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 false; 831 832 // Calculate taken and exit weights. 833 unsigned LatchExitWeight = 0; 834 unsigned BackedgeTakenWeight = 0; 835 836 if (EstimatedTripCount > 0) { 837 LatchExitWeight = EstimatedloopInvocationWeight; 838 BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight; 839 } 840 841 // Make a swap if back edge is taken when condition is "false". 842 if (LatchBranch->getSuccessor(0) != L->getHeader()) 843 std::swap(BackedgeTakenWeight, LatchExitWeight); 844 845 MDBuilder MDB(LatchBranch->getContext()); 846 847 // Set/Update profile metadata. 848 LatchBranch->setMetadata( 849 LLVMContext::MD_prof, 850 MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight)); 851 852 return true; 853 } 854 855 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop, 856 ScalarEvolution &SE) { 857 Loop *OuterL = InnerLoop->getParentLoop(); 858 if (!OuterL) 859 return true; 860 861 // Get the backedge taken count for the inner loop 862 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 863 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch); 864 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) || 865 !InnerLoopBECountSC->getType()->isIntegerTy()) 866 return false; 867 868 // Get whether count is invariant to the outer loop 869 ScalarEvolution::LoopDisposition LD = 870 SE.getLoopDisposition(InnerLoopBECountSC, OuterL); 871 if (LD != ScalarEvolution::LoopInvariant) 872 return false; 873 874 return true; 875 } 876 877 Value *llvm::createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left, 878 Value *Right) { 879 CmpInst::Predicate P = CmpInst::ICMP_NE; 880 switch (RK) { 881 default: 882 llvm_unreachable("Unknown min/max recurrence kind"); 883 case RecurKind::UMin: 884 P = CmpInst::ICMP_ULT; 885 break; 886 case RecurKind::UMax: 887 P = CmpInst::ICMP_UGT; 888 break; 889 case RecurKind::SMin: 890 P = CmpInst::ICMP_SLT; 891 break; 892 case RecurKind::SMax: 893 P = CmpInst::ICMP_SGT; 894 break; 895 case RecurKind::FMin: 896 P = CmpInst::FCMP_OLT; 897 break; 898 case RecurKind::FMax: 899 P = CmpInst::FCMP_OGT; 900 break; 901 } 902 903 // We only match FP sequences that are 'fast', so we can unconditionally 904 // set it on any generated instructions. 905 IRBuilderBase::FastMathFlagGuard FMFG(Builder); 906 FastMathFlags FMF; 907 FMF.setFast(); 908 Builder.setFastMathFlags(FMF); 909 Value *Cmp = Builder.CreateCmp(P, Left, Right, "rdx.minmax.cmp"); 910 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 911 return Select; 912 } 913 914 // Helper to generate an ordered reduction. 915 Value *llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src, 916 unsigned Op, RecurKind RdxKind, 917 ArrayRef<Value *> RedOps) { 918 unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements(); 919 920 // Extract and apply reduction ops in ascending order: 921 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1] 922 Value *Result = Acc; 923 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) { 924 Value *Ext = 925 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx)); 926 927 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 928 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext, 929 "bin.rdx"); 930 } else { 931 assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) && 932 "Invalid min/max"); 933 Result = createMinMaxOp(Builder, RdxKind, Result, Ext); 934 } 935 936 if (!RedOps.empty()) 937 propagateIRFlags(Result, RedOps); 938 } 939 940 return Result; 941 } 942 943 // Helper to generate a log2 shuffle reduction. 944 Value *llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src, 945 unsigned Op, RecurKind RdxKind, 946 ArrayRef<Value *> RedOps) { 947 unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements(); 948 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 949 // and vector ops, reducing the set of values being computed by half each 950 // round. 951 assert(isPowerOf2_32(VF) && 952 "Reduction emission only supported for pow2 vectors!"); 953 Value *TmpVec = Src; 954 SmallVector<int, 32> ShuffleMask(VF); 955 for (unsigned i = VF; i != 1; i >>= 1) { 956 // Move the upper half of the vector to the lower half. 957 for (unsigned j = 0; j != i / 2; ++j) 958 ShuffleMask[j] = i / 2 + j; 959 960 // Fill the rest of the mask with undef. 961 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1); 962 963 Value *Shuf = Builder.CreateShuffleVector(TmpVec, ShuffleMask, "rdx.shuf"); 964 965 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 966 // The builder propagates its fast-math-flags setting. 967 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf, 968 "bin.rdx"); 969 } else { 970 assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) && 971 "Invalid min/max"); 972 TmpVec = createMinMaxOp(Builder, RdxKind, TmpVec, Shuf); 973 } 974 if (!RedOps.empty()) 975 propagateIRFlags(TmpVec, RedOps); 976 977 // We may compute the reassociated scalar ops in a way that does not 978 // preserve nsw/nuw etc. Conservatively, drop those flags. 979 if (auto *ReductionInst = dyn_cast<Instruction>(TmpVec)) 980 ReductionInst->dropPoisonGeneratingFlags(); 981 } 982 // The result is in the first element of the vector. 983 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 984 } 985 986 Value *llvm::createSimpleTargetReduction(IRBuilderBase &Builder, 987 const TargetTransformInfo *TTI, 988 Value *Src, RecurKind RdxKind, 989 ArrayRef<Value *> RedOps) { 990 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind); 991 TargetTransformInfo::ReductionFlags RdxFlags; 992 RdxFlags.IsMaxOp = RdxKind == RecurKind::SMax || RdxKind == RecurKind::UMax || 993 RdxKind == RecurKind::FMax; 994 RdxFlags.IsSigned = RdxKind == RecurKind::SMax || RdxKind == RecurKind::SMin; 995 if (!ForceReductionIntrinsic && 996 !TTI->useReductionIntrinsic(Opcode, Src->getType(), RdxFlags)) 997 return getShuffleReduction(Builder, Src, Opcode, RdxKind, RedOps); 998 999 auto *SrcVecEltTy = cast<VectorType>(Src->getType())->getElementType(); 1000 switch (RdxKind) { 1001 case RecurKind::Add: 1002 return Builder.CreateAddReduce(Src); 1003 case RecurKind::Mul: 1004 return Builder.CreateMulReduce(Src); 1005 case RecurKind::And: 1006 return Builder.CreateAndReduce(Src); 1007 case RecurKind::Or: 1008 return Builder.CreateOrReduce(Src); 1009 case RecurKind::Xor: 1010 return Builder.CreateXorReduce(Src); 1011 case RecurKind::FAdd: 1012 return Builder.CreateFAddReduce(ConstantFP::getNegativeZero(SrcVecEltTy), 1013 Src); 1014 case RecurKind::FMul: 1015 return Builder.CreateFMulReduce(ConstantFP::get(SrcVecEltTy, 1.0), Src); 1016 case RecurKind::SMax: 1017 return Builder.CreateIntMaxReduce(Src, true); 1018 case RecurKind::SMin: 1019 return Builder.CreateIntMinReduce(Src, true); 1020 case RecurKind::UMax: 1021 return Builder.CreateIntMaxReduce(Src, false); 1022 case RecurKind::UMin: 1023 return Builder.CreateIntMinReduce(Src, false); 1024 case RecurKind::FMax: 1025 return Builder.CreateFPMaxReduce(Src); 1026 case RecurKind::FMin: 1027 return Builder.CreateFPMinReduce(Src); 1028 default: 1029 llvm_unreachable("Unhandled opcode"); 1030 } 1031 } 1032 1033 Value *llvm::createTargetReduction(IRBuilderBase &B, 1034 const TargetTransformInfo *TTI, 1035 RecurrenceDescriptor &Desc, Value *Src) { 1036 // TODO: Support in-order reductions based on the recurrence descriptor. 1037 // All ops in the reduction inherit fast-math-flags from the recurrence 1038 // descriptor. 1039 IRBuilderBase::FastMathFlagGuard FMFGuard(B); 1040 B.setFastMathFlags(Desc.getFastMathFlags()); 1041 return createSimpleTargetReduction(B, TTI, Src, Desc.getRecurrenceKind()); 1042 } 1043 1044 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) { 1045 auto *VecOp = dyn_cast<Instruction>(I); 1046 if (!VecOp) 1047 return; 1048 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0]) 1049 : dyn_cast<Instruction>(OpValue); 1050 if (!Intersection) 1051 return; 1052 const unsigned Opcode = Intersection->getOpcode(); 1053 VecOp->copyIRFlags(Intersection); 1054 for (auto *V : VL) { 1055 auto *Instr = dyn_cast<Instruction>(V); 1056 if (!Instr) 1057 continue; 1058 if (OpValue == nullptr || Opcode == Instr->getOpcode()) 1059 VecOp->andIRFlags(V); 1060 } 1061 } 1062 1063 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L, 1064 ScalarEvolution &SE) { 1065 const SCEV *Zero = SE.getZero(S->getType()); 1066 return SE.isAvailableAtLoopEntry(S, L) && 1067 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero); 1068 } 1069 1070 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, 1071 ScalarEvolution &SE) { 1072 const SCEV *Zero = SE.getZero(S->getType()); 1073 return SE.isAvailableAtLoopEntry(S, L) && 1074 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero); 1075 } 1076 1077 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1078 bool Signed) { 1079 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1080 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) : 1081 APInt::getMinValue(BitWidth); 1082 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1083 return SE.isAvailableAtLoopEntry(S, L) && 1084 SE.isLoopEntryGuardedByCond(L, Predicate, S, 1085 SE.getConstant(Min)); 1086 } 1087 1088 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 1089 bool Signed) { 1090 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 1091 APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) : 1092 APInt::getMaxValue(BitWidth); 1093 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1094 return SE.isAvailableAtLoopEntry(S, L) && 1095 SE.isLoopEntryGuardedByCond(L, Predicate, S, 1096 SE.getConstant(Max)); 1097 } 1098 1099 //===----------------------------------------------------------------------===// 1100 // rewriteLoopExitValues - Optimize IV users outside the loop. 1101 // As a side effect, reduces the amount of IV processing within the loop. 1102 //===----------------------------------------------------------------------===// 1103 1104 // Return true if the SCEV expansion generated by the rewriter can replace the 1105 // original value. SCEV guarantees that it produces the same value, but the way 1106 // it is produced may be illegal IR. Ideally, this function will only be 1107 // called for verification. 1108 static bool isValidRewrite(ScalarEvolution *SE, Value *FromVal, Value *ToVal) { 1109 // If an SCEV expression subsumed multiple pointers, its expansion could 1110 // reassociate the GEP changing the base pointer. This is illegal because the 1111 // final address produced by a GEP chain must be inbounds relative to its 1112 // underlying object. Otherwise basic alias analysis, among other things, 1113 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid 1114 // producing an expression involving multiple pointers. Until then, we must 1115 // bail out here. 1116 // 1117 // Retrieve the pointer operand of the GEP. Don't use getUnderlyingObject 1118 // because it understands lcssa phis while SCEV does not. 1119 Value *FromPtr = FromVal; 1120 Value *ToPtr = ToVal; 1121 if (auto *GEP = dyn_cast<GEPOperator>(FromVal)) 1122 FromPtr = GEP->getPointerOperand(); 1123 1124 if (auto *GEP = dyn_cast<GEPOperator>(ToVal)) 1125 ToPtr = GEP->getPointerOperand(); 1126 1127 if (FromPtr != FromVal || ToPtr != ToVal) { 1128 // Quickly check the common case 1129 if (FromPtr == ToPtr) 1130 return true; 1131 1132 // SCEV may have rewritten an expression that produces the GEP's pointer 1133 // operand. That's ok as long as the pointer operand has the same base 1134 // pointer. Unlike getUnderlyingObject(), getPointerBase() will find the 1135 // base of a recurrence. This handles the case in which SCEV expansion 1136 // converts a pointer type recurrence into a nonrecurrent pointer base 1137 // indexed by an integer recurrence. 1138 1139 // If the GEP base pointer is a vector of pointers, abort. 1140 if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy()) 1141 return false; 1142 1143 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr)); 1144 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr)); 1145 if (FromBase == ToBase) 1146 return true; 1147 1148 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: GEP rewrite bail out " 1149 << *FromBase << " != " << *ToBase << "\n"); 1150 1151 return false; 1152 } 1153 return true; 1154 } 1155 1156 static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) { 1157 SmallPtrSet<const Instruction *, 8> Visited; 1158 SmallVector<const Instruction *, 8> WorkList; 1159 Visited.insert(I); 1160 WorkList.push_back(I); 1161 while (!WorkList.empty()) { 1162 const Instruction *Curr = WorkList.pop_back_val(); 1163 // This use is outside the loop, nothing to do. 1164 if (!L->contains(Curr)) 1165 continue; 1166 // Do we assume it is a "hard" use which will not be eliminated easily? 1167 if (Curr->mayHaveSideEffects()) 1168 return true; 1169 // Otherwise, add all its users to worklist. 1170 for (auto U : Curr->users()) { 1171 auto *UI = cast<Instruction>(U); 1172 if (Visited.insert(UI).second) 1173 WorkList.push_back(UI); 1174 } 1175 } 1176 return false; 1177 } 1178 1179 // Collect information about PHI nodes which can be transformed in 1180 // rewriteLoopExitValues. 1181 struct RewritePhi { 1182 PHINode *PN; // For which PHI node is this replacement? 1183 unsigned Ith; // For which incoming value? 1184 const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting. 1185 Instruction *ExpansionPoint; // Where we'd like to expand that SCEV? 1186 bool HighCost; // Is this expansion a high-cost? 1187 1188 Value *Expansion = nullptr; 1189 bool ValidRewrite = false; 1190 1191 RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt, 1192 bool H) 1193 : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt), 1194 HighCost(H) {} 1195 }; 1196 1197 // Check whether it is possible to delete the loop after rewriting exit 1198 // value. If it is possible, ignore ReplaceExitValue and do rewriting 1199 // aggressively. 1200 static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) { 1201 BasicBlock *Preheader = L->getLoopPreheader(); 1202 // If there is no preheader, the loop will not be deleted. 1203 if (!Preheader) 1204 return false; 1205 1206 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1. 1207 // We obviate multiple ExitingBlocks case for simplicity. 1208 // TODO: If we see testcase with multiple ExitingBlocks can be deleted 1209 // after exit value rewriting, we can enhance the logic here. 1210 SmallVector<BasicBlock *, 4> ExitingBlocks; 1211 L->getExitingBlocks(ExitingBlocks); 1212 SmallVector<BasicBlock *, 8> ExitBlocks; 1213 L->getUniqueExitBlocks(ExitBlocks); 1214 if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1) 1215 return false; 1216 1217 BasicBlock *ExitBlock = ExitBlocks[0]; 1218 BasicBlock::iterator BI = ExitBlock->begin(); 1219 while (PHINode *P = dyn_cast<PHINode>(BI)) { 1220 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); 1221 1222 // If the Incoming value of P is found in RewritePhiSet, we know it 1223 // could be rewritten to use a loop invariant value in transformation 1224 // phase later. Skip it in the loop invariant check below. 1225 bool found = false; 1226 for (const RewritePhi &Phi : RewritePhiSet) { 1227 if (!Phi.ValidRewrite) 1228 continue; 1229 unsigned i = Phi.Ith; 1230 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) { 1231 found = true; 1232 break; 1233 } 1234 } 1235 1236 Instruction *I; 1237 if (!found && (I = dyn_cast<Instruction>(Incoming))) 1238 if (!L->hasLoopInvariantOperands(I)) 1239 return false; 1240 1241 ++BI; 1242 } 1243 1244 for (auto *BB : L->blocks()) 1245 if (llvm::any_of(*BB, [](Instruction &I) { 1246 return I.mayHaveSideEffects(); 1247 })) 1248 return false; 1249 1250 return true; 1251 } 1252 1253 int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI, 1254 ScalarEvolution *SE, 1255 const TargetTransformInfo *TTI, 1256 SCEVExpander &Rewriter, DominatorTree *DT, 1257 ReplaceExitVal ReplaceExitValue, 1258 SmallVector<WeakTrackingVH, 16> &DeadInsts) { 1259 // Check a pre-condition. 1260 assert(L->isRecursivelyLCSSAForm(*DT, *LI) && 1261 "Indvars did not preserve LCSSA!"); 1262 1263 SmallVector<BasicBlock*, 8> ExitBlocks; 1264 L->getUniqueExitBlocks(ExitBlocks); 1265 1266 SmallVector<RewritePhi, 8> RewritePhiSet; 1267 // Find all values that are computed inside the loop, but used outside of it. 1268 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan 1269 // the exit blocks of the loop to find them. 1270 for (BasicBlock *ExitBB : ExitBlocks) { 1271 // If there are no PHI nodes in this exit block, then no values defined 1272 // inside the loop are used on this path, skip it. 1273 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin()); 1274 if (!PN) continue; 1275 1276 unsigned NumPreds = PN->getNumIncomingValues(); 1277 1278 // Iterate over all of the PHI nodes. 1279 BasicBlock::iterator BBI = ExitBB->begin(); 1280 while ((PN = dyn_cast<PHINode>(BBI++))) { 1281 if (PN->use_empty()) 1282 continue; // dead use, don't replace it 1283 1284 if (!SE->isSCEVable(PN->getType())) 1285 continue; 1286 1287 // It's necessary to tell ScalarEvolution about this explicitly so that 1288 // it can walk the def-use list and forget all SCEVs, as it may not be 1289 // watching the PHI itself. Once the new exit value is in place, there 1290 // may not be a def-use connection between the loop and every instruction 1291 // which got a SCEVAddRecExpr for that loop. 1292 SE->forgetValue(PN); 1293 1294 // Iterate over all of the values in all the PHI nodes. 1295 for (unsigned i = 0; i != NumPreds; ++i) { 1296 // If the value being merged in is not integer or is not defined 1297 // in the loop, skip it. 1298 Value *InVal = PN->getIncomingValue(i); 1299 if (!isa<Instruction>(InVal)) 1300 continue; 1301 1302 // If this pred is for a subloop, not L itself, skip it. 1303 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) 1304 continue; // The Block is in a subloop, skip it. 1305 1306 // Check that InVal is defined in the loop. 1307 Instruction *Inst = cast<Instruction>(InVal); 1308 if (!L->contains(Inst)) 1309 continue; 1310 1311 // Okay, this instruction has a user outside of the current loop 1312 // and varies predictably *inside* the loop. Evaluate the value it 1313 // contains when the loop exits, if possible. We prefer to start with 1314 // expressions which are true for all exits (so as to maximize 1315 // expression reuse by the SCEVExpander), but resort to per-exit 1316 // evaluation if that fails. 1317 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop()); 1318 if (isa<SCEVCouldNotCompute>(ExitValue) || 1319 !SE->isLoopInvariant(ExitValue, L) || 1320 !isSafeToExpand(ExitValue, *SE)) { 1321 // TODO: This should probably be sunk into SCEV in some way; maybe a 1322 // getSCEVForExit(SCEV*, L, ExitingBB)? It can be generalized for 1323 // most SCEV expressions and other recurrence types (e.g. shift 1324 // recurrences). Is there existing code we can reuse? 1325 const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i)); 1326 if (isa<SCEVCouldNotCompute>(ExitCount)) 1327 continue; 1328 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst))) 1329 if (AddRec->getLoop() == L) 1330 ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE); 1331 if (isa<SCEVCouldNotCompute>(ExitValue) || 1332 !SE->isLoopInvariant(ExitValue, L) || 1333 !isSafeToExpand(ExitValue, *SE)) 1334 continue; 1335 } 1336 1337 // Computing the value outside of the loop brings no benefit if it is 1338 // definitely used inside the loop in a way which can not be optimized 1339 // away. Avoid doing so unless we know we have a value which computes 1340 // the ExitValue already. TODO: This should be merged into SCEV 1341 // expander to leverage its knowledge of existing expressions. 1342 if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) && 1343 !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst)) 1344 continue; 1345 1346 // Check if expansions of this SCEV would count as being high cost. 1347 bool HighCost = Rewriter.isHighCostExpansion( 1348 ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst); 1349 1350 // Note that we must not perform expansions until after 1351 // we query *all* the costs, because if we perform temporary expansion 1352 // inbetween, one that we might not intend to keep, said expansion 1353 // *may* affect cost calculation of the the next SCEV's we'll query, 1354 // and next SCEV may errneously get smaller cost. 1355 1356 // Collect all the candidate PHINodes to be rewritten. 1357 RewritePhiSet.emplace_back(PN, i, ExitValue, Inst, HighCost); 1358 } 1359 } 1360 } 1361 1362 // Now that we've done preliminary filtering and billed all the SCEV's, 1363 // we can perform the last sanity check - the expansion must be valid. 1364 for (RewritePhi &Phi : RewritePhiSet) { 1365 Phi.Expansion = Rewriter.expandCodeFor(Phi.ExpansionSCEV, Phi.PN->getType(), 1366 Phi.ExpansionPoint); 1367 1368 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " 1369 << *(Phi.Expansion) << '\n' 1370 << " LoopVal = " << *(Phi.ExpansionPoint) << "\n"); 1371 1372 // FIXME: isValidRewrite() is a hack. it should be an assert, eventually. 1373 Phi.ValidRewrite = isValidRewrite(SE, Phi.ExpansionPoint, Phi.Expansion); 1374 if (!Phi.ValidRewrite) { 1375 DeadInsts.push_back(Phi.Expansion); 1376 continue; 1377 } 1378 1379 #ifndef NDEBUG 1380 // If we reuse an instruction from a loop which is neither L nor one of 1381 // its containing loops, we end up breaking LCSSA form for this loop by 1382 // creating a new use of its instruction. 1383 if (auto *ExitInsn = dyn_cast<Instruction>(Phi.Expansion)) 1384 if (auto *EVL = LI->getLoopFor(ExitInsn->getParent())) 1385 if (EVL != L) 1386 assert(EVL->contains(L) && "LCSSA breach detected!"); 1387 #endif 1388 } 1389 1390 // TODO: after isValidRewrite() is an assertion, evaluate whether 1391 // it is beneficial to change how we calculate high-cost: 1392 // if we have SCEV 'A' which we know we will expand, should we calculate 1393 // the cost of other SCEV's after expanding SCEV 'A', 1394 // thus potentially giving cost bonus to those other SCEV's? 1395 1396 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet); 1397 int NumReplaced = 0; 1398 1399 // Transformation. 1400 for (const RewritePhi &Phi : RewritePhiSet) { 1401 if (!Phi.ValidRewrite) 1402 continue; 1403 1404 PHINode *PN = Phi.PN; 1405 Value *ExitVal = Phi.Expansion; 1406 1407 // Only do the rewrite when the ExitValue can be expanded cheaply. 1408 // If LoopCanBeDel is true, rewrite exit value aggressively. 1409 if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) { 1410 DeadInsts.push_back(ExitVal); 1411 continue; 1412 } 1413 1414 NumReplaced++; 1415 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith)); 1416 PN->setIncomingValue(Phi.Ith, ExitVal); 1417 1418 // If this instruction is dead now, delete it. Don't do it now to avoid 1419 // invalidating iterators. 1420 if (isInstructionTriviallyDead(Inst, TLI)) 1421 DeadInsts.push_back(Inst); 1422 1423 // Replace PN with ExitVal if that is legal and does not break LCSSA. 1424 if (PN->getNumIncomingValues() == 1 && 1425 LI->replacementPreservesLCSSAForm(PN, ExitVal)) { 1426 PN->replaceAllUsesWith(ExitVal); 1427 PN->eraseFromParent(); 1428 } 1429 } 1430 1431 // The insertion point instruction may have been deleted; clear it out 1432 // so that the rewriter doesn't trip over it later. 1433 Rewriter.clearInsertPoint(); 1434 return NumReplaced; 1435 } 1436 1437 /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for 1438 /// \p OrigLoop. 1439 void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop, 1440 Loop *RemainderLoop, uint64_t UF) { 1441 assert(UF > 0 && "Zero unrolled factor is not supported"); 1442 assert(UnrolledLoop != RemainderLoop && 1443 "Unrolled and Remainder loops are expected to distinct"); 1444 1445 // Get number of iterations in the original scalar loop. 1446 unsigned OrigLoopInvocationWeight = 0; 1447 Optional<unsigned> OrigAverageTripCount = 1448 getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight); 1449 if (!OrigAverageTripCount) 1450 return; 1451 1452 // Calculate number of iterations in unrolled loop. 1453 unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF; 1454 // Calculate number of iterations for remainder loop. 1455 unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF; 1456 1457 setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount, 1458 OrigLoopInvocationWeight); 1459 setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount, 1460 OrigLoopInvocationWeight); 1461 } 1462 1463 /// Utility that implements appending of loops onto a worklist. 1464 /// Loops are added in preorder (analogous for reverse postorder for trees), 1465 /// and the worklist is processed LIFO. 1466 template <typename RangeT> 1467 void llvm::appendReversedLoopsToWorklist( 1468 RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) { 1469 // We use an internal worklist to build up the preorder traversal without 1470 // recursion. 1471 SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist; 1472 1473 // We walk the initial sequence of loops in reverse because we generally want 1474 // to visit defs before uses and the worklist is LIFO. 1475 for (Loop *RootL : Loops) { 1476 assert(PreOrderLoops.empty() && "Must start with an empty preorder walk."); 1477 assert(PreOrderWorklist.empty() && 1478 "Must start with an empty preorder walk worklist."); 1479 PreOrderWorklist.push_back(RootL); 1480 do { 1481 Loop *L = PreOrderWorklist.pop_back_val(); 1482 PreOrderWorklist.append(L->begin(), L->end()); 1483 PreOrderLoops.push_back(L); 1484 } while (!PreOrderWorklist.empty()); 1485 1486 Worklist.insert(std::move(PreOrderLoops)); 1487 PreOrderLoops.clear(); 1488 } 1489 } 1490 1491 template <typename RangeT> 1492 void llvm::appendLoopsToWorklist(RangeT &&Loops, 1493 SmallPriorityWorklist<Loop *, 4> &Worklist) { 1494 appendReversedLoopsToWorklist(reverse(Loops), Worklist); 1495 } 1496 1497 template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>( 1498 ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist); 1499 1500 template void 1501 llvm::appendLoopsToWorklist<Loop &>(Loop &L, 1502 SmallPriorityWorklist<Loop *, 4> &Worklist); 1503 1504 void llvm::appendLoopsToWorklist(LoopInfo &LI, 1505 SmallPriorityWorklist<Loop *, 4> &Worklist) { 1506 appendReversedLoopsToWorklist(LI, Worklist); 1507 } 1508 1509 Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, 1510 LoopInfo *LI, LPPassManager *LPM) { 1511 Loop &New = *LI->AllocateLoop(); 1512 if (PL) 1513 PL->addChildLoop(&New); 1514 else 1515 LI->addTopLevelLoop(&New); 1516 1517 if (LPM) 1518 LPM->addLoop(New); 1519 1520 // Add all of the blocks in L to the new loop. 1521 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 1522 I != E; ++I) 1523 if (LI->getLoopFor(*I) == L) 1524 New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI); 1525 1526 // Add all of the subloops to the new loop. 1527 for (Loop *I : *L) 1528 cloneLoop(I, &New, VM, LI, LPM); 1529 1530 return &New; 1531 } 1532 1533 /// IR Values for the lower and upper bounds of a pointer evolution. We 1534 /// need to use value-handles because SCEV expansion can invalidate previously 1535 /// expanded values. Thus expansion of a pointer can invalidate the bounds for 1536 /// a previous one. 1537 struct PointerBounds { 1538 TrackingVH<Value> Start; 1539 TrackingVH<Value> End; 1540 }; 1541 1542 /// Expand code for the lower and upper bound of the pointer group \p CG 1543 /// in \p TheLoop. \return the values for the bounds. 1544 static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG, 1545 Loop *TheLoop, Instruction *Loc, 1546 SCEVExpander &Exp, ScalarEvolution *SE) { 1547 // TODO: Add helper to retrieve pointers to CG. 1548 Value *Ptr = CG->RtCheck.Pointers[CG->Members[0]].PointerValue; 1549 const SCEV *Sc = SE->getSCEV(Ptr); 1550 1551 unsigned AS = Ptr->getType()->getPointerAddressSpace(); 1552 LLVMContext &Ctx = Loc->getContext(); 1553 1554 // Use this type for pointer arithmetic. 1555 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS); 1556 1557 if (SE->isLoopInvariant(Sc, TheLoop)) { 1558 LLVM_DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" 1559 << *Ptr << "\n"); 1560 // Ptr could be in the loop body. If so, expand a new one at the correct 1561 // location. 1562 Instruction *Inst = dyn_cast<Instruction>(Ptr); 1563 Value *NewPtr = (Inst && TheLoop->contains(Inst)) 1564 ? Exp.expandCodeFor(Sc, PtrArithTy, Loc) 1565 : Ptr; 1566 // We must return a half-open range, which means incrementing Sc. 1567 const SCEV *ScPlusOne = SE->getAddExpr(Sc, SE->getOne(PtrArithTy)); 1568 Value *NewPtrPlusOne = Exp.expandCodeFor(ScPlusOne, PtrArithTy, Loc); 1569 return {NewPtr, NewPtrPlusOne}; 1570 } else { 1571 Value *Start = nullptr, *End = nullptr; 1572 LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n"); 1573 Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc); 1574 End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc); 1575 LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High 1576 << "\n"); 1577 return {Start, End}; 1578 } 1579 } 1580 1581 /// Turns a collection of checks into a collection of expanded upper and 1582 /// lower bounds for both pointers in the check. 1583 static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> 1584 expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L, 1585 Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp) { 1586 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds; 1587 1588 // Here we're relying on the SCEV Expander's cache to only emit code for the 1589 // same bounds once. 1590 transform(PointerChecks, std::back_inserter(ChecksWithBounds), 1591 [&](const RuntimePointerCheck &Check) { 1592 PointerBounds First = expandBounds(Check.first, L, Loc, Exp, SE), 1593 Second = 1594 expandBounds(Check.second, L, Loc, Exp, SE); 1595 return std::make_pair(First, Second); 1596 }); 1597 1598 return ChecksWithBounds; 1599 } 1600 1601 std::pair<Instruction *, Instruction *> llvm::addRuntimeChecks( 1602 Instruction *Loc, Loop *TheLoop, 1603 const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, 1604 ScalarEvolution *SE) { 1605 // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible. 1606 // TODO: Pass RtPtrChecking instead of PointerChecks and SE separately, if possible 1607 const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout(); 1608 SCEVExpander Exp(*SE, DL, "induction"); 1609 auto ExpandedChecks = expandBounds(PointerChecks, TheLoop, Loc, SE, Exp); 1610 1611 LLVMContext &Ctx = Loc->getContext(); 1612 Instruction *FirstInst = nullptr; 1613 IRBuilder<> ChkBuilder(Loc); 1614 // Our instructions might fold to a constant. 1615 Value *MemoryRuntimeCheck = nullptr; 1616 1617 // FIXME: this helper is currently a duplicate of the one in 1618 // LoopVectorize.cpp. 1619 auto GetFirstInst = [](Instruction *FirstInst, Value *V, 1620 Instruction *Loc) -> Instruction * { 1621 if (FirstInst) 1622 return FirstInst; 1623 if (Instruction *I = dyn_cast<Instruction>(V)) 1624 return I->getParent() == Loc->getParent() ? I : nullptr; 1625 return nullptr; 1626 }; 1627 1628 for (const auto &Check : ExpandedChecks) { 1629 const PointerBounds &A = Check.first, &B = Check.second; 1630 // Check if two pointers (A and B) conflict where conflict is computed as: 1631 // start(A) <= end(B) && start(B) <= end(A) 1632 unsigned AS0 = A.Start->getType()->getPointerAddressSpace(); 1633 unsigned AS1 = B.Start->getType()->getPointerAddressSpace(); 1634 1635 assert((AS0 == B.End->getType()->getPointerAddressSpace()) && 1636 (AS1 == A.End->getType()->getPointerAddressSpace()) && 1637 "Trying to bounds check pointers with different address spaces"); 1638 1639 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0); 1640 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1); 1641 1642 Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc"); 1643 Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc"); 1644 Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc"); 1645 Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc"); 1646 1647 // [A|B].Start points to the first accessed byte under base [A|B]. 1648 // [A|B].End points to the last accessed byte, plus one. 1649 // There is no conflict when the intervals are disjoint: 1650 // NoConflict = (B.Start >= A.End) || (A.Start >= B.End) 1651 // 1652 // bound0 = (B.Start < A.End) 1653 // bound1 = (A.Start < B.End) 1654 // IsConflict = bound0 & bound1 1655 Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0"); 1656 FirstInst = GetFirstInst(FirstInst, Cmp0, Loc); 1657 Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1"); 1658 FirstInst = GetFirstInst(FirstInst, Cmp1, Loc); 1659 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict"); 1660 FirstInst = GetFirstInst(FirstInst, IsConflict, Loc); 1661 if (MemoryRuntimeCheck) { 1662 IsConflict = 1663 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx"); 1664 FirstInst = GetFirstInst(FirstInst, IsConflict, Loc); 1665 } 1666 MemoryRuntimeCheck = IsConflict; 1667 } 1668 1669 if (!MemoryRuntimeCheck) 1670 return std::make_pair(nullptr, nullptr); 1671 1672 // We have to do this trickery because the IRBuilder might fold the check to a 1673 // constant expression in which case there is no Instruction anchored in a 1674 // the block. 1675 Instruction *Check = 1676 BinaryOperator::CreateAnd(MemoryRuntimeCheck, ConstantInt::getTrue(Ctx)); 1677 ChkBuilder.Insert(Check, "memcheck.conflict"); 1678 FirstInst = GetFirstInst(FirstInst, Check, Loc); 1679 return std::make_pair(FirstInst, Check); 1680 } 1681