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 if (ConstantInt *IntMD = 220 mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get())) 221 return IntMD->getZExtValue(); 222 return true; 223 } 224 llvm_unreachable("unexpected number of options"); 225 } 226 227 static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) { 228 return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false); 229 } 230 231 llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop, 232 StringRef Name) { 233 const MDOperand *AttrMD = 234 findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr); 235 if (!AttrMD) 236 return None; 237 238 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get()); 239 if (!IntMD) 240 return None; 241 242 return IntMD->getSExtValue(); 243 } 244 245 Optional<MDNode *> llvm::makeFollowupLoopID( 246 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions, 247 const char *InheritOptionsExceptPrefix, bool AlwaysNew) { 248 if (!OrigLoopID) { 249 if (AlwaysNew) 250 return nullptr; 251 return None; 252 } 253 254 assert(OrigLoopID->getOperand(0) == OrigLoopID); 255 256 bool InheritAllAttrs = !InheritOptionsExceptPrefix; 257 bool InheritSomeAttrs = 258 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0'; 259 SmallVector<Metadata *, 8> MDs; 260 MDs.push_back(nullptr); 261 262 bool Changed = false; 263 if (InheritAllAttrs || InheritSomeAttrs) { 264 for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) { 265 MDNode *Op = cast<MDNode>(Existing.get()); 266 267 auto InheritThisAttribute = [InheritSomeAttrs, 268 InheritOptionsExceptPrefix](MDNode *Op) { 269 if (!InheritSomeAttrs) 270 return false; 271 272 // Skip malformatted attribute metadata nodes. 273 if (Op->getNumOperands() == 0) 274 return true; 275 Metadata *NameMD = Op->getOperand(0).get(); 276 if (!isa<MDString>(NameMD)) 277 return true; 278 StringRef AttrName = cast<MDString>(NameMD)->getString(); 279 280 // Do not inherit excluded attributes. 281 return !AttrName.startswith(InheritOptionsExceptPrefix); 282 }; 283 284 if (InheritThisAttribute(Op)) 285 MDs.push_back(Op); 286 else 287 Changed = true; 288 } 289 } else { 290 // Modified if we dropped at least one attribute. 291 Changed = OrigLoopID->getNumOperands() > 1; 292 } 293 294 bool HasAnyFollowup = false; 295 for (StringRef OptionName : FollowupOptions) { 296 MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName); 297 if (!FollowupNode) 298 continue; 299 300 HasAnyFollowup = true; 301 for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) { 302 MDs.push_back(Option.get()); 303 Changed = true; 304 } 305 } 306 307 // Attributes of the followup loop not specified explicity, so signal to the 308 // transformation pass to add suitable attributes. 309 if (!AlwaysNew && !HasAnyFollowup) 310 return None; 311 312 // If no attributes were added or remove, the previous loop Id can be reused. 313 if (!AlwaysNew && !Changed) 314 return OrigLoopID; 315 316 // No attributes is equivalent to having no !llvm.loop metadata at all. 317 if (MDs.size() == 1) 318 return nullptr; 319 320 // Build the new loop ID. 321 MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs); 322 FollowupLoopID->replaceOperandWith(0, FollowupLoopID); 323 return FollowupLoopID; 324 } 325 326 bool llvm::hasDisableAllTransformsHint(const Loop *L) { 327 return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced); 328 } 329 330 TransformationMode llvm::hasUnrollTransformation(Loop *L) { 331 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable")) 332 return TM_SuppressedByUser; 333 334 Optional<int> Count = 335 getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count"); 336 if (Count.hasValue()) 337 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 338 339 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable")) 340 return TM_ForcedByUser; 341 342 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full")) 343 return TM_ForcedByUser; 344 345 if (hasDisableAllTransformsHint(L)) 346 return TM_Disable; 347 348 return TM_Unspecified; 349 } 350 351 TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) { 352 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable")) 353 return TM_SuppressedByUser; 354 355 Optional<int> Count = 356 getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count"); 357 if (Count.hasValue()) 358 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; 359 360 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable")) 361 return TM_ForcedByUser; 362 363 if (hasDisableAllTransformsHint(L)) 364 return TM_Disable; 365 366 return TM_Unspecified; 367 } 368 369 TransformationMode llvm::hasVectorizeTransformation(Loop *L) { 370 Optional<bool> Enable = 371 getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable"); 372 373 if (Enable == false) 374 return TM_SuppressedByUser; 375 376 Optional<int> VectorizeWidth = 377 getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width"); 378 Optional<int> InterleaveCount = 379 getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count"); 380 381 // 'Forcing' vector width and interleave count to one effectively disables 382 // this tranformation. 383 if (Enable == true && VectorizeWidth == 1 && InterleaveCount == 1) 384 return TM_SuppressedByUser; 385 386 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized")) 387 return TM_Disable; 388 389 if (Enable == true) 390 return TM_ForcedByUser; 391 392 if (VectorizeWidth == 1 && InterleaveCount == 1) 393 return TM_Disable; 394 395 if (VectorizeWidth > 1 || InterleaveCount > 1) 396 return TM_Enable; 397 398 if (hasDisableAllTransformsHint(L)) 399 return TM_Disable; 400 401 return TM_Unspecified; 402 } 403 404 TransformationMode llvm::hasDistributeTransformation(Loop *L) { 405 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable")) 406 return TM_ForcedByUser; 407 408 if (hasDisableAllTransformsHint(L)) 409 return TM_Disable; 410 411 return TM_Unspecified; 412 } 413 414 TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) { 415 if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable")) 416 return TM_SuppressedByUser; 417 418 if (hasDisableAllTransformsHint(L)) 419 return TM_Disable; 420 421 return TM_Unspecified; 422 } 423 424 /// Does a BFS from a given node to all of its children inside a given loop. 425 /// The returned vector of nodes includes the starting point. 426 SmallVector<DomTreeNode *, 16> 427 llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) { 428 SmallVector<DomTreeNode *, 16> Worklist; 429 auto AddRegionToWorklist = [&](DomTreeNode *DTN) { 430 // Only include subregions in the top level loop. 431 BasicBlock *BB = DTN->getBlock(); 432 if (CurLoop->contains(BB)) 433 Worklist.push_back(DTN); 434 }; 435 436 AddRegionToWorklist(N); 437 438 for (size_t I = 0; I < Worklist.size(); I++) 439 for (DomTreeNode *Child : Worklist[I]->getChildren()) 440 AddRegionToWorklist(Child); 441 442 return Worklist; 443 } 444 445 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr, 446 ScalarEvolution *SE = nullptr, 447 LoopInfo *LI = nullptr) { 448 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!"); 449 auto *Preheader = L->getLoopPreheader(); 450 assert(Preheader && "Preheader should exist!"); 451 452 // Now that we know the removal is safe, remove the loop by changing the 453 // branch from the preheader to go to the single exit block. 454 // 455 // Because we're deleting a large chunk of code at once, the sequence in which 456 // we remove things is very important to avoid invalidation issues. 457 458 // Tell ScalarEvolution that the loop is deleted. Do this before 459 // deleting the loop so that ScalarEvolution can look at the loop 460 // to determine what it needs to clean up. 461 if (SE) 462 SE->forgetLoop(L); 463 464 auto *ExitBlock = L->getUniqueExitBlock(); 465 assert(ExitBlock && "Should have a unique exit block!"); 466 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!"); 467 468 auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator()); 469 assert(OldBr && "Preheader must end with a branch"); 470 assert(OldBr->isUnconditional() && "Preheader must have a single successor"); 471 // Connect the preheader to the exit block. Keep the old edge to the header 472 // around to perform the dominator tree update in two separate steps 473 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge 474 // preheader -> header. 475 // 476 // 477 // 0. Preheader 1. Preheader 2. Preheader 478 // | | | | 479 // V | V | 480 // Header <--\ | Header <--\ | Header <--\ 481 // | | | | | | | | | | | 482 // | V | | | V | | | V | 483 // | Body --/ | | Body --/ | | Body --/ 484 // V V V V V 485 // Exit Exit Exit 486 // 487 // By doing this is two separate steps we can perform the dominator tree 488 // update without using the batch update API. 489 // 490 // Even when the loop is never executed, we cannot remove the edge from the 491 // source block to the exit block. Consider the case where the unexecuted loop 492 // branches back to an outer loop. If we deleted the loop and removed the edge 493 // coming to this inner loop, this will break the outer loop structure (by 494 // deleting the backedge of the outer loop). If the outer loop is indeed a 495 // non-loop, it will be deleted in a future iteration of loop deletion pass. 496 IRBuilder<> Builder(OldBr); 497 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock); 498 // Remove the old branch. The conditional branch becomes a new terminator. 499 OldBr->eraseFromParent(); 500 501 // Rewrite phis in the exit block to get their inputs from the Preheader 502 // instead of the exiting block. 503 for (PHINode &P : ExitBlock->phis()) { 504 // Set the zero'th element of Phi to be from the preheader and remove all 505 // other incoming values. Given the loop has dedicated exits, all other 506 // incoming values must be from the exiting blocks. 507 int PredIndex = 0; 508 P.setIncomingBlock(PredIndex, Preheader); 509 // Removes all incoming values from all other exiting blocks (including 510 // duplicate values from an exiting block). 511 // Nuke all entries except the zero'th entry which is the preheader entry. 512 // NOTE! We need to remove Incoming Values in the reverse order as done 513 // below, to keep the indices valid for deletion (removeIncomingValues 514 // updates getNumIncomingValues and shifts all values down into the operand 515 // being deleted). 516 for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i) 517 P.removeIncomingValue(e - i, false); 518 519 assert((P.getNumIncomingValues() == 1 && 520 P.getIncomingBlock(PredIndex) == Preheader) && 521 "Should have exactly one value and that's from the preheader!"); 522 } 523 524 // Disconnect the loop body by branching directly to its exit. 525 Builder.SetInsertPoint(Preheader->getTerminator()); 526 Builder.CreateBr(ExitBlock); 527 // Remove the old branch. 528 Preheader->getTerminator()->eraseFromParent(); 529 530 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 531 if (DT) { 532 // Update the dominator tree by informing it about the new edge from the 533 // preheader to the exit. 534 DTU.insertEdge(Preheader, ExitBlock); 535 // Inform the dominator tree about the removed edge. 536 DTU.deleteEdge(Preheader, L->getHeader()); 537 } 538 539 // Use a map to unique and a vector to guarantee deterministic ordering. 540 llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet; 541 llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst; 542 543 // Given LCSSA form is satisfied, we should not have users of instructions 544 // within the dead loop outside of the loop. However, LCSSA doesn't take 545 // unreachable uses into account. We handle them here. 546 // We could do it after drop all references (in this case all users in the 547 // loop will be already eliminated and we have less work to do but according 548 // to API doc of User::dropAllReferences only valid operation after dropping 549 // references, is deletion. So let's substitute all usages of 550 // instruction from the loop with undef value of corresponding type first. 551 for (auto *Block : L->blocks()) 552 for (Instruction &I : *Block) { 553 auto *Undef = UndefValue::get(I.getType()); 554 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) { 555 Use &U = *UI; 556 ++UI; 557 if (auto *Usr = dyn_cast<Instruction>(U.getUser())) 558 if (L->contains(Usr->getParent())) 559 continue; 560 // If we have a DT then we can check that uses outside a loop only in 561 // unreachable block. 562 if (DT) 563 assert(!DT->isReachableFromEntry(U) && 564 "Unexpected user in reachable block"); 565 U.set(Undef); 566 } 567 auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I); 568 if (!DVI) 569 continue; 570 auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()}); 571 if (Key != DeadDebugSet.end()) 572 continue; 573 DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()}); 574 DeadDebugInst.push_back(DVI); 575 } 576 577 // After the loop has been deleted all the values defined and modified 578 // inside the loop are going to be unavailable. 579 // Since debug values in the loop have been deleted, inserting an undef 580 // dbg.value truncates the range of any dbg.value before the loop where the 581 // loop used to be. This is particularly important for constant values. 582 DIBuilder DIB(*ExitBlock->getModule()); 583 for (auto *DVI : DeadDebugInst) 584 DIB.insertDbgValueIntrinsic( 585 UndefValue::get(Builder.getInt32Ty()), DVI->getVariable(), 586 DVI->getExpression(), DVI->getDebugLoc(), ExitBlock->getFirstNonPHI()); 587 588 // Remove the block from the reference counting scheme, so that we can 589 // delete it freely later. 590 for (auto *Block : L->blocks()) 591 Block->dropAllReferences(); 592 593 if (LI) { 594 // Erase the instructions and the blocks without having to worry 595 // about ordering because we already dropped the references. 596 // NOTE: This iteration is safe because erasing the block does not remove 597 // its entry from the loop's block list. We do that in the next section. 598 for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end(); 599 LpI != LpE; ++LpI) 600 (*LpI)->eraseFromParent(); 601 602 // Finally, the blocks from loopinfo. This has to happen late because 603 // otherwise our loop iterators won't work. 604 605 SmallPtrSet<BasicBlock *, 8> blocks; 606 blocks.insert(L->block_begin(), L->block_end()); 607 for (BasicBlock *BB : blocks) 608 LI->removeBlock(BB); 609 610 // The last step is to update LoopInfo now that we've eliminated this loop. 611 LI->erase(L); 612 } 613 } 614 615 Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) { 616 // Only support loops with a unique exiting block, and a latch. 617 if (!L->getExitingBlock()) 618 return None; 619 620 // Get the branch weights for the loop's backedge. 621 BranchInst *LatchBR = 622 dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator()); 623 if (!LatchBR || LatchBR->getNumSuccessors() != 2) 624 return None; 625 626 assert((LatchBR->getSuccessor(0) == L->getHeader() || 627 LatchBR->getSuccessor(1) == L->getHeader()) && 628 "At least one edge out of the latch must go to the header"); 629 630 // To estimate the number of times the loop body was executed, we want to 631 // know the number of times the backedge was taken, vs. the number of times 632 // we exited the loop. 633 uint64_t TrueVal, FalseVal; 634 if (!LatchBR->extractProfMetadata(TrueVal, FalseVal)) 635 return None; 636 637 if (!TrueVal || !FalseVal) 638 return 0; 639 640 // Divide the count of the backedge by the count of the edge exiting the loop, 641 // rounding to nearest. 642 if (LatchBR->getSuccessor(0) == L->getHeader()) 643 return (TrueVal + (FalseVal / 2)) / FalseVal; 644 else 645 return (FalseVal + (TrueVal / 2)) / TrueVal; 646 } 647 648 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop, 649 ScalarEvolution &SE) { 650 Loop *OuterL = InnerLoop->getParentLoop(); 651 if (!OuterL) 652 return true; 653 654 // Get the backedge taken count for the inner loop 655 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 656 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch); 657 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) || 658 !InnerLoopBECountSC->getType()->isIntegerTy()) 659 return false; 660 661 // Get whether count is invariant to the outer loop 662 ScalarEvolution::LoopDisposition LD = 663 SE.getLoopDisposition(InnerLoopBECountSC, OuterL); 664 if (LD != ScalarEvolution::LoopInvariant) 665 return false; 666 667 return true; 668 } 669 670 /// Adds a 'fast' flag to floating point operations. 671 static Value *addFastMathFlag(Value *V) { 672 if (isa<FPMathOperator>(V)) { 673 FastMathFlags Flags; 674 Flags.setFast(); 675 cast<Instruction>(V)->setFastMathFlags(Flags); 676 } 677 return V; 678 } 679 680 Value *llvm::createMinMaxOp(IRBuilder<> &Builder, 681 RecurrenceDescriptor::MinMaxRecurrenceKind RK, 682 Value *Left, Value *Right) { 683 CmpInst::Predicate P = CmpInst::ICMP_NE; 684 switch (RK) { 685 default: 686 llvm_unreachable("Unknown min/max recurrence kind"); 687 case RecurrenceDescriptor::MRK_UIntMin: 688 P = CmpInst::ICMP_ULT; 689 break; 690 case RecurrenceDescriptor::MRK_UIntMax: 691 P = CmpInst::ICMP_UGT; 692 break; 693 case RecurrenceDescriptor::MRK_SIntMin: 694 P = CmpInst::ICMP_SLT; 695 break; 696 case RecurrenceDescriptor::MRK_SIntMax: 697 P = CmpInst::ICMP_SGT; 698 break; 699 case RecurrenceDescriptor::MRK_FloatMin: 700 P = CmpInst::FCMP_OLT; 701 break; 702 case RecurrenceDescriptor::MRK_FloatMax: 703 P = CmpInst::FCMP_OGT; 704 break; 705 } 706 707 // We only match FP sequences that are 'fast', so we can unconditionally 708 // set it on any generated instructions. 709 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 710 FastMathFlags FMF; 711 FMF.setFast(); 712 Builder.setFastMathFlags(FMF); 713 714 Value *Cmp; 715 if (RK == RecurrenceDescriptor::MRK_FloatMin || 716 RK == RecurrenceDescriptor::MRK_FloatMax) 717 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp"); 718 else 719 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp"); 720 721 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 722 return Select; 723 } 724 725 // Helper to generate an ordered reduction. 726 Value * 727 llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src, 728 unsigned Op, 729 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 730 ArrayRef<Value *> RedOps) { 731 unsigned VF = Src->getType()->getVectorNumElements(); 732 733 // Extract and apply reduction ops in ascending order: 734 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1] 735 Value *Result = Acc; 736 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) { 737 Value *Ext = 738 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx)); 739 740 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 741 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext, 742 "bin.rdx"); 743 } else { 744 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 745 "Invalid min/max"); 746 Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext); 747 } 748 749 if (!RedOps.empty()) 750 propagateIRFlags(Result, RedOps); 751 } 752 753 return Result; 754 } 755 756 // Helper to generate a log2 shuffle reduction. 757 Value * 758 llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op, 759 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, 760 ArrayRef<Value *> RedOps) { 761 unsigned VF = Src->getType()->getVectorNumElements(); 762 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 763 // and vector ops, reducing the set of values being computed by half each 764 // round. 765 assert(isPowerOf2_32(VF) && 766 "Reduction emission only supported for pow2 vectors!"); 767 Value *TmpVec = Src; 768 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr); 769 for (unsigned i = VF; i != 1; i >>= 1) { 770 // Move the upper half of the vector to the lower half. 771 for (unsigned j = 0; j != i / 2; ++j) 772 ShuffleMask[j] = Builder.getInt32(i / 2 + j); 773 774 // Fill the rest of the mask with undef. 775 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), 776 UndefValue::get(Builder.getInt32Ty())); 777 778 Value *Shuf = Builder.CreateShuffleVector( 779 TmpVec, UndefValue::get(TmpVec->getType()), 780 ConstantVector::get(ShuffleMask), "rdx.shuf"); 781 782 if (Op != Instruction::ICmp && Op != Instruction::FCmp) { 783 // Floating point operations had to be 'fast' to enable the reduction. 784 TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op, 785 TmpVec, Shuf, "bin.rdx")); 786 } else { 787 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && 788 "Invalid min/max"); 789 TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf); 790 } 791 if (!RedOps.empty()) 792 propagateIRFlags(TmpVec, RedOps); 793 } 794 // The result is in the first element of the vector. 795 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 796 } 797 798 /// Create a simple vector reduction specified by an opcode and some 799 /// flags (if generating min/max reductions). 800 Value *llvm::createSimpleTargetReduction( 801 IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode, 802 Value *Src, TargetTransformInfo::ReductionFlags Flags, 803 ArrayRef<Value *> RedOps) { 804 assert(isa<VectorType>(Src->getType()) && "Type must be a vector"); 805 806 Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType()); 807 std::function<Value *()> BuildFunc; 808 using RD = RecurrenceDescriptor; 809 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid; 810 // TODO: Support creating ordered reductions. 811 FastMathFlags FMFFast; 812 FMFFast.setFast(); 813 814 switch (Opcode) { 815 case Instruction::Add: 816 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); }; 817 break; 818 case Instruction::Mul: 819 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); }; 820 break; 821 case Instruction::And: 822 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); }; 823 break; 824 case Instruction::Or: 825 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); }; 826 break; 827 case Instruction::Xor: 828 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); }; 829 break; 830 case Instruction::FAdd: 831 BuildFunc = [&]() { 832 auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src); 833 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast); 834 return Rdx; 835 }; 836 break; 837 case Instruction::FMul: 838 BuildFunc = [&]() { 839 auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src); 840 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast); 841 return Rdx; 842 }; 843 break; 844 case Instruction::ICmp: 845 if (Flags.IsMaxOp) { 846 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax; 847 BuildFunc = [&]() { 848 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned); 849 }; 850 } else { 851 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin; 852 BuildFunc = [&]() { 853 return Builder.CreateIntMinReduce(Src, Flags.IsSigned); 854 }; 855 } 856 break; 857 case Instruction::FCmp: 858 if (Flags.IsMaxOp) { 859 MinMaxKind = RD::MRK_FloatMax; 860 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); }; 861 } else { 862 MinMaxKind = RD::MRK_FloatMin; 863 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); }; 864 } 865 break; 866 default: 867 llvm_unreachable("Unhandled opcode"); 868 break; 869 } 870 if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags)) 871 return BuildFunc(); 872 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps); 873 } 874 875 /// Create a vector reduction using a given recurrence descriptor. 876 Value *llvm::createTargetReduction(IRBuilder<> &B, 877 const TargetTransformInfo *TTI, 878 RecurrenceDescriptor &Desc, Value *Src, 879 bool NoNaN) { 880 // TODO: Support in-order reductions based on the recurrence descriptor. 881 using RD = RecurrenceDescriptor; 882 RD::RecurrenceKind RecKind = Desc.getRecurrenceKind(); 883 TargetTransformInfo::ReductionFlags Flags; 884 Flags.NoNaN = NoNaN; 885 switch (RecKind) { 886 case RD::RK_FloatAdd: 887 return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags); 888 case RD::RK_FloatMult: 889 return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags); 890 case RD::RK_IntegerAdd: 891 return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags); 892 case RD::RK_IntegerMult: 893 return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags); 894 case RD::RK_IntegerAnd: 895 return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags); 896 case RD::RK_IntegerOr: 897 return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags); 898 case RD::RK_IntegerXor: 899 return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags); 900 case RD::RK_IntegerMinMax: { 901 RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind(); 902 Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax); 903 Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin); 904 return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags); 905 } 906 case RD::RK_FloatMinMax: { 907 Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax; 908 return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags); 909 } 910 default: 911 llvm_unreachable("Unhandled RecKind"); 912 } 913 } 914 915 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) { 916 auto *VecOp = dyn_cast<Instruction>(I); 917 if (!VecOp) 918 return; 919 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0]) 920 : dyn_cast<Instruction>(OpValue); 921 if (!Intersection) 922 return; 923 const unsigned Opcode = Intersection->getOpcode(); 924 VecOp->copyIRFlags(Intersection); 925 for (auto *V : VL) { 926 auto *Instr = dyn_cast<Instruction>(V); 927 if (!Instr) 928 continue; 929 if (OpValue == nullptr || Opcode == Instr->getOpcode()) 930 VecOp->andIRFlags(V); 931 } 932 } 933 934 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L, 935 ScalarEvolution &SE) { 936 const SCEV *Zero = SE.getZero(S->getType()); 937 return SE.isAvailableAtLoopEntry(S, L) && 938 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero); 939 } 940 941 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, 942 ScalarEvolution &SE) { 943 const SCEV *Zero = SE.getZero(S->getType()); 944 return SE.isAvailableAtLoopEntry(S, L) && 945 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero); 946 } 947 948 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 949 bool Signed) { 950 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 951 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) : 952 APInt::getMinValue(BitWidth); 953 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 954 return SE.isAvailableAtLoopEntry(S, L) && 955 SE.isLoopEntryGuardedByCond(L, Predicate, S, 956 SE.getConstant(Min)); 957 } 958 959 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, 960 bool Signed) { 961 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth(); 962 APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) : 963 APInt::getMaxValue(BitWidth); 964 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 965 return SE.isAvailableAtLoopEntry(S, L) && 966 SE.isLoopEntryGuardedByCond(L, Predicate, S, 967 SE.getConstant(Max)); 968 } 969