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 |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 19 | // unrolled loop to execute the 'left over' iterations. Other strategies |
| 20 | // include generate a loop before or after the unrolled loop. |
| 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" |
| 26 | #include "llvm/Analysis/LoopIterator.h" |
| 27 | #include "llvm/Analysis/LoopPass.h" |
| 28 | #include "llvm/Analysis/ScalarEvolution.h" |
| 29 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 30 | #include "llvm/IR/BasicBlock.h" |
Chandler Carruth | 32c52c7 | 2015-01-18 02:39:37 +0000 | [diff] [blame^] | 31 | #include "llvm/IR/Dominators.h" |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 32 | #include "llvm/IR/Metadata.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 33 | #include "llvm/Support/Debug.h" |
| 34 | #include "llvm/Support/raw_ostream.h" |
| 35 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 36 | #include "llvm/Transforms/Utils/Cloning.h" |
| 37 | #include <algorithm> |
| 38 | |
| 39 | using namespace llvm; |
| 40 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 41 | #define DEBUG_TYPE "loop-unroll" |
| 42 | |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 43 | STATISTIC(NumRuntimeUnrolled, |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 44 | "Number of loops unrolled with run-time trip counts"); |
| 45 | |
| 46 | /// Connect the unrolling prolog code to the original loop. |
| 47 | /// The unrolling prolog code contains code to execute the |
| 48 | /// 'extra' iterations if the run-time trip count modulo the |
| 49 | /// unroll count is non-zero. |
| 50 | /// |
| 51 | /// This function performs the following: |
| 52 | /// - Create PHI nodes at prolog end block to combine values |
| 53 | /// that exit the prolog code and jump around the prolog. |
| 54 | /// - Add a PHI operand to a PHI node at the loop exit block |
| 55 | /// for values that exit the prolog and go around the loop. |
| 56 | /// - Branch around the original loop if the trip count is less |
| 57 | /// than the unroll factor. |
| 58 | /// |
| 59 | static void ConnectProlog(Loop *L, Value *TripCount, unsigned Count, |
| 60 | BasicBlock *LastPrologBB, BasicBlock *PrologEnd, |
| 61 | BasicBlock *OrigPH, BasicBlock *NewPH, |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 62 | ValueToValueMapTy &VMap, Pass *P) { |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 63 | BasicBlock *Latch = L->getLoopLatch(); |
Craig Topper | e73658d | 2014-04-28 04:05:08 +0000 | [diff] [blame] | 64 | assert(Latch && "Loop must have a latch"); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 65 | |
| 66 | // Create a PHI node for each outgoing value from the original loop |
| 67 | // (which means it is an outgoing value from the prolog code too). |
| 68 | // The new PHI node is inserted in the prolog end basic block. |
| 69 | // The new PHI name is added as an operand of a PHI node in either |
| 70 | // the loop header or the loop exit block. |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 71 | for (succ_iterator SBI = succ_begin(Latch), SBE = succ_end(Latch); |
| 72 | SBI != SBE; ++SBI) { |
| 73 | for (BasicBlock::iterator BBI = (*SBI)->begin(); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 74 | PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) { |
| 75 | |
| 76 | // Add a new PHI node to the prolog end block and add the |
| 77 | // appropriate incoming values. |
| 78 | PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName()+".unr", |
| 79 | PrologEnd->getTerminator()); |
| 80 | // Adding a value to the new PHI node from the original loop preheader. |
| 81 | // This is the value that skips all the prolog code. |
| 82 | if (L->contains(PN)) { |
| 83 | NewPN->addIncoming(PN->getIncomingValueForBlock(NewPH), OrigPH); |
| 84 | } else { |
| 85 | NewPN->addIncoming(Constant::getNullValue(PN->getType()), OrigPH); |
| 86 | } |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 87 | |
| 88 | Value *V = PN->getIncomingValueForBlock(Latch); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 89 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 90 | if (L->contains(I)) { |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 91 | V = VMap[I]; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 92 | } |
| 93 | } |
| 94 | // Adding a value to the new PHI node from the last prolog block |
| 95 | // that was created. |
| 96 | NewPN->addIncoming(V, LastPrologBB); |
| 97 | |
| 98 | // Update the existing PHI node operand with the value from the |
| 99 | // new PHI node. How this is done depends on if the existing |
| 100 | // PHI node is in the original loop block, or the exit block. |
| 101 | if (L->contains(PN)) { |
| 102 | PN->setIncomingValue(PN->getBasicBlockIndex(NewPH), NewPN); |
| 103 | } else { |
| 104 | PN->addIncoming(NewPN, PrologEnd); |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | // Create a branch around the orignal loop, which is taken if the |
| 110 | // trip count is less than the unroll factor. |
| 111 | Instruction *InsertPt = PrologEnd->getTerminator(); |
| 112 | Instruction *BrLoopExit = |
| 113 | new ICmpInst(InsertPt, ICmpInst::ICMP_ULT, TripCount, |
| 114 | ConstantInt::get(TripCount->getType(), Count)); |
| 115 | BasicBlock *Exit = L->getUniqueExitBlock(); |
Craig Topper | e73658d | 2014-04-28 04:05:08 +0000 | [diff] [blame] | 116 | assert(Exit && "Loop must have a single exit block only"); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 117 | // Split the exit to maintain loop canonicalization guarantees |
| 118 | SmallVector<BasicBlock*, 4> Preds(pred_begin(Exit), pred_end(Exit)); |
| 119 | if (!Exit->isLandingPad()) { |
Jakub Staszak | f5b32e5 | 2011-12-09 21:19:53 +0000 | [diff] [blame] | 120 | SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", P); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 121 | } else { |
| 122 | SmallVector<BasicBlock*, 2> NewBBs; |
| 123 | SplitLandingPadPredecessors(Exit, Preds, ".unr1-lcssa", ".unr2-lcssa", |
| 124 | P, NewBBs); |
| 125 | } |
| 126 | // Add the branch to the exit block (around the unrolled loop) |
| 127 | BranchInst::Create(Exit, NewPH, BrLoopExit, InsertPt); |
| 128 | InsertPt->eraseFromParent(); |
| 129 | } |
| 130 | |
| 131 | /// Create a clone of the blocks in a loop and connect them together. |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 132 | /// If UnrollProlog is true, loop structure will not be cloned, otherwise a new |
| 133 | /// loop will be created including all cloned blocks, and the iterator of it |
| 134 | /// switches to count NewIter down to 0. |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 135 | /// |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 136 | static void CloneLoopBlocks(Loop *L, Value *NewIter, const bool UnrollProlog, |
| 137 | BasicBlock *InsertTop, BasicBlock *InsertBot, |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 138 | std::vector<BasicBlock *> &NewBlocks, |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 139 | LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap, |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 140 | LoopInfo *LI) { |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 141 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 142 | BasicBlock *Header = L->getHeader(); |
| 143 | BasicBlock *Latch = L->getLoopLatch(); |
| 144 | Function *F = Header->getParent(); |
| 145 | LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); |
| 146 | LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 147 | Loop *NewLoop = 0; |
| 148 | Loop *ParentLoop = L->getParentLoop(); |
| 149 | if (!UnrollProlog) { |
| 150 | NewLoop = new Loop(); |
| 151 | if (ParentLoop) |
| 152 | ParentLoop->addChildLoop(NewLoop); |
| 153 | else |
| 154 | LI->addTopLevelLoop(NewLoop); |
| 155 | } |
| 156 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 157 | // For each block in the original loop, create a new copy, |
| 158 | // and update the value map with the newly created values. |
| 159 | for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 160 | BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".prol", F); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 161 | NewBlocks.push_back(NewBB); |
| 162 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 163 | if (NewLoop) |
Chandler Carruth | 691addc | 2015-01-18 01:25:51 +0000 | [diff] [blame] | 164 | NewLoop->addBasicBlockToLoop(NewBB, *LI); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 165 | else if (ParentLoop) |
Chandler Carruth | 691addc | 2015-01-18 01:25:51 +0000 | [diff] [blame] | 166 | ParentLoop->addBasicBlockToLoop(NewBB, *LI); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 167 | |
| 168 | VMap[*BB] = NewBB; |
| 169 | if (Header == *BB) { |
| 170 | // For the first block, add a CFG connection to this newly |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 171 | // created block. |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 172 | InsertTop->getTerminator()->setSuccessor(0, NewBB); |
| 173 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 174 | } |
| 175 | if (Latch == *BB) { |
| 176 | // For the last block, if UnrollProlog is true, create a direct jump to |
| 177 | // InsertBot. If not, create a loop back to cloned head. |
| 178 | VMap.erase((*BB)->getTerminator()); |
| 179 | BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]); |
| 180 | BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator()); |
| 181 | if (UnrollProlog) { |
| 182 | LatchBR->eraseFromParent(); |
| 183 | BranchInst::Create(InsertBot, NewBB); |
| 184 | } else { |
| 185 | PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, "prol.iter", |
| 186 | FirstLoopBB->getFirstNonPHI()); |
| 187 | IRBuilder<> Builder(LatchBR); |
| 188 | Value *IdxSub = |
| 189 | Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), |
| 190 | NewIdx->getName() + ".sub"); |
| 191 | Value *IdxCmp = |
| 192 | Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp"); |
| 193 | BranchInst::Create(FirstLoopBB, InsertBot, IdxCmp, NewBB); |
| 194 | NewIdx->addIncoming(NewIter, InsertTop); |
| 195 | NewIdx->addIncoming(IdxSub, NewBB); |
| 196 | LatchBR->eraseFromParent(); |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // Change the incoming values to the ones defined in the preheader or |
| 202 | // cloned loop. |
| 203 | for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { |
| 204 | PHINode *NewPHI = cast<PHINode>(VMap[I]); |
| 205 | if (UnrollProlog) { |
| 206 | VMap[I] = NewPHI->getIncomingValueForBlock(Preheader); |
| 207 | cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); |
| 208 | } else { |
| 209 | unsigned idx = NewPHI->getBasicBlockIndex(Preheader); |
| 210 | NewPHI->setIncomingBlock(idx, InsertTop); |
| 211 | BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); |
| 212 | idx = NewPHI->getBasicBlockIndex(Latch); |
| 213 | Value *InVal = NewPHI->getIncomingValue(idx); |
| 214 | NewPHI->setIncomingBlock(idx, NewLatch); |
| 215 | if (VMap[InVal]) |
| 216 | NewPHI->setIncomingValue(idx, VMap[InVal]); |
| 217 | } |
| 218 | } |
| 219 | if (NewLoop) { |
| 220 | // 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] | 221 | SmallVector<Metadata *, 4> MDs; |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 222 | // 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] | 223 | MDs.push_back(nullptr); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 224 | MDNode *LoopID = NewLoop->getLoopID(); |
| 225 | if (LoopID) { |
| 226 | // First remove any existing loop unrolling metadata. |
| 227 | for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { |
| 228 | bool IsUnrollMetadata = false; |
| 229 | MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); |
| 230 | if (MD) { |
| 231 | const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); |
| 232 | IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 233 | } |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 234 | if (!IsUnrollMetadata) |
| 235 | MDs.push_back(LoopID->getOperand(i)); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 236 | } |
| 237 | } |
| 238 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 239 | LLVMContext &Context = NewLoop->getHeader()->getContext(); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 240 | SmallVector<Metadata *, 1> DisableOperands; |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 241 | DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); |
| 242 | MDNode *DisableNode = MDNode::get(Context, DisableOperands); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 243 | MDs.push_back(DisableNode); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 244 | |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 245 | MDNode *NewLoopID = MDNode::get(Context, MDs); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 246 | // Set operand 0 to refer to the loop id itself. |
| 247 | NewLoopID->replaceOperandWith(0, NewLoopID); |
| 248 | NewLoop->setLoopID(NewLoopID); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 249 | } |
| 250 | } |
| 251 | |
| 252 | /// Insert code in the prolog code when unrolling a loop with a |
| 253 | /// run-time trip-count. |
| 254 | /// |
| 255 | /// This method assumes that the loop unroll factor is total number |
| 256 | /// of loop bodes in the loop after unrolling. (Some folks refer |
| 257 | /// to the unroll factor as the number of *extra* copies added). |
| 258 | /// We assume also that the loop unroll factor is a power-of-two. So, after |
| 259 | /// unrolling the loop, the number of loop bodies executed is 2, |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 260 | /// 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] | 261 | /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for |
| 262 | /// the switch instruction is generated. |
| 263 | /// |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 264 | /// extraiters = tripcount % loopfactor |
| 265 | /// if (extraiters == 0) jump Loop: |
| 266 | /// else jump Prol |
| 267 | /// Prol: LoopBody; |
| 268 | /// extraiters -= 1 // Omitted if unroll factor is 2. |
| 269 | /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2. |
| 270 | /// if (tripcount < loopfactor) jump End |
| 271 | /// Loop: |
| 272 | /// ... |
| 273 | /// End: |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 274 | /// |
| 275 | bool llvm::UnrollRuntimeLoopProlog(Loop *L, unsigned Count, LoopInfo *LI, |
| 276 | LPPassManager *LPM) { |
| 277 | // for now, only unroll loops that contain a single exit |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 278 | if (!L->getExitingBlock()) |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 279 | return false; |
| 280 | |
| 281 | // Make sure the loop is in canonical form, and there is a single |
| 282 | // exit block only. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 283 | if (!L->isLoopSimplifyForm() || !L->getUniqueExitBlock()) |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 284 | return false; |
| 285 | |
| 286 | // Use Scalar Evolution to compute the trip count. This allows more |
| 287 | // loops to be unrolled than relying on induction var simplification |
Andrew Trick | d29cd73 | 2012-05-08 02:52:09 +0000 | [diff] [blame] | 288 | if (!LPM) |
| 289 | return false; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 290 | ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>(); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 291 | if (!SE) |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 292 | return false; |
| 293 | |
| 294 | // Only unroll loops with a computable trip count and the trip count needs |
| 295 | // to be an int value (allowing a pointer type is a TODO item) |
| 296 | const SCEV *BECount = SE->getBackedgeTakenCount(L); |
| 297 | if (isa<SCEVCouldNotCompute>(BECount) || !BECount->getType()->isIntegerTy()) |
| 298 | return false; |
| 299 | |
Michael Zolotukhin | 0dcae71 | 2014-11-20 20:19:55 +0000 | [diff] [blame] | 300 | // If BECount is INT_MAX, we can't compute trip-count without overflow. |
| 301 | if (BECount->isAllOnesValue()) |
| 302 | return false; |
| 303 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 304 | // 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] | 305 | const SCEV *TripCountSC = |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 306 | SE->getAddExpr(BECount, SE->getConstant(BECount->getType(), 1)); |
| 307 | if (isa<SCEVCouldNotCompute>(TripCountSC)) |
| 308 | return false; |
| 309 | |
| 310 | // We only handle cases when the unroll factor is a power of 2. |
| 311 | // Count is the loop unroll factor, the number of extra copies added + 1. |
| 312 | if ((Count & (Count-1)) != 0) |
| 313 | return false; |
| 314 | |
| 315 | // If this loop is nested, then the loop unroller changes the code in |
| 316 | // parent loop, so the Scalar Evolution pass needs to be run again |
| 317 | if (Loop *ParentLoop = L->getParentLoop()) |
| 318 | SE->forgetLoop(ParentLoop); |
| 319 | |
Chandler Carruth | 32c52c7 | 2015-01-18 02:39:37 +0000 | [diff] [blame^] | 320 | // Grab the dominator tree so we can preserve it. |
| 321 | auto *DTWP = LPM->getAnalysisIfAvailable<DominatorTreeWrapperPass>(); |
| 322 | auto *DT = DTWP ? &DTWP->getDomTree() : nullptr; |
| 323 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 324 | BasicBlock *PH = L->getLoopPreheader(); |
| 325 | BasicBlock *Header = L->getHeader(); |
| 326 | BasicBlock *Latch = L->getLoopLatch(); |
| 327 | // It helps to splits the original preheader twice, one for the end of the |
| 328 | // prolog code and one for a new loop preheader |
| 329 | BasicBlock *PEnd = SplitEdge(PH, Header, LPM->getAsPass()); |
Chandler Carruth | 32c52c7 | 2015-01-18 02:39:37 +0000 | [diff] [blame^] | 330 | BasicBlock *NewPH = SplitBlock(PEnd, PEnd->getTerminator(), DT, LI); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 331 | BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator()); |
| 332 | |
| 333 | // Compute the number of extra iterations required, which is: |
| 334 | // extra iterations = run-time trip count % (loop unroll factor + 1) |
| 335 | SCEVExpander Expander(*SE, "loop-unroll"); |
| 336 | Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(), |
| 337 | PreHeaderBR); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 338 | |
Benjamin Kramer | 0bf086f | 2014-06-21 13:46:25 +0000 | [diff] [blame] | 339 | IRBuilder<> B(PreHeaderBR); |
| 340 | Value *ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter"); |
| 341 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 342 | // Check if for no extra iterations, then jump to cloned/unrolled loop. |
| 343 | // We have to check that the trip count computation didn't overflow when |
| 344 | // adding one to the backedge taken count. |
Benjamin Kramer | 0bf086f | 2014-06-21 13:46:25 +0000 | [diff] [blame] | 345 | Value *LCmp = B.CreateIsNotNull(ModVal, "lcmp.mod"); |
| 346 | Value *OverflowCheck = B.CreateIsNull(TripCount, "lcmp.overflow"); |
| 347 | Value *BranchVal = B.CreateOr(OverflowCheck, LCmp, "lcmp.or"); |
| 348 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 349 | // Branch to either the extra iterations or the cloned/unrolled loop |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 350 | // We will fix up the true branch label when adding loop body copies |
| 351 | BranchInst::Create(PEnd, PEnd, BranchVal, PreHeaderBR); |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 352 | assert(PreHeaderBR->isUnconditional() && |
| 353 | PreHeaderBR->getSuccessor(0) == PEnd && |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 354 | "CFG edges in Preheader are not correct"); |
| 355 | PreHeaderBR->eraseFromParent(); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 356 | Function *F = Header->getParent(); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 357 | // Get an ordered list of blocks in the loop to help with the ordering of the |
| 358 | // cloned blocks in the prolog code |
| 359 | LoopBlocksDFS LoopBlocks(L); |
| 360 | LoopBlocks.perform(LI); |
| 361 | |
| 362 | // |
| 363 | // For each extra loop iteration, create a copy of the loop's basic blocks |
| 364 | // and generate a condition that branches to the copy depending on the |
| 365 | // number of 'left over' iterations. |
| 366 | // |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 367 | std::vector<BasicBlock *> NewBlocks; |
| 368 | ValueToValueMapTy VMap; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 369 | |
Michael Zolotukhin | 0dcae71 | 2014-11-20 20:19:55 +0000 | [diff] [blame] | 370 | // If unroll count is 2 and we can't overflow in tripcount computation (which |
| 371 | // is BECount + 1), then we don't need a loop for prologue, and we can unroll |
| 372 | // it. We can be sure that we don't overflow only if tripcount is a constant. |
| 373 | bool UnrollPrologue = (Count == 2 && isa<ConstantInt>(TripCount)); |
| 374 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 375 | // Clone all the basic blocks in the loop. If Count is 2, we don't clone |
| 376 | // the loop, otherwise we create a cloned loop to execute the extra |
| 377 | // iterations. This function adds the appropriate CFG connections. |
Michael Zolotukhin | 0dcae71 | 2014-11-20 20:19:55 +0000 | [diff] [blame] | 378 | CloneLoopBlocks(L, ModVal, UnrollPrologue, PH, PEnd, NewBlocks, LoopBlocks, |
| 379 | VMap, LI); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 380 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 381 | // Insert the cloned blocks into function just before the original loop |
| 382 | F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0], |
| 383 | F->end()); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 384 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 385 | // Rewrite the cloned instruction operands to use the values |
| 386 | // created when the clone is created. |
| 387 | for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) { |
| 388 | for (BasicBlock::iterator I = NewBlocks[i]->begin(), |
| 389 | E = NewBlocks[i]->end(); |
| 390 | I != E; ++I) { |
| 391 | RemapInstruction(I, VMap, |
| 392 | RF_NoModuleLevelChanges | RF_IgnoreMissingEntries); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 393 | } |
| 394 | } |
| 395 | |
| 396 | // Connect the prolog code to the original loop and update the |
| 397 | // PHI functions. |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 398 | BasicBlock *LastLoopBB = cast<BasicBlock>(VMap[Latch]); |
| 399 | ConnectProlog(L, TripCount, Count, LastLoopBB, PEnd, PH, NewPH, VMap, |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 400 | LPM->getAsPass()); |
| 401 | NumRuntimeUnrolled++; |
| 402 | return true; |
| 403 | } |