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 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 24 | #include "llvm/Transforms/Utils/UnrollLoop.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +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" |
| 28 | #include "llvm/Analysis/LoopPass.h" |
| 29 | #include "llvm/Analysis/ScalarEvolution.h" |
| 30 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 31 | #include "llvm/IR/BasicBlock.h" |
Chandler Carruth | 32c52c7 | 2015-01-18 02:39:37 +0000 | [diff] [blame] | 32 | #include "llvm/IR/Dominators.h" |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 33 | #include "llvm/IR/Metadata.h" |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 34 | #include "llvm/IR/Module.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 35 | #include "llvm/Support/Debug.h" |
| 36 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | b5797b6 | 2015-01-18 09:21:15 +0000 | [diff] [blame] | 37 | #include "llvm/Transforms/Scalar.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 38 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 39 | #include "llvm/Transforms/Utils/Cloning.h" |
| 40 | #include <algorithm> |
| 41 | |
| 42 | using namespace llvm; |
| 43 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 44 | #define DEBUG_TYPE "loop-unroll" |
| 45 | |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 46 | STATISTIC(NumRuntimeUnrolled, |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 47 | "Number of loops unrolled with run-time trip counts"); |
| 48 | |
| 49 | /// Connect the unrolling prolog code to the original loop. |
| 50 | /// The unrolling prolog code contains code to execute the |
| 51 | /// 'extra' iterations if the run-time trip count modulo the |
| 52 | /// unroll count is non-zero. |
| 53 | /// |
| 54 | /// This function performs the following: |
| 55 | /// - Create PHI nodes at prolog end block to combine values |
| 56 | /// that exit the prolog code and jump around the prolog. |
| 57 | /// - Add a PHI operand to a PHI node at the loop exit block |
| 58 | /// for values that exit the prolog and go around the loop. |
| 59 | /// - Branch around the original loop if the trip count is less |
| 60 | /// than the unroll factor. |
| 61 | /// |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 62 | static void ConnectProlog(Loop *L, Value *BECount, unsigned Count, |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 63 | BasicBlock *PrologExit, BasicBlock *PreHeader, |
| 64 | BasicBlock *NewPreHeader, ValueToValueMapTy &VMap, |
| 65 | DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA) { |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 66 | BasicBlock *Latch = L->getLoopLatch(); |
Craig Topper | e73658d | 2014-04-28 04:05:08 +0000 | [diff] [blame] | 67 | assert(Latch && "Loop must have a latch"); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 68 | BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 69 | |
| 70 | // Create a PHI node for each outgoing value from the original loop |
| 71 | // (which means it is an outgoing value from the prolog code too). |
| 72 | // 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] | 73 | // 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] | 74 | // the loop header or the loop exit block. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 75 | for (BasicBlock *Succ : successors(Latch)) { |
| 76 | for (Instruction &BBI : *Succ) { |
| 77 | PHINode *PN = dyn_cast<PHINode>(&BBI); |
| 78 | // Exit when we passed all PHI nodes. |
| 79 | if (!PN) |
| 80 | break; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 81 | // Add a new PHI node to the prolog end block and add the |
| 82 | // appropriate incoming values. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 83 | PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr", |
| 84 | PrologExit->getFirstNonPHI()); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 85 | // Adding a value to the new PHI node from the original loop preheader. |
| 86 | // This is the value that skips all the prolog code. |
| 87 | if (L->contains(PN)) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 88 | NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader), |
| 89 | PreHeader); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 90 | } else { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 91 | NewPN->addIncoming(UndefValue::get(PN->getType()), PreHeader); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 92 | } |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 93 | |
| 94 | Value *V = PN->getIncomingValueForBlock(Latch); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 95 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 96 | if (L->contains(I)) { |
Duncan P. N. Exon Smith | a71301b | 2016-04-17 19:26:49 +0000 | [diff] [blame] | 97 | V = VMap.lookup(I); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 98 | } |
| 99 | } |
| 100 | // Adding a value to the new PHI node from the last prolog block |
| 101 | // that was created. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 102 | NewPN->addIncoming(V, PrologLatch); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 103 | |
| 104 | // Update the existing PHI node operand with the value from the |
| 105 | // new PHI node. How this is done depends on if the existing |
| 106 | // PHI node is in the original loop block, or the exit block. |
| 107 | if (L->contains(PN)) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 108 | PN->setIncomingValue(PN->getBasicBlockIndex(NewPreHeader), NewPN); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 109 | } else { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 110 | PN->addIncoming(NewPN, PrologExit); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 111 | } |
| 112 | } |
| 113 | } |
| 114 | |
Michael Zolotukhin | d9b6ad3 | 2016-08-02 19:19:31 +0000 | [diff] [blame] | 115 | // Make sure that created prolog loop is in simplified form |
| 116 | SmallVector<BasicBlock *, 4> PrologExitPreds; |
| 117 | Loop *PrologLoop = LI->getLoopFor(PrologLatch); |
| 118 | if (PrologLoop) { |
| 119 | for (BasicBlock *PredBB : predecessors(PrologExit)) |
| 120 | if (PrologLoop->contains(PredBB)) |
| 121 | PrologExitPreds.push_back(PredBB); |
| 122 | |
| 123 | SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI, |
| 124 | PreserveLCSSA); |
| 125 | } |
| 126 | |
Sanjay Patel | e08381a | 2016-02-08 19:27:33 +0000 | [diff] [blame] | 127 | // 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] | 128 | // iterations remaining to be executed after running the prologue. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 129 | Instruction *InsertPt = PrologExit->getTerminator(); |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 130 | IRBuilder<> B(InsertPt); |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 131 | |
| 132 | assert(Count != 0 && "nonsensical Count!"); |
| 133 | |
David L Kreitzer | 8d441eb | 2016-03-25 14:24:52 +0000 | [diff] [blame] | 134 | // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1) |
| 135 | // This means %xtraiter is (BECount + 1) and all of the iterations of this |
| 136 | // loop were executed by the prologue. Note that if BECount <u (Count - 1) |
| 137 | // then (BECount + 1) cannot unsigned-overflow. |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 138 | Value *BrLoopExit = |
| 139 | B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1)); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 140 | BasicBlock *Exit = L->getUniqueExitBlock(); |
Craig Topper | e73658d | 2014-04-28 04:05:08 +0000 | [diff] [blame] | 141 | assert(Exit && "Loop must have a single exit block only"); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 142 | // Split the exit to maintain loop canonicalization guarantees |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 143 | SmallVector<BasicBlock*, 4> Preds(predecessors(Exit)); |
Chandler Carruth | 96ada25 | 2015-07-22 09:52:54 +0000 | [diff] [blame] | 144 | SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", DT, LI, |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 145 | PreserveLCSSA); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 146 | // Add the branch to the exit block (around the unrolled loop) |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 147 | B.CreateCondBr(BrLoopExit, Exit, NewPreHeader); |
| 148 | InsertPt->eraseFromParent(); |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 149 | if (DT) |
| 150 | DT->changeImmediateDominator(Exit, PrologExit); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 151 | } |
| 152 | |
| 153 | /// Connect the unrolling epilog code to the original loop. |
| 154 | /// The unrolling epilog code contains code to execute the |
| 155 | /// 'extra' iterations if the run-time trip count modulo the |
| 156 | /// unroll count is non-zero. |
| 157 | /// |
| 158 | /// This function performs the following: |
| 159 | /// - Update PHI nodes at the unrolling loop exit and epilog loop exit |
| 160 | /// - Create PHI nodes at the unrolling loop exit to combine |
| 161 | /// values that exit the unrolling loop code and jump around it. |
| 162 | /// - Update PHI operands in the epilog loop by the new PHI nodes |
| 163 | /// - Branch around the epilog loop if extra iters (ModVal) is zero. |
| 164 | /// |
| 165 | static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit, |
| 166 | BasicBlock *Exit, BasicBlock *PreHeader, |
| 167 | BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader, |
| 168 | ValueToValueMapTy &VMap, DominatorTree *DT, |
| 169 | LoopInfo *LI, bool PreserveLCSSA) { |
| 170 | BasicBlock *Latch = L->getLoopLatch(); |
| 171 | assert(Latch && "Loop must have a latch"); |
| 172 | BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]); |
| 173 | |
| 174 | // Loop structure should be the following: |
| 175 | // |
| 176 | // PreHeader |
| 177 | // NewPreHeader |
| 178 | // Header |
| 179 | // ... |
| 180 | // Latch |
| 181 | // NewExit (PN) |
| 182 | // EpilogPreHeader |
| 183 | // EpilogHeader |
| 184 | // ... |
| 185 | // EpilogLatch |
| 186 | // Exit (EpilogPN) |
| 187 | |
| 188 | // Update PHI nodes at NewExit and Exit. |
| 189 | for (Instruction &BBI : *NewExit) { |
| 190 | PHINode *PN = dyn_cast<PHINode>(&BBI); |
| 191 | // Exit when we passed all PHI nodes. |
| 192 | if (!PN) |
| 193 | break; |
| 194 | // PN should be used in another PHI located in Exit block as |
| 195 | // Exit was split by SplitBlockPredecessors into Exit and NewExit |
| 196 | // Basicaly it should look like: |
| 197 | // NewExit: |
| 198 | // PN = PHI [I, Latch] |
| 199 | // ... |
| 200 | // Exit: |
| 201 | // EpilogPN = PHI [PN, EpilogPreHeader] |
| 202 | // |
| 203 | // There is EpilogPreHeader incoming block instead of NewExit as |
| 204 | // NewExit was spilt 1 more time to get EpilogPreHeader. |
| 205 | assert(PN->hasOneUse() && "The phi should have 1 use"); |
| 206 | PHINode *EpilogPN = cast<PHINode> (PN->use_begin()->getUser()); |
| 207 | assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block"); |
| 208 | |
| 209 | // Add incoming PreHeader from branch around the Loop |
| 210 | PN->addIncoming(UndefValue::get(PN->getType()), PreHeader); |
| 211 | |
| 212 | Value *V = PN->getIncomingValueForBlock(Latch); |
| 213 | Instruction *I = dyn_cast<Instruction>(V); |
| 214 | if (I && L->contains(I)) |
| 215 | // 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] | 216 | V = VMap.lookup(I); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 217 | // For the instruction out of the loop, constant or undefined value |
| 218 | // insert value itself. |
| 219 | EpilogPN->addIncoming(V, EpilogLatch); |
| 220 | |
| 221 | assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 && |
| 222 | "EpilogPN should have EpilogPreHeader incoming block"); |
| 223 | // Change EpilogPreHeader incoming block to NewExit. |
| 224 | EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader), |
| 225 | NewExit); |
| 226 | // Now PHIs should look like: |
| 227 | // NewExit: |
| 228 | // PN = PHI [I, Latch], [undef, PreHeader] |
| 229 | // ... |
| 230 | // Exit: |
| 231 | // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch] |
| 232 | } |
| 233 | |
| 234 | // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader). |
| 235 | // Update corresponding PHI nodes in epilog loop. |
| 236 | for (BasicBlock *Succ : successors(Latch)) { |
| 237 | // Skip this as we already updated phis in exit blocks. |
| 238 | if (!L->contains(Succ)) |
| 239 | continue; |
| 240 | for (Instruction &BBI : *Succ) { |
| 241 | PHINode *PN = dyn_cast<PHINode>(&BBI); |
| 242 | // Exit when we passed all PHI nodes. |
| 243 | if (!PN) |
| 244 | break; |
| 245 | // Add new PHI nodes to the loop exit block and update epilog |
| 246 | // PHIs with the new PHI values. |
| 247 | PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr", |
| 248 | NewExit->getFirstNonPHI()); |
| 249 | // Adding a value to the new PHI node from the unrolling loop preheader. |
| 250 | NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader), PreHeader); |
| 251 | // Adding a value to the new PHI node from the unrolling loop latch. |
| 252 | NewPN->addIncoming(PN->getIncomingValueForBlock(Latch), Latch); |
| 253 | |
| 254 | // Update the existing PHI node operand with the value from the new PHI |
| 255 | // node. Corresponding instruction in epilog loop should be PHI. |
| 256 | PHINode *VPN = cast<PHINode>(VMap[&BBI]); |
| 257 | VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN); |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | Instruction *InsertPt = NewExit->getTerminator(); |
| 262 | IRBuilder<> B(InsertPt); |
Evgeny Stupachenko | 23ce61b | 2016-04-27 03:04:54 +0000 | [diff] [blame] | 263 | Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod"); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 264 | assert(Exit && "Loop must have a single exit block only"); |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 265 | // Split the epilogue exit to maintain loop canonicalization guarantees |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 266 | SmallVector<BasicBlock*, 4> Preds(predecessors(Exit)); |
| 267 | SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, |
| 268 | PreserveLCSSA); |
| 269 | // Add the branch to the exit block (around the unrolling loop) |
| 270 | B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 271 | InsertPt->eraseFromParent(); |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 272 | if (DT) |
| 273 | DT->changeImmediateDominator(Exit, NewExit); |
| 274 | |
| 275 | // Split the main loop exit to maintain canonicalization guarantees. |
| 276 | SmallVector<BasicBlock*, 4> NewExitPreds{Latch}; |
| 277 | SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, |
| 278 | PreserveLCSSA); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 279 | } |
| 280 | |
| 281 | /// 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] | 282 | /// If CreateRemainderLoop is false, loop structure will not be cloned, |
| 283 | /// otherwise a new loop will be created including all cloned blocks, and the |
| 284 | /// iterator of it switches to count NewIter down to 0. |
| 285 | /// The cloned blocks should be inserted between InsertTop and InsertBot. |
| 286 | /// If loop structure is cloned InsertTop should be new preheader, InsertBot |
| 287 | /// new loop exit. |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 288 | /// |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 289 | static void CloneLoopBlocks(Loop *L, Value *NewIter, |
| 290 | const bool CreateRemainderLoop, |
| 291 | const bool UseEpilogRemainder, |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 292 | BasicBlock *InsertTop, BasicBlock *InsertBot, |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 293 | BasicBlock *Preheader, |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 294 | std::vector<BasicBlock *> &NewBlocks, |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 295 | LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap, |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 296 | DominatorTree *DT, LoopInfo *LI) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 297 | StringRef suffix = UseEpilogRemainder ? "epil" : "prol"; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 298 | BasicBlock *Header = L->getHeader(); |
| 299 | BasicBlock *Latch = L->getLoopLatch(); |
| 300 | Function *F = Header->getParent(); |
| 301 | LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); |
| 302 | LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 303 | Loop *ParentLoop = L->getParentLoop(); |
Florian Hahn | 4f9d6d5 | 2017-01-10 23:43:35 +0000 | [diff] [blame] | 304 | NewLoopsMap NewLoops; |
Florian Hahn | 5364cf3 | 2017-01-31 11:13:44 +0000 | [diff] [blame] | 305 | NewLoops[ParentLoop] = ParentLoop; |
| 306 | if (!CreateRemainderLoop) |
Michael Kuperstein | 5dd55e8 | 2017-01-26 01:04:11 +0000 | [diff] [blame] | 307 | NewLoops[L] = ParentLoop; |
| 308 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 309 | // For each block in the original loop, create a new copy, |
| 310 | // and update the value map with the newly created values. |
| 311 | for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 312 | BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 313 | NewBlocks.push_back(NewBB); |
Florian Hahn | 5364cf3 | 2017-01-31 11:13:44 +0000 | [diff] [blame] | 314 | |
Michael Kuperstein | 5dd55e8 | 2017-01-26 01:04:11 +0000 | [diff] [blame] | 315 | // If we're unrolling the outermost loop, there's no remainder loop, |
| 316 | // and this block isn't in a nested loop, then the new block is not |
| 317 | // in any loop. Otherwise, add it to loopinfo. |
| 318 | if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop) |
Florian Hahn | 4f9d6d5 | 2017-01-10 23:43:35 +0000 | [diff] [blame] | 319 | addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 320 | |
| 321 | VMap[*BB] = NewBB; |
| 322 | if (Header == *BB) { |
| 323 | // For the first block, add a CFG connection to this newly |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 324 | // created block. |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 325 | InsertTop->getTerminator()->setSuccessor(0, NewBB); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 326 | } |
Junmo Park | 502ff66 | 2016-01-28 01:23:18 +0000 | [diff] [blame] | 327 | |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 328 | if (DT) { |
| 329 | if (Header == *BB) { |
| 330 | // The header is dominated by the preheader. |
| 331 | DT->addNewBlock(NewBB, InsertTop); |
| 332 | } else { |
| 333 | // Copy information from original loop to unrolled loop. |
| 334 | BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock(); |
| 335 | DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB])); |
| 336 | } |
| 337 | } |
| 338 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 339 | if (Latch == *BB) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 340 | // For the last block, if CreateRemainderLoop is false, create a direct |
| 341 | // jump to InsertBot. If not, create a loop back to cloned head. |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 342 | VMap.erase((*BB)->getTerminator()); |
| 343 | BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]); |
| 344 | BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator()); |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 345 | IRBuilder<> Builder(LatchBR); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 346 | if (!CreateRemainderLoop) { |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 347 | Builder.CreateBr(InsertBot); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 348 | } else { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 349 | PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, |
| 350 | suffix + ".iter", |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 351 | FirstLoopBB->getFirstNonPHI()); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 352 | Value *IdxSub = |
| 353 | Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), |
| 354 | NewIdx->getName() + ".sub"); |
| 355 | Value *IdxCmp = |
| 356 | Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp"); |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 357 | Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 358 | NewIdx->addIncoming(NewIter, InsertTop); |
| 359 | NewIdx->addIncoming(IdxSub, NewBB); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 360 | } |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 361 | LatchBR->eraseFromParent(); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 362 | } |
| 363 | } |
| 364 | |
| 365 | // Change the incoming values to the ones defined in the preheader or |
| 366 | // cloned loop. |
| 367 | 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] | 368 | PHINode *NewPHI = cast<PHINode>(VMap[&*I]); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 369 | if (!CreateRemainderLoop) { |
| 370 | if (UseEpilogRemainder) { |
| 371 | unsigned idx = NewPHI->getBasicBlockIndex(Preheader); |
| 372 | NewPHI->setIncomingBlock(idx, InsertTop); |
| 373 | NewPHI->removeIncomingValue(Latch, false); |
| 374 | } else { |
| 375 | VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader); |
| 376 | cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); |
| 377 | } |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 378 | } else { |
| 379 | unsigned idx = NewPHI->getBasicBlockIndex(Preheader); |
| 380 | NewPHI->setIncomingBlock(idx, InsertTop); |
| 381 | BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); |
| 382 | idx = NewPHI->getBasicBlockIndex(Latch); |
| 383 | Value *InVal = NewPHI->getIncomingValue(idx); |
| 384 | NewPHI->setIncomingBlock(idx, NewLatch); |
Duncan P. N. Exon Smith | a71301b | 2016-04-17 19:26:49 +0000 | [diff] [blame] | 385 | if (Value *V = VMap.lookup(InVal)) |
| 386 | NewPHI->setIncomingValue(idx, V); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 387 | } |
| 388 | } |
Florian Hahn | 5364cf3 | 2017-01-31 11:13:44 +0000 | [diff] [blame] | 389 | if (CreateRemainderLoop) { |
| 390 | Loop *NewLoop = NewLoops[L]; |
| 391 | assert(NewLoop && "L should have been cloned"); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 392 | // Add unroll disable metadata to disable future unrolling for this loop. |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 393 | SmallVector<Metadata *, 4> MDs; |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 394 | // Reserve first location for self reference to the LoopID metadata node. |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 395 | MDs.push_back(nullptr); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 396 | MDNode *LoopID = NewLoop->getLoopID(); |
| 397 | if (LoopID) { |
| 398 | // First remove any existing loop unrolling metadata. |
| 399 | for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { |
| 400 | bool IsUnrollMetadata = false; |
| 401 | MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); |
| 402 | if (MD) { |
| 403 | const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); |
| 404 | IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 405 | } |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 406 | if (!IsUnrollMetadata) |
| 407 | MDs.push_back(LoopID->getOperand(i)); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 408 | } |
| 409 | } |
| 410 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 411 | LLVMContext &Context = NewLoop->getHeader()->getContext(); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 412 | SmallVector<Metadata *, 1> DisableOperands; |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 413 | DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); |
| 414 | MDNode *DisableNode = MDNode::get(Context, DisableOperands); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 415 | MDs.push_back(DisableNode); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 416 | |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 417 | MDNode *NewLoopID = MDNode::get(Context, MDs); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 418 | // Set operand 0 to refer to the loop id itself. |
| 419 | NewLoopID->replaceOperandWith(0, NewLoopID); |
| 420 | NewLoop->setLoopID(NewLoopID); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 421 | } |
| 422 | } |
| 423 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 424 | /// 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] | 425 | /// run-time trip-count. |
| 426 | /// |
| 427 | /// This method assumes that the loop unroll factor is total number |
Justin Lebar | 6086c6a | 2016-02-12 21:01:37 +0000 | [diff] [blame] | 428 | /// of loop bodies in the loop after unrolling. (Some folks refer |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 429 | /// to the unroll factor as the number of *extra* copies added). |
| 430 | /// We assume also that the loop unroll factor is a power-of-two. So, after |
| 431 | /// unrolling the loop, the number of loop bodies executed is 2, |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 432 | /// 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] | 433 | /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for |
| 434 | /// the switch instruction is generated. |
| 435 | /// |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 436 | /// ***Prolog case*** |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 437 | /// extraiters = tripcount % loopfactor |
| 438 | /// if (extraiters == 0) jump Loop: |
Evgeny Stupachenko | 8788048 | 2016-04-08 20:20:38 +0000 | [diff] [blame] | 439 | /// else jump Prol: |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 440 | /// Prol: LoopBody; |
| 441 | /// extraiters -= 1 // Omitted if unroll factor is 2. |
| 442 | /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2. |
Evgeny Stupachenko | 8788048 | 2016-04-08 20:20:38 +0000 | [diff] [blame] | 443 | /// if (tripcount < loopfactor) jump End: |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 444 | /// Loop: |
| 445 | /// ... |
| 446 | /// End: |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 447 | /// |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 448 | /// ***Epilog case*** |
| 449 | /// extraiters = tripcount % loopfactor |
Evgeny Stupachenko | 23ce61b | 2016-04-27 03:04:54 +0000 | [diff] [blame] | 450 | /// if (tripcount < loopfactor) jump LoopExit: |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 451 | /// unroll_iters = tripcount - extraiters |
| 452 | /// Loop: LoopBody; (executes unroll_iter times); |
| 453 | /// unroll_iter -= 1 |
| 454 | /// if (unroll_iter != 0) jump Loop: |
| 455 | /// LoopExit: |
| 456 | /// if (extraiters == 0) jump EpilExit: |
| 457 | /// Epil: LoopBody; (executes extraiters times) |
| 458 | /// extraiters -= 1 // Omitted if unroll factor is 2. |
| 459 | /// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2. |
| 460 | /// EpilExit: |
| 461 | |
| 462 | bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, |
| 463 | bool AllowExpensiveTripCount, |
| 464 | bool UseEpilogRemainder, |
| 465 | LoopInfo *LI, ScalarEvolution *SE, |
| 466 | DominatorTree *DT, bool PreserveLCSSA) { |
| 467 | // for now, only unroll loops that contain a single exit |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 468 | if (!L->getExitingBlock()) |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 469 | return false; |
| 470 | |
| 471 | // Make sure the loop is in canonical form, and there is a single |
| 472 | // exit block only. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 473 | if (!L->isLoopSimplifyForm()) |
| 474 | return false; |
| 475 | BasicBlock *Exit = L->getUniqueExitBlock(); // successor out of loop |
| 476 | if (!Exit) |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 477 | return false; |
| 478 | |
Sanjay Patel | e08381a | 2016-02-08 19:27:33 +0000 | [diff] [blame] | 479 | // Use Scalar Evolution to compute the trip count. This allows more loops to |
| 480 | // be unrolled than relying on induction var simplification. |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 481 | if (!SE) |
Andrew Trick | d29cd73 | 2012-05-08 02:52:09 +0000 | [diff] [blame] | 482 | return false; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 483 | |
Sanjay Patel | e08381a | 2016-02-08 19:27:33 +0000 | [diff] [blame] | 484 | // Only unroll loops with a computable trip count, and the trip count needs |
| 485 | // to be an int value (allowing a pointer type is a TODO item). |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 486 | const SCEV *BECountSC = SE->getBackedgeTakenCount(L); |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 487 | if (isa<SCEVCouldNotCompute>(BECountSC) || |
| 488 | !BECountSC->getType()->isIntegerTy()) |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 489 | return false; |
| 490 | |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 491 | unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth(); |
Michael Zolotukhin | 0dcae71 | 2014-11-20 20:19:55 +0000 | [diff] [blame] | 492 | |
Sanjay Patel | e08381a | 2016-02-08 19:27:33 +0000 | [diff] [blame] | 493 | // 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] | 494 | const SCEV *TripCountSC = |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 495 | SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1)); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 496 | if (isa<SCEVCouldNotCompute>(TripCountSC)) |
| 497 | return false; |
| 498 | |
Sanjoy Das | e178f46 | 2015-04-14 03:20:38 +0000 | [diff] [blame] | 499 | BasicBlock *Header = L->getHeader(); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 500 | BasicBlock *PreHeader = L->getLoopPreheader(); |
| 501 | BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator()); |
Sanjoy Das | e178f46 | 2015-04-14 03:20:38 +0000 | [diff] [blame] | 502 | const DataLayout &DL = Header->getModule()->getDataLayout(); |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 503 | SCEVExpander Expander(*SE, DL, "loop-unroll"); |
Junmo Park | 6ebdc14 | 2016-02-16 06:46:58 +0000 | [diff] [blame] | 504 | if (!AllowExpensiveTripCount && |
| 505 | Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) |
Sanjoy Das | e178f46 | 2015-04-14 03:20:38 +0000 | [diff] [blame] | 506 | return false; |
| 507 | |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 508 | // 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] | 509 | // comment on ModVal below. |
| 510 | if (Log2_32(Count) > BEWidth) |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 511 | return false; |
| 512 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 513 | BasicBlock *Latch = L->getLoopLatch(); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 514 | |
Anna Thomas | ac0ec22 | 2017-05-03 17:43:59 +0000 | [diff] [blame^] | 515 | // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the |
| 516 | // targets of the Latch be the single exit block out of the loop. This needs |
| 517 | // to be guaranteed by the callers of UnrollRuntimeLoopRemainder. |
| 518 | BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator()); |
| 519 | assert(LatchBR->getSuccessor(0) == Exit || |
| 520 | LatchBR->getSuccessor(1) == Exit && "loop latch successor should be " |
| 521 | "exit block!"); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 522 | // Loop structure is the following: |
| 523 | // |
| 524 | // PreHeader |
| 525 | // Header |
| 526 | // ... |
| 527 | // Latch |
| 528 | // Exit |
| 529 | |
| 530 | BasicBlock *NewPreHeader; |
| 531 | BasicBlock *NewExit = nullptr; |
| 532 | BasicBlock *PrologExit = nullptr; |
| 533 | BasicBlock *EpilogPreHeader = nullptr; |
| 534 | BasicBlock *PrologPreHeader = nullptr; |
| 535 | |
| 536 | if (UseEpilogRemainder) { |
| 537 | // If epilog remainder |
| 538 | // Split PreHeader to insert a branch around loop for unrolling. |
| 539 | NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI); |
| 540 | NewPreHeader->setName(PreHeader->getName() + ".new"); |
| 541 | // Split Exit to create phi nodes from branch above. |
| 542 | SmallVector<BasicBlock*, 4> Preds(predecessors(Exit)); |
| 543 | NewExit = SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", |
| 544 | DT, LI, PreserveLCSSA); |
| 545 | // Split NewExit to insert epilog remainder loop. |
| 546 | EpilogPreHeader = SplitBlock(NewExit, NewExit->getTerminator(), DT, LI); |
| 547 | EpilogPreHeader->setName(Header->getName() + ".epil.preheader"); |
| 548 | } else { |
| 549 | // If prolog remainder |
| 550 | // Split the original preheader twice to insert prolog remainder loop |
| 551 | PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI); |
| 552 | PrologPreHeader->setName(Header->getName() + ".prol.preheader"); |
| 553 | PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(), |
| 554 | DT, LI); |
| 555 | PrologExit->setName(Header->getName() + ".prol.loopexit"); |
| 556 | // Split PrologExit to get NewPreHeader. |
| 557 | NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI); |
| 558 | NewPreHeader->setName(PreHeader->getName() + ".new"); |
| 559 | } |
| 560 | // Loop structure should be the following: |
| 561 | // Epilog Prolog |
| 562 | // |
| 563 | // PreHeader PreHeader |
| 564 | // *NewPreHeader *PrologPreHeader |
| 565 | // Header *PrologExit |
| 566 | // ... *NewPreHeader |
| 567 | // Latch Header |
| 568 | // *NewExit ... |
| 569 | // *EpilogPreHeader Latch |
| 570 | // Exit Exit |
| 571 | |
| 572 | // Calculate conditions for branch around loop for unrolling |
| 573 | // in epilog case and around prolog remainder loop in prolog case. |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 574 | // Compute the number of extra iterations required, which is: |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 575 | // extra iterations = run-time trip count % loop unroll factor |
| 576 | PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator()); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 577 | Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(), |
| 578 | PreHeaderBR); |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 579 | Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(), |
| 580 | PreHeaderBR); |
Benjamin Kramer | 0bf086f | 2014-06-21 13:46:25 +0000 | [diff] [blame] | 581 | IRBuilder<> B(PreHeaderBR); |
David L Kreitzer | 8d441eb | 2016-03-25 14:24:52 +0000 | [diff] [blame] | 582 | Value *ModVal; |
| 583 | // Calculate ModVal = (BECount + 1) % Count. |
| 584 | // Note that TripCount is BECount + 1. |
| 585 | if (isPowerOf2_32(Count)) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 586 | // When Count is power of 2 we don't BECount for epilog case, however we'll |
| 587 | // need it for a branch around unrolling loop for prolog case. |
David L Kreitzer | 8d441eb | 2016-03-25 14:24:52 +0000 | [diff] [blame] | 588 | ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter"); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 589 | // 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] | 590 | // OR |
| 591 | // 2. The addition computing TripCount overflowed. |
| 592 | // |
| 593 | // If (2) is true, we know that TripCount really is (1 << BEWidth) and so |
| 594 | // the number of iterations that remain to be run in the original loop is a |
| 595 | // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we |
| 596 | // explicitly check this above). |
| 597 | } else { |
| 598 | // As (BECount + 1) can potentially unsigned overflow we count |
| 599 | // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count. |
| 600 | Value *ModValTmp = B.CreateURem(BECount, |
| 601 | ConstantInt::get(BECount->getType(), |
| 602 | Count)); |
| 603 | Value *ModValAdd = B.CreateAdd(ModValTmp, |
| 604 | ConstantInt::get(ModValTmp->getType(), 1)); |
| 605 | // At that point (BECount % Count) + 1 could be equal to Count. |
| 606 | // To handle this case we need to take mod by Count one more time. |
| 607 | ModVal = B.CreateURem(ModValAdd, |
| 608 | ConstantInt::get(BECount->getType(), Count), |
| 609 | "xtraiter"); |
| 610 | } |
Evgeny Stupachenko | 23ce61b | 2016-04-27 03:04:54 +0000 | [diff] [blame] | 611 | Value *BranchVal = |
| 612 | UseEpilogRemainder ? B.CreateICmpULT(BECount, |
| 613 | ConstantInt::get(BECount->getType(), |
| 614 | Count - 1)) : |
| 615 | B.CreateIsNotNull(ModVal, "lcmp.mod"); |
| 616 | BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader; |
| 617 | BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit; |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 618 | // Branch to either remainder (extra iterations) loop or unrolling loop. |
Evgeny Stupachenko | 23ce61b | 2016-04-27 03:04:54 +0000 | [diff] [blame] | 619 | B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 620 | PreHeaderBR->eraseFromParent(); |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 621 | if (DT) { |
| 622 | if (UseEpilogRemainder) |
| 623 | DT->changeImmediateDominator(NewExit, PreHeader); |
| 624 | else |
| 625 | DT->changeImmediateDominator(PrologExit, PreHeader); |
| 626 | } |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 627 | Function *F = Header->getParent(); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 628 | // 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] | 629 | // cloned blocks in the prolog/epilog code |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 630 | LoopBlocksDFS LoopBlocks(L); |
| 631 | LoopBlocks.perform(LI); |
| 632 | |
| 633 | // |
| 634 | // For each extra loop iteration, create a copy of the loop's basic blocks |
| 635 | // and generate a condition that branches to the copy depending on the |
| 636 | // number of 'left over' iterations. |
| 637 | // |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 638 | std::vector<BasicBlock *> NewBlocks; |
| 639 | ValueToValueMapTy VMap; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 640 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 641 | // For unroll factor 2 remainder loop will have 1 iterations. |
| 642 | // Do not create 1 iteration loop. |
| 643 | bool CreateRemainderLoop = (Count != 2); |
Michael Zolotukhin | 0dcae71 | 2014-11-20 20:19:55 +0000 | [diff] [blame] | 644 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 645 | // Clone all the basic blocks in the loop. If Count is 2, we don't clone |
| 646 | // the loop, otherwise we create a cloned loop to execute the extra |
| 647 | // iterations. This function adds the appropriate CFG connections. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 648 | BasicBlock *InsertBot = UseEpilogRemainder ? Exit : PrologExit; |
| 649 | BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader; |
| 650 | CloneLoopBlocks(L, ModVal, CreateRemainderLoop, UseEpilogRemainder, InsertTop, |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 651 | InsertBot, NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 652 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 653 | // Insert the cloned blocks into the function. |
| 654 | F->getBasicBlockList().splice(InsertBot->getIterator(), |
| 655 | F->getBasicBlockList(), |
| 656 | NewBlocks[0]->getIterator(), |
| 657 | F->end()); |
| 658 | |
| 659 | // Loop structure should be the following: |
| 660 | // Epilog Prolog |
| 661 | // |
| 662 | // PreHeader PreHeader |
| 663 | // NewPreHeader PrologPreHeader |
| 664 | // Header PrologHeader |
| 665 | // ... ... |
| 666 | // Latch PrologLatch |
| 667 | // NewExit PrologExit |
| 668 | // EpilogPreHeader NewPreHeader |
| 669 | // EpilogHeader Header |
| 670 | // ... ... |
| 671 | // EpilogLatch Latch |
| 672 | // Exit Exit |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 673 | |
Sanjay Patel | 4d36bba | 2016-02-08 21:32:43 +0000 | [diff] [blame] | 674 | // Rewrite the cloned instruction operands to use the values created when the |
| 675 | // clone is created. |
| 676 | for (BasicBlock *BB : NewBlocks) { |
| 677 | for (Instruction &I : *BB) { |
| 678 | RemapInstruction(&I, VMap, |
Duncan P. N. Exon Smith | da68cbc | 2016-04-07 00:26:43 +0000 | [diff] [blame] | 679 | RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 680 | } |
| 681 | } |
| 682 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 683 | if (UseEpilogRemainder) { |
| 684 | // Connect the epilog code to the original loop and update the |
| 685 | // PHI functions. |
| 686 | ConnectEpilog(L, ModVal, NewExit, Exit, PreHeader, |
| 687 | EpilogPreHeader, NewPreHeader, VMap, DT, LI, |
| 688 | PreserveLCSSA); |
| 689 | |
| 690 | // Update counter in loop for unrolling. |
| 691 | // I should be multiply of Count. |
| 692 | IRBuilder<> B2(NewPreHeader->getTerminator()); |
| 693 | Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter"); |
| 694 | BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator()); |
| 695 | B2.SetInsertPoint(LatchBR); |
| 696 | PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter", |
| 697 | Header->getFirstNonPHI()); |
| 698 | Value *IdxSub = |
| 699 | B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), |
| 700 | NewIdx->getName() + ".nsub"); |
| 701 | Value *IdxCmp; |
| 702 | if (LatchBR->getSuccessor(0) == Header) |
| 703 | IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp"); |
| 704 | else |
| 705 | IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp"); |
| 706 | NewIdx->addIncoming(TestVal, NewPreHeader); |
| 707 | NewIdx->addIncoming(IdxSub, Latch); |
| 708 | LatchBR->setCondition(IdxCmp); |
| 709 | } else { |
| 710 | // Connect the prolog code to the original loop and update the |
| 711 | // PHI functions. |
| 712 | ConnectProlog(L, BECount, Count, PrologExit, PreHeader, NewPreHeader, |
| 713 | VMap, DT, LI, PreserveLCSSA); |
| 714 | } |
Wei Mi | 59ca966 | 2016-08-25 16:17:18 +0000 | [diff] [blame] | 715 | |
| 716 | // If this loop is nested, then the loop unroller changes the code in the |
| 717 | // parent loop, so the Scalar Evolution pass needs to be run again. |
| 718 | if (Loop *ParentLoop = L->getParentLoop()) |
| 719 | SE->forgetLoop(ParentLoop); |
| 720 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 721 | NumRuntimeUnrolled++; |
| 722 | return true; |
| 723 | } |