blob: 46db8f1210b6957d12090926ab944c3558144b8b [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"
Chandler Carruth7b560d42015-09-09 17:55:00 +000017#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000018#include "llvm/Analysis/AssumptionCache.h"
Chris Lattner679572e2011-01-02 07:35:53 +000019#include "llvm/Analysis/CodeMetrics.h"
Chris Lattner8c5defd2011-01-08 08:24:46 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000021#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/LoopPass.h"
Justin Bognerd0d23412016-05-03 22:02:31 +000023#include "llvm/Analysis/LoopPassManager.h"
Devang Patelfac4d1f2007-07-11 23:47:28 +000024#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000025#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000026#include "llvm/Analysis/TargetTransformInfo.h"
Andrew Trick10cc4532012-02-14 00:00:23 +000027#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000028#include "llvm/IR/CFG.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/IntrinsicInst.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000032#include "llvm/IR/Module.h"
Owen Anderson115aa162014-05-26 08:58:51 +000033#include "llvm/Support/CommandLine.h"
Devang Patelf42389f2007-04-07 01:25:15 +000034#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000035#include "llvm/Support/raw_ostream.h"
Justin Bognerd0d23412016-05-03 22:02:31 +000036#include "llvm/Transforms/Scalar.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
Sebastian Popdfb66a12016-06-14 14:44:05 +000052/// A simple loop rotation transformation.
53class LoopRotate {
54 const unsigned MaxHeaderSize;
55 LoopInfo *LI;
56 const TargetTransformInfo *TTI;
57 AssumptionCache *AC;
58 DominatorTree *DT;
59 ScalarEvolution *SE;
60
61public:
62 LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
63 const TargetTransformInfo *TTI, AssumptionCache *AC,
64 DominatorTree *DT, ScalarEvolution *SE)
65 : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE) {
66 }
67 bool processLoop(Loop *L);
68
69private:
70 bool rotateLoop(Loop *L, bool SimplifiedLatch);
71 bool simplifyLoopLatch(Loop *L);
72};
73
Chris Lattner30f318e2011-01-08 19:26:33 +000074/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
75/// old header into the preheader. If there were uses of the values produced by
76/// these instruction that were outside of the loop, we have to insert PHI nodes
77/// to merge the two values. Do this now.
78static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
79 BasicBlock *OrigPreheader,
80 ValueToValueMapTy &ValueMap) {
81 // Remove PHI node entries that are no longer live.
82 BasicBlock::iterator I, E = OrigHeader->end();
83 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
84 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Tricka20f1982012-02-14 00:00:19 +000085
Chris Lattner30f318e2011-01-08 19:26:33 +000086 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
87 // as necessary.
88 SSAUpdater SSA;
89 for (I = OrigHeader->begin(); I != E; ++I) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +000090 Value *OrigHeaderVal = &*I;
Andrew Tricka20f1982012-02-14 00:00:19 +000091
Chris Lattner30f318e2011-01-08 19:26:33 +000092 // If there are no uses of the value (e.g. because it returns void), there
93 // is nothing to rewrite.
94 if (OrigHeaderVal->use_empty())
95 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +000096
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +000097 Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
Chris Lattner30f318e2011-01-08 19:26:33 +000098
99 // The value now exits in two versions: the initial value in the preheader
100 // and the loop "next" value in the original header.
101 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
102 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
103 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Tricka20f1982012-02-14 00:00:19 +0000104
Chris Lattner30f318e2011-01-08 19:26:33 +0000105 // Visit each use of the OrigHeader instruction.
106 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
Sebastian Popdfb66a12016-06-14 14:44:05 +0000107 UE = OrigHeaderVal->use_end();
108 UI != UE;) {
Chris Lattner30f318e2011-01-08 19:26:33 +0000109 // Grab the use before incrementing the iterator.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000110 Use &U = *UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000111
Chris Lattner30f318e2011-01-08 19:26:33 +0000112 // Increment the iterator before removing the use from the list.
113 ++UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000114
Chris Lattner30f318e2011-01-08 19:26:33 +0000115 // SSAUpdater can't handle a non-PHI use in the same block as an
116 // earlier def. We can easily handle those cases manually.
117 Instruction *UserInst = cast<Instruction>(U.getUser());
118 if (!isa<PHINode>(UserInst)) {
119 BasicBlock *UserBB = UserInst->getParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000120
Chris Lattner30f318e2011-01-08 19:26:33 +0000121 // The original users in the OrigHeader are already using the
122 // original definitions.
123 if (UserBB == OrigHeader)
124 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000125
Chris Lattner30f318e2011-01-08 19:26:33 +0000126 // Users in the OrigPreHeader need to use the value to which the
127 // original definitions are mapped.
128 if (UserBB == OrigPreheader) {
129 U = OrigPreHeaderVal;
130 continue;
131 }
132 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000133
Chris Lattner30f318e2011-01-08 19:26:33 +0000134 // Anything else can be handled by SSAUpdater.
135 SSA.RewriteUse(U);
136 }
Chuang-Yu Cheng175741d2016-05-10 09:45:44 +0000137
138 // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
139 // intrinsics.
140 LLVMContext &C = OrigHeader->getContext();
141 if (auto *VAM = ValueAsMetadata::getIfExists(OrigHeaderVal)) {
142 if (auto *MAV = MetadataAsValue::getIfExists(C, VAM)) {
Sebastian Popdfb66a12016-06-14 14:44:05 +0000143 for (auto UI = MAV->use_begin(), E = MAV->use_end(); UI != E;) {
Chuang-Yu Cheng175741d2016-05-10 09:45:44 +0000144 // Grab the use before incrementing the iterator. Otherwise, altering
145 // the Use will invalidate the iterator.
146 Use &U = *UI++;
147 DbgInfoIntrinsic *UserInst = dyn_cast<DbgInfoIntrinsic>(U.getUser());
Sebastian Popdfb66a12016-06-14 14:44:05 +0000148 if (!UserInst)
149 continue;
Chuang-Yu Cheng175741d2016-05-10 09:45:44 +0000150
151 // The original users in the OrigHeader are already using the original
152 // definitions.
153 BasicBlock *UserBB = UserInst->getParent();
154 if (UserBB == OrigHeader)
155 continue;
156
157 // Users in the OrigPreHeader need to use the value to which the
158 // original definitions are mapped and anything else can be handled by
159 // the SSAUpdater. To avoid adding PHINodes, check if the value is
160 // available in UserBB, if not substitute undef.
161 Value *NewVal;
162 if (UserBB == OrigPreheader)
163 NewVal = OrigPreHeaderVal;
164 else if (SSA.HasValueForBlock(UserBB))
165 NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
166 else
167 NewVal = UndefValue::get(OrigHeaderVal->getType());
168 U = MetadataAsValue::get(C, ValueAsMetadata::get(NewVal));
169 }
170 }
171 }
Chris Lattner30f318e2011-01-08 19:26:33 +0000172 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000173}
Chris Lattner30f318e2011-01-08 19:26:33 +0000174
Dan Gohmanb5650eb2007-05-11 21:10:54 +0000175/// Rotate loop LP. Return true if the loop is rotated.
Andrew Trick9c72b072013-05-06 17:58:18 +0000176///
177/// \param SimplifiedLatch is true if the latch was just folded into the final
178/// loop exit. In this case we may want to rotate even though the new latch is
179/// now an exiting branch. This rotation would have happened had the latch not
180/// been simplified. However, if SimplifiedLatch is false, then we avoid
181/// rotating loops in which the latch exits to avoid excessive or endless
182/// rotation. LoopRotate should be repeatable and converge to a canonical
183/// form. This property is satisfied because simplifying the loop latch can only
184/// happen once across multiple invocations of the LoopRotate pass.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000185bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
Dan Gohman091e4402009-06-25 00:22:44 +0000186 // If the loop has only one block then there is not much to rotate.
Devang Patel88bc2c62007-04-09 16:11:48 +0000187 if (L->getBlocks().size() == 1)
Devang Patelf42389f2007-04-07 01:25:15 +0000188 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000189
Chris Lattner7fab23b2011-01-08 18:06:22 +0000190 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000191 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Tricka20f1982012-02-14 00:00:19 +0000192
Chris Lattner7fab23b2011-01-08 18:06:22 +0000193 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000194 if (!BI || BI->isUnconditional())
Chris Lattner7fab23b2011-01-08 18:06:22 +0000195 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000196
Dan Gohman091e4402009-06-25 00:22:44 +0000197 // If the loop header is not one of the loop exiting blocks then
198 // either this loop is already rotated or it is not
Devang Patelf42389f2007-04-07 01:25:15 +0000199 // suitable for loop rotation transformations.
Dan Gohman8f4078b2009-10-24 23:34:26 +0000200 if (!L->isLoopExiting(OrigHeader))
Devang Patelf42389f2007-04-07 01:25:15 +0000201 return false;
202
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000203 // If the loop latch already contains a branch that leaves the loop then the
204 // loop is already rotated.
Craig Topperf40110f2014-04-25 05:29:35 +0000205 if (!OrigLatch)
Andrew Trick9c72b072013-05-06 17:58:18 +0000206 return false;
207
208 // Rotate if either the loop latch does *not* exit the loop, or if the loop
209 // latch was just simplified.
210 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
Devang Patelf42389f2007-04-07 01:25:15 +0000211 return false;
212
James Molloy4f6fb952012-12-20 16:04:27 +0000213 // Check size of original header and reject loop if it is very big or we can't
214 // duplicate blocks inside it.
Chris Lattner679572e2011-01-02 07:35:53 +0000215 {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000216 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000217 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000218
Chris Lattner679572e2011-01-02 07:35:53 +0000219 CodeMetrics Metrics;
Hal Finkel57f03dd2014-09-07 13:49:57 +0000220 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
James Molloy4f6fb952012-12-20 16:04:27 +0000221 if (Metrics.notDuplicatable) {
Alp Tokerf907b892013-12-05 05:44:44 +0000222 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
Sebastian Popdfb66a12016-06-14 14:44:05 +0000223 << " instructions: ";
224 L->dump());
James Molloy4f6fb952012-12-20 16:04:27 +0000225 return false;
226 }
Justin Lebardf04d2a2016-02-12 21:01:33 +0000227 if (Metrics.convergent) {
228 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
Sebastian Popdfb66a12016-06-14 14:44:05 +0000229 "instructions: ";
230 L->dump());
Justin Lebardf04d2a2016-02-12 21:01:33 +0000231 return false;
232 }
Owen Anderson115aa162014-05-26 08:58:51 +0000233 if (Metrics.NumInsts > MaxHeaderSize)
Chris Lattner679572e2011-01-02 07:35:53 +0000234 return false;
Devang Patelbab43b42009-03-06 03:51:30 +0000235 }
236
Devang Patelfac4d1f2007-07-11 23:47:28 +0000237 // Now, this loop is suitable for rotation.
Chris Lattner30f318e2011-01-08 19:26:33 +0000238 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Tricka20f1982012-02-14 00:00:19 +0000239
Chris Lattner88974f42011-04-09 07:25:58 +0000240 // If the loop could not be converted to canonical form, it must have an
241 // indirectbr in it, just give up.
Craig Topperf40110f2014-04-25 05:29:35 +0000242 if (!OrigPreheader)
Chris Lattner88974f42011-04-09 07:25:58 +0000243 return false;
Devang Patelfac4d1f2007-07-11 23:47:28 +0000244
Dan Gohmanfc20b672009-09-27 15:37:03 +0000245 // Anything ScalarEvolution may know about this loop or the PHI nodes
246 // in its header will soon be invalidated.
Justin Bogner6291b582015-12-14 23:22:48 +0000247 if (SE)
248 SE->forgetLoop(L);
Dan Gohmanfc20b672009-09-27 15:37:03 +0000249
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000250 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
251
Devang Patelf42389f2007-04-07 01:25:15 +0000252 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattner57cb4722009-01-26 01:57:01 +0000253 // that is inside loop. Header's other successor is outside the
254 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner385f2ec2011-01-08 17:48:33 +0000255 BasicBlock *Exit = BI->getSuccessor(0);
256 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel88bc2c62007-04-09 16:11:48 +0000257 if (L->contains(Exit))
258 std::swap(Exit, NewHeader);
Chris Lattnerd67aaa62009-01-26 01:38:24 +0000259 assert(NewHeader && "Unable to determine new loop header");
Andrew Tricka20f1982012-02-14 00:00:19 +0000260 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel88bc2c62007-04-09 16:11:48 +0000261 "Unable to determine loop header and exit blocks");
Andrew Tricka20f1982012-02-14 00:00:19 +0000262
Dan Gohman091e4402009-06-25 00:22:44 +0000263 // This code assumes that the new header has exactly one predecessor.
264 // Remove any single-entry PHI nodes in it.
Chris Lattner7b6647c2009-01-26 02:11:30 +0000265 assert(NewHeader->getSinglePredecessor() &&
266 "New header doesn't have one pred!");
267 FoldSingleEntryPHINodes(NewHeader);
Devang Patelf42389f2007-04-07 01:25:15 +0000268
Dan Gohmanb9797942009-10-24 23:19:52 +0000269 // Begin by walking OrigHeader and populating ValueMap with an entry for
270 // each Instruction.
Devang Patel88bc2c62007-04-09 16:11:48 +0000271 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner2b3f20e2011-01-08 07:21:31 +0000272 ValueToValueMapTy ValueMap;
Devang Patelb9af5742007-04-09 19:04:21 +0000273
Dan Gohmanb9797942009-10-24 23:19:52 +0000274 // For PHI nodes, the value available in OldPreHeader is just the
275 // incoming value from OldPreHeader.
276 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foad372ad642011-06-20 14:18:48 +0000277 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000278
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000279 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
280
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000281 // For the rest of the instructions, either hoist to the OrigPreheader if
282 // possible or create a clone in the OldPreHeader if not.
Chris Lattner30f318e2011-01-08 19:26:33 +0000283 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000284 while (I != E) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000285 Instruction *Inst = &*I++;
Andrew Tricka20f1982012-02-14 00:00:19 +0000286
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000287 // If the instruction's operands are invariant and it doesn't read or write
288 // memory, then it is safe to hoist. Doing this doesn't change the order of
289 // execution in the preheader, but does prevent the instruction from
290 // executing in each iteration of the loop. This means it is safe to hoist
291 // something that might trap, but isn't safe to hoist something that reads
292 // memory (without proving that the loop doesn't write).
Sebastian Popdfb66a12016-06-14 14:44:05 +0000293 if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
294 !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) &&
295 !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000296 Inst->moveBefore(LoopEntryBranch);
297 continue;
298 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000299
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000300 // Otherwise, create a duplicate of the instruction.
301 Instruction *C = Inst->clone();
Andrew Tricka20f1982012-02-14 00:00:19 +0000302
Chris Lattner8c5defd2011-01-08 08:24:46 +0000303 // Eagerly remap the operands of the instruction.
304 RemapInstruction(C, ValueMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000305 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Andrew Tricka20f1982012-02-14 00:00:19 +0000306
Chris Lattner8c5defd2011-01-08 08:24:46 +0000307 // With the operands remapped, see if the instruction constant folds or is
308 // otherwise simplifyable. This commonly occurs because the entry from PHI
309 // nodes allows icmps and other instructions to fold.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000310 // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
311 Value *V = SimplifyInstruction(C, DL);
Chris Lattner25ba40a2011-01-08 17:38:45 +0000312 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000313 // If so, then delete the temporary instruction and stick the folded value
314 // in the map.
Chris Lattner8c5defd2011-01-08 08:24:46 +0000315 ValueMap[Inst] = V;
David Majnemerb8da3a22016-06-25 00:04:10 +0000316 if (!C->mayHaveSideEffects()) {
317 delete C;
318 C = nullptr;
319 }
Chris Lattner8c5defd2011-01-08 08:24:46 +0000320 } else {
David Majnemerb8da3a22016-06-25 00:04:10 +0000321 ValueMap[Inst] = C;
322 }
323 if (C) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000324 // Otherwise, stick the new instruction into the new block!
325 C->setName(Inst->getName());
326 C->insertBefore(LoopEntryBranch);
Chris Lattner8c5defd2011-01-08 08:24:46 +0000327 }
Devang Patelf42389f2007-04-07 01:25:15 +0000328 }
329
Dan Gohmanb9797942009-10-24 23:19:52 +0000330 // Along with all the other instructions, we just cloned OrigHeader's
331 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
332 // successors by duplicating their incoming values for OrigHeader.
333 TerminatorInst *TI = OrigHeader->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +0000334 for (BasicBlock *SuccBB : TI->successors())
335 for (BasicBlock::iterator BI = SuccBB->begin();
Dan Gohmanb9797942009-10-24 23:19:52 +0000336 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner30f318e2011-01-08 19:26:33 +0000337 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000338
Dan Gohmanb9797942009-10-24 23:19:52 +0000339 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
340 // OrigPreHeader's old terminator (the original branch into the loop), and
341 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
342 LoopEntryBranch->eraseFromParent();
Devang Patelf42389f2007-04-07 01:25:15 +0000343
Chris Lattner30f318e2011-01-08 19:26:33 +0000344 // If there were any uses of instructions in the duplicated block outside the
345 // loop, update them, inserting PHI nodes as required
346 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelf42389f2007-04-07 01:25:15 +0000347
Dan Gohmanb9797942009-10-24 23:19:52 +0000348 // NewHeader is now the header of the loop.
Devang Patelf42389f2007-04-07 01:25:15 +0000349 L->moveToHeader(NewHeader);
Chris Lattner26151302011-01-08 19:10:28 +0000350 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelf42389f2007-04-07 01:25:15 +0000351
Chris Lattner59c82f82011-01-08 19:59:06 +0000352 // At this point, we've finished our major CFG changes. As part of cloning
353 // the loop into the preheader we've simplified instructions and the
354 // duplicated conditional branch may now be branching on a constant. If it is
355 // branching on a constant and if that constant means that we enter the loop,
356 // then we fold away the cond branch to an uncond branch. This simplifies the
357 // loop in cases important for nested loops, and it also means we don't have
358 // to split as many edges.
359 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
360 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
361 if (!isa<ConstantInt>(PHBI->getCondition()) ||
Sebastian Popdfb66a12016-06-14 14:44:05 +0000362 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
363 NewHeader) {
Chris Lattner59c82f82011-01-08 19:59:06 +0000364 // The conditional branch can't be folded, handle the general case.
365 // Update DominatorTree to reflect the CFG change we just made. Then split
366 // edges as necessary to preserve LoopSimplify form.
Chandler Carruth94209092015-01-18 02:08:05 +0000367 if (DT) {
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000368 // Everything that was dominated by the old loop header is now dominated
369 // by the original loop preheader. Conceptually the header was merged
370 // into the preheader, even though we reuse the actual block as a new
371 // loop latch.
Chandler Carruth94209092015-01-18 02:08:05 +0000372 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000373 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
374 OrigHeaderNode->end());
Chandler Carruth94209092015-01-18 02:08:05 +0000375 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000376 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
Chandler Carruth94209092015-01-18 02:08:05 +0000377 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Tricka20f1982012-02-14 00:00:19 +0000378
Chandler Carruth94209092015-01-18 02:08:05 +0000379 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
380 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
Benjamin Kramer3be6a482012-09-01 12:04:51 +0000381
Chris Lattner59c82f82011-01-08 19:59:06 +0000382 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000383 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Chris Lattner59c82f82011-01-08 19:59:06 +0000384 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000385
Chris Lattner59c82f82011-01-08 19:59:06 +0000386 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotem465834c2012-07-24 10:51:42 +0000387 // thus is not a preheader anymore.
388 // Split the edge to form a real preheader.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000389 BasicBlock *NewPH = SplitCriticalEdge(
390 OrigPreheader, NewHeader,
391 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chris Lattner59c82f82011-01-08 19:59:06 +0000392 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Tricka20f1982012-02-14 00:00:19 +0000393
Nadav Rotem465834c2012-07-24 10:51:42 +0000394 // Preserve canonical loop form, which means that 'Exit' should have only
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000395 // one predecessor. Note that Exit could be an exit block for multiple
396 // nested loops, causing both of the edges to now be critical and need to
397 // be split.
398 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
399 bool SplitLatchEdge = false;
400 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
401 PE = ExitPreds.end();
402 PI != PE; ++PI) {
403 // We only need to split loop exit edges.
404 Loop *PredLoop = LI->getLoopFor(*PI);
405 if (!PredLoop || PredLoop->contains(Exit))
406 continue;
Benjamin Kramer911d5b32015-02-20 20:49:25 +0000407 if (isa<IndirectBrInst>((*PI)->getTerminator()))
408 continue;
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000409 SplitLatchEdge |= L->getLoopLatch() == *PI;
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000410 BasicBlock *ExitSplit = SplitCriticalEdge(
411 *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000412 ExitSplit->moveBefore(Exit);
413 }
414 assert(SplitLatchEdge &&
415 "Despite splitting all preds, failed to split latch exit?");
Chris Lattner59c82f82011-01-08 19:59:06 +0000416 } else {
417 // We can fold the conditional branch in the preheader, this makes things
418 // simpler. The first step is to remove the extra edge to the Exit block.
419 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelc1f7c1d2011-04-29 20:38:55 +0000420 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
421 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner59c82f82011-01-08 19:59:06 +0000422 PHBI->eraseFromParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000423
Chris Lattner59c82f82011-01-08 19:59:06 +0000424 // With our CFG finalized, update DomTree if it is available.
Chandler Carruth94209092015-01-18 02:08:05 +0000425 if (DT) {
Chris Lattner59c82f82011-01-08 19:59:06 +0000426 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000427 DT->changeImmediateDominator(NewHeader, OrigPreheader);
428 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000429
430 // Brute force incremental dominator tree update. Call
431 // findNearestCommonDominator on all CFG predecessors of each child of the
432 // original header.
Chandler Carruth94209092015-01-18 02:08:05 +0000433 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000434 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
435 OrigHeaderNode->end());
436 bool Changed;
437 do {
438 Changed = false;
439 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
440 DomTreeNode *Node = HeaderChildren[I];
441 BasicBlock *BB = Node->getBlock();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000442
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000443 pred_iterator PI = pred_begin(BB);
444 BasicBlock *NearestDom = *PI;
445 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
Chandler Carruth94209092015-01-18 02:08:05 +0000446 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000447
448 // Remember if this changes the DomTree.
449 if (Node->getIDom()->getBlock() != NearestDom) {
Chandler Carruth94209092015-01-18 02:08:05 +0000450 DT->changeImmediateDominator(BB, NearestDom);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000451 Changed = true;
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000452 }
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000453 }
454
Sebastian Popdfb66a12016-06-14 14:44:05 +0000455 // If the dominator changed, this may have an effect on other
456 // predecessors, continue until we reach a fixpoint.
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000457 } while (Changed);
Chris Lattner59c82f82011-01-08 19:59:06 +0000458 }
Devang Patelfac4d1f2007-07-11 23:47:28 +0000459 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000460
Chris Lattner59c82f82011-01-08 19:59:06 +0000461 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner063dca02011-01-08 18:52:51 +0000462 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnerfee37c52011-01-08 18:55:50 +0000463
Chris Lattner63fe78d2011-01-11 07:47:59 +0000464 // Now that the CFG and DomTree are in a consistent state again, try to merge
465 // the OrigHeader block into OrigLatch. This will succeed if they are
466 // connected by an unconditional branch. This is just a cleanup so the
467 // emitted code isn't too gross in this common case.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000468 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
Andrew Tricka20f1982012-02-14 00:00:19 +0000469
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000470 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
471
Chris Lattnerfee37c52011-01-08 18:55:50 +0000472 ++NumRotated;
473 return true;
Devang Patel85419782007-04-09 20:19:46 +0000474}
Justin Bognera7300452015-12-14 23:22:44 +0000475
476/// Determine whether the instructions in this range may be safely and cheaply
477/// speculated. This is not an important enough situation to develop complex
478/// heuristics. We handle a single arithmetic instruction along with any type
479/// conversions.
480static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
481 BasicBlock::iterator End, Loop *L) {
482 bool seenIncrement = false;
483 bool MultiExitLoop = false;
484
485 if (!L->getExitingBlock())
486 MultiExitLoop = true;
487
488 for (BasicBlock::iterator I = Begin; I != End; ++I) {
489
490 if (!isSafeToSpeculativelyExecute(&*I))
491 return false;
492
493 if (isa<DbgInfoIntrinsic>(I))
494 continue;
495
496 switch (I->getOpcode()) {
497 default:
498 return false;
499 case Instruction::GetElementPtr:
500 // GEPs are cheap if all indices are constant.
501 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
502 return false;
Sebastian Popdfb66a12016-06-14 14:44:05 +0000503 // fall-thru to increment case
Justin Bognera7300452015-12-14 23:22:44 +0000504 case Instruction::Add:
505 case Instruction::Sub:
506 case Instruction::And:
507 case Instruction::Or:
508 case Instruction::Xor:
509 case Instruction::Shl:
510 case Instruction::LShr:
511 case Instruction::AShr: {
Sebastian Popdfb66a12016-06-14 14:44:05 +0000512 Value *IVOpnd =
513 !isa<Constant>(I->getOperand(0))
514 ? I->getOperand(0)
515 : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
Justin Bognera7300452015-12-14 23:22:44 +0000516 if (!IVOpnd)
517 return false;
518
519 // If increment operand is used outside of the loop, this speculation
520 // could cause extra live range interference.
521 if (MultiExitLoop) {
522 for (User *UseI : IVOpnd->users()) {
523 auto *UserInst = cast<Instruction>(UseI);
524 if (!L->contains(UserInst))
525 return false;
526 }
527 }
528
529 if (seenIncrement)
530 return false;
531 seenIncrement = true;
532 break;
533 }
534 case Instruction::Trunc:
535 case Instruction::ZExt:
536 case Instruction::SExt:
537 // ignore type conversions
538 break;
539 }
540 }
541 return true;
542}
543
544/// Fold the loop tail into the loop exit by speculating the loop tail
545/// instructions. Typically, this is a single post-increment. In the case of a
546/// simple 2-block loop, hoisting the increment can be much better than
547/// duplicating the entire loop header. In the case of loops with early exits,
548/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
549/// canonical form so downstream passes can handle it.
550///
551/// I don't believe this invalidates SCEV.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000552bool LoopRotate::simplifyLoopLatch(Loop *L) {
Justin Bognera7300452015-12-14 23:22:44 +0000553 BasicBlock *Latch = L->getLoopLatch();
554 if (!Latch || Latch->hasAddressTaken())
555 return false;
556
557 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
558 if (!Jmp || !Jmp->isUnconditional())
559 return false;
560
561 BasicBlock *LastExit = Latch->getSinglePredecessor();
562 if (!LastExit || !L->isLoopExiting(LastExit))
563 return false;
564
565 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
566 if (!BI)
567 return false;
568
569 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
570 return false;
571
572 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
Sebastian Popdfb66a12016-06-14 14:44:05 +0000573 << LastExit->getName() << "\n");
Justin Bognera7300452015-12-14 23:22:44 +0000574
575 // Hoist the instructions from Latch into LastExit.
576 LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
577 Latch->begin(), Jmp->getIterator());
578
579 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
580 BasicBlock *Header = Jmp->getSuccessor(0);
581 assert(Header == L->getHeader() && "expected a backward branch");
582
583 // Remove Latch from the CFG so that LastExit becomes the new Latch.
584 BI->setSuccessor(FallThruPath, Header);
585 Latch->replaceSuccessorsPhiUsesWith(LastExit);
586 Jmp->eraseFromParent();
587
588 // Nuke the Latch block.
589 assert(Latch->empty() && "unable to evacuate Latch");
590 LI->removeBlock(Latch);
591 if (DT)
592 DT->eraseNode(Latch);
593 Latch->eraseFromParent();
594 return true;
595}
596
Michael Zolotukhinb98294d2016-06-10 22:03:56 +0000597/// Rotate \c L, and return true if any modification was made.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000598bool LoopRotate::processLoop(Loop *L) {
Justin Bognera7300452015-12-14 23:22:44 +0000599 // Save the loop metadata.
600 MDNode *LoopMD = L->getLoopID();
601
Justin Bognera7300452015-12-14 23:22:44 +0000602 // Simplify the loop latch before attempting to rotate the header
603 // upward. Rotation may not be needed if the loop tail can be folded into the
604 // loop exit.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000605 bool SimplifiedLatch = simplifyLoopLatch(L);
Justin Bognera7300452015-12-14 23:22:44 +0000606
Sebastian Popdfb66a12016-06-14 14:44:05 +0000607 bool MadeChange = rotateLoop(L, SimplifiedLatch);
Michael Zolotukhinb98294d2016-06-10 22:03:56 +0000608 assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
609 "Loop latch should be exiting after loop-rotate.");
Justin Bognera7300452015-12-14 23:22:44 +0000610
611 // Restore the loop metadata.
612 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
613 if ((MadeChange || SimplifiedLatch) && LoopMD)
614 L->setLoopID(LoopMD);
615
616 return MadeChange;
617}
Justin Bogner6291b582015-12-14 23:22:48 +0000618
Sebastian Popdfb66a12016-06-14 14:44:05 +0000619LoopRotatePass::LoopRotatePass() {}
Justin Bognerd0d23412016-05-03 22:02:31 +0000620
621PreservedAnalyses LoopRotatePass::run(Loop &L, AnalysisManager<Loop> &AM) {
622 auto &FAM = AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
623 Function *F = L.getHeader()->getParent();
624
625 auto *LI = FAM.getCachedResult<LoopAnalysis>(*F);
626 const auto *TTI = FAM.getCachedResult<TargetIRAnalysis>(*F);
627 auto *AC = FAM.getCachedResult<AssumptionAnalysis>(*F);
628 assert((LI && TTI && AC) && "Analyses for loop rotation not available");
629
630 // Optional analyses.
631 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
632 auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
Sebastian Popdfb66a12016-06-14 14:44:05 +0000633 LoopRotate LR(DefaultRotationThreshold, LI, TTI, AC, DT, SE);
Justin Bognerd0d23412016-05-03 22:02:31 +0000634
Sebastian Popdfb66a12016-06-14 14:44:05 +0000635 bool Changed = LR.processLoop(&L);
Justin Bognerd0d23412016-05-03 22:02:31 +0000636 if (!Changed)
637 return PreservedAnalyses::all();
638 return getLoopPassPreservedAnalyses();
639}
640
Justin Bogner6291b582015-12-14 23:22:48 +0000641namespace {
642
Justin Bognerd0d23412016-05-03 22:02:31 +0000643class LoopRotateLegacyPass : public LoopPass {
Justin Bogner6291b582015-12-14 23:22:48 +0000644 unsigned MaxHeaderSize;
645
646public:
647 static char ID; // Pass ID, replacement for typeid
Justin Bognerd0d23412016-05-03 22:02:31 +0000648 LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
649 initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry());
Justin Bogner6291b582015-12-14 23:22:48 +0000650 if (SpecifiedMaxHeaderSize == -1)
651 MaxHeaderSize = DefaultRotationThreshold;
652 else
653 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
654 }
655
656 // LCSSA form makes instruction renaming easier.
657 void getAnalysisUsage(AnalysisUsage &AU) const override {
Justin Bogner6291b582015-12-14 23:22:48 +0000658 AU.addRequired<AssumptionCacheTracker>();
Justin Bogner6291b582015-12-14 23:22:48 +0000659 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000660 getLoopAnalysisUsage(AU);
Justin Bogner6291b582015-12-14 23:22:48 +0000661 }
662
663 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000664 if (skipLoop(L))
Justin Bogner6291b582015-12-14 23:22:48 +0000665 return false;
666 Function &F = *L->getHeader()->getParent();
667
668 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
669 const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
670 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
671 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
672 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
673 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
674 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
Sebastian Popdfb66a12016-06-14 14:44:05 +0000675 LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE);
676 return LR.processLoop(L);
Justin Bogner6291b582015-12-14 23:22:48 +0000677 }
678};
679}
680
Justin Bognerd0d23412016-05-03 22:02:31 +0000681char LoopRotateLegacyPass::ID = 0;
682INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
683 false, false)
Justin Bogner6291b582015-12-14 23:22:48 +0000684INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth31088a92016-02-19 10:45:18 +0000685INITIALIZE_PASS_DEPENDENCY(LoopPass)
686INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Sebastian Popdfb66a12016-06-14 14:44:05 +0000687INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false,
688 false)
Justin Bogner6291b582015-12-14 23:22:48 +0000689
690Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
Justin Bognerd0d23412016-05-03 22:02:31 +0000691 return new LoopRotateLegacyPass(MaxHeaderSize);
Justin Bogner6291b582015-12-14 23:22:48 +0000692}