Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 1 | //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements some loop unrolling utilities for loops with run-time |
| 11 | // trip counts. See LoopUnroll.cpp for unrolling loops with compile-time |
| 12 | // trip counts. |
| 13 | // |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 14 | // The functions in this file are used to generate extra code when the |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 15 | // run-time trip count modulo the unroll factor is not 0. When this is the |
| 16 | // case, we need to generate code to execute these 'left over' iterations. |
| 17 | // |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 18 | // The current strategy generates an if-then-else sequence prior to the |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 19 | // unrolled loop to execute the 'left over' iterations before or after the |
| 20 | // unrolled loop. |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 21 | // |
| 22 | //===----------------------------------------------------------------------===// |
| 23 | |
Florian Hahn | a1cc848 | 2018-06-12 11:16:56 +0000 | [diff] [blame] | 24 | #include "llvm/ADT/SmallPtrSet.h" |
David Blaikie | a373d18 | 2018-03-28 17:44:36 +0000 | [diff] [blame] | 25 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | b5797b6 | 2015-01-18 09:21:15 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/AliasAnalysis.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/LoopIterator.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 28 | #include "llvm/Analysis/ScalarEvolution.h" |
| 29 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 30 | #include "llvm/IR/BasicBlock.h" |
Chandler Carruth | 32c52c7 | 2015-01-18 02:39:37 +0000 | [diff] [blame] | 31 | #include "llvm/IR/Dominators.h" |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 32 | #include "llvm/IR/Metadata.h" |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 33 | #include "llvm/IR/Module.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 34 | #include "llvm/Support/Debug.h" |
| 35 | #include "llvm/Support/raw_ostream.h" |
David Blaikie | a373d18 | 2018-03-28 17:44:36 +0000 | [diff] [blame] | 36 | #include "llvm/Transforms/Utils.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 37 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 38 | #include "llvm/Transforms/Utils/Cloning.h" |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 39 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 40 | #include "llvm/Transforms/Utils/UnrollLoop.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 41 | #include <algorithm> |
| 42 | |
| 43 | using namespace llvm; |
| 44 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 45 | #define DEBUG_TYPE "loop-unroll" |
| 46 | |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 47 | STATISTIC(NumRuntimeUnrolled, |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 48 | "Number of loops unrolled with run-time trip counts"); |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 49 | static cl::opt<bool> UnrollRuntimeMultiExit( |
| 50 | "unroll-runtime-multi-exit", cl::init(false), cl::Hidden, |
| 51 | cl::desc("Allow runtime unrolling for loops with multiple exits, when " |
| 52 | "epilog is generated")); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 53 | |
| 54 | /// Connect the unrolling prolog code to the original loop. |
| 55 | /// The unrolling prolog code contains code to execute the |
| 56 | /// 'extra' iterations if the run-time trip count modulo the |
| 57 | /// unroll count is non-zero. |
| 58 | /// |
| 59 | /// This function performs the following: |
| 60 | /// - Create PHI nodes at prolog end block to combine values |
| 61 | /// that exit the prolog code and jump around the prolog. |
| 62 | /// - Add a PHI operand to a PHI node at the loop exit block |
| 63 | /// for values that exit the prolog and go around the loop. |
| 64 | /// - Branch around the original loop if the trip count is less |
| 65 | /// than the unroll factor. |
| 66 | /// |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 67 | static void ConnectProlog(Loop *L, Value *BECount, unsigned Count, |
Anna Thomas | 734ab3f | 2017-07-07 18:05:28 +0000 | [diff] [blame] | 68 | BasicBlock *PrologExit, |
| 69 | BasicBlock *OriginalLoopLatchExit, |
| 70 | BasicBlock *PreHeader, BasicBlock *NewPreHeader, |
| 71 | ValueToValueMapTy &VMap, DominatorTree *DT, |
| 72 | LoopInfo *LI, bool PreserveLCSSA) { |
Anna Thomas | 18be3cb | 2018-12-21 19:45:05 +0000 | [diff] [blame] | 73 | // Loop structure should be the following: |
| 74 | // Preheader |
Anna Thomas | 98743fa | 2018-12-28 18:52:16 +0000 | [diff] [blame] | 75 | // PrologHeader |
Anna Thomas | 18be3cb | 2018-12-21 19:45:05 +0000 | [diff] [blame] | 76 | // ... |
| 77 | // PrologLatch |
| 78 | // PrologExit |
| 79 | // NewPreheader |
| 80 | // Header |
| 81 | // ... |
| 82 | // Latch |
| 83 | // LatchExit |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 84 | BasicBlock *Latch = L->getLoopLatch(); |
Craig Topper | e73658d | 2014-04-28 04:05:08 +0000 | [diff] [blame] | 85 | assert(Latch && "Loop must have a latch"); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 86 | BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 87 | |
| 88 | // Create a PHI node for each outgoing value from the original loop |
| 89 | // (which means it is an outgoing value from the prolog code too). |
| 90 | // The new PHI node is inserted in the prolog end basic block. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 91 | // The new PHI node value is added as an operand of a PHI node in either |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 92 | // the loop header or the loop exit block. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 93 | for (BasicBlock *Succ : successors(Latch)) { |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 94 | for (PHINode &PN : Succ->phis()) { |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 95 | // Add a new PHI node to the prolog end block and add the |
| 96 | // appropriate incoming values. |
Anna Thomas | 18be3cb | 2018-12-21 19:45:05 +0000 | [diff] [blame] | 97 | // TODO: This code assumes that the PrologExit (or the LatchExit block for |
| 98 | // prolog loop) contains only one predecessor from the loop, i.e. the |
| 99 | // PrologLatch. When supporting multiple-exiting block loops, we can have |
| 100 | // two or more blocks that have the LatchExit as the target in the |
| 101 | // original loop. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 102 | PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr", |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 103 | PrologExit->getFirstNonPHI()); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 104 | // Adding a value to the new PHI node from the original loop preheader. |
| 105 | // This is the value that skips all the prolog code. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 106 | if (L->contains(&PN)) { |
Anna Thomas | 18be3cb | 2018-12-21 19:45:05 +0000 | [diff] [blame] | 107 | // Succ is loop header. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 108 | NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 109 | PreHeader); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 110 | } else { |
Anna Thomas | 98743fa | 2018-12-28 18:52:16 +0000 | [diff] [blame] | 111 | // Succ is LatchExit. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 112 | NewPN->addIncoming(UndefValue::get(PN.getType()), PreHeader); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 113 | } |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 114 | |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 115 | Value *V = PN.getIncomingValueForBlock(Latch); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 116 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 117 | if (L->contains(I)) { |
Duncan P. N. Exon Smith | a71301b | 2016-04-17 19:26:49 +0000 | [diff] [blame] | 118 | V = VMap.lookup(I); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 119 | } |
| 120 | } |
| 121 | // Adding a value to the new PHI node from the last prolog block |
| 122 | // that was created. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 123 | NewPN->addIncoming(V, PrologLatch); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 124 | |
| 125 | // Update the existing PHI node operand with the value from the |
| 126 | // new PHI node. How this is done depends on if the existing |
| 127 | // PHI node is in the original loop block, or the exit block. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 128 | if (L->contains(&PN)) { |
| 129 | PN.setIncomingValue(PN.getBasicBlockIndex(NewPreHeader), NewPN); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 130 | } else { |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 131 | PN.addIncoming(NewPN, PrologExit); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
Michael Zolotukhin | d9b6ad3 | 2016-08-02 19:19:31 +0000 | [diff] [blame] | 136 | // Make sure that created prolog loop is in simplified form |
| 137 | SmallVector<BasicBlock *, 4> PrologExitPreds; |
| 138 | Loop *PrologLoop = LI->getLoopFor(PrologLatch); |
| 139 | if (PrologLoop) { |
| 140 | for (BasicBlock *PredBB : predecessors(PrologExit)) |
| 141 | if (PrologLoop->contains(PredBB)) |
| 142 | PrologExitPreds.push_back(PredBB); |
| 143 | |
| 144 | SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI, |
Alina Sbirlea | ab6f84f7 | 2018-08-21 23:32:03 +0000 | [diff] [blame] | 145 | nullptr, PreserveLCSSA); |
Michael Zolotukhin | d9b6ad3 | 2016-08-02 19:19:31 +0000 | [diff] [blame] | 146 | } |
| 147 | |
Sanjay Patel | e08381a | 2016-02-08 19:27:33 +0000 | [diff] [blame] | 148 | // Create a branch around the original loop, which is taken if there are no |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 149 | // iterations remaining to be executed after running the prologue. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 150 | Instruction *InsertPt = PrologExit->getTerminator(); |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 151 | IRBuilder<> B(InsertPt); |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 152 | |
| 153 | assert(Count != 0 && "nonsensical Count!"); |
| 154 | |
David L Kreitzer | 8d441eb | 2016-03-25 14:24:52 +0000 | [diff] [blame] | 155 | // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1) |
| 156 | // This means %xtraiter is (BECount + 1) and all of the iterations of this |
| 157 | // loop were executed by the prologue. Note that if BECount <u (Count - 1) |
| 158 | // then (BECount + 1) cannot unsigned-overflow. |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 159 | Value *BrLoopExit = |
| 160 | B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1)); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 161 | // Split the exit to maintain loop canonicalization guarantees |
Anna Thomas | 734ab3f | 2017-07-07 18:05:28 +0000 | [diff] [blame] | 162 | SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit)); |
| 163 | SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI, |
Alina Sbirlea | ab6f84f7 | 2018-08-21 23:32:03 +0000 | [diff] [blame] | 164 | nullptr, PreserveLCSSA); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 165 | // Add the branch to the exit block (around the unrolled loop) |
Anna Thomas | 734ab3f | 2017-07-07 18:05:28 +0000 | [diff] [blame] | 166 | B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 167 | InsertPt->eraseFromParent(); |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 168 | if (DT) |
Anna Thomas | 734ab3f | 2017-07-07 18:05:28 +0000 | [diff] [blame] | 169 | DT->changeImmediateDominator(OriginalLoopLatchExit, PrologExit); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 170 | } |
| 171 | |
| 172 | /// Connect the unrolling epilog code to the original loop. |
| 173 | /// The unrolling epilog code contains code to execute the |
| 174 | /// 'extra' iterations if the run-time trip count modulo the |
| 175 | /// unroll count is non-zero. |
| 176 | /// |
| 177 | /// This function performs the following: |
| 178 | /// - Update PHI nodes at the unrolling loop exit and epilog loop exit |
| 179 | /// - Create PHI nodes at the unrolling loop exit to combine |
| 180 | /// values that exit the unrolling loop code and jump around it. |
| 181 | /// - Update PHI operands in the epilog loop by the new PHI nodes |
| 182 | /// - Branch around the epilog loop if extra iters (ModVal) is zero. |
| 183 | /// |
| 184 | static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit, |
| 185 | BasicBlock *Exit, BasicBlock *PreHeader, |
| 186 | BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader, |
| 187 | ValueToValueMapTy &VMap, DominatorTree *DT, |
| 188 | LoopInfo *LI, bool PreserveLCSSA) { |
| 189 | BasicBlock *Latch = L->getLoopLatch(); |
| 190 | assert(Latch && "Loop must have a latch"); |
| 191 | BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]); |
| 192 | |
| 193 | // Loop structure should be the following: |
| 194 | // |
| 195 | // PreHeader |
| 196 | // NewPreHeader |
| 197 | // Header |
| 198 | // ... |
| 199 | // Latch |
| 200 | // NewExit (PN) |
| 201 | // EpilogPreHeader |
| 202 | // EpilogHeader |
| 203 | // ... |
| 204 | // EpilogLatch |
| 205 | // Exit (EpilogPN) |
| 206 | |
| 207 | // Update PHI nodes at NewExit and Exit. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 208 | for (PHINode &PN : NewExit->phis()) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 209 | // PN should be used in another PHI located in Exit block as |
| 210 | // Exit was split by SplitBlockPredecessors into Exit and NewExit |
| 211 | // Basicaly it should look like: |
| 212 | // NewExit: |
| 213 | // PN = PHI [I, Latch] |
| 214 | // ... |
| 215 | // Exit: |
| 216 | // EpilogPN = PHI [PN, EpilogPreHeader] |
| 217 | // |
| 218 | // There is EpilogPreHeader incoming block instead of NewExit as |
| 219 | // NewExit was spilt 1 more time to get EpilogPreHeader. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 220 | assert(PN.hasOneUse() && "The phi should have 1 use"); |
| 221 | PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser()); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 222 | assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block"); |
| 223 | |
| 224 | // Add incoming PreHeader from branch around the Loop |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 225 | PN.addIncoming(UndefValue::get(PN.getType()), PreHeader); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 226 | |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 227 | Value *V = PN.getIncomingValueForBlock(Latch); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 228 | Instruction *I = dyn_cast<Instruction>(V); |
| 229 | if (I && L->contains(I)) |
| 230 | // If value comes from an instruction in the loop add VMap value. |
Duncan P. N. Exon Smith | a71301b | 2016-04-17 19:26:49 +0000 | [diff] [blame] | 231 | V = VMap.lookup(I); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 232 | // For the instruction out of the loop, constant or undefined value |
| 233 | // insert value itself. |
| 234 | EpilogPN->addIncoming(V, EpilogLatch); |
| 235 | |
| 236 | assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 && |
| 237 | "EpilogPN should have EpilogPreHeader incoming block"); |
| 238 | // Change EpilogPreHeader incoming block to NewExit. |
| 239 | EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader), |
| 240 | NewExit); |
| 241 | // Now PHIs should look like: |
| 242 | // NewExit: |
| 243 | // PN = PHI [I, Latch], [undef, PreHeader] |
| 244 | // ... |
| 245 | // Exit: |
| 246 | // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch] |
| 247 | } |
| 248 | |
| 249 | // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader). |
| 250 | // Update corresponding PHI nodes in epilog loop. |
| 251 | for (BasicBlock *Succ : successors(Latch)) { |
| 252 | // Skip this as we already updated phis in exit blocks. |
| 253 | if (!L->contains(Succ)) |
| 254 | continue; |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 255 | for (PHINode &PN : Succ->phis()) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 256 | // Add new PHI nodes to the loop exit block and update epilog |
| 257 | // PHIs with the new PHI values. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 258 | PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr", |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 259 | NewExit->getFirstNonPHI()); |
| 260 | // Adding a value to the new PHI node from the unrolling loop preheader. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 261 | NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 262 | // Adding a value to the new PHI node from the unrolling loop latch. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 263 | NewPN->addIncoming(PN.getIncomingValueForBlock(Latch), Latch); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 264 | |
| 265 | // Update the existing PHI node operand with the value from the new PHI |
| 266 | // node. Corresponding instruction in epilog loop should be PHI. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 267 | PHINode *VPN = cast<PHINode>(VMap[&PN]); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 268 | VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN); |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | Instruction *InsertPt = NewExit->getTerminator(); |
| 273 | IRBuilder<> B(InsertPt); |
Evgeny Stupachenko | 23ce61b | 2016-04-27 03:04:54 +0000 | [diff] [blame] | 274 | Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod"); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 275 | assert(Exit && "Loop must have a single exit block only"); |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 276 | // Split the epilogue exit to maintain loop canonicalization guarantees |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 277 | SmallVector<BasicBlock*, 4> Preds(predecessors(Exit)); |
Alina Sbirlea | ab6f84f7 | 2018-08-21 23:32:03 +0000 | [diff] [blame] | 278 | SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr, |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 279 | PreserveLCSSA); |
| 280 | // Add the branch to the exit block (around the unrolling loop) |
| 281 | B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 282 | InsertPt->eraseFromParent(); |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 283 | if (DT) |
| 284 | DT->changeImmediateDominator(Exit, NewExit); |
| 285 | |
| 286 | // Split the main loop exit to maintain canonicalization guarantees. |
| 287 | SmallVector<BasicBlock*, 4> NewExitPreds{Latch}; |
Alina Sbirlea | ab6f84f7 | 2018-08-21 23:32:03 +0000 | [diff] [blame] | 288 | SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, nullptr, |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 289 | PreserveLCSSA); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 290 | } |
| 291 | |
| 292 | /// Create a clone of the blocks in a loop and connect them together. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 293 | /// If CreateRemainderLoop is false, loop structure will not be cloned, |
| 294 | /// otherwise a new loop will be created including all cloned blocks, and the |
| 295 | /// iterator of it switches to count NewIter down to 0. |
| 296 | /// The cloned blocks should be inserted between InsertTop and InsertBot. |
| 297 | /// If loop structure is cloned InsertTop should be new preheader, InsertBot |
| 298 | /// new loop exit. |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 299 | /// Return the new cloned loop that is created when CreateRemainderLoop is true. |
| 300 | static Loop * |
| 301 | CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop, |
Sam Parker | 718c8a6 | 2017-08-14 09:25:26 +0000 | [diff] [blame] | 302 | const bool UseEpilogRemainder, const bool UnrollRemainder, |
| 303 | BasicBlock *InsertTop, |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 304 | BasicBlock *InsertBot, BasicBlock *Preheader, |
| 305 | std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks, |
| 306 | ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 307 | StringRef suffix = UseEpilogRemainder ? "epil" : "prol"; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 308 | BasicBlock *Header = L->getHeader(); |
| 309 | BasicBlock *Latch = L->getLoopLatch(); |
| 310 | Function *F = Header->getParent(); |
| 311 | LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); |
| 312 | LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 313 | Loop *ParentLoop = L->getParentLoop(); |
Florian Hahn | 4f9d6d5 | 2017-01-10 23:43:35 +0000 | [diff] [blame] | 314 | NewLoopsMap NewLoops; |
Florian Hahn | 5364cf3 | 2017-01-31 11:13:44 +0000 | [diff] [blame] | 315 | NewLoops[ParentLoop] = ParentLoop; |
| 316 | if (!CreateRemainderLoop) |
Michael Kuperstein | 5dd55e8 | 2017-01-26 01:04:11 +0000 | [diff] [blame] | 317 | NewLoops[L] = ParentLoop; |
| 318 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 319 | // For each block in the original loop, create a new copy, |
| 320 | // and update the value map with the newly created values. |
| 321 | for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 322 | BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 323 | NewBlocks.push_back(NewBB); |
Florian Hahn | 5364cf3 | 2017-01-31 11:13:44 +0000 | [diff] [blame] | 324 | |
Michael Kuperstein | 5dd55e8 | 2017-01-26 01:04:11 +0000 | [diff] [blame] | 325 | // If we're unrolling the outermost loop, there's no remainder loop, |
| 326 | // and this block isn't in a nested loop, then the new block is not |
| 327 | // in any loop. Otherwise, add it to loopinfo. |
| 328 | if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop) |
Florian Hahn | 4f9d6d5 | 2017-01-10 23:43:35 +0000 | [diff] [blame] | 329 | addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 330 | |
| 331 | VMap[*BB] = NewBB; |
| 332 | if (Header == *BB) { |
| 333 | // For the first block, add a CFG connection to this newly |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 334 | // created block. |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 335 | InsertTop->getTerminator()->setSuccessor(0, NewBB); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 336 | } |
Junmo Park | 502ff66 | 2016-01-28 01:23:18 +0000 | [diff] [blame] | 337 | |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 338 | if (DT) { |
| 339 | if (Header == *BB) { |
| 340 | // The header is dominated by the preheader. |
| 341 | DT->addNewBlock(NewBB, InsertTop); |
| 342 | } else { |
| 343 | // Copy information from original loop to unrolled loop. |
| 344 | BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock(); |
| 345 | DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB])); |
| 346 | } |
| 347 | } |
| 348 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 349 | if (Latch == *BB) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 350 | // For the last block, if CreateRemainderLoop is false, create a direct |
| 351 | // jump to InsertBot. If not, create a loop back to cloned head. |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 352 | VMap.erase((*BB)->getTerminator()); |
| 353 | BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]); |
| 354 | BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator()); |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 355 | IRBuilder<> Builder(LatchBR); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 356 | if (!CreateRemainderLoop) { |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 357 | Builder.CreateBr(InsertBot); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 358 | } else { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 359 | PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, |
| 360 | suffix + ".iter", |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 361 | FirstLoopBB->getFirstNonPHI()); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 362 | Value *IdxSub = |
| 363 | Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), |
| 364 | NewIdx->getName() + ".sub"); |
| 365 | Value *IdxCmp = |
| 366 | Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp"); |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 367 | Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 368 | NewIdx->addIncoming(NewIter, InsertTop); |
| 369 | NewIdx->addIncoming(IdxSub, NewBB); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 370 | } |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 371 | LatchBR->eraseFromParent(); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 372 | } |
| 373 | } |
| 374 | |
| 375 | // Change the incoming values to the ones defined in the preheader or |
| 376 | // cloned loop. |
| 377 | for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 378 | PHINode *NewPHI = cast<PHINode>(VMap[&*I]); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 379 | if (!CreateRemainderLoop) { |
| 380 | if (UseEpilogRemainder) { |
| 381 | unsigned idx = NewPHI->getBasicBlockIndex(Preheader); |
| 382 | NewPHI->setIncomingBlock(idx, InsertTop); |
| 383 | NewPHI->removeIncomingValue(Latch, false); |
| 384 | } else { |
| 385 | VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader); |
| 386 | cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); |
| 387 | } |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 388 | } else { |
| 389 | unsigned idx = NewPHI->getBasicBlockIndex(Preheader); |
| 390 | NewPHI->setIncomingBlock(idx, InsertTop); |
| 391 | BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); |
| 392 | idx = NewPHI->getBasicBlockIndex(Latch); |
| 393 | Value *InVal = NewPHI->getIncomingValue(idx); |
| 394 | NewPHI->setIncomingBlock(idx, NewLatch); |
Duncan P. N. Exon Smith | a71301b | 2016-04-17 19:26:49 +0000 | [diff] [blame] | 395 | if (Value *V = VMap.lookup(InVal)) |
| 396 | NewPHI->setIncomingValue(idx, V); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 397 | } |
| 398 | } |
Florian Hahn | 5364cf3 | 2017-01-31 11:13:44 +0000 | [diff] [blame] | 399 | if (CreateRemainderLoop) { |
| 400 | Loop *NewLoop = NewLoops[L]; |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 401 | MDNode *LoopID = NewLoop->getLoopID(); |
Florian Hahn | 5364cf3 | 2017-01-31 11:13:44 +0000 | [diff] [blame] | 402 | assert(NewLoop && "L should have been cloned"); |
Sam Parker | 7cd826a | 2017-09-04 08:12:16 +0000 | [diff] [blame] | 403 | |
| 404 | // Only add loop metadata if the loop is not going to be completely |
| 405 | // unrolled. |
| 406 | if (UnrollRemainder) |
| 407 | return NewLoop; |
| 408 | |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 409 | Optional<MDNode *> NewLoopID = makeFollowupLoopID( |
| 410 | LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder}); |
| 411 | if (NewLoopID.hasValue()) { |
| 412 | NewLoop->setLoopID(NewLoopID.getValue()); |
| 413 | |
| 414 | // Do not setLoopAlreadyUnrolled if loop attributes have been defined |
| 415 | // explicitly. |
| 416 | return NewLoop; |
| 417 | } |
| 418 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 419 | // Add unroll disable metadata to disable future unrolling for this loop. |
Hongbin Zheng | 73f6504 | 2017-10-15 07:31:02 +0000 | [diff] [blame] | 420 | NewLoop->setLoopAlreadyUnrolled(); |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 421 | return NewLoop; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 422 | } |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 423 | else |
| 424 | return nullptr; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 425 | } |
| 426 | |
Anna Thomas | 8e431a9 | 2017-07-12 20:55:43 +0000 | [diff] [blame] | 427 | /// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits |
| 428 | /// is populated with all the loop exit blocks other than the LatchExit block. |
| 429 | static bool |
| 430 | canSafelyUnrollMultiExitLoop(Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, |
| 431 | BasicBlock *LatchExit, bool PreserveLCSSA, |
| 432 | bool UseEpilogRemainder) { |
| 433 | |
Anna Thomas | 5c07a4c | 2017-07-21 16:30:38 +0000 | [diff] [blame] | 434 | // We currently have some correctness constrains in unrolling a multi-exit |
| 435 | // loop. Check for these below. |
| 436 | |
Anna Thomas | 8e431a9 | 2017-07-12 20:55:43 +0000 | [diff] [blame] | 437 | // We rely on LCSSA form being preserved when the exit blocks are transformed. |
| 438 | if (!PreserveLCSSA) |
| 439 | return false; |
| 440 | SmallVector<BasicBlock *, 4> Exits; |
| 441 | L->getUniqueExitBlocks(Exits); |
| 442 | for (auto *BB : Exits) |
| 443 | if (BB != LatchExit) |
| 444 | OtherExits.push_back(BB); |
| 445 | |
| 446 | // TODO: Support multiple exiting blocks jumping to the `LatchExit` when |
| 447 | // UnrollRuntimeMultiExit is true. This will need updating the logic in |
| 448 | // connectEpilog/connectProlog. |
| 449 | if (!LatchExit->getSinglePredecessor()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 450 | LLVM_DEBUG( |
| 451 | dbgs() << "Bailout for multi-exit handling when latch exit has >1 " |
| 452 | "predecessor.\n"); |
Anna Thomas | 8e431a9 | 2017-07-12 20:55:43 +0000 | [diff] [blame] | 453 | return false; |
| 454 | } |
| 455 | // FIXME: We bail out of multi-exit unrolling when epilog loop is generated |
| 456 | // and L is an inner loop. This is because in presence of multiple exits, the |
| 457 | // outer loop is incorrect: we do not add the EpilogPreheader and exit to the |
| 458 | // outer loop. This is automatically handled in the prolog case, so we do not |
| 459 | // have that bug in prolog generation. |
| 460 | if (UseEpilogRemainder && L->getParentLoop()) |
| 461 | return false; |
| 462 | |
| 463 | // All constraints have been satisfied. |
| 464 | return true; |
| 465 | } |
| 466 | |
Anna Thomas | 5c07a4c | 2017-07-21 16:30:38 +0000 | [diff] [blame] | 467 | /// Returns true if we can profitably unroll the multi-exit loop L. Currently, |
| 468 | /// we return true only if UnrollRuntimeMultiExit is set to true. |
| 469 | static bool canProfitablyUnrollMultiExitLoop( |
| 470 | Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit, |
| 471 | bool PreserveLCSSA, bool UseEpilogRemainder) { |
Anna Thomas | 8e431a9 | 2017-07-12 20:55:43 +0000 | [diff] [blame] | 472 | |
Anna Thomas | 5c07a4c | 2017-07-21 16:30:38 +0000 | [diff] [blame] | 473 | #if !defined(NDEBUG) |
| 474 | SmallVector<BasicBlock *, 8> OtherExitsDummyCheck; |
| 475 | assert(canSafelyUnrollMultiExitLoop(L, OtherExitsDummyCheck, LatchExit, |
| 476 | PreserveLCSSA, UseEpilogRemainder) && |
| 477 | "Should be safe to unroll before checking profitability!"); |
| 478 | #endif |
Anna Thomas | f34537d | 2017-09-15 15:56:05 +0000 | [diff] [blame] | 479 | |
Anna Thomas | 5c07a4c | 2017-07-21 16:30:38 +0000 | [diff] [blame] | 480 | // Priority goes to UnrollRuntimeMultiExit if it's supplied. |
Anna Thomas | f34537d | 2017-09-15 15:56:05 +0000 | [diff] [blame] | 481 | if (UnrollRuntimeMultiExit.getNumOccurrences()) |
| 482 | return UnrollRuntimeMultiExit; |
| 483 | |
| 484 | // The main pain point with multi-exit loop unrolling is that once unrolled, |
| 485 | // we will not be able to merge all blocks into a straight line code. |
| 486 | // There are branches within the unrolled loop that go to the OtherExits. |
| 487 | // The second point is the increase in code size, but this is true |
| 488 | // irrespective of multiple exits. |
| 489 | |
| 490 | // Note: Both the heuristics below are coarse grained. We are essentially |
| 491 | // enabling unrolling of loops that have a single side exit other than the |
| 492 | // normal LatchExit (i.e. exiting into a deoptimize block). |
| 493 | // The heuristics considered are: |
| 494 | // 1. low number of branches in the unrolled version. |
| 495 | // 2. high predictability of these extra branches. |
| 496 | // We avoid unrolling loops that have more than two exiting blocks. This |
| 497 | // limits the total number of branches in the unrolled loop to be atmost |
| 498 | // the unroll factor (since one of the exiting blocks is the latch block). |
| 499 | SmallVector<BasicBlock*, 4> ExitingBlocks; |
| 500 | L->getExitingBlocks(ExitingBlocks); |
| 501 | if (ExitingBlocks.size() > 2) |
| 502 | return false; |
| 503 | |
| 504 | // The second heuristic is that L has one exit other than the latchexit and |
| 505 | // that exit is a deoptimize block. We know that deoptimize blocks are rarely |
| 506 | // taken, which also implies the branch leading to the deoptimize block is |
| 507 | // highly predictable. |
| 508 | return (OtherExits.size() == 1 && |
| 509 | OtherExits[0]->getTerminatingDeoptimizeCall()); |
| 510 | // TODO: These can be fine-tuned further to consider code size or deopt states |
| 511 | // that are captured by the deoptimize exit block. |
| 512 | // Also, we can extend this to support more cases, if we actually |
| 513 | // know of kinds of multiexit loops that would benefit from unrolling. |
Anna Thomas | 5c07a4c | 2017-07-21 16:30:38 +0000 | [diff] [blame] | 514 | } |
Anna Thomas | 8e431a9 | 2017-07-12 20:55:43 +0000 | [diff] [blame] | 515 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 516 | /// Insert code in the prolog/epilog code when unrolling a loop with a |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 517 | /// run-time trip-count. |
| 518 | /// |
| 519 | /// This method assumes that the loop unroll factor is total number |
Justin Lebar | 6086c6a | 2016-02-12 21:01:37 +0000 | [diff] [blame] | 520 | /// of loop bodies in the loop after unrolling. (Some folks refer |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 521 | /// to the unroll factor as the number of *extra* copies added). |
| 522 | /// We assume also that the loop unroll factor is a power-of-two. So, after |
| 523 | /// unrolling the loop, the number of loop bodies executed is 2, |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 524 | /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 525 | /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for |
| 526 | /// the switch instruction is generated. |
| 527 | /// |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 528 | /// ***Prolog case*** |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 529 | /// extraiters = tripcount % loopfactor |
| 530 | /// if (extraiters == 0) jump Loop: |
Evgeny Stupachenko | 8788048 | 2016-04-08 20:20:38 +0000 | [diff] [blame] | 531 | /// else jump Prol: |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 532 | /// Prol: LoopBody; |
| 533 | /// extraiters -= 1 // Omitted if unroll factor is 2. |
| 534 | /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2. |
Evgeny Stupachenko | 8788048 | 2016-04-08 20:20:38 +0000 | [diff] [blame] | 535 | /// if (tripcount < loopfactor) jump End: |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 536 | /// Loop: |
| 537 | /// ... |
| 538 | /// End: |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 539 | /// |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 540 | /// ***Epilog case*** |
| 541 | /// extraiters = tripcount % loopfactor |
Evgeny Stupachenko | 23ce61b | 2016-04-27 03:04:54 +0000 | [diff] [blame] | 542 | /// if (tripcount < loopfactor) jump LoopExit: |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 543 | /// unroll_iters = tripcount - extraiters |
| 544 | /// Loop: LoopBody; (executes unroll_iter times); |
| 545 | /// unroll_iter -= 1 |
| 546 | /// if (unroll_iter != 0) jump Loop: |
| 547 | /// LoopExit: |
| 548 | /// if (extraiters == 0) jump EpilExit: |
| 549 | /// Epil: LoopBody; (executes extraiters times) |
| 550 | /// extraiters -= 1 // Omitted if unroll factor is 2. |
| 551 | /// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2. |
| 552 | /// EpilExit: |
| 553 | |
| 554 | bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, |
| 555 | bool AllowExpensiveTripCount, |
| 556 | bool UseEpilogRemainder, |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 557 | bool UnrollRemainder, LoopInfo *LI, |
| 558 | ScalarEvolution *SE, DominatorTree *DT, |
| 559 | AssumptionCache *AC, bool PreserveLCSSA, |
| 560 | Loop **ResultLoop) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 561 | LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n"); |
| 562 | LLVM_DEBUG(L->dump()); |
| 563 | LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n" |
| 564 | : dbgs() << "Using prolog remainder.\n"); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 565 | |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 566 | // Make sure the loop is in canonical form. |
Anna Thomas | bafe766 | 2017-07-11 20:44:37 +0000 | [diff] [blame] | 567 | if (!L->isLoopSimplifyForm()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 568 | LLVM_DEBUG(dbgs() << "Not in simplify form!\n"); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 569 | return false; |
Anna Thomas | bafe766 | 2017-07-11 20:44:37 +0000 | [diff] [blame] | 570 | } |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 571 | |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 572 | // Guaranteed by LoopSimplifyForm. |
| 573 | BasicBlock *Latch = L->getLoopLatch(); |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 574 | BasicBlock *Header = L->getHeader(); |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 575 | |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 576 | BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator()); |
David Green | 9108c2b | 2018-09-25 10:08:47 +0000 | [diff] [blame] | 577 | |
| 578 | if (!LatchBR || LatchBR->isUnconditional()) { |
| 579 | // The loop-rotate pass can be helpful to avoid this in many cases. |
| 580 | LLVM_DEBUG( |
| 581 | dbgs() |
| 582 | << "Loop latch not terminated by a conditional branch.\n"); |
| 583 | return false; |
| 584 | } |
| 585 | |
Anna Thomas | 8e431a9 | 2017-07-12 20:55:43 +0000 | [diff] [blame] | 586 | unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0; |
| 587 | BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex); |
David Green | 9108c2b | 2018-09-25 10:08:47 +0000 | [diff] [blame] | 588 | |
| 589 | if (L->contains(LatchExit)) { |
| 590 | // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the |
| 591 | // targets of the Latch be an exit block out of the loop. |
| 592 | LLVM_DEBUG( |
| 593 | dbgs() |
| 594 | << "One of the loop latch successors must be the exit block.\n"); |
| 595 | return false; |
| 596 | } |
| 597 | |
Anna Thomas | 8e431a9 | 2017-07-12 20:55:43 +0000 | [diff] [blame] | 598 | // These are exit blocks other than the target of the latch exiting block. |
| 599 | SmallVector<BasicBlock *, 4> OtherExits; |
Anna Thomas | 5c07a4c | 2017-07-21 16:30:38 +0000 | [diff] [blame] | 600 | bool isMultiExitUnrollingEnabled = |
| 601 | canSafelyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA, |
| 602 | UseEpilogRemainder) && |
| 603 | canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA, |
| 604 | UseEpilogRemainder); |
Anna Thomas | 8e431a9 | 2017-07-12 20:55:43 +0000 | [diff] [blame] | 605 | // Support only single exit and exiting block unless multi-exit loop unrolling is enabled. |
| 606 | if (!isMultiExitUnrollingEnabled && |
| 607 | (!L->getExitingBlock() || OtherExits.size())) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 608 | LLVM_DEBUG( |
Anna Thomas | 8e431a9 | 2017-07-12 20:55:43 +0000 | [diff] [blame] | 609 | dbgs() |
| 610 | << "Multiple exit/exiting blocks in loop and multi-exit unrolling not " |
| 611 | "enabled!\n"); |
Anna Thomas | eb6d5d1 | 2017-07-06 18:39:26 +0000 | [diff] [blame] | 612 | return false; |
Anna Thomas | bafe766 | 2017-07-11 20:44:37 +0000 | [diff] [blame] | 613 | } |
Sanjay Patel | e08381a | 2016-02-08 19:27:33 +0000 | [diff] [blame] | 614 | // Use Scalar Evolution to compute the trip count. This allows more loops to |
| 615 | // be unrolled than relying on induction var simplification. |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 616 | if (!SE) |
Andrew Trick | d29cd73 | 2012-05-08 02:52:09 +0000 | [diff] [blame] | 617 | return false; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 618 | |
Sanjay Patel | e08381a | 2016-02-08 19:27:33 +0000 | [diff] [blame] | 619 | // Only unroll loops with a computable trip count, and the trip count needs |
| 620 | // to be an int value (allowing a pointer type is a TODO item). |
Anna Thomas | dc935a6 | 2017-06-27 14:14:35 +0000 | [diff] [blame] | 621 | // We calculate the backedge count by using getExitCount on the Latch block, |
| 622 | // which is proven to be the only exiting block in this loop. This is same as |
| 623 | // calculating getBackedgeTakenCount on the loop (which computes SCEV for all |
| 624 | // exiting blocks). |
| 625 | const SCEV *BECountSC = SE->getExitCount(L, Latch); |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 626 | if (isa<SCEVCouldNotCompute>(BECountSC) || |
Anna Thomas | bafe766 | 2017-07-11 20:44:37 +0000 | [diff] [blame] | 627 | !BECountSC->getType()->isIntegerTy()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 628 | LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n"); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 629 | return false; |
Anna Thomas | bafe766 | 2017-07-11 20:44:37 +0000 | [diff] [blame] | 630 | } |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 631 | |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 632 | unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth(); |
Michael Zolotukhin | 0dcae71 | 2014-11-20 20:19:55 +0000 | [diff] [blame] | 633 | |
Sanjay Patel | e08381a | 2016-02-08 19:27:33 +0000 | [diff] [blame] | 634 | // Add 1 since the backedge count doesn't include the first loop iteration. |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 635 | const SCEV *TripCountSC = |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 636 | SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1)); |
Anna Thomas | bafe766 | 2017-07-11 20:44:37 +0000 | [diff] [blame] | 637 | if (isa<SCEVCouldNotCompute>(TripCountSC)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 638 | LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n"); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 639 | return false; |
Anna Thomas | bafe766 | 2017-07-11 20:44:37 +0000 | [diff] [blame] | 640 | } |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 641 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 642 | BasicBlock *PreHeader = L->getLoopPreheader(); |
| 643 | BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator()); |
Sanjoy Das | e178f46 | 2015-04-14 03:20:38 +0000 | [diff] [blame] | 644 | const DataLayout &DL = Header->getModule()->getDataLayout(); |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 645 | SCEVExpander Expander(*SE, DL, "loop-unroll"); |
Junmo Park | 6ebdc14 | 2016-02-16 06:46:58 +0000 | [diff] [blame] | 646 | if (!AllowExpensiveTripCount && |
Anna Thomas | bafe766 | 2017-07-11 20:44:37 +0000 | [diff] [blame] | 647 | Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 648 | LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n"); |
Sanjoy Das | e178f46 | 2015-04-14 03:20:38 +0000 | [diff] [blame] | 649 | return false; |
Anna Thomas | bafe766 | 2017-07-11 20:44:37 +0000 | [diff] [blame] | 650 | } |
Sanjoy Das | e178f46 | 2015-04-14 03:20:38 +0000 | [diff] [blame] | 651 | |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 652 | // This constraint lets us deal with an overflowing trip count easily; see the |
Sanjoy Das | 71190fe | 2015-04-12 01:24:01 +0000 | [diff] [blame] | 653 | // comment on ModVal below. |
Anna Thomas | bafe766 | 2017-07-11 20:44:37 +0000 | [diff] [blame] | 654 | if (Log2_32(Count) > BEWidth) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 655 | LLVM_DEBUG( |
| 656 | dbgs() |
| 657 | << "Count failed constraint on overflow trip count calculation.\n"); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 658 | return false; |
Anna Thomas | bafe766 | 2017-07-11 20:44:37 +0000 | [diff] [blame] | 659 | } |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 660 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 661 | // Loop structure is the following: |
| 662 | // |
| 663 | // PreHeader |
| 664 | // Header |
| 665 | // ... |
| 666 | // Latch |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 667 | // LatchExit |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 668 | |
| 669 | BasicBlock *NewPreHeader; |
| 670 | BasicBlock *NewExit = nullptr; |
| 671 | BasicBlock *PrologExit = nullptr; |
| 672 | BasicBlock *EpilogPreHeader = nullptr; |
| 673 | BasicBlock *PrologPreHeader = nullptr; |
| 674 | |
| 675 | if (UseEpilogRemainder) { |
| 676 | // If epilog remainder |
| 677 | // Split PreHeader to insert a branch around loop for unrolling. |
| 678 | NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI); |
| 679 | NewPreHeader->setName(PreHeader->getName() + ".new"); |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 680 | // Split LatchExit to create phi nodes from branch above. |
| 681 | SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit)); |
Alina Sbirlea | ab6f84f7 | 2018-08-21 23:32:03 +0000 | [diff] [blame] | 682 | NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa", DT, LI, |
| 683 | nullptr, PreserveLCSSA); |
Zhaoshi Zheng | 8af1e1c | 2017-12-26 23:31:21 +0000 | [diff] [blame] | 684 | // NewExit gets its DebugLoc from LatchExit, which is not part of the |
| 685 | // original Loop. |
| 686 | // Fix this by setting Loop's DebugLoc to NewExit. |
| 687 | auto *NewExitTerminator = NewExit->getTerminator(); |
| 688 | NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc()); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 689 | // Split NewExit to insert epilog remainder loop. |
Zhaoshi Zheng | 8af1e1c | 2017-12-26 23:31:21 +0000 | [diff] [blame] | 690 | EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 691 | EpilogPreHeader->setName(Header->getName() + ".epil.preheader"); |
| 692 | } else { |
| 693 | // If prolog remainder |
| 694 | // Split the original preheader twice to insert prolog remainder loop |
| 695 | PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI); |
| 696 | PrologPreHeader->setName(Header->getName() + ".prol.preheader"); |
| 697 | PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(), |
| 698 | DT, LI); |
| 699 | PrologExit->setName(Header->getName() + ".prol.loopexit"); |
| 700 | // Split PrologExit to get NewPreHeader. |
| 701 | NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI); |
| 702 | NewPreHeader->setName(PreHeader->getName() + ".new"); |
| 703 | } |
| 704 | // Loop structure should be the following: |
| 705 | // Epilog Prolog |
| 706 | // |
| 707 | // PreHeader PreHeader |
| 708 | // *NewPreHeader *PrologPreHeader |
| 709 | // Header *PrologExit |
| 710 | // ... *NewPreHeader |
| 711 | // Latch Header |
| 712 | // *NewExit ... |
| 713 | // *EpilogPreHeader Latch |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 714 | // LatchExit LatchExit |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 715 | |
| 716 | // Calculate conditions for branch around loop for unrolling |
| 717 | // in epilog case and around prolog remainder loop in prolog case. |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 718 | // Compute the number of extra iterations required, which is: |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 719 | // extra iterations = run-time trip count % loop unroll factor |
| 720 | PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator()); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 721 | Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(), |
| 722 | PreHeaderBR); |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 723 | Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(), |
| 724 | PreHeaderBR); |
Benjamin Kramer | 0bf086f | 2014-06-21 13:46:25 +0000 | [diff] [blame] | 725 | IRBuilder<> B(PreHeaderBR); |
David L Kreitzer | 8d441eb | 2016-03-25 14:24:52 +0000 | [diff] [blame] | 726 | Value *ModVal; |
| 727 | // Calculate ModVal = (BECount + 1) % Count. |
| 728 | // Note that TripCount is BECount + 1. |
| 729 | if (isPowerOf2_32(Count)) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 730 | // When Count is power of 2 we don't BECount for epilog case, however we'll |
| 731 | // need it for a branch around unrolling loop for prolog case. |
David L Kreitzer | 8d441eb | 2016-03-25 14:24:52 +0000 | [diff] [blame] | 732 | ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter"); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 733 | // 1. There are no iterations to be run in the prolog/epilog loop. |
David L Kreitzer | 8d441eb | 2016-03-25 14:24:52 +0000 | [diff] [blame] | 734 | // OR |
| 735 | // 2. The addition computing TripCount overflowed. |
| 736 | // |
| 737 | // If (2) is true, we know that TripCount really is (1 << BEWidth) and so |
| 738 | // the number of iterations that remain to be run in the original loop is a |
| 739 | // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we |
| 740 | // explicitly check this above). |
| 741 | } else { |
| 742 | // As (BECount + 1) can potentially unsigned overflow we count |
| 743 | // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count. |
| 744 | Value *ModValTmp = B.CreateURem(BECount, |
| 745 | ConstantInt::get(BECount->getType(), |
| 746 | Count)); |
| 747 | Value *ModValAdd = B.CreateAdd(ModValTmp, |
| 748 | ConstantInt::get(ModValTmp->getType(), 1)); |
| 749 | // At that point (BECount % Count) + 1 could be equal to Count. |
| 750 | // To handle this case we need to take mod by Count one more time. |
| 751 | ModVal = B.CreateURem(ModValAdd, |
| 752 | ConstantInt::get(BECount->getType(), Count), |
| 753 | "xtraiter"); |
| 754 | } |
Evgeny Stupachenko | 23ce61b | 2016-04-27 03:04:54 +0000 | [diff] [blame] | 755 | Value *BranchVal = |
| 756 | UseEpilogRemainder ? B.CreateICmpULT(BECount, |
| 757 | ConstantInt::get(BECount->getType(), |
| 758 | Count - 1)) : |
| 759 | B.CreateIsNotNull(ModVal, "lcmp.mod"); |
| 760 | BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader; |
| 761 | BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit; |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 762 | // Branch to either remainder (extra iterations) loop or unrolling loop. |
Evgeny Stupachenko | 23ce61b | 2016-04-27 03:04:54 +0000 | [diff] [blame] | 763 | B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 764 | PreHeaderBR->eraseFromParent(); |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 765 | if (DT) { |
| 766 | if (UseEpilogRemainder) |
| 767 | DT->changeImmediateDominator(NewExit, PreHeader); |
| 768 | else |
| 769 | DT->changeImmediateDominator(PrologExit, PreHeader); |
| 770 | } |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 771 | Function *F = Header->getParent(); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 772 | // Get an ordered list of blocks in the loop to help with the ordering of the |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 773 | // cloned blocks in the prolog/epilog code |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 774 | LoopBlocksDFS LoopBlocks(L); |
| 775 | LoopBlocks.perform(LI); |
| 776 | |
| 777 | // |
| 778 | // For each extra loop iteration, create a copy of the loop's basic blocks |
| 779 | // and generate a condition that branches to the copy depending on the |
| 780 | // number of 'left over' iterations. |
| 781 | // |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 782 | std::vector<BasicBlock *> NewBlocks; |
| 783 | ValueToValueMapTy VMap; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 784 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 785 | // For unroll factor 2 remainder loop will have 1 iterations. |
| 786 | // Do not create 1 iteration loop. |
| 787 | bool CreateRemainderLoop = (Count != 2); |
Michael Zolotukhin | 0dcae71 | 2014-11-20 20:19:55 +0000 | [diff] [blame] | 788 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 789 | // Clone all the basic blocks in the loop. If Count is 2, we don't clone |
| 790 | // the loop, otherwise we create a cloned loop to execute the extra |
| 791 | // iterations. This function adds the appropriate CFG connections. |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 792 | BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit; |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 793 | BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader; |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 794 | Loop *remainderLoop = CloneLoopBlocks( |
Sam Parker | 718c8a6 | 2017-08-14 09:25:26 +0000 | [diff] [blame] | 795 | L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder, |
| 796 | InsertTop, InsertBot, |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 797 | NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 798 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 799 | // Insert the cloned blocks into the function. |
| 800 | F->getBasicBlockList().splice(InsertBot->getIterator(), |
| 801 | F->getBasicBlockList(), |
| 802 | NewBlocks[0]->getIterator(), |
| 803 | F->end()); |
| 804 | |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 805 | // Now the loop blocks are cloned and the other exiting blocks from the |
| 806 | // remainder are connected to the original Loop's exit blocks. The remaining |
| 807 | // work is to update the phi nodes in the original loop, and take in the |
| 808 | // values from the cloned region. Also update the dominator info for |
Anna Thomas | ec9b326 | 2017-07-13 13:21:23 +0000 | [diff] [blame] | 809 | // OtherExits and their immediate successors, since we have new edges into |
| 810 | // OtherExits. |
Florian Hahn | a1cc848 | 2018-06-12 11:16:56 +0000 | [diff] [blame] | 811 | SmallPtrSet<BasicBlock*, 8> ImmediateSuccessorsOfExitBlocks; |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 812 | for (auto *BB : OtherExits) { |
| 813 | for (auto &II : *BB) { |
| 814 | |
| 815 | // Given we preserve LCSSA form, we know that the values used outside the |
| 816 | // loop will be used through these phi nodes at the exit blocks that are |
| 817 | // transformed below. |
| 818 | if (!isa<PHINode>(II)) |
| 819 | break; |
| 820 | PHINode *Phi = cast<PHINode>(&II); |
| 821 | unsigned oldNumOperands = Phi->getNumIncomingValues(); |
| 822 | // Add the incoming values from the remainder code to the end of the phi |
| 823 | // node. |
| 824 | for (unsigned i =0; i < oldNumOperands; i++){ |
Anna Thomas | 512dde7 | 2017-09-15 13:29:33 +0000 | [diff] [blame] | 825 | Value *newVal = VMap.lookup(Phi->getIncomingValue(i)); |
Anna Thomas | 70ffd65 | 2017-07-10 15:29:38 +0000 | [diff] [blame] | 826 | // newVal can be a constant or derived from values outside the loop, and |
Anna Thomas | 512dde7 | 2017-09-15 13:29:33 +0000 | [diff] [blame] | 827 | // hence need not have a VMap value. Also, since lookup already generated |
| 828 | // a default "null" VMap entry for this value, we need to populate that |
| 829 | // VMap entry correctly, with the mapped entry being itself. |
| 830 | if (!newVal) { |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 831 | newVal = Phi->getIncomingValue(i); |
Anna Thomas | 512dde7 | 2017-09-15 13:29:33 +0000 | [diff] [blame] | 832 | VMap[Phi->getIncomingValue(i)] = Phi->getIncomingValue(i); |
| 833 | } |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 834 | Phi->addIncoming(newVal, |
| 835 | cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)])); |
| 836 | } |
| 837 | } |
Simon Pilgrim | f32f4be | 2017-07-13 17:10:12 +0000 | [diff] [blame] | 838 | #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG) |
Anna Thomas | ec9b326 | 2017-07-13 13:21:23 +0000 | [diff] [blame] | 839 | for (BasicBlock *SuccBB : successors(BB)) { |
| 840 | assert(!(any_of(OtherExits, |
| 841 | [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) || |
| 842 | SuccBB == LatchExit) && |
| 843 | "Breaks the definition of dedicated exits!"); |
| 844 | } |
| 845 | #endif |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 846 | // Update the dominator info because the immediate dominator is no longer the |
| 847 | // header of the original Loop. BB has edges both from L and remainder code. |
| 848 | // Since the preheader determines which loop is run (L or directly jump to |
| 849 | // the remainder code), we set the immediate dominator as the preheader. |
Anna Thomas | ec9b326 | 2017-07-13 13:21:23 +0000 | [diff] [blame] | 850 | if (DT) { |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 851 | DT->changeImmediateDominator(BB, PreHeader); |
Anna Thomas | ec9b326 | 2017-07-13 13:21:23 +0000 | [diff] [blame] | 852 | // Also update the IDom for immediate successors of BB. If the current |
| 853 | // IDom is the header, update the IDom to be the preheader because that is |
| 854 | // the nearest common dominator of all predecessors of SuccBB. We need to |
| 855 | // check for IDom being the header because successors of exit blocks can |
| 856 | // have edges from outside the loop, and we should not incorrectly update |
| 857 | // the IDom in that case. |
| 858 | for (BasicBlock *SuccBB: successors(BB)) |
| 859 | if (ImmediateSuccessorsOfExitBlocks.insert(SuccBB).second) { |
| 860 | if (DT->getNode(SuccBB)->getIDom()->getBlock() == Header) { |
| 861 | assert(!SuccBB->getSinglePredecessor() && |
| 862 | "BB should be the IDom then!"); |
| 863 | DT->changeImmediateDominator(SuccBB, PreHeader); |
| 864 | } |
| 865 | } |
| 866 | } |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 867 | } |
| 868 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 869 | // Loop structure should be the following: |
| 870 | // Epilog Prolog |
| 871 | // |
| 872 | // PreHeader PreHeader |
| 873 | // NewPreHeader PrologPreHeader |
| 874 | // Header PrologHeader |
| 875 | // ... ... |
| 876 | // Latch PrologLatch |
| 877 | // NewExit PrologExit |
| 878 | // EpilogPreHeader NewPreHeader |
| 879 | // EpilogHeader Header |
| 880 | // ... ... |
| 881 | // EpilogLatch Latch |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 882 | // LatchExit LatchExit |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 883 | |
Sanjay Patel | 4d36bba | 2016-02-08 21:32:43 +0000 | [diff] [blame] | 884 | // Rewrite the cloned instruction operands to use the values created when the |
| 885 | // clone is created. |
| 886 | for (BasicBlock *BB : NewBlocks) { |
| 887 | for (Instruction &I : *BB) { |
| 888 | RemapInstruction(&I, VMap, |
Duncan P. N. Exon Smith | da68cbc | 2016-04-07 00:26:43 +0000 | [diff] [blame] | 889 | RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 890 | } |
| 891 | } |
| 892 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 893 | if (UseEpilogRemainder) { |
| 894 | // Connect the epilog code to the original loop and update the |
| 895 | // PHI functions. |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 896 | ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader, |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 897 | EpilogPreHeader, NewPreHeader, VMap, DT, LI, |
| 898 | PreserveLCSSA); |
| 899 | |
| 900 | // Update counter in loop for unrolling. |
| 901 | // I should be multiply of Count. |
| 902 | IRBuilder<> B2(NewPreHeader->getTerminator()); |
| 903 | Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter"); |
| 904 | BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator()); |
| 905 | B2.SetInsertPoint(LatchBR); |
| 906 | PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter", |
| 907 | Header->getFirstNonPHI()); |
| 908 | Value *IdxSub = |
| 909 | B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), |
| 910 | NewIdx->getName() + ".nsub"); |
| 911 | Value *IdxCmp; |
| 912 | if (LatchBR->getSuccessor(0) == Header) |
| 913 | IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp"); |
| 914 | else |
| 915 | IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp"); |
| 916 | NewIdx->addIncoming(TestVal, NewPreHeader); |
| 917 | NewIdx->addIncoming(IdxSub, Latch); |
| 918 | LatchBR->setCondition(IdxCmp); |
| 919 | } else { |
| 920 | // Connect the prolog code to the original loop and update the |
| 921 | // PHI functions. |
Anna Thomas | 734ab3f | 2017-07-07 18:05:28 +0000 | [diff] [blame] | 922 | ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader, |
| 923 | NewPreHeader, VMap, DT, LI, PreserveLCSSA); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 924 | } |
Wei Mi | 59ca966 | 2016-08-25 16:17:18 +0000 | [diff] [blame] | 925 | |
Max Kazantsev | acda4c0 | 2018-04-23 10:39:38 +0000 | [diff] [blame] | 926 | // If this loop is nested, then the loop unroller changes the code in the any |
| 927 | // of its parent loops, so the Scalar Evolution pass needs to be run again. |
| 928 | SE->forgetTopmostLoop(L); |
Wei Mi | 59ca966 | 2016-08-25 16:17:18 +0000 | [diff] [blame] | 929 | |
Anna Thomas | 0785e73 | 2019-01-03 17:44:44 +0000 | [diff] [blame] | 930 | // Verify that the Dom Tree is correct. |
Anna Thomas | a470aa6 | 2019-01-03 19:43:33 +0000 | [diff] [blame] | 931 | #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG) |
Anna Thomas | 0785e73 | 2019-01-03 17:44:44 +0000 | [diff] [blame] | 932 | if (DT) |
| 933 | assert(DT->verify(DominatorTree::VerificationLevel::Full)); |
| 934 | #endif |
| 935 | |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 936 | // Canonicalize to LoopSimplifyForm both original and remainder loops. We |
| 937 | // cannot rely on the LoopUnrollPass to do this because it only does |
| 938 | // canonicalization for parent/subloops and not the sibling loops. |
| 939 | if (OtherExits.size() > 0) { |
| 940 | // Generate dedicated exit blocks for the original loop, to preserve |
| 941 | // LoopSimplifyForm. |
| 942 | formDedicatedExitBlocks(L, DT, LI, PreserveLCSSA); |
| 943 | // Generate dedicated exit blocks for the remainder loop if one exists, to |
| 944 | // preserve LoopSimplifyForm. |
| 945 | if (remainderLoop) |
| 946 | formDedicatedExitBlocks(remainderLoop, DT, LI, PreserveLCSSA); |
| 947 | } |
| 948 | |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 949 | auto UnrollResult = LoopUnrollResult::Unmodified; |
Sam Parker | 718c8a6 | 2017-08-14 09:25:26 +0000 | [diff] [blame] | 950 | if (remainderLoop && UnrollRemainder) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 951 | LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n"); |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 952 | UnrollResult = |
| 953 | UnrollLoop(remainderLoop, /*Count*/ Count - 1, /*TripCount*/ Count - 1, |
| 954 | /*Force*/ false, /*AllowRuntime*/ false, |
| 955 | /*AllowExpensiveTripCount*/ false, /*PreserveCondBr*/ true, |
| 956 | /*PreserveOnlyFirst*/ false, /*TripMultiple*/ 1, |
| 957 | /*PeelCount*/ 0, /*UnrollRemainder*/ false, LI, SE, DT, AC, |
| 958 | /*ORE*/ nullptr, PreserveLCSSA); |
Sam Parker | 718c8a6 | 2017-08-14 09:25:26 +0000 | [diff] [blame] | 959 | } |
| 960 | |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 961 | if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled) |
| 962 | *ResultLoop = remainderLoop; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 963 | NumRuntimeUnrolled++; |
| 964 | return true; |
| 965 | } |