blob: 1c567fd66557e08e605c6ff113194a1fd8e78446 [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 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"
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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Transforms/Utils/BasicBlockUtils.h"
36#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000037#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/Transforms/Utils/SSAUpdater.h"
39#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelf42389f2007-04-07 01:25:15 +000040using namespace llvm;
41
Chandler Carruth964daaa2014-04-22 02:55:47 +000042#define DEBUG_TYPE "loop-rotate"
43
Owen Anderson115aa162014-05-26 08:58:51 +000044static cl::opt<unsigned>
45DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
46 cl::desc("The default maximum header size for automatic loop rotation"));
Devang Patelf42389f2007-04-07 01:25:15 +000047
48STATISTIC(NumRotated, "Number of loops rotated");
Devang Patelf42389f2007-04-07 01:25:15 +000049
Chris Lattner30f318e2011-01-08 19:26:33 +000050/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
51/// old header into the preheader. If there were uses of the values produced by
52/// these instruction that were outside of the loop, we have to insert PHI nodes
53/// to merge the two values. Do this now.
54static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
55 BasicBlock *OrigPreheader,
56 ValueToValueMapTy &ValueMap) {
57 // Remove PHI node entries that are no longer live.
58 BasicBlock::iterator I, E = OrigHeader->end();
59 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
60 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Tricka20f1982012-02-14 00:00:19 +000061
Chris Lattner30f318e2011-01-08 19:26:33 +000062 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
63 // as necessary.
64 SSAUpdater SSA;
65 for (I = OrigHeader->begin(); I != E; ++I) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +000066 Value *OrigHeaderVal = &*I;
Andrew Tricka20f1982012-02-14 00:00:19 +000067
Chris Lattner30f318e2011-01-08 19:26:33 +000068 // If there are no uses of the value (e.g. because it returns void), there
69 // is nothing to rewrite.
70 if (OrigHeaderVal->use_empty())
71 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +000072
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +000073 Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
Chris Lattner30f318e2011-01-08 19:26:33 +000074
75 // The value now exits in two versions: the initial value in the preheader
76 // and the loop "next" value in the original header.
77 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
78 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
79 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Tricka20f1982012-02-14 00:00:19 +000080
Chris Lattner30f318e2011-01-08 19:26:33 +000081 // Visit each use of the OrigHeader instruction.
82 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
83 UE = OrigHeaderVal->use_end(); UI != UE; ) {
84 // Grab the use before incrementing the iterator.
Chandler Carruthcdf47882014-03-09 03:16:01 +000085 Use &U = *UI;
Andrew Tricka20f1982012-02-14 00:00:19 +000086
Chris Lattner30f318e2011-01-08 19:26:33 +000087 // Increment the iterator before removing the use from the list.
88 ++UI;
Andrew Tricka20f1982012-02-14 00:00:19 +000089
Chris Lattner30f318e2011-01-08 19:26:33 +000090 // SSAUpdater can't handle a non-PHI use in the same block as an
91 // earlier def. We can easily handle those cases manually.
92 Instruction *UserInst = cast<Instruction>(U.getUser());
93 if (!isa<PHINode>(UserInst)) {
94 BasicBlock *UserBB = UserInst->getParent();
Andrew Tricka20f1982012-02-14 00:00:19 +000095
Chris Lattner30f318e2011-01-08 19:26:33 +000096 // The original users in the OrigHeader are already using the
97 // original definitions.
98 if (UserBB == OrigHeader)
99 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000100
Chris Lattner30f318e2011-01-08 19:26:33 +0000101 // Users in the OrigPreHeader need to use the value to which the
102 // original definitions are mapped.
103 if (UserBB == OrigPreheader) {
104 U = OrigPreHeaderVal;
105 continue;
106 }
107 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000108
Chris Lattner30f318e2011-01-08 19:26:33 +0000109 // Anything else can be handled by SSAUpdater.
110 SSA.RewriteUse(U);
111 }
112 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000113}
Chris Lattner30f318e2011-01-08 19:26:33 +0000114
Dan Gohmanb5650eb2007-05-11 21:10:54 +0000115/// Rotate loop LP. Return true if the loop is rotated.
Andrew Trick9c72b072013-05-06 17:58:18 +0000116///
117/// \param SimplifiedLatch is true if the latch was just folded into the final
118/// loop exit. In this case we may want to rotate even though the new latch is
119/// now an exiting branch. This rotation would have happened had the latch not
120/// been simplified. However, if SimplifiedLatch is false, then we avoid
121/// rotating loops in which the latch exits to avoid excessive or endless
122/// rotation. LoopRotate should be repeatable and converge to a canonical
123/// form. This property is satisfied because simplifying the loop latch can only
124/// happen once across multiple invocations of the LoopRotate pass.
Justin Bogner6291b582015-12-14 23:22:48 +0000125static bool rotateLoop(Loop *L, unsigned MaxHeaderSize, LoopInfo *LI,
126 const TargetTransformInfo *TTI, AssumptionCache *AC,
127 DominatorTree *DT, ScalarEvolution *SE,
128 bool SimplifiedLatch) {
Dan Gohman091e4402009-06-25 00:22:44 +0000129 // If the loop has only one block then there is not much to rotate.
Devang Patel88bc2c62007-04-09 16:11:48 +0000130 if (L->getBlocks().size() == 1)
Devang Patelf42389f2007-04-07 01:25:15 +0000131 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000132
Chris Lattner7fab23b2011-01-08 18:06:22 +0000133 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000134 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Tricka20f1982012-02-14 00:00:19 +0000135
Chris Lattner7fab23b2011-01-08 18:06:22 +0000136 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000137 if (!BI || BI->isUnconditional())
Chris Lattner7fab23b2011-01-08 18:06:22 +0000138 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000139
Dan Gohman091e4402009-06-25 00:22:44 +0000140 // If the loop header is not one of the loop exiting blocks then
141 // either this loop is already rotated or it is not
Devang Patelf42389f2007-04-07 01:25:15 +0000142 // suitable for loop rotation transformations.
Dan Gohman8f4078b2009-10-24 23:34:26 +0000143 if (!L->isLoopExiting(OrigHeader))
Devang Patelf42389f2007-04-07 01:25:15 +0000144 return false;
145
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000146 // If the loop latch already contains a branch that leaves the loop then the
147 // loop is already rotated.
Craig Topperf40110f2014-04-25 05:29:35 +0000148 if (!OrigLatch)
Andrew Trick9c72b072013-05-06 17:58:18 +0000149 return false;
150
151 // Rotate if either the loop latch does *not* exit the loop, or if the loop
152 // latch was just simplified.
153 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
Devang Patelf42389f2007-04-07 01:25:15 +0000154 return false;
155
James Molloy4f6fb952012-12-20 16:04:27 +0000156 // Check size of original header and reject loop if it is very big or we can't
157 // duplicate blocks inside it.
Chris Lattner679572e2011-01-02 07:35:53 +0000158 {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000159 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000160 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000161
Chris Lattner679572e2011-01-02 07:35:53 +0000162 CodeMetrics Metrics;
Hal Finkel57f03dd2014-09-07 13:49:57 +0000163 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
James Molloy4f6fb952012-12-20 16:04:27 +0000164 if (Metrics.notDuplicatable) {
Alp Tokerf907b892013-12-05 05:44:44 +0000165 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
James Molloy4f6fb952012-12-20 16:04:27 +0000166 << " instructions: "; L->dump());
167 return false;
168 }
Justin Lebardf04d2a2016-02-12 21:01:33 +0000169 if (Metrics.convergent) {
170 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
171 "instructions: "; L->dump());
172 return false;
173 }
Owen Anderson115aa162014-05-26 08:58:51 +0000174 if (Metrics.NumInsts > MaxHeaderSize)
Chris Lattner679572e2011-01-02 07:35:53 +0000175 return false;
Devang Patelbab43b42009-03-06 03:51:30 +0000176 }
177
Devang Patelfac4d1f2007-07-11 23:47:28 +0000178 // Now, this loop is suitable for rotation.
Chris Lattner30f318e2011-01-08 19:26:33 +0000179 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Tricka20f1982012-02-14 00:00:19 +0000180
Chris Lattner88974f42011-04-09 07:25:58 +0000181 // If the loop could not be converted to canonical form, it must have an
182 // indirectbr in it, just give up.
Craig Topperf40110f2014-04-25 05:29:35 +0000183 if (!OrigPreheader)
Chris Lattner88974f42011-04-09 07:25:58 +0000184 return false;
Devang Patelfac4d1f2007-07-11 23:47:28 +0000185
Dan Gohmanfc20b672009-09-27 15:37:03 +0000186 // Anything ScalarEvolution may know about this loop or the PHI nodes
187 // in its header will soon be invalidated.
Justin Bogner6291b582015-12-14 23:22:48 +0000188 if (SE)
189 SE->forgetLoop(L);
Dan Gohmanfc20b672009-09-27 15:37:03 +0000190
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000191 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
192
Devang Patelf42389f2007-04-07 01:25:15 +0000193 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattner57cb4722009-01-26 01:57:01 +0000194 // that is inside loop. Header's other successor is outside the
195 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner385f2ec2011-01-08 17:48:33 +0000196 BasicBlock *Exit = BI->getSuccessor(0);
197 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel88bc2c62007-04-09 16:11:48 +0000198 if (L->contains(Exit))
199 std::swap(Exit, NewHeader);
Chris Lattnerd67aaa62009-01-26 01:38:24 +0000200 assert(NewHeader && "Unable to determine new loop header");
Andrew Tricka20f1982012-02-14 00:00:19 +0000201 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel88bc2c62007-04-09 16:11:48 +0000202 "Unable to determine loop header and exit blocks");
Andrew Tricka20f1982012-02-14 00:00:19 +0000203
Dan Gohman091e4402009-06-25 00:22:44 +0000204 // This code assumes that the new header has exactly one predecessor.
205 // Remove any single-entry PHI nodes in it.
Chris Lattner7b6647c2009-01-26 02:11:30 +0000206 assert(NewHeader->getSinglePredecessor() &&
207 "New header doesn't have one pred!");
208 FoldSingleEntryPHINodes(NewHeader);
Devang Patelf42389f2007-04-07 01:25:15 +0000209
Dan Gohmanb9797942009-10-24 23:19:52 +0000210 // Begin by walking OrigHeader and populating ValueMap with an entry for
211 // each Instruction.
Devang Patel88bc2c62007-04-09 16:11:48 +0000212 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner2b3f20e2011-01-08 07:21:31 +0000213 ValueToValueMapTy ValueMap;
Devang Patelb9af5742007-04-09 19:04:21 +0000214
Dan Gohmanb9797942009-10-24 23:19:52 +0000215 // For PHI nodes, the value available in OldPreHeader is just the
216 // incoming value from OldPreHeader.
217 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foad372ad642011-06-20 14:18:48 +0000218 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000219
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000220 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
221
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000222 // For the rest of the instructions, either hoist to the OrigPreheader if
223 // possible or create a clone in the OldPreHeader if not.
Chris Lattner30f318e2011-01-08 19:26:33 +0000224 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000225 while (I != E) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000226 Instruction *Inst = &*I++;
Andrew Tricka20f1982012-02-14 00:00:19 +0000227
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000228 // If the instruction's operands are invariant and it doesn't read or write
229 // memory, then it is safe to hoist. Doing this doesn't change the order of
230 // execution in the preheader, but does prevent the instruction from
231 // executing in each iteration of the loop. This means it is safe to hoist
232 // something that might trap, but isn't safe to hoist something that reads
233 // memory (without proving that the loop doesn't write).
234 if (L->hasLoopInvariantOperands(Inst) &&
235 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
Eli Friedmanc4588852012-02-16 00:41:10 +0000236 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
237 !isa<AllocaInst>(Inst)) {
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000238 Inst->moveBefore(LoopEntryBranch);
239 continue;
240 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000241
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000242 // Otherwise, create a duplicate of the instruction.
243 Instruction *C = Inst->clone();
Andrew Tricka20f1982012-02-14 00:00:19 +0000244
Chris Lattner8c5defd2011-01-08 08:24:46 +0000245 // Eagerly remap the operands of the instruction.
246 RemapInstruction(C, ValueMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000247 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Andrew Tricka20f1982012-02-14 00:00:19 +0000248
Chris Lattner8c5defd2011-01-08 08:24:46 +0000249 // With the operands remapped, see if the instruction constant folds or is
250 // otherwise simplifyable. This commonly occurs because the entry from PHI
251 // nodes allows icmps and other instructions to fold.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000252 // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
253 Value *V = SimplifyInstruction(C, DL);
Chris Lattner25ba40a2011-01-08 17:38:45 +0000254 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000255 // If so, then delete the temporary instruction and stick the folded value
256 // in the map.
257 delete C;
258 ValueMap[Inst] = V;
259 } else {
260 // Otherwise, stick the new instruction into the new block!
261 C->setName(Inst->getName());
262 C->insertBefore(LoopEntryBranch);
263 ValueMap[Inst] = C;
264 }
Devang Patelf42389f2007-04-07 01:25:15 +0000265 }
266
Dan Gohmanb9797942009-10-24 23:19:52 +0000267 // Along with all the other instructions, we just cloned OrigHeader's
268 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
269 // successors by duplicating their incoming values for OrigHeader.
270 TerminatorInst *TI = OrigHeader->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +0000271 for (BasicBlock *SuccBB : TI->successors())
272 for (BasicBlock::iterator BI = SuccBB->begin();
Dan Gohmanb9797942009-10-24 23:19:52 +0000273 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner30f318e2011-01-08 19:26:33 +0000274 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000275
Dan Gohmanb9797942009-10-24 23:19:52 +0000276 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
277 // OrigPreHeader's old terminator (the original branch into the loop), and
278 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
279 LoopEntryBranch->eraseFromParent();
Devang Patelf42389f2007-04-07 01:25:15 +0000280
Chris Lattner30f318e2011-01-08 19:26:33 +0000281 // If there were any uses of instructions in the duplicated block outside the
282 // loop, update them, inserting PHI nodes as required
283 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelf42389f2007-04-07 01:25:15 +0000284
Dan Gohmanb9797942009-10-24 23:19:52 +0000285 // NewHeader is now the header of the loop.
Devang Patelf42389f2007-04-07 01:25:15 +0000286 L->moveToHeader(NewHeader);
Chris Lattner26151302011-01-08 19:10:28 +0000287 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelf42389f2007-04-07 01:25:15 +0000288
Andrew Tricka20f1982012-02-14 00:00:19 +0000289
Chris Lattner59c82f82011-01-08 19:59:06 +0000290 // At this point, we've finished our major CFG changes. As part of cloning
291 // the loop into the preheader we've simplified instructions and the
292 // duplicated conditional branch may now be branching on a constant. If it is
293 // branching on a constant and if that constant means that we enter the loop,
294 // then we fold away the cond branch to an uncond branch. This simplifies the
295 // loop in cases important for nested loops, and it also means we don't have
296 // to split as many edges.
297 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
298 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
299 if (!isa<ConstantInt>(PHBI->getCondition()) ||
300 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
301 != NewHeader) {
302 // The conditional branch can't be folded, handle the general case.
303 // Update DominatorTree to reflect the CFG change we just made. Then split
304 // edges as necessary to preserve LoopSimplify form.
Chandler Carruth94209092015-01-18 02:08:05 +0000305 if (DT) {
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000306 // Everything that was dominated by the old loop header is now dominated
307 // by the original loop preheader. Conceptually the header was merged
308 // into the preheader, even though we reuse the actual block as a new
309 // loop latch.
Chandler Carruth94209092015-01-18 02:08:05 +0000310 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000311 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
312 OrigHeaderNode->end());
Chandler Carruth94209092015-01-18 02:08:05 +0000313 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000314 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
Chandler Carruth94209092015-01-18 02:08:05 +0000315 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Tricka20f1982012-02-14 00:00:19 +0000316
Chandler Carruth94209092015-01-18 02:08:05 +0000317 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
318 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
Benjamin Kramer3be6a482012-09-01 12:04:51 +0000319
Chris Lattner59c82f82011-01-08 19:59:06 +0000320 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000321 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Chris Lattner59c82f82011-01-08 19:59:06 +0000322 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000323
Chris Lattner59c82f82011-01-08 19:59:06 +0000324 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotem465834c2012-07-24 10:51:42 +0000325 // thus is not a preheader anymore.
326 // Split the edge to form a real preheader.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000327 BasicBlock *NewPH = SplitCriticalEdge(
328 OrigPreheader, NewHeader,
329 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chris Lattner59c82f82011-01-08 19:59:06 +0000330 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Tricka20f1982012-02-14 00:00:19 +0000331
Nadav Rotem465834c2012-07-24 10:51:42 +0000332 // Preserve canonical loop form, which means that 'Exit' should have only
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000333 // one predecessor. Note that Exit could be an exit block for multiple
334 // nested loops, causing both of the edges to now be critical and need to
335 // be split.
336 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
337 bool SplitLatchEdge = false;
338 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
339 PE = ExitPreds.end();
340 PI != PE; ++PI) {
341 // We only need to split loop exit edges.
342 Loop *PredLoop = LI->getLoopFor(*PI);
343 if (!PredLoop || PredLoop->contains(Exit))
344 continue;
Benjamin Kramer911d5b32015-02-20 20:49:25 +0000345 if (isa<IndirectBrInst>((*PI)->getTerminator()))
346 continue;
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000347 SplitLatchEdge |= L->getLoopLatch() == *PI;
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000348 BasicBlock *ExitSplit = SplitCriticalEdge(
349 *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000350 ExitSplit->moveBefore(Exit);
351 }
352 assert(SplitLatchEdge &&
353 "Despite splitting all preds, failed to split latch exit?");
Chris Lattner59c82f82011-01-08 19:59:06 +0000354 } else {
355 // We can fold the conditional branch in the preheader, this makes things
356 // simpler. The first step is to remove the extra edge to the Exit block.
357 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelc1f7c1d2011-04-29 20:38:55 +0000358 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
359 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner59c82f82011-01-08 19:59:06 +0000360 PHBI->eraseFromParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000361
Chris Lattner59c82f82011-01-08 19:59:06 +0000362 // With our CFG finalized, update DomTree if it is available.
Chandler Carruth94209092015-01-18 02:08:05 +0000363 if (DT) {
Chris Lattner59c82f82011-01-08 19:59:06 +0000364 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000365 DT->changeImmediateDominator(NewHeader, OrigPreheader);
366 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000367
368 // Brute force incremental dominator tree update. Call
369 // findNearestCommonDominator on all CFG predecessors of each child of the
370 // original header.
Chandler Carruth94209092015-01-18 02:08:05 +0000371 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000372 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
373 OrigHeaderNode->end());
374 bool Changed;
375 do {
376 Changed = false;
377 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
378 DomTreeNode *Node = HeaderChildren[I];
379 BasicBlock *BB = Node->getBlock();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000380
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000381 pred_iterator PI = pred_begin(BB);
382 BasicBlock *NearestDom = *PI;
383 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
Chandler Carruth94209092015-01-18 02:08:05 +0000384 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000385
386 // Remember if this changes the DomTree.
387 if (Node->getIDom()->getBlock() != NearestDom) {
Chandler Carruth94209092015-01-18 02:08:05 +0000388 DT->changeImmediateDominator(BB, NearestDom);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000389 Changed = true;
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000390 }
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000391 }
392
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000393 // If the dominator changed, this may have an effect on other
394 // predecessors, continue until we reach a fixpoint.
395 } while (Changed);
Chris Lattner59c82f82011-01-08 19:59:06 +0000396 }
Devang Patelfac4d1f2007-07-11 23:47:28 +0000397 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000398
Chris Lattner59c82f82011-01-08 19:59:06 +0000399 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner063dca02011-01-08 18:52:51 +0000400 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnerfee37c52011-01-08 18:55:50 +0000401
Chris Lattner63fe78d2011-01-11 07:47:59 +0000402 // Now that the CFG and DomTree are in a consistent state again, try to merge
403 // the OrigHeader block into OrigLatch. This will succeed if they are
404 // connected by an unconditional branch. This is just a cleanup so the
405 // emitted code isn't too gross in this common case.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000406 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
Andrew Tricka20f1982012-02-14 00:00:19 +0000407
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000408 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
409
Chris Lattnerfee37c52011-01-08 18:55:50 +0000410 ++NumRotated;
411 return true;
Devang Patel85419782007-04-09 20:19:46 +0000412}
Justin Bognera7300452015-12-14 23:22:44 +0000413
414/// Determine whether the instructions in this range may be safely and cheaply
415/// speculated. This is not an important enough situation to develop complex
416/// heuristics. We handle a single arithmetic instruction along with any type
417/// conversions.
418static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
419 BasicBlock::iterator End, Loop *L) {
420 bool seenIncrement = false;
421 bool MultiExitLoop = false;
422
423 if (!L->getExitingBlock())
424 MultiExitLoop = true;
425
426 for (BasicBlock::iterator I = Begin; I != End; ++I) {
427
428 if (!isSafeToSpeculativelyExecute(&*I))
429 return false;
430
431 if (isa<DbgInfoIntrinsic>(I))
432 continue;
433
434 switch (I->getOpcode()) {
435 default:
436 return false;
437 case Instruction::GetElementPtr:
438 // GEPs are cheap if all indices are constant.
439 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
440 return false;
441 // fall-thru to increment case
442 case Instruction::Add:
443 case Instruction::Sub:
444 case Instruction::And:
445 case Instruction::Or:
446 case Instruction::Xor:
447 case Instruction::Shl:
448 case Instruction::LShr:
449 case Instruction::AShr: {
450 Value *IVOpnd = !isa<Constant>(I->getOperand(0))
451 ? I->getOperand(0)
452 : !isa<Constant>(I->getOperand(1))
453 ? I->getOperand(1)
454 : nullptr;
455 if (!IVOpnd)
456 return false;
457
458 // If increment operand is used outside of the loop, this speculation
459 // could cause extra live range interference.
460 if (MultiExitLoop) {
461 for (User *UseI : IVOpnd->users()) {
462 auto *UserInst = cast<Instruction>(UseI);
463 if (!L->contains(UserInst))
464 return false;
465 }
466 }
467
468 if (seenIncrement)
469 return false;
470 seenIncrement = true;
471 break;
472 }
473 case Instruction::Trunc:
474 case Instruction::ZExt:
475 case Instruction::SExt:
476 // ignore type conversions
477 break;
478 }
479 }
480 return true;
481}
482
483/// Fold the loop tail into the loop exit by speculating the loop tail
484/// instructions. Typically, this is a single post-increment. In the case of a
485/// simple 2-block loop, hoisting the increment can be much better than
486/// duplicating the entire loop header. In the case of loops with early exits,
487/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
488/// canonical form so downstream passes can handle it.
489///
490/// I don't believe this invalidates SCEV.
Justin Bogner6291b582015-12-14 23:22:48 +0000491static bool simplifyLoopLatch(Loop *L, LoopInfo *LI, DominatorTree *DT) {
Justin Bognera7300452015-12-14 23:22:44 +0000492 BasicBlock *Latch = L->getLoopLatch();
493 if (!Latch || Latch->hasAddressTaken())
494 return false;
495
496 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
497 if (!Jmp || !Jmp->isUnconditional())
498 return false;
499
500 BasicBlock *LastExit = Latch->getSinglePredecessor();
501 if (!LastExit || !L->isLoopExiting(LastExit))
502 return false;
503
504 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
505 if (!BI)
506 return false;
507
508 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
509 return false;
510
511 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
512 << LastExit->getName() << "\n");
513
514 // Hoist the instructions from Latch into LastExit.
515 LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
516 Latch->begin(), Jmp->getIterator());
517
518 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
519 BasicBlock *Header = Jmp->getSuccessor(0);
520 assert(Header == L->getHeader() && "expected a backward branch");
521
522 // Remove Latch from the CFG so that LastExit becomes the new Latch.
523 BI->setSuccessor(FallThruPath, Header);
524 Latch->replaceSuccessorsPhiUsesWith(LastExit);
525 Jmp->eraseFromParent();
526
527 // Nuke the Latch block.
528 assert(Latch->empty() && "unable to evacuate Latch");
529 LI->removeBlock(Latch);
530 if (DT)
531 DT->eraseNode(Latch);
532 Latch->eraseFromParent();
533 return true;
534}
535
Justin Bogner6291b582015-12-14 23:22:48 +0000536/// Rotate \c L as many times as possible. Return true if the loop is rotated
537/// at least once.
538static bool iterativelyRotateLoop(Loop *L, unsigned MaxHeaderSize, LoopInfo *LI,
539 const TargetTransformInfo *TTI,
540 AssumptionCache *AC, DominatorTree *DT,
541 ScalarEvolution *SE) {
Justin Bognera7300452015-12-14 23:22:44 +0000542 // Save the loop metadata.
543 MDNode *LoopMD = L->getLoopID();
544
Justin Bognera7300452015-12-14 23:22:44 +0000545 // Simplify the loop latch before attempting to rotate the header
546 // upward. Rotation may not be needed if the loop tail can be folded into the
547 // loop exit.
Justin Bogner6291b582015-12-14 23:22:48 +0000548 bool SimplifiedLatch = simplifyLoopLatch(L, LI, DT);
Justin Bognera7300452015-12-14 23:22:44 +0000549
550 // One loop can be rotated multiple times.
551 bool MadeChange = false;
Justin Bogner6291b582015-12-14 23:22:48 +0000552 while (rotateLoop(L, MaxHeaderSize, LI, TTI, AC, DT, SE, SimplifiedLatch)) {
Justin Bognera7300452015-12-14 23:22:44 +0000553 MadeChange = true;
554 SimplifiedLatch = false;
555 }
556
557 // Restore the loop metadata.
558 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
559 if ((MadeChange || SimplifiedLatch) && LoopMD)
560 L->setLoopID(LoopMD);
561
562 return MadeChange;
563}
Justin Bogner6291b582015-12-14 23:22:48 +0000564
565namespace {
566
567class LoopRotate : public LoopPass {
568 unsigned MaxHeaderSize;
569
570public:
571 static char ID; // Pass ID, replacement for typeid
572 LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
573 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
574 if (SpecifiedMaxHeaderSize == -1)
575 MaxHeaderSize = DefaultRotationThreshold;
576 else
577 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
578 }
579
580 // LCSSA form makes instruction renaming easier.
581 void getAnalysisUsage(AnalysisUsage &AU) const override {
Justin Bogner6291b582015-12-14 23:22:48 +0000582 AU.addRequired<AssumptionCacheTracker>();
Justin Bogner6291b582015-12-14 23:22:48 +0000583 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000584 getLoopAnalysisUsage(AU);
Justin Bogner6291b582015-12-14 23:22:48 +0000585 }
586
587 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
588 if (skipOptnoneFunction(L))
589 return false;
590 Function &F = *L->getHeader()->getParent();
591
592 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
593 const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
594 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
595 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
596 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
597 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
598 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
599
600 return iterativelyRotateLoop(L, MaxHeaderSize, LI, TTI, AC, DT, SE);
601 }
602};
603}
604
605char LoopRotate::ID = 0;
606INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Justin Bogner6291b582015-12-14 23:22:48 +0000607INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth31088a92016-02-19 10:45:18 +0000608INITIALIZE_PASS_DEPENDENCY(LoopPass)
609INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Justin Bogner6291b582015-12-14 23:22:48 +0000610INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
611
612Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
613 return new LoopRotate(MaxHeaderSize);
614}