blob: 512f17433dce141b230809a724fc58f55bd149f8 [file] [log] [blame]
Devang Patelf42389f2007-04-07 01:25:15 +00001//===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Devang Patelf42389f2007-04-07 01:25:15 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Rotation Pass.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelf42389f2007-04-07 01:25:15 +000014#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000016#include "llvm/Analysis/AssumptionCache.h"
Chris Lattner679572e2011-01-02 07:35:53 +000017#include "llvm/Analysis/CodeMetrics.h"
Chris Lattner8c5defd2011-01-08 08:24:46 +000018#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/LoopPass.h"
Devang Patelfac4d1f2007-07-11 23:47:28 +000020#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Andrew Trick10cc4532012-02-14 00:00:23 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000023#include "llvm/IR/CFG.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000024#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Function.h"
26#include "llvm/IR/IntrinsicInst.h"
Owen Anderson115aa162014-05-26 08:58:51 +000027#include "llvm/Support/CommandLine.h"
Devang Patelf42389f2007-04-07 01:25:15 +000028#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
30#include "llvm/Transforms/Utils/Local.h"
31#include "llvm/Transforms/Utils/SSAUpdater.h"
32#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelf42389f2007-04-07 01:25:15 +000033using namespace llvm;
34
Chandler Carruth964daaa2014-04-22 02:55:47 +000035#define DEBUG_TYPE "loop-rotate"
36
Owen Anderson115aa162014-05-26 08:58:51 +000037static cl::opt<unsigned>
38DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
39 cl::desc("The default maximum header size for automatic loop rotation"));
Devang Patelf42389f2007-04-07 01:25:15 +000040
41STATISTIC(NumRotated, "Number of loops rotated");
42namespace {
43
Chris Lattner2dd09db2009-09-02 06:11:42 +000044 class LoopRotate : public LoopPass {
Devang Patelf42389f2007-04-07 01:25:15 +000045 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000046 static char ID; // Pass ID, replacement for typeid
Owen Anderson115aa162014-05-26 08:58:51 +000047 LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +000048 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
Owen Anderson115aa162014-05-26 08:58:51 +000049 if (SpecifiedMaxHeaderSize == -1)
50 MaxHeaderSize = DefaultRotationThreshold;
51 else
52 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
Owen Anderson6c18d1a2010-10-19 17:21:58 +000053 }
Devang Patel09f162c2007-05-01 21:15:47 +000054
Devang Patel88bc2c62007-04-09 16:11:48 +000055 // LCSSA form makes instruction renaming easier.
Craig Topper3e4c6972014-03-05 09:10:37 +000056 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +000057 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth73523022014-01-13 13:07:17 +000058 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +000059 AU.addRequired<LoopInfoWrapperPass>();
60 AU.addPreserved<LoopInfoWrapperPass>();
Devang Patela42c3142008-02-15 01:24:49 +000061 AU.addRequiredID(LoopSimplifyID);
62 AU.addPreservedID(LoopSimplifyID);
Devang Patelf42389f2007-04-07 01:25:15 +000063 AU.addRequiredID(LCSSAID);
64 AU.addPreservedID(LCSSAID);
Devang Patelfac4d1f2007-07-11 23:47:28 +000065 AU.addPreserved<ScalarEvolution>();
Chandler Carruthbb9caa92013-01-21 13:04:33 +000066 AU.addRequired<TargetTransformInfo>();
Devang Patelf42389f2007-04-07 01:25:15 +000067 }
68
Craig Topper3e4c6972014-03-05 09:10:37 +000069 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Andrew Trick9c72b072013-05-06 17:58:18 +000070 bool simplifyLoopLatch(Loop *L);
71 bool rotateLoop(Loop *L, bool SimplifiedLatch);
Andrew Tricka20f1982012-02-14 00:00:19 +000072
Devang Patelf42389f2007-04-07 01:25:15 +000073 private:
Owen Anderson115aa162014-05-26 08:58:51 +000074 unsigned MaxHeaderSize;
Chris Lattner25ba40a2011-01-08 17:38:45 +000075 LoopInfo *LI;
Chandler Carruthbb9caa92013-01-21 13:04:33 +000076 const TargetTransformInfo *TTI;
Chandler Carruth66b31302015-01-04 12:03:27 +000077 AssumptionCache *AC;
Devang Patelf42389f2007-04-07 01:25:15 +000078 };
Devang Patelf42389f2007-04-07 01:25:15 +000079}
Andrew Tricka20f1982012-02-14 00:00:19 +000080
Dan Gohmand78c4002008-05-13 00:00:25 +000081char LoopRotate::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000082INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Chandler Carruthbb9caa92013-01-21 13:04:33 +000083INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Chandler Carruth66b31302015-01-04 12:03:27 +000084INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth4f8f3072015-01-17 14:16:18 +000085INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +000086INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
87INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson8ac477f2010-10-12 19:48:12 +000088INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelf42389f2007-04-07 01:25:15 +000089
Owen Anderson115aa162014-05-26 08:58:51 +000090Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
91 return new LoopRotate(MaxHeaderSize);
92}
Devang Patelf42389f2007-04-07 01:25:15 +000093
Devang Patel88bc2c62007-04-09 16:11:48 +000094/// Rotate Loop L as many times as possible. Return true if
Dan Gohman091e4402009-06-25 00:22:44 +000095/// the loop is rotated at least once.
Chris Lattner385f2ec2011-01-08 17:48:33 +000096bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +000097 if (skipOptnoneFunction(L))
98 return false;
99
Alexey Bataevb97f9e82014-04-15 09:37:30 +0000100 // Save the loop metadata.
101 MDNode *LoopMD = L->getLoopID();
102
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000103 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000104 TTI = &getAnalysis<TargetTransformInfo>();
Chandler Carruth66b31302015-01-04 12:03:27 +0000105 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
106 *L->getHeader()->getParent());
Devang Patelfac4d1f2007-07-11 23:47:28 +0000107
Andrew Trick10cc4532012-02-14 00:00:23 +0000108 // Simplify the loop latch before attempting to rotate the header
109 // upward. Rotation may not be needed if the loop tail can be folded into the
110 // loop exit.
Andrew Trick9c72b072013-05-06 17:58:18 +0000111 bool SimplifiedLatch = simplifyLoopLatch(L);
Andrew Trick10cc4532012-02-14 00:00:23 +0000112
Devang Patelf42389f2007-04-07 01:25:15 +0000113 // One loop can be rotated multiple times.
Chris Lattner25ba40a2011-01-08 17:38:45 +0000114 bool MadeChange = false;
Andrew Trick9c72b072013-05-06 17:58:18 +0000115 while (rotateLoop(L, SimplifiedLatch)) {
Chris Lattner25ba40a2011-01-08 17:38:45 +0000116 MadeChange = true;
Andrew Trick9c72b072013-05-06 17:58:18 +0000117 SimplifiedLatch = false;
118 }
Alexey Bataevb97f9e82014-04-15 09:37:30 +0000119
120 // Restore the loop metadata.
121 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
122 if ((MadeChange || SimplifiedLatch) && LoopMD)
123 L->setLoopID(LoopMD);
124
Chris Lattner25ba40a2011-01-08 17:38:45 +0000125 return MadeChange;
Devang Patelf42389f2007-04-07 01:25:15 +0000126}
127
Chris Lattner30f318e2011-01-08 19:26:33 +0000128/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
129/// old header into the preheader. If there were uses of the values produced by
130/// these instruction that were outside of the loop, we have to insert PHI nodes
131/// to merge the two values. Do this now.
132static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
133 BasicBlock *OrigPreheader,
134 ValueToValueMapTy &ValueMap) {
135 // Remove PHI node entries that are no longer live.
136 BasicBlock::iterator I, E = OrigHeader->end();
137 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
138 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Tricka20f1982012-02-14 00:00:19 +0000139
Chris Lattner30f318e2011-01-08 19:26:33 +0000140 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
141 // as necessary.
142 SSAUpdater SSA;
143 for (I = OrigHeader->begin(); I != E; ++I) {
144 Value *OrigHeaderVal = I;
Andrew Tricka20f1982012-02-14 00:00:19 +0000145
Chris Lattner30f318e2011-01-08 19:26:33 +0000146 // If there are no uses of the value (e.g. because it returns void), there
147 // is nothing to rewrite.
148 if (OrigHeaderVal->use_empty())
149 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000150
Chris Lattner30f318e2011-01-08 19:26:33 +0000151 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
152
153 // The value now exits in two versions: the initial value in the preheader
154 // and the loop "next" value in the original header.
155 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
156 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
157 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Tricka20f1982012-02-14 00:00:19 +0000158
Chris Lattner30f318e2011-01-08 19:26:33 +0000159 // Visit each use of the OrigHeader instruction.
160 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
161 UE = OrigHeaderVal->use_end(); UI != UE; ) {
162 // Grab the use before incrementing the iterator.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000163 Use &U = *UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000164
Chris Lattner30f318e2011-01-08 19:26:33 +0000165 // Increment the iterator before removing the use from the list.
166 ++UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000167
Chris Lattner30f318e2011-01-08 19:26:33 +0000168 // SSAUpdater can't handle a non-PHI use in the same block as an
169 // earlier def. We can easily handle those cases manually.
170 Instruction *UserInst = cast<Instruction>(U.getUser());
171 if (!isa<PHINode>(UserInst)) {
172 BasicBlock *UserBB = UserInst->getParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000173
Chris Lattner30f318e2011-01-08 19:26:33 +0000174 // The original users in the OrigHeader are already using the
175 // original definitions.
176 if (UserBB == OrigHeader)
177 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000178
Chris Lattner30f318e2011-01-08 19:26:33 +0000179 // Users in the OrigPreHeader need to use the value to which the
180 // original definitions are mapped.
181 if (UserBB == OrigPreheader) {
182 U = OrigPreHeaderVal;
183 continue;
184 }
185 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000186
Chris Lattner30f318e2011-01-08 19:26:33 +0000187 // Anything else can be handled by SSAUpdater.
188 SSA.RewriteUse(U);
189 }
190 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000191}
Chris Lattner30f318e2011-01-08 19:26:33 +0000192
JF Bastienac8b66b2014-08-05 23:27:34 +0000193/// Determine whether the instructions in this range may be safely and cheaply
Andrew Trick10cc4532012-02-14 00:00:23 +0000194/// speculated. This is not an important enough situation to develop complex
195/// heuristics. We handle a single arithmetic instruction along with any type
196/// conversions.
197static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
Yi Jiangab19fff2014-10-29 20:19:47 +0000198 BasicBlock::iterator End, Loop *L) {
Andrew Trick10cc4532012-02-14 00:00:23 +0000199 bool seenIncrement = false;
Yi Jiangab19fff2014-10-29 20:19:47 +0000200 bool MultiExitLoop = false;
201
202 if (!L->getExitingBlock())
203 MultiExitLoop = true;
204
Andrew Trick10cc4532012-02-14 00:00:23 +0000205 for (BasicBlock::iterator I = Begin; I != End; ++I) {
206
207 if (!isSafeToSpeculativelyExecute(I))
208 return false;
209
210 if (isa<DbgInfoIntrinsic>(I))
211 continue;
212
213 switch (I->getOpcode()) {
214 default:
215 return false;
216 case Instruction::GetElementPtr:
217 // GEPs are cheap if all indices are constant.
218 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
219 return false;
220 // fall-thru to increment case
221 case Instruction::Add:
222 case Instruction::Sub:
223 case Instruction::And:
224 case Instruction::Or:
225 case Instruction::Xor:
226 case Instruction::Shl:
227 case Instruction::LShr:
Yi Jiangab19fff2014-10-29 20:19:47 +0000228 case Instruction::AShr: {
229 Value *IVOpnd = nullptr;
230 if (isa<ConstantInt>(I->getOperand(0)))
231 IVOpnd = I->getOperand(1);
232
233 if (isa<ConstantInt>(I->getOperand(1))) {
234 if (IVOpnd)
235 return false;
236
237 IVOpnd = I->getOperand(0);
238 }
239
240 // If increment operand is used outside of the loop, this speculation
241 // could cause extra live range interference.
242 if (MultiExitLoop && IVOpnd) {
243 for (User *UseI : IVOpnd->users()) {
244 auto *UserInst = cast<Instruction>(UseI);
245 if (!L->contains(UserInst))
246 return false;
247 }
248 }
249
Andrew Trick10cc4532012-02-14 00:00:23 +0000250 if (seenIncrement)
251 return false;
252 seenIncrement = true;
253 break;
Yi Jiangab19fff2014-10-29 20:19:47 +0000254 }
Andrew Trick10cc4532012-02-14 00:00:23 +0000255 case Instruction::Trunc:
256 case Instruction::ZExt:
257 case Instruction::SExt:
258 // ignore type conversions
259 break;
260 }
261 }
262 return true;
263}
264
265/// Fold the loop tail into the loop exit by speculating the loop tail
266/// instructions. Typically, this is a single post-increment. In the case of a
267/// simple 2-block loop, hoisting the increment can be much better than
JF Bastienac8b66b2014-08-05 23:27:34 +0000268/// duplicating the entire loop header. In the case of loops with early exits,
Andrew Trick10cc4532012-02-14 00:00:23 +0000269/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
270/// canonical form so downstream passes can handle it.
271///
272/// I don't believe this invalidates SCEV.
Andrew Trick9c72b072013-05-06 17:58:18 +0000273bool LoopRotate::simplifyLoopLatch(Loop *L) {
Andrew Trick10cc4532012-02-14 00:00:23 +0000274 BasicBlock *Latch = L->getLoopLatch();
275 if (!Latch || Latch->hasAddressTaken())
Andrew Trick9c72b072013-05-06 17:58:18 +0000276 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000277
278 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
279 if (!Jmp || !Jmp->isUnconditional())
Andrew Trick9c72b072013-05-06 17:58:18 +0000280 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000281
282 BasicBlock *LastExit = Latch->getSinglePredecessor();
283 if (!LastExit || !L->isLoopExiting(LastExit))
Andrew Trick9c72b072013-05-06 17:58:18 +0000284 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000285
286 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
287 if (!BI)
Andrew Trick9c72b072013-05-06 17:58:18 +0000288 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000289
Yi Jiangab19fff2014-10-29 20:19:47 +0000290 if (!shouldSpeculateInstrs(Latch->begin(), Jmp, L))
Andrew Trick9c72b072013-05-06 17:58:18 +0000291 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000292
293 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
294 << LastExit->getName() << "\n");
295
296 // Hoist the instructions from Latch into LastExit.
297 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
298
299 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
300 BasicBlock *Header = Jmp->getSuccessor(0);
301 assert(Header == L->getHeader() && "expected a backward branch");
302
303 // Remove Latch from the CFG so that LastExit becomes the new Latch.
304 BI->setSuccessor(FallThruPath, Header);
305 Latch->replaceSuccessorsPhiUsesWith(LastExit);
306 Jmp->eraseFromParent();
307
308 // Nuke the Latch block.
309 assert(Latch->empty() && "unable to evacuate Latch");
310 LI->removeBlock(Latch);
Chandler Carruth73523022014-01-13 13:07:17 +0000311 if (DominatorTreeWrapperPass *DTWP =
312 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
313 DTWP->getDomTree().eraseNode(Latch);
Andrew Trick10cc4532012-02-14 00:00:23 +0000314 Latch->eraseFromParent();
Andrew Trick9c72b072013-05-06 17:58:18 +0000315 return true;
Andrew Trick10cc4532012-02-14 00:00:23 +0000316}
317
Dan Gohmanb5650eb2007-05-11 21:10:54 +0000318/// Rotate loop LP. Return true if the loop is rotated.
Andrew Trick9c72b072013-05-06 17:58:18 +0000319///
320/// \param SimplifiedLatch is true if the latch was just folded into the final
321/// loop exit. In this case we may want to rotate even though the new latch is
322/// now an exiting branch. This rotation would have happened had the latch not
323/// been simplified. However, if SimplifiedLatch is false, then we avoid
324/// rotating loops in which the latch exits to avoid excessive or endless
325/// rotation. LoopRotate should be repeatable and converge to a canonical
326/// form. This property is satisfied because simplifying the loop latch can only
327/// happen once across multiple invocations of the LoopRotate pass.
328bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
Dan Gohman091e4402009-06-25 00:22:44 +0000329 // If the loop has only one block then there is not much to rotate.
Devang Patel88bc2c62007-04-09 16:11:48 +0000330 if (L->getBlocks().size() == 1)
Devang Patelf42389f2007-04-07 01:25:15 +0000331 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000332
Chris Lattner7fab23b2011-01-08 18:06:22 +0000333 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000334 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Tricka20f1982012-02-14 00:00:19 +0000335
Chris Lattner7fab23b2011-01-08 18:06:22 +0000336 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000337 if (!BI || BI->isUnconditional())
Chris Lattner7fab23b2011-01-08 18:06:22 +0000338 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000339
Dan Gohman091e4402009-06-25 00:22:44 +0000340 // If the loop header is not one of the loop exiting blocks then
341 // either this loop is already rotated or it is not
Devang Patelf42389f2007-04-07 01:25:15 +0000342 // suitable for loop rotation transformations.
Dan Gohman8f4078b2009-10-24 23:34:26 +0000343 if (!L->isLoopExiting(OrigHeader))
Devang Patelf42389f2007-04-07 01:25:15 +0000344 return false;
345
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000346 // If the loop latch already contains a branch that leaves the loop then the
347 // loop is already rotated.
Craig Topperf40110f2014-04-25 05:29:35 +0000348 if (!OrigLatch)
Andrew Trick9c72b072013-05-06 17:58:18 +0000349 return false;
350
351 // Rotate if either the loop latch does *not* exit the loop, or if the loop
352 // latch was just simplified.
353 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
Devang Patelf42389f2007-04-07 01:25:15 +0000354 return false;
355
James Molloy4f6fb952012-12-20 16:04:27 +0000356 // Check size of original header and reject loop if it is very big or we can't
357 // duplicate blocks inside it.
Chris Lattner679572e2011-01-02 07:35:53 +0000358 {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000359 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000360 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000361
Chris Lattner679572e2011-01-02 07:35:53 +0000362 CodeMetrics Metrics;
Hal Finkel57f03dd2014-09-07 13:49:57 +0000363 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
James Molloy4f6fb952012-12-20 16:04:27 +0000364 if (Metrics.notDuplicatable) {
Alp Tokerf907b892013-12-05 05:44:44 +0000365 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
James Molloy4f6fb952012-12-20 16:04:27 +0000366 << " instructions: "; L->dump());
367 return false;
368 }
Owen Anderson115aa162014-05-26 08:58:51 +0000369 if (Metrics.NumInsts > MaxHeaderSize)
Chris Lattner679572e2011-01-02 07:35:53 +0000370 return false;
Devang Patelbab43b42009-03-06 03:51:30 +0000371 }
372
Devang Patelfac4d1f2007-07-11 23:47:28 +0000373 // Now, this loop is suitable for rotation.
Chris Lattner30f318e2011-01-08 19:26:33 +0000374 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Tricka20f1982012-02-14 00:00:19 +0000375
Chris Lattner88974f42011-04-09 07:25:58 +0000376 // If the loop could not be converted to canonical form, it must have an
377 // indirectbr in it, just give up.
Craig Topperf40110f2014-04-25 05:29:35 +0000378 if (!OrigPreheader)
Chris Lattner88974f42011-04-09 07:25:58 +0000379 return false;
Devang Patelfac4d1f2007-07-11 23:47:28 +0000380
Dan Gohmanfc20b672009-09-27 15:37:03 +0000381 // Anything ScalarEvolution may know about this loop or the PHI nodes
382 // in its header will soon be invalidated.
383 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman880c92a2009-10-31 15:04:55 +0000384 SE->forgetLoop(L);
Dan Gohmanfc20b672009-09-27 15:37:03 +0000385
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000386 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
387
Devang Patelf42389f2007-04-07 01:25:15 +0000388 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattner57cb4722009-01-26 01:57:01 +0000389 // that is inside loop. Header's other successor is outside the
390 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner385f2ec2011-01-08 17:48:33 +0000391 BasicBlock *Exit = BI->getSuccessor(0);
392 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel88bc2c62007-04-09 16:11:48 +0000393 if (L->contains(Exit))
394 std::swap(Exit, NewHeader);
Chris Lattnerd67aaa62009-01-26 01:38:24 +0000395 assert(NewHeader && "Unable to determine new loop header");
Andrew Tricka20f1982012-02-14 00:00:19 +0000396 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel88bc2c62007-04-09 16:11:48 +0000397 "Unable to determine loop header and exit blocks");
Andrew Tricka20f1982012-02-14 00:00:19 +0000398
Dan Gohman091e4402009-06-25 00:22:44 +0000399 // This code assumes that the new header has exactly one predecessor.
400 // Remove any single-entry PHI nodes in it.
Chris Lattner7b6647c2009-01-26 02:11:30 +0000401 assert(NewHeader->getSinglePredecessor() &&
402 "New header doesn't have one pred!");
403 FoldSingleEntryPHINodes(NewHeader);
Devang Patelf42389f2007-04-07 01:25:15 +0000404
Dan Gohmanb9797942009-10-24 23:19:52 +0000405 // Begin by walking OrigHeader and populating ValueMap with an entry for
406 // each Instruction.
Devang Patel88bc2c62007-04-09 16:11:48 +0000407 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner2b3f20e2011-01-08 07:21:31 +0000408 ValueToValueMapTy ValueMap;
Devang Patelb9af5742007-04-09 19:04:21 +0000409
Dan Gohmanb9797942009-10-24 23:19:52 +0000410 // For PHI nodes, the value available in OldPreHeader is just the
411 // incoming value from OldPreHeader.
412 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foad372ad642011-06-20 14:18:48 +0000413 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000414
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000415 // For the rest of the instructions, either hoist to the OrigPreheader if
416 // possible or create a clone in the OldPreHeader if not.
Chris Lattner30f318e2011-01-08 19:26:33 +0000417 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000418 while (I != E) {
419 Instruction *Inst = I++;
Andrew Tricka20f1982012-02-14 00:00:19 +0000420
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000421 // If the instruction's operands are invariant and it doesn't read or write
422 // memory, then it is safe to hoist. Doing this doesn't change the order of
423 // execution in the preheader, but does prevent the instruction from
424 // executing in each iteration of the loop. This means it is safe to hoist
425 // something that might trap, but isn't safe to hoist something that reads
426 // memory (without proving that the loop doesn't write).
427 if (L->hasLoopInvariantOperands(Inst) &&
428 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
Eli Friedmanc4588852012-02-16 00:41:10 +0000429 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
430 !isa<AllocaInst>(Inst)) {
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000431 Inst->moveBefore(LoopEntryBranch);
432 continue;
433 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000434
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000435 // Otherwise, create a duplicate of the instruction.
436 Instruction *C = Inst->clone();
Andrew Tricka20f1982012-02-14 00:00:19 +0000437
Chris Lattner8c5defd2011-01-08 08:24:46 +0000438 // Eagerly remap the operands of the instruction.
439 RemapInstruction(C, ValueMap,
440 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Tricka20f1982012-02-14 00:00:19 +0000441
Chris Lattner8c5defd2011-01-08 08:24:46 +0000442 // With the operands remapped, see if the instruction constant folds or is
443 // otherwise simplifyable. This commonly occurs because the entry from PHI
444 // nodes allows icmps and other instructions to fold.
Chandler Carruth66b31302015-01-04 12:03:27 +0000445 // FIXME: Provide DL, TLI, DT, AC to SimplifyInstruction.
Chris Lattner25ba40a2011-01-08 17:38:45 +0000446 Value *V = SimplifyInstruction(C);
447 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000448 // If so, then delete the temporary instruction and stick the folded value
449 // in the map.
450 delete C;
451 ValueMap[Inst] = V;
452 } else {
453 // Otherwise, stick the new instruction into the new block!
454 C->setName(Inst->getName());
455 C->insertBefore(LoopEntryBranch);
456 ValueMap[Inst] = C;
457 }
Devang Patelf42389f2007-04-07 01:25:15 +0000458 }
459
Dan Gohmanb9797942009-10-24 23:19:52 +0000460 // Along with all the other instructions, we just cloned OrigHeader's
461 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
462 // successors by duplicating their incoming values for OrigHeader.
463 TerminatorInst *TI = OrigHeader->getTerminator();
464 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
465 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
466 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner30f318e2011-01-08 19:26:33 +0000467 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000468
Dan Gohmanb9797942009-10-24 23:19:52 +0000469 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
470 // OrigPreHeader's old terminator (the original branch into the loop), and
471 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
472 LoopEntryBranch->eraseFromParent();
Devang Patelf42389f2007-04-07 01:25:15 +0000473
Chris Lattner30f318e2011-01-08 19:26:33 +0000474 // If there were any uses of instructions in the duplicated block outside the
475 // loop, update them, inserting PHI nodes as required
476 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelf42389f2007-04-07 01:25:15 +0000477
Dan Gohmanb9797942009-10-24 23:19:52 +0000478 // NewHeader is now the header of the loop.
Devang Patelf42389f2007-04-07 01:25:15 +0000479 L->moveToHeader(NewHeader);
Chris Lattner26151302011-01-08 19:10:28 +0000480 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelf42389f2007-04-07 01:25:15 +0000481
Andrew Tricka20f1982012-02-14 00:00:19 +0000482
Chris Lattner59c82f82011-01-08 19:59:06 +0000483 // At this point, we've finished our major CFG changes. As part of cloning
484 // the loop into the preheader we've simplified instructions and the
485 // duplicated conditional branch may now be branching on a constant. If it is
486 // branching on a constant and if that constant means that we enter the loop,
487 // then we fold away the cond branch to an uncond branch. This simplifies the
488 // loop in cases important for nested loops, and it also means we don't have
489 // to split as many edges.
490 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
491 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
492 if (!isa<ConstantInt>(PHBI->getCondition()) ||
493 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
494 != NewHeader) {
495 // The conditional branch can't be folded, handle the general case.
496 // Update DominatorTree to reflect the CFG change we just made. Then split
497 // edges as necessary to preserve LoopSimplify form.
Chandler Carruth73523022014-01-13 13:07:17 +0000498 if (DominatorTreeWrapperPass *DTWP =
499 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
500 DominatorTree &DT = DTWP->getDomTree();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000501 // Everything that was dominated by the old loop header is now dominated
502 // by the original loop preheader. Conceptually the header was merged
503 // into the preheader, even though we reuse the actual block as a new
504 // loop latch.
Chandler Carruth73523022014-01-13 13:07:17 +0000505 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000506 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
507 OrigHeaderNode->end());
Chandler Carruth73523022014-01-13 13:07:17 +0000508 DomTreeNode *OrigPreheaderNode = DT.getNode(OrigPreheader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000509 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
Chandler Carruth73523022014-01-13 13:07:17 +0000510 DT.changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Tricka20f1982012-02-14 00:00:19 +0000511
Chandler Carruth73523022014-01-13 13:07:17 +0000512 assert(DT.getNode(Exit)->getIDom() == OrigPreheaderNode);
513 assert(DT.getNode(NewHeader)->getIDom() == OrigPreheaderNode);
Benjamin Kramer3be6a482012-09-01 12:04:51 +0000514
Chris Lattner59c82f82011-01-08 19:59:06 +0000515 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth73523022014-01-13 13:07:17 +0000516 DT.changeImmediateDominator(OrigHeader, OrigLatch);
Chris Lattner59c82f82011-01-08 19:59:06 +0000517 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000518
Chris Lattner59c82f82011-01-08 19:59:06 +0000519 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotem465834c2012-07-24 10:51:42 +0000520 // thus is not a preheader anymore.
521 // Split the edge to form a real preheader.
Chris Lattner59c82f82011-01-08 19:59:06 +0000522 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
523 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Tricka20f1982012-02-14 00:00:19 +0000524
Nadav Rotem465834c2012-07-24 10:51:42 +0000525 // Preserve canonical loop form, which means that 'Exit' should have only
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000526 // one predecessor. Note that Exit could be an exit block for multiple
527 // nested loops, causing both of the edges to now be critical and need to
528 // be split.
529 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
530 bool SplitLatchEdge = false;
531 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
532 PE = ExitPreds.end();
533 PI != PE; ++PI) {
534 // We only need to split loop exit edges.
535 Loop *PredLoop = LI->getLoopFor(*PI);
536 if (!PredLoop || PredLoop->contains(Exit))
537 continue;
538 SplitLatchEdge |= L->getLoopLatch() == *PI;
539 BasicBlock *ExitSplit = SplitCriticalEdge(*PI, Exit, this);
540 ExitSplit->moveBefore(Exit);
541 }
542 assert(SplitLatchEdge &&
543 "Despite splitting all preds, failed to split latch exit?");
Chris Lattner59c82f82011-01-08 19:59:06 +0000544 } else {
545 // We can fold the conditional branch in the preheader, this makes things
546 // simpler. The first step is to remove the extra edge to the Exit block.
547 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelc1f7c1d2011-04-29 20:38:55 +0000548 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
549 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner59c82f82011-01-08 19:59:06 +0000550 PHBI->eraseFromParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000551
Chris Lattner59c82f82011-01-08 19:59:06 +0000552 // With our CFG finalized, update DomTree if it is available.
Chandler Carruth73523022014-01-13 13:07:17 +0000553 if (DominatorTreeWrapperPass *DTWP =
554 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
555 DominatorTree &DT = DTWP->getDomTree();
Chris Lattner59c82f82011-01-08 19:59:06 +0000556 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth73523022014-01-13 13:07:17 +0000557 DT.changeImmediateDominator(NewHeader, OrigPreheader);
558 DT.changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000559
560 // Brute force incremental dominator tree update. Call
561 // findNearestCommonDominator on all CFG predecessors of each child of the
562 // original header.
Chandler Carruth73523022014-01-13 13:07:17 +0000563 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000564 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
565 OrigHeaderNode->end());
566 bool Changed;
567 do {
568 Changed = false;
569 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
570 DomTreeNode *Node = HeaderChildren[I];
571 BasicBlock *BB = Node->getBlock();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000572
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000573 pred_iterator PI = pred_begin(BB);
574 BasicBlock *NearestDom = *PI;
575 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
Chandler Carruth73523022014-01-13 13:07:17 +0000576 NearestDom = DT.findNearestCommonDominator(NearestDom, *PI);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000577
578 // Remember if this changes the DomTree.
579 if (Node->getIDom()->getBlock() != NearestDom) {
Chandler Carruth73523022014-01-13 13:07:17 +0000580 DT.changeImmediateDominator(BB, NearestDom);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000581 Changed = true;
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000582 }
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000583 }
584
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000585 // If the dominator changed, this may have an effect on other
586 // predecessors, continue until we reach a fixpoint.
587 } while (Changed);
Chris Lattner59c82f82011-01-08 19:59:06 +0000588 }
Devang Patelfac4d1f2007-07-11 23:47:28 +0000589 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000590
Chris Lattner59c82f82011-01-08 19:59:06 +0000591 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner063dca02011-01-08 18:52:51 +0000592 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnerfee37c52011-01-08 18:55:50 +0000593
Chris Lattner63fe78d2011-01-11 07:47:59 +0000594 // Now that the CFG and DomTree are in a consistent state again, try to merge
595 // the OrigHeader block into OrigLatch. This will succeed if they are
596 // connected by an unconditional branch. This is just a cleanup so the
597 // emitted code isn't too gross in this common case.
598 MergeBlockIntoPredecessor(OrigHeader, this);
Andrew Tricka20f1982012-02-14 00:00:19 +0000599
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000600 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
601
Chris Lattnerfee37c52011-01-08 18:55:50 +0000602 ++NumRotated;
603 return true;
Devang Patel85419782007-04-09 20:19:46 +0000604}