1 //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
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 defines common loop utility functions.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Transforms/Utils/LoopUtils.h"
14 #include "llvm/ADT/DenseSet.h"
15 #include "llvm/ADT/PriorityWorklist.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BasicAliasAnalysis.h"
22 #include "llvm/Analysis/DomTreeUpdater.h"
23 #include "llvm/Analysis/GlobalsModRef.h"
24 #include "llvm/Analysis/InstSimplifyFolder.h"
25 #include "llvm/Analysis/LoopAccessAnalysis.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Analysis/MemorySSA.h"
29 #include "llvm/Analysis/MemorySSAUpdater.h"
30 #include "llvm/Analysis/ScalarEvolution.h"
31 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
32 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
33 #include "llvm/IR/DIBuilder.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/MDBuilder.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/PatternMatch.h"
40 #include "llvm/IR/ProfDataUtils.h"
41 #include "llvm/IR/ValueHandle.h"
42 #include "llvm/InitializePasses.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
49
50 using namespace llvm;
51 using namespace llvm::PatternMatch;
52
53 #define DEBUG_TYPE "loop-utils"
54
55 static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
56 static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
57
formDedicatedExitBlocks(Loop * L,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)58 bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
59 MemorySSAUpdater *MSSAU,
60 bool PreserveLCSSA) {
61 bool Changed = false;
62
63 // We re-use a vector for the in-loop predecesosrs.
64 SmallVector<BasicBlock *, 4> InLoopPredecessors;
65
66 auto RewriteExit = [&](BasicBlock *BB) {
67 assert(InLoopPredecessors.empty() &&
68 "Must start with an empty predecessors list!");
69 auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
70
71 // See if there are any non-loop predecessors of this exit block and
72 // keep track of the in-loop predecessors.
73 bool IsDedicatedExit = true;
74 for (auto *PredBB : predecessors(BB))
75 if (L->contains(PredBB)) {
76 if (isa<IndirectBrInst>(PredBB->getTerminator()))
77 // We cannot rewrite exiting edges from an indirectbr.
78 return false;
79
80 InLoopPredecessors.push_back(PredBB);
81 } else {
82 IsDedicatedExit = false;
83 }
84
85 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
86
87 // Nothing to do if this is already a dedicated exit.
88 if (IsDedicatedExit)
89 return false;
90
91 auto *NewExitBB = SplitBlockPredecessors(
92 BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
93
94 if (!NewExitBB)
95 LLVM_DEBUG(
96 dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
97 << *L << "\n");
98 else
99 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
100 << NewExitBB->getName() << "\n");
101 return true;
102 };
103
104 // Walk the exit blocks directly rather than building up a data structure for
105 // them, but only visit each one once.
106 SmallPtrSet<BasicBlock *, 4> Visited;
107 for (auto *BB : L->blocks())
108 for (auto *SuccBB : successors(BB)) {
109 // We're looking for exit blocks so skip in-loop successors.
110 if (L->contains(SuccBB))
111 continue;
112
113 // Visit each exit block exactly once.
114 if (!Visited.insert(SuccBB).second)
115 continue;
116
117 Changed |= RewriteExit(SuccBB);
118 }
119
120 return Changed;
121 }
122
123 /// Returns the instructions that use values defined in the loop.
findDefsUsedOutsideOfLoop(Loop * L)124 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
125 SmallVector<Instruction *, 8> UsedOutside;
126
127 for (auto *Block : L->getBlocks())
128 // FIXME: I believe that this could use copy_if if the Inst reference could
129 // be adapted into a pointer.
130 for (auto &Inst : *Block) {
131 auto Users = Inst.users();
132 if (any_of(Users, [&](User *U) {
133 auto *Use = cast<Instruction>(U);
134 return !L->contains(Use->getParent());
135 }))
136 UsedOutside.push_back(&Inst);
137 }
138
139 return UsedOutside;
140 }
141
getLoopAnalysisUsage(AnalysisUsage & AU)142 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
143 // By definition, all loop passes need the LoopInfo analysis and the
144 // Dominator tree it depends on. Because they all participate in the loop
145 // pass manager, they must also preserve these.
146 AU.addRequired<DominatorTreeWrapperPass>();
147 AU.addPreserved<DominatorTreeWrapperPass>();
148 AU.addRequired<LoopInfoWrapperPass>();
149 AU.addPreserved<LoopInfoWrapperPass>();
150
151 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
152 // here because users shouldn't directly get them from this header.
153 extern char &LoopSimplifyID;
154 extern char &LCSSAID;
155 AU.addRequiredID(LoopSimplifyID);
156 AU.addPreservedID(LoopSimplifyID);
157 AU.addRequiredID(LCSSAID);
158 AU.addPreservedID(LCSSAID);
159 // This is used in the LPPassManager to perform LCSSA verification on passes
160 // which preserve lcssa form
161 AU.addRequired<LCSSAVerificationPass>();
162 AU.addPreserved<LCSSAVerificationPass>();
163
164 // Loop passes are designed to run inside of a loop pass manager which means
165 // that any function analyses they require must be required by the first loop
166 // pass in the manager (so that it is computed before the loop pass manager
167 // runs) and preserved by all loop pasess in the manager. To make this
168 // reasonably robust, the set needed for most loop passes is maintained here.
169 // If your loop pass requires an analysis not listed here, you will need to
170 // carefully audit the loop pass manager nesting structure that results.
171 AU.addRequired<AAResultsWrapperPass>();
172 AU.addPreserved<AAResultsWrapperPass>();
173 AU.addPreserved<BasicAAWrapperPass>();
174 AU.addPreserved<GlobalsAAWrapperPass>();
175 AU.addPreserved<SCEVAAWrapperPass>();
176 AU.addRequired<ScalarEvolutionWrapperPass>();
177 AU.addPreserved<ScalarEvolutionWrapperPass>();
178 // FIXME: When all loop passes preserve MemorySSA, it can be required and
179 // preserved here instead of the individual handling in each pass.
180 }
181
182 /// Manually defined generic "LoopPass" dependency initialization. This is used
183 /// to initialize the exact set of passes from above in \c
184 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
185 /// with:
186 ///
187 /// INITIALIZE_PASS_DEPENDENCY(LoopPass)
188 ///
189 /// As-if "LoopPass" were a pass.
initializeLoopPassPass(PassRegistry & Registry)190 void llvm::initializeLoopPassPass(PassRegistry &Registry) {
191 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
192 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
193 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
194 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
195 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
196 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
197 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
198 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
199 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
200 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
201 }
202
203 /// Create MDNode for input string.
createStringMetadata(Loop * TheLoop,StringRef Name,unsigned V)204 static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
205 LLVMContext &Context = TheLoop->getHeader()->getContext();
206 Metadata *MDs[] = {
207 MDString::get(Context, Name),
208 ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
209 return MDNode::get(Context, MDs);
210 }
211
212 /// Set input string into loop metadata by keeping other values intact.
213 /// If the string is already in loop metadata update value if it is
214 /// different.
addStringMetadataToLoop(Loop * TheLoop,const char * StringMD,unsigned V)215 void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
216 unsigned V) {
217 SmallVector<Metadata *, 4> MDs(1);
218 // If the loop already has metadata, retain it.
219 MDNode *LoopID = TheLoop->getLoopID();
220 if (LoopID) {
221 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
222 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
223 // If it is of form key = value, try to parse it.
224 if (Node->getNumOperands() == 2) {
225 MDString *S = dyn_cast<MDString>(Node->getOperand(0));
226 if (S && S->getString() == StringMD) {
227 ConstantInt *IntMD =
228 mdconst::extract_or_null<ConstantInt>(Node->getOperand(1));
229 if (IntMD && IntMD->getSExtValue() == V)
230 // It is already in place. Do nothing.
231 return;
232 // We need to update the value, so just skip it here and it will
233 // be added after copying other existed nodes.
234 continue;
235 }
236 }
237 MDs.push_back(Node);
238 }
239 }
240 // Add new metadata.
241 MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
242 // Replace current metadata node with new one.
243 LLVMContext &Context = TheLoop->getHeader()->getContext();
244 MDNode *NewLoopID = MDNode::get(Context, MDs);
245 // Set operand 0 to refer to the loop id itself.
246 NewLoopID->replaceOperandWith(0, NewLoopID);
247 TheLoop->setLoopID(NewLoopID);
248 }
249
250 std::optional<ElementCount>
getOptionalElementCountLoopAttribute(const Loop * TheLoop)251 llvm::getOptionalElementCountLoopAttribute(const Loop *TheLoop) {
252 std::optional<int> Width =
253 getOptionalIntLoopAttribute(TheLoop, "llvm.loop.vectorize.width");
254
255 if (Width) {
256 std::optional<int> IsScalable = getOptionalIntLoopAttribute(
257 TheLoop, "llvm.loop.vectorize.scalable.enable");
258 return ElementCount::get(*Width, IsScalable.value_or(false));
259 }
260
261 return std::nullopt;
262 }
263
makeFollowupLoopID(MDNode * OrigLoopID,ArrayRef<StringRef> FollowupOptions,const char * InheritOptionsExceptPrefix,bool AlwaysNew)264 std::optional<MDNode *> llvm::makeFollowupLoopID(
265 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
266 const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
267 if (!OrigLoopID) {
268 if (AlwaysNew)
269 return nullptr;
270 return std::nullopt;
271 }
272
273 assert(OrigLoopID->getOperand(0) == OrigLoopID);
274
275 bool InheritAllAttrs = !InheritOptionsExceptPrefix;
276 bool InheritSomeAttrs =
277 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
278 SmallVector<Metadata *, 8> MDs;
279 MDs.push_back(nullptr);
280
281 bool Changed = false;
282 if (InheritAllAttrs || InheritSomeAttrs) {
283 for (const MDOperand &Existing : drop_begin(OrigLoopID->operands())) {
284 MDNode *Op = cast<MDNode>(Existing.get());
285
286 auto InheritThisAttribute = [InheritSomeAttrs,
287 InheritOptionsExceptPrefix](MDNode *Op) {
288 if (!InheritSomeAttrs)
289 return false;
290
291 // Skip malformatted attribute metadata nodes.
292 if (Op->getNumOperands() == 0)
293 return true;
294 Metadata *NameMD = Op->getOperand(0).get();
295 if (!isa<MDString>(NameMD))
296 return true;
297 StringRef AttrName = cast<MDString>(NameMD)->getString();
298
299 // Do not inherit excluded attributes.
300 return !AttrName.starts_with(InheritOptionsExceptPrefix);
301 };
302
303 if (InheritThisAttribute(Op))
304 MDs.push_back(Op);
305 else
306 Changed = true;
307 }
308 } else {
309 // Modified if we dropped at least one attribute.
310 Changed = OrigLoopID->getNumOperands() > 1;
311 }
312
313 bool HasAnyFollowup = false;
314 for (StringRef OptionName : FollowupOptions) {
315 MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
316 if (!FollowupNode)
317 continue;
318
319 HasAnyFollowup = true;
320 for (const MDOperand &Option : drop_begin(FollowupNode->operands())) {
321 MDs.push_back(Option.get());
322 Changed = true;
323 }
324 }
325
326 // Attributes of the followup loop not specified explicity, so signal to the
327 // transformation pass to add suitable attributes.
328 if (!AlwaysNew && !HasAnyFollowup)
329 return std::nullopt;
330
331 // If no attributes were added or remove, the previous loop Id can be reused.
332 if (!AlwaysNew && !Changed)
333 return OrigLoopID;
334
335 // No attributes is equivalent to having no !llvm.loop metadata at all.
336 if (MDs.size() == 1)
337 return nullptr;
338
339 // Build the new loop ID.
340 MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
341 FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
342 return FollowupLoopID;
343 }
344
hasDisableAllTransformsHint(const Loop * L)345 bool llvm::hasDisableAllTransformsHint(const Loop *L) {
346 return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
347 }
348
hasDisableLICMTransformsHint(const Loop * L)349 bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
350 return getBooleanLoopAttribute(L, LLVMLoopDisableLICM);
351 }
352
hasUnrollTransformation(const Loop * L)353 TransformationMode llvm::hasUnrollTransformation(const Loop *L) {
354 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
355 return TM_SuppressedByUser;
356
357 std::optional<int> Count =
358 getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
359 if (Count)
360 return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
361
362 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
363 return TM_ForcedByUser;
364
365 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
366 return TM_ForcedByUser;
367
368 if (hasDisableAllTransformsHint(L))
369 return TM_Disable;
370
371 return TM_Unspecified;
372 }
373
hasUnrollAndJamTransformation(const Loop * L)374 TransformationMode llvm::hasUnrollAndJamTransformation(const Loop *L) {
375 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
376 return TM_SuppressedByUser;
377
378 std::optional<int> Count =
379 getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
380 if (Count)
381 return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
382
383 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
384 return TM_ForcedByUser;
385
386 if (hasDisableAllTransformsHint(L))
387 return TM_Disable;
388
389 return TM_Unspecified;
390 }
391
hasVectorizeTransformation(const Loop * L)392 TransformationMode llvm::hasVectorizeTransformation(const Loop *L) {
393 std::optional<bool> Enable =
394 getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
395
396 if (Enable == false)
397 return TM_SuppressedByUser;
398
399 std::optional<ElementCount> VectorizeWidth =
400 getOptionalElementCountLoopAttribute(L);
401 std::optional<int> InterleaveCount =
402 getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
403
404 // 'Forcing' vector width and interleave count to one effectively disables
405 // this tranformation.
406 if (Enable == true && VectorizeWidth && VectorizeWidth->isScalar() &&
407 InterleaveCount == 1)
408 return TM_SuppressedByUser;
409
410 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
411 return TM_Disable;
412
413 if (Enable == true)
414 return TM_ForcedByUser;
415
416 if ((VectorizeWidth && VectorizeWidth->isScalar()) && InterleaveCount == 1)
417 return TM_Disable;
418
419 if ((VectorizeWidth && VectorizeWidth->isVector()) || InterleaveCount > 1)
420 return TM_Enable;
421
422 if (hasDisableAllTransformsHint(L))
423 return TM_Disable;
424
425 return TM_Unspecified;
426 }
427
hasDistributeTransformation(const Loop * L)428 TransformationMode llvm::hasDistributeTransformation(const Loop *L) {
429 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
430 return TM_ForcedByUser;
431
432 if (hasDisableAllTransformsHint(L))
433 return TM_Disable;
434
435 return TM_Unspecified;
436 }
437
hasLICMVersioningTransformation(const Loop * L)438 TransformationMode llvm::hasLICMVersioningTransformation(const Loop *L) {
439 if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
440 return TM_SuppressedByUser;
441
442 if (hasDisableAllTransformsHint(L))
443 return TM_Disable;
444
445 return TM_Unspecified;
446 }
447
448 /// Does a BFS from a given node to all of its children inside a given loop.
449 /// The returned vector of basic blocks includes the starting point.
collectChildrenInLoop(DominatorTree * DT,DomTreeNode * N,const Loop * CurLoop)450 SmallVector<BasicBlock *, 16> llvm::collectChildrenInLoop(DominatorTree *DT,
451 DomTreeNode *N,
452 const Loop *CurLoop) {
453 SmallVector<BasicBlock *, 16> Worklist;
454 auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
455 // Only include subregions in the top level loop.
456 BasicBlock *BB = DTN->getBlock();
457 if (CurLoop->contains(BB))
458 Worklist.push_back(DTN->getBlock());
459 };
460
461 AddRegionToWorklist(N);
462
463 for (size_t I = 0; I < Worklist.size(); I++) {
464 for (DomTreeNode *Child : DT->getNode(Worklist[I])->children())
465 AddRegionToWorklist(Child);
466 }
467
468 return Worklist;
469 }
470
isAlmostDeadIV(PHINode * PN,BasicBlock * LatchBlock,Value * Cond)471 bool llvm::isAlmostDeadIV(PHINode *PN, BasicBlock *LatchBlock, Value *Cond) {
472 int LatchIdx = PN->getBasicBlockIndex(LatchBlock);
473 assert(LatchIdx != -1 && "LatchBlock is not a case in this PHINode");
474 Value *IncV = PN->getIncomingValue(LatchIdx);
475
476 for (User *U : PN->users())
477 if (U != Cond && U != IncV) return false;
478
479 for (User *U : IncV->users())
480 if (U != Cond && U != PN) return false;
481 return true;
482 }
483
484
deleteDeadLoop(Loop * L,DominatorTree * DT,ScalarEvolution * SE,LoopInfo * LI,MemorySSA * MSSA)485 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
486 LoopInfo *LI, MemorySSA *MSSA) {
487 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
488 auto *Preheader = L->getLoopPreheader();
489 assert(Preheader && "Preheader should exist!");
490
491 std::unique_ptr<MemorySSAUpdater> MSSAU;
492 if (MSSA)
493 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
494
495 // Now that we know the removal is safe, remove the loop by changing the
496 // branch from the preheader to go to the single exit block.
497 //
498 // Because we're deleting a large chunk of code at once, the sequence in which
499 // we remove things is very important to avoid invalidation issues.
500
501 // Tell ScalarEvolution that the loop is deleted. Do this before
502 // deleting the loop so that ScalarEvolution can look at the loop
503 // to determine what it needs to clean up.
504 if (SE) {
505 SE->forgetLoop(L);
506 SE->forgetBlockAndLoopDispositions();
507 }
508
509 Instruction *OldTerm = Preheader->getTerminator();
510 assert(!OldTerm->mayHaveSideEffects() &&
511 "Preheader must end with a side-effect-free terminator");
512 assert(OldTerm->getNumSuccessors() == 1 &&
513 "Preheader must have a single successor");
514 // Connect the preheader to the exit block. Keep the old edge to the header
515 // around to perform the dominator tree update in two separate steps
516 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
517 // preheader -> header.
518 //
519 //
520 // 0. Preheader 1. Preheader 2. Preheader
521 // | | | |
522 // V | V |
523 // Header <--\ | Header <--\ | Header <--\
524 // | | | | | | | | | | |
525 // | V | | | V | | | V |
526 // | Body --/ | | Body --/ | | Body --/
527 // V V V V V
528 // Exit Exit Exit
529 //
530 // By doing this is two separate steps we can perform the dominator tree
531 // update without using the batch update API.
532 //
533 // Even when the loop is never executed, we cannot remove the edge from the
534 // source block to the exit block. Consider the case where the unexecuted loop
535 // branches back to an outer loop. If we deleted the loop and removed the edge
536 // coming to this inner loop, this will break the outer loop structure (by
537 // deleting the backedge of the outer loop). If the outer loop is indeed a
538 // non-loop, it will be deleted in a future iteration of loop deletion pass.
539 IRBuilder<> Builder(OldTerm);
540
541 auto *ExitBlock = L->getUniqueExitBlock();
542 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
543 if (ExitBlock) {
544 assert(ExitBlock && "Should have a unique exit block!");
545 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
546
547 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
548 // Remove the old branch. The conditional branch becomes a new terminator.
549 OldTerm->eraseFromParent();
550
551 // Rewrite phis in the exit block to get their inputs from the Preheader
552 // instead of the exiting block.
553 for (PHINode &P : ExitBlock->phis()) {
554 // Set the zero'th element of Phi to be from the preheader and remove all
555 // other incoming values. Given the loop has dedicated exits, all other
556 // incoming values must be from the exiting blocks.
557 int PredIndex = 0;
558 P.setIncomingBlock(PredIndex, Preheader);
559 // Removes all incoming values from all other exiting blocks (including
560 // duplicate values from an exiting block).
561 // Nuke all entries except the zero'th entry which is the preheader entry.
562 P.removeIncomingValueIf([](unsigned Idx) { return Idx != 0; },
563 /* DeletePHIIfEmpty */ false);
564
565 assert((P.getNumIncomingValues() == 1 &&
566 P.getIncomingBlock(PredIndex) == Preheader) &&
567 "Should have exactly one value and that's from the preheader!");
568 }
569
570 if (DT) {
571 DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
572 if (MSSA) {
573 MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}},
574 *DT);
575 if (VerifyMemorySSA)
576 MSSA->verifyMemorySSA();
577 }
578 }
579
580 // Disconnect the loop body by branching directly to its exit.
581 Builder.SetInsertPoint(Preheader->getTerminator());
582 Builder.CreateBr(ExitBlock);
583 // Remove the old branch.
584 Preheader->getTerminator()->eraseFromParent();
585 } else {
586 assert(L->hasNoExitBlocks() &&
587 "Loop should have either zero or one exit blocks.");
588
589 Builder.SetInsertPoint(OldTerm);
590 Builder.CreateUnreachable();
591 Preheader->getTerminator()->eraseFromParent();
592 }
593
594 if (DT) {
595 DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
596 if (MSSA) {
597 MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}},
598 *DT);
599 SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
600 L->block_end());
601 MSSAU->removeBlocks(DeadBlockSet);
602 if (VerifyMemorySSA)
603 MSSA->verifyMemorySSA();
604 }
605 }
606
607 // Use a map to unique and a vector to guarantee deterministic ordering.
608 llvm::SmallDenseSet<DebugVariable, 4> DeadDebugSet;
609 llvm::SmallVector<DbgVariableRecord *, 4> DeadDbgVariableRecords;
610
611 if (ExitBlock) {
612 // Given LCSSA form is satisfied, we should not have users of instructions
613 // within the dead loop outside of the loop. However, LCSSA doesn't take
614 // unreachable uses into account. We handle them here.
615 // We could do it after drop all references (in this case all users in the
616 // loop will be already eliminated and we have less work to do but according
617 // to API doc of User::dropAllReferences only valid operation after dropping
618 // references, is deletion. So let's substitute all usages of
619 // instruction from the loop with poison value of corresponding type first.
620 for (auto *Block : L->blocks())
621 for (Instruction &I : *Block) {
622 auto *Poison = PoisonValue::get(I.getType());
623 for (Use &U : llvm::make_early_inc_range(I.uses())) {
624 if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
625 if (L->contains(Usr->getParent()))
626 continue;
627 // If we have a DT then we can check that uses outside a loop only in
628 // unreachable block.
629 if (DT)
630 assert(!DT->isReachableFromEntry(U) &&
631 "Unexpected user in reachable block");
632 U.set(Poison);
633 }
634
635 // For one of each variable encountered, preserve a debug record (set
636 // to Poison) and transfer it to the loop exit. This terminates any
637 // variable locations that were set during the loop.
638 for (DbgVariableRecord &DVR :
639 llvm::make_early_inc_range(filterDbgVars(I.getDbgRecordRange()))) {
640 DebugVariable Key(DVR.getVariable(), DVR.getExpression(),
641 DVR.getDebugLoc().get());
642 if (!DeadDebugSet.insert(Key).second)
643 continue;
644 // Unlinks the DVR from it's container, for later insertion.
645 DVR.removeFromParent();
646 DeadDbgVariableRecords.push_back(&DVR);
647 }
648 }
649
650 // After the loop has been deleted all the values defined and modified
651 // inside the loop are going to be unavailable. Values computed in the
652 // loop will have been deleted, automatically causing their debug uses
653 // be be replaced with undef. Loop invariant values will still be available.
654 // Move dbg.values out the loop so that earlier location ranges are still
655 // terminated and loop invariant assignments are preserved.
656 DIBuilder DIB(*ExitBlock->getModule());
657 BasicBlock::iterator InsertDbgValueBefore =
658 ExitBlock->getFirstInsertionPt();
659 assert(InsertDbgValueBefore != ExitBlock->end() &&
660 "There should be a non-PHI instruction in exit block, else these "
661 "instructions will have no parent.");
662
663 // Due to the "head" bit in BasicBlock::iterator, we're going to insert
664 // each DbgVariableRecord right at the start of the block, wheras dbg.values
665 // would be repeatedly inserted before the first instruction. To replicate
666 // this behaviour, do it backwards.
667 for (DbgVariableRecord *DVR : llvm::reverse(DeadDbgVariableRecords))
668 ExitBlock->insertDbgRecordBefore(DVR, InsertDbgValueBefore);
669 }
670
671 // Remove the block from the reference counting scheme, so that we can
672 // delete it freely later.
673 for (auto *Block : L->blocks())
674 Block->dropAllReferences();
675
676 if (MSSA && VerifyMemorySSA)
677 MSSA->verifyMemorySSA();
678
679 if (LI) {
680 // Erase the instructions and the blocks without having to worry
681 // about ordering because we already dropped the references.
682 // NOTE: This iteration is safe because erasing the block does not remove
683 // its entry from the loop's block list. We do that in the next section.
684 for (BasicBlock *BB : L->blocks())
685 BB->eraseFromParent();
686
687 // Finally, the blocks from loopinfo. This has to happen late because
688 // otherwise our loop iterators won't work.
689
690 SmallPtrSet<BasicBlock *, 8> blocks(llvm::from_range, L->blocks());
691 for (BasicBlock *BB : blocks)
692 LI->removeBlock(BB);
693
694 // The last step is to update LoopInfo now that we've eliminated this loop.
695 // Note: LoopInfo::erase remove the given loop and relink its subloops with
696 // its parent. While removeLoop/removeChildLoop remove the given loop but
697 // not relink its subloops, which is what we want.
698 if (Loop *ParentLoop = L->getParentLoop()) {
699 Loop::iterator I = find(*ParentLoop, L);
700 assert(I != ParentLoop->end() && "Couldn't find loop");
701 ParentLoop->removeChildLoop(I);
702 } else {
703 Loop::iterator I = find(*LI, L);
704 assert(I != LI->end() && "Couldn't find loop");
705 LI->removeLoop(I);
706 }
707 LI->destroy(L);
708 }
709 }
710
breakLoopBackedge(Loop * L,DominatorTree & DT,ScalarEvolution & SE,LoopInfo & LI,MemorySSA * MSSA)711 void llvm::breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
712 LoopInfo &LI, MemorySSA *MSSA) {
713 auto *Latch = L->getLoopLatch();
714 assert(Latch && "multiple latches not yet supported");
715 auto *Header = L->getHeader();
716 Loop *OutermostLoop = L->getOutermostLoop();
717
718 SE.forgetLoop(L);
719 SE.forgetBlockAndLoopDispositions();
720
721 std::unique_ptr<MemorySSAUpdater> MSSAU;
722 if (MSSA)
723 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
724
725 // Update the CFG and domtree. We chose to special case a couple of
726 // of common cases for code quality and test readability reasons.
727 [&]() -> void {
728 if (auto *BI = dyn_cast<BranchInst>(Latch->getTerminator())) {
729 if (!BI->isConditional()) {
730 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
731 (void)changeToUnreachable(BI, /*PreserveLCSSA*/ true, &DTU,
732 MSSAU.get());
733 return;
734 }
735
736 // Conditional latch/exit - note that latch can be shared by inner
737 // and outer loop so the other target doesn't need to an exit
738 if (L->isLoopExiting(Latch)) {
739 // TODO: Generalize ConstantFoldTerminator so that it can be used
740 // here without invalidating LCSSA or MemorySSA. (Tricky case for
741 // LCSSA: header is an exit block of a preceeding sibling loop w/o
742 // dedicated exits.)
743 const unsigned ExitIdx = L->contains(BI->getSuccessor(0)) ? 1 : 0;
744 BasicBlock *ExitBB = BI->getSuccessor(ExitIdx);
745
746 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
747 Header->removePredecessor(Latch, true);
748
749 IRBuilder<> Builder(BI);
750 auto *NewBI = Builder.CreateBr(ExitBB);
751 // Transfer the metadata to the new branch instruction (minus the
752 // loop info since this is no longer a loop)
753 NewBI->copyMetadata(*BI, {LLVMContext::MD_dbg,
754 LLVMContext::MD_annotation});
755
756 BI->eraseFromParent();
757 DTU.applyUpdates({{DominatorTree::Delete, Latch, Header}});
758 if (MSSA)
759 MSSAU->applyUpdates({{DominatorTree::Delete, Latch, Header}}, DT);
760 return;
761 }
762 }
763
764 // General case. By splitting the backedge, and then explicitly making it
765 // unreachable we gracefully handle corner cases such as switch and invoke
766 // termiantors.
767 auto *BackedgeBB = SplitEdge(Latch, Header, &DT, &LI, MSSAU.get());
768
769 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
770 (void)changeToUnreachable(BackedgeBB->getTerminator(),
771 /*PreserveLCSSA*/ true, &DTU, MSSAU.get());
772 }();
773
774 // Erase (and destroy) this loop instance. Handles relinking sub-loops
775 // and blocks within the loop as needed.
776 LI.erase(L);
777
778 // If the loop we broke had a parent, then changeToUnreachable might have
779 // caused a block to be removed from the parent loop (see loop_nest_lcssa
780 // test case in zero-btc.ll for an example), thus changing the parent's
781 // exit blocks. If that happened, we need to rebuild LCSSA on the outermost
782 // loop which might have a had a block removed.
783 if (OutermostLoop != L)
784 formLCSSARecursively(*OutermostLoop, DT, &LI, &SE);
785 }
786
787
788 /// Checks if \p L has an exiting latch branch. There may also be other
789 /// exiting blocks. Returns branch instruction terminating the loop
790 /// latch if above check is successful, nullptr otherwise.
getExpectedExitLoopLatchBranch(Loop * L)791 static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) {
792 BasicBlock *Latch = L->getLoopLatch();
793 if (!Latch)
794 return nullptr;
795
796 BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
797 if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
798 return nullptr;
799
800 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
801 LatchBR->getSuccessor(1) == L->getHeader()) &&
802 "At least one edge out of the latch must go to the header");
803
804 return LatchBR;
805 }
806
807 /// Return the estimated trip count for any exiting branch which dominates
808 /// the loop latch.
getEstimatedTripCount(BranchInst * ExitingBranch,Loop * L,uint64_t & OrigExitWeight)809 static std::optional<unsigned> getEstimatedTripCount(BranchInst *ExitingBranch,
810 Loop *L,
811 uint64_t &OrigExitWeight) {
812 // To estimate the number of times the loop body was executed, we want to
813 // know the number of times the backedge was taken, vs. the number of times
814 // we exited the loop.
815 uint64_t LoopWeight, ExitWeight;
816 if (!extractBranchWeights(*ExitingBranch, LoopWeight, ExitWeight))
817 return std::nullopt;
818
819 if (L->contains(ExitingBranch->getSuccessor(1)))
820 std::swap(LoopWeight, ExitWeight);
821
822 if (!ExitWeight)
823 // Don't have a way to return predicated infinite
824 return std::nullopt;
825
826 OrigExitWeight = ExitWeight;
827
828 // Estimated exit count is a ratio of the loop weight by the weight of the
829 // edge exiting the loop, rounded to nearest.
830 uint64_t ExitCount = llvm::divideNearest(LoopWeight, ExitWeight);
831
832 // When ExitCount + 1 would wrap in unsigned, saturate at UINT_MAX.
833 if (ExitCount >= std::numeric_limits<unsigned>::max())
834 return std::numeric_limits<unsigned>::max();
835
836 // Estimated trip count is one plus estimated exit count.
837 return ExitCount + 1;
838 }
839
840 std::optional<unsigned>
getLoopEstimatedTripCount(Loop * L,unsigned * EstimatedLoopInvocationWeight)841 llvm::getLoopEstimatedTripCount(Loop *L,
842 unsigned *EstimatedLoopInvocationWeight) {
843 // Currently we take the estimate exit count only from the loop latch,
844 // ignoring other exiting blocks. This can overestimate the trip count
845 // if we exit through another exit, but can never underestimate it.
846 // TODO: incorporate information from other exits
847 if (BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L)) {
848 uint64_t ExitWeight;
849 if (std::optional<uint64_t> EstTripCount =
850 getEstimatedTripCount(LatchBranch, L, ExitWeight)) {
851 if (EstimatedLoopInvocationWeight)
852 *EstimatedLoopInvocationWeight = ExitWeight;
853 return *EstTripCount;
854 }
855 }
856 return std::nullopt;
857 }
858
setLoopEstimatedTripCount(Loop * L,unsigned EstimatedTripCount,unsigned EstimatedloopInvocationWeight)859 bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
860 unsigned EstimatedloopInvocationWeight) {
861 // At the moment, we currently support changing the estimate trip count of
862 // the latch branch only. We could extend this API to manipulate estimated
863 // trip counts for any exit.
864 BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
865 if (!LatchBranch)
866 return false;
867
868 // Calculate taken and exit weights.
869 unsigned LatchExitWeight = 0;
870 unsigned BackedgeTakenWeight = 0;
871
872 if (EstimatedTripCount > 0) {
873 LatchExitWeight = EstimatedloopInvocationWeight;
874 BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
875 }
876
877 // Make a swap if back edge is taken when condition is "false".
878 if (LatchBranch->getSuccessor(0) != L->getHeader())
879 std::swap(BackedgeTakenWeight, LatchExitWeight);
880
881 MDBuilder MDB(LatchBranch->getContext());
882
883 // Set/Update profile metadata.
884 LatchBranch->setMetadata(
885 LLVMContext::MD_prof,
886 MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight));
887
888 return true;
889 }
890
hasIterationCountInvariantInParent(Loop * InnerLoop,ScalarEvolution & SE)891 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
892 ScalarEvolution &SE) {
893 Loop *OuterL = InnerLoop->getParentLoop();
894 if (!OuterL)
895 return true;
896
897 // Get the backedge taken count for the inner loop
898 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
899 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
900 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
901 !InnerLoopBECountSC->getType()->isIntegerTy())
902 return false;
903
904 // Get whether count is invariant to the outer loop
905 ScalarEvolution::LoopDisposition LD =
906 SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
907 if (LD != ScalarEvolution::LoopInvariant)
908 return false;
909
910 return true;
911 }
912
getReductionIntrinsicID(RecurKind RK)913 constexpr Intrinsic::ID llvm::getReductionIntrinsicID(RecurKind RK) {
914 switch (RK) {
915 default:
916 llvm_unreachable("Unexpected recurrence kind");
917 case RecurKind::Add:
918 return Intrinsic::vector_reduce_add;
919 case RecurKind::Mul:
920 return Intrinsic::vector_reduce_mul;
921 case RecurKind::And:
922 return Intrinsic::vector_reduce_and;
923 case RecurKind::Or:
924 return Intrinsic::vector_reduce_or;
925 case RecurKind::Xor:
926 return Intrinsic::vector_reduce_xor;
927 case RecurKind::FMulAdd:
928 case RecurKind::FAdd:
929 return Intrinsic::vector_reduce_fadd;
930 case RecurKind::FMul:
931 return Intrinsic::vector_reduce_fmul;
932 case RecurKind::SMax:
933 return Intrinsic::vector_reduce_smax;
934 case RecurKind::SMin:
935 return Intrinsic::vector_reduce_smin;
936 case RecurKind::UMax:
937 return Intrinsic::vector_reduce_umax;
938 case RecurKind::UMin:
939 return Intrinsic::vector_reduce_umin;
940 case RecurKind::FMax:
941 case RecurKind::FMaxNum:
942 return Intrinsic::vector_reduce_fmax;
943 case RecurKind::FMin:
944 case RecurKind::FMinNum:
945 return Intrinsic::vector_reduce_fmin;
946 case RecurKind::FMaximum:
947 return Intrinsic::vector_reduce_fmaximum;
948 case RecurKind::FMinimum:
949 return Intrinsic::vector_reduce_fminimum;
950 case RecurKind::FMaximumNum:
951 return Intrinsic::vector_reduce_fmax;
952 case RecurKind::FMinimumNum:
953 return Intrinsic::vector_reduce_fmin;
954 }
955 }
956
957 // This is the inverse to getReductionForBinop
getArithmeticReductionInstruction(Intrinsic::ID RdxID)958 unsigned llvm::getArithmeticReductionInstruction(Intrinsic::ID RdxID) {
959 switch (RdxID) {
960 case Intrinsic::vector_reduce_fadd:
961 return Instruction::FAdd;
962 case Intrinsic::vector_reduce_fmul:
963 return Instruction::FMul;
964 case Intrinsic::vector_reduce_add:
965 return Instruction::Add;
966 case Intrinsic::vector_reduce_mul:
967 return Instruction::Mul;
968 case Intrinsic::vector_reduce_and:
969 return Instruction::And;
970 case Intrinsic::vector_reduce_or:
971 return Instruction::Or;
972 case Intrinsic::vector_reduce_xor:
973 return Instruction::Xor;
974 case Intrinsic::vector_reduce_smax:
975 case Intrinsic::vector_reduce_smin:
976 case Intrinsic::vector_reduce_umax:
977 case Intrinsic::vector_reduce_umin:
978 return Instruction::ICmp;
979 case Intrinsic::vector_reduce_fmax:
980 case Intrinsic::vector_reduce_fmin:
981 return Instruction::FCmp;
982 default:
983 llvm_unreachable("Unexpected ID");
984 }
985 }
986
987 // This is the inverse to getArithmeticReductionInstruction
getReductionForBinop(Instruction::BinaryOps Opc)988 Intrinsic::ID llvm::getReductionForBinop(Instruction::BinaryOps Opc) {
989 switch (Opc) {
990 default:
991 break;
992 case Instruction::Add:
993 return Intrinsic::vector_reduce_add;
994 case Instruction::Mul:
995 return Intrinsic::vector_reduce_mul;
996 case Instruction::And:
997 return Intrinsic::vector_reduce_and;
998 case Instruction::Or:
999 return Intrinsic::vector_reduce_or;
1000 case Instruction::Xor:
1001 return Intrinsic::vector_reduce_xor;
1002 }
1003 return Intrinsic::not_intrinsic;
1004 }
1005
getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)1006 Intrinsic::ID llvm::getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID) {
1007 switch (RdxID) {
1008 default:
1009 llvm_unreachable("Unknown min/max recurrence kind");
1010 case Intrinsic::vector_reduce_umin:
1011 return Intrinsic::umin;
1012 case Intrinsic::vector_reduce_umax:
1013 return Intrinsic::umax;
1014 case Intrinsic::vector_reduce_smin:
1015 return Intrinsic::smin;
1016 case Intrinsic::vector_reduce_smax:
1017 return Intrinsic::smax;
1018 case Intrinsic::vector_reduce_fmin:
1019 return Intrinsic::minnum;
1020 case Intrinsic::vector_reduce_fmax:
1021 return Intrinsic::maxnum;
1022 case Intrinsic::vector_reduce_fminimum:
1023 return Intrinsic::minimum;
1024 case Intrinsic::vector_reduce_fmaximum:
1025 return Intrinsic::maximum;
1026 }
1027 }
1028
getMinMaxReductionIntrinsicOp(RecurKind RK)1029 Intrinsic::ID llvm::getMinMaxReductionIntrinsicOp(RecurKind RK) {
1030 switch (RK) {
1031 default:
1032 llvm_unreachable("Unknown min/max recurrence kind");
1033 case RecurKind::UMin:
1034 return Intrinsic::umin;
1035 case RecurKind::UMax:
1036 return Intrinsic::umax;
1037 case RecurKind::SMin:
1038 return Intrinsic::smin;
1039 case RecurKind::SMax:
1040 return Intrinsic::smax;
1041 case RecurKind::FMin:
1042 case RecurKind::FMinNum:
1043 return Intrinsic::minnum;
1044 case RecurKind::FMax:
1045 case RecurKind::FMaxNum:
1046 return Intrinsic::maxnum;
1047 case RecurKind::FMinimum:
1048 return Intrinsic::minimum;
1049 case RecurKind::FMaximum:
1050 return Intrinsic::maximum;
1051 case RecurKind::FMinimumNum:
1052 return Intrinsic::minimumnum;
1053 case RecurKind::FMaximumNum:
1054 return Intrinsic::maximumnum;
1055 }
1056 }
1057
getMinMaxReductionRecurKind(Intrinsic::ID RdxID)1058 RecurKind llvm::getMinMaxReductionRecurKind(Intrinsic::ID RdxID) {
1059 switch (RdxID) {
1060 case Intrinsic::vector_reduce_smax:
1061 return RecurKind::SMax;
1062 case Intrinsic::vector_reduce_smin:
1063 return RecurKind::SMin;
1064 case Intrinsic::vector_reduce_umax:
1065 return RecurKind::UMax;
1066 case Intrinsic::vector_reduce_umin:
1067 return RecurKind::UMin;
1068 case Intrinsic::vector_reduce_fmax:
1069 return RecurKind::FMax;
1070 case Intrinsic::vector_reduce_fmin:
1071 return RecurKind::FMin;
1072 default:
1073 return RecurKind::None;
1074 }
1075 }
1076
getMinMaxReductionPredicate(RecurKind RK)1077 CmpInst::Predicate llvm::getMinMaxReductionPredicate(RecurKind RK) {
1078 switch (RK) {
1079 default:
1080 llvm_unreachable("Unknown min/max recurrence kind");
1081 case RecurKind::UMin:
1082 return CmpInst::ICMP_ULT;
1083 case RecurKind::UMax:
1084 return CmpInst::ICMP_UGT;
1085 case RecurKind::SMin:
1086 return CmpInst::ICMP_SLT;
1087 case RecurKind::SMax:
1088 return CmpInst::ICMP_SGT;
1089 case RecurKind::FMin:
1090 return CmpInst::FCMP_OLT;
1091 case RecurKind::FMax:
1092 return CmpInst::FCMP_OGT;
1093 // We do not add FMinimum/FMaximum recurrence kind here since there is no
1094 // equivalent predicate which compares signed zeroes according to the
1095 // semantics of the intrinsics (llvm.minimum/maximum).
1096 }
1097 }
1098
createMinMaxOp(IRBuilderBase & Builder,RecurKind RK,Value * Left,Value * Right)1099 Value *llvm::createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left,
1100 Value *Right) {
1101 Type *Ty = Left->getType();
1102 if (Ty->isIntOrIntVectorTy() ||
1103 (RK == RecurKind::FMinNum || RK == RecurKind::FMaxNum ||
1104 RK == RecurKind::FMinimum || RK == RecurKind::FMaximum ||
1105 RK == RecurKind::FMinimumNum || RK == RecurKind::FMaximumNum)) {
1106 Intrinsic::ID Id = getMinMaxReductionIntrinsicOp(RK);
1107 return Builder.CreateIntrinsic(Ty, Id, {Left, Right}, nullptr,
1108 "rdx.minmax");
1109 }
1110 CmpInst::Predicate Pred = getMinMaxReductionPredicate(RK);
1111 Value *Cmp = Builder.CreateCmp(Pred, Left, Right, "rdx.minmax.cmp");
1112 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
1113 return Select;
1114 }
1115
1116 // Helper to generate an ordered reduction.
getOrderedReduction(IRBuilderBase & Builder,Value * Acc,Value * Src,unsigned Op,RecurKind RdxKind)1117 Value *llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
1118 unsigned Op, RecurKind RdxKind) {
1119 unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
1120
1121 // Extract and apply reduction ops in ascending order:
1122 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
1123 Value *Result = Acc;
1124 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
1125 Value *Ext =
1126 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
1127
1128 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1129 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
1130 "bin.rdx");
1131 } else {
1132 assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
1133 "Invalid min/max");
1134 Result = createMinMaxOp(Builder, RdxKind, Result, Ext);
1135 }
1136 }
1137
1138 return Result;
1139 }
1140
1141 // Helper to generate a log2 shuffle reduction.
getShuffleReduction(IRBuilderBase & Builder,Value * Src,unsigned Op,TargetTransformInfo::ReductionShuffle RS,RecurKind RdxKind)1142 Value *llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src,
1143 unsigned Op,
1144 TargetTransformInfo::ReductionShuffle RS,
1145 RecurKind RdxKind) {
1146 unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
1147 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1148 // and vector ops, reducing the set of values being computed by half each
1149 // round.
1150 assert(isPowerOf2_32(VF) &&
1151 "Reduction emission only supported for pow2 vectors!");
1152 // Note: fast-math-flags flags are controlled by the builder configuration
1153 // and are assumed to apply to all generated arithmetic instructions. Other
1154 // poison generating flags (nsw/nuw/inbounds/inrange/exact) are not part
1155 // of the builder configuration, and since they're not passed explicitly,
1156 // will never be relevant here. Note that it would be generally unsound to
1157 // propagate these from an intrinsic call to the expansion anyways as we/
1158 // change the order of operations.
1159 auto BuildShuffledOp = [&Builder, &Op,
1160 &RdxKind](SmallVectorImpl<int> &ShuffleMask,
1161 Value *&TmpVec) -> void {
1162 Value *Shuf = Builder.CreateShuffleVector(TmpVec, ShuffleMask, "rdx.shuf");
1163 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1164 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
1165 "bin.rdx");
1166 } else {
1167 assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
1168 "Invalid min/max");
1169 TmpVec = createMinMaxOp(Builder, RdxKind, TmpVec, Shuf);
1170 }
1171 };
1172
1173 Value *TmpVec = Src;
1174 if (TargetTransformInfo::ReductionShuffle::Pairwise == RS) {
1175 SmallVector<int, 32> ShuffleMask(VF);
1176 for (unsigned stride = 1; stride < VF; stride <<= 1) {
1177 // Initialise the mask with undef.
1178 llvm::fill(ShuffleMask, -1);
1179 for (unsigned j = 0; j < VF; j += stride << 1) {
1180 ShuffleMask[j] = j + stride;
1181 }
1182 BuildShuffledOp(ShuffleMask, TmpVec);
1183 }
1184 } else {
1185 SmallVector<int, 32> ShuffleMask(VF);
1186 for (unsigned i = VF; i != 1; i >>= 1) {
1187 // Move the upper half of the vector to the lower half.
1188 for (unsigned j = 0; j != i / 2; ++j)
1189 ShuffleMask[j] = i / 2 + j;
1190
1191 // Fill the rest of the mask with undef.
1192 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
1193 BuildShuffledOp(ShuffleMask, TmpVec);
1194 }
1195 }
1196 // The result is in the first element of the vector.
1197 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1198 }
1199
createAnyOfReduction(IRBuilderBase & Builder,Value * Src,Value * InitVal,PHINode * OrigPhi)1200 Value *llvm::createAnyOfReduction(IRBuilderBase &Builder, Value *Src,
1201 Value *InitVal, PHINode *OrigPhi) {
1202 Value *NewVal = nullptr;
1203
1204 // First use the original phi to determine the new value we're trying to
1205 // select from in the loop.
1206 SelectInst *SI = nullptr;
1207 for (auto *U : OrigPhi->users()) {
1208 if ((SI = dyn_cast<SelectInst>(U)))
1209 break;
1210 }
1211 assert(SI && "One user of the original phi should be a select");
1212
1213 if (SI->getTrueValue() == OrigPhi)
1214 NewVal = SI->getFalseValue();
1215 else {
1216 assert(SI->getFalseValue() == OrigPhi &&
1217 "At least one input to the select should be the original Phi");
1218 NewVal = SI->getTrueValue();
1219 }
1220
1221 // If any predicate is true it means that we want to select the new value.
1222 Value *AnyOf =
1223 Src->getType()->isVectorTy() ? Builder.CreateOrReduce(Src) : Src;
1224 // The compares in the loop may yield poison, which propagates through the
1225 // bitwise ORs. Freeze it here before the condition is used.
1226 AnyOf = Builder.CreateFreeze(AnyOf);
1227 return Builder.CreateSelect(AnyOf, NewVal, InitVal, "rdx.select");
1228 }
1229
createFindLastIVReduction(IRBuilderBase & Builder,Value * Src,RecurKind RdxKind,Value * Start,Value * Sentinel)1230 Value *llvm::createFindLastIVReduction(IRBuilderBase &Builder, Value *Src,
1231 RecurKind RdxKind, Value *Start,
1232 Value *Sentinel) {
1233 bool IsSigned = RecurrenceDescriptor::isSignedRecurrenceKind(RdxKind);
1234 bool IsMaxRdx = RecurrenceDescriptor::isFindLastIVRecurrenceKind(RdxKind);
1235 Value *MaxRdx = Src->getType()->isVectorTy()
1236 ? (IsMaxRdx ? Builder.CreateIntMaxReduce(Src, IsSigned)
1237 : Builder.CreateIntMinReduce(Src, IsSigned))
1238 : Src;
1239 // Correct the final reduction result back to the start value if the maximum
1240 // reduction is sentinel value.
1241 Value *Cmp =
1242 Builder.CreateCmp(CmpInst::ICMP_NE, MaxRdx, Sentinel, "rdx.select.cmp");
1243 return Builder.CreateSelect(Cmp, MaxRdx, Start, "rdx.select");
1244 }
1245
getReductionIdentity(Intrinsic::ID RdxID,Type * Ty,FastMathFlags Flags)1246 Value *llvm::getReductionIdentity(Intrinsic::ID RdxID, Type *Ty,
1247 FastMathFlags Flags) {
1248 bool Negative = false;
1249 switch (RdxID) {
1250 default:
1251 llvm_unreachable("Expecting a reduction intrinsic");
1252 case Intrinsic::vector_reduce_add:
1253 case Intrinsic::vector_reduce_mul:
1254 case Intrinsic::vector_reduce_or:
1255 case Intrinsic::vector_reduce_xor:
1256 case Intrinsic::vector_reduce_and:
1257 case Intrinsic::vector_reduce_fadd:
1258 case Intrinsic::vector_reduce_fmul: {
1259 unsigned Opc = getArithmeticReductionInstruction(RdxID);
1260 return ConstantExpr::getBinOpIdentity(Opc, Ty, false,
1261 Flags.noSignedZeros());
1262 }
1263 case Intrinsic::vector_reduce_umax:
1264 case Intrinsic::vector_reduce_umin:
1265 case Intrinsic::vector_reduce_smin:
1266 case Intrinsic::vector_reduce_smax: {
1267 Intrinsic::ID ScalarID = getMinMaxReductionIntrinsicOp(RdxID);
1268 return ConstantExpr::getIntrinsicIdentity(ScalarID, Ty);
1269 }
1270 case Intrinsic::vector_reduce_fmax:
1271 case Intrinsic::vector_reduce_fmaximum:
1272 Negative = true;
1273 [[fallthrough]];
1274 case Intrinsic::vector_reduce_fmin:
1275 case Intrinsic::vector_reduce_fminimum: {
1276 bool PropagatesNaN = RdxID == Intrinsic::vector_reduce_fminimum ||
1277 RdxID == Intrinsic::vector_reduce_fmaximum;
1278 const fltSemantics &Semantics = Ty->getFltSemantics();
1279 return (!Flags.noNaNs() && !PropagatesNaN)
1280 ? ConstantFP::getQNaN(Ty, Negative)
1281 : !Flags.noInfs()
1282 ? ConstantFP::getInfinity(Ty, Negative)
1283 : ConstantFP::get(Ty, APFloat::getLargest(Semantics, Negative));
1284 }
1285 }
1286 }
1287
getRecurrenceIdentity(RecurKind K,Type * Tp,FastMathFlags FMF)1288 Value *llvm::getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF) {
1289 assert((!(K == RecurKind::FMin || K == RecurKind::FMax) ||
1290 (FMF.noNaNs() && FMF.noSignedZeros())) &&
1291 "nnan, nsz is expected to be set for FP min/max reduction.");
1292 Intrinsic::ID RdxID = getReductionIntrinsicID(K);
1293 return getReductionIdentity(RdxID, Tp, FMF);
1294 }
1295
createSimpleReduction(IRBuilderBase & Builder,Value * Src,RecurKind RdxKind)1296 Value *llvm::createSimpleReduction(IRBuilderBase &Builder, Value *Src,
1297 RecurKind RdxKind) {
1298 auto *SrcVecEltTy = cast<VectorType>(Src->getType())->getElementType();
1299 auto getIdentity = [&]() {
1300 return getRecurrenceIdentity(RdxKind, SrcVecEltTy,
1301 Builder.getFastMathFlags());
1302 };
1303 switch (RdxKind) {
1304 case RecurKind::Add:
1305 case RecurKind::Mul:
1306 case RecurKind::And:
1307 case RecurKind::Or:
1308 case RecurKind::Xor:
1309 case RecurKind::SMax:
1310 case RecurKind::SMin:
1311 case RecurKind::UMax:
1312 case RecurKind::UMin:
1313 case RecurKind::FMax:
1314 case RecurKind::FMin:
1315 case RecurKind::FMinNum:
1316 case RecurKind::FMaxNum:
1317 case RecurKind::FMinimum:
1318 case RecurKind::FMaximum:
1319 case RecurKind::FMinimumNum:
1320 case RecurKind::FMaximumNum:
1321 return Builder.CreateUnaryIntrinsic(getReductionIntrinsicID(RdxKind), Src);
1322 case RecurKind::FMulAdd:
1323 case RecurKind::FAdd:
1324 return Builder.CreateFAddReduce(getIdentity(), Src);
1325 case RecurKind::FMul:
1326 return Builder.CreateFMulReduce(getIdentity(), Src);
1327 default:
1328 llvm_unreachable("Unhandled opcode");
1329 }
1330 }
1331
createSimpleReduction(IRBuilderBase & Builder,Value * Src,RecurKind Kind,Value * Mask,Value * EVL)1332 Value *llvm::createSimpleReduction(IRBuilderBase &Builder, Value *Src,
1333 RecurKind Kind, Value *Mask, Value *EVL) {
1334 assert(!RecurrenceDescriptor::isAnyOfRecurrenceKind(Kind) &&
1335 !RecurrenceDescriptor::isFindIVRecurrenceKind(Kind) &&
1336 "AnyOf and FindIV reductions are not supported.");
1337 Intrinsic::ID Id = getReductionIntrinsicID(Kind);
1338 auto VPID = VPIntrinsic::getForIntrinsic(Id);
1339 assert(VPReductionIntrinsic::isVPReduction(VPID) &&
1340 "No VPIntrinsic for this reduction");
1341 auto *EltTy = cast<VectorType>(Src->getType())->getElementType();
1342 Value *Iden = getRecurrenceIdentity(Kind, EltTy, Builder.getFastMathFlags());
1343 Value *Ops[] = {Iden, Src, Mask, EVL};
1344 return Builder.CreateIntrinsic(EltTy, VPID, Ops);
1345 }
1346
createOrderedReduction(IRBuilderBase & B,RecurKind Kind,Value * Src,Value * Start)1347 Value *llvm::createOrderedReduction(IRBuilderBase &B, RecurKind Kind,
1348 Value *Src, Value *Start) {
1349 assert((Kind == RecurKind::FAdd || Kind == RecurKind::FMulAdd) &&
1350 "Unexpected reduction kind");
1351 assert(Src->getType()->isVectorTy() && "Expected a vector type");
1352 assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
1353
1354 return B.CreateFAddReduce(Start, Src);
1355 }
1356
createOrderedReduction(IRBuilderBase & Builder,RecurKind Kind,Value * Src,Value * Start,Value * Mask,Value * EVL)1357 Value *llvm::createOrderedReduction(IRBuilderBase &Builder, RecurKind Kind,
1358 Value *Src, Value *Start, Value *Mask,
1359 Value *EVL) {
1360 assert((Kind == RecurKind::FAdd || Kind == RecurKind::FMulAdd) &&
1361 "Unexpected reduction kind");
1362 assert(Src->getType()->isVectorTy() && "Expected a vector type");
1363 assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
1364
1365 Intrinsic::ID Id = getReductionIntrinsicID(RecurKind::FAdd);
1366 auto VPID = VPIntrinsic::getForIntrinsic(Id);
1367 assert(VPReductionIntrinsic::isVPReduction(VPID) &&
1368 "No VPIntrinsic for this reduction");
1369 auto *EltTy = cast<VectorType>(Src->getType())->getElementType();
1370 Value *Ops[] = {Start, Src, Mask, EVL};
1371 return Builder.CreateIntrinsic(EltTy, VPID, Ops);
1372 }
1373
propagateIRFlags(Value * I,ArrayRef<Value * > VL,Value * OpValue,bool IncludeWrapFlags)1374 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue,
1375 bool IncludeWrapFlags) {
1376 auto *VecOp = dyn_cast<Instruction>(I);
1377 if (!VecOp)
1378 return;
1379 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1380 : dyn_cast<Instruction>(OpValue);
1381 if (!Intersection)
1382 return;
1383 const unsigned Opcode = Intersection->getOpcode();
1384 VecOp->copyIRFlags(Intersection, IncludeWrapFlags);
1385 for (auto *V : VL) {
1386 auto *Instr = dyn_cast<Instruction>(V);
1387 if (!Instr)
1388 continue;
1389 if (OpValue == nullptr || Opcode == Instr->getOpcode())
1390 VecOp->andIRFlags(V);
1391 }
1392 }
1393
isKnownNegativeInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE)1394 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1395 ScalarEvolution &SE) {
1396 const SCEV *Zero = SE.getZero(S->getType());
1397 return SE.isAvailableAtLoopEntry(S, L) &&
1398 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
1399 }
1400
isKnownNonNegativeInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE)1401 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1402 ScalarEvolution &SE) {
1403 const SCEV *Zero = SE.getZero(S->getType());
1404 return SE.isAvailableAtLoopEntry(S, L) &&
1405 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
1406 }
1407
isKnownPositiveInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE)1408 bool llvm::isKnownPositiveInLoop(const SCEV *S, const Loop *L,
1409 ScalarEvolution &SE) {
1410 const SCEV *Zero = SE.getZero(S->getType());
1411 return SE.isAvailableAtLoopEntry(S, L) &&
1412 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, S, Zero);
1413 }
1414
isKnownNonPositiveInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE)1415 bool llvm::isKnownNonPositiveInLoop(const SCEV *S, const Loop *L,
1416 ScalarEvolution &SE) {
1417 const SCEV *Zero = SE.getZero(S->getType());
1418 return SE.isAvailableAtLoopEntry(S, L) &&
1419 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLE, S, Zero);
1420 }
1421
cannotBeMinInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE,bool Signed)1422 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1423 bool Signed) {
1424 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1425 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
1426 APInt::getMinValue(BitWidth);
1427 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1428 return SE.isAvailableAtLoopEntry(S, L) &&
1429 SE.isLoopEntryGuardedByCond(L, Predicate, S,
1430 SE.getConstant(Min));
1431 }
1432
cannotBeMaxInLoop(const SCEV * S,const Loop * L,ScalarEvolution & SE,bool Signed)1433 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1434 bool Signed) {
1435 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1436 APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1437 APInt::getMaxValue(BitWidth);
1438 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1439 return SE.isAvailableAtLoopEntry(S, L) &&
1440 SE.isLoopEntryGuardedByCond(L, Predicate, S,
1441 SE.getConstant(Max));
1442 }
1443
1444 //===----------------------------------------------------------------------===//
1445 // rewriteLoopExitValues - Optimize IV users outside the loop.
1446 // As a side effect, reduces the amount of IV processing within the loop.
1447 //===----------------------------------------------------------------------===//
1448
hasHardUserWithinLoop(const Loop * L,const Instruction * I)1449 static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
1450 SmallPtrSet<const Instruction *, 8> Visited;
1451 SmallVector<const Instruction *, 8> WorkList;
1452 Visited.insert(I);
1453 WorkList.push_back(I);
1454 while (!WorkList.empty()) {
1455 const Instruction *Curr = WorkList.pop_back_val();
1456 // This use is outside the loop, nothing to do.
1457 if (!L->contains(Curr))
1458 continue;
1459 // Do we assume it is a "hard" use which will not be eliminated easily?
1460 if (Curr->mayHaveSideEffects())
1461 return true;
1462 // Otherwise, add all its users to worklist.
1463 for (const auto *U : Curr->users()) {
1464 auto *UI = cast<Instruction>(U);
1465 if (Visited.insert(UI).second)
1466 WorkList.push_back(UI);
1467 }
1468 }
1469 return false;
1470 }
1471
1472 // Collect information about PHI nodes which can be transformed in
1473 // rewriteLoopExitValues.
1474 struct RewritePhi {
1475 PHINode *PN; // For which PHI node is this replacement?
1476 unsigned Ith; // For which incoming value?
1477 const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting.
1478 Instruction *ExpansionPoint; // Where we'd like to expand that SCEV?
1479 bool HighCost; // Is this expansion a high-cost?
1480
RewritePhiRewritePhi1481 RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt,
1482 bool H)
1483 : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt),
1484 HighCost(H) {}
1485 };
1486
1487 // Check whether it is possible to delete the loop after rewriting exit
1488 // value. If it is possible, ignore ReplaceExitValue and do rewriting
1489 // aggressively.
canLoopBeDeleted(Loop * L,SmallVector<RewritePhi,8> & RewritePhiSet)1490 static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
1491 BasicBlock *Preheader = L->getLoopPreheader();
1492 // If there is no preheader, the loop will not be deleted.
1493 if (!Preheader)
1494 return false;
1495
1496 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
1497 // We obviate multiple ExitingBlocks case for simplicity.
1498 // TODO: If we see testcase with multiple ExitingBlocks can be deleted
1499 // after exit value rewriting, we can enhance the logic here.
1500 SmallVector<BasicBlock *, 4> ExitingBlocks;
1501 L->getExitingBlocks(ExitingBlocks);
1502 SmallVector<BasicBlock *, 8> ExitBlocks;
1503 L->getUniqueExitBlocks(ExitBlocks);
1504 if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
1505 return false;
1506
1507 BasicBlock *ExitBlock = ExitBlocks[0];
1508 BasicBlock::iterator BI = ExitBlock->begin();
1509 while (PHINode *P = dyn_cast<PHINode>(BI)) {
1510 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
1511
1512 // If the Incoming value of P is found in RewritePhiSet, we know it
1513 // could be rewritten to use a loop invariant value in transformation
1514 // phase later. Skip it in the loop invariant check below.
1515 bool found = false;
1516 for (const RewritePhi &Phi : RewritePhiSet) {
1517 unsigned i = Phi.Ith;
1518 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
1519 found = true;
1520 break;
1521 }
1522 }
1523
1524 Instruction *I;
1525 if (!found && (I = dyn_cast<Instruction>(Incoming)))
1526 if (!L->hasLoopInvariantOperands(I))
1527 return false;
1528
1529 ++BI;
1530 }
1531
1532 for (auto *BB : L->blocks())
1533 if (llvm::any_of(*BB, [](Instruction &I) {
1534 return I.mayHaveSideEffects();
1535 }))
1536 return false;
1537
1538 return true;
1539 }
1540
1541 /// Checks if it is safe to call InductionDescriptor::isInductionPHI for \p Phi,
1542 /// and returns true if this Phi is an induction phi in the loop. When
1543 /// isInductionPHI returns true, \p ID will be also be set by isInductionPHI.
checkIsIndPhi(PHINode * Phi,Loop * L,ScalarEvolution * SE,InductionDescriptor & ID)1544 static bool checkIsIndPhi(PHINode *Phi, Loop *L, ScalarEvolution *SE,
1545 InductionDescriptor &ID) {
1546 if (!Phi)
1547 return false;
1548 if (!L->getLoopPreheader())
1549 return false;
1550 if (Phi->getParent() != L->getHeader())
1551 return false;
1552 return InductionDescriptor::isInductionPHI(Phi, L, SE, ID);
1553 }
1554
rewriteLoopExitValues(Loop * L,LoopInfo * LI,TargetLibraryInfo * TLI,ScalarEvolution * SE,const TargetTransformInfo * TTI,SCEVExpander & Rewriter,DominatorTree * DT,ReplaceExitVal ReplaceExitValue,SmallVector<WeakTrackingVH,16> & DeadInsts)1555 int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
1556 ScalarEvolution *SE,
1557 const TargetTransformInfo *TTI,
1558 SCEVExpander &Rewriter, DominatorTree *DT,
1559 ReplaceExitVal ReplaceExitValue,
1560 SmallVector<WeakTrackingVH, 16> &DeadInsts) {
1561 // Check a pre-condition.
1562 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
1563 "Indvars did not preserve LCSSA!");
1564
1565 SmallVector<BasicBlock*, 8> ExitBlocks;
1566 L->getUniqueExitBlocks(ExitBlocks);
1567
1568 SmallVector<RewritePhi, 8> RewritePhiSet;
1569 // Find all values that are computed inside the loop, but used outside of it.
1570 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
1571 // the exit blocks of the loop to find them.
1572 for (BasicBlock *ExitBB : ExitBlocks) {
1573 // If there are no PHI nodes in this exit block, then no values defined
1574 // inside the loop are used on this path, skip it.
1575 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
1576 if (!PN) continue;
1577
1578 unsigned NumPreds = PN->getNumIncomingValues();
1579
1580 // Iterate over all of the PHI nodes.
1581 BasicBlock::iterator BBI = ExitBB->begin();
1582 while ((PN = dyn_cast<PHINode>(BBI++))) {
1583 if (PN->use_empty())
1584 continue; // dead use, don't replace it
1585
1586 if (!SE->isSCEVable(PN->getType()))
1587 continue;
1588
1589 // Iterate over all of the values in all the PHI nodes.
1590 for (unsigned i = 0; i != NumPreds; ++i) {
1591 // If the value being merged in is not integer or is not defined
1592 // in the loop, skip it.
1593 Value *InVal = PN->getIncomingValue(i);
1594 if (!isa<Instruction>(InVal))
1595 continue;
1596
1597 // If this pred is for a subloop, not L itself, skip it.
1598 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
1599 continue; // The Block is in a subloop, skip it.
1600
1601 // Check that InVal is defined in the loop.
1602 Instruction *Inst = cast<Instruction>(InVal);
1603 if (!L->contains(Inst))
1604 continue;
1605
1606 // Find exit values which are induction variables in the loop, and are
1607 // unused in the loop, with the only use being the exit block PhiNode,
1608 // and the induction variable update binary operator.
1609 // The exit value can be replaced with the final value when it is cheap
1610 // to do so.
1611 if (ReplaceExitValue == UnusedIndVarInLoop) {
1612 InductionDescriptor ID;
1613 PHINode *IndPhi = dyn_cast<PHINode>(Inst);
1614 if (IndPhi) {
1615 if (!checkIsIndPhi(IndPhi, L, SE, ID))
1616 continue;
1617 // This is an induction PHI. Check that the only users are PHI
1618 // nodes, and induction variable update binary operators.
1619 if (llvm::any_of(Inst->users(), [&](User *U) {
1620 if (!isa<PHINode>(U) && !isa<BinaryOperator>(U))
1621 return true;
1622 BinaryOperator *B = dyn_cast<BinaryOperator>(U);
1623 if (B && B != ID.getInductionBinOp())
1624 return true;
1625 return false;
1626 }))
1627 continue;
1628 } else {
1629 // If it is not an induction phi, it must be an induction update
1630 // binary operator with an induction phi user.
1631 BinaryOperator *B = dyn_cast<BinaryOperator>(Inst);
1632 if (!B)
1633 continue;
1634 if (llvm::any_of(Inst->users(), [&](User *U) {
1635 PHINode *Phi = dyn_cast<PHINode>(U);
1636 if (Phi != PN && !checkIsIndPhi(Phi, L, SE, ID))
1637 return true;
1638 return false;
1639 }))
1640 continue;
1641 if (B != ID.getInductionBinOp())
1642 continue;
1643 }
1644 }
1645
1646 // Okay, this instruction has a user outside of the current loop
1647 // and varies predictably *inside* the loop. Evaluate the value it
1648 // contains when the loop exits, if possible. We prefer to start with
1649 // expressions which are true for all exits (so as to maximize
1650 // expression reuse by the SCEVExpander), but resort to per-exit
1651 // evaluation if that fails.
1652 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
1653 if (isa<SCEVCouldNotCompute>(ExitValue) ||
1654 !SE->isLoopInvariant(ExitValue, L) ||
1655 !Rewriter.isSafeToExpand(ExitValue)) {
1656 // TODO: This should probably be sunk into SCEV in some way; maybe a
1657 // getSCEVForExit(SCEV*, L, ExitingBB)? It can be generalized for
1658 // most SCEV expressions and other recurrence types (e.g. shift
1659 // recurrences). Is there existing code we can reuse?
1660 const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
1661 if (isa<SCEVCouldNotCompute>(ExitCount))
1662 continue;
1663 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
1664 if (AddRec->getLoop() == L)
1665 ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
1666 if (isa<SCEVCouldNotCompute>(ExitValue) ||
1667 !SE->isLoopInvariant(ExitValue, L) ||
1668 !Rewriter.isSafeToExpand(ExitValue))
1669 continue;
1670 }
1671
1672 // Computing the value outside of the loop brings no benefit if it is
1673 // definitely used inside the loop in a way which can not be optimized
1674 // away. Avoid doing so unless we know we have a value which computes
1675 // the ExitValue already. TODO: This should be merged into SCEV
1676 // expander to leverage its knowledge of existing expressions.
1677 if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
1678 !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
1679 continue;
1680
1681 // Check if expansions of this SCEV would count as being high cost.
1682 bool HighCost = Rewriter.isHighCostExpansion(
1683 ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst);
1684
1685 // Note that we must not perform expansions until after
1686 // we query *all* the costs, because if we perform temporary expansion
1687 // inbetween, one that we might not intend to keep, said expansion
1688 // *may* affect cost calculation of the next SCEV's we'll query,
1689 // and next SCEV may errneously get smaller cost.
1690
1691 // Collect all the candidate PHINodes to be rewritten.
1692 Instruction *InsertPt =
1693 (isa<PHINode>(Inst) || isa<LandingPadInst>(Inst)) ?
1694 &*Inst->getParent()->getFirstInsertionPt() : Inst;
1695 RewritePhiSet.emplace_back(PN, i, ExitValue, InsertPt, HighCost);
1696 }
1697 }
1698 }
1699
1700 // TODO: evaluate whether it is beneficial to change how we calculate
1701 // high-cost: if we have SCEV 'A' which we know we will expand, should we
1702 // calculate the cost of other SCEV's after expanding SCEV 'A', thus
1703 // potentially giving cost bonus to those other SCEV's?
1704
1705 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
1706 int NumReplaced = 0;
1707
1708 // Transformation.
1709 for (const RewritePhi &Phi : RewritePhiSet) {
1710 PHINode *PN = Phi.PN;
1711
1712 // Only do the rewrite when the ExitValue can be expanded cheaply.
1713 // If LoopCanBeDel is true, rewrite exit value aggressively.
1714 if ((ReplaceExitValue == OnlyCheapRepl ||
1715 ReplaceExitValue == UnusedIndVarInLoop) &&
1716 !LoopCanBeDel && Phi.HighCost)
1717 continue;
1718
1719 Value *ExitVal = Rewriter.expandCodeFor(
1720 Phi.ExpansionSCEV, Phi.PN->getType(), Phi.ExpansionPoint);
1721
1722 LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " << *ExitVal
1723 << '\n'
1724 << " LoopVal = " << *(Phi.ExpansionPoint) << "\n");
1725
1726 #ifndef NDEBUG
1727 // If we reuse an instruction from a loop which is neither L nor one of
1728 // its containing loops, we end up breaking LCSSA form for this loop by
1729 // creating a new use of its instruction.
1730 if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
1731 if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
1732 if (EVL != L)
1733 assert(EVL->contains(L) && "LCSSA breach detected!");
1734 #endif
1735
1736 NumReplaced++;
1737 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
1738 PN->setIncomingValue(Phi.Ith, ExitVal);
1739 // It's necessary to tell ScalarEvolution about this explicitly so that
1740 // it can walk the def-use list and forget all SCEVs, as it may not be
1741 // watching the PHI itself. Once the new exit value is in place, there
1742 // may not be a def-use connection between the loop and every instruction
1743 // which got a SCEVAddRecExpr for that loop.
1744 SE->forgetValue(PN);
1745
1746 // If this instruction is dead now, delete it. Don't do it now to avoid
1747 // invalidating iterators.
1748 if (isInstructionTriviallyDead(Inst, TLI))
1749 DeadInsts.push_back(Inst);
1750
1751 // Replace PN with ExitVal if that is legal and does not break LCSSA.
1752 if (PN->getNumIncomingValues() == 1 &&
1753 LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
1754 PN->replaceAllUsesWith(ExitVal);
1755 PN->eraseFromParent();
1756 }
1757 }
1758
1759 // The insertion point instruction may have been deleted; clear it out
1760 // so that the rewriter doesn't trip over it later.
1761 Rewriter.clearInsertPoint();
1762 return NumReplaced;
1763 }
1764
1765 /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
1766 /// \p OrigLoop.
setProfileInfoAfterUnrolling(Loop * OrigLoop,Loop * UnrolledLoop,Loop * RemainderLoop,uint64_t UF)1767 void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
1768 Loop *RemainderLoop, uint64_t UF) {
1769 assert(UF > 0 && "Zero unrolled factor is not supported");
1770 assert(UnrolledLoop != RemainderLoop &&
1771 "Unrolled and Remainder loops are expected to distinct");
1772
1773 // Get number of iterations in the original scalar loop.
1774 unsigned OrigLoopInvocationWeight = 0;
1775 std::optional<unsigned> OrigAverageTripCount =
1776 getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
1777 if (!OrigAverageTripCount)
1778 return;
1779
1780 // Calculate number of iterations in unrolled loop.
1781 unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF;
1782 // Calculate number of iterations for remainder loop.
1783 unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF;
1784
1785 setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount,
1786 OrigLoopInvocationWeight);
1787 setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount,
1788 OrigLoopInvocationWeight);
1789 }
1790
1791 /// Utility that implements appending of loops onto a worklist.
1792 /// Loops are added in preorder (analogous for reverse postorder for trees),
1793 /// and the worklist is processed LIFO.
1794 template <typename RangeT>
appendReversedLoopsToWorklist(RangeT && Loops,SmallPriorityWorklist<Loop *,4> & Worklist)1795 void llvm::appendReversedLoopsToWorklist(
1796 RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
1797 // We use an internal worklist to build up the preorder traversal without
1798 // recursion.
1799 SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1800
1801 // We walk the initial sequence of loops in reverse because we generally want
1802 // to visit defs before uses and the worklist is LIFO.
1803 for (Loop *RootL : Loops) {
1804 assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1805 assert(PreOrderWorklist.empty() &&
1806 "Must start with an empty preorder walk worklist.");
1807 PreOrderWorklist.push_back(RootL);
1808 do {
1809 Loop *L = PreOrderWorklist.pop_back_val();
1810 PreOrderWorklist.append(L->begin(), L->end());
1811 PreOrderLoops.push_back(L);
1812 } while (!PreOrderWorklist.empty());
1813
1814 Worklist.insert(std::move(PreOrderLoops));
1815 PreOrderLoops.clear();
1816 }
1817 }
1818
1819 template <typename RangeT>
appendLoopsToWorklist(RangeT && Loops,SmallPriorityWorklist<Loop *,4> & Worklist)1820 void llvm::appendLoopsToWorklist(RangeT &&Loops,
1821 SmallPriorityWorklist<Loop *, 4> &Worklist) {
1822 appendReversedLoopsToWorklist(reverse(Loops), Worklist);
1823 }
1824
1825 template LLVM_EXPORT_TEMPLATE void
1826 llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>(
1827 ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist);
1828
1829 template LLVM_EXPORT_TEMPLATE void
1830 llvm::appendLoopsToWorklist<Loop &>(Loop &L,
1831 SmallPriorityWorklist<Loop *, 4> &Worklist);
1832
appendLoopsToWorklist(LoopInfo & LI,SmallPriorityWorklist<Loop *,4> & Worklist)1833 void llvm::appendLoopsToWorklist(LoopInfo &LI,
1834 SmallPriorityWorklist<Loop *, 4> &Worklist) {
1835 appendReversedLoopsToWorklist(LI, Worklist);
1836 }
1837
cloneLoop(Loop * L,Loop * PL,ValueToValueMapTy & VM,LoopInfo * LI,LPPassManager * LPM)1838 Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
1839 LoopInfo *LI, LPPassManager *LPM) {
1840 Loop &New = *LI->AllocateLoop();
1841 if (PL)
1842 PL->addChildLoop(&New);
1843 else
1844 LI->addTopLevelLoop(&New);
1845
1846 if (LPM)
1847 LPM->addLoop(New);
1848
1849 // Add all of the blocks in L to the new loop.
1850 for (BasicBlock *BB : L->blocks())
1851 if (LI->getLoopFor(BB) == L)
1852 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), *LI);
1853
1854 // Add all of the subloops to the new loop.
1855 for (Loop *I : *L)
1856 cloneLoop(I, &New, VM, LI, LPM);
1857
1858 return &New;
1859 }
1860
1861 /// IR Values for the lower and upper bounds of a pointer evolution. We
1862 /// need to use value-handles because SCEV expansion can invalidate previously
1863 /// expanded values. Thus expansion of a pointer can invalidate the bounds for
1864 /// a previous one.
1865 struct PointerBounds {
1866 TrackingVH<Value> Start;
1867 TrackingVH<Value> End;
1868 Value *StrideToCheck;
1869 };
1870
1871 /// Expand code for the lower and upper bound of the pointer group \p CG
1872 /// in \p TheLoop. \return the values for the bounds.
expandBounds(const RuntimeCheckingPtrGroup * CG,Loop * TheLoop,Instruction * Loc,SCEVExpander & Exp,bool HoistRuntimeChecks)1873 static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG,
1874 Loop *TheLoop, Instruction *Loc,
1875 SCEVExpander &Exp, bool HoistRuntimeChecks) {
1876 LLVMContext &Ctx = Loc->getContext();
1877 Type *PtrArithTy = PointerType::get(Ctx, CG->AddressSpace);
1878
1879 Value *Start = nullptr, *End = nullptr;
1880 LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1881 const SCEV *Low = CG->Low, *High = CG->High, *Stride = nullptr;
1882
1883 // If the Low and High values are themselves loop-variant, then we may want
1884 // to expand the range to include those covered by the outer loop as well.
1885 // There is a trade-off here with the advantage being that creating checks
1886 // using the expanded range permits the runtime memory checks to be hoisted
1887 // out of the outer loop. This reduces the cost of entering the inner loop,
1888 // which can be significant for low trip counts. The disadvantage is that
1889 // there is a chance we may now never enter the vectorized inner loop,
1890 // whereas using a restricted range check could have allowed us to enter at
1891 // least once. This is why the behaviour is not currently the default and is
1892 // controlled by the parameter 'HoistRuntimeChecks'.
1893 if (HoistRuntimeChecks && TheLoop->getParentLoop() &&
1894 isa<SCEVAddRecExpr>(High) && isa<SCEVAddRecExpr>(Low)) {
1895 auto *HighAR = cast<SCEVAddRecExpr>(High);
1896 auto *LowAR = cast<SCEVAddRecExpr>(Low);
1897 const Loop *OuterLoop = TheLoop->getParentLoop();
1898 ScalarEvolution &SE = *Exp.getSE();
1899 const SCEV *Recur = LowAR->getStepRecurrence(SE);
1900 if (Recur == HighAR->getStepRecurrence(SE) &&
1901 HighAR->getLoop() == OuterLoop && LowAR->getLoop() == OuterLoop) {
1902 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1903 const SCEV *OuterExitCount = SE.getExitCount(OuterLoop, OuterLoopLatch);
1904 if (!isa<SCEVCouldNotCompute>(OuterExitCount) &&
1905 OuterExitCount->getType()->isIntegerTy()) {
1906 const SCEV *NewHigh =
1907 cast<SCEVAddRecExpr>(High)->evaluateAtIteration(OuterExitCount, SE);
1908 if (!isa<SCEVCouldNotCompute>(NewHigh)) {
1909 LLVM_DEBUG(dbgs() << "LAA: Expanded RT check for range to include "
1910 "outer loop in order to permit hoisting\n");
1911 High = NewHigh;
1912 Low = cast<SCEVAddRecExpr>(Low)->getStart();
1913 // If there is a possibility that the stride is negative then we have
1914 // to generate extra checks to ensure the stride is positive.
1915 if (!SE.isKnownNonNegative(
1916 SE.applyLoopGuards(Recur, HighAR->getLoop()))) {
1917 Stride = Recur;
1918 LLVM_DEBUG(dbgs() << "LAA: ... but need to check stride is "
1919 "positive: "
1920 << *Stride << '\n');
1921 }
1922 }
1923 }
1924 }
1925 }
1926
1927 Start = Exp.expandCodeFor(Low, PtrArithTy, Loc);
1928 End = Exp.expandCodeFor(High, PtrArithTy, Loc);
1929 if (CG->NeedsFreeze) {
1930 IRBuilder<> Builder(Loc);
1931 Start = Builder.CreateFreeze(Start, Start->getName() + ".fr");
1932 End = Builder.CreateFreeze(End, End->getName() + ".fr");
1933 }
1934 Value *StrideVal =
1935 Stride ? Exp.expandCodeFor(Stride, Stride->getType(), Loc) : nullptr;
1936 LLVM_DEBUG(dbgs() << "Start: " << *Low << " End: " << *High << "\n");
1937 return {Start, End, StrideVal};
1938 }
1939
1940 /// Turns a collection of checks into a collection of expanded upper and
1941 /// lower bounds for both pointers in the check.
1942 static SmallVector<std::pair<PointerBounds, PointerBounds>, 4>
expandBounds(const SmallVectorImpl<RuntimePointerCheck> & PointerChecks,Loop * L,Instruction * Loc,SCEVExpander & Exp,bool HoistRuntimeChecks)1943 expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L,
1944 Instruction *Loc, SCEVExpander &Exp, bool HoistRuntimeChecks) {
1945 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1946
1947 // Here we're relying on the SCEV Expander's cache to only emit code for the
1948 // same bounds once.
1949 transform(PointerChecks, std::back_inserter(ChecksWithBounds),
1950 [&](const RuntimePointerCheck &Check) {
1951 PointerBounds First = expandBounds(Check.first, L, Loc, Exp,
1952 HoistRuntimeChecks),
1953 Second = expandBounds(Check.second, L, Loc, Exp,
1954 HoistRuntimeChecks);
1955 return std::make_pair(First, Second);
1956 });
1957
1958 return ChecksWithBounds;
1959 }
1960
addRuntimeChecks(Instruction * Loc,Loop * TheLoop,const SmallVectorImpl<RuntimePointerCheck> & PointerChecks,SCEVExpander & Exp,bool HoistRuntimeChecks)1961 Value *llvm::addRuntimeChecks(
1962 Instruction *Loc, Loop *TheLoop,
1963 const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
1964 SCEVExpander &Exp, bool HoistRuntimeChecks) {
1965 // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible.
1966 // TODO: Pass RtPtrChecking instead of PointerChecks and SE separately, if possible
1967 auto ExpandedChecks =
1968 expandBounds(PointerChecks, TheLoop, Loc, Exp, HoistRuntimeChecks);
1969
1970 LLVMContext &Ctx = Loc->getContext();
1971 IRBuilder ChkBuilder(Ctx, InstSimplifyFolder(Loc->getDataLayout()));
1972 ChkBuilder.SetInsertPoint(Loc);
1973 // Our instructions might fold to a constant.
1974 Value *MemoryRuntimeCheck = nullptr;
1975
1976 for (const auto &[A, B] : ExpandedChecks) {
1977 // Check if two pointers (A and B) conflict where conflict is computed as:
1978 // start(A) <= end(B) && start(B) <= end(A)
1979
1980 assert((A.Start->getType()->getPointerAddressSpace() ==
1981 B.End->getType()->getPointerAddressSpace()) &&
1982 (B.Start->getType()->getPointerAddressSpace() ==
1983 A.End->getType()->getPointerAddressSpace()) &&
1984 "Trying to bounds check pointers with different address spaces");
1985
1986 // [A|B].Start points to the first accessed byte under base [A|B].
1987 // [A|B].End points to the last accessed byte, plus one.
1988 // There is no conflict when the intervals are disjoint:
1989 // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
1990 //
1991 // bound0 = (B.Start < A.End)
1992 // bound1 = (A.Start < B.End)
1993 // IsConflict = bound0 & bound1
1994 Value *Cmp0 = ChkBuilder.CreateICmpULT(A.Start, B.End, "bound0");
1995 Value *Cmp1 = ChkBuilder.CreateICmpULT(B.Start, A.End, "bound1");
1996 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1997 if (A.StrideToCheck) {
1998 Value *IsNegativeStride = ChkBuilder.CreateICmpSLT(
1999 A.StrideToCheck, ConstantInt::get(A.StrideToCheck->getType(), 0),
2000 "stride.check");
2001 IsConflict = ChkBuilder.CreateOr(IsConflict, IsNegativeStride);
2002 }
2003 if (B.StrideToCheck) {
2004 Value *IsNegativeStride = ChkBuilder.CreateICmpSLT(
2005 B.StrideToCheck, ConstantInt::get(B.StrideToCheck->getType(), 0),
2006 "stride.check");
2007 IsConflict = ChkBuilder.CreateOr(IsConflict, IsNegativeStride);
2008 }
2009 if (MemoryRuntimeCheck) {
2010 IsConflict =
2011 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
2012 }
2013 MemoryRuntimeCheck = IsConflict;
2014 }
2015
2016 return MemoryRuntimeCheck;
2017 }
2018
addDiffRuntimeChecks(Instruction * Loc,ArrayRef<PointerDiffInfo> Checks,SCEVExpander & Expander,function_ref<Value * (IRBuilderBase &,unsigned)> GetVF,unsigned IC)2019 Value *llvm::addDiffRuntimeChecks(
2020 Instruction *Loc, ArrayRef<PointerDiffInfo> Checks, SCEVExpander &Expander,
2021 function_ref<Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC) {
2022
2023 LLVMContext &Ctx = Loc->getContext();
2024 IRBuilder ChkBuilder(Ctx, InstSimplifyFolder(Loc->getDataLayout()));
2025 ChkBuilder.SetInsertPoint(Loc);
2026 // Our instructions might fold to a constant.
2027 Value *MemoryRuntimeCheck = nullptr;
2028
2029 auto &SE = *Expander.getSE();
2030 // Map to keep track of created compares, The key is the pair of operands for
2031 // the compare, to allow detecting and re-using redundant compares.
2032 DenseMap<std::pair<Value *, Value *>, Value *> SeenCompares;
2033 for (const auto &[SrcStart, SinkStart, AccessSize, NeedsFreeze] : Checks) {
2034 Type *Ty = SinkStart->getType();
2035 // Compute VF * IC * AccessSize.
2036 auto *VFTimesICTimesSize =
2037 ChkBuilder.CreateMul(GetVF(ChkBuilder, Ty->getScalarSizeInBits()),
2038 ConstantInt::get(Ty, IC * AccessSize));
2039 Value *Diff =
2040 Expander.expandCodeFor(SE.getMinusSCEV(SinkStart, SrcStart), Ty, Loc);
2041
2042 // Check if the same compare has already been created earlier. In that case,
2043 // there is no need to check it again.
2044 Value *IsConflict = SeenCompares.lookup({Diff, VFTimesICTimesSize});
2045 if (IsConflict)
2046 continue;
2047
2048 IsConflict =
2049 ChkBuilder.CreateICmpULT(Diff, VFTimesICTimesSize, "diff.check");
2050 SeenCompares.insert({{Diff, VFTimesICTimesSize}, IsConflict});
2051 if (NeedsFreeze)
2052 IsConflict =
2053 ChkBuilder.CreateFreeze(IsConflict, IsConflict->getName() + ".fr");
2054 if (MemoryRuntimeCheck) {
2055 IsConflict =
2056 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
2057 }
2058 MemoryRuntimeCheck = IsConflict;
2059 }
2060
2061 return MemoryRuntimeCheck;
2062 }
2063
2064 std::optional<IVConditionInfo>
hasPartialIVCondition(const Loop & L,unsigned MSSAThreshold,const MemorySSA & MSSA,AAResults & AA)2065 llvm::hasPartialIVCondition(const Loop &L, unsigned MSSAThreshold,
2066 const MemorySSA &MSSA, AAResults &AA) {
2067 auto *TI = dyn_cast<BranchInst>(L.getHeader()->getTerminator());
2068 if (!TI || !TI->isConditional())
2069 return {};
2070
2071 auto *CondI = dyn_cast<Instruction>(TI->getCondition());
2072 // The case with the condition outside the loop should already be handled
2073 // earlier.
2074 // Allow CmpInst and TruncInsts as they may be users of load instructions
2075 // and have potential for partial unswitching
2076 if (!CondI || !isa<CmpInst, TruncInst>(CondI) || !L.contains(CondI))
2077 return {};
2078
2079 SmallVector<Instruction *> InstToDuplicate;
2080 InstToDuplicate.push_back(CondI);
2081
2082 SmallVector<Value *, 4> WorkList;
2083 WorkList.append(CondI->op_begin(), CondI->op_end());
2084
2085 SmallVector<MemoryAccess *, 4> AccessesToCheck;
2086 SmallVector<MemoryLocation, 4> AccessedLocs;
2087 while (!WorkList.empty()) {
2088 Instruction *I = dyn_cast<Instruction>(WorkList.pop_back_val());
2089 if (!I || !L.contains(I))
2090 continue;
2091
2092 // TODO: support additional instructions.
2093 if (!isa<LoadInst>(I) && !isa<GetElementPtrInst>(I))
2094 return {};
2095
2096 // Do not duplicate volatile and atomic loads.
2097 if (auto *LI = dyn_cast<LoadInst>(I))
2098 if (LI->isVolatile() || LI->isAtomic())
2099 return {};
2100
2101 InstToDuplicate.push_back(I);
2102 if (MemoryAccess *MA = MSSA.getMemoryAccess(I)) {
2103 if (auto *MemUse = dyn_cast_or_null<MemoryUse>(MA)) {
2104 // Queue the defining access to check for alias checks.
2105 AccessesToCheck.push_back(MemUse->getDefiningAccess());
2106 AccessedLocs.push_back(MemoryLocation::get(I));
2107 } else {
2108 // MemoryDefs may clobber the location or may be atomic memory
2109 // operations. Bail out.
2110 return {};
2111 }
2112 }
2113 WorkList.append(I->op_begin(), I->op_end());
2114 }
2115
2116 if (InstToDuplicate.empty())
2117 return {};
2118
2119 SmallVector<BasicBlock *, 4> ExitingBlocks;
2120 L.getExitingBlocks(ExitingBlocks);
2121 auto HasNoClobbersOnPath =
2122 [&L, &AA, &AccessedLocs, &ExitingBlocks, &InstToDuplicate,
2123 MSSAThreshold](BasicBlock *Succ, BasicBlock *Header,
2124 SmallVector<MemoryAccess *, 4> AccessesToCheck)
2125 -> std::optional<IVConditionInfo> {
2126 IVConditionInfo Info;
2127 // First, collect all blocks in the loop that are on a patch from Succ
2128 // to the header.
2129 SmallVector<BasicBlock *, 4> WorkList;
2130 WorkList.push_back(Succ);
2131 WorkList.push_back(Header);
2132 SmallPtrSet<BasicBlock *, 4> Seen;
2133 Seen.insert(Header);
2134 Info.PathIsNoop &=
2135 all_of(*Header, [](Instruction &I) { return !I.mayHaveSideEffects(); });
2136
2137 while (!WorkList.empty()) {
2138 BasicBlock *Current = WorkList.pop_back_val();
2139 if (!L.contains(Current))
2140 continue;
2141 const auto &SeenIns = Seen.insert(Current);
2142 if (!SeenIns.second)
2143 continue;
2144
2145 Info.PathIsNoop &= all_of(
2146 *Current, [](Instruction &I) { return !I.mayHaveSideEffects(); });
2147 WorkList.append(succ_begin(Current), succ_end(Current));
2148 }
2149
2150 // Require at least 2 blocks on a path through the loop. This skips
2151 // paths that directly exit the loop.
2152 if (Seen.size() < 2)
2153 return {};
2154
2155 // Next, check if there are any MemoryDefs that are on the path through
2156 // the loop (in the Seen set) and they may-alias any of the locations in
2157 // AccessedLocs. If that is the case, they may modify the condition and
2158 // partial unswitching is not possible.
2159 SmallPtrSet<MemoryAccess *, 4> SeenAccesses;
2160 while (!AccessesToCheck.empty()) {
2161 MemoryAccess *Current = AccessesToCheck.pop_back_val();
2162 auto SeenI = SeenAccesses.insert(Current);
2163 if (!SeenI.second || !Seen.contains(Current->getBlock()))
2164 continue;
2165
2166 // Bail out if exceeded the threshold.
2167 if (SeenAccesses.size() >= MSSAThreshold)
2168 return {};
2169
2170 // MemoryUse are read-only accesses.
2171 if (isa<MemoryUse>(Current))
2172 continue;
2173
2174 // For a MemoryDef, check if is aliases any of the location feeding
2175 // the original condition.
2176 if (auto *CurrentDef = dyn_cast<MemoryDef>(Current)) {
2177 if (any_of(AccessedLocs, [&AA, CurrentDef](MemoryLocation &Loc) {
2178 return isModSet(
2179 AA.getModRefInfo(CurrentDef->getMemoryInst(), Loc));
2180 }))
2181 return {};
2182 }
2183
2184 for (Use &U : Current->uses())
2185 AccessesToCheck.push_back(cast<MemoryAccess>(U.getUser()));
2186 }
2187
2188 // We could also allow loops with known trip counts without mustprogress,
2189 // but ScalarEvolution may not be available.
2190 Info.PathIsNoop &= isMustProgress(&L);
2191
2192 // If the path is considered a no-op so far, check if it reaches a
2193 // single exit block without any phis. This ensures no values from the
2194 // loop are used outside of the loop.
2195 if (Info.PathIsNoop) {
2196 for (auto *Exiting : ExitingBlocks) {
2197 if (!Seen.contains(Exiting))
2198 continue;
2199 for (auto *Succ : successors(Exiting)) {
2200 if (L.contains(Succ))
2201 continue;
2202
2203 Info.PathIsNoop &= Succ->phis().empty() &&
2204 (!Info.ExitForPath || Info.ExitForPath == Succ);
2205 if (!Info.PathIsNoop)
2206 break;
2207 assert((!Info.ExitForPath || Info.ExitForPath == Succ) &&
2208 "cannot have multiple exit blocks");
2209 Info.ExitForPath = Succ;
2210 }
2211 }
2212 }
2213 if (!Info.ExitForPath)
2214 Info.PathIsNoop = false;
2215
2216 Info.InstToDuplicate = InstToDuplicate;
2217 return Info;
2218 };
2219
2220 // If we branch to the same successor, partial unswitching will not be
2221 // beneficial.
2222 if (TI->getSuccessor(0) == TI->getSuccessor(1))
2223 return {};
2224
2225 if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(0), L.getHeader(),
2226 AccessesToCheck)) {
2227 Info->KnownValue = ConstantInt::getTrue(TI->getContext());
2228 return Info;
2229 }
2230 if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(1), L.getHeader(),
2231 AccessesToCheck)) {
2232 Info->KnownValue = ConstantInt::getFalse(TI->getContext());
2233 return Info;
2234 }
2235
2236 return {};
2237 }
2238