| 1 | //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===// |
| 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 implements some loop unrolling utilities. It does not define any |
| 10 | // actual pass or policy, but provides a single function to perform loop |
| 11 | // unrolling. |
| 12 | // |
| 13 | // The process of unrolling can produce extraneous basic blocks linked with |
| 14 | // unconditional branches. This will be corrected in the future. |
| 15 | // |
| 16 | //===----------------------------------------------------------------------===// |
| 17 | |
| 18 | #include "llvm/ADT/ArrayRef.h" |
| 19 | #include "llvm/ADT/DenseMap.h" |
| 20 | #include "llvm/ADT/MapVector.h" |
| 21 | #include "llvm/ADT/STLExtras.h" |
| 22 | #include "llvm/ADT/ScopedHashTable.h" |
| 23 | #include "llvm/ADT/SetVector.h" |
| 24 | #include "llvm/ADT/SmallVector.h" |
| 25 | #include "llvm/ADT/Statistic.h" |
| 26 | #include "llvm/ADT/StringRef.h" |
| 27 | #include "llvm/ADT/Twine.h" |
| 28 | #include "llvm/Analysis/AliasAnalysis.h" |
| 29 | #include "llvm/Analysis/AssumptionCache.h" |
| 30 | #include "llvm/Analysis/DomTreeUpdater.h" |
| 31 | #include "llvm/Analysis/InstructionSimplify.h" |
| 32 | #include "llvm/Analysis/LoopInfo.h" |
| 33 | #include "llvm/Analysis/LoopIterator.h" |
| 34 | #include "llvm/Analysis/MemorySSA.h" |
| 35 | #include "llvm/Analysis/OptimizationRemarkEmitter.h" |
| 36 | #include "llvm/Analysis/ScalarEvolution.h" |
| 37 | #include "llvm/IR/BasicBlock.h" |
| 38 | #include "llvm/IR/CFG.h" |
| 39 | #include "llvm/IR/Constants.h" |
| 40 | #include "llvm/IR/DebugInfoMetadata.h" |
| 41 | #include "llvm/IR/DebugLoc.h" |
| 42 | #include "llvm/IR/DiagnosticInfo.h" |
| 43 | #include "llvm/IR/Dominators.h" |
| 44 | #include "llvm/IR/Function.h" |
| 45 | #include "llvm/IR/IRBuilder.h" |
| 46 | #include "llvm/IR/Instruction.h" |
| 47 | #include "llvm/IR/Instructions.h" |
| 48 | #include "llvm/IR/IntrinsicInst.h" |
| 49 | #include "llvm/IR/Metadata.h" |
| 50 | #include "llvm/IR/PatternMatch.h" |
| 51 | #include "llvm/IR/Use.h" |
| 52 | #include "llvm/IR/User.h" |
| 53 | #include "llvm/IR/ValueHandle.h" |
| 54 | #include "llvm/IR/ValueMap.h" |
| 55 | #include "llvm/Support/Casting.h" |
| 56 | #include "llvm/Support/CommandLine.h" |
| 57 | #include "llvm/Support/Debug.h" |
| 58 | #include "llvm/Support/GenericDomTree.h" |
| 59 | #include "llvm/Support/raw_ostream.h" |
| 60 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 61 | #include "llvm/Transforms/Utils/Cloning.h" |
| 62 | #include "llvm/Transforms/Utils/Local.h" |
| 63 | #include "llvm/Transforms/Utils/LoopSimplify.h" |
| 64 | #include "llvm/Transforms/Utils/LoopUtils.h" |
| 65 | #include "llvm/Transforms/Utils/SimplifyIndVar.h" |
| 66 | #include "llvm/Transforms/Utils/UnrollLoop.h" |
| 67 | #include "llvm/Transforms/Utils/ValueMapper.h" |
| 68 | #include <assert.h> |
| 69 | #include <cmath> |
| 70 | #include <numeric> |
| 71 | #include <vector> |
| 72 | |
| 73 | namespace llvm { |
| 74 | class DataLayout; |
| 75 | class Value; |
| 76 | } // namespace llvm |
| 77 | |
| 78 | using namespace llvm; |
| 79 | |
| 80 | #define DEBUG_TYPE "loop-unroll" |
| 81 | |
| 82 | // TODO: Should these be here or in LoopUnroll? |
| 83 | STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled" ); |
| 84 | STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)" ); |
| 85 | STATISTIC(NumUnrolledNotLatch, "Number of loops unrolled without a conditional " |
| 86 | "latch (completely or otherwise)" ); |
| 87 | |
| 88 | static cl::opt<bool> |
| 89 | UnrollRuntimeEpilog("unroll-runtime-epilog" , cl::init(Val: false), cl::Hidden, |
| 90 | cl::desc("Allow runtime unrolled loops to be unrolled " |
| 91 | "with epilog instead of prolog." )); |
| 92 | |
| 93 | static cl::opt<bool> UnrollUniformWeights( |
| 94 | "unroll-uniform-weights" , cl::init(Val: false), cl::Hidden, |
| 95 | cl::desc("If new branch weights must be found, work harder to keep them " |
| 96 | "uniform." )); |
| 97 | |
| 98 | static cl::opt<bool> |
| 99 | UnrollVerifyDomtree("unroll-verify-domtree" , cl::Hidden, |
| 100 | cl::desc("Verify domtree after unrolling" ), |
| 101 | #ifdef EXPENSIVE_CHECKS |
| 102 | cl::init(true) |
| 103 | #else |
| 104 | cl::init(Val: false) |
| 105 | #endif |
| 106 | ); |
| 107 | |
| 108 | static cl::opt<bool> |
| 109 | UnrollVerifyLoopInfo("unroll-verify-loopinfo" , cl::Hidden, |
| 110 | cl::desc("Verify loopinfo after unrolling" ), |
| 111 | #ifdef EXPENSIVE_CHECKS |
| 112 | cl::init(true) |
| 113 | #else |
| 114 | cl::init(Val: false) |
| 115 | #endif |
| 116 | ); |
| 117 | |
| 118 | static cl::opt<bool> UnrollAddParallelReductions( |
| 119 | "unroll-add-parallel-reductions" , cl::init(Val: false), cl::Hidden, |
| 120 | cl::desc("Allow unrolling to add parallel reduction phis." )); |
| 121 | |
| 122 | /// Check if unrolling created a situation where we need to insert phi nodes to |
| 123 | /// preserve LCSSA form. |
| 124 | /// \param Blocks is a vector of basic blocks representing unrolled loop. |
| 125 | /// \param L is the outer loop. |
| 126 | /// It's possible that some of the blocks are in L, and some are not. In this |
| 127 | /// case, if there is a use is outside L, and definition is inside L, we need to |
| 128 | /// insert a phi-node, otherwise LCSSA will be broken. |
| 129 | /// The function is just a helper function for llvm::UnrollLoop that returns |
| 130 | /// true if this situation occurs, indicating that LCSSA needs to be fixed. |
| 131 | static bool needToInsertPhisForLCSSA(Loop *L, |
| 132 | const std::vector<BasicBlock *> &Blocks, |
| 133 | LoopInfo *LI) { |
| 134 | for (BasicBlock *BB : Blocks) { |
| 135 | if (LI->getLoopFor(BB) == L) |
| 136 | continue; |
| 137 | for (Instruction &I : *BB) { |
| 138 | for (Use &U : I.operands()) { |
| 139 | if (const auto *Def = dyn_cast<Instruction>(Val&: U)) { |
| 140 | Loop *DefLoop = LI->getLoopFor(BB: Def->getParent()); |
| 141 | if (!DefLoop) |
| 142 | continue; |
| 143 | if (DefLoop->contains(L)) |
| 144 | return true; |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | return false; |
| 150 | } |
| 151 | |
| 152 | /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary |
| 153 | /// and adds a mapping from the original loop to the new loop to NewLoops. |
| 154 | /// Returns nullptr if no new loop was created and a pointer to the |
| 155 | /// original loop OriginalBB was part of otherwise. |
| 156 | const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB, |
| 157 | BasicBlock *ClonedBB, LoopInfo *LI, |
| 158 | NewLoopsMap &NewLoops) { |
| 159 | // Figure out which loop New is in. |
| 160 | const Loop *OldLoop = LI->getLoopFor(BB: OriginalBB); |
| 161 | assert(OldLoop && "Should (at least) be in the loop being unrolled!" ); |
| 162 | |
| 163 | Loop *&NewLoop = NewLoops[OldLoop]; |
| 164 | if (!NewLoop) { |
| 165 | // Found a new sub-loop. |
| 166 | assert(OriginalBB == OldLoop->getHeader() && |
| 167 | "Header should be first in RPO" ); |
| 168 | |
| 169 | NewLoop = LI->AllocateLoop(); |
| 170 | Loop *NewLoopParent = NewLoops.lookup(Val: OldLoop->getParentLoop()); |
| 171 | |
| 172 | if (NewLoopParent) |
| 173 | NewLoopParent->addChildLoop(NewChild: NewLoop); |
| 174 | else |
| 175 | LI->addTopLevelLoop(New: NewLoop); |
| 176 | |
| 177 | NewLoop->addBasicBlockToLoop(NewBB: ClonedBB, LI&: *LI); |
| 178 | return OldLoop; |
| 179 | } else { |
| 180 | NewLoop->addBasicBlockToLoop(NewBB: ClonedBB, LI&: *LI); |
| 181 | return nullptr; |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | /// The function chooses which type of unroll (epilog or prolog) is more |
| 186 | /// profitabale. |
| 187 | /// Epilog unroll is more profitable when there is PHI that starts from |
| 188 | /// constant. In this case epilog will leave PHI start from constant, |
| 189 | /// but prolog will convert it to non-constant. |
| 190 | /// |
| 191 | /// loop: |
| 192 | /// PN = PHI [I, Latch], [CI, PreHeader] |
| 193 | /// I = foo(PN) |
| 194 | /// ... |
| 195 | /// |
| 196 | /// Epilog unroll case. |
| 197 | /// loop: |
| 198 | /// PN = PHI [I2, Latch], [CI, PreHeader] |
| 199 | /// I1 = foo(PN) |
| 200 | /// I2 = foo(I1) |
| 201 | /// ... |
| 202 | /// Prolog unroll case. |
| 203 | /// NewPN = PHI [PrologI, Prolog], [CI, PreHeader] |
| 204 | /// loop: |
| 205 | /// PN = PHI [I2, Latch], [NewPN, PreHeader] |
| 206 | /// I1 = foo(PN) |
| 207 | /// I2 = foo(I1) |
| 208 | /// ... |
| 209 | /// |
| 210 | static bool isEpilogProfitable(Loop *L) { |
| 211 | BasicBlock * = L->getLoopPreheader(); |
| 212 | BasicBlock * = L->getHeader(); |
| 213 | assert(PreHeader && Header); |
| 214 | for (const PHINode &PN : Header->phis()) { |
| 215 | if (isa<ConstantInt>(Val: PN.getIncomingValueForBlock(BB: PreHeader))) |
| 216 | return true; |
| 217 | } |
| 218 | return false; |
| 219 | } |
| 220 | |
| 221 | struct LoadValue { |
| 222 | Instruction *DefI = nullptr; |
| 223 | unsigned Generation = 0; |
| 224 | LoadValue() = default; |
| 225 | LoadValue(Instruction *Inst, unsigned Generation) |
| 226 | : DefI(Inst), Generation(Generation) {} |
| 227 | }; |
| 228 | |
| 229 | class StackNode { |
| 230 | ScopedHashTable<const SCEV *, LoadValue>::ScopeTy LoadScope; |
| 231 | unsigned CurrentGeneration; |
| 232 | unsigned ChildGeneration; |
| 233 | DomTreeNode *Node; |
| 234 | DomTreeNode::const_iterator ChildIter; |
| 235 | DomTreeNode::const_iterator EndIter; |
| 236 | bool Processed = false; |
| 237 | |
| 238 | public: |
| 239 | StackNode(ScopedHashTable<const SCEV *, LoadValue> &AvailableLoads, |
| 240 | unsigned cg, DomTreeNode *N, DomTreeNode::const_iterator Child, |
| 241 | DomTreeNode::const_iterator End) |
| 242 | : LoadScope(AvailableLoads), CurrentGeneration(cg), ChildGeneration(cg), |
| 243 | Node(N), ChildIter(Child), EndIter(End) {} |
| 244 | // Accessors. |
| 245 | unsigned currentGeneration() const { return CurrentGeneration; } |
| 246 | unsigned childGeneration() const { return ChildGeneration; } |
| 247 | void childGeneration(unsigned generation) { ChildGeneration = generation; } |
| 248 | DomTreeNode *node() { return Node; } |
| 249 | DomTreeNode::const_iterator childIter() const { return ChildIter; } |
| 250 | |
| 251 | DomTreeNode *nextChild() { |
| 252 | DomTreeNode *Child = *ChildIter; |
| 253 | ++ChildIter; |
| 254 | return Child; |
| 255 | } |
| 256 | |
| 257 | DomTreeNode::const_iterator end() const { return EndIter; } |
| 258 | bool isProcessed() const { return Processed; } |
| 259 | void process() { Processed = true; } |
| 260 | }; |
| 261 | |
| 262 | Value *getMatchingValue(LoadValue LV, LoadInst *LI, unsigned CurrentGeneration, |
| 263 | BatchAAResults &BAA, |
| 264 | function_ref<MemorySSA *()> GetMSSA) { |
| 265 | if (!LV.DefI) |
| 266 | return nullptr; |
| 267 | if (LV.DefI->getType() != LI->getType()) |
| 268 | return nullptr; |
| 269 | if (LV.Generation != CurrentGeneration) { |
| 270 | MemorySSA *MSSA = GetMSSA(); |
| 271 | if (!MSSA) |
| 272 | return nullptr; |
| 273 | auto *EarlierMA = MSSA->getMemoryAccess(I: LV.DefI); |
| 274 | MemoryAccess *LaterDef = |
| 275 | MSSA->getWalker()->getClobberingMemoryAccess(I: LI, AA&: BAA); |
| 276 | if (!MSSA->dominates(A: LaterDef, B: EarlierMA)) |
| 277 | return nullptr; |
| 278 | } |
| 279 | return LV.DefI; |
| 280 | } |
| 281 | |
| 282 | void loadCSE(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, |
| 283 | BatchAAResults &BAA, function_ref<MemorySSA *()> GetMSSA) { |
| 284 | ScopedHashTable<const SCEV *, LoadValue> AvailableLoads; |
| 285 | SmallVector<std::unique_ptr<StackNode>> NodesToProcess; |
| 286 | DomTreeNode * = DT.getNode(BB: L->getHeader()); |
| 287 | NodesToProcess.emplace_back(Args: new StackNode(AvailableLoads, 0, HeaderD, |
| 288 | HeaderD->begin(), HeaderD->end())); |
| 289 | |
| 290 | unsigned CurrentGeneration = 0; |
| 291 | while (!NodesToProcess.empty()) { |
| 292 | StackNode *NodeToProcess = &*NodesToProcess.back(); |
| 293 | |
| 294 | CurrentGeneration = NodeToProcess->currentGeneration(); |
| 295 | |
| 296 | if (!NodeToProcess->isProcessed()) { |
| 297 | // Process the node. |
| 298 | |
| 299 | // If this block has a single predecessor, then the predecessor is the |
| 300 | // parent |
| 301 | // of the domtree node and all of the live out memory values are still |
| 302 | // current in this block. If this block has multiple predecessors, then |
| 303 | // they could have invalidated the live-out memory values of our parent |
| 304 | // value. For now, just be conservative and invalidate memory if this |
| 305 | // block has multiple predecessors. |
| 306 | if (!NodeToProcess->node()->getBlock()->getSinglePredecessor()) |
| 307 | ++CurrentGeneration; |
| 308 | for (auto &I : make_early_inc_range(Range&: *NodeToProcess->node()->getBlock())) { |
| 309 | |
| 310 | auto *Load = dyn_cast<LoadInst>(Val: &I); |
| 311 | if (!Load || !Load->isSimple()) { |
| 312 | if (I.mayWriteToMemory()) |
| 313 | CurrentGeneration++; |
| 314 | continue; |
| 315 | } |
| 316 | |
| 317 | const SCEV *PtrSCEV = SE.getSCEV(V: Load->getPointerOperand()); |
| 318 | LoadValue LV = AvailableLoads.lookup(Key: PtrSCEV); |
| 319 | if (Value *M = |
| 320 | getMatchingValue(LV, LI: Load, CurrentGeneration, BAA, GetMSSA)) { |
| 321 | if (LI.replacementPreservesLCSSAForm(From: Load, To: M)) { |
| 322 | Load->replaceAllUsesWith(V: M); |
| 323 | Load->eraseFromParent(); |
| 324 | } |
| 325 | } else { |
| 326 | AvailableLoads.insert(Key: PtrSCEV, Val: LoadValue(Load, CurrentGeneration)); |
| 327 | } |
| 328 | } |
| 329 | NodeToProcess->childGeneration(generation: CurrentGeneration); |
| 330 | NodeToProcess->process(); |
| 331 | } else if (NodeToProcess->childIter() != NodeToProcess->end()) { |
| 332 | // Push the next child onto the stack. |
| 333 | DomTreeNode *Child = NodeToProcess->nextChild(); |
| 334 | if (!L->contains(BB: Child->getBlock())) |
| 335 | continue; |
| 336 | NodesToProcess.emplace_back( |
| 337 | Args: new StackNode(AvailableLoads, NodeToProcess->childGeneration(), Child, |
| 338 | Child->begin(), Child->end())); |
| 339 | } else { |
| 340 | // It has been processed, and there are no more children to process, |
| 341 | // so delete it and pop it off the stack. |
| 342 | NodesToProcess.pop_back(); |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | /// Perform some cleanup and simplifications on loops after unrolling. It is |
| 348 | /// useful to simplify the IV's in the new loop, as well as do a quick |
| 349 | /// simplify/dce pass of the instructions. |
| 350 | void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, |
| 351 | ScalarEvolution *SE, DominatorTree *DT, |
| 352 | AssumptionCache *AC, |
| 353 | const TargetTransformInfo *TTI, |
| 354 | ArrayRef<BasicBlock *> Blocks, |
| 355 | AAResults *AA) { |
| 356 | using namespace llvm::PatternMatch; |
| 357 | |
| 358 | // Simplify any new induction variables in the partially unrolled loop. |
| 359 | if (SE && SimplifyIVs) { |
| 360 | SmallVector<WeakTrackingVH, 16> DeadInsts; |
| 361 | simplifyLoopIVs(L, SE, DT, LI, TTI, Dead&: DeadInsts); |
| 362 | |
| 363 | // Aggressively clean up dead instructions that simplifyLoopIVs already |
| 364 | // identified. Any remaining should be cleaned up below. |
| 365 | while (!DeadInsts.empty()) { |
| 366 | Value *V = DeadInsts.pop_back_val(); |
| 367 | if (Instruction *Inst = dyn_cast_or_null<Instruction>(Val: V)) |
| 368 | RecursivelyDeleteTriviallyDeadInstructions(V: Inst); |
| 369 | } |
| 370 | |
| 371 | if (AA) { |
| 372 | std::unique_ptr<MemorySSA> MSSA = nullptr; |
| 373 | BatchAAResults BAA(*AA); |
| 374 | loadCSE(L, DT&: *DT, SE&: *SE, LI&: *LI, BAA, GetMSSA: [L, AA, DT, &MSSA]() -> MemorySSA * { |
| 375 | if (!MSSA) |
| 376 | MSSA.reset(p: new MemorySSA(*L, AA, DT)); |
| 377 | return &*MSSA; |
| 378 | }); |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | // At this point, the code is well formed. Perform constprop, instsimplify, |
| 383 | // and dce. |
| 384 | SmallVector<WeakTrackingVH, 16> DeadInsts; |
| 385 | for (BasicBlock *BB : Blocks) { |
| 386 | // Remove repeated debug instructions after loop unrolling. |
| 387 | if (BB->getParent()->getSubprogram()) |
| 388 | RemoveRedundantDbgInstrs(BB); |
| 389 | |
| 390 | for (Instruction &Inst : llvm::make_early_inc_range(Range&: *BB)) { |
| 391 | if (Value *V = simplifyInstruction( |
| 392 | I: &Inst, Q: {BB->getDataLayout(), nullptr, DT, AC})) |
| 393 | if (LI->replacementPreservesLCSSAForm(From: &Inst, To: V)) |
| 394 | Inst.replaceAllUsesWith(V); |
| 395 | if (isInstructionTriviallyDead(I: &Inst)) |
| 396 | DeadInsts.emplace_back(Args: &Inst); |
| 397 | |
| 398 | // Fold ((add X, C1), C2) to (add X, C1+C2). This is very common in |
| 399 | // unrolled loops, and handling this early allows following code to |
| 400 | // identify the IV as a "simple recurrence" without first folding away |
| 401 | // a long chain of adds. |
| 402 | { |
| 403 | Value *X; |
| 404 | const APInt *C1, *C2; |
| 405 | if (match(V: &Inst, P: m_Add(L: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: C1)), R: m_APInt(Res&: C2)))) { |
| 406 | auto *InnerI = dyn_cast<Instruction>(Val: Inst.getOperand(i: 0)); |
| 407 | auto *InnerOBO = cast<OverflowingBinaryOperator>(Val: Inst.getOperand(i: 0)); |
| 408 | bool SignedOverflow; |
| 409 | APInt NewC = C1->sadd_ov(RHS: *C2, Overflow&: SignedOverflow); |
| 410 | Inst.setOperand(i: 0, Val: X); |
| 411 | Inst.setOperand(i: 1, Val: ConstantInt::get(Ty: Inst.getType(), V: NewC)); |
| 412 | Inst.setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap() && |
| 413 | InnerOBO->hasNoUnsignedWrap()); |
| 414 | Inst.setHasNoSignedWrap(Inst.hasNoSignedWrap() && |
| 415 | InnerOBO->hasNoSignedWrap() && |
| 416 | !SignedOverflow); |
| 417 | if (InnerI && isInstructionTriviallyDead(I: InnerI)) |
| 418 | DeadInsts.emplace_back(Args&: InnerI); |
| 419 | } |
| 420 | } |
| 421 | } |
| 422 | // We can't do recursive deletion until we're done iterating, as we might |
| 423 | // have a phi which (potentially indirectly) uses instructions later in |
| 424 | // the block we're iterating through. |
| 425 | RecursivelyDeleteTriviallyDeadInstructions(DeadInsts); |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | // Loops containing convergent instructions that are uncontrolled or controlled |
| 430 | // from outside the loop must have a count that divides their TripMultiple. |
| 431 | LLVM_ATTRIBUTE_USED |
| 432 | static bool canHaveUnrollRemainder(const Loop *L) { |
| 433 | if (getLoopConvergenceHeart(TheLoop: L)) |
| 434 | return false; |
| 435 | |
| 436 | // Check for uncontrolled convergent operations. |
| 437 | for (auto &BB : L->blocks()) { |
| 438 | for (auto &I : *BB) { |
| 439 | if (isa<ConvergenceControlInst>(Val: I)) |
| 440 | return true; |
| 441 | if (auto *CB = dyn_cast<CallBase>(Val: &I)) |
| 442 | if (CB->isConvergent()) |
| 443 | return CB->getConvergenceControlToken(); |
| 444 | } |
| 445 | } |
| 446 | return true; |
| 447 | } |
| 448 | |
| 449 | // If LoopUnroll has proven OriginalLoopProb is incorrect for some iterations |
| 450 | // of the original loop, adjust latch probabilities in the unrolled loop to |
| 451 | // maintain the original total frequency of the original loop body. |
| 452 | // |
| 453 | // OriginalLoopProb is practical but imprecise |
| 454 | // ------------------------------------------- |
| 455 | // |
| 456 | // The latch branch weights that LLVM originally adds to a loop encode one latch |
| 457 | // probability, OriginalLoopProb, applied uniformly across the loop's infinite |
| 458 | // set of theoretically possible iterations. While this uniform latch |
| 459 | // probability serves as a practical statistic summarizing the trip counts |
| 460 | // observed during profiling, it is imprecise. Specifically, unless it is zero, |
| 461 | // it is impossible for it to be the actual probability observed at every |
| 462 | // individual iteration. To see why, consider that the only way to actually |
| 463 | // observe at run time that the latch probability remains non-zero is to profile |
| 464 | // at least one loop execution that has an infinite number of iterations. I do |
| 465 | // not know how to profile an infinite number of loop iterations, and most loops |
| 466 | // I work with are always finite. |
| 467 | // |
| 468 | // LoopUnroll proves OriginalLoopProb is incorrect |
| 469 | // ------------------------------------------------ |
| 470 | // |
| 471 | // LoopUnroll reorganizes the original loop so that loop iterations are no |
| 472 | // longer all implemented by the same code, and then it analyzes some of those |
| 473 | // loop iteration implementations independently of others. In particular, it |
| 474 | // converts some of their conditional latches to unconditional. That is, by |
| 475 | // examining code structure without any profile data, LoopUnroll proves that the |
| 476 | // actual latch probability at the end of such an iteration is either 1 or 0. |
| 477 | // When an individual iteration's actual latch probability is 1 or 0, that means |
| 478 | // it always behaves the same, so it is impossible to observe it as having any |
| 479 | // other probability. The original uniform latch probability is rarely 1 or 0 |
| 480 | // because, when applied to all possible iterations, that would yield an |
| 481 | // estimated trip count of infinity or 1, respectively. |
| 482 | // |
| 483 | // Thus, the new probabilities of 1 or 0 are proven corrections to |
| 484 | // OriginalLoopProb for individual iterations in the original loop. However, |
| 485 | // LoopUnroll often is able to perform these corrections for only some |
| 486 | // iterations, leaving other iterations with OriginalLoopProb, and thus |
| 487 | // corrupting the aggregate effect on the total frequency of the original loop |
| 488 | // body. |
| 489 | // |
| 490 | // Adjusting latch probabilities |
| 491 | // ----------------------------- |
| 492 | // |
| 493 | // This function ensures that the total frequency of the original loop body, |
| 494 | // summed across all its occurrences in the unrolled loop after the |
| 495 | // aforementioned latch conversions, is the same as in the original loop. To do |
| 496 | // so, it adjusts probabilities on the remaining conditional latches. However, |
| 497 | // it cannot derive the new probabilities directly from the original uniform |
| 498 | // latch probability because the latter has been proven incorrect for some |
| 499 | // original loop iterations. |
| 500 | // |
| 501 | // There are often many sets of latch probabilities that can produce the |
| 502 | // original total loop body frequency. If there are many remaining conditional |
| 503 | // latches and !UnrollUniformWeights, this function just quickly hacks a few of |
| 504 | // their probabilities to restore the original total loop body frequency. |
| 505 | // Otherwise, it tries harder to determine less arbitrary probabilities. |
| 506 | static void (Loop *L, UnrollLoopOptions ULO, |
| 507 | OptimizationRemarkEmitter *ORE, |
| 508 | BranchProbability OriginalLoopProb, |
| 509 | bool CompletelyUnroll, |
| 510 | std::vector<unsigned> &IterCounts, |
| 511 | const std::vector<BasicBlock *> &CondLatches, |
| 512 | std::vector<BasicBlock *> &CondLatchNexts) { |
| 513 | // Runtime unrolling is handled later in LoopUnroll not here. |
| 514 | // |
| 515 | // There are two scenarios in which LoopUnroll sets ProbUpdateRequired to true |
| 516 | // because it needs to update probabilities that were originally |
| 517 | // OriginalLoopProb, but only in one scenario has LoopUnroll proven |
| 518 | // OriginalLoopProb incorrect for iterations within the original loop: |
| 519 | // - If ULO.Runtime, LoopUnroll adds new guards that enforce new reaching |
| 520 | // conditions for new loop iteration implementations (e.g., one unrolled |
| 521 | // loop iteration executes only if at least ULO.Count original loop |
| 522 | // iterations remain). Those reaching conditions dictate how conditional |
| 523 | // latches can be converted to unconditional (e.g., within an unrolled loop |
| 524 | // iteration, there is no need to recheck the number of remaining original |
| 525 | // loop iterations). None of this reorganization alters the set of possible |
| 526 | // original loop iteration counts or proves OriginalLoopProb incorrect for |
| 527 | // any of the original loop iterations. Thus, LoopUnroll derives |
| 528 | // probabilities for the new guards and latches directly from |
| 529 | // OriginalLoopProb based on the probabilities that their reaching |
| 530 | // conditions would occur in the original loop. Doing so maintains the |
| 531 | // total frequency of the original loop body. |
| 532 | // - If !ULO.Runtime, LoopUnroll initially adds new loop iteration |
| 533 | // implementations, which have the same latch probabilities as in the |
| 534 | // original loop because there are no new guards that change their reaching |
| 535 | // conditions. Sometimes, LoopUnroll is then done, and so does not set |
| 536 | // ProbUpdateRequired to true. Other times, LoopUnroll then proves that |
| 537 | // some latches are unconditional, directly contradicting OriginalLoopProb |
| 538 | // for the corresponding original loop iterations. That reduces the set of |
| 539 | // possible original loop iteration counts, possibly producing a finite set |
| 540 | // if it manages to eliminate the backedge. LoopUnroll has to choose a new |
| 541 | // set of latch probabilities that produce the same total loop body |
| 542 | // frequency. |
| 543 | // |
| 544 | // This function addresses the second scenario only. |
| 545 | if (ULO.Runtime) |
| 546 | return; |
| 547 | |
| 548 | // If CondLatches.empty(), there are no latch branches with probabilities we |
| 549 | // can adjust. That should mean that the actual trip count is always exactly |
| 550 | // the number of remaining unrolled iterations, and so OriginalLoopProb should |
| 551 | // have yielded that trip count as the original loop body frequency. Of |
| 552 | // course, OriginalLoopProb could be based on inaccurate profile data, but |
| 553 | // there is nothing we can do about that here. |
| 554 | if (CondLatches.empty()) |
| 555 | return; |
| 556 | |
| 557 | // If the original latch probability is 1, the original frequency is infinity. |
| 558 | // Leaving all remaining probabilities set to 1 might or might not get us |
| 559 | // there (e.g., a completely unrolled loop cannot be infinite), but it is the |
| 560 | // closest we can come. |
| 561 | assert(!OriginalLoopProb.isUnknown() && |
| 562 | "Expected to have loop probability to fix" ); |
| 563 | if (OriginalLoopProb.isOne()) |
| 564 | return; |
| 565 | |
| 566 | // FreqDesired is the frequency implied by the original loop probability. |
| 567 | double FreqDesired = 1 / (1 - OriginalLoopProb.toDouble()); |
| 568 | |
| 569 | // Get the probability at CondLatches[I]. |
| 570 | auto GetProb = [&](unsigned I) { |
| 571 | CondBrInst *B = cast<CondBrInst>(Val: CondLatches[I]->getTerminator()); |
| 572 | bool FirstTargetIsNext = B->getSuccessor(i: 0) == CondLatchNexts[I]; |
| 573 | return getBranchProbability(B, ForFirstTarget: FirstTargetIsNext).toDouble(); |
| 574 | }; |
| 575 | |
| 576 | // Set the probability at CondLatches[I] to Prob. |
| 577 | auto SetProb = [&](unsigned I, double Prob) { |
| 578 | CondBrInst *B = cast<CondBrInst>(Val: CondLatches[I]->getTerminator()); |
| 579 | bool FirstTargetIsNext = B->getSuccessor(i: 0) == CondLatchNexts[I]; |
| 580 | setBranchProbability(B, P: BranchProbability::getBranchProbability(Prob), |
| 581 | ForFirstTarget: FirstTargetIsNext); |
| 582 | }; |
| 583 | |
| 584 | // Set all probabilities in CondLatches to Prob. |
| 585 | auto SetAllProbs = [&](double Prob) { |
| 586 | for (unsigned I = 0, E = CondLatches.size(); I < E; ++I) |
| 587 | SetProb(I, Prob); |
| 588 | }; |
| 589 | |
| 590 | // If UnrollUniformWeights or n <= 2, we choose the simplest probability model |
| 591 | // we can think of: every remaining conditional branch instruction has the |
| 592 | // same probability, Prob, of continuing to the next iteration. This model |
| 593 | // has several helpful properties: |
| 594 | // - There is only one search parameter, Prob. |
| 595 | // - We have no reason to think one latch branch's probability should be |
| 596 | // higher or lower than another, and so this model makes them all the same. |
| 597 | // In the worst cases, we thus avoid setting just some probabilities to 0 or |
| 598 | // 1, which can unrealistically make some code appear unreachable. There |
| 599 | // are cases where they *all* must become 0 or 1 to achieve the total |
| 600 | // frequency of original loop body, and our model does permit that. |
| 601 | // - The frequency, FreqOne, of the original loop body in a single iteration |
| 602 | // of the unrolled loop is computed by a simple polynomial, where p=Prob, |
| 603 | // n=CondLatches.size(), and c_i=IterCounts[i]: |
| 604 | // |
| 605 | // FreqOne = Sum(i=0..n)(c_i * p^i) |
| 606 | // |
| 607 | // - If the backedge has been eliminated: |
| 608 | // - FreqOne is the total frequency of the original loop body in the |
| 609 | // unrolled loop. |
| 610 | // - If Prob == 1, the total frequency of the original loop body is exactly |
| 611 | // the number of remaining loop iterations, as expected because every |
| 612 | // remaining loop iteration always then executes. |
| 613 | // - If the backedge remains: |
| 614 | // - Sum(i=0..inf)(FreqOne * p^(n*i)) = FreqOne / (1 - p^n) is the total |
| 615 | // frequency of the original loop body in the unrolled loop, regardless of |
| 616 | // whether the backedge is conditional or unconditional. |
| 617 | // - As Prob approaches 1, the total frequency of the original loop body |
| 618 | // approaches infinity, as expected because the loop approaches never |
| 619 | // exiting. |
| 620 | // - For n <= 2, we can use simple formulas to solve the above polynomial |
| 621 | // equations exactly for p without performing a search. |
| 622 | // - For n > 2, evaluating each point in the search space, using ComputeFreq |
| 623 | // below, requires about as few instructions as we could hope for. That is, |
| 624 | // the probability is constant across the conditional branches, so the only |
| 625 | // computation is across conditional branches and any backedge, as required |
| 626 | // for any model for Prob. |
| 627 | // - Prob == 1 produces the maximum possible total frequency for the original |
| 628 | // loop body, as described above. Prob == 0 produces the minimum, 0. |
| 629 | // Increasing or decreasing Prob monotonically increases or decreases the |
| 630 | // frequency, respectively. Thus, for every possible frequency, there |
| 631 | // exists some Prob that can produce it, and we can easily use bisection to |
| 632 | // search the problem space. |
| 633 | |
| 634 | // When iterating for a solution, we stop early if we find probabilities |
| 635 | // that produce a Freq whose relative difference from FreqDesired is small |
| 636 | // (FreqPrec). Otherwise, we expect to compute a solution at least that |
| 637 | // accurate (but surely far more accurate). |
| 638 | const double FreqPrec = 1e-6; |
| 639 | |
| 640 | // Compute the new frequency produced by using Prob throughout CondLatches. |
| 641 | auto ComputeFreq = [&](double Prob) { |
| 642 | double ProbReaching = 1; // p^0 |
| 643 | double FreqOne = IterCounts[0]; // c_0*p^0 |
| 644 | for (unsigned I = 0, E = CondLatches.size(); I < E; ++I) { |
| 645 | ProbReaching *= Prob; // p^(I+1) |
| 646 | FreqOne += IterCounts[I + 1] * ProbReaching; // c_(I+1)*p^(I+1) |
| 647 | } |
| 648 | double ProbReachingBackedge = CompletelyUnroll ? 0 : ProbReaching; |
| 649 | assert(FreqOne > 0 && "Expected at least one iteration before first latch" ); |
| 650 | if (ProbReachingBackedge == 1) |
| 651 | return std::numeric_limits<double>::infinity(); |
| 652 | return FreqOne / (1 - ProbReachingBackedge); |
| 653 | }; |
| 654 | |
| 655 | // Compute the probability that, used at CondLaches[0] where |
| 656 | // CondLatches.size() == 1, gets as close as possible to FreqDesired. |
| 657 | auto ComputeProbForLinear = [&]() { |
| 658 | // The polynomial is linear (0 = A*p + B), so just solve it. |
| 659 | double A = IterCounts[1] + (CompletelyUnroll ? 0 : FreqDesired); |
| 660 | double B = IterCounts[0] - FreqDesired; |
| 661 | assert(A > 0 && "Expected iterations after last conditional latch" ); |
| 662 | double Prob = -B / A; |
| 663 | // If it computes an invalid Prob, FreqDesired is impossibly low or high. |
| 664 | // Otherwise, Prob should produce nearly FreqDesired. |
| 665 | assert((Prob < 0 || Prob > 1 || |
| 666 | fabs(ComputeFreq(Prob) - FreqDesired) / FreqDesired < FreqPrec) && |
| 667 | "Expected accurate frequency when linear case is possible" ); |
| 668 | Prob = std::max(a: Prob, b: 0.); |
| 669 | Prob = std::min(a: Prob, b: 1.); |
| 670 | return Prob; |
| 671 | }; |
| 672 | |
| 673 | // Compute the probability that, used throughout CondLatches where |
| 674 | // CondLatches.size() == 2, gets as close as possible to FreqDesired. |
| 675 | auto ComputeProbForQuadratic = [&]() { |
| 676 | // The polynomial is quadratic (0 = A*p^2 + B*p + C), so just solve it. |
| 677 | double A = IterCounts[2] + (CompletelyUnroll ? 0 : FreqDesired); |
| 678 | double B = IterCounts[1]; |
| 679 | double C = IterCounts[0] - FreqDesired; |
| 680 | assert(A > 0 && "Expected iterations after last conditional latch" ); |
| 681 | double Prob = (-B + sqrt(x: B * B - 4 * A * C)) / (2 * A); |
| 682 | // If it computes an invalid Prob, FreqDesired is impossibly low or high. |
| 683 | // Otherwise, Prob should produce nearly FreqDesired. |
| 684 | assert((Prob < 0 || Prob > 1 || |
| 685 | fabs(ComputeFreq(Prob) - FreqDesired) / FreqDesired < FreqPrec) && |
| 686 | "Expected accurate frequency when quadratic case is possible" ); |
| 687 | Prob = std::max(a: Prob, b: 0.); |
| 688 | Prob = std::min(a: Prob, b: 1.); |
| 689 | return Prob; |
| 690 | }; |
| 691 | |
| 692 | // Adjust the probability at CondLatches[ComputeIdx] to get as close as |
| 693 | // possible to FreqDesired without replacing probabilities elsewhere in |
| 694 | // CondLatches. Return the new total frequency. |
| 695 | // |
| 696 | // Given a CondLatches index I, then for a single unrolled loop iteration: |
| 697 | // - ProbBefore or ProbAfter is the probability that control flow can pass |
| 698 | // through every CondLatches[J] for J < I or J > I, respectively. |
| 699 | // - FreqBefore or FreqAfter is the total frequency accumulated before or |
| 700 | // after CondLatches[I], respectively, while the probability at |
| 701 | // CondLatches[I] is treated as 1. |
| 702 | // |
| 703 | // If ComputeIdx == 0, then ComputeProb will set those values for I == 0 and |
| 704 | // ignore the current values. If ComputeIdx > 0, then it expects those values |
| 705 | // to already be set for I == ComputeIdx - 1, and it will set them for I == |
| 706 | // ComputeIdx. |
| 707 | auto AdjustProb = [&](unsigned ComputeIdx, double &ProbBefore, |
| 708 | double &ProbAfter, double &FreqBefore, |
| 709 | double &FreqAfter) { |
| 710 | assert(ComputeIdx < CondLatches.size() && |
| 711 | "Expected valid CondLatches index" ); |
| 712 | |
| 713 | // Compute or update ProbBefore, ProbAfter, FreqBefore, and FreqAfter. |
| 714 | auto ComputeAfter = [&]() { |
| 715 | ProbAfter = 1; |
| 716 | FreqAfter = IterCounts[ComputeIdx + 1]; |
| 717 | for (unsigned I = ComputeIdx + 1, E = CondLatches.size(); I < E; ++I) { |
| 718 | double Prob = GetProb(I); |
| 719 | ProbAfter *= Prob; |
| 720 | // After Prob == 0, ProbAfter and FreqAfter won't change, so save time. |
| 721 | if (Prob == 0) |
| 722 | break; |
| 723 | FreqAfter += IterCounts[I + 1] * ProbAfter; |
| 724 | } |
| 725 | }; |
| 726 | if (ComputeIdx == 0) { |
| 727 | ProbBefore = 1; |
| 728 | FreqBefore = IterCounts[0]; |
| 729 | ComputeAfter(); |
| 730 | } else { |
| 731 | // Rather than iterating all of CondLatches again, we fix up the |
| 732 | // previously computed values. |
| 733 | double ProbOld = GetProb(ComputeIdx); |
| 734 | if (ProbOld > 0) { |
| 735 | FreqAfter -= IterCounts[ComputeIdx] * ProbBefore; |
| 736 | ProbAfter /= ProbOld; |
| 737 | FreqAfter /= ProbOld; |
| 738 | } else { |
| 739 | // We cannot divide out the old zero probability. We short-circuited |
| 740 | // the iteration at that zero in the previous ComputeAfter call, so now |
| 741 | // we pick up where we left off. |
| 742 | ComputeAfter(); |
| 743 | } |
| 744 | ProbBefore *= GetProb(ComputeIdx - 1); |
| 745 | FreqBefore += IterCounts[ComputeIdx] * ProbBefore; |
| 746 | } |
| 747 | |
| 748 | // Compute the required probability, and limit it to a valid probability (0 |
| 749 | // <= p <= 1). See the FreqCompute formula below for how to derive the |
| 750 | // ProbCompute formula. |
| 751 | double ProbReachingBackedge = CompletelyUnroll ? 0 : ProbBefore * ProbAfter; |
| 752 | double ProbComputeNumerator = FreqDesired - FreqBefore; |
| 753 | double ProbComputeDenominator = |
| 754 | FreqAfter + FreqDesired * ProbReachingBackedge; |
| 755 | double ProbCompute = -1; // Init expected to be unused. |
| 756 | if (ProbComputeNumerator <= 0) { |
| 757 | // FreqBefore has already reached or surpassed FreqDesired, so add no more |
| 758 | // frequency. It is possible that ProbComputeDenominator == 0 here |
| 759 | // because some latch probability (maybe the original) was set to zero, so |
| 760 | // this check avoids setting ProbCompute=1 (in the else if below) and |
| 761 | // division by zero where the numerator <= 0 (in the else below). |
| 762 | ProbCompute = 0; |
| 763 | } else if (ProbComputeDenominator == 0) { |
| 764 | // Analytically, this case seems impossible. It would occur if either: |
| 765 | // - Both FreqAfter and FreqDesired are zero. But the latter would cause |
| 766 | // ProbComputeNumerator < 0, which we catch above, and FreqDesired |
| 767 | // should always be >= 1 anyway. |
| 768 | // - There are no iterations after CondLatches[ComputeIdx], not even via |
| 769 | // a backedge, so that both FreqAfter and ProbReachingBackedge are zero. |
| 770 | // But iterations should exist after even the last conditional latch. |
| 771 | // - Some latch probability (maybe the original) was set to zero so that |
| 772 | // both FreqAfter and ProbReachingBackedge are zero. But that should |
| 773 | // not have happened because, according to the above |
| 774 | // ProbComputeNumerator check, we have not yet reached FreqDesired |
| 775 | // (which, if the original latch probability is zero, is just 1 and thus |
| 776 | // always reached or surpassed). |
| 777 | // |
| 778 | // Numerically, perhaps this case is possible. We interpret it to mean we |
| 779 | // need more frequency (ProbComputeNumerator > 0) but have no way to get |
| 780 | // any (ProbComputeDenominator is analytically too small to distinguish it |
| 781 | // from 0 in floating point), suggesting infinite probability is needed, |
| 782 | // but 1 is the maximum valid probability and thus the best we can do. |
| 783 | // |
| 784 | // TODO: Cover this case in the test suite if you can. |
| 785 | ProbCompute = 1; |
| 786 | } else { |
| 787 | ProbCompute = ProbComputeNumerator / ProbComputeDenominator; |
| 788 | ProbCompute = std::max(a: ProbCompute, b: 0.); |
| 789 | ProbCompute = std::min(a: ProbCompute, b: 1.); |
| 790 | } |
| 791 | SetProb(ComputeIdx, ProbCompute); |
| 792 | |
| 793 | // Compute the resulting total frequency. |
| 794 | double FreqCompute = -1; // Init expected to be unused. |
| 795 | if (ProbReachingBackedge * ProbCompute == 1) { |
| 796 | // Analytically, this case seems impossible. It requires that there is a |
| 797 | // backedge and that FreqDesired == infinity so that every conditional |
| 798 | // latch's probability had to be set to 1. But FreqDesired == infinity |
| 799 | // means OriginalLoopProb.isOne(), which we guarded against earlier. |
| 800 | // |
| 801 | // Numerically, perhaps this case is possible. We interpret it to mean |
| 802 | // that analytically the probability has to be so near 1 that, in floating |
| 803 | // point, the frequency is computed as infinite. |
| 804 | // |
| 805 | // TODO: Cover this case in the test suite if you can. |
| 806 | FreqCompute = std::numeric_limits<double>::infinity(); |
| 807 | if (ORE) { |
| 808 | ORE->emit(RemarkBuilder: [&]() { |
| 809 | return OptimizationRemark(DEBUG_TYPE, "InfiniteFrequency" , |
| 810 | L->getStartLoc(), L->getHeader()); |
| 811 | }); |
| 812 | } |
| 813 | } else { |
| 814 | assert(FreqBefore > 0 && |
| 815 | "Expected at least one iteration before first latch" ); |
| 816 | // In this equation, if we replace the left-hand side with FreqDesired and |
| 817 | // then solve for ProbCompute, we get the ProbCompute formula above. |
| 818 | FreqCompute = (FreqBefore + FreqAfter * ProbCompute) / |
| 819 | (1 - ProbReachingBackedge * ProbCompute); |
| 820 | } |
| 821 | assert(FreqCompute > 0 && "Expected valid frequency" ); |
| 822 | return FreqCompute; |
| 823 | }; |
| 824 | |
| 825 | // Determine and set branch weights. |
| 826 | // |
| 827 | // Prob < 0 and Prob > 1 cannot be represented as branch weights. We might |
| 828 | // compute such a Prob if FreqDesired is impossible (e.g., due to inaccurate |
| 829 | // profile data) for the maximum trip count we have determined when completely |
| 830 | // unrolling. In that case, so just go with whichever is closest. |
| 831 | if (CondLatches.size() == 1) { |
| 832 | SetAllProbs(ComputeProbForLinear()); |
| 833 | } else if (CondLatches.size() == 2) { |
| 834 | SetAllProbs(ComputeProbForQuadratic()); |
| 835 | } else if (!UnrollUniformWeights) { |
| 836 | // The polynomial is too complex for a simple formula, and the quick and |
| 837 | // dirty fix has been selected. Adjust probabilities starting from the |
| 838 | // first latch, which has the most influence on the total frequency, so |
| 839 | // starting there should minimize the number of latches that have to be |
| 840 | // visited. We do have to iterate because the first latch alone might not |
| 841 | // be enough. For example, we might need to set all probabilities to 1 if |
| 842 | // the frequency is the unroll factor. |
| 843 | double ProbBefore = -1, ProbAfter = -1; // Inits expected to be unused. |
| 844 | double FreqBefore = -1, FreqAfter = -1; // Inits expected to be unused. |
| 845 | for (unsigned I = 0; I != CondLatches.size(); ++I) { |
| 846 | double Freq = AdjustProb(I, ProbBefore, ProbAfter, FreqBefore, FreqAfter); |
| 847 | if (fabs(x: Freq - FreqDesired) / FreqDesired < FreqPrec) |
| 848 | break; |
| 849 | } |
| 850 | } else { |
| 851 | // The polynomial is too complex for a simple formula, and uniform branch |
| 852 | // weights have been selected, so bisect. |
| 853 | double ProbMin = -1, ProbMax = -1; // Inits expected to be unused. |
| 854 | double ProbPrev = -1; // Inits expected to be unused. |
| 855 | auto TryProb = [&](double Prob) { |
| 856 | ProbPrev = Prob; |
| 857 | double FreqDelta = ComputeFreq(Prob) - FreqDesired; |
| 858 | if (fabs(x: FreqDelta) / FreqDesired < FreqPrec) |
| 859 | return 0; |
| 860 | if (FreqDelta < 0) { |
| 861 | ProbMin = Prob; |
| 862 | return -1; |
| 863 | } |
| 864 | ProbMax = Prob; |
| 865 | return 1; |
| 866 | }; |
| 867 | // If Prob == 0 is too small and Prob == 1 is too large, bisect between |
| 868 | // them. Accuracy (relative difference) is controlled by FreqPrec above. |
| 869 | // However, to place a hard upper limit on the search time, we stop |
| 870 | // bisecting when Prob stops changing (ProbDelta) by much (ProbPrec). In |
| 871 | // this case, we compute an absolute difference not a relative difference, |
| 872 | // which could produce more search time for smaller probabilities. |
| 873 | if (TryProb(0.) < 0 && TryProb(1.) > 0) { |
| 874 | assert(ProbMin == 0 && ProbMax == 1 && |
| 875 | "expected probability bounds to be initialized" ); |
| 876 | const double ProbPrec = 1e-12; |
| 877 | double Prob, ProbDelta; |
| 878 | do { |
| 879 | Prob = (ProbMin + ProbMax) / 2; |
| 880 | ProbDelta = Prob - ProbPrev; |
| 881 | } while (TryProb(Prob) != 0 && fabs(x: ProbDelta) > ProbPrec); |
| 882 | } |
| 883 | SetAllProbs(ProbPrev); |
| 884 | } |
| 885 | |
| 886 | // FIXME: We have not considered non-latch loop exits: |
| 887 | // - Their original probabilities are not considered in our calculation of |
| 888 | // FreqDesired. |
| 889 | // - Their probabilities are not considered in our probability model used to |
| 890 | // determine new probabilities for remaining conditional branches. |
| 891 | // - If they are conditional and LoopUnroll converts them to unconditional, |
| 892 | // LoopUnroll has proven their original probabilities are incorrect for some |
| 893 | // original loop iterations, but that does not cause ProbUpdateRequired to |
| 894 | // be set to true. |
| 895 | // |
| 896 | // To adjust FreqDesired and our probability model correctly for a non-latch |
| 897 | // loop exit, we would need to compute the original probability that the exit |
| 898 | // is reached from the loop header (in contrast, we currently assume that |
| 899 | // probability is 1 in the case of a latch exit) and the probability that the |
| 900 | // exit is taken if it is conditional (use the branch's old or new weights for |
| 901 | // FreqDesired or the probability model, respectively). Does computing the |
| 902 | // reaching probability require a CFG traversal, or is there some existing |
| 903 | // library that can do it? Prior discussions suggest some such libraries are |
| 904 | // difficult to use within LoopUnroll: |
| 905 | // <https://github.com/llvm/llvm-project/pull/164799#issuecomment-3438681519>. |
| 906 | // For now, we just let our corrected probabilities be less accurate in that |
| 907 | // scenario. Alternatively, we could refuse to correct probabilities at all |
| 908 | // in that scenario, but that seems worse. |
| 909 | } |
| 910 | |
| 911 | /// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling |
| 912 | /// can only fail when the loop's latch block is not terminated by a conditional |
| 913 | /// branch instruction. However, if the trip count (and multiple) are not known, |
| 914 | /// loop unrolling will mostly produce more code that is no faster. |
| 915 | /// |
| 916 | /// If Runtime is true then UnrollLoop will try to insert a prologue or |
| 917 | /// epilogue that ensures the latch has a trip multiple of Count. UnrollLoop |
| 918 | /// will not runtime-unroll the loop if computing the run-time trip count will |
| 919 | /// be expensive and AllowExpensiveTripCount is false. |
| 920 | /// |
| 921 | /// The LoopInfo Analysis that is passed will be kept consistent. |
| 922 | /// |
| 923 | /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and |
| 924 | /// DominatorTree if they are non-null. |
| 925 | /// |
| 926 | /// If RemainderLoop is non-null, it will receive the remainder loop (if |
| 927 | /// required and not fully unrolled). |
| 928 | LoopUnrollResult |
| 929 | llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI, |
| 930 | ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, |
| 931 | const TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE, |
| 932 | bool PreserveLCSSA, Loop **RemainderLoop, AAResults *AA) { |
| 933 | assert(DT && "DomTree is required" ); |
| 934 | |
| 935 | if (!L->getLoopPreheader()) { |
| 936 | LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n" ); |
| 937 | return LoopUnrollResult::Unmodified; |
| 938 | } |
| 939 | |
| 940 | if (!L->getLoopLatch()) { |
| 941 | LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n" ); |
| 942 | return LoopUnrollResult::Unmodified; |
| 943 | } |
| 944 | |
| 945 | // Loops with indirectbr cannot be cloned. |
| 946 | if (!L->isSafeToClone()) { |
| 947 | LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n" ); |
| 948 | return LoopUnrollResult::Unmodified; |
| 949 | } |
| 950 | |
| 951 | if (L->getHeader()->hasAddressTaken()) { |
| 952 | // The loop-rotate pass can be helpful to avoid this in many cases. |
| 953 | LLVM_DEBUG( |
| 954 | dbgs() << " Won't unroll loop: address of header block is taken.\n" ); |
| 955 | return LoopUnrollResult::Unmodified; |
| 956 | } |
| 957 | |
| 958 | assert(ULO.Count > 0); |
| 959 | |
| 960 | // All these values should be taken only after peeling because they might have |
| 961 | // changed. |
| 962 | BasicBlock * = L->getLoopPreheader(); |
| 963 | BasicBlock * = L->getHeader(); |
| 964 | BasicBlock *LatchBlock = L->getLoopLatch(); |
| 965 | SmallVector<BasicBlock *, 4> ExitBlocks; |
| 966 | L->getExitBlocks(ExitBlocks); |
| 967 | std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks(); |
| 968 | |
| 969 | const unsigned MaxTripCount = SE->getSmallConstantMaxTripCount(L); |
| 970 | const bool MaxOrZero = SE->isBackedgeTakenCountMaxOrZero(L); |
| 971 | std::optional<unsigned> OriginalTripCount = |
| 972 | llvm::getLoopEstimatedTripCount(L); |
| 973 | BranchProbability OriginalLoopProb = llvm::getLoopProbability(L); |
| 974 | |
| 975 | // Effectively "DCE" unrolled iterations that are beyond the max tripcount |
| 976 | // and will never be executed. |
| 977 | if (MaxTripCount && ULO.Count > MaxTripCount) |
| 978 | ULO.Count = MaxTripCount; |
| 979 | |
| 980 | struct ExitInfo { |
| 981 | unsigned TripCount; |
| 982 | unsigned TripMultiple; |
| 983 | unsigned BreakoutTrip; |
| 984 | bool ExitOnTrue; |
| 985 | BasicBlock *FirstExitingBlock = nullptr; |
| 986 | SmallVector<BasicBlock *> ExitingBlocks; |
| 987 | }; |
| 988 | MapVector<BasicBlock *, ExitInfo> ExitInfos; |
| 989 | SmallVector<BasicBlock *, 4> ExitingBlocks; |
| 990 | L->getExitingBlocks(ExitingBlocks); |
| 991 | for (auto *ExitingBlock : ExitingBlocks) { |
| 992 | // The folding code is not prepared to deal with non-branch instructions |
| 993 | // right now. |
| 994 | auto *BI = dyn_cast<CondBrInst>(Val: ExitingBlock->getTerminator()); |
| 995 | if (!BI) |
| 996 | continue; |
| 997 | |
| 998 | ExitInfo &Info = ExitInfos[ExitingBlock]; |
| 999 | Info.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); |
| 1000 | Info.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); |
| 1001 | if (Info.TripCount != 0) { |
| 1002 | Info.BreakoutTrip = Info.TripCount % ULO.Count; |
| 1003 | Info.TripMultiple = 0; |
| 1004 | } else { |
| 1005 | Info.BreakoutTrip = Info.TripMultiple = |
| 1006 | (unsigned)std::gcd(m: ULO.Count, n: Info.TripMultiple); |
| 1007 | } |
| 1008 | Info.ExitOnTrue = !L->contains(BB: BI->getSuccessor(i: 0)); |
| 1009 | Info.ExitingBlocks.push_back(Elt: ExitingBlock); |
| 1010 | LLVM_DEBUG(dbgs() << " Exiting block %" << ExitingBlock->getName() |
| 1011 | << ": TripCount=" << Info.TripCount |
| 1012 | << ", TripMultiple=" << Info.TripMultiple |
| 1013 | << ", BreakoutTrip=" << Info.BreakoutTrip << "\n" ); |
| 1014 | } |
| 1015 | |
| 1016 | // Are we eliminating the loop control altogether? Note that we can know |
| 1017 | // we're eliminating the backedge without knowing exactly which iteration |
| 1018 | // of the unrolled body exits. |
| 1019 | const bool CompletelyUnroll = ULO.Count == MaxTripCount; |
| 1020 | |
| 1021 | const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero; |
| 1022 | |
| 1023 | // There's no point in performing runtime unrolling if this unroll count |
| 1024 | // results in a full unroll. |
| 1025 | if (CompletelyUnroll) |
| 1026 | ULO.Runtime = false; |
| 1027 | |
| 1028 | // Go through all exits of L and see if there are any phi-nodes there. We just |
| 1029 | // conservatively assume that they're inserted to preserve LCSSA form, which |
| 1030 | // means that complete unrolling might break this form. We need to either fix |
| 1031 | // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For |
| 1032 | // now we just recompute LCSSA for the outer loop, but it should be possible |
| 1033 | // to fix it in-place. |
| 1034 | bool NeedToFixLCSSA = |
| 1035 | PreserveLCSSA && CompletelyUnroll && |
| 1036 | any_of(Range&: ExitBlocks, |
| 1037 | P: [](const BasicBlock *BB) { return isa<PHINode>(Val: BB->begin()); }); |
| 1038 | |
| 1039 | // The current loop unroll pass can unroll loops that have |
| 1040 | // (1) single latch; and |
| 1041 | // (2a) latch is unconditional; or |
| 1042 | // (2b) latch is conditional and is an exiting block |
| 1043 | // FIXME: The implementation can be extended to work with more complicated |
| 1044 | // cases, e.g. loops with multiple latches. |
| 1045 | Instruction *LatchTerm = LatchBlock->getTerminator(); |
| 1046 | |
| 1047 | // A conditional branch which exits the loop, which can be optimized to an |
| 1048 | // unconditional branch in the unrolled loop in some cases. |
| 1049 | bool LatchIsExiting = L->isLoopExiting(BB: LatchBlock); |
| 1050 | if (!isa<UncondBrInst>(Val: LatchTerm) && |
| 1051 | !(isa<CondBrInst>(Val: LatchTerm) && LatchIsExiting)) { |
| 1052 | LLVM_DEBUG( |
| 1053 | dbgs() << "Can't unroll; a conditional latch must exit the loop" ); |
| 1054 | return LoopUnrollResult::Unmodified; |
| 1055 | } |
| 1056 | |
| 1057 | bool EpilogProfitability = |
| 1058 | UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog |
| 1059 | : isEpilogProfitable(L); |
| 1060 | |
| 1061 | if (ULO.Runtime && |
| 1062 | !UnrollRuntimeLoopRemainder( |
| 1063 | L, Count: ULO.Count, AllowExpensiveTripCount: ULO.AllowExpensiveTripCount, UseEpilogRemainder: EpilogProfitability, |
| 1064 | UnrollRemainder: ULO.UnrollRemainder, ForgetAllSCEV: ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI, |
| 1065 | PreserveLCSSA, SCEVExpansionBudget: ULO.SCEVExpansionBudget, RuntimeUnrollMultiExit: ULO.RuntimeUnrollMultiExit, |
| 1066 | ResultLoop: RemainderLoop, OriginalTripCount, OriginalLoopProb)) { |
| 1067 | if (ULO.Force) |
| 1068 | ULO.Runtime = false; |
| 1069 | else { |
| 1070 | LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be " |
| 1071 | "generated when assuming runtime trip count\n" ); |
| 1072 | return LoopUnrollResult::Unmodified; |
| 1073 | } |
| 1074 | } |
| 1075 | |
| 1076 | using namespace ore; |
| 1077 | |
| 1078 | // Determine whether this loop originated from the vectorizer so we can |
| 1079 | // produce more informative remarks. |
| 1080 | StringRef LoopKind = getLoopVectorizeKindPrefix(L); |
| 1081 | |
| 1082 | // Report the unrolling decision. |
| 1083 | if (CompletelyUnroll) { |
| 1084 | LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName() |
| 1085 | << " with trip count " << ULO.Count << "!\n" ); |
| 1086 | if (ORE) |
| 1087 | ORE->emit(RemarkBuilder: [&]() { |
| 1088 | return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled" , L->getStartLoc(), |
| 1089 | L->getHeader()) |
| 1090 | << "completely unrolled " + LoopKind.str() + "loop with " |
| 1091 | << NV("UnrollCount" , ULO.Count) << " iterations" ; |
| 1092 | }); |
| 1093 | } else { |
| 1094 | LLVM_DEBUG({ |
| 1095 | dbgs() << "UNROLLING loop %" << Header->getName() << " by " << ULO.Count; |
| 1096 | if (ULO.Runtime) { |
| 1097 | dbgs() << " with run-time trip count" ; |
| 1098 | if (ULO.UnrollRemainder) |
| 1099 | dbgs() << " (remainder unrolled)" ; |
| 1100 | } |
| 1101 | dbgs() << "!\n" ; |
| 1102 | }); |
| 1103 | |
| 1104 | if (ORE) |
| 1105 | ORE->emit(RemarkBuilder: [&]() { |
| 1106 | OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled" , L->getStartLoc(), |
| 1107 | L->getHeader()); |
| 1108 | Diag << "unrolled " + LoopKind.str() + "loop by a factor of " |
| 1109 | << NV("UnrollCount" , ULO.Count); |
| 1110 | if (ULO.Runtime) |
| 1111 | Diag << " with run-time trip count" |
| 1112 | << (ULO.UnrollRemainder ? " (remainder unrolled)" : "" ); |
| 1113 | return Diag; |
| 1114 | }); |
| 1115 | } |
| 1116 | |
| 1117 | // We are going to make changes to this loop. SCEV may be keeping cached info |
| 1118 | // about it, in particular about backedge taken count. The changes we make |
| 1119 | // are guaranteed to invalidate this information for our loop. It is tempting |
| 1120 | // to only invalidate the loop being unrolled, but it is incorrect as long as |
| 1121 | // all exiting branches from all inner loops have impact on the outer loops, |
| 1122 | // and if something changes inside them then any of outer loops may also |
| 1123 | // change. When we forget outermost loop, we also forget all contained loops |
| 1124 | // and this is what we need here. |
| 1125 | if (SE) { |
| 1126 | if (ULO.ForgetAllSCEV) |
| 1127 | SE->forgetAllLoops(); |
| 1128 | else { |
| 1129 | SE->forgetTopmostLoop(L); |
| 1130 | SE->forgetBlockAndLoopDispositions(); |
| 1131 | } |
| 1132 | } |
| 1133 | |
| 1134 | if (!LatchIsExiting) |
| 1135 | ++NumUnrolledNotLatch; |
| 1136 | |
| 1137 | // For the first iteration of the loop, we should use the precloned values for |
| 1138 | // PHI nodes. Insert associations now. |
| 1139 | ValueToValueMapTy LastValueMap; |
| 1140 | std::vector<PHINode*> OrigPHINode; |
| 1141 | for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(Val: I); ++I) { |
| 1142 | OrigPHINode.push_back(x: cast<PHINode>(Val&: I)); |
| 1143 | } |
| 1144 | |
| 1145 | // Collect phi nodes for reductions for which we can introduce multiple |
| 1146 | // parallel reduction phis and compute the final reduction result after the |
| 1147 | // loop. This requires a single exit block after unrolling. This is ensured by |
| 1148 | // restricting to single-block loops where the unrolled iterations are known |
| 1149 | // to not exit. |
| 1150 | DenseMap<PHINode *, RecurrenceDescriptor> Reductions; |
| 1151 | bool CanAddAdditionalAccumulators = |
| 1152 | (UnrollAddParallelReductions.getNumOccurrences() > 0 |
| 1153 | ? UnrollAddParallelReductions |
| 1154 | : ULO.AddAdditionalAccumulators) && |
| 1155 | !CompletelyUnroll && L->getNumBlocks() == 1 && |
| 1156 | (ULO.Runtime || |
| 1157 | (ExitInfos.contains(Key: Header) && ((ExitInfos[Header].TripCount != 0 && |
| 1158 | ExitInfos[Header].BreakoutTrip == 0)))); |
| 1159 | |
| 1160 | // Limit parallelizing reductions to unroll counts of 4 or less for now. |
| 1161 | // TODO: The number of parallel reductions should depend on the number of |
| 1162 | // execution units. We also don't have to add a parallel reduction phi per |
| 1163 | // unrolled iteration, but could for example add a parallel phi for every 2 |
| 1164 | // unrolled iterations. |
| 1165 | if (CanAddAdditionalAccumulators && ULO.Count <= 4) { |
| 1166 | for (PHINode &Phi : Header->phis()) { |
| 1167 | auto RdxDesc = canParallelizeReductionWhenUnrolling(Phi, L, SE); |
| 1168 | if (!RdxDesc) |
| 1169 | continue; |
| 1170 | |
| 1171 | // Only handle duplicate phis for a single reduction for now. |
| 1172 | // TODO: Handle any number of reductions |
| 1173 | if (!Reductions.empty()) |
| 1174 | continue; |
| 1175 | |
| 1176 | Reductions[&Phi] = *RdxDesc; |
| 1177 | } |
| 1178 | } |
| 1179 | |
| 1180 | std::vector<BasicBlock *> ; |
| 1181 | std::vector<BasicBlock *> Latches; |
| 1182 | Headers.push_back(x: Header); |
| 1183 | Latches.push_back(x: LatchBlock); |
| 1184 | |
| 1185 | // The current on-the-fly SSA update requires blocks to be processed in |
| 1186 | // reverse postorder so that LastValueMap contains the correct value at each |
| 1187 | // exit. |
| 1188 | LoopBlocksDFS DFS(L); |
| 1189 | DFS.perform(LI); |
| 1190 | |
| 1191 | // Stash the DFS iterators before adding blocks to the loop. |
| 1192 | LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO(); |
| 1193 | LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO(); |
| 1194 | |
| 1195 | std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks(); |
| 1196 | |
| 1197 | // Loop Unrolling might create new loops. While we do preserve LoopInfo, we |
| 1198 | // might break loop-simplified form for these loops (as they, e.g., would |
| 1199 | // share the same exit blocks). We'll keep track of loops for which we can |
| 1200 | // break this so that later we can re-simplify them. |
| 1201 | SmallSetVector<Loop *, 4> LoopsToSimplify; |
| 1202 | LoopsToSimplify.insert_range(R&: *L); |
| 1203 | |
| 1204 | // When a FSDiscriminator is enabled, we don't need to add the multiply |
| 1205 | // factors to the discriminators. |
| 1206 | if (Header->getParent()->shouldEmitDebugInfoForProfiling() && |
| 1207 | !EnableFSDiscriminator) |
| 1208 | for (BasicBlock *BB : L->getBlocks()) |
| 1209 | for (Instruction &I : *BB) |
| 1210 | if (!I.isDebugOrPseudoInst()) |
| 1211 | if (const DILocation *DIL = I.getDebugLoc()) { |
| 1212 | auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(DF: ULO.Count); |
| 1213 | if (NewDIL) |
| 1214 | I.setDebugLoc(*NewDIL); |
| 1215 | else |
| 1216 | LLVM_DEBUG(dbgs() |
| 1217 | << "Failed to create new discriminator: " |
| 1218 | << DIL->getFilename() << " Line: " << DIL->getLine()); |
| 1219 | } |
| 1220 | |
| 1221 | // Identify what noalias metadata is inside the loop: if it is inside the |
| 1222 | // loop, the associated metadata must be cloned for each iteration. |
| 1223 | SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes; |
| 1224 | identifyNoAliasScopesToClone(BBs: L->getBlocks(), NoAliasDeclScopes&: LoopLocalNoAliasDeclScopes); |
| 1225 | |
| 1226 | // We place the unrolled iterations immediately after the original loop |
| 1227 | // latch. This is a reasonable default placement if we don't have block |
| 1228 | // frequencies, and if we do, well the layout will be adjusted later. |
| 1229 | auto BlockInsertPt = std::next(x: LatchBlock->getIterator()); |
| 1230 | SmallVector<Instruction *> PartialReductions; |
| 1231 | for (unsigned It = 1; It != ULO.Count; ++It) { |
| 1232 | SmallVector<BasicBlock *, 8> NewBlocks; |
| 1233 | SmallDenseMap<const Loop *, Loop *, 4> NewLoops; |
| 1234 | NewLoops[L] = L; |
| 1235 | |
| 1236 | for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { |
| 1237 | ValueToValueMapTy VMap; |
| 1238 | BasicBlock *New = CloneBasicBlock(BB: *BB, VMap, NameSuffix: "." + Twine(It)); |
| 1239 | Header->getParent()->insert(Position: BlockInsertPt, BB: New); |
| 1240 | |
| 1241 | assert((*BB != Header || LI->getLoopFor(*BB) == L) && |
| 1242 | "Header should not be in a sub-loop" ); |
| 1243 | // Tell LI about New. |
| 1244 | const Loop *OldLoop = addClonedBlockToLoopInfo(OriginalBB: *BB, ClonedBB: New, LI, NewLoops); |
| 1245 | if (OldLoop) |
| 1246 | LoopsToSimplify.insert(X: NewLoops[OldLoop]); |
| 1247 | |
| 1248 | if (*BB == Header) { |
| 1249 | // Loop over all of the PHI nodes in the block, changing them to use |
| 1250 | // the incoming values from the previous block. |
| 1251 | for (PHINode *OrigPHI : OrigPHINode) { |
| 1252 | PHINode *NewPHI = cast<PHINode>(Val&: VMap[OrigPHI]); |
| 1253 | Value *InVal = NewPHI->getIncomingValueForBlock(BB: LatchBlock); |
| 1254 | |
| 1255 | // Use cloned phis as parallel phis for partial reductions, which will |
| 1256 | // get combined to the final reduction result after the loop. |
| 1257 | if (Reductions.contains(Val: OrigPHI)) { |
| 1258 | // Collect partial reduction results. |
| 1259 | if (PartialReductions.empty()) |
| 1260 | PartialReductions.push_back(Elt: cast<Instruction>(Val: InVal)); |
| 1261 | PartialReductions.push_back(Elt: cast<Instruction>(Val&: VMap[InVal])); |
| 1262 | |
| 1263 | // Update the start value for the cloned phis to use the identity |
| 1264 | // value for the reduction. |
| 1265 | const RecurrenceDescriptor &RdxDesc = Reductions[OrigPHI]; |
| 1266 | NewPHI->setIncomingValueForBlock( |
| 1267 | BB: L->getLoopPreheader(), |
| 1268 | V: getRecurrenceIdentity(K: RdxDesc.getRecurrenceKind(), |
| 1269 | Tp: OrigPHI->getType(), |
| 1270 | FMF: RdxDesc.getFastMathFlags())); |
| 1271 | |
| 1272 | // Update NewPHI to use the cloned value for the iteration and move |
| 1273 | // to header. |
| 1274 | NewPHI->replaceUsesOfWith(From: InVal, To: VMap[InVal]); |
| 1275 | NewPHI->moveBefore(InsertPos: OrigPHI->getIterator()); |
| 1276 | continue; |
| 1277 | } |
| 1278 | |
| 1279 | if (Instruction *InValI = dyn_cast<Instruction>(Val: InVal)) |
| 1280 | if (It > 1 && L->contains(Inst: InValI)) |
| 1281 | InVal = LastValueMap[InValI]; |
| 1282 | VMap[OrigPHI] = InVal; |
| 1283 | NewPHI->eraseFromParent(); |
| 1284 | } |
| 1285 | |
| 1286 | // Eliminate copies of the loop heart intrinsic, if any. |
| 1287 | if (ULO.Heart) { |
| 1288 | auto it = VMap.find(Val: ULO.Heart); |
| 1289 | assert(it != VMap.end()); |
| 1290 | Instruction *heartCopy = cast<Instruction>(Val&: it->second); |
| 1291 | heartCopy->eraseFromParent(); |
| 1292 | VMap.erase(I: it); |
| 1293 | } |
| 1294 | } |
| 1295 | |
| 1296 | // Remap source location atom instance. Do this now, rather than |
| 1297 | // when we remap instructions, because remap is called once we've |
| 1298 | // cloned all blocks (all the clones would get the same atom |
| 1299 | // number). |
| 1300 | if (!VMap.AtomMap.empty()) |
| 1301 | for (Instruction &I : *New) |
| 1302 | RemapSourceAtom(I: &I, VM&: VMap); |
| 1303 | |
| 1304 | // Update our running map of newest clones |
| 1305 | LastValueMap[*BB] = New; |
| 1306 | for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end(); |
| 1307 | VI != VE; ++VI) |
| 1308 | LastValueMap[VI->first] = VI->second; |
| 1309 | |
| 1310 | // Add phi entries for newly created values to all exit blocks. |
| 1311 | for (BasicBlock *Succ : successors(BB: *BB)) { |
| 1312 | if (L->contains(BB: Succ)) |
| 1313 | continue; |
| 1314 | for (PHINode &PHI : Succ->phis()) { |
| 1315 | Value *Incoming = PHI.getIncomingValueForBlock(BB: *BB); |
| 1316 | ValueToValueMapTy::iterator It = LastValueMap.find(Val: Incoming); |
| 1317 | if (It != LastValueMap.end()) |
| 1318 | Incoming = It->second; |
| 1319 | PHI.addIncoming(V: Incoming, BB: New); |
| 1320 | SE->forgetLcssaPhiWithNewPredecessor(L, V: &PHI); |
| 1321 | } |
| 1322 | } |
| 1323 | // Keep track of new headers and latches as we create them, so that |
| 1324 | // we can insert the proper branches later. |
| 1325 | if (*BB == Header) |
| 1326 | Headers.push_back(x: New); |
| 1327 | if (*BB == LatchBlock) |
| 1328 | Latches.push_back(x: New); |
| 1329 | |
| 1330 | // Keep track of the exiting block and its successor block contained in |
| 1331 | // the loop for the current iteration. |
| 1332 | auto ExitInfoIt = ExitInfos.find(Key: *BB); |
| 1333 | if (ExitInfoIt != ExitInfos.end()) |
| 1334 | ExitInfoIt->second.ExitingBlocks.push_back(Elt: New); |
| 1335 | |
| 1336 | NewBlocks.push_back(Elt: New); |
| 1337 | UnrolledLoopBlocks.push_back(x: New); |
| 1338 | |
| 1339 | // Update DomTree: since we just copy the loop body, and each copy has a |
| 1340 | // dedicated entry block (copy of the header block), this header's copy |
| 1341 | // dominates all copied blocks. That means, dominance relations in the |
| 1342 | // copied body are the same as in the original body. |
| 1343 | if (*BB == Header) |
| 1344 | DT->addNewBlock(BB: New, DomBB: Latches[It - 1]); |
| 1345 | else { |
| 1346 | auto BBDomNode = DT->getNode(BB: *BB); |
| 1347 | auto BBIDom = BBDomNode->getIDom(); |
| 1348 | BasicBlock *OriginalBBIDom = BBIDom->getBlock(); |
| 1349 | DT->addNewBlock( |
| 1350 | BB: New, DomBB: cast<BasicBlock>(Val&: LastValueMap[cast<Value>(Val: OriginalBBIDom)])); |
| 1351 | } |
| 1352 | } |
| 1353 | |
| 1354 | // Remap all instructions in the most recent iteration. |
| 1355 | // Key Instructions: Nothing to do - we've already remapped the atoms. |
| 1356 | remapInstructionsInBlocks(Blocks: NewBlocks, VMap&: LastValueMap); |
| 1357 | for (BasicBlock *NewBlock : NewBlocks) |
| 1358 | for (Instruction &I : *NewBlock) |
| 1359 | if (auto *II = dyn_cast<AssumeInst>(Val: &I)) |
| 1360 | AC->registerAssumption(CI: II); |
| 1361 | |
| 1362 | { |
| 1363 | // Identify what other metadata depends on the cloned version. After |
| 1364 | // cloning, replace the metadata with the corrected version for both |
| 1365 | // memory instructions and noalias intrinsics. |
| 1366 | std::string ext = (Twine("It" ) + Twine(It)).str(); |
| 1367 | cloneAndAdaptNoAliasScopes(NoAliasDeclScopes: LoopLocalNoAliasDeclScopes, NewBlocks, |
| 1368 | Context&: Header->getContext(), Ext: ext); |
| 1369 | } |
| 1370 | } |
| 1371 | |
| 1372 | // Loop over the PHI nodes in the original block, setting incoming values. |
| 1373 | for (PHINode *PN : OrigPHINode) { |
| 1374 | if (CompletelyUnroll) { |
| 1375 | // The RAUW below disconnects the original PHI from its users. |
| 1376 | // Invalidate cached SCEVs while the def-use chain is still intact. |
| 1377 | if (SE) |
| 1378 | SE->forgetValue(V: PN); |
| 1379 | PN->replaceAllUsesWith(V: PN->getIncomingValueForBlock(BB: Preheader)); |
| 1380 | PN->eraseFromParent(); |
| 1381 | } else if (ULO.Count > 1) { |
| 1382 | if (Reductions.contains(Val: PN)) |
| 1383 | continue; |
| 1384 | |
| 1385 | Value *InVal = PN->removeIncomingValue(BB: LatchBlock, DeletePHIIfEmpty: false); |
| 1386 | // If this value was defined in the loop, take the value defined by the |
| 1387 | // last iteration of the loop. |
| 1388 | if (Instruction *InValI = dyn_cast<Instruction>(Val: InVal)) { |
| 1389 | if (L->contains(Inst: InValI)) |
| 1390 | InVal = LastValueMap[InVal]; |
| 1391 | } |
| 1392 | assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch" ); |
| 1393 | PN->addIncoming(V: InVal, BB: Latches.back()); |
| 1394 | } |
| 1395 | } |
| 1396 | |
| 1397 | // Connect latches of the unrolled iterations to the headers of the next |
| 1398 | // iteration. Currently they point to the header of the same iteration. |
| 1399 | for (unsigned i = 0, e = Latches.size(); i != e; ++i) { |
| 1400 | unsigned j = (i + 1) % e; |
| 1401 | Latches[i]->getTerminator()->replaceSuccessorWith(OldBB: Headers[i], NewBB: Headers[j]); |
| 1402 | } |
| 1403 | |
| 1404 | // Remove loop metadata copied from the original loop latch to branches that |
| 1405 | // are no longer latches. |
| 1406 | for (unsigned I = 0, E = Latches.size() - (CompletelyUnroll ? 0 : 1); I < E; |
| 1407 | ++I) |
| 1408 | Latches[I]->getTerminator()->setMetadata(KindID: LLVMContext::MD_loop, Node: nullptr); |
| 1409 | |
| 1410 | // Update dominators of blocks we might reach through exits. |
| 1411 | // Immediate dominator of such block might change, because we add more |
| 1412 | // routes which can lead to the exit: we can now reach it from the copied |
| 1413 | // iterations too. |
| 1414 | if (ULO.Count > 1) { |
| 1415 | for (auto *BB : OriginalLoopBlocks) { |
| 1416 | auto *BBDomNode = DT->getNode(BB); |
| 1417 | SmallVector<BasicBlock *, 16> ChildrenToUpdate; |
| 1418 | for (auto *ChildDomNode : BBDomNode->children()) { |
| 1419 | auto *ChildBB = ChildDomNode->getBlock(); |
| 1420 | if (!L->contains(BB: ChildBB)) |
| 1421 | ChildrenToUpdate.push_back(Elt: ChildBB); |
| 1422 | } |
| 1423 | // The new idom of the block will be the nearest common dominator |
| 1424 | // of all copies of the previous idom. This is equivalent to the |
| 1425 | // nearest common dominator of the previous idom and the first latch, |
| 1426 | // which dominates all copies of the previous idom. |
| 1427 | BasicBlock *NewIDom = DT->findNearestCommonDominator(A: BB, B: LatchBlock); |
| 1428 | for (auto *ChildBB : ChildrenToUpdate) |
| 1429 | DT->changeImmediateDominator(BB: ChildBB, NewBB: NewIDom); |
| 1430 | } |
| 1431 | } |
| 1432 | |
| 1433 | assert(!UnrollVerifyDomtree || |
| 1434 | DT->verify(DominatorTree::VerificationLevel::Fast)); |
| 1435 | |
| 1436 | SmallVector<DominatorTree::UpdateType> DTUpdates; |
| 1437 | auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) { |
| 1438 | auto *Term = cast<CondBrInst>(Val: Src->getTerminator()); |
| 1439 | const unsigned Idx = ExitOnTrue ^ WillExit; |
| 1440 | BasicBlock *Dest = Term->getSuccessor(i: Idx); |
| 1441 | BasicBlock *DeadSucc = Term->getSuccessor(i: 1-Idx); |
| 1442 | |
| 1443 | // Remove predecessors from all non-Dest successors. |
| 1444 | DeadSucc->removePredecessor(Pred: Src, /* KeepOneInputPHIs */ true); |
| 1445 | |
| 1446 | // Replace the conditional branch with an unconditional one. |
| 1447 | auto *BI = UncondBrInst::Create(Target: Dest, InsertBefore: Term->getIterator()); |
| 1448 | BI->setDebugLoc(Term->getDebugLoc()); |
| 1449 | Term->eraseFromParent(); |
| 1450 | |
| 1451 | DTUpdates.emplace_back(Args: DominatorTree::Delete, Args&: Src, Args&: DeadSucc); |
| 1452 | }; |
| 1453 | |
| 1454 | auto WillExit = [&](const ExitInfo &Info, unsigned i, unsigned j, |
| 1455 | bool IsLatch) -> std::optional<bool> { |
| 1456 | if (CompletelyUnroll) { |
| 1457 | if (PreserveOnlyFirst) { |
| 1458 | if (i == 0) |
| 1459 | return std::nullopt; |
| 1460 | return j == 0; |
| 1461 | } |
| 1462 | // Complete (but possibly inexact) unrolling |
| 1463 | if (j == 0) |
| 1464 | return true; |
| 1465 | if (Info.TripCount && j != Info.TripCount) |
| 1466 | return false; |
| 1467 | return std::nullopt; |
| 1468 | } |
| 1469 | |
| 1470 | if (ULO.Runtime) { |
| 1471 | // If runtime unrolling inserts a prologue, information about non-latch |
| 1472 | // exits may be stale. |
| 1473 | if (IsLatch && j != 0) |
| 1474 | return false; |
| 1475 | return std::nullopt; |
| 1476 | } |
| 1477 | |
| 1478 | if (j != Info.BreakoutTrip && |
| 1479 | (Info.TripMultiple == 0 || j % Info.TripMultiple != 0)) { |
| 1480 | // If we know the trip count or a multiple of it, we can safely use an |
| 1481 | // unconditional branch for some iterations. |
| 1482 | return false; |
| 1483 | } |
| 1484 | return std::nullopt; |
| 1485 | }; |
| 1486 | |
| 1487 | // Fold branches for iterations where we know that they will exit or not |
| 1488 | // exit. In the case of an iteration's latch, if we thus find |
| 1489 | // *OriginalLoopProb is incorrect, set ProbUpdateRequired to true. |
| 1490 | bool ProbUpdateRequired = false; |
| 1491 | for (auto &Pair : ExitInfos) { |
| 1492 | ExitInfo &Info = Pair.second; |
| 1493 | for (unsigned i = 0, e = Info.ExitingBlocks.size(); i != e; ++i) { |
| 1494 | // The branch destination. |
| 1495 | unsigned j = (i + 1) % e; |
| 1496 | bool IsLatch = Pair.first == LatchBlock; |
| 1497 | std::optional<bool> KnownWillExit = WillExit(Info, i, j, IsLatch); |
| 1498 | if (!KnownWillExit) { |
| 1499 | if (!Info.FirstExitingBlock) |
| 1500 | Info.FirstExitingBlock = Info.ExitingBlocks[i]; |
| 1501 | continue; |
| 1502 | } |
| 1503 | |
| 1504 | // We don't fold known-exiting branches for non-latch exits here, |
| 1505 | // because this ensures that both all loop blocks and all exit blocks |
| 1506 | // remain reachable in the CFG. |
| 1507 | // TODO: We could fold these branches, but it would require much more |
| 1508 | // sophisticated updates to LoopInfo. |
| 1509 | if (*KnownWillExit && !IsLatch) { |
| 1510 | if (!Info.FirstExitingBlock) |
| 1511 | Info.FirstExitingBlock = Info.ExitingBlocks[i]; |
| 1512 | continue; |
| 1513 | } |
| 1514 | |
| 1515 | // For a latch, record any OriginalLoopProb contradiction. |
| 1516 | if (!OriginalLoopProb.isUnknown() && IsLatch) { |
| 1517 | BranchProbability ActualProb = *KnownWillExit |
| 1518 | ? BranchProbability::getZero() |
| 1519 | : BranchProbability::getOne(); |
| 1520 | ProbUpdateRequired |= OriginalLoopProb != ActualProb; |
| 1521 | } |
| 1522 | |
| 1523 | SetDest(Info.ExitingBlocks[i], *KnownWillExit, Info.ExitOnTrue); |
| 1524 | } |
| 1525 | } |
| 1526 | |
| 1527 | DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); |
| 1528 | DomTreeUpdater *DTUToUse = &DTU; |
| 1529 | if (ExitingBlocks.size() == 1 && ExitInfos.size() == 1) { |
| 1530 | // Manually update the DT if there's a single exiting node. In that case |
| 1531 | // there's a single exit node and it is sufficient to update the nodes |
| 1532 | // immediately dominated by the original exiting block. They will become |
| 1533 | // dominated by the first exiting block that leaves the loop after |
| 1534 | // unrolling. Note that the CFG inside the loop does not change, so there's |
| 1535 | // no need to update the DT inside the unrolled loop. |
| 1536 | DTUToUse = nullptr; |
| 1537 | auto &[OriginalExit, Info] = *ExitInfos.begin(); |
| 1538 | if (!Info.FirstExitingBlock) |
| 1539 | Info.FirstExitingBlock = Info.ExitingBlocks.back(); |
| 1540 | for (auto *C : to_vector(Range: DT->getNode(BB: OriginalExit)->children())) { |
| 1541 | if (L->contains(BB: C->getBlock())) |
| 1542 | continue; |
| 1543 | C->setIDom(DT->getNode(BB: Info.FirstExitingBlock)); |
| 1544 | } |
| 1545 | } else { |
| 1546 | DTU.applyUpdates(Updates: DTUpdates); |
| 1547 | } |
| 1548 | |
| 1549 | // When completely unrolling, the last latch becomes unreachable. |
| 1550 | if (!LatchIsExiting && CompletelyUnroll) { |
| 1551 | // There is no need to update the DT here, because there must be a unique |
| 1552 | // latch. Hence if the latch is not exiting it must directly branch back to |
| 1553 | // the original loop header and does not dominate any nodes. |
| 1554 | assert(LatchBlock->getSingleSuccessor() && "Loop with multiple latches?" ); |
| 1555 | changeToUnreachable(I: Latches.back()->getTerminator(), PreserveLCSSA); |
| 1556 | } |
| 1557 | |
| 1558 | // After merging adjacent blocks in Latches below: |
| 1559 | // - CondLatches will list the blocks from Latches that are still terminated |
| 1560 | // with conditional branches. |
| 1561 | // - For 1 <= I < CondLatches.size(), IterCounts[I] will store the number of |
| 1562 | // the original loop iterations through which control flows from |
| 1563 | // CondLatches[I-1] to CondLatches[I]. |
| 1564 | // - For I == 0 or I == CondLatches.size(), IterCounts[I] will store the |
| 1565 | // number of the original loop iterations through which control can flow |
| 1566 | // before CondLatches.front() or after CondLatches.back(), respectively, |
| 1567 | // without taking the unrolled loop's backedge, if any. |
| 1568 | // - CondLatchNexts[I] will store the CondLatches[I] branch target for the |
| 1569 | // next of the original loop's iterations (as opposed to the exit target). |
| 1570 | assert(ULO.Count == Latches.size() && |
| 1571 | "Expected one latch block per unrolled iteration" ); |
| 1572 | std::vector<unsigned> IterCounts(1, 0); |
| 1573 | std::vector<BasicBlock *> CondLatches; |
| 1574 | std::vector<BasicBlock *> CondLatchNexts; |
| 1575 | IterCounts.reserve(n: Latches.size() + 1); |
| 1576 | CondLatches.reserve(n: Latches.size()); |
| 1577 | CondLatchNexts.reserve(n: Latches.size()); |
| 1578 | |
| 1579 | // Merge adjacent basic blocks, if possible. |
| 1580 | for (auto [I, Latch] : enumerate(First&: Latches)) { |
| 1581 | ++IterCounts.back(); |
| 1582 | assert((isa<UncondBrInst, CondBrInst>(Latch->getTerminator()) || |
| 1583 | (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) && |
| 1584 | "Need a branch as terminator, except when fully unrolling with " |
| 1585 | "unconditional latch" ); |
| 1586 | if (auto *Term = dyn_cast<UncondBrInst>(Val: Latch->getTerminator())) { |
| 1587 | BasicBlock *Dest = Term->getSuccessor(); |
| 1588 | BasicBlock *Fold = Dest->getUniquePredecessor(); |
| 1589 | if (MergeBlockIntoPredecessor(BB: Dest, /*DTU=*/DTUToUse, LI, |
| 1590 | /*MSSAU=*/nullptr, /*MemDep=*/nullptr, |
| 1591 | /*PredecessorWithTwoSuccessors=*/false, |
| 1592 | DT: DTUToUse ? nullptr : DT)) { |
| 1593 | // Dest has been folded into Fold. Update our worklists accordingly. |
| 1594 | llvm::replace(Range&: Latches, OldValue: Dest, NewValue: Fold); |
| 1595 | llvm::erase(C&: UnrolledLoopBlocks, V: Dest); |
| 1596 | } |
| 1597 | } else if (isa<CondBrInst>(Val: Latch->getTerminator())) { |
| 1598 | IterCounts.push_back(x: 0); |
| 1599 | CondLatches.push_back(x: Latch); |
| 1600 | CondLatchNexts.push_back(x: Headers[(I + 1) % Latches.size()]); |
| 1601 | } |
| 1602 | } |
| 1603 | |
| 1604 | // Fix probabilities we contradicted above. |
| 1605 | if (ProbUpdateRequired) { |
| 1606 | fixProbContradiction(L, ULO, ORE, OriginalLoopProb, CompletelyUnroll, |
| 1607 | IterCounts, CondLatches, CondLatchNexts); |
| 1608 | } |
| 1609 | |
| 1610 | // If there are partial reductions, create code in the exit block to compute |
| 1611 | // the final result and update users of the final result. |
| 1612 | if (!PartialReductions.empty()) { |
| 1613 | BasicBlock *ExitBlock = L->getExitBlock(); |
| 1614 | assert(ExitBlock && |
| 1615 | "Can only introduce parallel reduction phis with single exit block" ); |
| 1616 | assert(Reductions.size() == 1 && |
| 1617 | "currently only a single reduction is supported" ); |
| 1618 | Value *FinalRdxValue = PartialReductions.back(); |
| 1619 | Value *RdxResult = nullptr; |
| 1620 | for (PHINode &Phi : ExitBlock->phis()) { |
| 1621 | if (Phi.getIncomingValueForBlock(BB: L->getLoopLatch()) != FinalRdxValue) |
| 1622 | continue; |
| 1623 | if (!RdxResult) { |
| 1624 | RdxResult = PartialReductions.front(); |
| 1625 | IRBuilder Builder(ExitBlock, ExitBlock->getFirstNonPHIIt()); |
| 1626 | Builder.setFastMathFlags(Reductions.begin()->second.getFastMathFlags()); |
| 1627 | RecurKind RK = Reductions.begin()->second.getRecurrenceKind(); |
| 1628 | for (Instruction *RdxPart : drop_begin(RangeOrContainer&: PartialReductions)) { |
| 1629 | if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind: RK)) |
| 1630 | RdxResult = createMinMaxOp(Builder, RK, Left: RdxResult, Right: RdxPart); |
| 1631 | else |
| 1632 | RdxResult = Builder.CreateBinOp( |
| 1633 | Opc: (Instruction::BinaryOps)RecurrenceDescriptor::getOpcode(Kind: RK), |
| 1634 | LHS: RdxPart, RHS: RdxResult, Name: "bin.rdx" ); |
| 1635 | } |
| 1636 | NeedToFixLCSSA = true; |
| 1637 | for (Instruction *RdxPart : PartialReductions) |
| 1638 | RdxPart->dropPoisonGeneratingFlags(); |
| 1639 | } |
| 1640 | |
| 1641 | Phi.replaceAllUsesWith(V: RdxResult); |
| 1642 | } |
| 1643 | } |
| 1644 | |
| 1645 | if (DTUToUse) { |
| 1646 | // Apply updates to the DomTree. |
| 1647 | DT = &DTU.getDomTree(); |
| 1648 | } |
| 1649 | assert(!UnrollVerifyDomtree || |
| 1650 | DT->verify(DominatorTree::VerificationLevel::Fast)); |
| 1651 | |
| 1652 | Loop *OuterL = L->getParentLoop(); |
| 1653 | std::vector<BasicBlock *> Blocks; |
| 1654 | // Update LoopInfo if the loop is completely removed. |
| 1655 | if (CompletelyUnroll) { |
| 1656 | Blocks = L->getBlocks(); |
| 1657 | LI->erase(L); |
| 1658 | // We shouldn't try to use `L` anymore. |
| 1659 | L = nullptr; |
| 1660 | } |
| 1661 | |
| 1662 | // At this point, the code is well formed. We now simplify the unrolled loop, |
| 1663 | // doing constant propagation and dead code elimination as we go. |
| 1664 | simplifyLoopAfterUnroll( |
| 1665 | L, SimplifyIVs: !CompletelyUnroll && ULO.Count > 1, LI, SE, DT, AC, TTI, |
| 1666 | Blocks: CompletelyUnroll ? ArrayRef<BasicBlock *>(Blocks) : L->getBlocks(), AA); |
| 1667 | |
| 1668 | NumCompletelyUnrolled += CompletelyUnroll; |
| 1669 | ++NumUnrolled; |
| 1670 | |
| 1671 | if (!CompletelyUnroll) { |
| 1672 | // Update metadata for the loop's branch weights and estimated trip count: |
| 1673 | // - If ULO.Runtime, UnrollRuntimeLoopRemainder sets the guard branch |
| 1674 | // weights, latch branch weights, and estimated trip count of the |
| 1675 | // remainder loop it creates. It also sets the branch weights for the |
| 1676 | // unrolled loop guard it creates. The branch weights for the unrolled |
| 1677 | // loop latch are adjusted below. FIXME: Handle prologue loops. |
| 1678 | // - Otherwise, if unrolled loop iteration latches become unconditional, |
| 1679 | // branch weights are adjusted by the fixProbContradiction call above. |
| 1680 | // - Otherwise, the original loop's branch weights are correct for the |
| 1681 | // unrolled loop, so do not adjust them. |
| 1682 | // - In all cases, the unrolled loop's estimated trip count is set below. |
| 1683 | // |
| 1684 | // As an example of the last case, consider what happens if the unroll count |
| 1685 | // is 4 for a loop with an estimated trip count of 10 when we do not create |
| 1686 | // a remainder loop and all iterations' latches remain conditional. Each |
| 1687 | // unrolled iteration's latch still has the same probability of exiting the |
| 1688 | // loop as it did when in the original loop, and thus it should still have |
| 1689 | // the same branch weights. Each unrolled iteration's non-zero probability |
| 1690 | // of exiting already appropriately reduces the probability of reaching the |
| 1691 | // remaining iterations just as it did in the original loop. Trying to also |
| 1692 | // adjust the branch weights of the final unrolled iteration's latch (i.e., |
| 1693 | // the backedge for the unrolled loop as a whole) to reflect its new trip |
| 1694 | // count of 3 will erroneously further reduce its block frequencies. |
| 1695 | // However, in case an analysis later needs to estimate the trip count of |
| 1696 | // the unrolled loop as a whole without considering the branch weights for |
| 1697 | // each unrolled iteration's latch within it, we store the new trip count as |
| 1698 | // separate metadata. |
| 1699 | if (!OriginalLoopProb.isUnknown() && ULO.Runtime && EpilogProfitability) { |
| 1700 | assert((CondLatches.size() == 1 && |
| 1701 | (ProbUpdateRequired || OriginalLoopProb.isOne())) && |
| 1702 | "Expected ULO.Runtime to give unrolled loop 1 conditional latch, " |
| 1703 | "the backedge, requiring a probability update unless infinite" ); |
| 1704 | // Where p is always the probability of executing at least 1 more |
| 1705 | // iteration, the probability for at least n more iterations is p^n. |
| 1706 | setLoopProbability(L, P: OriginalLoopProb.pow(N: ULO.Count)); |
| 1707 | } |
| 1708 | if (OriginalTripCount) { |
| 1709 | unsigned NewTripCount = *OriginalTripCount / ULO.Count; |
| 1710 | if (!ULO.Runtime && *OriginalTripCount % ULO.Count) |
| 1711 | ++NewTripCount; |
| 1712 | setLoopEstimatedTripCount(L, EstimatedTripCount: NewTripCount); |
| 1713 | } |
| 1714 | } |
| 1715 | |
| 1716 | // LoopInfo should not be valid, confirm that. |
| 1717 | if (UnrollVerifyLoopInfo) |
| 1718 | LI->verify(); |
| 1719 | |
| 1720 | // After complete unrolling most of the blocks should be contained in OuterL. |
| 1721 | // However, some of them might happen to be out of OuterL (e.g. if they |
| 1722 | // precede a loop exit). In this case we might need to insert PHI nodes in |
| 1723 | // order to preserve LCSSA form. |
| 1724 | // We don't need to check this if we already know that we need to fix LCSSA |
| 1725 | // form. |
| 1726 | // TODO: For now we just recompute LCSSA for the outer loop in this case, but |
| 1727 | // it should be possible to fix it in-place. |
| 1728 | if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA) |
| 1729 | NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(L: OuterL, Blocks: UnrolledLoopBlocks, LI); |
| 1730 | |
| 1731 | // Make sure that loop-simplify form is preserved. We want to simplify |
| 1732 | // at least one layer outside of the loop that was unrolled so that any |
| 1733 | // changes to the parent loop exposed by the unrolling are considered. |
| 1734 | if (OuterL) { |
| 1735 | // OuterL includes all loops for which we can break loop-simplify, so |
| 1736 | // it's sufficient to simplify only it (it'll recursively simplify inner |
| 1737 | // loops too). |
| 1738 | if (NeedToFixLCSSA) { |
| 1739 | // LCSSA must be performed on the outermost affected loop. The unrolled |
| 1740 | // loop's last loop latch is guaranteed to be in the outermost loop |
| 1741 | // after LoopInfo's been updated by LoopInfo::erase. |
| 1742 | Loop *LatchLoop = LI->getLoopFor(BB: Latches.back()); |
| 1743 | Loop *FixLCSSALoop = OuterL; |
| 1744 | if (!FixLCSSALoop->contains(L: LatchLoop)) |
| 1745 | while (FixLCSSALoop->getParentLoop() != LatchLoop) |
| 1746 | FixLCSSALoop = FixLCSSALoop->getParentLoop(); |
| 1747 | |
| 1748 | formLCSSARecursively(L&: *FixLCSSALoop, DT: *DT, LI, SE); |
| 1749 | } else if (PreserveLCSSA) { |
| 1750 | assert(OuterL->isLCSSAForm(*DT) && |
| 1751 | "Loops should be in LCSSA form after loop-unroll." ); |
| 1752 | } |
| 1753 | |
| 1754 | // TODO: That potentially might be compile-time expensive. We should try |
| 1755 | // to fix the loop-simplified form incrementally. |
| 1756 | simplifyLoop(L: OuterL, DT, LI, SE, AC, MSSAU: nullptr, PreserveLCSSA); |
| 1757 | } else { |
| 1758 | // Simplify loops for which we might've broken loop-simplify form. |
| 1759 | for (Loop *SubLoop : LoopsToSimplify) |
| 1760 | simplifyLoop(L: SubLoop, DT, LI, SE, AC, MSSAU: nullptr, PreserveLCSSA); |
| 1761 | } |
| 1762 | |
| 1763 | return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled |
| 1764 | : LoopUnrollResult::PartiallyUnrolled; |
| 1765 | } |
| 1766 | |
| 1767 | /// Given an llvm.loop loop id metadata node, returns the loop hint metadata |
| 1768 | /// node with the given name (for example, "llvm.loop.unroll.count"). If no |
| 1769 | /// such metadata node exists, then nullptr is returned. |
| 1770 | MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) { |
| 1771 | // First operand should refer to the loop id itself. |
| 1772 | assert(LoopID->getNumOperands() > 0 && "requires at least one operand" ); |
| 1773 | assert(LoopID->getOperand(0) == LoopID && "invalid loop id" ); |
| 1774 | |
| 1775 | for (const MDOperand &MDO : llvm::drop_begin(RangeOrContainer: LoopID->operands())) { |
| 1776 | MDNode *MD = dyn_cast<MDNode>(Val: MDO); |
| 1777 | if (!MD) |
| 1778 | continue; |
| 1779 | |
| 1780 | MDString *S = dyn_cast<MDString>(Val: MD->getOperand(I: 0)); |
| 1781 | if (!S) |
| 1782 | continue; |
| 1783 | |
| 1784 | if (Name == S->getString()) |
| 1785 | return MD; |
| 1786 | } |
| 1787 | return nullptr; |
| 1788 | } |
| 1789 | |
| 1790 | // Returns the loop hint metadata node with the given name (for example, |
| 1791 | // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is |
| 1792 | // returned. |
| 1793 | MDNode *llvm::getUnrollMetadataForLoop(const Loop *L, StringRef Name) { |
| 1794 | if (MDNode *LoopID = L->getLoopID()) |
| 1795 | return GetUnrollMetadata(LoopID, Name); |
| 1796 | return nullptr; |
| 1797 | } |
| 1798 | |
| 1799 | std::optional<RecurrenceDescriptor> |
| 1800 | llvm::canParallelizeReductionWhenUnrolling(PHINode &Phi, Loop *L, |
| 1801 | ScalarEvolution *SE) { |
| 1802 | RecurrenceDescriptor RdxDesc; |
| 1803 | if (!RecurrenceDescriptor::isReductionPHI(Phi: &Phi, TheLoop: L, RedDes&: RdxDesc, |
| 1804 | /*DemandedBits=*/DB: nullptr, |
| 1805 | /*AC=*/nullptr, /*DT=*/nullptr, SE)) |
| 1806 | return std::nullopt; |
| 1807 | if (RdxDesc.hasUsesOutsideReductionChain()) |
| 1808 | return std::nullopt; |
| 1809 | RecurKind RK = RdxDesc.getRecurrenceKind(); |
| 1810 | static const auto ValidRKs = { |
| 1811 | RecurKind::Add, RecurKind::Mul, RecurKind::Or, |
| 1812 | RecurKind::And, RecurKind::Xor, RecurKind::SMin, |
| 1813 | RecurKind::SMax, RecurKind::UMin, RecurKind::UMax, |
| 1814 | RecurKind::FAdd, RecurKind::FMul, RecurKind::FMin, |
| 1815 | RecurKind::FMax, RecurKind::FMinNum, RecurKind::FMaxNum, |
| 1816 | RecurKind::FMinimum, RecurKind::FMaximum, RecurKind::FMinimumNum, |
| 1817 | RecurKind::FMaximumNum, RecurKind::FMulAdd}; |
| 1818 | // Skip unsupported reductions, including sub, any-of and find-last. |
| 1819 | // TODO: Handle sub, any-of and find-last reductions. |
| 1820 | if (!any_of(Range: ValidRKs, P: equal_to(Arg&: RK))) |
| 1821 | return std::nullopt; |
| 1822 | |
| 1823 | if (RdxDesc.hasExactFPMath()) |
| 1824 | return std::nullopt; |
| 1825 | |
| 1826 | if (RdxDesc.IntermediateStore) |
| 1827 | return std::nullopt; |
| 1828 | |
| 1829 | BasicBlock *Latch = L->getLoopLatch(); |
| 1830 | if (!Latch) |
| 1831 | return std::nullopt; |
| 1832 | Instruction *LatchInst = |
| 1833 | cast<Instruction>(Val: Phi.getIncomingValueForBlock(BB: Latch)); |
| 1834 | // Don't unroll reductions with constant ops; those can be folded to a |
| 1835 | // single induction update. For calls (e.g. fmuladd or min/max |
| 1836 | // intrinsics), the called function is itself a Constant operand and is |
| 1837 | // not a reduction operand, so restrict the check to the argument list. |
| 1838 | auto Ops = isa<CallBase>(Val: LatchInst) ? cast<CallBase>(Val: LatchInst)->args() |
| 1839 | : LatchInst->operands(); |
| 1840 | if (any_of(Range&: Ops, P: IsaPred<Constant>)) |
| 1841 | return std::nullopt; |
| 1842 | |
| 1843 | if (!is_contained(Range: LatchInst->operands(), Element: &Phi)) |
| 1844 | return std::nullopt; |
| 1845 | |
| 1846 | return RdxDesc; |
| 1847 | } |
| 1848 | |