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