1b0aa36f9SDavid Green //===----------------- LoopRotationUtils.cpp -----------------------------===//
2b0aa36f9SDavid Green //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6b0aa36f9SDavid Green //
7b0aa36f9SDavid Green //===----------------------------------------------------------------------===//
8b0aa36f9SDavid Green //
9b0aa36f9SDavid Green // This file provides utilities to convert a loop into a loop with bottom test.
10b0aa36f9SDavid Green //
11b0aa36f9SDavid Green //===----------------------------------------------------------------------===//
12b0aa36f9SDavid Green 
13b0aa36f9SDavid Green #include "llvm/Transforms/Utils/LoopRotationUtils.h"
14b0aa36f9SDavid Green #include "llvm/ADT/Statistic.h"
15b0aa36f9SDavid Green #include "llvm/Analysis/AliasAnalysis.h"
16b0aa36f9SDavid Green #include "llvm/Analysis/AssumptionCache.h"
17b0aa36f9SDavid Green #include "llvm/Analysis/BasicAliasAnalysis.h"
18b0aa36f9SDavid Green #include "llvm/Analysis/CodeMetrics.h"
195f436fc5SRichard Trieu #include "llvm/Analysis/DomTreeUpdater.h"
20b0aa36f9SDavid Green #include "llvm/Analysis/GlobalsModRef.h"
21b0aa36f9SDavid Green #include "llvm/Analysis/InstructionSimplify.h"
22b0aa36f9SDavid Green #include "llvm/Analysis/LoopPass.h"
23ad4d0182SAlina Sbirlea #include "llvm/Analysis/MemorySSA.h"
24ad4d0182SAlina Sbirlea #include "llvm/Analysis/MemorySSAUpdater.h"
25b0aa36f9SDavid Green #include "llvm/Analysis/ScalarEvolution.h"
26b0aa36f9SDavid Green #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
27b0aa36f9SDavid Green #include "llvm/Analysis/TargetTransformInfo.h"
28b0aa36f9SDavid Green #include "llvm/Analysis/ValueTracking.h"
29b0aa36f9SDavid Green #include "llvm/IR/CFG.h"
30b0aa36f9SDavid Green #include "llvm/IR/DebugInfoMetadata.h"
31b0aa36f9SDavid Green #include "llvm/IR/Dominators.h"
32b0aa36f9SDavid Green #include "llvm/IR/Function.h"
33b0aa36f9SDavid Green #include "llvm/IR/IntrinsicInst.h"
34b0aa36f9SDavid Green #include "llvm/IR/Module.h"
35b0aa36f9SDavid Green #include "llvm/Support/CommandLine.h"
36b0aa36f9SDavid Green #include "llvm/Support/Debug.h"
37b0aa36f9SDavid Green #include "llvm/Support/raw_ostream.h"
38b0aa36f9SDavid Green #include "llvm/Transforms/Utils/BasicBlockUtils.h"
3921a8b605SChijun Sima #include "llvm/Transforms/Utils/Local.h"
40b0aa36f9SDavid Green #include "llvm/Transforms/Utils/LoopUtils.h"
41b0aa36f9SDavid Green #include "llvm/Transforms/Utils/SSAUpdater.h"
42b0aa36f9SDavid Green #include "llvm/Transforms/Utils/ValueMapper.h"
43b0aa36f9SDavid Green using namespace llvm;
44b0aa36f9SDavid Green 
45b0aa36f9SDavid Green #define DEBUG_TYPE "loop-rotate"
46b0aa36f9SDavid Green 
47b0aa36f9SDavid Green STATISTIC(NumRotated, "Number of loops rotated");
48b0aa36f9SDavid Green 
49*2f6987baSFedor Sergeev static cl::opt<bool>
50*2f6987baSFedor Sergeev     MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden,
51*2f6987baSFedor Sergeev                 cl::desc("Allow loop rotation multiple times in order to reach "
52*2f6987baSFedor Sergeev                          "a better latch exit"));
53*2f6987baSFedor Sergeev 
54b0aa36f9SDavid Green namespace {
55b0aa36f9SDavid Green /// A simple loop rotation transformation.
56b0aa36f9SDavid Green class LoopRotate {
57b0aa36f9SDavid Green   const unsigned MaxHeaderSize;
58b0aa36f9SDavid Green   LoopInfo *LI;
59b0aa36f9SDavid Green   const TargetTransformInfo *TTI;
60b0aa36f9SDavid Green   AssumptionCache *AC;
61b0aa36f9SDavid Green   DominatorTree *DT;
62b0aa36f9SDavid Green   ScalarEvolution *SE;
63ad4d0182SAlina Sbirlea   MemorySSAUpdater *MSSAU;
64b0aa36f9SDavid Green   const SimplifyQuery &SQ;
65585f2699SJin Lin   bool RotationOnly;
66585f2699SJin Lin   bool IsUtilMode;
67b0aa36f9SDavid Green 
68b0aa36f9SDavid Green public:
69b0aa36f9SDavid Green   LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
70b0aa36f9SDavid Green              const TargetTransformInfo *TTI, AssumptionCache *AC,
71ad4d0182SAlina Sbirlea              DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
72ad4d0182SAlina Sbirlea              const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode)
73b0aa36f9SDavid Green       : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
74ad4d0182SAlina Sbirlea         MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
75ad4d0182SAlina Sbirlea         IsUtilMode(IsUtilMode) {}
76b0aa36f9SDavid Green   bool processLoop(Loop *L);
77b0aa36f9SDavid Green 
78b0aa36f9SDavid Green private:
79b0aa36f9SDavid Green   bool rotateLoop(Loop *L, bool SimplifiedLatch);
80b0aa36f9SDavid Green   bool simplifyLoopLatch(Loop *L);
81b0aa36f9SDavid Green };
82b0aa36f9SDavid Green } // end anonymous namespace
83b0aa36f9SDavid Green 
844b698645SAlina Sbirlea /// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
854b698645SAlina Sbirlea /// previously exist in the map, and the value was inserted.
864b698645SAlina Sbirlea static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V) {
874b698645SAlina Sbirlea   bool Inserted = VM.insert({K, V}).second;
884b698645SAlina Sbirlea   assert(Inserted);
894b698645SAlina Sbirlea   (void)Inserted;
904b698645SAlina Sbirlea }
91b0aa36f9SDavid Green /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
92b0aa36f9SDavid Green /// old header into the preheader.  If there were uses of the values produced by
93b0aa36f9SDavid Green /// these instruction that were outside of the loop, we have to insert PHI nodes
94b0aa36f9SDavid Green /// to merge the two values.  Do this now.
95b0aa36f9SDavid Green static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
96b0aa36f9SDavid Green                                             BasicBlock *OrigPreheader,
97b0aa36f9SDavid Green                                             ValueToValueMapTy &ValueMap,
98b0aa36f9SDavid Green                                 SmallVectorImpl<PHINode*> *InsertedPHIs) {
99b0aa36f9SDavid Green   // Remove PHI node entries that are no longer live.
100b0aa36f9SDavid Green   BasicBlock::iterator I, E = OrigHeader->end();
101b0aa36f9SDavid Green   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
102b0aa36f9SDavid Green     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
103b0aa36f9SDavid Green 
104b0aa36f9SDavid Green   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
105b0aa36f9SDavid Green   // as necessary.
106b0aa36f9SDavid Green   SSAUpdater SSA(InsertedPHIs);
107b0aa36f9SDavid Green   for (I = OrigHeader->begin(); I != E; ++I) {
108b0aa36f9SDavid Green     Value *OrigHeaderVal = &*I;
109b0aa36f9SDavid Green 
110b0aa36f9SDavid Green     // If there are no uses of the value (e.g. because it returns void), there
111b0aa36f9SDavid Green     // is nothing to rewrite.
112b0aa36f9SDavid Green     if (OrigHeaderVal->use_empty())
113b0aa36f9SDavid Green       continue;
114b0aa36f9SDavid Green 
115b0aa36f9SDavid Green     Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
116b0aa36f9SDavid Green 
117b0aa36f9SDavid Green     // The value now exits in two versions: the initial value in the preheader
118b0aa36f9SDavid Green     // and the loop "next" value in the original header.
119b0aa36f9SDavid Green     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
120b0aa36f9SDavid Green     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
121b0aa36f9SDavid Green     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
122b0aa36f9SDavid Green 
123b0aa36f9SDavid Green     // Visit each use of the OrigHeader instruction.
124b0aa36f9SDavid Green     for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
125b0aa36f9SDavid Green                              UE = OrigHeaderVal->use_end();
126b0aa36f9SDavid Green          UI != UE;) {
127b0aa36f9SDavid Green       // Grab the use before incrementing the iterator.
128b0aa36f9SDavid Green       Use &U = *UI;
129b0aa36f9SDavid Green 
130b0aa36f9SDavid Green       // Increment the iterator before removing the use from the list.
131b0aa36f9SDavid Green       ++UI;
132b0aa36f9SDavid Green 
133b0aa36f9SDavid Green       // SSAUpdater can't handle a non-PHI use in the same block as an
134b0aa36f9SDavid Green       // earlier def. We can easily handle those cases manually.
135b0aa36f9SDavid Green       Instruction *UserInst = cast<Instruction>(U.getUser());
136b0aa36f9SDavid Green       if (!isa<PHINode>(UserInst)) {
137b0aa36f9SDavid Green         BasicBlock *UserBB = UserInst->getParent();
138b0aa36f9SDavid Green 
139b0aa36f9SDavid Green         // The original users in the OrigHeader are already using the
140b0aa36f9SDavid Green         // original definitions.
141b0aa36f9SDavid Green         if (UserBB == OrigHeader)
142b0aa36f9SDavid Green           continue;
143b0aa36f9SDavid Green 
144b0aa36f9SDavid Green         // Users in the OrigPreHeader need to use the value to which the
145b0aa36f9SDavid Green         // original definitions are mapped.
146b0aa36f9SDavid Green         if (UserBB == OrigPreheader) {
147b0aa36f9SDavid Green           U = OrigPreHeaderVal;
148b0aa36f9SDavid Green           continue;
149b0aa36f9SDavid Green         }
150b0aa36f9SDavid Green       }
151b0aa36f9SDavid Green 
152b0aa36f9SDavid Green       // Anything else can be handled by SSAUpdater.
153b0aa36f9SDavid Green       SSA.RewriteUse(U);
154b0aa36f9SDavid Green     }
155b0aa36f9SDavid Green 
156b0aa36f9SDavid Green     // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
157b0aa36f9SDavid Green     // intrinsics.
158b0aa36f9SDavid Green     SmallVector<DbgValueInst *, 1> DbgValues;
159b0aa36f9SDavid Green     llvm::findDbgValues(DbgValues, OrigHeaderVal);
160b0aa36f9SDavid Green     for (auto &DbgValue : DbgValues) {
161b0aa36f9SDavid Green       // The original users in the OrigHeader are already using the original
162b0aa36f9SDavid Green       // definitions.
163b0aa36f9SDavid Green       BasicBlock *UserBB = DbgValue->getParent();
164b0aa36f9SDavid Green       if (UserBB == OrigHeader)
165b0aa36f9SDavid Green         continue;
166b0aa36f9SDavid Green 
167b0aa36f9SDavid Green       // Users in the OrigPreHeader need to use the value to which the
168b0aa36f9SDavid Green       // original definitions are mapped and anything else can be handled by
169b0aa36f9SDavid Green       // the SSAUpdater. To avoid adding PHINodes, check if the value is
170b0aa36f9SDavid Green       // available in UserBB, if not substitute undef.
171b0aa36f9SDavid Green       Value *NewVal;
172b0aa36f9SDavid Green       if (UserBB == OrigPreheader)
173b0aa36f9SDavid Green         NewVal = OrigPreHeaderVal;
174b0aa36f9SDavid Green       else if (SSA.HasValueForBlock(UserBB))
175b0aa36f9SDavid Green         NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
176b0aa36f9SDavid Green       else
177b0aa36f9SDavid Green         NewVal = UndefValue::get(OrigHeaderVal->getType());
178b0aa36f9SDavid Green       DbgValue->setOperand(0,
179b0aa36f9SDavid Green                            MetadataAsValue::get(OrigHeaderVal->getContext(),
180b0aa36f9SDavid Green                                                 ValueAsMetadata::get(NewVal)));
181b0aa36f9SDavid Green     }
182b0aa36f9SDavid Green   }
183b0aa36f9SDavid Green }
184b0aa36f9SDavid Green 
185*2f6987baSFedor Sergeev // Assuming both header and latch are exiting, look for a phi which is only
186*2f6987baSFedor Sergeev // used outside the loop (via a LCSSA phi) in the exit from the header.
187*2f6987baSFedor Sergeev // This means that rotating the loop can remove the phi.
188*2f6987baSFedor Sergeev static bool profitableToRotateLoopExitingLatch(Loop *L) {
189f80ebc8dSDavid Green   BasicBlock *Header = L->getHeader();
190*2f6987baSFedor Sergeev   BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
191*2f6987baSFedor Sergeev   assert(BI && BI->isConditional() && "need header with conditional exit");
192*2f6987baSFedor Sergeev   BasicBlock *HeaderExit = BI->getSuccessor(0);
193f80ebc8dSDavid Green   if (L->contains(HeaderExit))
194*2f6987baSFedor Sergeev     HeaderExit = BI->getSuccessor(1);
195f80ebc8dSDavid Green 
196f80ebc8dSDavid Green   for (auto &Phi : Header->phis()) {
197f80ebc8dSDavid Green     // Look for uses of this phi in the loop/via exits other than the header.
198f80ebc8dSDavid Green     if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
199f80ebc8dSDavid Green           return cast<Instruction>(U)->getParent() != HeaderExit;
200f80ebc8dSDavid Green         }))
201f80ebc8dSDavid Green       continue;
202f80ebc8dSDavid Green     return true;
203f80ebc8dSDavid Green   }
204*2f6987baSFedor Sergeev   return false;
205*2f6987baSFedor Sergeev }
206f80ebc8dSDavid Green 
207*2f6987baSFedor Sergeev // Check that latch exit is deoptimizing (which means - very unlikely to happen)
208*2f6987baSFedor Sergeev // and there is another exit from the loop which is non-deoptimizing.
209*2f6987baSFedor Sergeev // If we rotate latch to that exit our loop has a better chance of being fully
210*2f6987baSFedor Sergeev // canonical.
211*2f6987baSFedor Sergeev //
212*2f6987baSFedor Sergeev // It can give false positives in some rare cases.
213*2f6987baSFedor Sergeev static bool canRotateDeoptimizingLatchExit(Loop *L) {
214*2f6987baSFedor Sergeev   BasicBlock *Latch = L->getLoopLatch();
215*2f6987baSFedor Sergeev   assert(Latch && "need latch");
216*2f6987baSFedor Sergeev   BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
217*2f6987baSFedor Sergeev   // Need normal exiting latch.
218*2f6987baSFedor Sergeev   if (!BI || !BI->isConditional())
219*2f6987baSFedor Sergeev     return false;
220*2f6987baSFedor Sergeev 
221*2f6987baSFedor Sergeev   BasicBlock *Exit = BI->getSuccessor(1);
222*2f6987baSFedor Sergeev   if (L->contains(Exit))
223*2f6987baSFedor Sergeev     Exit = BI->getSuccessor(0);
224*2f6987baSFedor Sergeev 
225*2f6987baSFedor Sergeev   // Latch exit is non-deoptimizing, no need to rotate.
226*2f6987baSFedor Sergeev   if (!Exit->getPostdominatingDeoptimizeCall())
227*2f6987baSFedor Sergeev     return false;
228*2f6987baSFedor Sergeev 
229*2f6987baSFedor Sergeev   SmallVector<BasicBlock *, 4> Exits;
230*2f6987baSFedor Sergeev   L->getUniqueExitBlocks(Exits);
231*2f6987baSFedor Sergeev   if (!Exits.empty()) {
232*2f6987baSFedor Sergeev     // There is at least one non-deoptimizing exit.
233*2f6987baSFedor Sergeev     //
234*2f6987baSFedor Sergeev     // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact,
235*2f6987baSFedor Sergeev     // as it can conservatively return false for deoptimizing exits with
236*2f6987baSFedor Sergeev     // complex enough control flow down to deoptimize call.
237*2f6987baSFedor Sergeev     //
238*2f6987baSFedor Sergeev     // That means here we can report success for a case where
239*2f6987baSFedor Sergeev     // all exits are deoptimizing but one of them has complex enough
240*2f6987baSFedor Sergeev     // control flow (e.g. with loops).
241*2f6987baSFedor Sergeev     //
242*2f6987baSFedor Sergeev     // That should be a very rare case and false positives for this function
243*2f6987baSFedor Sergeev     // have compile-time effect only.
244*2f6987baSFedor Sergeev     return any_of(Exits, [](const BasicBlock *BB) {
245*2f6987baSFedor Sergeev       return !BB->getPostdominatingDeoptimizeCall();
246*2f6987baSFedor Sergeev     });
247*2f6987baSFedor Sergeev   }
248f80ebc8dSDavid Green   return false;
249f80ebc8dSDavid Green }
250f80ebc8dSDavid Green 
251b0aa36f9SDavid Green /// Rotate loop LP. Return true if the loop is rotated.
252b0aa36f9SDavid Green ///
253b0aa36f9SDavid Green /// \param SimplifiedLatch is true if the latch was just folded into the final
254b0aa36f9SDavid Green /// loop exit. In this case we may want to rotate even though the new latch is
255b0aa36f9SDavid Green /// now an exiting branch. This rotation would have happened had the latch not
256b0aa36f9SDavid Green /// been simplified. However, if SimplifiedLatch is false, then we avoid
257b0aa36f9SDavid Green /// rotating loops in which the latch exits to avoid excessive or endless
258b0aa36f9SDavid Green /// rotation. LoopRotate should be repeatable and converge to a canonical
259b0aa36f9SDavid Green /// form. This property is satisfied because simplifying the loop latch can only
260b0aa36f9SDavid Green /// happen once across multiple invocations of the LoopRotate pass.
261*2f6987baSFedor Sergeev ///
262*2f6987baSFedor Sergeev /// If -loop-rotate-multi is enabled we can do multiple rotations in one go
263*2f6987baSFedor Sergeev /// so to reach a suitable (non-deoptimizing) exit.
264b0aa36f9SDavid Green bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
265b0aa36f9SDavid Green   // If the loop has only one block then there is not much to rotate.
266b0aa36f9SDavid Green   if (L->getBlocks().size() == 1)
267b0aa36f9SDavid Green     return false;
268b0aa36f9SDavid Green 
269*2f6987baSFedor Sergeev   bool Rotated = false;
270*2f6987baSFedor Sergeev   do {
271b0aa36f9SDavid Green     BasicBlock *OrigHeader = L->getHeader();
272b0aa36f9SDavid Green     BasicBlock *OrigLatch = L->getLoopLatch();
273b0aa36f9SDavid Green 
274b0aa36f9SDavid Green     BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
275b0aa36f9SDavid Green     if (!BI || BI->isUnconditional())
276*2f6987baSFedor Sergeev       return Rotated;
277b0aa36f9SDavid Green 
278b0aa36f9SDavid Green     // If the loop header is not one of the loop exiting blocks then
279b0aa36f9SDavid Green     // either this loop is already rotated or it is not
280b0aa36f9SDavid Green     // suitable for loop rotation transformations.
281b0aa36f9SDavid Green     if (!L->isLoopExiting(OrigHeader))
282*2f6987baSFedor Sergeev       return Rotated;
283b0aa36f9SDavid Green 
284b0aa36f9SDavid Green     // If the loop latch already contains a branch that leaves the loop then the
285b0aa36f9SDavid Green     // loop is already rotated.
286b0aa36f9SDavid Green     if (!OrigLatch)
287*2f6987baSFedor Sergeev       return Rotated;
288b0aa36f9SDavid Green 
289b0aa36f9SDavid Green     // Rotate if either the loop latch does *not* exit the loop, or if the loop
290f80ebc8dSDavid Green     // latch was just simplified. Or if we think it will be profitable.
291585f2699SJin Lin     if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
292*2f6987baSFedor Sergeev         !profitableToRotateLoopExitingLatch(L) &&
293*2f6987baSFedor Sergeev         !canRotateDeoptimizingLatchExit(L))
294*2f6987baSFedor Sergeev       return Rotated;
295b0aa36f9SDavid Green 
296b0aa36f9SDavid Green     // Check size of original header and reject loop if it is very big or we can't
297b0aa36f9SDavid Green     // duplicate blocks inside it.
298b0aa36f9SDavid Green     {
299b0aa36f9SDavid Green       SmallPtrSet<const Value *, 32> EphValues;
300b0aa36f9SDavid Green       CodeMetrics::collectEphemeralValues(L, AC, EphValues);
301b0aa36f9SDavid Green 
302b0aa36f9SDavid Green       CodeMetrics Metrics;
303b0aa36f9SDavid Green       Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
304b0aa36f9SDavid Green       if (Metrics.notDuplicatable) {
305d34e60caSNicola Zaghen         LLVM_DEBUG(
306d34e60caSNicola Zaghen                    dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
307b0aa36f9SDavid Green                    << " instructions: ";
308b0aa36f9SDavid Green                    L->dump());
309*2f6987baSFedor Sergeev         return Rotated;
310b0aa36f9SDavid Green       }
311b0aa36f9SDavid Green       if (Metrics.convergent) {
312d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
313b0aa36f9SDavid Green                    "instructions: ";
314b0aa36f9SDavid Green                    L->dump());
315*2f6987baSFedor Sergeev         return Rotated;
316b0aa36f9SDavid Green       }
317b0aa36f9SDavid Green       if (Metrics.NumInsts > MaxHeaderSize)
318*2f6987baSFedor Sergeev         return Rotated;
319b0aa36f9SDavid Green     }
320b0aa36f9SDavid Green 
321b0aa36f9SDavid Green     // Now, this loop is suitable for rotation.
322b0aa36f9SDavid Green     BasicBlock *OrigPreheader = L->getLoopPreheader();
323b0aa36f9SDavid Green 
324b0aa36f9SDavid Green     // If the loop could not be converted to canonical form, it must have an
325b0aa36f9SDavid Green     // indirectbr in it, just give up.
326b0aa36f9SDavid Green     if (!OrigPreheader || !L->hasDedicatedExits())
327*2f6987baSFedor Sergeev       return Rotated;
328b0aa36f9SDavid Green 
329b0aa36f9SDavid Green     // Anything ScalarEvolution may know about this loop or the PHI nodes
3305a0a40b8SMax Kazantsev     // in its header will soon be invalidated. We should also invalidate
3315a0a40b8SMax Kazantsev     // all outer loops because insertion and deletion of blocks that happens
3325a0a40b8SMax Kazantsev     // during the rotation may violate invariants related to backedge taken
3335a0a40b8SMax Kazantsev     // infos in them.
334b0aa36f9SDavid Green     if (SE)
33591f48166SMax Kazantsev       SE->forgetTopmostLoop(L);
336b0aa36f9SDavid Green 
337d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
338ad4d0182SAlina Sbirlea     if (MSSAU && VerifyMemorySSA)
339ad4d0182SAlina Sbirlea       MSSAU->getMemorySSA()->verifyMemorySSA();
340b0aa36f9SDavid Green 
341b0aa36f9SDavid Green     // Find new Loop header. NewHeader is a Header's one and only successor
342b0aa36f9SDavid Green     // that is inside loop.  Header's other successor is outside the
343b0aa36f9SDavid Green     // loop.  Otherwise loop is not suitable for rotation.
344b0aa36f9SDavid Green     BasicBlock *Exit = BI->getSuccessor(0);
345b0aa36f9SDavid Green     BasicBlock *NewHeader = BI->getSuccessor(1);
346b0aa36f9SDavid Green     if (L->contains(Exit))
347b0aa36f9SDavid Green       std::swap(Exit, NewHeader);
348b0aa36f9SDavid Green     assert(NewHeader && "Unable to determine new loop header");
349b0aa36f9SDavid Green     assert(L->contains(NewHeader) && !L->contains(Exit) &&
350b0aa36f9SDavid Green            "Unable to determine loop header and exit blocks");
351b0aa36f9SDavid Green 
352b0aa36f9SDavid Green     // This code assumes that the new header has exactly one predecessor.
353b0aa36f9SDavid Green     // Remove any single-entry PHI nodes in it.
354b0aa36f9SDavid Green     assert(NewHeader->getSinglePredecessor() &&
355b0aa36f9SDavid Green            "New header doesn't have one pred!");
356b0aa36f9SDavid Green     FoldSingleEntryPHINodes(NewHeader);
357b0aa36f9SDavid Green 
358b0aa36f9SDavid Green     // Begin by walking OrigHeader and populating ValueMap with an entry for
359b0aa36f9SDavid Green     // each Instruction.
360b0aa36f9SDavid Green     BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
36158a37754SAlina Sbirlea     ValueToValueMapTy ValueMap, ValueMapMSSA;
362b0aa36f9SDavid Green 
363b0aa36f9SDavid Green     // For PHI nodes, the value available in OldPreHeader is just the
364b0aa36f9SDavid Green     // incoming value from OldPreHeader.
365b0aa36f9SDavid Green     for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
3664b698645SAlina Sbirlea       InsertNewValueIntoMap(ValueMap, PN,
3674b698645SAlina Sbirlea                             PN->getIncomingValueForBlock(OrigPreheader));
368b0aa36f9SDavid Green 
369b0aa36f9SDavid Green     // For the rest of the instructions, either hoist to the OrigPreheader if
370b0aa36f9SDavid Green     // possible or create a clone in the OldPreHeader if not.
371edb12a83SChandler Carruth     Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
372b0aa36f9SDavid Green 
373b0aa36f9SDavid Green     // Record all debug intrinsics preceding LoopEntryBranch to avoid duplication.
374b0aa36f9SDavid Green     using DbgIntrinsicHash =
375b0aa36f9SDavid Green       std::pair<std::pair<Value *, DILocalVariable *>, DIExpression *>;
376ef72e481SHsiangkai Wang     auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash {
377b0aa36f9SDavid Green       return {{D->getVariableLocation(), D->getVariable()}, D->getExpression()};
378b0aa36f9SDavid Green     };
379b0aa36f9SDavid Green     SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
380b0aa36f9SDavid Green     for (auto I = std::next(OrigPreheader->rbegin()), E = OrigPreheader->rend();
381b0aa36f9SDavid Green          I != E; ++I) {
382ef72e481SHsiangkai Wang       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&*I))
383b0aa36f9SDavid Green         DbgIntrinsics.insert(makeHash(DII));
384b0aa36f9SDavid Green       else
385b0aa36f9SDavid Green         break;
386b0aa36f9SDavid Green     }
387b0aa36f9SDavid Green 
388b0aa36f9SDavid Green     while (I != E) {
389b0aa36f9SDavid Green       Instruction *Inst = &*I++;
390b0aa36f9SDavid Green 
391b0aa36f9SDavid Green       // If the instruction's operands are invariant and it doesn't read or write
392b0aa36f9SDavid Green       // memory, then it is safe to hoist.  Doing this doesn't change the order of
393b0aa36f9SDavid Green       // execution in the preheader, but does prevent the instruction from
394b0aa36f9SDavid Green       // executing in each iteration of the loop.  This means it is safe to hoist
395b0aa36f9SDavid Green       // something that might trap, but isn't safe to hoist something that reads
396b0aa36f9SDavid Green       // memory (without proving that the loop doesn't write).
397b0aa36f9SDavid Green       if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
3989ae926b9SChandler Carruth           !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
399b0aa36f9SDavid Green           !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
400b0aa36f9SDavid Green         Inst->moveBefore(LoopEntryBranch);
401b0aa36f9SDavid Green         continue;
402b0aa36f9SDavid Green       }
403b0aa36f9SDavid Green 
404b0aa36f9SDavid Green       // Otherwise, create a duplicate of the instruction.
405b0aa36f9SDavid Green       Instruction *C = Inst->clone();
406b0aa36f9SDavid Green 
407b0aa36f9SDavid Green       // Eagerly remap the operands of the instruction.
408b0aa36f9SDavid Green       RemapInstruction(C, ValueMap,
409b0aa36f9SDavid Green                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
410b0aa36f9SDavid Green 
411b0aa36f9SDavid Green       // Avoid inserting the same intrinsic twice.
412ef72e481SHsiangkai Wang       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
413b0aa36f9SDavid Green         if (DbgIntrinsics.count(makeHash(DII))) {
414b0aa36f9SDavid Green           C->deleteValue();
415b0aa36f9SDavid Green           continue;
416b0aa36f9SDavid Green         }
417b0aa36f9SDavid Green 
418b0aa36f9SDavid Green       // With the operands remapped, see if the instruction constant folds or is
419b0aa36f9SDavid Green       // otherwise simplifyable.  This commonly occurs because the entry from PHI
420b0aa36f9SDavid Green       // nodes allows icmps and other instructions to fold.
421b0aa36f9SDavid Green       Value *V = SimplifyInstruction(C, SQ);
422b0aa36f9SDavid Green       if (V && LI->replacementPreservesLCSSAForm(C, V)) {
423b0aa36f9SDavid Green         // If so, then delete the temporary instruction and stick the folded value
424b0aa36f9SDavid Green         // in the map.
4254b698645SAlina Sbirlea         InsertNewValueIntoMap(ValueMap, Inst, V);
426b0aa36f9SDavid Green         if (!C->mayHaveSideEffects()) {
427b0aa36f9SDavid Green           C->deleteValue();
428b0aa36f9SDavid Green           C = nullptr;
429b0aa36f9SDavid Green         }
430b0aa36f9SDavid Green       } else {
4314b698645SAlina Sbirlea         InsertNewValueIntoMap(ValueMap, Inst, C);
432b0aa36f9SDavid Green       }
433b0aa36f9SDavid Green       if (C) {
434b0aa36f9SDavid Green         // Otherwise, stick the new instruction into the new block!
435b0aa36f9SDavid Green         C->setName(Inst->getName());
436b0aa36f9SDavid Green         C->insertBefore(LoopEntryBranch);
437b0aa36f9SDavid Green 
438b0aa36f9SDavid Green         if (auto *II = dyn_cast<IntrinsicInst>(C))
439b0aa36f9SDavid Green           if (II->getIntrinsicID() == Intrinsic::assume)
440b0aa36f9SDavid Green             AC->registerAssumption(II);
44158a37754SAlina Sbirlea         // MemorySSA cares whether the cloned instruction was inserted or not, and
44258a37754SAlina Sbirlea         // not whether it can be remapped to a simplified value.
4434b698645SAlina Sbirlea         if (MSSAU)
4444b698645SAlina Sbirlea           InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
445b0aa36f9SDavid Green       }
446b0aa36f9SDavid Green     }
447b0aa36f9SDavid Green 
448b0aa36f9SDavid Green     // Along with all the other instructions, we just cloned OrigHeader's
449b0aa36f9SDavid Green     // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
450b0aa36f9SDavid Green     // successors by duplicating their incoming values for OrigHeader.
45196fc1de7SChandler Carruth     for (BasicBlock *SuccBB : successors(OrigHeader))
452b0aa36f9SDavid Green       for (BasicBlock::iterator BI = SuccBB->begin();
453b0aa36f9SDavid Green            PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
454b0aa36f9SDavid Green         PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
455b0aa36f9SDavid Green 
456b0aa36f9SDavid Green     // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
457b0aa36f9SDavid Green     // OrigPreHeader's old terminator (the original branch into the loop), and
458b0aa36f9SDavid Green     // remove the corresponding incoming values from the PHI nodes in OrigHeader.
459b0aa36f9SDavid Green     LoopEntryBranch->eraseFromParent();
460b0aa36f9SDavid Green 
461ad4d0182SAlina Sbirlea     // Update MemorySSA before the rewrite call below changes the 1:1
46258a37754SAlina Sbirlea     // instruction:cloned_instruction_or_value mapping.
463ad4d0182SAlina Sbirlea     if (MSSAU) {
4644b698645SAlina Sbirlea       InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
46558a37754SAlina Sbirlea       MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
46658a37754SAlina Sbirlea                                           ValueMapMSSA);
467ad4d0182SAlina Sbirlea     }
468b0aa36f9SDavid Green 
469b0aa36f9SDavid Green     SmallVector<PHINode*, 2> InsertedPHIs;
470b0aa36f9SDavid Green     // If there were any uses of instructions in the duplicated block outside the
471b0aa36f9SDavid Green     // loop, update them, inserting PHI nodes as required
472b0aa36f9SDavid Green     RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
473b0aa36f9SDavid Green                                     &InsertedPHIs);
474b0aa36f9SDavid Green 
475b0aa36f9SDavid Green     // Attach dbg.value intrinsics to the new phis if that phi uses a value that
476b0aa36f9SDavid Green     // previously had debug metadata attached. This keeps the debug info
477b0aa36f9SDavid Green     // up-to-date in the loop body.
478b0aa36f9SDavid Green     if (!InsertedPHIs.empty())
479b0aa36f9SDavid Green       insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
480b0aa36f9SDavid Green 
481b0aa36f9SDavid Green     // NewHeader is now the header of the loop.
482b0aa36f9SDavid Green     L->moveToHeader(NewHeader);
483b0aa36f9SDavid Green     assert(L->getHeader() == NewHeader && "Latch block is our new header");
484b0aa36f9SDavid Green 
485b0aa36f9SDavid Green     // Inform DT about changes to the CFG.
486b0aa36f9SDavid Green     if (DT) {
487b0aa36f9SDavid Green       // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
488b0aa36f9SDavid Green       // the DT about the removed edge to the OrigHeader (that got removed).
489b0aa36f9SDavid Green       SmallVector<DominatorTree::UpdateType, 3> Updates;
490b0aa36f9SDavid Green       Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
491b0aa36f9SDavid Green       Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
492b0aa36f9SDavid Green       Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
493b0aa36f9SDavid Green       DT->applyUpdates(Updates);
494ad4d0182SAlina Sbirlea 
495ad4d0182SAlina Sbirlea       if (MSSAU) {
496ad4d0182SAlina Sbirlea         MSSAU->applyUpdates(Updates, *DT);
497ad4d0182SAlina Sbirlea         if (VerifyMemorySSA)
498ad4d0182SAlina Sbirlea           MSSAU->getMemorySSA()->verifyMemorySSA();
499ad4d0182SAlina Sbirlea       }
500b0aa36f9SDavid Green     }
501b0aa36f9SDavid Green 
502b0aa36f9SDavid Green     // At this point, we've finished our major CFG changes.  As part of cloning
503b0aa36f9SDavid Green     // the loop into the preheader we've simplified instructions and the
504b0aa36f9SDavid Green     // duplicated conditional branch may now be branching on a constant.  If it is
505b0aa36f9SDavid Green     // branching on a constant and if that constant means that we enter the loop,
506b0aa36f9SDavid Green     // then we fold away the cond branch to an uncond branch.  This simplifies the
507b0aa36f9SDavid Green     // loop in cases important for nested loops, and it also means we don't have
508b0aa36f9SDavid Green     // to split as many edges.
509b0aa36f9SDavid Green     BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
510b0aa36f9SDavid Green     assert(PHBI->isConditional() && "Should be clone of BI condbr!");
511b0aa36f9SDavid Green     if (!isa<ConstantInt>(PHBI->getCondition()) ||
512b0aa36f9SDavid Green         PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
513b0aa36f9SDavid Green         NewHeader) {
514b0aa36f9SDavid Green       // The conditional branch can't be folded, handle the general case.
515b0aa36f9SDavid Green       // Split edges as necessary to preserve LoopSimplify form.
516b0aa36f9SDavid Green 
517b0aa36f9SDavid Green       // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
518b0aa36f9SDavid Green       // thus is not a preheader anymore.
519b0aa36f9SDavid Green       // Split the edge to form a real preheader.
520b0aa36f9SDavid Green       BasicBlock *NewPH = SplitCriticalEdge(
521b0aa36f9SDavid Green                                             OrigPreheader, NewHeader,
522ad4d0182SAlina Sbirlea                                             CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
523b0aa36f9SDavid Green       NewPH->setName(NewHeader->getName() + ".lr.ph");
524b0aa36f9SDavid Green 
525b0aa36f9SDavid Green       // Preserve canonical loop form, which means that 'Exit' should have only
526b0aa36f9SDavid Green       // one predecessor. Note that Exit could be an exit block for multiple
527b0aa36f9SDavid Green       // nested loops, causing both of the edges to now be critical and need to
528b0aa36f9SDavid Green       // be split.
529b0aa36f9SDavid Green       SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
530b0aa36f9SDavid Green       bool SplitLatchEdge = false;
531b0aa36f9SDavid Green       for (BasicBlock *ExitPred : ExitPreds) {
532b0aa36f9SDavid Green         // We only need to split loop exit edges.
533b0aa36f9SDavid Green         Loop *PredLoop = LI->getLoopFor(ExitPred);
534212c8ac2SNick Desaulniers         if (!PredLoop || PredLoop->contains(Exit) ||
535212c8ac2SNick Desaulniers             ExitPred->getTerminator()->isIndirectTerminator())
536b0aa36f9SDavid Green           continue;
537b0aa36f9SDavid Green         SplitLatchEdge |= L->getLoopLatch() == ExitPred;
538b0aa36f9SDavid Green         BasicBlock *ExitSplit = SplitCriticalEdge(
539b0aa36f9SDavid Green                                                   ExitPred, Exit,
540ad4d0182SAlina Sbirlea                                                   CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
541b0aa36f9SDavid Green         ExitSplit->moveBefore(Exit);
542b0aa36f9SDavid Green       }
543b0aa36f9SDavid Green       assert(SplitLatchEdge &&
544b0aa36f9SDavid Green              "Despite splitting all preds, failed to split latch exit?");
545b0aa36f9SDavid Green     } else {
546b0aa36f9SDavid Green       // We can fold the conditional branch in the preheader, this makes things
547b0aa36f9SDavid Green       // simpler. The first step is to remove the extra edge to the Exit block.
548b0aa36f9SDavid Green       Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
549b0aa36f9SDavid Green       BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
550b0aa36f9SDavid Green       NewBI->setDebugLoc(PHBI->getDebugLoc());
551b0aa36f9SDavid Green       PHBI->eraseFromParent();
552b0aa36f9SDavid Green 
553b0aa36f9SDavid Green       // With our CFG finalized, update DomTree if it is available.
554b0aa36f9SDavid Green       if (DT) DT->deleteEdge(OrigPreheader, Exit);
555ad4d0182SAlina Sbirlea 
556ad4d0182SAlina Sbirlea       // Update MSSA too, if available.
557ad4d0182SAlina Sbirlea       if (MSSAU)
558ad4d0182SAlina Sbirlea         MSSAU->removeEdge(OrigPreheader, Exit);
559b0aa36f9SDavid Green     }
560b0aa36f9SDavid Green 
561b0aa36f9SDavid Green     assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
562b0aa36f9SDavid Green     assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
563b0aa36f9SDavid Green 
564ad4d0182SAlina Sbirlea     if (MSSAU && VerifyMemorySSA)
565ad4d0182SAlina Sbirlea       MSSAU->getMemorySSA()->verifyMemorySSA();
566ad4d0182SAlina Sbirlea 
567b0aa36f9SDavid Green     // Now that the CFG and DomTree are in a consistent state again, try to merge
568b0aa36f9SDavid Green     // the OrigHeader block into OrigLatch.  This will succeed if they are
569b0aa36f9SDavid Green     // connected by an unconditional branch.  This is just a cleanup so the
570b0aa36f9SDavid Green     // emitted code isn't too gross in this common case.
57121a8b605SChijun Sima     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
572ad4d0182SAlina Sbirlea     MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
573ad4d0182SAlina Sbirlea 
574ad4d0182SAlina Sbirlea     if (MSSAU && VerifyMemorySSA)
575ad4d0182SAlina Sbirlea       MSSAU->getMemorySSA()->verifyMemorySSA();
576b0aa36f9SDavid Green 
577d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
578b0aa36f9SDavid Green 
579b0aa36f9SDavid Green     ++NumRotated;
580*2f6987baSFedor Sergeev 
581*2f6987baSFedor Sergeev     Rotated = true;
582*2f6987baSFedor Sergeev     SimplifiedLatch = false;
583*2f6987baSFedor Sergeev 
584*2f6987baSFedor Sergeev     // Check that new latch is a deoptimizing exit and then repeat rotation if possible.
585*2f6987baSFedor Sergeev     // Deoptimizing latch exit is not a generally typical case, so we just loop over.
586*2f6987baSFedor Sergeev     // TODO: if it becomes a performance bottleneck extend rotation algorithm
587*2f6987baSFedor Sergeev     // to handle multiple rotations in one go.
588*2f6987baSFedor Sergeev   } while (MultiRotate && canRotateDeoptimizingLatchExit(L));
589*2f6987baSFedor Sergeev 
590*2f6987baSFedor Sergeev 
591b0aa36f9SDavid Green   return true;
592b0aa36f9SDavid Green }
593b0aa36f9SDavid Green 
594b0aa36f9SDavid Green /// Determine whether the instructions in this range may be safely and cheaply
595b0aa36f9SDavid Green /// speculated. This is not an important enough situation to develop complex
596b0aa36f9SDavid Green /// heuristics. We handle a single arithmetic instruction along with any type
597b0aa36f9SDavid Green /// conversions.
598b0aa36f9SDavid Green static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
599b0aa36f9SDavid Green                                   BasicBlock::iterator End, Loop *L) {
600b0aa36f9SDavid Green   bool seenIncrement = false;
601b0aa36f9SDavid Green   bool MultiExitLoop = false;
602b0aa36f9SDavid Green 
603b0aa36f9SDavid Green   if (!L->getExitingBlock())
604b0aa36f9SDavid Green     MultiExitLoop = true;
605b0aa36f9SDavid Green 
606b0aa36f9SDavid Green   for (BasicBlock::iterator I = Begin; I != End; ++I) {
607b0aa36f9SDavid Green 
608b0aa36f9SDavid Green     if (!isSafeToSpeculativelyExecute(&*I))
609b0aa36f9SDavid Green       return false;
610b0aa36f9SDavid Green 
611b0aa36f9SDavid Green     if (isa<DbgInfoIntrinsic>(I))
612b0aa36f9SDavid Green       continue;
613b0aa36f9SDavid Green 
614b0aa36f9SDavid Green     switch (I->getOpcode()) {
615b0aa36f9SDavid Green     default:
616b0aa36f9SDavid Green       return false;
617b0aa36f9SDavid Green     case Instruction::GetElementPtr:
618b0aa36f9SDavid Green       // GEPs are cheap if all indices are constant.
619b0aa36f9SDavid Green       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
620b0aa36f9SDavid Green         return false;
621b0aa36f9SDavid Green       // fall-thru to increment case
622b0aa36f9SDavid Green       LLVM_FALLTHROUGH;
623b0aa36f9SDavid Green     case Instruction::Add:
624b0aa36f9SDavid Green     case Instruction::Sub:
625b0aa36f9SDavid Green     case Instruction::And:
626b0aa36f9SDavid Green     case Instruction::Or:
627b0aa36f9SDavid Green     case Instruction::Xor:
628b0aa36f9SDavid Green     case Instruction::Shl:
629b0aa36f9SDavid Green     case Instruction::LShr:
630b0aa36f9SDavid Green     case Instruction::AShr: {
631b0aa36f9SDavid Green       Value *IVOpnd =
632b0aa36f9SDavid Green           !isa<Constant>(I->getOperand(0))
633b0aa36f9SDavid Green               ? I->getOperand(0)
634b0aa36f9SDavid Green               : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
635b0aa36f9SDavid Green       if (!IVOpnd)
636b0aa36f9SDavid Green         return false;
637b0aa36f9SDavid Green 
638b0aa36f9SDavid Green       // If increment operand is used outside of the loop, this speculation
639b0aa36f9SDavid Green       // could cause extra live range interference.
640b0aa36f9SDavid Green       if (MultiExitLoop) {
641b0aa36f9SDavid Green         for (User *UseI : IVOpnd->users()) {
642b0aa36f9SDavid Green           auto *UserInst = cast<Instruction>(UseI);
643b0aa36f9SDavid Green           if (!L->contains(UserInst))
644b0aa36f9SDavid Green             return false;
645b0aa36f9SDavid Green         }
646b0aa36f9SDavid Green       }
647b0aa36f9SDavid Green 
648b0aa36f9SDavid Green       if (seenIncrement)
649b0aa36f9SDavid Green         return false;
650b0aa36f9SDavid Green       seenIncrement = true;
651b0aa36f9SDavid Green       break;
652b0aa36f9SDavid Green     }
653b0aa36f9SDavid Green     case Instruction::Trunc:
654b0aa36f9SDavid Green     case Instruction::ZExt:
655b0aa36f9SDavid Green     case Instruction::SExt:
656b0aa36f9SDavid Green       // ignore type conversions
657b0aa36f9SDavid Green       break;
658b0aa36f9SDavid Green     }
659b0aa36f9SDavid Green   }
660b0aa36f9SDavid Green   return true;
661b0aa36f9SDavid Green }
662b0aa36f9SDavid Green 
663b0aa36f9SDavid Green /// Fold the loop tail into the loop exit by speculating the loop tail
664b0aa36f9SDavid Green /// instructions. Typically, this is a single post-increment. In the case of a
665b0aa36f9SDavid Green /// simple 2-block loop, hoisting the increment can be much better than
666b0aa36f9SDavid Green /// duplicating the entire loop header. In the case of loops with early exits,
667b0aa36f9SDavid Green /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
668b0aa36f9SDavid Green /// canonical form so downstream passes can handle it.
669b0aa36f9SDavid Green ///
670b0aa36f9SDavid Green /// I don't believe this invalidates SCEV.
671b0aa36f9SDavid Green bool LoopRotate::simplifyLoopLatch(Loop *L) {
672b0aa36f9SDavid Green   BasicBlock *Latch = L->getLoopLatch();
673b0aa36f9SDavid Green   if (!Latch || Latch->hasAddressTaken())
674b0aa36f9SDavid Green     return false;
675b0aa36f9SDavid Green 
676b0aa36f9SDavid Green   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
677b0aa36f9SDavid Green   if (!Jmp || !Jmp->isUnconditional())
678b0aa36f9SDavid Green     return false;
679b0aa36f9SDavid Green 
680b0aa36f9SDavid Green   BasicBlock *LastExit = Latch->getSinglePredecessor();
681b0aa36f9SDavid Green   if (!LastExit || !L->isLoopExiting(LastExit))
682b0aa36f9SDavid Green     return false;
683b0aa36f9SDavid Green 
684b0aa36f9SDavid Green   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
685b0aa36f9SDavid Green   if (!BI)
686b0aa36f9SDavid Green     return false;
687b0aa36f9SDavid Green 
688b0aa36f9SDavid Green   if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
689b0aa36f9SDavid Green     return false;
690b0aa36f9SDavid Green 
691d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
692b0aa36f9SDavid Green                     << LastExit->getName() << "\n");
693b0aa36f9SDavid Green 
6944eb1a573SAlina Sbirlea   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
6954eb1a573SAlina Sbirlea   MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
6964eb1a573SAlina Sbirlea                             /*PredecessorWithTwoSuccessors=*/true);
697ad4d0182SAlina Sbirlea 
698ad4d0182SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
699ad4d0182SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
700ad4d0182SAlina Sbirlea 
701b0aa36f9SDavid Green   return true;
702b0aa36f9SDavid Green }
703b0aa36f9SDavid Green 
704b0aa36f9SDavid Green /// Rotate \c L, and return true if any modification was made.
705b0aa36f9SDavid Green bool LoopRotate::processLoop(Loop *L) {
706b0aa36f9SDavid Green   // Save the loop metadata.
707b0aa36f9SDavid Green   MDNode *LoopMD = L->getLoopID();
708b0aa36f9SDavid Green 
709585f2699SJin Lin   bool SimplifiedLatch = false;
710585f2699SJin Lin 
711b0aa36f9SDavid Green   // Simplify the loop latch before attempting to rotate the header
712b0aa36f9SDavid Green   // upward. Rotation may not be needed if the loop tail can be folded into the
713b0aa36f9SDavid Green   // loop exit.
714585f2699SJin Lin   if (!RotationOnly)
715585f2699SJin Lin     SimplifiedLatch = simplifyLoopLatch(L);
716b0aa36f9SDavid Green 
717b0aa36f9SDavid Green   bool MadeChange = rotateLoop(L, SimplifiedLatch);
718b0aa36f9SDavid Green   assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
719b0aa36f9SDavid Green          "Loop latch should be exiting after loop-rotate.");
720b0aa36f9SDavid Green 
721b0aa36f9SDavid Green   // Restore the loop metadata.
722b0aa36f9SDavid Green   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
723b0aa36f9SDavid Green   if ((MadeChange || SimplifiedLatch) && LoopMD)
724b0aa36f9SDavid Green     L->setLoopID(LoopMD);
725b0aa36f9SDavid Green 
726b0aa36f9SDavid Green   return MadeChange || SimplifiedLatch;
727b0aa36f9SDavid Green }
728b0aa36f9SDavid Green 
729b0aa36f9SDavid Green 
730b0aa36f9SDavid Green /// The utility to convert a loop into a loop with bottom test.
731585f2699SJin Lin bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
732585f2699SJin Lin                         AssumptionCache *AC, DominatorTree *DT,
733ad4d0182SAlina Sbirlea                         ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
734ad4d0182SAlina Sbirlea                         const SimplifyQuery &SQ, bool RotationOnly = true,
735585f2699SJin Lin                         unsigned Threshold = unsigned(-1),
736585f2699SJin Lin                         bool IsUtilMode = true) {
737ad4d0182SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
738ad4d0182SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
739ad4d0182SAlina Sbirlea   LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
740ad4d0182SAlina Sbirlea                 IsUtilMode);
741ad4d0182SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
742ad4d0182SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
743b0aa36f9SDavid Green 
744b0aa36f9SDavid Green   return LR.processLoop(L);
745b0aa36f9SDavid Green }
746