[AMDGPU] Test codegen'ing True16 additions.
[llvm-project.git] / llvm / lib / Transforms / Utils / LoopRotationUtils.cpp
blob012aa5dbb9ca0047d4ae35682749d8f44de0e25c
1 //===----------------- LoopRotationUtils.cpp -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides utilities to convert a loop into a loop with bottom test.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Transforms/Utils/LoopRotationUtils.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/Analysis/AssumptionCache.h"
16 #include "llvm/Analysis/CodeMetrics.h"
17 #include "llvm/Analysis/DomTreeUpdater.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/MemorySSA.h"
21 #include "llvm/Analysis/MemorySSAUpdater.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/CFG.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/MDBuilder.h"
29 #include "llvm/IR/ProfDataUtils.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Transforms/Utils/Cloning.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include "llvm/Transforms/Utils/SSAUpdater.h"
37 #include "llvm/Transforms/Utils/ValueMapper.h"
38 using namespace llvm;
40 #define DEBUG_TYPE "loop-rotate"
42 STATISTIC(NumNotRotatedDueToHeaderSize,
43 "Number of loops not rotated due to the header size");
44 STATISTIC(NumInstrsHoisted,
45 "Number of instructions hoisted into loop preheader");
46 STATISTIC(NumInstrsDuplicated,
47 "Number of instructions cloned into loop preheader");
48 STATISTIC(NumRotated, "Number of loops rotated");
50 static cl::opt<bool>
51 MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden,
52 cl::desc("Allow loop rotation multiple times in order to reach "
53 "a better latch exit"));
55 // Probability that a rotated loop has zero trip count / is never entered.
56 static constexpr uint32_t ZeroTripCountWeights[] = {1, 127};
58 namespace {
59 /// A simple loop rotation transformation.
60 class LoopRotate {
61 const unsigned MaxHeaderSize;
62 LoopInfo *LI;
63 const TargetTransformInfo *TTI;
64 AssumptionCache *AC;
65 DominatorTree *DT;
66 ScalarEvolution *SE;
67 MemorySSAUpdater *MSSAU;
68 const SimplifyQuery &SQ;
69 bool RotationOnly;
70 bool IsUtilMode;
71 bool PrepareForLTO;
73 public:
74 LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
75 const TargetTransformInfo *TTI, AssumptionCache *AC,
76 DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
77 const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode,
78 bool PrepareForLTO)
79 : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
80 MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
81 IsUtilMode(IsUtilMode), PrepareForLTO(PrepareForLTO) {}
82 bool processLoop(Loop *L);
84 private:
85 bool rotateLoop(Loop *L, bool SimplifiedLatch);
86 bool simplifyLoopLatch(Loop *L);
88 } // end anonymous namespace
90 /// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
91 /// previously exist in the map, and the value was inserted.
92 static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V) {
93 bool Inserted = VM.insert({K, V}).second;
94 assert(Inserted);
95 (void)Inserted;
97 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
98 /// old header into the preheader. If there were uses of the values produced by
99 /// these instruction that were outside of the loop, we have to insert PHI nodes
100 /// to merge the two values. Do this now.
101 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
102 BasicBlock *OrigPreheader,
103 ValueToValueMapTy &ValueMap,
104 ScalarEvolution *SE,
105 SmallVectorImpl<PHINode*> *InsertedPHIs) {
106 // Remove PHI node entries that are no longer live.
107 BasicBlock::iterator I, E = OrigHeader->end();
108 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
109 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
111 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
112 // as necessary.
113 SSAUpdater SSA(InsertedPHIs);
114 for (I = OrigHeader->begin(); I != E; ++I) {
115 Value *OrigHeaderVal = &*I;
117 // If there are no uses of the value (e.g. because it returns void), there
118 // is nothing to rewrite.
119 if (OrigHeaderVal->use_empty())
120 continue;
122 Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
124 // The value now exits in two versions: the initial value in the preheader
125 // and the loop "next" value in the original header.
126 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
127 // Force re-computation of OrigHeaderVal, as some users now need to use the
128 // new PHI node.
129 if (SE)
130 SE->forgetValue(OrigHeaderVal);
131 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
132 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
134 // Visit each use of the OrigHeader instruction.
135 for (Use &U : llvm::make_early_inc_range(OrigHeaderVal->uses())) {
136 // SSAUpdater can't handle a non-PHI use in the same block as an
137 // earlier def. We can easily handle those cases manually.
138 Instruction *UserInst = cast<Instruction>(U.getUser());
139 if (!isa<PHINode>(UserInst)) {
140 BasicBlock *UserBB = UserInst->getParent();
142 // The original users in the OrigHeader are already using the
143 // original definitions.
144 if (UserBB == OrigHeader)
145 continue;
147 // Users in the OrigPreHeader need to use the value to which the
148 // original definitions are mapped.
149 if (UserBB == OrigPreheader) {
150 U = OrigPreHeaderVal;
151 continue;
155 // Anything else can be handled by SSAUpdater.
156 SSA.RewriteUse(U);
159 // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
160 // intrinsics.
161 SmallVector<DbgValueInst *, 1> DbgValues;
162 llvm::findDbgValues(DbgValues, OrigHeaderVal);
163 for (auto &DbgValue : DbgValues) {
164 // The original users in the OrigHeader are already using the original
165 // definitions.
166 BasicBlock *UserBB = DbgValue->getParent();
167 if (UserBB == OrigHeader)
168 continue;
170 // Users in the OrigPreHeader need to use the value to which the
171 // original definitions are mapped and anything else can be handled by
172 // the SSAUpdater. To avoid adding PHINodes, check if the value is
173 // available in UserBB, if not substitute undef.
174 Value *NewVal;
175 if (UserBB == OrigPreheader)
176 NewVal = OrigPreHeaderVal;
177 else if (SSA.HasValueForBlock(UserBB))
178 NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
179 else
180 NewVal = UndefValue::get(OrigHeaderVal->getType());
181 DbgValue->replaceVariableLocationOp(OrigHeaderVal, NewVal);
186 // Assuming both header and latch are exiting, look for a phi which is only
187 // used outside the loop (via a LCSSA phi) in the exit from the header.
188 // This means that rotating the loop can remove the phi.
189 static bool profitableToRotateLoopExitingLatch(Loop *L) {
190 BasicBlock *Header = L->getHeader();
191 BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
192 assert(BI && BI->isConditional() && "need header with conditional exit");
193 BasicBlock *HeaderExit = BI->getSuccessor(0);
194 if (L->contains(HeaderExit))
195 HeaderExit = BI->getSuccessor(1);
197 for (auto &Phi : Header->phis()) {
198 // Look for uses of this phi in the loop/via exits other than the header.
199 if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
200 return cast<Instruction>(U)->getParent() != HeaderExit;
202 continue;
203 return true;
205 return false;
208 // Check that latch exit is deoptimizing (which means - very unlikely to happen)
209 // and there is another exit from the loop which is non-deoptimizing.
210 // If we rotate latch to that exit our loop has a better chance of being fully
211 // canonical.
213 // It can give false positives in some rare cases.
214 static bool canRotateDeoptimizingLatchExit(Loop *L) {
215 BasicBlock *Latch = L->getLoopLatch();
216 assert(Latch && "need latch");
217 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
218 // Need normal exiting latch.
219 if (!BI || !BI->isConditional())
220 return false;
222 BasicBlock *Exit = BI->getSuccessor(1);
223 if (L->contains(Exit))
224 Exit = BI->getSuccessor(0);
226 // Latch exit is non-deoptimizing, no need to rotate.
227 if (!Exit->getPostdominatingDeoptimizeCall())
228 return false;
230 SmallVector<BasicBlock *, 4> Exits;
231 L->getUniqueExitBlocks(Exits);
232 if (!Exits.empty()) {
233 // There is at least one non-deoptimizing exit.
235 // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact,
236 // as it can conservatively return false for deoptimizing exits with
237 // complex enough control flow down to deoptimize call.
239 // That means here we can report success for a case where
240 // all exits are deoptimizing but one of them has complex enough
241 // control flow (e.g. with loops).
243 // That should be a very rare case and false positives for this function
244 // have compile-time effect only.
245 return any_of(Exits, [](const BasicBlock *BB) {
246 return !BB->getPostdominatingDeoptimizeCall();
249 return false;
252 static void updateBranchWeights(BranchInst &PreHeaderBI, BranchInst &LoopBI,
253 bool HasConditionalPreHeader,
254 bool SuccsSwapped) {
255 MDNode *WeightMD = getBranchWeightMDNode(PreHeaderBI);
256 if (WeightMD == nullptr)
257 return;
259 // LoopBI should currently be a clone of PreHeaderBI with the same
260 // metadata. But we double check to make sure we don't have a degenerate case
261 // where instsimplify changed the instructions.
262 if (WeightMD != getBranchWeightMDNode(LoopBI))
263 return;
265 SmallVector<uint32_t, 2> Weights;
266 extractFromBranchWeightMD(WeightMD, Weights);
267 if (Weights.size() != 2)
268 return;
269 uint32_t OrigLoopExitWeight = Weights[0];
270 uint32_t OrigLoopBackedgeWeight = Weights[1];
272 if (SuccsSwapped)
273 std::swap(OrigLoopExitWeight, OrigLoopBackedgeWeight);
275 // Update branch weights. Consider the following edge-counts:
277 // | |-------- |
278 // V V | V
279 // Br i1 ... | Br i1 ...
280 // | | | | |
281 // x| y| | becomes: | y0| |-----
282 // V V | | V V |
283 // Exit Loop | | Loop |
284 // | | | Br i1 ... |
285 // ----- | | | |
286 // x0| x1| y1 | |
287 // V V ----
288 // Exit
290 // The following must hold:
291 // - x == x0 + x1 # counts to "exit" must stay the same.
292 // - y0 == x - x0 == x1 # how often loop was entered at all.
293 // - y1 == y - y0 # How often loop was repeated (after first iter.).
295 // We cannot generally deduce how often we had a zero-trip count loop so we
296 // have to make a guess for how to distribute x among the new x0 and x1.
298 uint32_t ExitWeight0; // aka x0
299 uint32_t ExitWeight1; // aka x1
300 uint32_t EnterWeight; // aka y0
301 uint32_t LoopBackWeight; // aka y1
302 if (OrigLoopExitWeight > 0 && OrigLoopBackedgeWeight > 0) {
303 ExitWeight0 = 0;
304 if (HasConditionalPreHeader) {
305 // Here we cannot know how many 0-trip count loops we have, so we guess:
306 if (OrigLoopBackedgeWeight >= OrigLoopExitWeight) {
307 // If the loop count is bigger than the exit count then we set
308 // probabilities as if 0-trip count nearly never happens.
309 ExitWeight0 = ZeroTripCountWeights[0];
310 // Scale up counts if necessary so we can match `ZeroTripCountWeights`
311 // for the `ExitWeight0`:`ExitWeight1` (aka `x0`:`x1` ratio`) ratio.
312 while (OrigLoopExitWeight < ZeroTripCountWeights[1] + ExitWeight0) {
313 // ... but don't overflow.
314 uint32_t const HighBit = uint32_t{1} << (sizeof(uint32_t) * 8 - 1);
315 if ((OrigLoopBackedgeWeight & HighBit) != 0 ||
316 (OrigLoopExitWeight & HighBit) != 0)
317 break;
318 OrigLoopBackedgeWeight <<= 1;
319 OrigLoopExitWeight <<= 1;
321 } else {
322 // If there's a higher exit-count than backedge-count then we set
323 // probabilities as if there are only 0-trip and 1-trip cases.
324 ExitWeight0 = OrigLoopExitWeight - OrigLoopBackedgeWeight;
327 ExitWeight1 = OrigLoopExitWeight - ExitWeight0;
328 EnterWeight = ExitWeight1;
329 LoopBackWeight = OrigLoopBackedgeWeight - EnterWeight;
330 } else if (OrigLoopExitWeight == 0) {
331 if (OrigLoopBackedgeWeight == 0) {
332 // degenerate case... keep everything zero...
333 ExitWeight0 = 0;
334 ExitWeight1 = 0;
335 EnterWeight = 0;
336 LoopBackWeight = 0;
337 } else {
338 // Special case "LoopExitWeight == 0" weights which behaves like an
339 // endless where we don't want loop-enttry (y0) to be the same as
340 // loop-exit (x1).
341 ExitWeight0 = 0;
342 ExitWeight1 = 0;
343 EnterWeight = 1;
344 LoopBackWeight = OrigLoopBackedgeWeight;
346 } else {
347 // loop is never entered.
348 assert(OrigLoopBackedgeWeight == 0 && "remaining case is backedge zero");
349 ExitWeight0 = 1;
350 ExitWeight1 = 1;
351 EnterWeight = 0;
352 LoopBackWeight = 0;
355 MDBuilder MDB(LoopBI.getContext());
356 MDNode *LoopWeightMD =
357 MDB.createBranchWeights(SuccsSwapped ? LoopBackWeight : ExitWeight1,
358 SuccsSwapped ? ExitWeight1 : LoopBackWeight);
359 LoopBI.setMetadata(LLVMContext::MD_prof, LoopWeightMD);
360 if (HasConditionalPreHeader) {
361 MDNode *PreHeaderWeightMD =
362 MDB.createBranchWeights(SuccsSwapped ? EnterWeight : ExitWeight0,
363 SuccsSwapped ? ExitWeight0 : EnterWeight);
364 PreHeaderBI.setMetadata(LLVMContext::MD_prof, PreHeaderWeightMD);
368 /// Rotate loop LP. Return true if the loop is rotated.
370 /// \param SimplifiedLatch is true if the latch was just folded into the final
371 /// loop exit. In this case we may want to rotate even though the new latch is
372 /// now an exiting branch. This rotation would have happened had the latch not
373 /// been simplified. However, if SimplifiedLatch is false, then we avoid
374 /// rotating loops in which the latch exits to avoid excessive or endless
375 /// rotation. LoopRotate should be repeatable and converge to a canonical
376 /// form. This property is satisfied because simplifying the loop latch can only
377 /// happen once across multiple invocations of the LoopRotate pass.
379 /// If -loop-rotate-multi is enabled we can do multiple rotations in one go
380 /// so to reach a suitable (non-deoptimizing) exit.
381 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
382 // If the loop has only one block then there is not much to rotate.
383 if (L->getBlocks().size() == 1)
384 return false;
386 bool Rotated = false;
387 do {
388 BasicBlock *OrigHeader = L->getHeader();
389 BasicBlock *OrigLatch = L->getLoopLatch();
391 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
392 if (!BI || BI->isUnconditional())
393 return Rotated;
395 // If the loop header is not one of the loop exiting blocks then
396 // either this loop is already rotated or it is not
397 // suitable for loop rotation transformations.
398 if (!L->isLoopExiting(OrigHeader))
399 return Rotated;
401 // If the loop latch already contains a branch that leaves the loop then the
402 // loop is already rotated.
403 if (!OrigLatch)
404 return Rotated;
406 // Rotate if either the loop latch does *not* exit the loop, or if the loop
407 // latch was just simplified. Or if we think it will be profitable.
408 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
409 !profitableToRotateLoopExitingLatch(L) &&
410 !canRotateDeoptimizingLatchExit(L))
411 return Rotated;
413 // Check size of original header and reject loop if it is very big or we can't
414 // duplicate blocks inside it.
416 SmallPtrSet<const Value *, 32> EphValues;
417 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
419 CodeMetrics Metrics;
420 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues, PrepareForLTO);
421 if (Metrics.notDuplicatable) {
422 LLVM_DEBUG(
423 dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
424 << " instructions: ";
425 L->dump());
426 return Rotated;
428 if (Metrics.convergent) {
429 LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
430 "instructions: ";
431 L->dump());
432 return Rotated;
434 if (!Metrics.NumInsts.isValid()) {
435 LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains instructions"
436 " with invalid cost: ";
437 L->dump());
438 return Rotated;
440 if (Metrics.NumInsts > MaxHeaderSize) {
441 LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains "
442 << Metrics.NumInsts
443 << " instructions, which is more than the threshold ("
444 << MaxHeaderSize << " instructions): ";
445 L->dump());
446 ++NumNotRotatedDueToHeaderSize;
447 return Rotated;
450 // When preparing for LTO, avoid rotating loops with calls that could be
451 // inlined during the LTO stage.
452 if (PrepareForLTO && Metrics.NumInlineCandidates > 0)
453 return Rotated;
456 // Now, this loop is suitable for rotation.
457 BasicBlock *OrigPreheader = L->getLoopPreheader();
459 // If the loop could not be converted to canonical form, it must have an
460 // indirectbr in it, just give up.
461 if (!OrigPreheader || !L->hasDedicatedExits())
462 return Rotated;
464 // Anything ScalarEvolution may know about this loop or the PHI nodes
465 // in its header will soon be invalidated. We should also invalidate
466 // all outer loops because insertion and deletion of blocks that happens
467 // during the rotation may violate invariants related to backedge taken
468 // infos in them.
469 if (SE) {
470 SE->forgetTopmostLoop(L);
471 // We may hoist some instructions out of loop. In case if they were cached
472 // as "loop variant" or "loop computable", these caches must be dropped.
473 // We also may fold basic blocks, so cached block dispositions also need
474 // to be dropped.
475 SE->forgetBlockAndLoopDispositions();
478 LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
479 if (MSSAU && VerifyMemorySSA)
480 MSSAU->getMemorySSA()->verifyMemorySSA();
482 // Find new Loop header. NewHeader is a Header's one and only successor
483 // that is inside loop. Header's other successor is outside the
484 // loop. Otherwise loop is not suitable for rotation.
485 BasicBlock *Exit = BI->getSuccessor(0);
486 BasicBlock *NewHeader = BI->getSuccessor(1);
487 bool BISuccsSwapped = L->contains(Exit);
488 if (BISuccsSwapped)
489 std::swap(Exit, NewHeader);
490 assert(NewHeader && "Unable to determine new loop header");
491 assert(L->contains(NewHeader) && !L->contains(Exit) &&
492 "Unable to determine loop header and exit blocks");
494 // This code assumes that the new header has exactly one predecessor.
495 // Remove any single-entry PHI nodes in it.
496 assert(NewHeader->getSinglePredecessor() &&
497 "New header doesn't have one pred!");
498 FoldSingleEntryPHINodes(NewHeader);
500 // Begin by walking OrigHeader and populating ValueMap with an entry for
501 // each Instruction.
502 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
503 ValueToValueMapTy ValueMap, ValueMapMSSA;
505 // For PHI nodes, the value available in OldPreHeader is just the
506 // incoming value from OldPreHeader.
507 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
508 InsertNewValueIntoMap(ValueMap, PN,
509 PN->getIncomingValueForBlock(OrigPreheader));
511 // For the rest of the instructions, either hoist to the OrigPreheader if
512 // possible or create a clone in the OldPreHeader if not.
513 Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
515 // Record all debug intrinsics preceding LoopEntryBranch to avoid
516 // duplication.
517 using DbgIntrinsicHash =
518 std::pair<std::pair<hash_code, DILocalVariable *>, DIExpression *>;
519 auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash {
520 auto VarLocOps = D->location_ops();
521 return {{hash_combine_range(VarLocOps.begin(), VarLocOps.end()),
522 D->getVariable()},
523 D->getExpression()};
525 SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
526 for (Instruction &I : llvm::drop_begin(llvm::reverse(*OrigPreheader))) {
527 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I))
528 DbgIntrinsics.insert(makeHash(DII));
529 else
530 break;
533 // Remember the local noalias scope declarations in the header. After the
534 // rotation, they must be duplicated and the scope must be cloned. This
535 // avoids unwanted interaction across iterations.
536 SmallVector<NoAliasScopeDeclInst *, 6> NoAliasDeclInstructions;
537 for (Instruction &I : *OrigHeader)
538 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
539 NoAliasDeclInstructions.push_back(Decl);
541 while (I != E) {
542 Instruction *Inst = &*I++;
544 // If the instruction's operands are invariant and it doesn't read or write
545 // memory, then it is safe to hoist. Doing this doesn't change the order of
546 // execution in the preheader, but does prevent the instruction from
547 // executing in each iteration of the loop. This means it is safe to hoist
548 // something that might trap, but isn't safe to hoist something that reads
549 // memory (without proving that the loop doesn't write).
550 if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
551 !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
552 !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
553 Inst->moveBefore(LoopEntryBranch);
554 ++NumInstrsHoisted;
555 continue;
558 // Otherwise, create a duplicate of the instruction.
559 Instruction *C = Inst->clone();
560 C->insertBefore(LoopEntryBranch);
562 ++NumInstrsDuplicated;
564 // Eagerly remap the operands of the instruction.
565 RemapInstruction(C, ValueMap,
566 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
568 // Avoid inserting the same intrinsic twice.
569 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
570 if (DbgIntrinsics.count(makeHash(DII))) {
571 C->eraseFromParent();
572 continue;
575 // With the operands remapped, see if the instruction constant folds or is
576 // otherwise simplifyable. This commonly occurs because the entry from PHI
577 // nodes allows icmps and other instructions to fold.
578 Value *V = simplifyInstruction(C, SQ);
579 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
580 // If so, then delete the temporary instruction and stick the folded value
581 // in the map.
582 InsertNewValueIntoMap(ValueMap, Inst, V);
583 if (!C->mayHaveSideEffects()) {
584 C->eraseFromParent();
585 C = nullptr;
587 } else {
588 InsertNewValueIntoMap(ValueMap, Inst, C);
590 if (C) {
591 // Otherwise, stick the new instruction into the new block!
592 C->setName(Inst->getName());
594 if (auto *II = dyn_cast<AssumeInst>(C))
595 AC->registerAssumption(II);
596 // MemorySSA cares whether the cloned instruction was inserted or not, and
597 // not whether it can be remapped to a simplified value.
598 if (MSSAU)
599 InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
603 if (!NoAliasDeclInstructions.empty()) {
604 // There are noalias scope declarations:
605 // (general):
606 // Original: OrigPre { OrigHeader NewHeader ... Latch }
607 // after: (OrigPre+OrigHeader') { NewHeader ... Latch OrigHeader }
609 // with D: llvm.experimental.noalias.scope.decl,
610 // U: !noalias or !alias.scope depending on D
611 // ... { D U1 U2 } can transform into:
612 // (0) : ... { D U1 U2 } // no relevant rotation for this part
613 // (1) : ... D' { U1 U2 D } // D is part of OrigHeader
614 // (2) : ... D' U1' { U2 D U1 } // D, U1 are part of OrigHeader
616 // We now want to transform:
617 // (1) -> : ... D' { D U1 U2 D'' }
618 // (2) -> : ... D' U1' { D U2 D'' U1'' }
619 // D: original llvm.experimental.noalias.scope.decl
620 // D', U1': duplicate with replaced scopes
621 // D'', U1'': different duplicate with replaced scopes
622 // This ensures a safe fallback to 'may_alias' introduced by the rotate,
623 // as U1'' and U1' scopes will not be compatible wrt to the local restrict
625 // Clone the llvm.experimental.noalias.decl again for the NewHeader.
626 Instruction *NewHeaderInsertionPoint = &(*NewHeader->getFirstNonPHI());
627 for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions) {
628 LLVM_DEBUG(dbgs() << " Cloning llvm.experimental.noalias.scope.decl:"
629 << *NAD << "\n");
630 Instruction *NewNAD = NAD->clone();
631 NewNAD->insertBefore(NewHeaderInsertionPoint);
634 // Scopes must now be duplicated, once for OrigHeader and once for
635 // OrigPreHeader'.
637 auto &Context = NewHeader->getContext();
639 SmallVector<MDNode *, 8> NoAliasDeclScopes;
640 for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions)
641 NoAliasDeclScopes.push_back(NAD->getScopeList());
643 LLVM_DEBUG(dbgs() << " Updating OrigHeader scopes\n");
644 cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, {OrigHeader}, Context,
645 "h.rot");
646 LLVM_DEBUG(OrigHeader->dump());
648 // Keep the compile time impact low by only adapting the inserted block
649 // of instructions in the OrigPreHeader. This might result in slightly
650 // more aliasing between these instructions and those that were already
651 // present, but it will be much faster when the original PreHeader is
652 // large.
653 LLVM_DEBUG(dbgs() << " Updating part of OrigPreheader scopes\n");
654 auto *FirstDecl =
655 cast<Instruction>(ValueMap[*NoAliasDeclInstructions.begin()]);
656 auto *LastInst = &OrigPreheader->back();
657 cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, FirstDecl, LastInst,
658 Context, "pre.rot");
659 LLVM_DEBUG(OrigPreheader->dump());
661 LLVM_DEBUG(dbgs() << " Updated NewHeader:\n");
662 LLVM_DEBUG(NewHeader->dump());
666 // Along with all the other instructions, we just cloned OrigHeader's
667 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
668 // successors by duplicating their incoming values for OrigHeader.
669 for (BasicBlock *SuccBB : successors(OrigHeader))
670 for (BasicBlock::iterator BI = SuccBB->begin();
671 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
672 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
674 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
675 // OrigPreHeader's old terminator (the original branch into the loop), and
676 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
677 LoopEntryBranch->eraseFromParent();
679 // Update MemorySSA before the rewrite call below changes the 1:1
680 // instruction:cloned_instruction_or_value mapping.
681 if (MSSAU) {
682 InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
683 MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
684 ValueMapMSSA);
687 SmallVector<PHINode*, 2> InsertedPHIs;
688 // If there were any uses of instructions in the duplicated block outside the
689 // loop, update them, inserting PHI nodes as required
690 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap, SE,
691 &InsertedPHIs);
693 // Attach dbg.value intrinsics to the new phis if that phi uses a value that
694 // previously had debug metadata attached. This keeps the debug info
695 // up-to-date in the loop body.
696 if (!InsertedPHIs.empty())
697 insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
699 // NewHeader is now the header of the loop.
700 L->moveToHeader(NewHeader);
701 assert(L->getHeader() == NewHeader && "Latch block is our new header");
703 // Inform DT about changes to the CFG.
704 if (DT) {
705 // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
706 // the DT about the removed edge to the OrigHeader (that got removed).
707 SmallVector<DominatorTree::UpdateType, 3> Updates;
708 Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
709 Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
710 Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
712 if (MSSAU) {
713 MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
714 if (VerifyMemorySSA)
715 MSSAU->getMemorySSA()->verifyMemorySSA();
716 } else {
717 DT->applyUpdates(Updates);
721 // At this point, we've finished our major CFG changes. As part of cloning
722 // the loop into the preheader we've simplified instructions and the
723 // duplicated conditional branch may now be branching on a constant. If it is
724 // branching on a constant and if that constant means that we enter the loop,
725 // then we fold away the cond branch to an uncond branch. This simplifies the
726 // loop in cases important for nested loops, and it also means we don't have
727 // to split as many edges.
728 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
729 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
730 const Value *Cond = PHBI->getCondition();
731 const bool HasConditionalPreHeader =
732 !isa<ConstantInt>(Cond) ||
733 PHBI->getSuccessor(cast<ConstantInt>(Cond)->isZero()) != NewHeader;
735 updateBranchWeights(*PHBI, *BI, HasConditionalPreHeader, BISuccsSwapped);
737 if (HasConditionalPreHeader) {
738 // The conditional branch can't be folded, handle the general case.
739 // Split edges as necessary to preserve LoopSimplify form.
741 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
742 // thus is not a preheader anymore.
743 // Split the edge to form a real preheader.
744 BasicBlock *NewPH = SplitCriticalEdge(
745 OrigPreheader, NewHeader,
746 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
747 NewPH->setName(NewHeader->getName() + ".lr.ph");
749 // Preserve canonical loop form, which means that 'Exit' should have only
750 // one predecessor. Note that Exit could be an exit block for multiple
751 // nested loops, causing both of the edges to now be critical and need to
752 // be split.
753 SmallVector<BasicBlock *, 4> ExitPreds(predecessors(Exit));
754 bool SplitLatchEdge = false;
755 for (BasicBlock *ExitPred : ExitPreds) {
756 // We only need to split loop exit edges.
757 Loop *PredLoop = LI->getLoopFor(ExitPred);
758 if (!PredLoop || PredLoop->contains(Exit) ||
759 isa<IndirectBrInst>(ExitPred->getTerminator()))
760 continue;
761 SplitLatchEdge |= L->getLoopLatch() == ExitPred;
762 BasicBlock *ExitSplit = SplitCriticalEdge(
763 ExitPred, Exit,
764 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
765 ExitSplit->moveBefore(Exit);
767 assert(SplitLatchEdge &&
768 "Despite splitting all preds, failed to split latch exit?");
769 (void)SplitLatchEdge;
770 } else {
771 // We can fold the conditional branch in the preheader, this makes things
772 // simpler. The first step is to remove the extra edge to the Exit block.
773 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
774 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
775 NewBI->setDebugLoc(PHBI->getDebugLoc());
776 PHBI->eraseFromParent();
778 // With our CFG finalized, update DomTree if it is available.
779 if (DT) DT->deleteEdge(OrigPreheader, Exit);
781 // Update MSSA too, if available.
782 if (MSSAU)
783 MSSAU->removeEdge(OrigPreheader, Exit);
786 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
787 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
789 if (MSSAU && VerifyMemorySSA)
790 MSSAU->getMemorySSA()->verifyMemorySSA();
792 // Now that the CFG and DomTree are in a consistent state again, try to merge
793 // the OrigHeader block into OrigLatch. This will succeed if they are
794 // connected by an unconditional branch. This is just a cleanup so the
795 // emitted code isn't too gross in this common case.
796 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
797 BasicBlock *PredBB = OrigHeader->getUniquePredecessor();
798 bool DidMerge = MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
799 if (DidMerge)
800 RemoveRedundantDbgInstrs(PredBB);
802 if (MSSAU && VerifyMemorySSA)
803 MSSAU->getMemorySSA()->verifyMemorySSA();
805 LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
807 ++NumRotated;
809 Rotated = true;
810 SimplifiedLatch = false;
812 // Check that new latch is a deoptimizing exit and then repeat rotation if possible.
813 // Deoptimizing latch exit is not a generally typical case, so we just loop over.
814 // TODO: if it becomes a performance bottleneck extend rotation algorithm
815 // to handle multiple rotations in one go.
816 } while (MultiRotate && canRotateDeoptimizingLatchExit(L));
819 return true;
822 /// Determine whether the instructions in this range may be safely and cheaply
823 /// speculated. This is not an important enough situation to develop complex
824 /// heuristics. We handle a single arithmetic instruction along with any type
825 /// conversions.
826 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
827 BasicBlock::iterator End, Loop *L) {
828 bool seenIncrement = false;
829 bool MultiExitLoop = false;
831 if (!L->getExitingBlock())
832 MultiExitLoop = true;
834 for (BasicBlock::iterator I = Begin; I != End; ++I) {
836 if (!isSafeToSpeculativelyExecute(&*I))
837 return false;
839 if (isa<DbgInfoIntrinsic>(I))
840 continue;
842 switch (I->getOpcode()) {
843 default:
844 return false;
845 case Instruction::GetElementPtr:
846 // GEPs are cheap if all indices are constant.
847 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
848 return false;
849 // fall-thru to increment case
850 [[fallthrough]];
851 case Instruction::Add:
852 case Instruction::Sub:
853 case Instruction::And:
854 case Instruction::Or:
855 case Instruction::Xor:
856 case Instruction::Shl:
857 case Instruction::LShr:
858 case Instruction::AShr: {
859 Value *IVOpnd =
860 !isa<Constant>(I->getOperand(0))
861 ? I->getOperand(0)
862 : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
863 if (!IVOpnd)
864 return false;
866 // If increment operand is used outside of the loop, this speculation
867 // could cause extra live range interference.
868 if (MultiExitLoop) {
869 for (User *UseI : IVOpnd->users()) {
870 auto *UserInst = cast<Instruction>(UseI);
871 if (!L->contains(UserInst))
872 return false;
876 if (seenIncrement)
877 return false;
878 seenIncrement = true;
879 break;
881 case Instruction::Trunc:
882 case Instruction::ZExt:
883 case Instruction::SExt:
884 // ignore type conversions
885 break;
888 return true;
891 /// Fold the loop tail into the loop exit by speculating the loop tail
892 /// instructions. Typically, this is a single post-increment. In the case of a
893 /// simple 2-block loop, hoisting the increment can be much better than
894 /// duplicating the entire loop header. In the case of loops with early exits,
895 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
896 /// canonical form so downstream passes can handle it.
898 /// I don't believe this invalidates SCEV.
899 bool LoopRotate::simplifyLoopLatch(Loop *L) {
900 BasicBlock *Latch = L->getLoopLatch();
901 if (!Latch || Latch->hasAddressTaken())
902 return false;
904 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
905 if (!Jmp || !Jmp->isUnconditional())
906 return false;
908 BasicBlock *LastExit = Latch->getSinglePredecessor();
909 if (!LastExit || !L->isLoopExiting(LastExit))
910 return false;
912 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
913 if (!BI)
914 return false;
916 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
917 return false;
919 LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
920 << LastExit->getName() << "\n");
922 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
923 MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
924 /*PredecessorWithTwoSuccessors=*/true);
926 if (SE) {
927 // Merging blocks may remove blocks reference in the block disposition cache. Clear the cache.
928 SE->forgetBlockAndLoopDispositions();
931 if (MSSAU && VerifyMemorySSA)
932 MSSAU->getMemorySSA()->verifyMemorySSA();
934 return true;
937 /// Rotate \c L, and return true if any modification was made.
938 bool LoopRotate::processLoop(Loop *L) {
939 // Save the loop metadata.
940 MDNode *LoopMD = L->getLoopID();
942 bool SimplifiedLatch = false;
944 // Simplify the loop latch before attempting to rotate the header
945 // upward. Rotation may not be needed if the loop tail can be folded into the
946 // loop exit.
947 if (!RotationOnly)
948 SimplifiedLatch = simplifyLoopLatch(L);
950 bool MadeChange = rotateLoop(L, SimplifiedLatch);
951 assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
952 "Loop latch should be exiting after loop-rotate.");
954 // Restore the loop metadata.
955 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
956 if ((MadeChange || SimplifiedLatch) && LoopMD)
957 L->setLoopID(LoopMD);
959 return MadeChange || SimplifiedLatch;
963 /// The utility to convert a loop into a loop with bottom test.
964 bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
965 AssumptionCache *AC, DominatorTree *DT,
966 ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
967 const SimplifyQuery &SQ, bool RotationOnly = true,
968 unsigned Threshold = unsigned(-1),
969 bool IsUtilMode = true, bool PrepareForLTO) {
970 LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
971 IsUtilMode, PrepareForLTO);
972 return LR.processLoop(L);