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