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