]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/Scalar/LoopRotation.cpp
libfdt: Update to 1.4.6, switch to using libfdt for overlay support
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Transforms / Scalar / LoopRotation.cpp
1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Loop Rotation Pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/Scalar/LoopRotation.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/BasicAliasAnalysis.h"
19 #include "llvm/Analysis/CodeMetrics.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/ScalarEvolution.h"
24 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
25 #include "llvm/Analysis/TargetTransformInfo.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/IR/CFG.h"
28 #include "llvm/IR/DebugInfoMetadata.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Scalar/LoopPassManager.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Transforms/Utils/Local.h"
40 #include "llvm/Transforms/Utils/LoopUtils.h"
41 #include "llvm/Transforms/Utils/SSAUpdater.h"
42 #include "llvm/Transforms/Utils/ValueMapper.h"
43 using namespace llvm;
44
45 #define DEBUG_TYPE "loop-rotate"
46
47 static cl::opt<unsigned> DefaultRotationThreshold(
48     "rotation-max-header-size", cl::init(16), cl::Hidden,
49     cl::desc("The default maximum header size for automatic loop rotation"));
50
51 STATISTIC(NumRotated, "Number of loops rotated");
52
53 namespace {
54 /// A simple loop rotation transformation.
55 class LoopRotate {
56   const unsigned MaxHeaderSize;
57   LoopInfo *LI;
58   const TargetTransformInfo *TTI;
59   AssumptionCache *AC;
60   DominatorTree *DT;
61   ScalarEvolution *SE;
62   const SimplifyQuery &SQ;
63
64 public:
65   LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
66              const TargetTransformInfo *TTI, AssumptionCache *AC,
67              DominatorTree *DT, ScalarEvolution *SE, const SimplifyQuery &SQ)
68       : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
69         SQ(SQ) {}
70   bool processLoop(Loop *L);
71
72 private:
73   bool rotateLoop(Loop *L, bool SimplifiedLatch);
74   bool simplifyLoopLatch(Loop *L);
75 };
76 } // end anonymous namespace
77
78 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
79 /// old header into the preheader.  If there were uses of the values produced by
80 /// these instruction that were outside of the loop, we have to insert PHI nodes
81 /// to merge the two values.  Do this now.
82 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
83                                             BasicBlock *OrigPreheader,
84                                             ValueToValueMapTy &ValueMap,
85                                 SmallVectorImpl<PHINode*> *InsertedPHIs) {
86   // Remove PHI node entries that are no longer live.
87   BasicBlock::iterator I, E = OrigHeader->end();
88   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
89     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
90
91   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
92   // as necessary.
93   SSAUpdater SSA(InsertedPHIs);
94   for (I = OrigHeader->begin(); I != E; ++I) {
95     Value *OrigHeaderVal = &*I;
96
97     // If there are no uses of the value (e.g. because it returns void), there
98     // is nothing to rewrite.
99     if (OrigHeaderVal->use_empty())
100       continue;
101
102     Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
103
104     // The value now exits in two versions: the initial value in the preheader
105     // and the loop "next" value in the original header.
106     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
107     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
108     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
109
110     // Visit each use of the OrigHeader instruction.
111     for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
112                              UE = OrigHeaderVal->use_end();
113          UI != UE;) {
114       // Grab the use before incrementing the iterator.
115       Use &U = *UI;
116
117       // Increment the iterator before removing the use from the list.
118       ++UI;
119
120       // SSAUpdater can't handle a non-PHI use in the same block as an
121       // earlier def. We can easily handle those cases manually.
122       Instruction *UserInst = cast<Instruction>(U.getUser());
123       if (!isa<PHINode>(UserInst)) {
124         BasicBlock *UserBB = UserInst->getParent();
125
126         // The original users in the OrigHeader are already using the
127         // original definitions.
128         if (UserBB == OrigHeader)
129           continue;
130
131         // Users in the OrigPreHeader need to use the value to which the
132         // original definitions are mapped.
133         if (UserBB == OrigPreheader) {
134           U = OrigPreHeaderVal;
135           continue;
136         }
137       }
138
139       // Anything else can be handled by SSAUpdater.
140       SSA.RewriteUse(U);
141     }
142
143     // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
144     // intrinsics.
145     SmallVector<DbgValueInst *, 1> DbgValues;
146     llvm::findDbgValues(DbgValues, OrigHeaderVal);
147     for (auto &DbgValue : DbgValues) {
148       // The original users in the OrigHeader are already using the original
149       // definitions.
150       BasicBlock *UserBB = DbgValue->getParent();
151       if (UserBB == OrigHeader)
152         continue;
153
154       // Users in the OrigPreHeader need to use the value to which the
155       // original definitions are mapped and anything else can be handled by
156       // the SSAUpdater. To avoid adding PHINodes, check if the value is
157       // available in UserBB, if not substitute undef.
158       Value *NewVal;
159       if (UserBB == OrigPreheader)
160         NewVal = OrigPreHeaderVal;
161       else if (SSA.HasValueForBlock(UserBB))
162         NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
163       else
164         NewVal = UndefValue::get(OrigHeaderVal->getType());
165       DbgValue->setOperand(0,
166                            MetadataAsValue::get(OrigHeaderVal->getContext(),
167                                                 ValueAsMetadata::get(NewVal)));
168     }
169   }
170 }
171
172 /// Propagate dbg.value intrinsics through the newly inserted Phis.
173 static void insertDebugValues(BasicBlock *OrigHeader,
174                               SmallVectorImpl<PHINode*> &InsertedPHIs) {
175   ValueToValueMapTy DbgValueMap;
176
177   // Map existing PHI nodes to their dbg.values.
178   for (auto &I : *OrigHeader) {
179     if (auto DbgII = dyn_cast<DbgInfoIntrinsic>(&I)) {
180       if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
181         DbgValueMap.insert({Loc, DbgII});
182     }
183   }
184
185   // Then iterate through the new PHIs and look to see if they use one of the
186   // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
187   // propagate the info through the new PHI.
188   LLVMContext &C = OrigHeader->getContext();
189   for (auto PHI : InsertedPHIs) {
190     for (auto VI : PHI->operand_values()) {
191       auto V = DbgValueMap.find(VI);
192       if (V != DbgValueMap.end()) {
193         auto *DbgII = cast<DbgInfoIntrinsic>(V->second);
194         Instruction *NewDbgII = DbgII->clone();
195         auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
196         NewDbgII->setOperand(0, PhiMAV);
197         BasicBlock *Parent = PHI->getParent();
198         NewDbgII->insertBefore(Parent->getFirstNonPHIOrDbgOrLifetime());
199       }
200     }
201   }
202 }
203
204 /// Rotate loop LP. Return true if the loop is rotated.
205 ///
206 /// \param SimplifiedLatch is true if the latch was just folded into the final
207 /// loop exit. In this case we may want to rotate even though the new latch is
208 /// now an exiting branch. This rotation would have happened had the latch not
209 /// been simplified. However, if SimplifiedLatch is false, then we avoid
210 /// rotating loops in which the latch exits to avoid excessive or endless
211 /// rotation. LoopRotate should be repeatable and converge to a canonical
212 /// form. This property is satisfied because simplifying the loop latch can only
213 /// happen once across multiple invocations of the LoopRotate pass.
214 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
215   // If the loop has only one block then there is not much to rotate.
216   if (L->getBlocks().size() == 1)
217     return false;
218
219   BasicBlock *OrigHeader = L->getHeader();
220   BasicBlock *OrigLatch = L->getLoopLatch();
221
222   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
223   if (!BI || BI->isUnconditional())
224     return false;
225
226   // If the loop header is not one of the loop exiting blocks then
227   // either this loop is already rotated or it is not
228   // suitable for loop rotation transformations.
229   if (!L->isLoopExiting(OrigHeader))
230     return false;
231
232   // If the loop latch already contains a branch that leaves the loop then the
233   // loop is already rotated.
234   if (!OrigLatch)
235     return false;
236
237   // Rotate if either the loop latch does *not* exit the loop, or if the loop
238   // latch was just simplified.
239   if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
240     return false;
241
242   // Check size of original header and reject loop if it is very big or we can't
243   // duplicate blocks inside it.
244   {
245     SmallPtrSet<const Value *, 32> EphValues;
246     CodeMetrics::collectEphemeralValues(L, AC, EphValues);
247
248     CodeMetrics Metrics;
249     Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
250     if (Metrics.notDuplicatable) {
251       DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
252                    << " instructions: ";
253             L->dump());
254       return false;
255     }
256     if (Metrics.convergent) {
257       DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
258                       "instructions: ";
259             L->dump());
260       return false;
261     }
262     if (Metrics.NumInsts > MaxHeaderSize)
263       return false;
264   }
265
266   // Now, this loop is suitable for rotation.
267   BasicBlock *OrigPreheader = L->getLoopPreheader();
268
269   // If the loop could not be converted to canonical form, it must have an
270   // indirectbr in it, just give up.
271   if (!OrigPreheader)
272     return false;
273
274   // Anything ScalarEvolution may know about this loop or the PHI nodes
275   // in its header will soon be invalidated.
276   if (SE)
277     SE->forgetLoop(L);
278
279   DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
280
281   // Find new Loop header. NewHeader is a Header's one and only successor
282   // that is inside loop.  Header's other successor is outside the
283   // loop.  Otherwise loop is not suitable for rotation.
284   BasicBlock *Exit = BI->getSuccessor(0);
285   BasicBlock *NewHeader = BI->getSuccessor(1);
286   if (L->contains(Exit))
287     std::swap(Exit, NewHeader);
288   assert(NewHeader && "Unable to determine new loop header");
289   assert(L->contains(NewHeader) && !L->contains(Exit) &&
290          "Unable to determine loop header and exit blocks");
291
292   // This code assumes that the new header has exactly one predecessor.
293   // Remove any single-entry PHI nodes in it.
294   assert(NewHeader->getSinglePredecessor() &&
295          "New header doesn't have one pred!");
296   FoldSingleEntryPHINodes(NewHeader);
297
298   // Begin by walking OrigHeader and populating ValueMap with an entry for
299   // each Instruction.
300   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
301   ValueToValueMapTy ValueMap;
302
303   // For PHI nodes, the value available in OldPreHeader is just the
304   // incoming value from OldPreHeader.
305   for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
306     ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
307
308   // For the rest of the instructions, either hoist to the OrigPreheader if
309   // possible or create a clone in the OldPreHeader if not.
310   TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
311
312   // Record all debug intrinsics preceding LoopEntryBranch to avoid duplication.
313   using DbgIntrinsicHash =
314       std::pair<std::pair<Value *, DILocalVariable *>, DIExpression *>;
315   auto makeHash = [](DbgInfoIntrinsic *D) -> DbgIntrinsicHash {
316     return {{D->getVariableLocation(), D->getVariable()}, D->getExpression()};
317   };
318   SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
319   for (auto I = std::next(OrigPreheader->rbegin()), E = OrigPreheader->rend();
320        I != E; ++I) {
321     if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&*I))
322       DbgIntrinsics.insert(makeHash(DII));
323     else
324       break;
325   }
326
327   while (I != E) {
328     Instruction *Inst = &*I++;
329
330     // If the instruction's operands are invariant and it doesn't read or write
331     // memory, then it is safe to hoist.  Doing this doesn't change the order of
332     // execution in the preheader, but does prevent the instruction from
333     // executing in each iteration of the loop.  This means it is safe to hoist
334     // something that might trap, but isn't safe to hoist something that reads
335     // memory (without proving that the loop doesn't write).
336     if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
337         !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) &&
338         !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
339       Inst->moveBefore(LoopEntryBranch);
340       continue;
341     }
342
343     // Otherwise, create a duplicate of the instruction.
344     Instruction *C = Inst->clone();
345
346     // Eagerly remap the operands of the instruction.
347     RemapInstruction(C, ValueMap,
348                      RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
349
350     // Avoid inserting the same intrinsic twice.
351     if (auto *DII = dyn_cast<DbgInfoIntrinsic>(C))
352       if (DbgIntrinsics.count(makeHash(DII))) {
353         C->deleteValue();
354         continue;
355       }
356
357     // With the operands remapped, see if the instruction constant folds or is
358     // otherwise simplifyable.  This commonly occurs because the entry from PHI
359     // nodes allows icmps and other instructions to fold.
360     Value *V = SimplifyInstruction(C, SQ);
361     if (V && LI->replacementPreservesLCSSAForm(C, V)) {
362       // If so, then delete the temporary instruction and stick the folded value
363       // in the map.
364       ValueMap[Inst] = V;
365       if (!C->mayHaveSideEffects()) {
366         C->deleteValue();
367         C = nullptr;
368       }
369     } else {
370       ValueMap[Inst] = C;
371     }
372     if (C) {
373       // Otherwise, stick the new instruction into the new block!
374       C->setName(Inst->getName());
375       C->insertBefore(LoopEntryBranch);
376
377       if (auto *II = dyn_cast<IntrinsicInst>(C))
378         if (II->getIntrinsicID() == Intrinsic::assume)
379           AC->registerAssumption(II);
380     }
381   }
382
383   // Along with all the other instructions, we just cloned OrigHeader's
384   // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
385   // successors by duplicating their incoming values for OrigHeader.
386   TerminatorInst *TI = OrigHeader->getTerminator();
387   for (BasicBlock *SuccBB : TI->successors())
388     for (BasicBlock::iterator BI = SuccBB->begin();
389          PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
390       PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
391
392   // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
393   // OrigPreHeader's old terminator (the original branch into the loop), and
394   // remove the corresponding incoming values from the PHI nodes in OrigHeader.
395   LoopEntryBranch->eraseFromParent();
396
397
398   SmallVector<PHINode*, 2> InsertedPHIs;
399   // If there were any uses of instructions in the duplicated block outside the
400   // loop, update them, inserting PHI nodes as required
401   RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
402                                   &InsertedPHIs);
403
404   // Attach dbg.value intrinsics to the new phis if that phi uses a value that
405   // previously had debug metadata attached. This keeps the debug info
406   // up-to-date in the loop body.
407   if (!InsertedPHIs.empty())
408     insertDebugValues(OrigHeader, InsertedPHIs);
409
410   // NewHeader is now the header of the loop.
411   L->moveToHeader(NewHeader);
412   assert(L->getHeader() == NewHeader && "Latch block is our new header");
413
414   // Inform DT about changes to the CFG.
415   if (DT) {
416     // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
417     // the DT about the removed edge to the OrigHeader (that got removed).
418     SmallVector<DominatorTree::UpdateType, 3> Updates;
419     Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
420     Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
421     Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
422     DT->applyUpdates(Updates);
423   }
424
425   // At this point, we've finished our major CFG changes.  As part of cloning
426   // the loop into the preheader we've simplified instructions and the
427   // duplicated conditional branch may now be branching on a constant.  If it is
428   // branching on a constant and if that constant means that we enter the loop,
429   // then we fold away the cond branch to an uncond branch.  This simplifies the
430   // loop in cases important for nested loops, and it also means we don't have
431   // to split as many edges.
432   BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
433   assert(PHBI->isConditional() && "Should be clone of BI condbr!");
434   if (!isa<ConstantInt>(PHBI->getCondition()) ||
435       PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
436           NewHeader) {
437     // The conditional branch can't be folded, handle the general case.
438     // Split edges as necessary to preserve LoopSimplify form.
439
440     // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
441     // thus is not a preheader anymore.
442     // Split the edge to form a real preheader.
443     BasicBlock *NewPH = SplitCriticalEdge(
444         OrigPreheader, NewHeader,
445         CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
446     NewPH->setName(NewHeader->getName() + ".lr.ph");
447
448     // Preserve canonical loop form, which means that 'Exit' should have only
449     // one predecessor. Note that Exit could be an exit block for multiple
450     // nested loops, causing both of the edges to now be critical and need to
451     // be split.
452     SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
453     bool SplitLatchEdge = false;
454     for (BasicBlock *ExitPred : ExitPreds) {
455       // We only need to split loop exit edges.
456       Loop *PredLoop = LI->getLoopFor(ExitPred);
457       if (!PredLoop || PredLoop->contains(Exit))
458         continue;
459       if (isa<IndirectBrInst>(ExitPred->getTerminator()))
460         continue;
461       SplitLatchEdge |= L->getLoopLatch() == ExitPred;
462       BasicBlock *ExitSplit = SplitCriticalEdge(
463           ExitPred, Exit,
464           CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
465       ExitSplit->moveBefore(Exit);
466     }
467     assert(SplitLatchEdge &&
468            "Despite splitting all preds, failed to split latch exit?");
469   } else {
470     // We can fold the conditional branch in the preheader, this makes things
471     // simpler. The first step is to remove the extra edge to the Exit block.
472     Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
473     BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
474     NewBI->setDebugLoc(PHBI->getDebugLoc());
475     PHBI->eraseFromParent();
476
477     // With our CFG finalized, update DomTree if it is available.
478     if (DT) DT->deleteEdge(OrigPreheader, Exit);
479   }
480
481   assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
482   assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
483
484   // Now that the CFG and DomTree are in a consistent state again, try to merge
485   // the OrigHeader block into OrigLatch.  This will succeed if they are
486   // connected by an unconditional branch.  This is just a cleanup so the
487   // emitted code isn't too gross in this common case.
488   MergeBlockIntoPredecessor(OrigHeader, DT, LI);
489
490   DEBUG(dbgs() << "LoopRotation: into "; L->dump());
491
492   ++NumRotated;
493   return true;
494 }
495
496 /// Determine whether the instructions in this range may be safely and cheaply
497 /// speculated. This is not an important enough situation to develop complex
498 /// heuristics. We handle a single arithmetic instruction along with any type
499 /// conversions.
500 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
501                                   BasicBlock::iterator End, Loop *L) {
502   bool seenIncrement = false;
503   bool MultiExitLoop = false;
504
505   if (!L->getExitingBlock())
506     MultiExitLoop = true;
507
508   for (BasicBlock::iterator I = Begin; I != End; ++I) {
509
510     if (!isSafeToSpeculativelyExecute(&*I))
511       return false;
512
513     if (isa<DbgInfoIntrinsic>(I))
514       continue;
515
516     switch (I->getOpcode()) {
517     default:
518       return false;
519     case Instruction::GetElementPtr:
520       // GEPs are cheap if all indices are constant.
521       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
522         return false;
523       // fall-thru to increment case
524       LLVM_FALLTHROUGH;
525     case Instruction::Add:
526     case Instruction::Sub:
527     case Instruction::And:
528     case Instruction::Or:
529     case Instruction::Xor:
530     case Instruction::Shl:
531     case Instruction::LShr:
532     case Instruction::AShr: {
533       Value *IVOpnd =
534           !isa<Constant>(I->getOperand(0))
535               ? I->getOperand(0)
536               : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
537       if (!IVOpnd)
538         return false;
539
540       // If increment operand is used outside of the loop, this speculation
541       // could cause extra live range interference.
542       if (MultiExitLoop) {
543         for (User *UseI : IVOpnd->users()) {
544           auto *UserInst = cast<Instruction>(UseI);
545           if (!L->contains(UserInst))
546             return false;
547         }
548       }
549
550       if (seenIncrement)
551         return false;
552       seenIncrement = true;
553       break;
554     }
555     case Instruction::Trunc:
556     case Instruction::ZExt:
557     case Instruction::SExt:
558       // ignore type conversions
559       break;
560     }
561   }
562   return true;
563 }
564
565 /// Fold the loop tail into the loop exit by speculating the loop tail
566 /// instructions. Typically, this is a single post-increment. In the case of a
567 /// simple 2-block loop, hoisting the increment can be much better than
568 /// duplicating the entire loop header. In the case of loops with early exits,
569 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
570 /// canonical form so downstream passes can handle it.
571 ///
572 /// I don't believe this invalidates SCEV.
573 bool LoopRotate::simplifyLoopLatch(Loop *L) {
574   BasicBlock *Latch = L->getLoopLatch();
575   if (!Latch || Latch->hasAddressTaken())
576     return false;
577
578   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
579   if (!Jmp || !Jmp->isUnconditional())
580     return false;
581
582   BasicBlock *LastExit = Latch->getSinglePredecessor();
583   if (!LastExit || !L->isLoopExiting(LastExit))
584     return false;
585
586   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
587   if (!BI)
588     return false;
589
590   if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
591     return false;
592
593   DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
594                << LastExit->getName() << "\n");
595
596   // Hoist the instructions from Latch into LastExit.
597   LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
598                                  Latch->begin(), Jmp->getIterator());
599
600   unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
601   BasicBlock *Header = Jmp->getSuccessor(0);
602   assert(Header == L->getHeader() && "expected a backward branch");
603
604   // Remove Latch from the CFG so that LastExit becomes the new Latch.
605   BI->setSuccessor(FallThruPath, Header);
606   Latch->replaceSuccessorsPhiUsesWith(LastExit);
607   Jmp->eraseFromParent();
608
609   // Nuke the Latch block.
610   assert(Latch->empty() && "unable to evacuate Latch");
611   LI->removeBlock(Latch);
612   if (DT)
613     DT->eraseNode(Latch);
614   Latch->eraseFromParent();
615   return true;
616 }
617
618 /// Rotate \c L, and return true if any modification was made.
619 bool LoopRotate::processLoop(Loop *L) {
620   // Save the loop metadata.
621   MDNode *LoopMD = L->getLoopID();
622
623   // Simplify the loop latch before attempting to rotate the header
624   // upward. Rotation may not be needed if the loop tail can be folded into the
625   // loop exit.
626   bool SimplifiedLatch = simplifyLoopLatch(L);
627
628   bool MadeChange = rotateLoop(L, SimplifiedLatch);
629   assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
630          "Loop latch should be exiting after loop-rotate.");
631
632   // Restore the loop metadata.
633   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
634   if ((MadeChange || SimplifiedLatch) && LoopMD)
635     L->setLoopID(LoopMD);
636
637   return MadeChange || SimplifiedLatch;
638 }
639
640 LoopRotatePass::LoopRotatePass(bool EnableHeaderDuplication)
641     : EnableHeaderDuplication(EnableHeaderDuplication) {}
642
643 PreservedAnalyses LoopRotatePass::run(Loop &L, LoopAnalysisManager &AM,
644                                       LoopStandardAnalysisResults &AR,
645                                       LPMUpdater &) {
646   int Threshold = EnableHeaderDuplication ? DefaultRotationThreshold : 0;
647   const DataLayout &DL = L.getHeader()->getModule()->getDataLayout();
648   const SimplifyQuery SQ = getBestSimplifyQuery(AR, DL);
649   LoopRotate LR(Threshold, &AR.LI, &AR.TTI, &AR.AC, &AR.DT, &AR.SE,
650                 SQ);
651
652   bool Changed = LR.processLoop(&L);
653   if (!Changed)
654     return PreservedAnalyses::all();
655
656   return getLoopPassPreservedAnalyses();
657 }
658
659 namespace {
660
661 class LoopRotateLegacyPass : public LoopPass {
662   unsigned MaxHeaderSize;
663
664 public:
665   static char ID; // Pass ID, replacement for typeid
666   LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
667     initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry());
668     if (SpecifiedMaxHeaderSize == -1)
669       MaxHeaderSize = DefaultRotationThreshold;
670     else
671       MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
672   }
673
674   // LCSSA form makes instruction renaming easier.
675   void getAnalysisUsage(AnalysisUsage &AU) const override {
676     AU.addRequired<AssumptionCacheTracker>();
677     AU.addRequired<TargetTransformInfoWrapperPass>();
678     getLoopAnalysisUsage(AU);
679   }
680
681   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
682     if (skipLoop(L))
683       return false;
684     Function &F = *L->getHeader()->getParent();
685
686     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
687     const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
688     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
689     auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
690     auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
691     auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
692     auto *SE = SEWP ? &SEWP->getSE() : nullptr;
693     const SimplifyQuery SQ = getBestSimplifyQuery(*this, F);
694     LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE, SQ);
695     return LR.processLoop(L);
696   }
697 };
698 }
699
700 char LoopRotateLegacyPass::ID = 0;
701 INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
702                       false, false)
703 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
704 INITIALIZE_PASS_DEPENDENCY(LoopPass)
705 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
706 INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false,
707                     false)
708
709 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
710   return new LoopRotateLegacyPass(MaxHeaderSize);
711 }