blob: faaab5c12e4cfb1807e6c552935d04f8eba63531 [file] [log] [blame]
Dan Gohman3dc2d922008-05-14 00:24:14 +00001//===-- UnrollLoop.cpp - 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. It does not define any
11// actual pass or policy, but provides a single function to perform loop
12// unrolling.
13//
Dan Gohman3dc2d922008-05-14 00:24:14 +000014// The process of unrolling can produce extraneous basic blocks linked with
15// unconditional branches. This will be corrected in the future.
Chris Lattnerdfcfcb42011-01-11 08:00:40 +000016//
Dan Gohman3dc2d922008-05-14 00:24:14 +000017//===----------------------------------------------------------------------===//
18
Dan Gohman3dc2d922008-05-14 00:24:14 +000019#include "llvm/Transforms/Utils/UnrollLoop.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000020#include "llvm/ADT/Statistic.h"
Duncan Sands433c1672010-11-23 20:26:33 +000021#include "llvm/Analysis/InstructionSimplify.h"
Andrew Trickb72bbe22011-08-10 00:28:10 +000022#include "llvm/Analysis/LoopIterator.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000023#include "llvm/Analysis/LoopPass.h"
Dan Gohmana7908ae2010-07-26 18:02:06 +000024#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/BasicBlock.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000026#include "llvm/IR/Dominators.h"
Diego Novillo34fc8a72014-04-29 14:27:31 +000027#include "llvm/IR/LLVMContext.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000028#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000031#include "llvm/Transforms/Utils/Cloning.h"
32#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +000033#include "llvm/Transforms/Utils/LoopUtils.h"
Andrew Trick4d0040b2011-08-10 04:29:49 +000034#include "llvm/Transforms/Utils/SimplifyIndVar.h"
Dan Gohman3dc2d922008-05-14 00:24:14 +000035using namespace llvm;
36
Chandler Carruth964daaa2014-04-22 02:55:47 +000037#define DEBUG_TYPE "loop-unroll"
38
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000039// TODO: Should these be here or in LoopUnroll?
Dan Gohman3dc2d922008-05-14 00:24:14 +000040STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
Chris Lattnerdfcfcb42011-01-11 08:00:40 +000041STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
Dan Gohman3dc2d922008-05-14 00:24:14 +000042
43/// RemapInstruction - Convert the instruction operands from referencing the
Devang Patelb8f11de2010-06-23 23:55:51 +000044/// current values into those specified by VMap.
Dan Gohman3dc2d922008-05-14 00:24:14 +000045static inline void RemapInstruction(Instruction *I,
Rafael Espindola229e38f2010-10-13 01:36:30 +000046 ValueToValueMapTy &VMap) {
Dan Gohman3dc2d922008-05-14 00:24:14 +000047 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
48 Value *Op = I->getOperand(op);
Rafael Espindola229e38f2010-10-13 01:36:30 +000049 ValueToValueMapTy::iterator It = VMap.find(Op);
Devang Patelb8f11de2010-06-23 23:55:51 +000050 if (It != VMap.end())
Dan Gohmanfa8969f2009-10-31 14:46:50 +000051 I->setOperand(op, It->second);
Dan Gohman3dc2d922008-05-14 00:24:14 +000052 }
Jay Foad61ea0e42011-06-23 09:09:15 +000053
54 if (PHINode *PN = dyn_cast<PHINode>(I)) {
55 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
56 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
57 if (It != VMap.end())
58 PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
59 }
60 }
Dan Gohman3dc2d922008-05-14 00:24:14 +000061}
62
Dan Gohman2d02ff82009-10-31 17:33:01 +000063/// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
64/// only has one predecessor, and that predecessor only has one successor.
65/// The LoopInfo Analysis that is passed will be kept consistent.
66/// Returns the new combined block.
Andrew Trickbf69d032011-08-03 18:32:11 +000067static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI,
68 LPPassManager *LPM) {
Dan Gohman2d02ff82009-10-31 17:33:01 +000069 // Merge basic blocks into their predecessor if there is only one distinct
70 // pred, and if there is only one distinct successor of the predecessor, and
71 // if there are no PHI nodes.
72 BasicBlock *OnlyPred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +000073 if (!OnlyPred) return nullptr;
Dan Gohman2d02ff82009-10-31 17:33:01 +000074
75 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +000076 return nullptr;
Dan Gohman2d02ff82009-10-31 17:33:01 +000077
David Greene627f40a2010-01-05 01:26:41 +000078 DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
Dan Gohman2d02ff82009-10-31 17:33:01 +000079
80 // Resolve any PHI nodes at the start of the block. They are all
81 // guaranteed to have exactly one entry if they exist, unless there are
82 // multiple duplicate (but guaranteed to be equal) entries for the
83 // incoming edges. This occurs when there are multiple edges from
84 // OnlyPred to OnlySucc.
85 FoldSingleEntryPHINodes(BB);
86
87 // Delete the unconditional branch from the predecessor...
88 OnlyPred->getInstList().pop_back();
89
Dan Gohman2d02ff82009-10-31 17:33:01 +000090 // Make all PHI nodes that referred to BB now refer to Pred as their
91 // source...
92 BB->replaceAllUsesWith(OnlyPred);
93
Jay Foad61ea0e42011-06-23 09:09:15 +000094 // Move all definitions in the successor to the predecessor...
95 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
96
NAKAMURA Takumif9c83392013-11-17 18:05:34 +000097 // OldName will be valid until erased.
Jakub Staszak86a74922013-11-13 20:09:11 +000098 StringRef OldName = BB->getName();
Dan Gohman2d02ff82009-10-31 17:33:01 +000099
100 // Erase basic block from the function...
Andrew Trickbf69d032011-08-03 18:32:11 +0000101
102 // ScalarEvolution holds references to loop exit blocks.
Andrew Tricka6fb9102012-06-05 17:51:05 +0000103 if (LPM) {
104 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) {
105 if (Loop *L = LI->getLoopFor(BB))
106 SE->forgetLoop(L);
107 }
Andrew Trickbf69d032011-08-03 18:32:11 +0000108 }
Dan Gohman2d02ff82009-10-31 17:33:01 +0000109 LI->removeBlock(BB);
Dan Gohman2d02ff82009-10-31 17:33:01 +0000110
111 // Inherit predecessor's name if it exists...
112 if (!OldName.empty() && !OnlyPred->hasName())
113 OnlyPred->setName(OldName);
114
NAKAMURA Takumif9c83392013-11-17 18:05:34 +0000115 BB->eraseFromParent();
116
Dan Gohman2d02ff82009-10-31 17:33:01 +0000117 return OnlyPred;
118}
119
Dan Gohman3dc2d922008-05-14 00:24:14 +0000120/// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
Chris Lattner4a14fbc2011-02-18 04:25:21 +0000121/// if unrolling was successful, or false if the loop was unmodified. Unrolling
Dan Gohman3dc2d922008-05-14 00:24:14 +0000122/// can only fail when the loop's latch block is not terminated by a conditional
123/// branch instruction. However, if the trip count (and multiple) are not known,
124/// loop unrolling will mostly produce more code that is no faster.
125///
Andrew Trick990f7712011-07-25 22:17:47 +0000126/// TripCount is generally defined as the number of times the loop header
127/// executes. UnrollLoop relaxes the definition to permit early exits: here
128/// TripCount is the iteration on which control exits LatchBlock if no early
129/// exits were taken. Note that UnrollLoop assumes that the loop counter test
130/// terminates LatchBlock in order to remove unnecesssary instances of the
131/// test. In other words, control may exit the loop prior to TripCount
132/// iterations via an early branch, but control may not exit the loop from the
133/// LatchBlock's terminator prior to TripCount iterations.
134///
135/// Similarly, TripMultiple divides the number of times that the LatchBlock may
136/// execute without exiting the loop.
137///
Dan Gohman3dc2d922008-05-14 00:24:14 +0000138/// The LoopInfo Analysis that is passed will be kept consistent.
139///
140/// If a LoopPassManager is passed in, and the loop is fully removed, it will be
141/// removed from the LoopPassManager as well. LPM can also be NULL.
Andrew Trick4d0040b2011-08-10 04:29:49 +0000142///
143/// This utility preserves LoopInfo. If DominatorTree or ScalarEvolution are
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +0000144/// available from the Pass it must also preserve those analyses.
Andrew Trick1cabe542011-07-23 00:33:05 +0000145bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
Andrew Trickd04d15292011-12-09 06:19:40 +0000146 bool AllowRuntime, unsigned TripMultiple,
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +0000147 LoopInfo *LI, Pass *PP, LPPassManager *LPM) {
Dan Gohman415c64e2009-11-05 19:44:06 +0000148 BasicBlock *Preheader = L->getLoopPreheader();
149 if (!Preheader) {
David Greene627f40a2010-01-05 01:26:41 +0000150 DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
Dan Gohman415c64e2009-11-05 19:44:06 +0000151 return false;
152 }
153
Dan Gohman3dc2d922008-05-14 00:24:14 +0000154 BasicBlock *LatchBlock = L->getLoopLatch();
Dan Gohman415c64e2009-11-05 19:44:06 +0000155 if (!LatchBlock) {
David Greene627f40a2010-01-05 01:26:41 +0000156 DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
Dan Gohman415c64e2009-11-05 19:44:06 +0000157 return false;
158 }
159
Andrew Trick4442bfe2012-04-10 05:14:42 +0000160 // Loops with indirectbr cannot be cloned.
161 if (!L->isSafeToClone()) {
162 DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
163 return false;
164 }
165
Dan Gohman415c64e2009-11-05 19:44:06 +0000166 BasicBlock *Header = L->getHeader();
Dan Gohman3dc2d922008-05-14 00:24:14 +0000167 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Andrew Trick279e7a62011-07-23 00:29:16 +0000168
Dan Gohman3dc2d922008-05-14 00:24:14 +0000169 if (!BI || BI->isUnconditional()) {
170 // The loop-rotate pass can be helpful to avoid this in many cases.
David Greene627f40a2010-01-05 01:26:41 +0000171 DEBUG(dbgs() <<
Chris Lattnerb25de3f2009-08-23 04:37:46 +0000172 " Can't unroll; loop not terminated by a conditional branch.\n");
Dan Gohman3dc2d922008-05-14 00:24:14 +0000173 return false;
174 }
Andrew Trick279e7a62011-07-23 00:29:16 +0000175
Chris Lattner4a14fbc2011-02-18 04:25:21 +0000176 if (Header->hasAddressTaken()) {
177 // The loop-rotate pass can be helpful to avoid this in many cases.
178 DEBUG(dbgs() <<
179 " Won't unroll loop: address of header block is taken.\n");
180 return false;
181 }
Dan Gohman3dc2d922008-05-14 00:24:14 +0000182
Dan Gohman3dc2d922008-05-14 00:24:14 +0000183 if (TripCount != 0)
David Greene627f40a2010-01-05 01:26:41 +0000184 DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
Dan Gohman3dc2d922008-05-14 00:24:14 +0000185 if (TripMultiple != 1)
David Greene627f40a2010-01-05 01:26:41 +0000186 DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
Dan Gohman3dc2d922008-05-14 00:24:14 +0000187
188 // Effectively "DCE" unrolled iterations that are beyond the tripcount
189 // and will never be executed.
190 if (TripCount != 0 && Count > TripCount)
191 Count = TripCount;
192
Andrew Trickca3417e2011-12-16 02:03:48 +0000193 // Don't enter the unroll code if there is nothing to do. This way we don't
194 // need to support "partial unrolling by 1".
195 if (TripCount == 0 && Count < 2)
196 return false;
197
Dan Gohman3dc2d922008-05-14 00:24:14 +0000198 assert(Count > 0);
199 assert(TripMultiple > 0);
200 assert(TripCount == 0 || TripCount % TripMultiple == 0);
201
202 // Are we eliminating the loop control altogether?
203 bool CompletelyUnroll = Count == TripCount;
204
Andrew Trickd04d15292011-12-09 06:19:40 +0000205 // We assume a run-time trip count if the compiler cannot
206 // figure out the loop trip count and the unroll-runtime
207 // flag is specified.
208 bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
209
210 if (RuntimeTripCount && !UnrollRuntimeLoopProlog(L, Count, LI, LPM))
211 return false;
212
213 // Notify ScalarEvolution that the loop will be substantially changed,
214 // if not outright eliminated.
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +0000215 if (PP) {
216 ScalarEvolution *SE = PP->getAnalysisIfAvailable<ScalarEvolution>();
Andrew Trickd29cd732012-05-08 02:52:09 +0000217 if (SE)
218 SE->forgetLoop(L);
219 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000220
Dan Gohman3dc2d922008-05-14 00:24:14 +0000221 // If we know the trip count, we know the multiple...
222 unsigned BreakoutTrip = 0;
223 if (TripCount != 0) {
224 BreakoutTrip = TripCount % Count;
225 TripMultiple = 0;
226 } else {
227 // Figure out what multiple to use.
228 BreakoutTrip = TripMultiple =
229 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
230 }
231
Diego Novillo34fc8a72014-04-29 14:27:31 +0000232 // Report the unrolling decision.
233 DebugLoc LoopLoc = L->getStartLoc();
234 Function *F = Header->getParent();
235 LLVMContext &Ctx = F->getContext();
236
Dan Gohman3dc2d922008-05-14 00:24:14 +0000237 if (CompletelyUnroll) {
David Greene627f40a2010-01-05 01:26:41 +0000238 DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000239 << " with trip count " << TripCount << "!\n");
Diego Novillo34fc8a72014-04-29 14:27:31 +0000240 Ctx.emitOptimizationRemark(DEBUG_TYPE, *F, LoopLoc,
241 Twine("completely unrolled loop with ") +
242 Twine(TripCount) + " iterations");
Dan Gohman3dc2d922008-05-14 00:24:14 +0000243 } else {
David Greene627f40a2010-01-05 01:26:41 +0000244 DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000245 << " by " << Count);
Diego Novillo34fc8a72014-04-29 14:27:31 +0000246 Twine DiagMsg("unrolled loop by a factor of " + Twine(Count));
Dan Gohman3dc2d922008-05-14 00:24:14 +0000247 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
David Greene627f40a2010-01-05 01:26:41 +0000248 DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
Diego Novillo34fc8a72014-04-29 14:27:31 +0000249 DiagMsg.concat(" with a breakout at trip " + Twine(BreakoutTrip));
Dan Gohman3dc2d922008-05-14 00:24:14 +0000250 } else if (TripMultiple != 1) {
David Greene627f40a2010-01-05 01:26:41 +0000251 DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
Diego Novillo34fc8a72014-04-29 14:27:31 +0000252 DiagMsg.concat(" with " + Twine(TripMultiple) + " trips per branch");
Andrew Trickd04d15292011-12-09 06:19:40 +0000253 } else if (RuntimeTripCount) {
254 DEBUG(dbgs() << " with run-time trip count");
Diego Novillo34fc8a72014-04-29 14:27:31 +0000255 DiagMsg.concat(" with run-time trip count");
Dan Gohman3dc2d922008-05-14 00:24:14 +0000256 }
David Greene627f40a2010-01-05 01:26:41 +0000257 DEBUG(dbgs() << "!\n");
Diego Novillo34fc8a72014-04-29 14:27:31 +0000258 Ctx.emitOptimizationRemark(DEBUG_TYPE, *F, LoopLoc, DiagMsg);
Dan Gohman3dc2d922008-05-14 00:24:14 +0000259 }
260
Dan Gohman04c8bd72008-06-24 20:44:42 +0000261 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
Dan Gohman3dc2d922008-05-14 00:24:14 +0000262 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
263
264 // For the first iteration of the loop, we should use the precloned values for
265 // PHI nodes. Insert associations now.
Devang Patel21766432010-04-20 22:24:18 +0000266 ValueToValueMapTy LastValueMap;
Dan Gohman04c8bd72008-06-24 20:44:42 +0000267 std::vector<PHINode*> OrigPHINode;
Dan Gohman3dc2d922008-05-14 00:24:14 +0000268 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Andrew Trick5e0ee1c2011-08-09 03:11:29 +0000269 OrigPHINode.push_back(cast<PHINode>(I));
Dan Gohman3dc2d922008-05-14 00:24:14 +0000270 }
271
272 std::vector<BasicBlock*> Headers;
273 std::vector<BasicBlock*> Latches;
274 Headers.push_back(Header);
275 Latches.push_back(LatchBlock);
276
Andrew Trickb72bbe22011-08-10 00:28:10 +0000277 // The current on-the-fly SSA update requires blocks to be processed in
278 // reverse postorder so that LastValueMap contains the correct value at each
279 // exit.
280 LoopBlocksDFS DFS(L);
Andrew Trick78b40c32011-08-10 01:59:05 +0000281 DFS.perform(LI);
282
Andrew Trickb72bbe22011-08-10 00:28:10 +0000283 // Stash the DFS iterators before adding blocks to the loop.
284 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
285 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
286
Dan Gohman3dc2d922008-05-14 00:24:14 +0000287 for (unsigned It = 1; It != Count; ++It) {
Dan Gohman3dc2d922008-05-14 00:24:14 +0000288 std::vector<BasicBlock*> NewBlocks;
Andrew Trick279e7a62011-07-23 00:29:16 +0000289
Andrew Trickb72bbe22011-08-10 00:28:10 +0000290 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
Devang Patelb8f11de2010-06-23 23:55:51 +0000291 ValueToValueMapTy VMap;
292 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
Dan Gohman04c8bd72008-06-24 20:44:42 +0000293 Header->getParent()->getBasicBlockList().push_back(New);
Dan Gohman3dc2d922008-05-14 00:24:14 +0000294
Dan Gohman04c8bd72008-06-24 20:44:42 +0000295 // Loop over all of the PHI nodes in the block, changing them to use the
296 // incoming values from the previous block.
297 if (*BB == Header)
298 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
Devang Patelb8f11de2010-06-23 23:55:51 +0000299 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
Dan Gohman3dc2d922008-05-14 00:24:14 +0000300 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
301 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
Dan Gohman18fa5682009-12-18 01:24:09 +0000302 if (It > 1 && L->contains(InValI))
Dan Gohman3dc2d922008-05-14 00:24:14 +0000303 InVal = LastValueMap[InValI];
Devang Patelb8f11de2010-06-23 23:55:51 +0000304 VMap[OrigPHINode[i]] = InVal;
Dan Gohman3dc2d922008-05-14 00:24:14 +0000305 New->getInstList().erase(NewPHI);
306 }
307
308 // Update our running map of newest clones
Dan Gohman04c8bd72008-06-24 20:44:42 +0000309 LastValueMap[*BB] = New;
Devang Patelb8f11de2010-06-23 23:55:51 +0000310 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
Dan Gohman3dc2d922008-05-14 00:24:14 +0000311 VI != VE; ++VI)
312 LastValueMap[VI->first] = VI->second;
313
Dan Gohman04c8bd72008-06-24 20:44:42 +0000314 L->addBasicBlockToLoop(New, LI->getBase());
315
Andrew Trickb72bbe22011-08-10 00:28:10 +0000316 // Add phi entries for newly created values to all exit blocks.
317 for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
318 SI != SE; ++SI) {
319 if (L->contains(*SI))
320 continue;
321 for (BasicBlock::iterator BBI = (*SI)->begin();
322 PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
323 Value *Incoming = phi->getIncomingValueForBlock(*BB);
324 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
325 if (It != LastValueMap.end())
326 Incoming = It->second;
327 phi->addIncoming(Incoming, New);
328 }
329 }
Dan Gohman04c8bd72008-06-24 20:44:42 +0000330 // Keep track of new headers and latches as we create them, so that
331 // we can insert the proper branches later.
332 if (*BB == Header)
333 Headers.push_back(New);
Andrew Trickb72bbe22011-08-10 00:28:10 +0000334 if (*BB == LatchBlock)
Dan Gohman04c8bd72008-06-24 20:44:42 +0000335 Latches.push_back(New);
336
Dan Gohman04c8bd72008-06-24 20:44:42 +0000337 NewBlocks.push_back(New);
Dan Gohman3dc2d922008-05-14 00:24:14 +0000338 }
Andrew Trick279e7a62011-07-23 00:29:16 +0000339
Dan Gohman3dc2d922008-05-14 00:24:14 +0000340 // Remap all instructions in the most recent iteration
Dan Gohman04c8bd72008-06-24 20:44:42 +0000341 for (unsigned i = 0; i < NewBlocks.size(); ++i)
Dan Gohman3dc2d922008-05-14 00:24:14 +0000342 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
343 E = NewBlocks[i]->end(); I != E; ++I)
Rafael Espindola229e38f2010-10-13 01:36:30 +0000344 ::RemapInstruction(I, LastValueMap);
Dan Gohman3dc2d922008-05-14 00:24:14 +0000345 }
Andrew Trick279e7a62011-07-23 00:29:16 +0000346
Andrew Trickb72bbe22011-08-10 00:28:10 +0000347 // Loop over the PHI nodes in the original block, setting incoming values.
348 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
349 PHINode *PN = OrigPHINode[i];
350 if (CompletelyUnroll) {
Dan Gohman04c8bd72008-06-24 20:44:42 +0000351 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
352 Header->getInstList().erase(PN);
353 }
Andrew Trickb72bbe22011-08-10 00:28:10 +0000354 else if (Count > 1) {
355 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
356 // If this value was defined in the loop, take the value defined by the
357 // last iteration of the loop.
358 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
359 if (L->contains(InValI))
360 InVal = LastValueMap[InVal];
361 }
362 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
363 PN->addIncoming(InVal, Latches.back());
364 }
Dan Gohman04c8bd72008-06-24 20:44:42 +0000365 }
Dan Gohman3dc2d922008-05-14 00:24:14 +0000366
367 // Now that all the basic blocks for the unrolled iterations are in place,
368 // set up the branches to connect them.
Dan Gohman04c8bd72008-06-24 20:44:42 +0000369 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
Dan Gohman3dc2d922008-05-14 00:24:14 +0000370 // The original branch was replicated in each unrolled iteration.
Dan Gohman04c8bd72008-06-24 20:44:42 +0000371 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
Dan Gohman3dc2d922008-05-14 00:24:14 +0000372
373 // The branch destination.
Dan Gohman04c8bd72008-06-24 20:44:42 +0000374 unsigned j = (i + 1) % e;
375 BasicBlock *Dest = Headers[j];
Dan Gohman3dc2d922008-05-14 00:24:14 +0000376 bool NeedConditional = true;
377
Andrew Trickd04d15292011-12-09 06:19:40 +0000378 if (RuntimeTripCount && j != 0) {
379 NeedConditional = false;
380 }
381
Dan Gohman04c8bd72008-06-24 20:44:42 +0000382 // For a complete unroll, make the last iteration end with a branch
383 // to the exit block.
384 if (CompletelyUnroll && j == 0) {
Dan Gohman3dc2d922008-05-14 00:24:14 +0000385 Dest = LoopExit;
386 NeedConditional = false;
387 }
388
389 // If we know the trip count or a multiple of it, we can safely use an
390 // unconditional branch for some iterations.
Dan Gohman04c8bd72008-06-24 20:44:42 +0000391 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
Dan Gohman3dc2d922008-05-14 00:24:14 +0000392 NeedConditional = false;
393 }
394
395 if (NeedConditional) {
396 // Update the conditional branch's successor for the following
397 // iteration.
398 Term->setSuccessor(!ContinueOnTrue, Dest);
399 } else {
Andrew Trickb72bbe22011-08-10 00:28:10 +0000400 // Remove phi operands at this loop exit
401 if (Dest != LoopExit) {
402 BasicBlock *BB = Latches[i];
403 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
404 SI != SE; ++SI) {
405 if (*SI == Headers[i])
406 continue;
407 for (BasicBlock::iterator BBI = (*SI)->begin();
408 PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
409 Phi->removeIncomingValue(BB, false);
410 }
411 }
412 }
Jay Foad89afb432011-01-07 20:25:56 +0000413 // Replace the conditional branch with an unconditional one.
414 BranchInst::Create(Dest, Term);
415 Term->eraseFromParent();
Jay Foada97a2c92011-06-21 10:33:19 +0000416 }
417 }
418
Jay Foad61ea0e42011-06-23 09:09:15 +0000419 // Merge adjacent basic blocks, if possible.
420 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
421 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
422 if (Term->isUnconditional()) {
423 BasicBlock *Dest = Term->getSuccessor(0);
Andrew Trickbf69d032011-08-03 18:32:11 +0000424 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM))
Jay Foad61ea0e42011-06-23 09:09:15 +0000425 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
426 }
427 }
Andrew Trick279e7a62011-07-23 00:29:16 +0000428
Craig Topperf40110f2014-04-25 05:29:35 +0000429 DominatorTree *DT = nullptr;
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +0000430 if (PP) {
Andrew Trickd29cd732012-05-08 02:52:09 +0000431 // FIXME: Reconstruct dom info, because it is not preserved properly.
432 // Incrementally updating domtree after loop unrolling would be easy.
Chandler Carruth73523022014-01-13 13:07:17 +0000433 if (DominatorTreeWrapperPass *DTWP =
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +0000434 PP->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
435 DT = &DTWP->getDomTree();
436 DT->recalculate(*L->getHeader()->getParent());
437 }
Andrew Trick4d0040b2011-08-10 04:29:49 +0000438
Andrew Trickd29cd732012-05-08 02:52:09 +0000439 // Simplify any new induction variables in the partially unrolled loop.
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +0000440 ScalarEvolution *SE = PP->getAnalysisIfAvailable<ScalarEvolution>();
Andrew Trickd29cd732012-05-08 02:52:09 +0000441 if (SE && !CompletelyUnroll) {
442 SmallVector<WeakVH, 16> DeadInsts;
443 simplifyLoopIVs(L, SE, LPM, DeadInsts);
Andrew Trick4d0040b2011-08-10 04:29:49 +0000444
Andrew Trickd29cd732012-05-08 02:52:09 +0000445 // Aggressively clean up dead instructions that simplifyLoopIVs already
446 // identified. Any remaining should be cleaned up below.
447 while (!DeadInsts.empty())
448 if (Instruction *Inst =
449 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
450 RecursivelyDeleteTriviallyDeadInstructions(Inst);
451 }
Andrew Trick4d0040b2011-08-10 04:29:49 +0000452 }
Dan Gohman04c8bd72008-06-24 20:44:42 +0000453 // At this point, the code is well formed. We now do a quick sweep over the
454 // inserted code, doing constant propagation and dead code elimination as we
455 // go.
456 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
457 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
458 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
459 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
Dan Gohman3dc2d922008-05-14 00:24:14 +0000460 Instruction *Inst = I++;
461
462 if (isInstructionTriviallyDead(Inst))
Dan Gohman04c8bd72008-06-24 20:44:42 +0000463 (*BB)->getInstList().erase(Inst);
Duncan Sands433c1672010-11-23 20:26:33 +0000464 else if (Value *V = SimplifyInstruction(Inst))
465 if (LI->replacementPreservesLCSSAForm(Inst, V)) {
466 Inst->replaceAllUsesWith(V);
467 (*BB)->getInstList().erase(Inst);
468 }
Dan Gohman3dc2d922008-05-14 00:24:14 +0000469 }
Dan Gohman3dc2d922008-05-14 00:24:14 +0000470
471 NumCompletelyUnrolled += CompletelyUnroll;
472 ++NumUnrolled;
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +0000473
474 Loop *OuterL = L->getParentLoop();
Dan Gohman3dc2d922008-05-14 00:24:14 +0000475 // Remove the loop from the LoopPassManager if it's completely removed.
Craig Topperf40110f2014-04-25 05:29:35 +0000476 if (CompletelyUnroll && LPM != nullptr)
Dan Gohman3dc2d922008-05-14 00:24:14 +0000477 LPM->deleteLoopFromQueue(L);
478
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +0000479 // If we have a pass and a DominatorTree we should re-simplify impacted loops
480 // to ensure subsequent analyses can rely on this form. We want to simplify
481 // at least one layer outside of the loop that was unrolled so that any
482 // changes to the parent loop exposed by the unrolling are considered.
483 if (PP && DT) {
484 if (!OuterL && !CompletelyUnroll)
485 OuterL = L;
Chandler Carruthd84f7762014-01-28 01:25:38 +0000486 if (OuterL) {
487 ScalarEvolution *SE = PP->getAnalysisIfAvailable<ScalarEvolution>();
Craig Topperf40110f2014-04-25 05:29:35 +0000488 simplifyLoop(OuterL, DT, LI, PP, /*AliasAnalysis*/ nullptr, SE);
Chandler Carruthd84f7762014-01-28 01:25:38 +0000489 formLCSSARecursively(*OuterL, *DT, SE);
490 }
Chandler Carruthaa7fa5e2014-01-23 11:23:19 +0000491 }
492
Dan Gohman3dc2d922008-05-14 00:24:14 +0000493 return true;
494}