blob: e5689368de80d38073e51fd376630911e5a139cb [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
Justin Bognerd0d23412016-05-03 22:02:31 +000014#include "llvm/Transforms/Scalar/LoopRotation.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/Statistic.h"
Chandler Carruth08eebe22015-07-23 09:34:01 +000016#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000017#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000018#include "llvm/Analysis/BasicAliasAnalysis.h"
Chris Lattner679572e2011-01-02 07:35:53 +000019#include "llvm/Analysis/CodeMetrics.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000020#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000021#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/LoopPass.h"
Devang Patelfac4d1f2007-07-11 23:47:28 +000023#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000024#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Andrew Trick10cc4532012-02-14 00:00:23 +000026#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000027#include "llvm/IR/CFG.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/IntrinsicInst.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000031#include "llvm/IR/Module.h"
Owen Anderson115aa162014-05-26 08:58:51 +000032#include "llvm/Support/CommandLine.h"
Devang Patelf42389f2007-04-07 01:25:15 +000033#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000034#include "llvm/Support/raw_ostream.h"
Justin Bognerd0d23412016-05-03 22:02:31 +000035#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000036#include "llvm/Transforms/Scalar/LoopPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
38#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000039#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Transforms/Utils/SSAUpdater.h"
41#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelf42389f2007-04-07 01:25:15 +000042using namespace llvm;
43
Chandler Carruth964daaa2014-04-22 02:55:47 +000044#define DEBUG_TYPE "loop-rotate"
45
Sebastian Popdfb66a12016-06-14 14:44:05 +000046static cl::opt<unsigned> DefaultRotationThreshold(
47 "rotation-max-header-size", cl::init(16), cl::Hidden,
48 cl::desc("The default maximum header size for automatic loop rotation"));
Devang Patelf42389f2007-04-07 01:25:15 +000049
50STATISTIC(NumRotated, "Number of loops rotated");
Devang Patelf42389f2007-04-07 01:25:15 +000051
Benjamin Kramer4d098922016-07-10 11:28:51 +000052namespace {
Sebastian Popdfb66a12016-06-14 14:44:05 +000053/// A simple loop rotation transformation.
54class LoopRotate {
55 const unsigned MaxHeaderSize;
56 LoopInfo *LI;
57 const TargetTransformInfo *TTI;
Daniel Jasperaec2fa32016-12-19 08:22:17 +000058 AssumptionCache *AC;
Sebastian Popdfb66a12016-06-14 14:44:05 +000059 DominatorTree *DT;
60 ScalarEvolution *SE;
61
62public:
63 LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +000064 const TargetTransformInfo *TTI, AssumptionCache *AC,
65 DominatorTree *DT, ScalarEvolution *SE)
66 : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE) {
Sebastian Popdfb66a12016-06-14 14:44:05 +000067 }
68 bool processLoop(Loop *L);
69
70private:
71 bool rotateLoop(Loop *L, bool SimplifiedLatch);
72 bool simplifyLoopLatch(Loop *L);
73};
Benjamin Kramer4d098922016-07-10 11:28:51 +000074} // end anonymous namespace
Sebastian Popdfb66a12016-06-14 14:44:05 +000075
Chris Lattner30f318e2011-01-08 19:26:33 +000076/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
77/// old header into the preheader. If there were uses of the values produced by
78/// these instruction that were outside of the loop, we have to insert PHI nodes
79/// to merge the two values. Do this now.
80static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
81 BasicBlock *OrigPreheader,
Sam Parker0f4db382017-03-08 09:56:22 +000082 ValueToValueMapTy &ValueMap,
83 SmallVectorImpl<PHINode*> *InsertedPHIs) {
Chris Lattner30f318e2011-01-08 19:26:33 +000084 // Remove PHI node entries that are no longer live.
85 BasicBlock::iterator I, E = OrigHeader->end();
86 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
87 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Tricka20f1982012-02-14 00:00:19 +000088
Chris Lattner30f318e2011-01-08 19:26:33 +000089 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
90 // as necessary.
Sam Parker0f4db382017-03-08 09:56:22 +000091 SSAUpdater SSA(InsertedPHIs);
Chris Lattner30f318e2011-01-08 19:26:33 +000092 for (I = OrigHeader->begin(); I != E; ++I) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +000093 Value *OrigHeaderVal = &*I;
Andrew Tricka20f1982012-02-14 00:00:19 +000094
Chris Lattner30f318e2011-01-08 19:26:33 +000095 // If there are no uses of the value (e.g. because it returns void), there
96 // is nothing to rewrite.
97 if (OrigHeaderVal->use_empty())
98 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +000099
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000100 Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
Chris Lattner30f318e2011-01-08 19:26:33 +0000101
102 // The value now exits in two versions: the initial value in the preheader
103 // and the loop "next" value in the original header.
104 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
105 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
106 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Tricka20f1982012-02-14 00:00:19 +0000107
Chris Lattner30f318e2011-01-08 19:26:33 +0000108 // Visit each use of the OrigHeader instruction.
109 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
Sebastian Popdfb66a12016-06-14 14:44:05 +0000110 UE = OrigHeaderVal->use_end();
111 UI != UE;) {
Chris Lattner30f318e2011-01-08 19:26:33 +0000112 // Grab the use before incrementing the iterator.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000113 Use &U = *UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000114
Chris Lattner30f318e2011-01-08 19:26:33 +0000115 // Increment the iterator before removing the use from the list.
116 ++UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000117
Chris Lattner30f318e2011-01-08 19:26:33 +0000118 // SSAUpdater can't handle a non-PHI use in the same block as an
119 // earlier def. We can easily handle those cases manually.
120 Instruction *UserInst = cast<Instruction>(U.getUser());
121 if (!isa<PHINode>(UserInst)) {
122 BasicBlock *UserBB = UserInst->getParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000123
Chris Lattner30f318e2011-01-08 19:26:33 +0000124 // The original users in the OrigHeader are already using the
125 // original definitions.
126 if (UserBB == OrigHeader)
127 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000128
Chris Lattner30f318e2011-01-08 19:26:33 +0000129 // Users in the OrigPreHeader need to use the value to which the
130 // original definitions are mapped.
131 if (UserBB == OrigPreheader) {
132 U = OrigPreHeaderVal;
133 continue;
134 }
135 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000136
Chris Lattner30f318e2011-01-08 19:26:33 +0000137 // Anything else can be handled by SSAUpdater.
138 SSA.RewriteUse(U);
139 }
Chuang-Yu Cheng175741d2016-05-10 09:45:44 +0000140
141 // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
142 // intrinsics.
143 LLVMContext &C = OrigHeader->getContext();
144 if (auto *VAM = ValueAsMetadata::getIfExists(OrigHeaderVal)) {
145 if (auto *MAV = MetadataAsValue::getIfExists(C, VAM)) {
Sebastian Popdfb66a12016-06-14 14:44:05 +0000146 for (auto UI = MAV->use_begin(), E = MAV->use_end(); UI != E;) {
Chuang-Yu Cheng175741d2016-05-10 09:45:44 +0000147 // Grab the use before incrementing the iterator. Otherwise, altering
148 // the Use will invalidate the iterator.
149 Use &U = *UI++;
150 DbgInfoIntrinsic *UserInst = dyn_cast<DbgInfoIntrinsic>(U.getUser());
Sebastian Popdfb66a12016-06-14 14:44:05 +0000151 if (!UserInst)
152 continue;
Chuang-Yu Cheng175741d2016-05-10 09:45:44 +0000153
154 // The original users in the OrigHeader are already using the original
155 // definitions.
156 BasicBlock *UserBB = UserInst->getParent();
157 if (UserBB == OrigHeader)
158 continue;
159
160 // Users in the OrigPreHeader need to use the value to which the
161 // original definitions are mapped and anything else can be handled by
162 // the SSAUpdater. To avoid adding PHINodes, check if the value is
163 // available in UserBB, if not substitute undef.
164 Value *NewVal;
165 if (UserBB == OrigPreheader)
166 NewVal = OrigPreHeaderVal;
167 else if (SSA.HasValueForBlock(UserBB))
168 NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
169 else
170 NewVal = UndefValue::get(OrigHeaderVal->getType());
171 U = MetadataAsValue::get(C, ValueAsMetadata::get(NewVal));
172 }
173 }
174 }
Chris Lattner30f318e2011-01-08 19:26:33 +0000175 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000176}
Chris Lattner30f318e2011-01-08 19:26:33 +0000177
Sam Parker0f4db382017-03-08 09:56:22 +0000178/// Propagate dbg.value intrinsics through the newly inserted Phis.
179static void insertDebugValues(BasicBlock *OrigHeader,
180 SmallVectorImpl<PHINode*> &InsertedPHIs) {
181 ValueToValueMapTy DbgValueMap;
182
183 // Map existing PHI nodes to their dbg.values.
184 for (auto &I : *OrigHeader) {
185 if (auto DbgII = dyn_cast<DbgInfoIntrinsic>(&I)) {
186 if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
187 DbgValueMap.insert({Loc, DbgII});
188 }
189 }
190
191 // Then iterate through the new PHIs and look to see if they use one of the
192 // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
193 // propagate the info through the new PHI.
194 LLVMContext &C = OrigHeader->getContext();
195 for (auto PHI : InsertedPHIs) {
196 for (auto VI : PHI->operand_values()) {
197 auto V = DbgValueMap.find(VI);
198 if (V != DbgValueMap.end()) {
199 auto *DbgII = cast<DbgInfoIntrinsic>(V->second);
200 Instruction *NewDbgII = DbgII->clone();
201 auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
202 NewDbgII->setOperand(0, PhiMAV);
203 BasicBlock *Parent = PHI->getParent();
204 NewDbgII->insertBefore(Parent->getFirstNonPHIOrDbgOrLifetime());
205 }
206 }
207 }
208}
209
Dan Gohmanb5650eb2007-05-11 21:10:54 +0000210/// Rotate loop LP. Return true if the loop is rotated.
Andrew Trick9c72b072013-05-06 17:58:18 +0000211///
212/// \param SimplifiedLatch is true if the latch was just folded into the final
213/// loop exit. In this case we may want to rotate even though the new latch is
214/// now an exiting branch. This rotation would have happened had the latch not
215/// been simplified. However, if SimplifiedLatch is false, then we avoid
216/// rotating loops in which the latch exits to avoid excessive or endless
217/// rotation. LoopRotate should be repeatable and converge to a canonical
218/// form. This property is satisfied because simplifying the loop latch can only
219/// happen once across multiple invocations of the LoopRotate pass.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000220bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
Dan Gohman091e4402009-06-25 00:22:44 +0000221 // If the loop has only one block then there is not much to rotate.
Devang Patel88bc2c62007-04-09 16:11:48 +0000222 if (L->getBlocks().size() == 1)
Devang Patelf42389f2007-04-07 01:25:15 +0000223 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000224
Chris Lattner7fab23b2011-01-08 18:06:22 +0000225 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000226 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Tricka20f1982012-02-14 00:00:19 +0000227
Chris Lattner7fab23b2011-01-08 18:06:22 +0000228 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000229 if (!BI || BI->isUnconditional())
Chris Lattner7fab23b2011-01-08 18:06:22 +0000230 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000231
Dan Gohman091e4402009-06-25 00:22:44 +0000232 // If the loop header is not one of the loop exiting blocks then
233 // either this loop is already rotated or it is not
Devang Patelf42389f2007-04-07 01:25:15 +0000234 // suitable for loop rotation transformations.
Dan Gohman8f4078b2009-10-24 23:34:26 +0000235 if (!L->isLoopExiting(OrigHeader))
Devang Patelf42389f2007-04-07 01:25:15 +0000236 return false;
237
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000238 // If the loop latch already contains a branch that leaves the loop then the
239 // loop is already rotated.
Craig Topperf40110f2014-04-25 05:29:35 +0000240 if (!OrigLatch)
Andrew Trick9c72b072013-05-06 17:58:18 +0000241 return false;
242
243 // Rotate if either the loop latch does *not* exit the loop, or if the loop
244 // latch was just simplified.
245 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
Devang Patelf42389f2007-04-07 01:25:15 +0000246 return false;
247
James Molloy4f6fb952012-12-20 16:04:27 +0000248 // Check size of original header and reject loop if it is very big or we can't
249 // duplicate blocks inside it.
Chris Lattner679572e2011-01-02 07:35:53 +0000250 {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000251 SmallPtrSet<const Value *, 32> EphValues;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000252 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000253
Chris Lattner679572e2011-01-02 07:35:53 +0000254 CodeMetrics Metrics;
Hal Finkel57f03dd2014-09-07 13:49:57 +0000255 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
James Molloy4f6fb952012-12-20 16:04:27 +0000256 if (Metrics.notDuplicatable) {
Alp Tokerf907b892013-12-05 05:44:44 +0000257 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
Sebastian Popdfb66a12016-06-14 14:44:05 +0000258 << " instructions: ";
259 L->dump());
James Molloy4f6fb952012-12-20 16:04:27 +0000260 return false;
261 }
Justin Lebardf04d2a2016-02-12 21:01:33 +0000262 if (Metrics.convergent) {
263 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
Sebastian Popdfb66a12016-06-14 14:44:05 +0000264 "instructions: ";
265 L->dump());
Justin Lebardf04d2a2016-02-12 21:01:33 +0000266 return false;
267 }
Owen Anderson115aa162014-05-26 08:58:51 +0000268 if (Metrics.NumInsts > MaxHeaderSize)
Chris Lattner679572e2011-01-02 07:35:53 +0000269 return false;
Devang Patelbab43b42009-03-06 03:51:30 +0000270 }
271
Devang Patelfac4d1f2007-07-11 23:47:28 +0000272 // Now, this loop is suitable for rotation.
Chris Lattner30f318e2011-01-08 19:26:33 +0000273 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Tricka20f1982012-02-14 00:00:19 +0000274
Chris Lattner88974f42011-04-09 07:25:58 +0000275 // If the loop could not be converted to canonical form, it must have an
276 // indirectbr in it, just give up.
Craig Topperf40110f2014-04-25 05:29:35 +0000277 if (!OrigPreheader)
Chris Lattner88974f42011-04-09 07:25:58 +0000278 return false;
Devang Patelfac4d1f2007-07-11 23:47:28 +0000279
Dan Gohmanfc20b672009-09-27 15:37:03 +0000280 // Anything ScalarEvolution may know about this loop or the PHI nodes
281 // in its header will soon be invalidated.
Justin Bogner6291b582015-12-14 23:22:48 +0000282 if (SE)
283 SE->forgetLoop(L);
Dan Gohmanfc20b672009-09-27 15:37:03 +0000284
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000285 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
286
Devang Patelf42389f2007-04-07 01:25:15 +0000287 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattner57cb4722009-01-26 01:57:01 +0000288 // that is inside loop. Header's other successor is outside the
289 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner385f2ec2011-01-08 17:48:33 +0000290 BasicBlock *Exit = BI->getSuccessor(0);
291 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel88bc2c62007-04-09 16:11:48 +0000292 if (L->contains(Exit))
293 std::swap(Exit, NewHeader);
Chris Lattnerd67aaa62009-01-26 01:38:24 +0000294 assert(NewHeader && "Unable to determine new loop header");
Andrew Tricka20f1982012-02-14 00:00:19 +0000295 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel88bc2c62007-04-09 16:11:48 +0000296 "Unable to determine loop header and exit blocks");
Andrew Tricka20f1982012-02-14 00:00:19 +0000297
Dan Gohman091e4402009-06-25 00:22:44 +0000298 // This code assumes that the new header has exactly one predecessor.
299 // Remove any single-entry PHI nodes in it.
Chris Lattner7b6647c2009-01-26 02:11:30 +0000300 assert(NewHeader->getSinglePredecessor() &&
301 "New header doesn't have one pred!");
302 FoldSingleEntryPHINodes(NewHeader);
Devang Patelf42389f2007-04-07 01:25:15 +0000303
Dan Gohmanb9797942009-10-24 23:19:52 +0000304 // Begin by walking OrigHeader and populating ValueMap with an entry for
305 // each Instruction.
Devang Patel88bc2c62007-04-09 16:11:48 +0000306 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner2b3f20e2011-01-08 07:21:31 +0000307 ValueToValueMapTy ValueMap;
Devang Patelb9af5742007-04-09 19:04:21 +0000308
Dan Gohmanb9797942009-10-24 23:19:52 +0000309 // For PHI nodes, the value available in OldPreHeader is just the
310 // incoming value from OldPreHeader.
311 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foad372ad642011-06-20 14:18:48 +0000312 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000313
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000314 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
315
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000316 // For the rest of the instructions, either hoist to the OrigPreheader if
317 // possible or create a clone in the OldPreHeader if not.
Chris Lattner30f318e2011-01-08 19:26:33 +0000318 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000319 while (I != E) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000320 Instruction *Inst = &*I++;
Andrew Tricka20f1982012-02-14 00:00:19 +0000321
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000322 // If the instruction's operands are invariant and it doesn't read or write
323 // memory, then it is safe to hoist. Doing this doesn't change the order of
324 // execution in the preheader, but does prevent the instruction from
325 // executing in each iteration of the loop. This means it is safe to hoist
326 // something that might trap, but isn't safe to hoist something that reads
327 // memory (without proving that the loop doesn't write).
Sebastian Popdfb66a12016-06-14 14:44:05 +0000328 if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
329 !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) &&
330 !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000331 Inst->moveBefore(LoopEntryBranch);
332 continue;
333 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000334
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000335 // Otherwise, create a duplicate of the instruction.
336 Instruction *C = Inst->clone();
Andrew Tricka20f1982012-02-14 00:00:19 +0000337
Chris Lattner8c5defd2011-01-08 08:24:46 +0000338 // Eagerly remap the operands of the instruction.
339 RemapInstruction(C, ValueMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000340 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Andrew Tricka20f1982012-02-14 00:00:19 +0000341
Chris Lattner8c5defd2011-01-08 08:24:46 +0000342 // With the operands remapped, see if the instruction constant folds or is
343 // otherwise simplifyable. This commonly occurs because the entry from PHI
344 // nodes allows icmps and other instructions to fold.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000345 // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000346 Value *V = SimplifyInstruction(C, DL);
Chris Lattner25ba40a2011-01-08 17:38:45 +0000347 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000348 // If so, then delete the temporary instruction and stick the folded value
349 // in the map.
Chris Lattner8c5defd2011-01-08 08:24:46 +0000350 ValueMap[Inst] = V;
David Majnemerb8da3a22016-06-25 00:04:10 +0000351 if (!C->mayHaveSideEffects()) {
352 delete C;
353 C = nullptr;
354 }
Chris Lattner8c5defd2011-01-08 08:24:46 +0000355 } else {
David Majnemerb8da3a22016-06-25 00:04:10 +0000356 ValueMap[Inst] = C;
357 }
358 if (C) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000359 // Otherwise, stick the new instruction into the new block!
360 C->setName(Inst->getName());
361 C->insertBefore(LoopEntryBranch);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000362
363 if (auto *II = dyn_cast<IntrinsicInst>(C))
364 if (II->getIntrinsicID() == Intrinsic::assume)
365 AC->registerAssumption(II);
Chris Lattner8c5defd2011-01-08 08:24:46 +0000366 }
Devang Patelf42389f2007-04-07 01:25:15 +0000367 }
368
Dan Gohmanb9797942009-10-24 23:19:52 +0000369 // Along with all the other instructions, we just cloned OrigHeader's
370 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
371 // successors by duplicating their incoming values for OrigHeader.
372 TerminatorInst *TI = OrigHeader->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +0000373 for (BasicBlock *SuccBB : TI->successors())
374 for (BasicBlock::iterator BI = SuccBB->begin();
Dan Gohmanb9797942009-10-24 23:19:52 +0000375 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner30f318e2011-01-08 19:26:33 +0000376 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000377
Dan Gohmanb9797942009-10-24 23:19:52 +0000378 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
379 // OrigPreHeader's old terminator (the original branch into the loop), and
380 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
381 LoopEntryBranch->eraseFromParent();
Devang Patelf42389f2007-04-07 01:25:15 +0000382
Sam Parker0f4db382017-03-08 09:56:22 +0000383
384 SmallVector<PHINode*, 2> InsertedPHIs;
Chris Lattner30f318e2011-01-08 19:26:33 +0000385 // If there were any uses of instructions in the duplicated block outside the
386 // loop, update them, inserting PHI nodes as required
Sam Parker0f4db382017-03-08 09:56:22 +0000387 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
388 &InsertedPHIs);
389
390 // Attach dbg.value intrinsics to the new phis if that phi uses a value that
391 // previously had debug metadata attached. This keeps the debug info
392 // up-to-date in the loop body.
393 if (!InsertedPHIs.empty())
394 insertDebugValues(OrigHeader, InsertedPHIs);
Devang Patelf42389f2007-04-07 01:25:15 +0000395
Dan Gohmanb9797942009-10-24 23:19:52 +0000396 // NewHeader is now the header of the loop.
Devang Patelf42389f2007-04-07 01:25:15 +0000397 L->moveToHeader(NewHeader);
Chris Lattner26151302011-01-08 19:10:28 +0000398 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelf42389f2007-04-07 01:25:15 +0000399
Chris Lattner59c82f82011-01-08 19:59:06 +0000400 // At this point, we've finished our major CFG changes. As part of cloning
401 // the loop into the preheader we've simplified instructions and the
402 // duplicated conditional branch may now be branching on a constant. If it is
403 // branching on a constant and if that constant means that we enter the loop,
404 // then we fold away the cond branch to an uncond branch. This simplifies the
405 // loop in cases important for nested loops, and it also means we don't have
406 // to split as many edges.
407 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
408 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
409 if (!isa<ConstantInt>(PHBI->getCondition()) ||
Sebastian Popdfb66a12016-06-14 14:44:05 +0000410 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
411 NewHeader) {
Chris Lattner59c82f82011-01-08 19:59:06 +0000412 // The conditional branch can't be folded, handle the general case.
413 // Update DominatorTree to reflect the CFG change we just made. Then split
414 // edges as necessary to preserve LoopSimplify form.
Chandler Carruth94209092015-01-18 02:08:05 +0000415 if (DT) {
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000416 // Everything that was dominated by the old loop header is now dominated
417 // by the original loop preheader. Conceptually the header was merged
418 // into the preheader, even though we reuse the actual block as a new
419 // loop latch.
Chandler Carruth94209092015-01-18 02:08:05 +0000420 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000421 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
422 OrigHeaderNode->end());
Chandler Carruth94209092015-01-18 02:08:05 +0000423 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000424 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
Chandler Carruth94209092015-01-18 02:08:05 +0000425 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Tricka20f1982012-02-14 00:00:19 +0000426
Chandler Carruth94209092015-01-18 02:08:05 +0000427 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
428 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
Benjamin Kramer3be6a482012-09-01 12:04:51 +0000429
Chris Lattner59c82f82011-01-08 19:59:06 +0000430 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000431 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Chris Lattner59c82f82011-01-08 19:59:06 +0000432 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000433
Chris Lattner59c82f82011-01-08 19:59:06 +0000434 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotem465834c2012-07-24 10:51:42 +0000435 // thus is not a preheader anymore.
436 // Split the edge to form a real preheader.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000437 BasicBlock *NewPH = SplitCriticalEdge(
438 OrigPreheader, NewHeader,
439 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chris Lattner59c82f82011-01-08 19:59:06 +0000440 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Tricka20f1982012-02-14 00:00:19 +0000441
Nadav Rotem465834c2012-07-24 10:51:42 +0000442 // Preserve canonical loop form, which means that 'Exit' should have only
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000443 // one predecessor. Note that Exit could be an exit block for multiple
444 // nested loops, causing both of the edges to now be critical and need to
445 // be split.
446 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
447 bool SplitLatchEdge = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000448 for (BasicBlock *ExitPred : ExitPreds) {
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000449 // We only need to split loop exit edges.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000450 Loop *PredLoop = LI->getLoopFor(ExitPred);
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000451 if (!PredLoop || PredLoop->contains(Exit))
452 continue;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000453 if (isa<IndirectBrInst>(ExitPred->getTerminator()))
Benjamin Kramer911d5b32015-02-20 20:49:25 +0000454 continue;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000455 SplitLatchEdge |= L->getLoopLatch() == ExitPred;
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000456 BasicBlock *ExitSplit = SplitCriticalEdge(
Benjamin Kramer135f7352016-06-26 12:28:59 +0000457 ExitPred, Exit,
458 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000459 ExitSplit->moveBefore(Exit);
460 }
461 assert(SplitLatchEdge &&
462 "Despite splitting all preds, failed to split latch exit?");
Chris Lattner59c82f82011-01-08 19:59:06 +0000463 } else {
464 // We can fold the conditional branch in the preheader, this makes things
465 // simpler. The first step is to remove the extra edge to the Exit block.
466 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelc1f7c1d2011-04-29 20:38:55 +0000467 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
468 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner59c82f82011-01-08 19:59:06 +0000469 PHBI->eraseFromParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000470
Chris Lattner59c82f82011-01-08 19:59:06 +0000471 // With our CFG finalized, update DomTree if it is available.
Chandler Carruth94209092015-01-18 02:08:05 +0000472 if (DT) {
Chris Lattner59c82f82011-01-08 19:59:06 +0000473 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000474 DT->changeImmediateDominator(NewHeader, OrigPreheader);
475 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000476
477 // Brute force incremental dominator tree update. Call
478 // findNearestCommonDominator on all CFG predecessors of each child of the
479 // original header.
Chandler Carruth94209092015-01-18 02:08:05 +0000480 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000481 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
482 OrigHeaderNode->end());
483 bool Changed;
484 do {
485 Changed = false;
486 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
487 DomTreeNode *Node = HeaderChildren[I];
488 BasicBlock *BB = Node->getBlock();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000489
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000490 pred_iterator PI = pred_begin(BB);
491 BasicBlock *NearestDom = *PI;
492 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
Chandler Carruth94209092015-01-18 02:08:05 +0000493 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000494
495 // Remember if this changes the DomTree.
496 if (Node->getIDom()->getBlock() != NearestDom) {
Chandler Carruth94209092015-01-18 02:08:05 +0000497 DT->changeImmediateDominator(BB, NearestDom);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000498 Changed = true;
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000499 }
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000500 }
501
Sebastian Popdfb66a12016-06-14 14:44:05 +0000502 // If the dominator changed, this may have an effect on other
503 // predecessors, continue until we reach a fixpoint.
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000504 } while (Changed);
Chris Lattner59c82f82011-01-08 19:59:06 +0000505 }
Devang Patelfac4d1f2007-07-11 23:47:28 +0000506 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000507
Chris Lattner59c82f82011-01-08 19:59:06 +0000508 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner063dca02011-01-08 18:52:51 +0000509 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnerfee37c52011-01-08 18:55:50 +0000510
Chris Lattner63fe78d2011-01-11 07:47:59 +0000511 // Now that the CFG and DomTree are in a consistent state again, try to merge
512 // the OrigHeader block into OrigLatch. This will succeed if they are
513 // connected by an unconditional branch. This is just a cleanup so the
514 // emitted code isn't too gross in this common case.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000515 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
Andrew Tricka20f1982012-02-14 00:00:19 +0000516
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000517 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
518
Chris Lattnerfee37c52011-01-08 18:55:50 +0000519 ++NumRotated;
520 return true;
Devang Patel85419782007-04-09 20:19:46 +0000521}
Justin Bognera7300452015-12-14 23:22:44 +0000522
523/// Determine whether the instructions in this range may be safely and cheaply
524/// speculated. This is not an important enough situation to develop complex
525/// heuristics. We handle a single arithmetic instruction along with any type
526/// conversions.
527static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
528 BasicBlock::iterator End, Loop *L) {
529 bool seenIncrement = false;
530 bool MultiExitLoop = false;
531
532 if (!L->getExitingBlock())
533 MultiExitLoop = true;
534
535 for (BasicBlock::iterator I = Begin; I != End; ++I) {
536
537 if (!isSafeToSpeculativelyExecute(&*I))
538 return false;
539
540 if (isa<DbgInfoIntrinsic>(I))
541 continue;
542
543 switch (I->getOpcode()) {
544 default:
545 return false;
546 case Instruction::GetElementPtr:
547 // GEPs are cheap if all indices are constant.
548 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
549 return false;
Justin Bognerb03fd122016-08-17 05:10:15 +0000550 // fall-thru to increment case
551 LLVM_FALLTHROUGH;
Justin Bognera7300452015-12-14 23:22:44 +0000552 case Instruction::Add:
553 case Instruction::Sub:
554 case Instruction::And:
555 case Instruction::Or:
556 case Instruction::Xor:
557 case Instruction::Shl:
558 case Instruction::LShr:
559 case Instruction::AShr: {
Sebastian Popdfb66a12016-06-14 14:44:05 +0000560 Value *IVOpnd =
561 !isa<Constant>(I->getOperand(0))
562 ? I->getOperand(0)
563 : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
Justin Bognera7300452015-12-14 23:22:44 +0000564 if (!IVOpnd)
565 return false;
566
567 // If increment operand is used outside of the loop, this speculation
568 // could cause extra live range interference.
569 if (MultiExitLoop) {
570 for (User *UseI : IVOpnd->users()) {
571 auto *UserInst = cast<Instruction>(UseI);
572 if (!L->contains(UserInst))
573 return false;
574 }
575 }
576
577 if (seenIncrement)
578 return false;
579 seenIncrement = true;
580 break;
581 }
582 case Instruction::Trunc:
583 case Instruction::ZExt:
584 case Instruction::SExt:
585 // ignore type conversions
586 break;
587 }
588 }
589 return true;
590}
591
592/// Fold the loop tail into the loop exit by speculating the loop tail
593/// instructions. Typically, this is a single post-increment. In the case of a
594/// simple 2-block loop, hoisting the increment can be much better than
595/// duplicating the entire loop header. In the case of loops with early exits,
596/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
597/// canonical form so downstream passes can handle it.
598///
599/// I don't believe this invalidates SCEV.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000600bool LoopRotate::simplifyLoopLatch(Loop *L) {
Justin Bognera7300452015-12-14 23:22:44 +0000601 BasicBlock *Latch = L->getLoopLatch();
602 if (!Latch || Latch->hasAddressTaken())
603 return false;
604
605 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
606 if (!Jmp || !Jmp->isUnconditional())
607 return false;
608
609 BasicBlock *LastExit = Latch->getSinglePredecessor();
610 if (!LastExit || !L->isLoopExiting(LastExit))
611 return false;
612
613 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
614 if (!BI)
615 return false;
616
617 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
618 return false;
619
620 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
Sebastian Popdfb66a12016-06-14 14:44:05 +0000621 << LastExit->getName() << "\n");
Justin Bognera7300452015-12-14 23:22:44 +0000622
623 // Hoist the instructions from Latch into LastExit.
624 LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
625 Latch->begin(), Jmp->getIterator());
626
627 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
628 BasicBlock *Header = Jmp->getSuccessor(0);
629 assert(Header == L->getHeader() && "expected a backward branch");
630
631 // Remove Latch from the CFG so that LastExit becomes the new Latch.
632 BI->setSuccessor(FallThruPath, Header);
633 Latch->replaceSuccessorsPhiUsesWith(LastExit);
634 Jmp->eraseFromParent();
635
636 // Nuke the Latch block.
637 assert(Latch->empty() && "unable to evacuate Latch");
638 LI->removeBlock(Latch);
639 if (DT)
640 DT->eraseNode(Latch);
641 Latch->eraseFromParent();
642 return true;
643}
644
Michael Zolotukhinb98294d2016-06-10 22:03:56 +0000645/// Rotate \c L, and return true if any modification was made.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000646bool LoopRotate::processLoop(Loop *L) {
Justin Bognera7300452015-12-14 23:22:44 +0000647 // Save the loop metadata.
648 MDNode *LoopMD = L->getLoopID();
649
Justin Bognera7300452015-12-14 23:22:44 +0000650 // Simplify the loop latch before attempting to rotate the header
651 // upward. Rotation may not be needed if the loop tail can be folded into the
652 // loop exit.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000653 bool SimplifiedLatch = simplifyLoopLatch(L);
Justin Bognera7300452015-12-14 23:22:44 +0000654
Sebastian Popdfb66a12016-06-14 14:44:05 +0000655 bool MadeChange = rotateLoop(L, SimplifiedLatch);
Michael Zolotukhinb98294d2016-06-10 22:03:56 +0000656 assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
657 "Loop latch should be exiting after loop-rotate.");
Justin Bognera7300452015-12-14 23:22:44 +0000658
659 // Restore the loop metadata.
660 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
661 if ((MadeChange || SimplifiedLatch) && LoopMD)
662 L->setLoopID(LoopMD);
663
664 return MadeChange;
665}
Justin Bogner6291b582015-12-14 23:22:48 +0000666
Chandler Carruthe3f50642016-12-22 06:59:15 +0000667LoopRotatePass::LoopRotatePass(bool EnableHeaderDuplication)
668 : EnableHeaderDuplication(EnableHeaderDuplication) {}
Justin Bognerd0d23412016-05-03 22:02:31 +0000669
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000670PreservedAnalyses LoopRotatePass::run(Loop &L, LoopAnalysisManager &AM,
671 LoopStandardAnalysisResults &AR,
672 LPMUpdater &) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000673 int Threshold = EnableHeaderDuplication ? DefaultRotationThreshold : 0;
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000674 LoopRotate LR(Threshold, &AR.LI, &AR.TTI, &AR.AC, &AR.DT, &AR.SE);
Justin Bognerd0d23412016-05-03 22:02:31 +0000675
Sebastian Popdfb66a12016-06-14 14:44:05 +0000676 bool Changed = LR.processLoop(&L);
Justin Bognerd0d23412016-05-03 22:02:31 +0000677 if (!Changed)
678 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000679
Justin Bognerd0d23412016-05-03 22:02:31 +0000680 return getLoopPassPreservedAnalyses();
681}
682
Justin Bogner6291b582015-12-14 23:22:48 +0000683namespace {
684
Justin Bognerd0d23412016-05-03 22:02:31 +0000685class LoopRotateLegacyPass : public LoopPass {
Justin Bogner6291b582015-12-14 23:22:48 +0000686 unsigned MaxHeaderSize;
687
688public:
689 static char ID; // Pass ID, replacement for typeid
Justin Bognerd0d23412016-05-03 22:02:31 +0000690 LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
691 initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry());
Justin Bogner6291b582015-12-14 23:22:48 +0000692 if (SpecifiedMaxHeaderSize == -1)
693 MaxHeaderSize = DefaultRotationThreshold;
694 else
695 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
696 }
697
698 // LCSSA form makes instruction renaming easier.
699 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000700 AU.addRequired<AssumptionCacheTracker>();
Justin Bogner6291b582015-12-14 23:22:48 +0000701 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000702 getLoopAnalysisUsage(AU);
Justin Bogner6291b582015-12-14 23:22:48 +0000703 }
704
705 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000706 if (skipLoop(L))
Justin Bogner6291b582015-12-14 23:22:48 +0000707 return false;
708 Function &F = *L->getHeader()->getParent();
709
710 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
711 const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000712 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Justin Bogner6291b582015-12-14 23:22:48 +0000713 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
714 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
715 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
716 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000717 LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE);
Sebastian Popdfb66a12016-06-14 14:44:05 +0000718 return LR.processLoop(L);
Justin Bogner6291b582015-12-14 23:22:48 +0000719 }
720};
721}
722
Justin Bognerd0d23412016-05-03 22:02:31 +0000723char LoopRotateLegacyPass::ID = 0;
724INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
725 false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000726INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth31088a92016-02-19 10:45:18 +0000727INITIALIZE_PASS_DEPENDENCY(LoopPass)
728INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Sebastian Popdfb66a12016-06-14 14:44:05 +0000729INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false,
730 false)
Justin Bogner6291b582015-12-14 23:22:48 +0000731
732Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
Justin Bognerd0d23412016-05-03 22:02:31 +0000733 return new LoopRotateLegacyPass(MaxHeaderSize);
Justin Bogner6291b582015-12-14 23:22:48 +0000734}