1 //===-- LoopUtils.cpp - Loop Utility functions -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines common loop utility functions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Transforms/Utils/LoopUtils.h" 14 #include "llvm/ADT/ScopeExit.h" 15 #include "llvm/Analysis/AliasAnalysis.h" 16 #include "llvm/Analysis/BasicAliasAnalysis.h" 17 #include "llvm/Analysis/GlobalsModRef.h" 18 #include "llvm/Analysis/InstructionSimplify.h" 19 #include "llvm/Analysis/LoopInfo.h" 20 #include "llvm/Analysis/LoopPass.h" 21 #include "llvm/Analysis/MustExecute.h" 22 #include "llvm/Analysis/ScalarEvolution.h" 23 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 24 #include "llvm/Analysis/ScalarEvolutionExpander.h" 25 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 26 #include "llvm/Analysis/TargetTransformInfo.h" 27 #include "llvm/Analysis/ValueTracking.h" 28 #include "llvm/IR/DIBuilder.h" 29 #include "llvm/IR/DomTreeUpdater.h" 30 #include "llvm/IR/Dominators.h" 31 #include "llvm/IR/Instructions.h" 32 #include "llvm/IR/IntrinsicInst.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/PatternMatch.h" 35 #include "llvm/IR/ValueHandle.h" 36 #include "llvm/Pass.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 40 41 using namespace llvm; 42 using namespace llvm::PatternMatch; 43 44 #define DEBUG_TYPE "loop-utils" 45 46 static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced"; 47 48 bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, 49 bool PreserveLCSSA) { 50 bool Changed = false; 51 52 // We re-use a vector for the in-loop predecesosrs. 53 SmallVector<BasicBlock *, 4> InLoopPredecessors; 54 55 auto RewriteExit = [&](BasicBlock *BB) { 56 assert(InLoopPredecessors.empty() && 57 "Must start with an empty predecessors list!"); 58 auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); }); 59 60 // See if there are any non-loop predecessors of this exit block and 61 // keep track of the in-loop predecessors. 62 bool IsDedicatedExit = true; 63 for (auto *PredBB : predecessors(BB)) 64 if (L->contains(PredBB)) { 65 if (isa<IndirectBrInst>(PredBB->getTerminator())) 66 // We cannot rewrite exiting edges from an indirectbr. 67 return false; 68 69 InLoopPredecessors.push_back(PredBB); 70 } else { 71 IsDedicatedExit = false; 72 } 73 74 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!"); 75 76 // Nothing to do if this is already a dedicated exit. 77 if (IsDedicatedExit) 78 return false; 79 80 auto *NewExitBB = SplitBlockPredecessors( 81 BB, InLoopPredecessors, ".loopexit", DT, LI, nullptr, PreserveLCSSA); 82 83 if (!NewExitBB) 84 LLVM_DEBUG( 85 dbgs() << "WARNING: Can't create a dedicated exit block for loop: " 86 << *L << "\n"); 87 else 88 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block " 89 << NewExitBB->getName() << "\n"); 90 return true; 91 }; 92 93 // Walk the exit blocks directly rather than building up a data structure for 94 // them, but only visit each one once. 95 SmallPtrSet<BasicBlock *, 4> Visited; 96 for (auto *BB : L->blocks()) 97 for (auto *SuccBB : successors(BB)) { 98 // We're looking for exit blocks so skip in-loop successors. 99 if (L->contains(SuccBB)) 100 continue; 101 102 // Visit each exit block exactly once. 103 if (!Visited.insert(SuccBB).second) 104 continue; 105 106 Changed |= RewriteExit(SuccBB); 107 } 108 109 return Changed; 110 } 111 112 /// Returns the instructions that use values defined in the loop. 113 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) { 114 SmallVector<Instruction *, 8> UsedOutside; 115 116 for (auto *Block : L->getBlocks()) 117 // FIXME: I believe that this could use copy_if if the Inst reference could 118 // be adapted into a pointer. 119 for (auto &Inst : *Block) { 120 auto Users = Inst.users(); 121 if (any_of(Users, [&](User *U) { 122 auto *Use = cast<Instruction>(U); 123 return !L->contains(Use->getParent()); 124 })) 125 UsedOutside.push_back(&Inst); 126 } 127 128 return UsedOutside; 129 } 130 131 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) { 132 // By definition, all loop passes need the LoopInfo analysis and the 133 // Dominator tree it depends on. Because they all participate in the loop 134 // pass manager, they must also preserve these. 135 AU.addRequired<DominatorTreeWrapperPass>(); 136 AU.addPreserved<DominatorTreeWrapperPass>(); 137 AU.addRequired<LoopInfoWrapperPass>(); 138 AU.addPreserved<LoopInfoWrapperPass>(); 139 140 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs 141 // here because users shouldn't directly get them from this header. 142 extern char &LoopSimplifyID; 143 extern char &LCSSAID; 144 AU.addRequiredID(LoopSimplifyID); 145 AU.addPreservedID(LoopSimplifyID); 146 AU.addRequiredID(LCSSAID); 147 AU.addPreservedID(LCSSAID); 148 // This is used in the LPPassManager to perform LCSSA verification on passes 149 // which preserve lcssa form 150 AU.addRequired<LCSSAVerificationPass>(); 151 AU.addPreserved<LCSSAVerificationPass>(); 152 153 // Loop passes are designed to run inside of a loop pass manager which means 154 // that any function analyses they require must be required by the first loop 155 // pass in the manager (so that it is computed before the loop pass manager 156 // runs) and preserved by all loop pasess in the manager. To make this 157 // reasonably robust, the set needed for most loop passes is maintained here. 158 // If your loop pass requires an analysis not listed here, you will need to 159 // carefully audit the loop pass manager nesting structure that results. 160 AU.addRequired<AAResultsWrapperPass>(); 161 AU.addPreserved<AAResultsWrapperPass>(); 162 AU.addPreserved<BasicAAWrapperPass>(); 163 AU.addPreserved<GlobalsAAWrapperPass>(); 164 AU.addPreserved<SCEVAAWrapperPass>(); 165 AU.addRequired<ScalarEvolutionWrapperPass>(); 166 AU.addPreserved<ScalarEvolutionWrapperPass>(); 167 } 168 169 /// Manually defined generic "LoopPass" dependency initialization. This is used 170 /// to initialize the exact set of passes from above in \c 171 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization 172 /// with: 173 /// 174 /// INITIALIZE_PASS_DEPENDENCY(LoopPass) 175 /// 176 /// As-if "LoopPass" were a pass. 177 void llvm::initializeLoopPassPass(PassRegistry &Registry) { 178 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 179 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 180 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 181 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 182 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 183 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 184 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 185 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 186 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 187 } 188 189 /// Find string metadata for loop 190 /// 191 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an 192 /// operand or null otherwise. If the string metadata is not found return 193 /// Optional's not-a-value. 194 Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop, 195 StringRef Name) { 196 MDNode *MD = findOptionMDForLoop(TheLoop, Name); 197 if (!MD) 198 return None; 199 switch (MD->getNumOperands()) { 200 case 1: 201 return nullptr; 202 case 2: 203 return &MD->getOperand(1); 204 default: 205 llvm_unreachable("loop metadata has 0 or 1 operand"); 206 } 207 } 208 209 static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop, 210 StringRef Name) { 211 MDNode *MD = findOptionMDForLoop(TheLoop, Name); 212 if (!MD) 213 return None; 214 switch (MD->getNumOperands()) { 215 case 1: 216 // When the value is absent it is interpreted as 'attribute set'. 217 return true; 218 case 2: 219 return mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()); 220 } 221 llvm_unreachable("unexpected number of options"); 222 } 223 224 static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) { 225 return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false); 226 } 227 228 llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop, 229 StringRef Name) { 230 const MDOperand *AttrMD = 231 findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr); 232 if (!AttrMD) 233 return None; 234 235 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get()); 236 if (!IntMD) 237 return None; 238 239 return IntMD->getSExtValue(); 240 } 241 242 Optional<MDNode *> llvm::makeFollowupLoopID( 243 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions, 244 const char *InheritOptionsExceptPrefix, bool AlwaysNew) { 245 if (!OrigLoopID) { 246 if (AlwaysNew) 247 return nullptr; 248 return None; 249 } 250 251 assert(OrigLoopID->getOperand(0) == OrigLoopID); 252 253 bool InheritAllAttrs = !InheritOptionsExceptPrefix; 254 bool InheritSomeAttrs = 255 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0'; 256 SmallVector<Metadata *, 8> MDs; 257 MDs.push_back(nullptr); 258 259 bool Changed = false; 260 if (InheritAllAttrs || InheritSomeAttrs) { 261 for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) { 262 MDNode *Op = cast<MDNode>(Existing.get()); 263 264 auto InheritThisAttribute = [InheritSomeAttrs, 265 InheritOptionsExceptPrefix](MDNode *Op) { 266 if (!InheritSomeAttrs) 267 return false; 268 269 // Skip malformatted attribute metadata nodes. 270 if (Op->getNumOperands() == 0) 271 return true; 272 Metadata *NameMD = Op->getOperand(0).get(); 273 if (!isa<MDString>(NameMD)) 274 return true; 275 StringRef AttrName = cast<MDString>(NameMD)->getString(); 276 277 // Do not inherit excluded attributes. 278 return !AttrName.startswith(InheritOptionsExceptPrefix); 279 }; 280 281 if (InheritThisAttribute(Op)) 282 MDs.push_back(Op); 283 else 284 Changed = true; 285 } 286 } else { 287 // Modified if we dropped at least one attribute. 288 Changed = OrigLoopID->getNumOperands() > 1; 289 } 290 291 bool HasAnyFollowup = false; 292 for (StringRef OptionName : FollowupOptions) { 293 MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName); 294 if (!FollowupNode) 295 continue; 296 297 HasAnyFollowup = true; 298 for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) { 299 MDs.push_back(Option.get()); 300 Changed = true; 301 } 302 } 303 304 // Attributes of the followup loop not specified explicity, so signal to the 305 // transformation pass to add suitable attributes. 306 if (!AlwaysNew && !HasAnyFollowup) 307 return None; 308 309 // If no attributes were added or remove, the previous loop Id can be reused. 310 if (!AlwaysNew && !Changed) 311 return OrigLoopID; 312 313 // No attributes is equivalent to having no !llvm.loop metadata at all. 314 if (MDs.size() == 1) 315 return nullptr; 316 317 // Build the new loop ID. 318 MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs); 319 FollowupLoopID->replaceOperandWith(0, FollowupLoopID); 320 return FollowupLoopID; 321 } 322 323 bool llvm::hasDisableAllTransformsHint(const Loop *L) { 324 return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced); 325 } 326 327 TransformationMode llvm::hasUnrollTransformation(Loop *L) { 328 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable")) 329 return TM_SuppressedByUser; 330 331 Optional<int> Count = 332 getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count"); 333 if (Count.hasValue()) 334 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 335 336 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable")) 337 return TM_ForcedByUser; 338 339 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full")) 340 return TM_ForcedByUser; 341 342 if (hasDisableAllTransformsHint(L)) 343 return TM_Disable; 344 345 return TM_Unspecified; 346 } 347 348 TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) { 349 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable")) 350 return TM_SuppressedByUser; 351 352 Optional<int> Count = 353 getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count"); 354 if (Count.hasValue()) 355 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 356 357 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable")) 358 return TM_ForcedByUser; 359 360 if (hasDisableAllTransformsHint(L)) 361 return TM_Disable; 362 363 return TM_Unspecified; 364 } 365 366 TransformationMode llvm::hasVectorizeTransformation(Loop *L) { 367 Optional<bool> Enable = 368 getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable"); 369 370 if (Enable == false) 371 return TM_SuppressedByUser; 372 373 Optional<int> VectorizeWidth = 374 getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width"); 375 Optional<int> InterleaveCount = 376 getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count"); 377 378 if (Enable == true) { 379 // 'Forcing' vector width and interleave count to one effectively disables 380 // this tranformation. 381 if (VectorizeWidth == 1 && InterleaveCount == 1) 382 return TM_SuppressedByUser; 383 return TM_ForcedByUser; 384 } 385 386 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized")) 387 return TM_Disable; 388 389 if (VectorizeWidth == 1 && InterleaveCount == 1) 390 return TM_Disable; 391 392 if (VectorizeWidth > 1 || InterleaveCount > 1) 393 return TM_Enable; 394 395 if (hasDisableAllTransformsHint(L)) 396 return TM_Disable; 397 398 return TM_Unspecified; 399 } 400 401 TransformationMode llvm::hasDistributeTransformation(Loop *L) { 402 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable")) 403 return TM_ForcedByUser; 404 405 if (hasDisableAllTransformsHint(L)) 406 return TM_Disable; 407 408 return TM_Unspecified; 409 } 410 411 TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) { 412 if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable")) 413 return TM_SuppressedByUser; 414 415 if (hasDisableAllTransformsHint(L)) 416 return TM_Disable; 417 418 return TM_Unspecified; 419 } 420 421 /// Does a BFS from a given node to all of its children inside a given loop. 422 /// The returned vector of nodes includes the starting point. 423 SmallVector<DomTreeNode *, 16> 424 llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) { 425 SmallVector<DomTreeNode *, 16> Worklist; 426 auto AddRegionToWorklist = [&](DomTreeNode *DTN) { 427 // Only include subregions in the top level loop. 428 BasicBlock *BB = DTN->getBlock(); 429 if (CurLoop->contains(BB)) 430 Worklist.push_back(DTN); 431 }; 432 433 AddRegionToWorklist(N); 434 435 for (size_t I = 0; I < Worklist.size(); I++) 436 for (DomTreeNode *Child : Worklist[I]->getChildren()) 437 AddRegionToWorklist(Child); 438 439 return Worklist; 440 } 441 442 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr, 443 ScalarEvolution *SE = nullptr, 444 LoopInfo *LI = nullptr) { 445 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!"); 446 auto *Preheader = L->getLoopPreheader(); 447 assert(Preheader && "Preheader should exist!"); 448 449 // Now that we know the removal is safe, remove the loop by changing the 450 // branch from the preheader to go to the single exit block. 451 // 452 // Because we're deleting a large chunk of code at once, the sequence in which 453 // we remove things is very important to avoid invalidation issues. 454 455 // Tell ScalarEvolution that the loop is deleted. Do this before 456 // deleting the loop so that ScalarEvolution can look at the loop 457 // to determine what it needs to clean up. 458 if (SE) 459 SE->forgetLoop(L); 460 461 auto *ExitBlock = L->getUniqueExitBlock(); 462 assert(ExitBlock && "Should have a unique exit block!"); 463 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!"); 464 465 auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator()); 466 assert(OldBr && "Preheader must end with a branch"); 467 assert(OldBr->isUnconditional() && "Preheader must have a single successor"); 468 // Connect the preheader to the exit block. Keep the old edge to the header 469 // around to perform the dominator tree update in two separate steps 470 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge 471 // preheader -> header. 472 // 473 // 474 // 0. Preheader 1. Preheader 2. Preheader 475 // | | | | 476 // V | V | 477 // Header <--\ | Header <--\ | Header <--\ 478 // | | | | | | | | | | | 479 // | V | | | V | | | V | 480 // | Body --/ | | Body --/ | | Body --/ 481 // V V V V V 482 // Exit Exit Exit 483 // 484 // By doing this is two separate steps we can perform the dominator tree 485 // update without using the batch update API. 486 // 487 // Even when the loop is never executed, we cannot remove the edge from the 488 // source block to the exit block. Consider the case where the unexecuted loop 489 // branches back to an outer loop. If we deleted the loop and removed the edge 490 // coming to this inner loop, this will break the outer loop structure (by 491 // deleting the backedge of the outer loop). If the outer loop is indeed a 492 // non-loop, it will be deleted in a future iteration of loop deletion pass. 493 IRBuilder<> Builder(OldBr); 494 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock); 495 // Remove the old branch. The conditional branch becomes a new terminator. 496 OldBr->eraseFromParent(); 497 498 // Rewrite phis in the exit block to get their inputs from the Preheader 499 // instead of the exiting block. 500 for (PHINode &P : ExitBlock->phis()) { 501 // Set the zero'th element of Phi to be from the preheader and remove all 502 // other incoming values. Given the loop has dedicated exits, all other 503 // incoming values must be from the exiting blocks. 504 int PredIndex = 0; 505 P.setIncomingBlock(PredIndex, Preheader); 506 // Removes all incoming values from all other exiting blocks (including 507 // duplicate values from an exiting block). 508 // Nuke all entries except the zero'th entry which is the preheader entry. 509 // NOTE! We need to remove Incoming Values in the reverse order as done 510 // below, to keep the indices valid for deletion (removeIncomingValues 511 // updates getNumIncomingValues and shifts all values down into the operand 512 // being deleted). 513 for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i) 514 P.removeIncomingValue(e - i, false); 515 516 assert((P.getNumIncomingValues() == 1 && 517 P.getIncomingBlock(PredIndex) == Preheader) && 518 "Should have exactly one value and that's from the preheader!"); 519 } 520 521 // Disconnect the loop body by branching directly to its exit. 522 Builder.SetInsertPoint(Preheader->getTerminator()); 523 Builder.CreateBr(ExitBlock); 524 // Remove the old branch. 525 Preheader->getTerminator()->eraseFromParent(); 526 527 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 528 if (DT) { 529 // Update the dominator tree by informing it about the new edge from the 530 // preheader to the exit. 531 DTU.insertEdge(Preheader, ExitBlock); 532 // Inform the dominator tree about the removed edge. 533 DTU.deleteEdge(Preheader, L->getHeader()); 534 } 535 536 // Use a map to unique and a vector to guarantee deterministic ordering. 537 llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet; 538 llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst; 539 540 // Given LCSSA form is satisfied, we should not have users of instructions 541 // within the dead loop outside of the loop. However, LCSSA doesn't take 542 // unreachable uses into account. We handle them here. 543 // We could do it after drop all references (in this case all users in the 544 // loop will be already eliminated and we have less work to do but according 545 // to API doc of User::dropAllReferences only valid operation after dropping 546 // references, is deletion. So let's substitute all usages of 547 // instruction from the loop with undef value of corresponding type first. 548 for (auto *Block : L->blocks()) 549 for (Instruction &I : *Block) { 550 auto *Undef = UndefValue::get(I.getType()); 551 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) { 552 Use &U = *UI; 553 ++UI; 554 if (auto *Usr = dyn_cast<Instruction>(U.getUser())) 555 if (L->contains(Usr->getParent())) 556 continue; 557 // If we have a DT then we can check that uses outside a loop only in 558 // unreachable block. 559 if (DT) 560 assert(!DT->isReachableFromEntry(U) && 561 "Unexpected user in reachable block"); 562 U.set(Undef); 563 } 564 auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I); 565 if (!DVI) 566 continue; 567 auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()}); 568 if (Key != DeadDebugSet.end()) 569 continue; 570 DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()}); 571 DeadDebugInst.push_back(DVI); 572 } 573 574 // After the loop has been deleted all the values defined and modified 575 // inside the loop are going to be unavailable. 576 // Since debug values in the loop have been deleted, inserting an undef 577 // dbg.value truncates the range of any dbg.value before the loop where the 578 // loop used to be. This is particularly important for constant values. 579 DIBuilder DIB(*ExitBlock->getModule()); 580 for (auto *DVI : DeadDebugInst) 581 DIB.insertDbgValueIntrinsic( 582 UndefValue::get(Builder.getInt32Ty()), DVI->getVariable(), 583 DVI->getExpression(), DVI->getDebugLoc(), ExitBlock->getFirstNonPHI()); 584 585 // Remove the block from the reference counting scheme, so that we can 586 // delete it freely later. 587 for (auto *Block : L->blocks()) 588 Block->dropAllReferences(); 589 590 if (LI) { 591 // Erase the instructions and the blocks without having to worry 592 // about ordering because we already dropped the references. 593 // NOTE: This iteration is safe because erasing the block does not remove 594 // its entry from the loop's block list. We do that in the next section. 595 for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end(); 596 LpI != LpE; ++LpI) 597 (*LpI)->eraseFromParent(); 598 599 // Finally, the blocks from loopinfo. This has to happen late because 600 // otherwise our loop iterators won't work. 601 602 SmallPtrSet<BasicBlock *, 8> blocks; 603 blocks.insert(L->block_begin(), L->block_end()); 604 for (BasicBlock *BB : blocks) 605 LI->removeBlock(BB); 606 607 // The last step is to update LoopInfo now that we've eliminated this loop. 608 LI->erase(L); 609 } 610 } 611 612 Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) { 613 // Only support loops with a unique exiting block, and a latch. 614 if (!L->getExitingBlock()) 615 return None; 616 617 // Get the branch weights for the loop's backedge. 618 BranchInst *LatchBR = 619 dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator()); 620 if (!LatchBR || LatchBR->getNumSuccessors() != 2) 621 return None; 622 623 assert((LatchBR->getSuccessor(0) == L->getHeader() || 624 LatchBR->getSuccessor(1) == L->getHeader()) && 625 "At least one edge out of the latch must go to the header"); 626 627 // To estimate the number of times the loop body was executed, we want to 628 // know the number of times the backedge was taken, vs. the number of times 629 // we exited the loop. 630 uint64_t TrueVal, FalseVal; 631 if (!LatchBR->extractProfMetadata(TrueVal, FalseVal)) 632 return None; 633 634 if (!TrueVal || !FalseVal) 635 return 0; 636 637 // Divide the count of the backedge by the count of the edge exiting the loop, 638 // rounding to nearest. 639 if (LatchBR->getSuccessor(0) == L->getHeader()) 640 return (TrueVal + (FalseVal / 2)) / FalseVal; 641 else 642 return (FalseVal + (TrueVal / 2)) / TrueVal; 643 } 644 645 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop, 646 ScalarEvolution &SE) { 647 Loop *OuterL = InnerLoop->getParentLoop(); 648 if (!OuterL) 649 return true; 650 651 // Get the backedge taken count for the inner loop 652 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 653 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch); 654 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) || 655 !InnerLoopBECountSC->getType()->isIntegerTy()) 656 return false; 657 658 // Get whether count is invariant to the outer loop 659 ScalarEvolution::LoopDisposition LD = 660 SE.getLoopDisposition(InnerLoopBECountSC, OuterL); 661 if (LD != ScalarEvolution::LoopInvariant) 662 return false; 663 664 return true; 665 } 666 667 /// Adds a 'fast' flag to floating point operations. 668 static Value *addFastMathFlag(Value *V) { 669 if (isa<FPMathOperator>(V)) { 670 FastMathFlags Flags; 671 Flags.setFast(); 672 cast<Instruction>(V)->setFastMathFlags(Flags); 673 } 674 return V; 675 } 676 677 Value *llvm::createMinMaxOp(IRBuilder<> &Builder, 678 RecurrenceDescriptor::MinMaxRecurrenceKind RK, 679 Value *Left, Value *Right) { 680 CmpInst::Predicate P = CmpInst::ICMP_NE; 681 switch (RK) { 682 default: 683 llvm_unreachable("Unknown min/max recurrence kind"); 684 case RecurrenceDescriptor::MRK_UIntMin: 685 P = CmpInst::ICMP_ULT; 686 break; 687 case RecurrenceDescriptor::MRK_UIntMax: 688 P = CmpInst::ICMP_UGT; 689 break; 690 case RecurrenceDescriptor::MRK_SIntMin: 691 P = CmpInst::ICMP_SLT; 692 break; 693 case RecurrenceDescriptor::MRK_SIntMax: 694 P = CmpInst::ICMP_SGT; 695 break; 696 case RecurrenceDescriptor::MRK_FloatMin: 697 P = CmpInst::FCMP_OLT; 698 break; 699 case RecurrenceDescriptor::MRK_FloatMax: 700 P = CmpInst::FCMP_OGT; 701 break; 702 } 703 704 // We only match FP sequences that are 'fast', so we can unconditionally 705 // set it on any generated instructions. 706 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 707 FastMathFlags FMF; 708 FMF.setFast(); 709 Builder.setFastMathFlags(FMF); 710 711 Value *Cmp; 712 if (RK == RecurrenceDescriptor::MRK_FloatMin || 713 RK == RecurrenceDescriptor::MRK_FloatMax) 714 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp"); 715 else 716 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp"); 717 718 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 719 return Select; 720 } 721 722 // Helper to generate an ordered reduction. 723 Value * 724 llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src, 725 unsigned Op, 726 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 727 ArrayRef<Value *> RedOps) { 728 unsigned VF = Src->getType()->getVectorNumElements(); 729 730 // Extract and apply reduction ops in ascending order: 731 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1] 732 Value *Result = Acc; 733 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) { 734 Value *Ext = 735 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx)); 736 737 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 738 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext, 739 "bin.rdx"); 740 } else { 741 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 742 "Invalid min/max"); 743 Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext); 744 } 745 746 if (!RedOps.empty()) 747 propagateIRFlags(Result, RedOps); 748 } 749 750 return Result; 751 } 752 753 // Helper to generate a log2 shuffle reduction. 754 Value * 755 llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op, 756 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 757 ArrayRef<Value *> RedOps) { 758 unsigned VF = Src->getType()->getVectorNumElements(); 759 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 760 // and vector ops, reducing the set of values being computed by half each 761 // round. 762 assert(isPowerOf2_32(VF) && 763 "Reduction emission only supported for pow2 vectors!"); 764 Value *TmpVec = Src; 765 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr); 766 for (unsigned i = VF; i != 1; i >>= 1) { 767 // Move the upper half of the vector to the lower half. 768 for (unsigned j = 0; j != i / 2; ++j) 769 ShuffleMask[j] = Builder.getInt32(i / 2 + j); 770 771 // Fill the rest of the mask with undef. 772 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), 773 UndefValue::get(Builder.getInt32Ty())); 774 775 Value *Shuf = Builder.CreateShuffleVector( 776 TmpVec, UndefValue::get(TmpVec->getType()), 777 ConstantVector::get(ShuffleMask), "rdx.shuf"); 778 779 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 780 // Floating point operations had to be 'fast' to enable the reduction. 781 TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op, 782 TmpVec, Shuf, "bin.rdx")); 783 } else { 784 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 785 "Invalid min/max"); 786 TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf); 787 } 788 if (!RedOps.empty()) 789 propagateIRFlags(TmpVec, RedOps); 790 } 791 // The result is in the first element of the vector. 792 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 793 } 794 795 /// Create a simple vector reduction specified by an opcode and some 796 /// flags (if generating min/max reductions). 797 Value *llvm::createSimpleTargetReduction( 798 IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode, 799 Value *Src, TargetTransformInfo::ReductionFlags Flags, 800 ArrayRef<Value *> RedOps) { 801 assert(isa<VectorType>(Src->getType()) && "Type must be a vector"); 802 803 Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType()); 804 std::function<Value *()> BuildFunc; 805 using RD = RecurrenceDescriptor; 806 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid; 807 // TODO: Support creating ordered reductions. 808 FastMathFlags FMFFast; 809 FMFFast.setFast(); 810 811 switch (Opcode) { 812 case Instruction::Add: 813 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); }; 814 break; 815 case Instruction::Mul: 816 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); }; 817 break; 818 case Instruction::And: 819 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); }; 820 break; 821 case Instruction::Or: 822 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); }; 823 break; 824 case Instruction::Xor: 825 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); }; 826 break; 827 case Instruction::FAdd: 828 BuildFunc = [&]() { 829 auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src); 830 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast); 831 return Rdx; 832 }; 833 break; 834 case Instruction::FMul: 835 BuildFunc = [&]() { 836 auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src); 837 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast); 838 return Rdx; 839 }; 840 break; 841 case Instruction::ICmp: 842 if (Flags.IsMaxOp) { 843 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax; 844 BuildFunc = [&]() { 845 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned); 846 }; 847 } else { 848 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin; 849 BuildFunc = [&]() { 850 return Builder.CreateIntMinReduce(Src, Flags.IsSigned); 851 }; 852 } 853 break; 854 case Instruction::FCmp: 855 if (Flags.IsMaxOp) { 856 MinMaxKind = RD::MRK_FloatMax; 857 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); }; 858 } else { 859 MinMaxKind = RD::MRK_FloatMin; 860 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); }; 861 } 862 break; 863 default: 864 llvm_unreachable("Unhandled opcode"); 865 break; 866 } 867 if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags)) 868 return BuildFunc(); 869 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps); 870 } 871 872 /// Create a vector reduction using a given recurrence descriptor. 873 Value *llvm::createTargetReduction(IRBuilder<> &B, 874 const TargetTransformInfo *TTI, 875 RecurrenceDescriptor &Desc, Value *Src, 876 bool NoNaN) { 877 // TODO: Support in-order reductions based on the recurrence descriptor. 878 using RD = RecurrenceDescriptor; 879 RD::RecurrenceKind RecKind = Desc.getRecurrenceKind(); 880 TargetTransformInfo::ReductionFlags Flags; 881 Flags.NoNaN = NoNaN; 882 switch (RecKind) { 883 case RD::RK_FloatAdd: 884 return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags); 885 case RD::RK_FloatMult: 886 return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags); 887 case RD::RK_IntegerAdd: 888 return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags); 889 case RD::RK_IntegerMult: 890 return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags); 891 case RD::RK_IntegerAnd: 892 return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags); 893 case RD::RK_IntegerOr: 894 return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags); 895 case RD::RK_IntegerXor: 896 return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags); 897 case RD::RK_IntegerMinMax: { 898 RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind(); 899 Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax); 900 Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin); 901 return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags); 902 } 903 case RD::RK_FloatMinMax: { 904 Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax; 905 return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags); 906 } 907 default: 908 llvm_unreachable("Unhandled RecKind"); 909 } 910 } 911 912 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) { 913 auto *VecOp = dyn_cast<Instruction>(I); 914 if (!VecOp) 915 return; 916 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0]) 917 : dyn_cast<Instruction>(OpValue); 918 if (!Intersection) 919 return; 920 const unsigned Opcode = Intersection->getOpcode(); 921 VecOp->copyIRFlags(Intersection); 922 for (auto *V : VL) { 923 auto *Instr = dyn_cast<Instruction>(V); 924 if (!Instr) 925 continue; 926 if (OpValue == nullptr || Opcode == Instr->getOpcode()) 927 VecOp->andIRFlags(V); 928 } 929 } 930 931 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L, 932 ScalarEvolution &SE) { 933 const SCEV *Zero = SE.getZero(S->getType()); 934 return SE.isAvailableAtLoopEntry(S, L) && 935 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero); 936 } 937 938 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, 939 ScalarEvolution &SE) { 940 const SCEV *Zero = SE.getZero(S->getType()); 941 return SE.isAvailableAtLoopEntry(S, L) && 942 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero); 943 } 944 945 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 946 bool Signed) { 947 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 948 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) : 949 APInt::getMinValue(BitWidth); 950 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 951 return SE.isAvailableAtLoopEntry(S, L) && 952 SE.isLoopEntryGuardedByCond(L, Predicate, S, 953 SE.getConstant(Min)); 954 } 955 956 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 957 bool Signed) { 958 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 959 APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) : 960 APInt::getMaxValue(BitWidth); 961 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 962 return SE.isAvailableAtLoopEntry(S, L) && 963 SE.isLoopEntryGuardedByCond(L, Predicate, S, 964 SE.getConstant(Max)); 965 } 966