blob: 6f8a35ecae2b288a12e9897af3e3bb5a3a274bf3 [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"
37#include "llvm/Transforms/Utils/SSAUpdater.h"
38#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelf42389f2007-04-07 01:25:15 +000039using namespace llvm;
40
Chandler Carruth964daaa2014-04-22 02:55:47 +000041#define DEBUG_TYPE "loop-rotate"
42
Owen Anderson115aa162014-05-26 08:58:51 +000043static cl::opt<unsigned>
44DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
45 cl::desc("The default maximum header size for automatic loop rotation"));
Devang Patelf42389f2007-04-07 01:25:15 +000046
47STATISTIC(NumRotated, "Number of loops rotated");
48namespace {
49
Chris Lattner2dd09db2009-09-02 06:11:42 +000050 class LoopRotate : public LoopPass {
Devang Patelf42389f2007-04-07 01:25:15 +000051 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000052 static char ID; // Pass ID, replacement for typeid
Owen Anderson115aa162014-05-26 08:58:51 +000053 LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +000054 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
Owen Anderson115aa162014-05-26 08:58:51 +000055 if (SpecifiedMaxHeaderSize == -1)
56 MaxHeaderSize = DefaultRotationThreshold;
57 else
58 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
Owen Anderson6c18d1a2010-10-19 17:21:58 +000059 }
Devang Patel09f162c2007-05-01 21:15:47 +000060
Devang Patel88bc2c62007-04-09 16:11:48 +000061 // LCSSA form makes instruction renaming easier.
Craig Topper3e4c6972014-03-05 09:10:37 +000062 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth7b560d42015-09-09 17:55:00 +000063 AU.addPreserved<AAResultsWrapperPass>();
Chandler Carruth66b31302015-01-04 12:03:27 +000064 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth73523022014-01-13 13:07:17 +000065 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +000066 AU.addRequired<LoopInfoWrapperPass>();
67 AU.addPreserved<LoopInfoWrapperPass>();
Devang Patela42c3142008-02-15 01:24:49 +000068 AU.addRequiredID(LoopSimplifyID);
69 AU.addPreservedID(LoopSimplifyID);
Devang Patelf42389f2007-04-07 01:25:15 +000070 AU.addRequiredID(LCSSAID);
71 AU.addPreservedID(LCSSAID);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000072 AU.addPreserved<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +000073 AU.addPreserved<SCEVAAWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +000074 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +000075 AU.addPreserved<BasicAAWrapperPass>();
76 AU.addPreserved<GlobalsAAWrapperPass>();
Devang Patelf42389f2007-04-07 01:25:15 +000077 }
78
Craig Topper3e4c6972014-03-05 09:10:37 +000079 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Andrew Trick9c72b072013-05-06 17:58:18 +000080 bool simplifyLoopLatch(Loop *L);
81 bool rotateLoop(Loop *L, bool SimplifiedLatch);
Andrew Tricka20f1982012-02-14 00:00:19 +000082
Devang Patelf42389f2007-04-07 01:25:15 +000083 private:
Owen Anderson115aa162014-05-26 08:58:51 +000084 unsigned MaxHeaderSize;
Chris Lattner25ba40a2011-01-08 17:38:45 +000085 LoopInfo *LI;
Chandler Carruthbb9caa92013-01-21 13:04:33 +000086 const TargetTransformInfo *TTI;
Chandler Carruth66b31302015-01-04 12:03:27 +000087 AssumptionCache *AC;
Chandler Carruth94209092015-01-18 02:08:05 +000088 DominatorTree *DT;
Devang Patelf42389f2007-04-07 01:25:15 +000089 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000090}
Andrew Tricka20f1982012-02-14 00:00:19 +000091
Dan Gohmand78c4002008-05-13 00:00:25 +000092char LoopRotate::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000093INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +000094INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +000095INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth4f8f3072015-01-17 14:16:18 +000096INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +000097INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
98INITIALIZE_PASS_DEPENDENCY(LCSSA)
Chandler Carruth7b560d42015-09-09 17:55:00 +000099INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
100INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
101INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000102INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelf42389f2007-04-07 01:25:15 +0000103
Owen Anderson115aa162014-05-26 08:58:51 +0000104Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
105 return new LoopRotate(MaxHeaderSize);
106}
Devang Patelf42389f2007-04-07 01:25:15 +0000107
Chris Lattner30f318e2011-01-08 19:26:33 +0000108/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
109/// old header into the preheader. If there were uses of the values produced by
110/// these instruction that were outside of the loop, we have to insert PHI nodes
111/// to merge the two values. Do this now.
112static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
113 BasicBlock *OrigPreheader,
114 ValueToValueMapTy &ValueMap) {
115 // Remove PHI node entries that are no longer live.
116 BasicBlock::iterator I, E = OrigHeader->end();
117 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
118 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Tricka20f1982012-02-14 00:00:19 +0000119
Chris Lattner30f318e2011-01-08 19:26:33 +0000120 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
121 // as necessary.
122 SSAUpdater SSA;
123 for (I = OrigHeader->begin(); I != E; ++I) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000124 Value *OrigHeaderVal = &*I;
Andrew Tricka20f1982012-02-14 00:00:19 +0000125
Chris Lattner30f318e2011-01-08 19:26:33 +0000126 // If there are no uses of the value (e.g. because it returns void), there
127 // is nothing to rewrite.
128 if (OrigHeaderVal->use_empty())
129 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000130
Chris Lattner30f318e2011-01-08 19:26:33 +0000131 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
132
133 // The value now exits in two versions: the initial value in the preheader
134 // and the loop "next" value in the original header.
135 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
136 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
137 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Tricka20f1982012-02-14 00:00:19 +0000138
Chris Lattner30f318e2011-01-08 19:26:33 +0000139 // Visit each use of the OrigHeader instruction.
140 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
141 UE = OrigHeaderVal->use_end(); UI != UE; ) {
142 // Grab the use before incrementing the iterator.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000143 Use &U = *UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000144
Chris Lattner30f318e2011-01-08 19:26:33 +0000145 // Increment the iterator before removing the use from the list.
146 ++UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000147
Chris Lattner30f318e2011-01-08 19:26:33 +0000148 // SSAUpdater can't handle a non-PHI use in the same block as an
149 // earlier def. We can easily handle those cases manually.
150 Instruction *UserInst = cast<Instruction>(U.getUser());
151 if (!isa<PHINode>(UserInst)) {
152 BasicBlock *UserBB = UserInst->getParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000153
Chris Lattner30f318e2011-01-08 19:26:33 +0000154 // The original users in the OrigHeader are already using the
155 // original definitions.
156 if (UserBB == OrigHeader)
157 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000158
Chris Lattner30f318e2011-01-08 19:26:33 +0000159 // Users in the OrigPreHeader need to use the value to which the
160 // original definitions are mapped.
161 if (UserBB == OrigPreheader) {
162 U = OrigPreHeaderVal;
163 continue;
164 }
165 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000166
Chris Lattner30f318e2011-01-08 19:26:33 +0000167 // Anything else can be handled by SSAUpdater.
168 SSA.RewriteUse(U);
169 }
170 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000171}
Chris Lattner30f318e2011-01-08 19:26:33 +0000172
Dan Gohmanb5650eb2007-05-11 21:10:54 +0000173/// Rotate loop LP. Return true if the loop is rotated.
Andrew Trick9c72b072013-05-06 17:58:18 +0000174///
175/// \param SimplifiedLatch is true if the latch was just folded into the final
176/// loop exit. In this case we may want to rotate even though the new latch is
177/// now an exiting branch. This rotation would have happened had the latch not
178/// been simplified. However, if SimplifiedLatch is false, then we avoid
179/// rotating loops in which the latch exits to avoid excessive or endless
180/// rotation. LoopRotate should be repeatable and converge to a canonical
181/// form. This property is satisfied because simplifying the loop latch can only
182/// happen once across multiple invocations of the LoopRotate pass.
183bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
Dan Gohman091e4402009-06-25 00:22:44 +0000184 // If the loop has only one block then there is not much to rotate.
Devang Patel88bc2c62007-04-09 16:11:48 +0000185 if (L->getBlocks().size() == 1)
Devang Patelf42389f2007-04-07 01:25:15 +0000186 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000187
Chris Lattner7fab23b2011-01-08 18:06:22 +0000188 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000189 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Tricka20f1982012-02-14 00:00:19 +0000190
Chris Lattner7fab23b2011-01-08 18:06:22 +0000191 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000192 if (!BI || BI->isUnconditional())
Chris Lattner7fab23b2011-01-08 18:06:22 +0000193 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000194
Dan Gohman091e4402009-06-25 00:22:44 +0000195 // If the loop header is not one of the loop exiting blocks then
196 // either this loop is already rotated or it is not
Devang Patelf42389f2007-04-07 01:25:15 +0000197 // suitable for loop rotation transformations.
Dan Gohman8f4078b2009-10-24 23:34:26 +0000198 if (!L->isLoopExiting(OrigHeader))
Devang Patelf42389f2007-04-07 01:25:15 +0000199 return false;
200
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000201 // If the loop latch already contains a branch that leaves the loop then the
202 // loop is already rotated.
Craig Topperf40110f2014-04-25 05:29:35 +0000203 if (!OrigLatch)
Andrew Trick9c72b072013-05-06 17:58:18 +0000204 return false;
205
206 // Rotate if either the loop latch does *not* exit the loop, or if the loop
207 // latch was just simplified.
208 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
Devang Patelf42389f2007-04-07 01:25:15 +0000209 return false;
210
James Molloy4f6fb952012-12-20 16:04:27 +0000211 // Check size of original header and reject loop if it is very big or we can't
212 // duplicate blocks inside it.
Chris Lattner679572e2011-01-02 07:35:53 +0000213 {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000214 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000215 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000216
Chris Lattner679572e2011-01-02 07:35:53 +0000217 CodeMetrics Metrics;
Hal Finkel57f03dd2014-09-07 13:49:57 +0000218 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
James Molloy4f6fb952012-12-20 16:04:27 +0000219 if (Metrics.notDuplicatable) {
Alp Tokerf907b892013-12-05 05:44:44 +0000220 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
James Molloy4f6fb952012-12-20 16:04:27 +0000221 << " instructions: "; L->dump());
222 return false;
223 }
Owen Anderson115aa162014-05-26 08:58:51 +0000224 if (Metrics.NumInsts > MaxHeaderSize)
Chris Lattner679572e2011-01-02 07:35:53 +0000225 return false;
Devang Patelbab43b42009-03-06 03:51:30 +0000226 }
227
Devang Patelfac4d1f2007-07-11 23:47:28 +0000228 // Now, this loop is suitable for rotation.
Chris Lattner30f318e2011-01-08 19:26:33 +0000229 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Tricka20f1982012-02-14 00:00:19 +0000230
Chris Lattner88974f42011-04-09 07:25:58 +0000231 // If the loop could not be converted to canonical form, it must have an
232 // indirectbr in it, just give up.
Craig Topperf40110f2014-04-25 05:29:35 +0000233 if (!OrigPreheader)
Chris Lattner88974f42011-04-09 07:25:58 +0000234 return false;
Devang Patelfac4d1f2007-07-11 23:47:28 +0000235
Dan Gohmanfc20b672009-09-27 15:37:03 +0000236 // Anything ScalarEvolution may know about this loop or the PHI nodes
237 // in its header will soon be invalidated.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000238 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
239 SEWP->getSE().forgetLoop(L);
Dan Gohmanfc20b672009-09-27 15:37:03 +0000240
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000241 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
242
Devang Patelf42389f2007-04-07 01:25:15 +0000243 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattner57cb4722009-01-26 01:57:01 +0000244 // that is inside loop. Header's other successor is outside the
245 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner385f2ec2011-01-08 17:48:33 +0000246 BasicBlock *Exit = BI->getSuccessor(0);
247 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel88bc2c62007-04-09 16:11:48 +0000248 if (L->contains(Exit))
249 std::swap(Exit, NewHeader);
Chris Lattnerd67aaa62009-01-26 01:38:24 +0000250 assert(NewHeader && "Unable to determine new loop header");
Andrew Tricka20f1982012-02-14 00:00:19 +0000251 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel88bc2c62007-04-09 16:11:48 +0000252 "Unable to determine loop header and exit blocks");
Andrew Tricka20f1982012-02-14 00:00:19 +0000253
Dan Gohman091e4402009-06-25 00:22:44 +0000254 // This code assumes that the new header has exactly one predecessor.
255 // Remove any single-entry PHI nodes in it.
Chris Lattner7b6647c2009-01-26 02:11:30 +0000256 assert(NewHeader->getSinglePredecessor() &&
257 "New header doesn't have one pred!");
258 FoldSingleEntryPHINodes(NewHeader);
Devang Patelf42389f2007-04-07 01:25:15 +0000259
Dan Gohmanb9797942009-10-24 23:19:52 +0000260 // Begin by walking OrigHeader and populating ValueMap with an entry for
261 // each Instruction.
Devang Patel88bc2c62007-04-09 16:11:48 +0000262 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner2b3f20e2011-01-08 07:21:31 +0000263 ValueToValueMapTy ValueMap;
Devang Patelb9af5742007-04-09 19:04:21 +0000264
Dan Gohmanb9797942009-10-24 23:19:52 +0000265 // For PHI nodes, the value available in OldPreHeader is just the
266 // incoming value from OldPreHeader.
267 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foad372ad642011-06-20 14:18:48 +0000268 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000269
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000270 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
271
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000272 // For the rest of the instructions, either hoist to the OrigPreheader if
273 // possible or create a clone in the OldPreHeader if not.
Chris Lattner30f318e2011-01-08 19:26:33 +0000274 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000275 while (I != E) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000276 Instruction *Inst = &*I++;
Andrew Tricka20f1982012-02-14 00:00:19 +0000277
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000278 // If the instruction's operands are invariant and it doesn't read or write
279 // memory, then it is safe to hoist. Doing this doesn't change the order of
280 // execution in the preheader, but does prevent the instruction from
281 // executing in each iteration of the loop. This means it is safe to hoist
282 // something that might trap, but isn't safe to hoist something that reads
283 // memory (without proving that the loop doesn't write).
284 if (L->hasLoopInvariantOperands(Inst) &&
285 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
Eli Friedmanc4588852012-02-16 00:41:10 +0000286 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
287 !isa<AllocaInst>(Inst)) {
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000288 Inst->moveBefore(LoopEntryBranch);
289 continue;
290 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000291
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000292 // Otherwise, create a duplicate of the instruction.
293 Instruction *C = Inst->clone();
Andrew Tricka20f1982012-02-14 00:00:19 +0000294
Chris Lattner8c5defd2011-01-08 08:24:46 +0000295 // Eagerly remap the operands of the instruction.
296 RemapInstruction(C, ValueMap,
297 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Tricka20f1982012-02-14 00:00:19 +0000298
Chris Lattner8c5defd2011-01-08 08:24:46 +0000299 // With the operands remapped, see if the instruction constant folds or is
300 // otherwise simplifyable. This commonly occurs because the entry from PHI
301 // nodes allows icmps and other instructions to fold.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000302 // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
303 Value *V = SimplifyInstruction(C, DL);
Chris Lattner25ba40a2011-01-08 17:38:45 +0000304 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000305 // If so, then delete the temporary instruction and stick the folded value
306 // in the map.
307 delete C;
308 ValueMap[Inst] = V;
309 } else {
310 // Otherwise, stick the new instruction into the new block!
311 C->setName(Inst->getName());
312 C->insertBefore(LoopEntryBranch);
313 ValueMap[Inst] = C;
314 }
Devang Patelf42389f2007-04-07 01:25:15 +0000315 }
316
Dan Gohmanb9797942009-10-24 23:19:52 +0000317 // Along with all the other instructions, we just cloned OrigHeader's
318 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
319 // successors by duplicating their incoming values for OrigHeader.
320 TerminatorInst *TI = OrigHeader->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +0000321 for (BasicBlock *SuccBB : TI->successors())
322 for (BasicBlock::iterator BI = SuccBB->begin();
Dan Gohmanb9797942009-10-24 23:19:52 +0000323 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner30f318e2011-01-08 19:26:33 +0000324 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000325
Dan Gohmanb9797942009-10-24 23:19:52 +0000326 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
327 // OrigPreHeader's old terminator (the original branch into the loop), and
328 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
329 LoopEntryBranch->eraseFromParent();
Devang Patelf42389f2007-04-07 01:25:15 +0000330
Chris Lattner30f318e2011-01-08 19:26:33 +0000331 // If there were any uses of instructions in the duplicated block outside the
332 // loop, update them, inserting PHI nodes as required
333 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelf42389f2007-04-07 01:25:15 +0000334
Dan Gohmanb9797942009-10-24 23:19:52 +0000335 // NewHeader is now the header of the loop.
Devang Patelf42389f2007-04-07 01:25:15 +0000336 L->moveToHeader(NewHeader);
Chris Lattner26151302011-01-08 19:10:28 +0000337 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelf42389f2007-04-07 01:25:15 +0000338
Andrew Tricka20f1982012-02-14 00:00:19 +0000339
Chris Lattner59c82f82011-01-08 19:59:06 +0000340 // At this point, we've finished our major CFG changes. As part of cloning
341 // the loop into the preheader we've simplified instructions and the
342 // duplicated conditional branch may now be branching on a constant. If it is
343 // branching on a constant and if that constant means that we enter the loop,
344 // then we fold away the cond branch to an uncond branch. This simplifies the
345 // loop in cases important for nested loops, and it also means we don't have
346 // to split as many edges.
347 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
348 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
349 if (!isa<ConstantInt>(PHBI->getCondition()) ||
350 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
351 != NewHeader) {
352 // The conditional branch can't be folded, handle the general case.
353 // Update DominatorTree to reflect the CFG change we just made. Then split
354 // edges as necessary to preserve LoopSimplify form.
Chandler Carruth94209092015-01-18 02:08:05 +0000355 if (DT) {
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000356 // Everything that was dominated by the old loop header is now dominated
357 // by the original loop preheader. Conceptually the header was merged
358 // into the preheader, even though we reuse the actual block as a new
359 // loop latch.
Chandler Carruth94209092015-01-18 02:08:05 +0000360 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000361 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
362 OrigHeaderNode->end());
Chandler Carruth94209092015-01-18 02:08:05 +0000363 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000364 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
Chandler Carruth94209092015-01-18 02:08:05 +0000365 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Tricka20f1982012-02-14 00:00:19 +0000366
Chandler Carruth94209092015-01-18 02:08:05 +0000367 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
368 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
Benjamin Kramer3be6a482012-09-01 12:04:51 +0000369
Chris Lattner59c82f82011-01-08 19:59:06 +0000370 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000371 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Chris Lattner59c82f82011-01-08 19:59:06 +0000372 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000373
Chris Lattner59c82f82011-01-08 19:59:06 +0000374 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotem465834c2012-07-24 10:51:42 +0000375 // thus is not a preheader anymore.
376 // Split the edge to form a real preheader.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000377 BasicBlock *NewPH = SplitCriticalEdge(
378 OrigPreheader, NewHeader,
379 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chris Lattner59c82f82011-01-08 19:59:06 +0000380 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Tricka20f1982012-02-14 00:00:19 +0000381
Nadav Rotem465834c2012-07-24 10:51:42 +0000382 // Preserve canonical loop form, which means that 'Exit' should have only
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000383 // one predecessor. Note that Exit could be an exit block for multiple
384 // nested loops, causing both of the edges to now be critical and need to
385 // be split.
386 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
387 bool SplitLatchEdge = false;
388 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
389 PE = ExitPreds.end();
390 PI != PE; ++PI) {
391 // We only need to split loop exit edges.
392 Loop *PredLoop = LI->getLoopFor(*PI);
393 if (!PredLoop || PredLoop->contains(Exit))
394 continue;
Benjamin Kramer911d5b32015-02-20 20:49:25 +0000395 if (isa<IndirectBrInst>((*PI)->getTerminator()))
396 continue;
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000397 SplitLatchEdge |= L->getLoopLatch() == *PI;
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000398 BasicBlock *ExitSplit = SplitCriticalEdge(
399 *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000400 ExitSplit->moveBefore(Exit);
401 }
402 assert(SplitLatchEdge &&
403 "Despite splitting all preds, failed to split latch exit?");
Chris Lattner59c82f82011-01-08 19:59:06 +0000404 } else {
405 // We can fold the conditional branch in the preheader, this makes things
406 // simpler. The first step is to remove the extra edge to the Exit block.
407 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelc1f7c1d2011-04-29 20:38:55 +0000408 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
409 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner59c82f82011-01-08 19:59:06 +0000410 PHBI->eraseFromParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000411
Chris Lattner59c82f82011-01-08 19:59:06 +0000412 // With our CFG finalized, update DomTree if it is available.
Chandler Carruth94209092015-01-18 02:08:05 +0000413 if (DT) {
Chris Lattner59c82f82011-01-08 19:59:06 +0000414 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000415 DT->changeImmediateDominator(NewHeader, OrigPreheader);
416 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000417
418 // Brute force incremental dominator tree update. Call
419 // findNearestCommonDominator on all CFG predecessors of each child of the
420 // original header.
Chandler Carruth94209092015-01-18 02:08:05 +0000421 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000422 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
423 OrigHeaderNode->end());
424 bool Changed;
425 do {
426 Changed = false;
427 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
428 DomTreeNode *Node = HeaderChildren[I];
429 BasicBlock *BB = Node->getBlock();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000430
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000431 pred_iterator PI = pred_begin(BB);
432 BasicBlock *NearestDom = *PI;
433 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
Chandler Carruth94209092015-01-18 02:08:05 +0000434 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000435
436 // Remember if this changes the DomTree.
437 if (Node->getIDom()->getBlock() != NearestDom) {
Chandler Carruth94209092015-01-18 02:08:05 +0000438 DT->changeImmediateDominator(BB, NearestDom);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000439 Changed = true;
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000440 }
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000441 }
442
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000443 // If the dominator changed, this may have an effect on other
444 // predecessors, continue until we reach a fixpoint.
445 } while (Changed);
Chris Lattner59c82f82011-01-08 19:59:06 +0000446 }
Devang Patelfac4d1f2007-07-11 23:47:28 +0000447 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000448
Chris Lattner59c82f82011-01-08 19:59:06 +0000449 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner063dca02011-01-08 18:52:51 +0000450 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnerfee37c52011-01-08 18:55:50 +0000451
Chris Lattner63fe78d2011-01-11 07:47:59 +0000452 // Now that the CFG and DomTree are in a consistent state again, try to merge
453 // the OrigHeader block into OrigLatch. This will succeed if they are
454 // connected by an unconditional branch. This is just a cleanup so the
455 // emitted code isn't too gross in this common case.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000456 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
Andrew Tricka20f1982012-02-14 00:00:19 +0000457
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000458 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
459
Chris Lattnerfee37c52011-01-08 18:55:50 +0000460 ++NumRotated;
461 return true;
Devang Patel85419782007-04-09 20:19:46 +0000462}
Justin Bognera7300452015-12-14 23:22:44 +0000463
464/// Determine whether the instructions in this range may be safely and cheaply
465/// speculated. This is not an important enough situation to develop complex
466/// heuristics. We handle a single arithmetic instruction along with any type
467/// conversions.
468static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
469 BasicBlock::iterator End, Loop *L) {
470 bool seenIncrement = false;
471 bool MultiExitLoop = false;
472
473 if (!L->getExitingBlock())
474 MultiExitLoop = true;
475
476 for (BasicBlock::iterator I = Begin; I != End; ++I) {
477
478 if (!isSafeToSpeculativelyExecute(&*I))
479 return false;
480
481 if (isa<DbgInfoIntrinsic>(I))
482 continue;
483
484 switch (I->getOpcode()) {
485 default:
486 return false;
487 case Instruction::GetElementPtr:
488 // GEPs are cheap if all indices are constant.
489 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
490 return false;
491 // fall-thru to increment case
492 case Instruction::Add:
493 case Instruction::Sub:
494 case Instruction::And:
495 case Instruction::Or:
496 case Instruction::Xor:
497 case Instruction::Shl:
498 case Instruction::LShr:
499 case Instruction::AShr: {
500 Value *IVOpnd = !isa<Constant>(I->getOperand(0))
501 ? I->getOperand(0)
502 : !isa<Constant>(I->getOperand(1))
503 ? I->getOperand(1)
504 : nullptr;
505 if (!IVOpnd)
506 return false;
507
508 // If increment operand is used outside of the loop, this speculation
509 // could cause extra live range interference.
510 if (MultiExitLoop) {
511 for (User *UseI : IVOpnd->users()) {
512 auto *UserInst = cast<Instruction>(UseI);
513 if (!L->contains(UserInst))
514 return false;
515 }
516 }
517
518 if (seenIncrement)
519 return false;
520 seenIncrement = true;
521 break;
522 }
523 case Instruction::Trunc:
524 case Instruction::ZExt:
525 case Instruction::SExt:
526 // ignore type conversions
527 break;
528 }
529 }
530 return true;
531}
532
533/// Fold the loop tail into the loop exit by speculating the loop tail
534/// instructions. Typically, this is a single post-increment. In the case of a
535/// simple 2-block loop, hoisting the increment can be much better than
536/// duplicating the entire loop header. In the case of loops with early exits,
537/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
538/// canonical form so downstream passes can handle it.
539///
540/// I don't believe this invalidates SCEV.
541bool LoopRotate::simplifyLoopLatch(Loop *L) {
542 BasicBlock *Latch = L->getLoopLatch();
543 if (!Latch || Latch->hasAddressTaken())
544 return false;
545
546 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
547 if (!Jmp || !Jmp->isUnconditional())
548 return false;
549
550 BasicBlock *LastExit = Latch->getSinglePredecessor();
551 if (!LastExit || !L->isLoopExiting(LastExit))
552 return false;
553
554 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
555 if (!BI)
556 return false;
557
558 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
559 return false;
560
561 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
562 << LastExit->getName() << "\n");
563
564 // Hoist the instructions from Latch into LastExit.
565 LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
566 Latch->begin(), Jmp->getIterator());
567
568 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
569 BasicBlock *Header = Jmp->getSuccessor(0);
570 assert(Header == L->getHeader() && "expected a backward branch");
571
572 // Remove Latch from the CFG so that LastExit becomes the new Latch.
573 BI->setSuccessor(FallThruPath, Header);
574 Latch->replaceSuccessorsPhiUsesWith(LastExit);
575 Jmp->eraseFromParent();
576
577 // Nuke the Latch block.
578 assert(Latch->empty() && "unable to evacuate Latch");
579 LI->removeBlock(Latch);
580 if (DT)
581 DT->eraseNode(Latch);
582 Latch->eraseFromParent();
583 return true;
584}
585
586/// Rotate Loop L as many times as possible. Return true if
587/// the loop is rotated at least once.
588bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
589 if (skipOptnoneFunction(L))
590 return false;
591
592 // Save the loop metadata.
593 MDNode *LoopMD = L->getLoopID();
594
595 Function &F = *L->getHeader()->getParent();
596
597 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
598 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
599 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
600 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
601 DT = DTWP ? &DTWP->getDomTree() : nullptr;
602
603 // Simplify the loop latch before attempting to rotate the header
604 // upward. Rotation may not be needed if the loop tail can be folded into the
605 // loop exit.
606 bool SimplifiedLatch = simplifyLoopLatch(L);
607
608 // One loop can be rotated multiple times.
609 bool MadeChange = false;
610 while (rotateLoop(L, SimplifiedLatch)) {
611 MadeChange = true;
612 SimplifiedLatch = false;
613 }
614
615 // Restore the loop metadata.
616 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
617 if ((MadeChange || SimplifiedLatch) && LoopMD)
618 L->setLoopID(LoopMD);
619
620 return MadeChange;
621}