LLVM 23.0.0git
VPlanConstruction.cpp
Go to the documentation of this file.
1//===-- VPlanConstruction.cpp - Transforms for initial VPlan construction -===//
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/// \file
10/// This file implements transforms for initial VPlan construction.
11///
12//===----------------------------------------------------------------------===//
13
15#include "VPlan.h"
16#include "VPlanAnalysis.h"
17#include "VPlanCFG.h"
18#include "VPlanDominatorTree.h"
19#include "VPlanHelpers.h"
20#include "VPlanPatternMatch.h"
21#include "VPlanTransforms.h"
22#include "VPlanUtils.h"
23#include "llvm/Analysis/Loads.h"
30#include "llvm/IR/InstrTypes.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/Support/Debug.h"
35
36#define DEBUG_TYPE "vplan"
37
38using namespace llvm;
39using namespace VPlanPatternMatch;
40
41namespace {
42// Class that is used to build the plain CFG for the incoming IR.
43class PlainCFGBuilder {
44 // The outermost loop of the input loop nest considered for vectorization.
45 Loop *TheLoop;
46
47 // Loop Info analysis.
48 LoopInfo *LI;
49
50 // Loop versioning for alias metadata.
51 LoopVersioning *LVer;
52
53 // Vectorization plan that we are working on.
54 std::unique_ptr<VPlan> Plan;
55
56 // Builder of the VPlan instruction-level representation.
57 VPBuilder VPIRBuilder;
58
59 // NOTE: The following maps are intentionally destroyed after the plain CFG
60 // construction because subsequent VPlan-to-VPlan transformation may
61 // invalidate them.
62 // Map incoming BasicBlocks to their newly-created VPBasicBlocks.
64 // Map incoming Value definitions to their newly-created VPValues.
65 DenseMap<Value *, VPValue *> IRDef2VPValue;
66
67 // Hold phi node's that need to be fixed once the plain CFG has been built.
69
70 // Utility functions.
71 void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB);
72 void fixHeaderPhis();
73 VPBasicBlock *getOrCreateVPBB(BasicBlock *BB);
74#ifndef NDEBUG
75 bool isExternalDef(Value *Val);
76#endif
77 VPValue *getOrCreateVPOperand(Value *IRVal);
78 void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB);
79
80public:
81 PlainCFGBuilder(Loop *Lp, LoopInfo *LI, LoopVersioning *LVer, Type *IdxTy)
82 : TheLoop(Lp), LI(LI), LVer(LVer),
83 Plan(std::make_unique<VPlan>(Lp, IdxTy)) {}
84
85 /// Build plain CFG for TheLoop and connect it to Plan's entry.
86 std::unique_ptr<VPlan> buildPlainCFG();
87};
88} // anonymous namespace
89
90// Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB
91// must have no predecessors.
92void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) {
93 // Collect VPBB predecessors.
95 for (BasicBlock *Pred : predecessors(BB))
96 VPBBPreds.push_back(getOrCreateVPBB(Pred));
97 VPBB->setPredecessors(VPBBPreds);
98}
99
100static bool isHeaderBB(BasicBlock *BB, Loop *L) {
101 return L && BB == L->getHeader();
102}
103
104// Add operands to VPInstructions representing phi nodes from the input IR.
105void PlainCFGBuilder::fixHeaderPhis() {
106 for (auto *Phi : PhisToFix) {
107 assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode.");
108 VPValue *VPVal = IRDef2VPValue[Phi];
109 assert(isa<VPPhi>(VPVal) && "Expected VPPhi for phi node.");
110 auto *PhiR = cast<VPPhi>(VPVal);
111 assert(PhiR->getNumOperands() == 0 && "Expected VPPhi with no operands.");
112 assert(isHeaderBB(Phi->getParent(), LI->getLoopFor(Phi->getParent())) &&
113 "Expected Phi in header block.");
114 assert(Phi->getNumOperands() == 2 &&
115 "header phi must have exactly 2 operands");
116 for (BasicBlock *Pred : predecessors(Phi->getParent()))
117 PhiR->addOperand(
118 getOrCreateVPOperand(Phi->getIncomingValueForBlock(Pred)));
119 }
120}
121
122// Create a new empty VPBasicBlock for an incoming BasicBlock or retrieve an
123// existing one if it was already created.
124VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {
125 if (auto *VPBB = BB2VPBB.lookup(BB)) {
126 // Retrieve existing VPBB.
127 return VPBB;
128 }
129
130 // Create new VPBB.
131 StringRef Name = BB->getName();
132 LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << Name << "\n");
133 VPBasicBlock *VPBB = Plan->createVPBasicBlock(Name);
134 BB2VPBB[BB] = VPBB;
135 return VPBB;
136}
137
138#ifndef NDEBUG
139// Return true if \p Val is considered an external definition. An external
140// definition is either:
141// 1. A Value that is not an Instruction. This will be refined in the future.
142// 2. An Instruction that is outside of the IR region represented in VPlan,
143// i.e., is not part of the loop nest.
144bool PlainCFGBuilder::isExternalDef(Value *Val) {
145 // All the Values that are not Instructions are considered external
146 // definitions for now.
148 if (!Inst)
149 return true;
150
151 // Check whether Instruction definition is in loop body.
152 return !TheLoop->contains(Inst);
153}
154#endif
155
156// Create a new VPValue or retrieve an existing one for the Instruction's
157// operand \p IRVal. This function must only be used to create/retrieve VPValues
158// for *Instruction's operands* and not to create regular VPInstruction's. For
159// the latter, please, look at 'createVPInstructionsForVPBB'.
160VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) {
161 auto VPValIt = IRDef2VPValue.find(IRVal);
162 if (VPValIt != IRDef2VPValue.end())
163 // Operand has an associated VPInstruction or VPValue that was previously
164 // created.
165 return VPValIt->second;
166
167 // Operand doesn't have a previously created VPInstruction/VPValue. This
168 // means that operand is:
169 // A) a definition external to VPlan,
170 // B) any other Value without specific representation in VPlan.
171 // For now, we use VPValue to represent A and B and classify both as external
172 // definitions. We may introduce specific VPValue subclasses for them in the
173 // future.
174 assert(isExternalDef(IRVal) && "Expected external definition as operand.");
175
176 // A and B: Create VPValue and add it to the pool of external definitions and
177 // to the Value->VPValue map.
178 VPValue *NewVPVal = Plan->getOrAddLiveIn(IRVal);
179 IRDef2VPValue[IRVal] = NewVPVal;
180 return NewVPVal;
181}
182
183// Create new VPInstructions in a VPBasicBlock, given its BasicBlock
184// counterpart. This function must be invoked in RPO so that the operands of a
185// VPInstruction in \p BB have been visited before (except for Phi nodes).
186void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,
187 BasicBlock *BB) {
188 VPIRBuilder.setInsertPoint(VPBB);
189 // TODO: Model and preserve debug intrinsics in VPlan.
190 for (Instruction &InstRef : *BB) {
191 Instruction *Inst = &InstRef;
192
193 // There shouldn't be any VPValue for Inst at this point. Otherwise, we
194 // visited Inst when we shouldn't, breaking the RPO traversal order.
195 assert(!IRDef2VPValue.count(Inst) &&
196 "Instruction shouldn't have been visited.");
197
198 if (isa<UncondBrInst>(Inst))
199 // Skip the rest of the Instruction processing for Branch instructions.
200 continue;
201
202 if (auto *Br = dyn_cast<CondBrInst>(Inst)) {
203 // Conditional branch instruction are represented using BranchOnCond
204 // recipes.
205 VPValue *Cond = getOrCreateVPOperand(Br->getCondition());
206 VPIRBuilder.createNaryOp(VPInstruction::BranchOnCond, {Cond}, Inst, {},
207 VPIRMetadata(*Inst), Inst->getDebugLoc());
208 continue;
209 }
210
211 if (auto *SI = dyn_cast<SwitchInst>(Inst)) {
212 // Don't emit recipes for unconditional switch instructions.
213 if (SI->getNumCases() == 0)
214 continue;
215 SmallVector<VPValue *> Ops = {getOrCreateVPOperand(SI->getCondition())};
216 for (auto Case : SI->cases())
217 Ops.push_back(getOrCreateVPOperand(Case.getCaseValue()));
218 VPIRBuilder.createNaryOp(Instruction::Switch, Ops, Inst, {},
219 VPIRMetadata(*Inst), Inst->getDebugLoc());
220 continue;
221 }
222
223 VPSingleDefRecipe *NewR;
224 if (auto *Phi = dyn_cast<PHINode>(Inst)) {
225 // Phi node's operands may not have been visited at this point. We create
226 // an empty VPInstruction that we will fix once the whole plain CFG has
227 // been built.
228 NewR =
229 VPIRBuilder.createScalarPhi({}, Phi->getDebugLoc(), "vec.phi", *Phi);
230 NewR->setUnderlyingValue(Phi);
231 if (isHeaderBB(Phi->getParent(), LI->getLoopFor(Phi->getParent()))) {
232 // Header phis need to be fixed after the VPBB for the latch has been
233 // created.
234 PhisToFix.push_back(Phi);
235 } else {
236 // Add operands for VPPhi in the order matching its predecessors in
237 // VPlan.
238 DenseMap<const VPBasicBlock *, VPValue *> VPPredToIncomingValue;
239 for (unsigned I = 0; I != Phi->getNumOperands(); ++I) {
240 VPPredToIncomingValue[BB2VPBB[Phi->getIncomingBlock(I)]] =
241 getOrCreateVPOperand(Phi->getIncomingValue(I));
242 }
243 for (VPBlockBase *Pred : VPBB->getPredecessors())
244 NewR->addOperand(
245 VPPredToIncomingValue.lookup(Pred->getExitingBasicBlock()));
246 }
247 } else {
248 // Build VPIRMetadata from the instruction and add loop versioning
249 // metadata for loads and stores.
250 VPIRMetadata MD(*Inst);
251 if (isa<LoadInst, StoreInst>(Inst) && LVer) {
252 const auto &[AliasScopeMD, NoAliasMD] =
253 LVer->getNoAliasMetadataFor(Inst);
254 if (AliasScopeMD)
255 MD.setMetadata(LLVMContext::MD_alias_scope, AliasScopeMD);
256 if (NoAliasMD)
257 MD.setMetadata(LLVMContext::MD_noalias, NoAliasMD);
258 }
259
260 // Translate LLVM-IR operands into VPValue operands and set them in the
261 // new VPInstruction.
262 SmallVector<VPValue *, 4> VPOperands;
263 for (Value *Op : Inst->operands())
264 VPOperands.push_back(getOrCreateVPOperand(Op));
265
266 if (auto *CI = dyn_cast<CastInst>(Inst)) {
267 NewR = VPIRBuilder.createScalarCast(CI->getOpcode(), VPOperands[0],
268 CI->getType(), CI->getDebugLoc(),
269 VPIRFlags(*CI), MD);
270 NewR->setUnderlyingValue(CI);
271 } else if (auto *LI = dyn_cast<LoadInst>(Inst)) {
272 NewR = VPIRBuilder.createScalarLoad(LI->getType(), VPOperands[0],
273 LI->getDebugLoc(), MD);
274 NewR->setUnderlyingValue(LI);
275 } else {
276 // Build VPInstruction for any arbitrary Instruction without specific
277 // representation in VPlan.
278 NewR =
279 VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst,
280 VPIRFlags(*Inst), MD, Inst->getDebugLoc());
281 }
282 }
283
284 IRDef2VPValue[Inst] = NewR;
285 }
286}
287
288// Main interface to build the plain CFG.
289std::unique_ptr<VPlan> PlainCFGBuilder::buildPlainCFG() {
290 VPIRBasicBlock *Entry = cast<VPIRBasicBlock>(Plan->getEntry());
291 BB2VPBB[Entry->getIRBasicBlock()] = Entry;
292 for (VPIRBasicBlock *ExitVPBB : Plan->getExitBlocks())
293 BB2VPBB[ExitVPBB->getIRBasicBlock()] = ExitVPBB;
294
295 // 1. Scan the body of the loop in a topological order to visit each basic
296 // block after having visited its predecessor basic blocks. Create a VPBB for
297 // each BB and link it to its successor and predecessor VPBBs. Note that
298 // predecessors must be set in the same order as they are in the incomming IR.
299 // Otherwise, there might be problems with existing phi nodes and algorithm
300 // based on predecessors traversal.
301
302 // Loop PH needs to be explicitly visited since it's not taken into account by
303 // LoopBlocksDFS.
304 BasicBlock *ThePreheaderBB = TheLoop->getLoopPreheader();
305 assert((ThePreheaderBB->getTerminator()->getNumSuccessors() == 1) &&
306 "Unexpected loop preheader");
307 for (auto &I : *ThePreheaderBB) {
308 if (I.getType()->isVoidTy())
309 continue;
310 IRDef2VPValue[&I] = Plan->getOrAddLiveIn(&I);
311 }
312
313 LoopBlocksRPO RPO(TheLoop);
314 RPO.perform(LI);
315
316 for (BasicBlock *BB : RPO) {
317 // Create or retrieve the VPBasicBlock for this BB.
318 VPBasicBlock *VPBB = getOrCreateVPBB(BB);
319 // Set VPBB predecessors in the same order as they are in the incoming BB.
320 setVPBBPredsFromBB(VPBB, BB);
321
322 // Create VPInstructions for BB.
323 createVPInstructionsForVPBB(VPBB, BB);
324
325 // Set VPBB successors. We create empty VPBBs for successors if they don't
326 // exist already. Recipes will be created when the successor is visited
327 // during the RPO traversal.
328 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
330 getOrCreateVPBB(SI->getDefaultDest())};
331 for (auto Case : SI->cases())
332 Succs.push_back(getOrCreateVPBB(Case.getCaseSuccessor()));
333 VPBB->setSuccessors(Succs);
334 continue;
335 }
336 if (auto *BI = dyn_cast<UncondBrInst>(BB->getTerminator())) {
337 VPBB->setOneSuccessor(getOrCreateVPBB(BI->getSuccessor()));
338 continue;
339 }
340 auto *BI = cast<CondBrInst>(BB->getTerminator());
341 BasicBlock *IRSucc0 = BI->getSuccessor(0);
342 BasicBlock *IRSucc1 = BI->getSuccessor(1);
343 VPBasicBlock *Successor0 = getOrCreateVPBB(IRSucc0);
344 VPBasicBlock *Successor1 = getOrCreateVPBB(IRSucc1);
345 VPBB->setTwoSuccessors(Successor0, Successor1);
346 }
347
348 for (auto *EB : Plan->getExitBlocks())
349 setVPBBPredsFromBB(EB, EB->getIRBasicBlock());
350
351 // 2. The whole CFG has been built at this point so all the input Values must
352 // have a VPlan counterpart. Fix VPlan header phi by adding their
353 // corresponding VPlan operands.
354 fixHeaderPhis();
355
356 Plan->getEntry()->setOneSuccessor(getOrCreateVPBB(TheLoop->getHeader()));
357 Plan->getEntry()->setPlan(&*Plan);
358
359 // Fix VPlan loop-closed-ssa exit phi's by adding incoming operands to the
360 // VPIRInstructions wrapping them.
361 // // Note that the operand order corresponds to IR predecessor order, and may
362 // need adjusting when VPlan predecessors are added, if an exit block has
363 // multiple predecessor.
364 for (auto *EB : Plan->getExitBlocks()) {
365 for (VPRecipeBase &R : EB->phis()) {
366 auto *PhiR = cast<VPIRPhi>(&R);
367 PHINode &Phi = PhiR->getIRPhi();
368 assert(PhiR->getNumOperands() == 0 &&
369 "no phi operands should be added yet");
370 for (BasicBlock *Pred : predecessors(EB->getIRBasicBlock()))
371 PhiR->addOperand(
372 getOrCreateVPOperand(Phi.getIncomingValueForBlock(Pred)));
373 }
374 }
375
376 LLVM_DEBUG(Plan->setName("Plain CFG\n"); dbgs() << *Plan);
377 return std::move(Plan);
378}
379
380/// Checks if \p HeaderVPB is a loop header block in the plain CFG; that is, it
381/// has exactly 2 predecessors (preheader and latch), where the block
382/// dominates the latch and the preheader dominates the block. If it is a
383/// header block return true and canonicalize the predecessors of the header
384/// (making sure the preheader appears first and the latch second) and the
385/// successors of the latch (making sure the loop exit comes first). Otherwise
386/// return false.
388 const VPDominatorTree &VPDT) {
389 ArrayRef<VPBlockBase *> Preds = HeaderVPB->getPredecessors();
390 if (Preds.size() != 2)
391 return false;
392
393 auto *PreheaderVPBB = Preds[0];
394 auto *LatchVPBB = Preds[1];
395 if (!VPDT.dominates(PreheaderVPBB, HeaderVPB) ||
396 !VPDT.dominates(HeaderVPB, LatchVPBB)) {
397 std::swap(PreheaderVPBB, LatchVPBB);
398
399 if (!VPDT.dominates(PreheaderVPBB, HeaderVPB) ||
400 !VPDT.dominates(HeaderVPB, LatchVPBB))
401 return false;
402
403 // Canonicalize predecessors of header so that preheader is first and
404 // latch second.
405 HeaderVPB->swapPredecessors();
406 for (VPRecipeBase &R : cast<VPBasicBlock>(HeaderVPB)->phis())
407 R.swapOperands();
408 }
409
410 // The two successors of conditional branch match the condition, with the
411 // first successor corresponding to true and the second to false. We
412 // canonicalize the successors of the latch when introducing the region, such
413 // that the latch exits the region when its condition is true; invert the
414 // original condition if the original CFG branches to the header on true.
415 // Note that the exit edge is not yet connected for top-level loops.
416 if (LatchVPBB->getSingleSuccessor() ||
417 LatchVPBB->getSuccessors()[0] != HeaderVPB)
418 return true;
419
420 assert(LatchVPBB->getNumSuccessors() == 2 && "Must have 2 successors");
421 auto *Term = cast<VPBasicBlock>(LatchVPBB)->getTerminator();
422 assert(cast<VPInstruction>(Term)->getOpcode() ==
424 "terminator must be a BranchOnCond");
425 auto *Not = new VPInstruction(VPInstruction::Not, {Term->getOperand(0)});
426 Not->insertBefore(Term);
427 Term->setOperand(0, Not);
428 LatchVPBB->swapSuccessors();
429
430 return true;
431}
432
433/// Create a new VPRegionBlock for the loop starting at \p HeaderVPB.
434static void createLoopRegion(VPlan &Plan, VPBlockBase *HeaderVPB) {
435 // Get type info and debug location from the scalar phi corresponding to the
436 // canonical IV of the outermost (to be vectorized) loop. Only the outermost
437 // header will have a canonical IV. Other, nested loops are assigned a
438 // canonical IV of null type and debug location.
439 Type *CanIVTy = nullptr;
441 auto *OutermostHeaderVPBB =
443 VPPhi *OutermostVPPhi = nullptr;
444 if (HeaderVPB == OutermostHeaderVPBB) {
445 OutermostVPPhi = cast<VPPhi>(&OutermostHeaderVPBB->front());
446 CanIVTy = OutermostVPPhi->getOperand(0)->getLiveInIRValue()->getType();
447 DL = OutermostVPPhi->getDebugLoc();
448 }
449
450 auto *PreheaderVPBB = HeaderVPB->getPredecessors()[0];
451 auto *LatchVPBB = HeaderVPB->getPredecessors()[1];
452
453 VPBlockUtils::disconnectBlocks(PreheaderVPBB, HeaderVPB);
454 VPBlockUtils::disconnectBlocks(LatchVPBB, HeaderVPB);
455
456 // Create an empty region first and insert it between PreheaderVPBB and
457 // the exit blocks, taking care to preserve the original predecessor &
458 // successor order of blocks. Set region entry and exiting after both
459 // HeaderVPB and LatchVPBB have been disconnected from their
460 // predecessors/successors.
461 auto *R = Plan.createLoopRegion(CanIVTy, DL);
462
463 // Transfer latch's successors to the region.
465
466 VPBlockUtils::connectBlocks(PreheaderVPBB, R);
467 R->setEntry(HeaderVPB);
468 R->setExiting(LatchVPBB);
469
470 // Update canonical IV users for the outermost loop only.
471 if (OutermostVPPhi) {
472 OutermostVPPhi->replaceAllUsesWith(R->getCanonicalIV());
473 OutermostVPPhi->eraseFromParent();
474 }
475
476 // All VPBB's reachable shallowly from HeaderVPB belong to the current region.
477 for (VPBlockBase *VPBB : vp_depth_first_shallow(HeaderVPB))
478 VPBB->setParent(R);
479}
480
482 auto [HeaderVPBB, LatchVPBB] = VPBlockUtils::getPlainCFGHeaderAndLatch(Plan);
483
484 // Add a VPPhi for the canonical IV starting at 0 as first recipe in header.
485 auto *CanonicalIVPHI =
486 new VPPhi(Plan.getZero(Plan.getVectorTripCount().getType()), {}, DL);
487 HeaderVPBB->insert(CanonicalIVPHI, HeaderVPBB->begin());
488
489 // We are about to replace the branch to exit the region. Remove the original
490 // BranchOnCond, if there is any.
491 DebugLoc LatchDL = DL;
492 if (!LatchVPBB->empty() && match(&LatchVPBB->back(), m_BranchOnCond())) {
493 LatchDL = LatchVPBB->getTerminator()->getDebugLoc();
494 LatchVPBB->getTerminator()->eraseFromParent();
495 }
496
497 VPBuilder Builder(LatchVPBB);
498 // Add a VPInstruction to increment the scalar canonical IV by VF * UF.
499 // Initially the induction increment is guaranteed to not wrap, but that may
500 // change later, e.g. when tail-folding, when the flags need to be dropped.
501 auto *CanonicalIVIncrement = Builder.createAdd(
502 CanonicalIVPHI, &Plan.getVFxUF(), DL, "index.next", {true, false});
503 CanonicalIVPHI->addOperand(CanonicalIVIncrement);
504
505 // Add the BranchOnCount VPInstruction to the latch.
506 Builder.createNaryOp(VPInstruction::BranchOnCount,
507 {CanonicalIVIncrement, &Plan.getVectorTripCount()},
508 LatchDL);
509}
510
511/// Creates extracts for values in \p Plan defined in a loop region and used
512/// outside a loop region.
513static void createExtractsForLiveOuts(VPlan &Plan, VPBasicBlock *MiddleVPBB) {
514 VPBuilder B(MiddleVPBB, MiddleVPBB->getFirstNonPhi());
515 for (VPBasicBlock *EB : Plan.getExitBlocks()) {
516 if (!is_contained(EB->predecessors(), MiddleVPBB))
517 continue;
518
519 for (VPRecipeBase &R : EB->phis()) {
520 auto *ExitIRI = cast<VPIRPhi>(&R);
521 VPValue *Exiting = ExitIRI->getIncomingValueForBlock(MiddleVPBB);
522 if (isa<VPIRValue>(Exiting))
523 continue;
524 Exiting = B.createNaryOp(VPInstruction::ExtractLastPart, Exiting);
525 Exiting = B.createNaryOp(VPInstruction::ExtractLastLane, Exiting);
526 ExitIRI->setIncomingValueForBlock(MiddleVPBB, Exiting);
527 }
528 }
529}
530
531static void addInitialSkeleton(VPlan &Plan, Type *InductionTy,
532 PredicatedScalarEvolution &PSE, Loop *TheLoop) {
533 VPDominatorTree VPDT(Plan);
534
535 auto *HeaderVPBB = cast<VPBasicBlock>(Plan.getEntry()->getSingleSuccessor());
536 canonicalHeaderAndLatch(HeaderVPBB, VPDT);
537 auto *LatchVPBB = cast<VPBasicBlock>(HeaderVPBB->getPredecessors()[1]);
538
539 VPBasicBlock *VecPreheader = Plan.createVPBasicBlock("vector.ph");
540 VPBlockUtils::insertBlockAfter(VecPreheader, Plan.getEntry());
541
542 VPBasicBlock *MiddleVPBB = Plan.createVPBasicBlock("middle.block");
543 // The canonical LatchVPBB has the header block as last successor. If it has
544 // another successor, this successor is an exit block - insert middle block on
545 // its edge. Otherwise, add middle block as another successor retaining header
546 // as last. In the latter case, the latch has no conditional terminator yet,
547 // so insert a placeholder BranchOnCond that always continues to the header.
548 // It will be canonicalized to a BranchOnCount later
549 if (LatchVPBB->getNumSuccessors() == 2) {
550 VPBlockBase *LatchExitVPB = LatchVPBB->getSuccessors()[0];
551 VPBlockUtils::insertOnEdge(LatchVPBB, LatchExitVPB, MiddleVPBB);
552 } else {
553 VPBlockUtils::connectBlocks(LatchVPBB, MiddleVPBB);
554 LatchVPBB->swapSuccessors();
556 {Plan.getFalse()});
557 }
558
559 // Create SCEV and VPValue for the trip count.
560 // We use the symbolic max backedge-taken-count, which works also when
561 // vectorizing loops with uncountable early exits.
562 const SCEV *BackedgeTakenCountSCEV = PSE.getSymbolicMaxBackedgeTakenCount();
563 assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCountSCEV) &&
564 "Invalid backedge-taken count");
565 ScalarEvolution &SE = *PSE.getSE();
566 const SCEV *TripCount = SE.getTripCountFromExitCount(BackedgeTakenCountSCEV,
567 InductionTy, TheLoop);
569
570 VPBasicBlock *ScalarPH = Plan.createVPBasicBlock("scalar.ph");
572
573 // The connection order corresponds to the operands of the conditional branch,
574 // with the middle block already connected to the exit block.
575 VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
576 // Also connect the entry block to the scalar preheader.
577 // TODO: Also introduce a branch recipe together with the minimum trip count
578 // check.
579 VPBlockUtils::connectBlocks(Plan.getEntry(), ScalarPH);
580 Plan.getEntry()->swapSuccessors();
581
582 createExtractsForLiveOuts(Plan, MiddleVPBB);
583
584 // Create resume phis in the scalar preheader for each phi in the scalar loop.
585 // Their incoming value from the vector loop will be the last lane of the
586 // corresponding vector loop header phi.
587 VPBuilder MiddleBuilder(MiddleVPBB, MiddleVPBB->getFirstNonPhi());
588 VPBuilder ScalarPHBuilder(ScalarPH);
589 assert(equal(ScalarPH->getPredecessors(),
590 ArrayRef<VPBlockBase *>({MiddleVPBB, Plan.getEntry()})) &&
591 "unexpected predecessor order of scalar ph");
592 for (const auto &[PhiR, ScalarPhiR] :
593 zip_equal(HeaderVPBB->phis(), Plan.getScalarHeader()->phis())) {
594 auto *VectorPhiR = cast<VPPhi>(&PhiR);
595 VPValue *BackedgeVal = VectorPhiR->getOperand(1);
596 VPValue *ResumeFromVectorLoop =
597 MiddleBuilder.createNaryOp(VPInstruction::ExtractLastPart, BackedgeVal);
598 ResumeFromVectorLoop = MiddleBuilder.createNaryOp(
599 VPInstruction::ExtractLastLane, ResumeFromVectorLoop);
600 // Create scalar resume phi, with the first operand being the incoming value
601 // from the middle block and the second operand coming from the entry block.
602 auto *ResumePhiR = ScalarPHBuilder.createScalarPhi(
603 {ResumeFromVectorLoop, VectorPhiR->getOperand(0)},
604 VectorPhiR->getDebugLoc());
605 cast<VPIRPhi>(&ScalarPhiR)->addOperand(ResumePhiR);
606 }
607}
608
609/// Check \p Plan's live-in and replace them with constants, if they can be
610/// simplified via SCEV.
613 auto GetSimplifiedLiveInViaSCEV = [&](VPValue *VPV) -> VPValue * {
614 const SCEV *Expr = vputils::getSCEVExprForVPValue(VPV, PSE);
615 if (auto *C = dyn_cast<SCEVConstant>(Expr))
616 return Plan.getOrAddLiveIn(C->getValue());
617 return nullptr;
618 };
619
620 for (VPValue *LiveIn : to_vector(Plan.getLiveIns())) {
621 if (VPValue *SimplifiedLiveIn = GetSimplifiedLiveInViaSCEV(LiveIn))
622 LiveIn->replaceAllUsesWith(SimplifiedLiveIn);
623 }
624}
625
626/// To make RUN_VPLAN_PASS print initial VPlan.
628
629std::unique_ptr<VPlan>
630VPlanTransforms::buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy,
632 LoopVersioning *LVer) {
633 PlainCFGBuilder Builder(TheLoop, &LI, LVer, InductionTy);
634 std::unique_ptr<VPlan> VPlan0 = Builder.buildPlainCFG();
635 addInitialSkeleton(*VPlan0, InductionTy, PSE, TheLoop);
636 simplifyLiveInsWithSCEV(*VPlan0, PSE);
637
639 return VPlan0;
640}
641
642/// Creates a VPWidenIntOrFpInductionRecipe or VPWidenPointerInductionRecipe
643/// for \p Phi based on \p IndDesc.
644static VPHeaderPHIRecipe *
646 const InductionDescriptor &IndDesc, VPlan &Plan,
647 PredicatedScalarEvolution &PSE, Loop &OrigLoop,
648 DebugLoc DL) {
649 [[maybe_unused]] ScalarEvolution &SE = *PSE.getSE();
650 assert(SE.isLoopInvariant(IndDesc.getStep(), &OrigLoop) &&
651 "step must be loop invariant");
652 assert((Plan.getLiveIn(IndDesc.getStartValue()) == Start ||
653 (SE.isSCEVable(IndDesc.getStartValue()->getType()) &&
654 SE.getSCEV(IndDesc.getStartValue()) ==
655 vputils::getSCEVExprForVPValue(Start, PSE))) &&
656 "Start VPValue must match IndDesc's start value");
657
658 VPValue *Step =
660
661 VPValue *BackedgeVal = PhiR->getOperand(1);
662 // Replace live-out extracts of WideIV's backedge value by ExitingIVValue
663 // recipes. optimizeInductionLiveOutUsers will later compute the proper
664 // DerivedIV.
665 auto ReplaceExtractsWithExitingIVValue = [&](VPHeaderPHIRecipe *WideIV) {
666 for (VPUser *U : to_vector(BackedgeVal->users())) {
668 continue;
669 auto *ExtractLastPart = cast<VPInstruction>(U);
670 VPUser *ExtractLastPartUser = ExtractLastPart->getSingleUser();
671 assert(ExtractLastPartUser && "must have a single user");
672 if (!match(ExtractLastPartUser, m_ExtractLastLane(m_VPValue())))
673 continue;
674 auto *ExtractLastLane = cast<VPInstruction>(ExtractLastPartUser);
675 assert(is_contained(ExtractLastLane->getParent()->successors(),
676 Plan.getScalarPreheader()) &&
677 "last lane must be extracted in the middle block");
678 VPBuilder Builder(ExtractLastLane);
679 ExtractLastLane->replaceAllUsesWith(
680 Builder.createNaryOp(VPInstruction::ExitingIVValue, {WideIV}));
681 ExtractLastLane->eraseFromParent();
682 ExtractLastPart->eraseFromParent();
683 }
684 };
685
687 auto *WideIV = new VPWidenPointerInductionRecipe(
688 Phi, Start, Step, &Plan.getVFxUF(), IndDesc, DL);
689 ReplaceExtractsWithExitingIVValue(WideIV);
690 return WideIV;
691 }
692
695 "must have an integer or float induction at this point");
696
697 // Update wide induction increments to use the same step as the corresponding
698 // wide induction. This enables detecting induction increments directly in
699 // VPlan and removes redundant splats.
700 if (match(BackedgeVal, m_Add(m_Specific(PhiR), m_VPValue())))
701 BackedgeVal->getDefiningRecipe()->setOperand(1, Step);
702
703 // It is always safe to copy over the NoWrap and FastMath flags. In
704 // particular, when folding tail by masking, the masked-off lanes are never
705 // used, so it is safe.
707
708 auto *WideIV = new VPWidenIntOrFpInductionRecipe(
709 Phi, Start, Step, &Plan.getVF(), IndDesc, Flags, DL);
710
711 ReplaceExtractsWithExitingIVValue(WideIV);
712 return WideIV;
713}
714
715/// Try to sink users of \p FOR after \p Previous. \returns true if sinking
716/// succeeded or was not necessary, and false otherwise.
717static bool
719 VPRecipeBase *Previous,
720 VPDominatorTree &VPDT) {
721 // Collect recipes that need sinking.
724 Seen.insert(Previous);
725 auto TryToPushSinkCandidate = [&](VPRecipeBase *SinkCandidate) {
726 // The previous value must not depend on the users of the recurrence phi.
727 // In that case, FOR is not a fixed order recurrence.
728 if (SinkCandidate == Previous)
729 return false;
730
731 if (isa<VPHeaderPHIRecipe>(SinkCandidate) ||
732 !Seen.insert(SinkCandidate).second ||
733 VPDT.properlyDominates(Previous, SinkCandidate))
734 return true;
735
736 if (vputils::cannotHoistOrSinkRecipe(*SinkCandidate, /*Sinking=*/true))
737 return false;
738
739 WorkList.push_back(SinkCandidate);
740 return true;
741 };
742
743 // Recursively sink users of FOR after Previous.
744 WorkList.push_back(FOR);
745 for (unsigned I = 0; I != WorkList.size(); ++I) {
746 VPRecipeBase *Current = WorkList[I];
747 assert(Current->getNumDefinedValues() == 1 &&
748 "only recipes with a single defined value expected");
749
750 for (VPUser *User : Current->getVPSingleValue()->users()) {
751 if (!TryToPushSinkCandidate(cast<VPRecipeBase>(User)))
752 return false;
753 }
754 }
755
756 // Keep recipes to sink ordered by dominance so earlier instructions are
757 // processed first.
758 sort(WorkList, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
759 return VPDT.properlyDominates(A, B);
760 });
761
762 for (VPRecipeBase *SinkCandidate : WorkList) {
763 if (SinkCandidate == FOR)
764 continue;
765
766 SinkCandidate->moveAfter(Previous);
767 Previous = SinkCandidate;
768 }
769 return true;
770}
771
772/// Try to hoist \p Previous and its operands before all users of \p FOR.
773/// \returns true if hoisting succeeded or was not necessary, and false
774/// otherwise.
776 VPRecipeBase *Previous,
777 VPDominatorTree &VPDT) {
779 return false;
780
781 // Collect recipes that need hoisting.
782 SmallVector<VPRecipeBase *> HoistCandidates;
784 // Find the closest hoist point by looking at all users of FOR and selecting
785 // the recipe dominating all other users.
786 VPRecipeBase *HoistPoint = nullptr;
787 for (VPUser *U : FOR->users()) {
788 auto *R = cast<VPRecipeBase>(U);
789 if (!HoistPoint || VPDT.properlyDominates(R, HoistPoint))
790 HoistPoint = R;
791 }
792 assert(all_of(FOR->users(),
793 [&VPDT, HoistPoint](VPUser *U) {
794 auto *R = cast<VPRecipeBase>(U);
795 return HoistPoint == R ||
796 VPDT.properlyDominates(HoistPoint, R);
797 }) &&
798 "HoistPoint must dominate all users of FOR");
799
800 auto NeedsHoisting = [HoistPoint, &VPDT,
801 &Visited](VPValue *HoistCandidateV) -> VPRecipeBase * {
802 VPRecipeBase *HoistCandidate = HoistCandidateV->getDefiningRecipe();
803 if (!HoistCandidate)
804 return nullptr;
805 // Hoist candidate was already visited, no need to hoist.
806 if (!Visited.insert(HoistCandidate).second)
807 return nullptr;
808 // If we reached a recipe that dominates HoistPoint, we don't need to
809 // hoist the recipe.
810 if (VPDT.properlyDominates(HoistCandidate, HoistPoint))
811 return nullptr;
812 return HoistCandidate;
813 };
814
815 if (!NeedsHoisting(Previous->getVPSingleValue()))
816 return true;
817
818 // Recursively try to hoist Previous and its operands before all users of
819 // FOR.
820 HoistCandidates.push_back(Previous);
821
822 for (unsigned I = 0; I != HoistCandidates.size(); ++I) {
823 VPRecipeBase *Current = HoistCandidates[I];
824 assert(Current->getNumDefinedValues() == 1 &&
825 "only recipes with a single defined value expected");
827 return false;
828
829 for (VPValue *Op : Current->operands()) {
830 // If we reach FOR, it means the original Previous depends on some other
831 // recurrence that in turn depends on FOR. If that is the case, we would
832 // also need to hoist recipes involving the other FOR, which may break
833 // dependencies.
834 if (Op == FOR)
835 return false;
836
837 if (auto *R = NeedsHoisting(Op)) {
838 // Bail out if the recipe defines multiple values.
839 // TODO: Hoisting such recipes requires additional handling.
840 if (R->getNumDefinedValues() != 1)
841 return false;
842 HoistCandidates.push_back(R);
843 }
844 }
845 }
846
847 // Order recipes to hoist by dominance so earlier instructions are processed
848 // first.
849 sort(HoistCandidates, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
850 return VPDT.properlyDominates(A, B);
851 });
852
853 for (VPRecipeBase *HoistCandidate : HoistCandidates) {
854 HoistCandidate->moveBefore(*HoistPoint->getParent(),
855 HoistPoint->getIterator());
856 }
857
858 return true;
859}
860
861/// Sink users of fixed-order recurrences past or hoist before the recipe
862/// defining the previous value, introduce FirstOrderRecurrenceSplice
863/// VPInstructions, and replace FOR uses. Returns false if hoisting or sinking
864/// fails.
866 VPDominatorTree &VPDT) {
867 for (VPRecipeBase &R : HeaderVPBB->phis()) {
869 if (!FOR)
870 continue;
871
872 // Follow through FOR phi chains to find the actual Previous recipe.
873 // Fixed-order recurrences do not contain cycles, so this loop is
874 // guaranteed to terminate.
876 VPRecipeBase *Previous = FOR->getBackedgeValue()->getDefiningRecipe();
877 while (auto *PrevPhi =
879 assert(PrevPhi->getParent() == FOR->getParent() &&
880 "PrevPhi must be in same block as FOR");
881 assert(SeenPhis.insert(PrevPhi).second &&
882 "PrevPhi must not be visited multiple times");
883 Previous = PrevPhi->getBackedgeValue()->getDefiningRecipe();
884 }
885
886 assert(Previous && "Previous must be a recipe");
887 // Sink FOR users after Previous or hoist Previous before FOR users.
888 if (!sinkRecurrenceUsersAfterPrevious(FOR, Previous, VPDT) &&
889 !hoistPreviousBeforeFORUsers(FOR, Previous, VPDT))
890 return false;
891
892 // Create FirstOrderRecurrenceSplice and replace FOR uses.
893 VPBasicBlock *InsertBlock = Previous->getParent();
894 auto InsertPt = isa<VPHeaderPHIRecipe>(Previous)
895 ? InsertBlock->getFirstNonPhi()
896 : std::next(Previous->getIterator());
897 VPBuilder LoopBuilder(InsertBlock, InsertPt);
898 auto *RecurSplice =
900 {FOR, FOR->getBackedgeValue()});
901 FOR->replaceUsesWithIf(RecurSplice, [RecurSplice](VPUser &U, unsigned) {
902 return &U != RecurSplice;
903 });
904 }
905
906 return true;
907}
908
910 VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop,
913 const SmallPtrSetImpl<const PHINode *> &FixedOrderRecurrences,
914 const SmallPtrSetImpl<PHINode *> &InLoopReductions, bool AllowReordering) {
915 // Retrieve the header manually from the intial plain-CFG VPlan.
916 auto [HeaderVPBB, LatchVPBB] = VPBlockUtils::getPlainCFGHeaderAndLatch(Plan);
917 VPDominatorTree VPDT(Plan);
918 assert(VPDT.dominates(HeaderVPBB, LatchVPBB) &&
919 "header must dominate its latch");
920
921 auto CreateHeaderPhiRecipe = [&](VPPhi *PhiR) -> VPHeaderPHIRecipe * {
922 // TODO: Gradually replace uses of underlying instruction by analyses on
923 // VPlan.
924 auto *Phi = cast<PHINode>(PhiR->getUnderlyingInstr());
925 assert(PhiR->getNumOperands() == 2 &&
926 "Must have 2 operands for header phis");
927
928 // Extract common values once.
929 VPIRValue *Start = cast<VPIRValue>(PhiR->getOperand(0));
930 VPValue *BackedgeValue = PhiR->getOperand(1);
931
932 if (FixedOrderRecurrences.contains(Phi)) {
933 // TODO: Currently fixed-order recurrences are modeled as chains of
934 // first-order recurrences. If there are no users of the intermediate
935 // recurrences in the chain, the fixed order recurrence should be
936 // modeled directly, enabling more efficient codegen.
937 return new VPFirstOrderRecurrencePHIRecipe(Phi, *Start, *BackedgeValue);
938 }
939
940 auto InductionIt = Inductions.find(Phi);
941 if (InductionIt != Inductions.end())
942 return createWidenInductionRecipe(Phi, PhiR, Start, InductionIt->second,
943 Plan, PSE, OrigLoop,
944 PhiR->getDebugLoc());
945
946 assert(Reductions.contains(Phi) && "only reductions are expected now");
947 const RecurrenceDescriptor &RdxDesc = Reductions.lookup(Phi);
949 Phi->getIncomingValueForBlock(OrigLoop.getLoopPreheader()) &&
950 "incoming value must match start value");
951 // Will be updated later to >1 if reduction is partial.
952 unsigned ScaleFactor = 1;
953 bool UseOrderedReductions = !AllowReordering && RdxDesc.isOrdered();
954 return new VPReductionPHIRecipe(
955 Phi, RdxDesc.getRecurrenceKind(), *Start, *BackedgeValue,
956 getReductionStyle(InLoopReductions.contains(Phi), UseOrderedReductions,
957 ScaleFactor),
958 Phi->getType()->isFloatingPointTy() ? RdxDesc.getFastMathFlags()
959 : VPIRFlags(),
961 };
962
963 for (VPRecipeBase &R : make_early_inc_range(HeaderVPBB->phis())) {
964 auto *PhiR = cast<VPPhi>(&R);
965 VPHeaderPHIRecipe *HeaderPhiR = CreateHeaderPhiRecipe(PhiR);
966 HeaderPhiR->insertBefore(PhiR);
967 PhiR->replaceAllUsesWith(HeaderPhiR);
968 PhiR->eraseFromParent();
969 }
970
971 if (!tryToSinkOrHoistRecurrenceUsers(HeaderVPBB, VPDT))
972 return false;
973
974 for (const auto &[HeaderPhiR, ScalarPhiR] :
975 zip_equal(HeaderVPBB->phis(), Plan.getScalarPreheader()->phis())) {
976 auto *ResumePhiR = cast<VPPhi>(&ScalarPhiR);
977 if (isa<VPFirstOrderRecurrencePHIRecipe>(&HeaderPhiR)) {
978 ResumePhiR->setName("scalar.recur.init");
979 auto *ExtractLastLane = cast<VPInstruction>(ResumePhiR->getOperand(0));
980 ExtractLastLane->setName("vector.recur.extract");
981 continue;
982 }
983 ResumePhiR->setName(isa<VPWidenInductionRecipe>(HeaderPhiR)
984 ? "bc.resume.val"
985 : "bc.merge.rdx");
986 }
987 return true;
988}
989
991 ElementCount MinVF) {
992 VPTypeAnalysis TypeInfo(Plan);
995
996 for (VPRecipeBase &R : Header->phis()) {
997 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
998 if (!PhiR || !PhiR->isInLoop() || (MinVF.isScalar() && !PhiR->isOrdered()))
999 continue;
1000
1001 RecurKind Kind = PhiR->getRecurrenceKind();
1005 "AnyOf and Find reductions are not allowed for in-loop reductions");
1006
1007 bool IsFPRecurrence =
1009 FastMathFlags FMFs =
1010 IsFPRecurrence ? FastMathFlags::getFast() : FastMathFlags();
1011
1012 // Collect the chain of "link" recipes for the reduction starting at PhiR.
1014 Worklist.insert(PhiR);
1015 for (unsigned I = 0; I != Worklist.size(); ++I) {
1016 VPSingleDefRecipe *Cur = Worklist[I];
1017 for (VPUser *U : Cur->users()) {
1018 auto *UserRecipe = cast<VPSingleDefRecipe>(U);
1019 if (!UserRecipe->getParent()->getEnclosingLoopRegion()) {
1020 assert((UserRecipe->getParent() == Plan.getMiddleBlock() ||
1021 UserRecipe->getParent() == Plan.getScalarPreheader()) &&
1022 "U must be either in the loop region, the middle block or the "
1023 "scalar preheader.");
1024 continue;
1025 }
1026
1027 // Stores using instructions will be sunk later.
1028 if (match(UserRecipe, m_VPInstruction<Instruction::Store>()))
1029 continue;
1030 Worklist.insert(UserRecipe);
1031 }
1032 }
1033
1034 // Visit operation "Links" along the reduction chain top-down starting from
1035 // the phi until LoopExitValue. We keep track of the previous item
1036 // (PreviousLink) to tell which of the two operands of a Link will remain
1037 // scalar and which will be reduced. For minmax by select(cmp), Link will be
1038 // the select instructions. Blend recipes of in-loop reduction phi's will
1039 // get folded to their non-phi operand, as the reduction recipe handles the
1040 // condition directly.
1041 VPSingleDefRecipe *PreviousLink = PhiR; // Aka Worklist[0].
1042 for (VPSingleDefRecipe *CurrentLink : drop_begin(Worklist)) {
1043 if (auto *Blend = dyn_cast<VPBlendRecipe>(CurrentLink)) {
1044 assert(Blend->getNumIncomingValues() == 2 &&
1045 "Blend must have 2 incoming values");
1046 unsigned PhiRIdx = Blend->getIncomingValue(0) == PhiR ? 0 : 1;
1047 assert(Blend->getIncomingValue(PhiRIdx) == PhiR &&
1048 "PhiR must be an operand of the blend");
1049 Blend->replaceAllUsesWith(Blend->getIncomingValue(1 - PhiRIdx));
1050 continue;
1051 }
1052
1053 if (IsFPRecurrence) {
1054 FastMathFlags CurFMF =
1055 cast<VPRecipeWithIRFlags>(CurrentLink)->getFastMathFlags();
1056 if (match(CurrentLink, m_Select(m_VPValue(), m_VPValue(), m_VPValue())))
1057 CurFMF |= cast<VPRecipeWithIRFlags>(CurrentLink->getOperand(0))
1058 ->getFastMathFlags();
1059 FMFs &= CurFMF;
1060 }
1061
1062 Instruction *CurrentLinkI = CurrentLink->getUnderlyingInstr();
1063
1064 // Recognize a call to the llvm.fmuladd intrinsic.
1065 bool IsFMulAdd = Kind == RecurKind::FMulAdd;
1066 VPValue *VecOp;
1067 VPBasicBlock *LinkVPBB = CurrentLink->getParent();
1068 if (IsFMulAdd) {
1070 "Expected current VPInstruction to be a call to the "
1071 "llvm.fmuladd intrinsic");
1072 assert(CurrentLink->getOperand(2) == PreviousLink &&
1073 "expected a call where the previous link is the added operand");
1074
1075 // If the instruction is a call to the llvm.fmuladd intrinsic then we
1076 // need to create an fmul recipe (multiplying the first two operands of
1077 // the fmuladd together) to use as the vector operand for the fadd
1078 // reduction.
1079 auto *FMulRecipe = new VPInstruction(
1080 Instruction::FMul,
1081 {CurrentLink->getOperand(0), CurrentLink->getOperand(1)},
1082 CurrentLinkI->getFastMathFlags());
1083 LinkVPBB->insert(FMulRecipe, CurrentLink->getIterator());
1084 VecOp = FMulRecipe;
1085 } else if (Kind == RecurKind::AddChainWithSubs &&
1086 match(CurrentLink, m_Sub(m_VPValue(), m_VPValue()))) {
1087 Type *PhiTy = TypeInfo.inferScalarType(PhiR);
1088 auto *Zero = Plan.getConstantInt(PhiTy, 0);
1089 VPBuilder Builder(LinkVPBB, CurrentLink->getIterator());
1090 auto *Sub = Builder.createSub(Zero, CurrentLink->getOperand(1),
1091 CurrentLinkI->getDebugLoc());
1092 Sub->setUnderlyingValue(CurrentLinkI);
1093 VecOp = Sub;
1094 } else {
1095 // Index of the first operand which holds a non-mask vector operand.
1096 unsigned IndexOfFirstOperand = 0;
1098 if (match(CurrentLink, m_Cmp(m_VPValue(), m_VPValue())))
1099 continue;
1100 assert(match(CurrentLink,
1102 "must be a select recipe");
1103 IndexOfFirstOperand = 1;
1104 }
1105 // Note that for non-commutable operands (cmp-selects), the semantics of
1106 // the cmp-select are captured in the recurrence kind.
1107 unsigned VecOpId =
1108 CurrentLink->getOperand(IndexOfFirstOperand) == PreviousLink
1109 ? IndexOfFirstOperand + 1
1110 : IndexOfFirstOperand;
1111 VecOp = CurrentLink->getOperand(VecOpId);
1112 assert(
1113 VecOp != PreviousLink &&
1114 CurrentLink->getOperand(
1115 cast<VPInstruction>(CurrentLink)->getNumOperandsWithoutMask() -
1116 1 - (VecOpId - IndexOfFirstOperand)) == PreviousLink &&
1117 "PreviousLink must be the operand other than VecOp");
1118 }
1119
1120 assert(PhiR->getVFScaleFactor() == 1 &&
1121 "inloop reductions must be unscaled");
1122 VPValue *CondOp = cast<VPInstruction>(CurrentLink)->getMask();
1123 auto *RedRecipe = new VPReductionRecipe(
1124 Kind, FMFs, CurrentLinkI, PreviousLink, VecOp, CondOp,
1125 getReductionStyle(/*IsInLoop=*/true, PhiR->isOrdered(), 1),
1126 CurrentLinkI->getDebugLoc());
1127 // Append the recipe to the end of the VPBasicBlock because we need to
1128 // ensure that it comes after all of it's inputs, including CondOp.
1129 // Delete CurrentLink as it will be invalid if its operand is replaced
1130 // with a reduction defined at the bottom of the block in the next link.
1131 if (LinkVPBB->getNumSuccessors() == 0)
1132 RedRecipe->insertBefore(&*std::prev(std::prev(LinkVPBB->end())));
1133 else
1134 LinkVPBB->appendRecipe(RedRecipe);
1135
1136 CurrentLink->replaceAllUsesWith(RedRecipe);
1137 // Move any store recipes using the RedRecipe that appear before it in the
1138 // same block to just after the RedRecipe.
1139 for (VPUser *U : make_early_inc_range(RedRecipe->users())) {
1140 auto *UserR = dyn_cast<VPRecipeBase>(U);
1141 if (!UserR || UserR->getParent() != LinkVPBB)
1142 continue;
1144 continue;
1145 UserR->moveAfter(RedRecipe);
1146 }
1147 ToDelete.push_back(CurrentLink);
1148 PreviousLink = RedRecipe;
1149 }
1150 }
1151
1152 for (VPRecipeBase *R : ToDelete)
1153 R->eraseFromParent();
1154}
1155
1156/// Check if all loads in the loop are dereferenceable. Iterates over the
1157/// loop body blocks reachable from \p HeaderVPBB. Returns false if any
1158/// non-dereferenceable load is found.
1159static bool areAllLoadsDereferenceable(VPBasicBlock *HeaderVPBB, Loop *TheLoop,
1161 DominatorTree &DT, AssumptionCache *AC) {
1162 ScalarEvolution &SE = *PSE.getSE();
1163 const DataLayout &DL = TheLoop->getHeader()->getDataLayout();
1164 for (VPBasicBlock *VPBB : vp_rpo_plain_cfg_loop_body(HeaderVPBB)) {
1165 for (VPRecipeBase &R : *VPBB) {
1166 auto *VPI = dyn_cast<VPInstructionWithType>(&R);
1167 if (!VPI || VPI->getOpcode() != Instruction::Load) {
1168 assert(!R.mayReadFromMemory() && "unexpected recipe reading memory");
1169 continue;
1170 }
1171
1172 // Get the pointer SCEV for dereferenceability checking.
1173 VPValue *Ptr = VPI->getOperand(0);
1174 const SCEV *PtrSCEV = vputils::getSCEVExprForVPValue(Ptr, PSE, TheLoop);
1175 if (isa<SCEVCouldNotCompute>(PtrSCEV)) {
1176 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Found non-dereferenceable "
1177 "load with SCEVCouldNotCompute pointer\n");
1178 return false;
1179 }
1180
1181 // Check dereferenceability using the SCEV-based version.
1182 Type *LoadTy = VPI->getResultType();
1183 const SCEV *SizeSCEV =
1184 SE.getStoreSizeOfExpr(DL.getIndexType(PtrSCEV->getType()), LoadTy);
1185 auto *Load = cast<LoadInst>(VPI->getUnderlyingValue());
1187 if (isDereferenceableAndAlignedInLoop(PtrSCEV, Load->getAlign(), SizeSCEV,
1188 TheLoop, SE, DT, AC, &Preds))
1189 continue;
1190
1191 LLVM_DEBUG(
1192 dbgs() << "LV: Not vectorizing: Auto-vectorization of loops with "
1193 "potentially faulting load is not supported.\n");
1194 return false;
1195 }
1196 }
1197 return true;
1198}
1199
1201 Loop *TheLoop,
1203 DominatorTree &DT, AssumptionCache *AC) {
1204 auto *MiddleVPBB = VPBlockUtils::getPlainCFGMiddleBlock(Plan);
1205 auto [HeaderVPBB, LatchVPBB] = VPBlockUtils::getPlainCFGHeaderAndLatch(Plan);
1206
1207 // TODO: We would like to detect uncountable exits and stores within loops
1208 // with such exits from the VPlan alone. Exit detection can be moved
1209 // here from handleUncountableEarlyExits, but we need to improve
1210 // detection of recipes which may write to memory.
1212 if (!areAllLoadsDereferenceable(HeaderVPBB, TheLoop, PSE, DT, AC))
1213 return false;
1214 // TODO: Check target preference for style.
1215 handleUncountableEarlyExits(Plan, HeaderVPBB, LatchVPBB, MiddleVPBB, Style);
1216 return true;
1217 }
1218
1219 // Disconnect countable early exits from the loop, leaving it with a single
1220 // exit from the latch. Countable early exits are left for a scalar epilog.
1221 for (VPIRBasicBlock *EB : Plan.getExitBlocks()) {
1222 for (VPBlockBase *Pred : to_vector(EB->getPredecessors())) {
1223 if (Pred == MiddleVPBB)
1224 continue;
1225
1226 // Remove phi operands for the early exiting block.
1227 for (VPRecipeBase &R : EB->phis())
1228 cast<VPIRPhi>(&R)->removeIncomingValueFor(Pred);
1229 auto *EarlyExitingVPBB = cast<VPBasicBlock>(Pred);
1230 EarlyExitingVPBB->getTerminator()->eraseFromParent();
1232 }
1233 }
1234 return true;
1235}
1236
1237void VPlanTransforms::addMiddleCheck(VPlan &Plan, bool TailFolded) {
1238 auto *MiddleVPBB = VPBlockUtils::getPlainCFGMiddleBlock(Plan);
1239 // If MiddleVPBB has a single successor then the original loop does not exit
1240 // via the latch and the single successor must be the scalar preheader.
1241 // There's no need to add a runtime check to MiddleVPBB.
1242 if (MiddleVPBB->getNumSuccessors() == 1) {
1243 assert(MiddleVPBB->getSingleSuccessor() == Plan.getScalarPreheader() &&
1244 "must have ScalarPH as single successor");
1245 return;
1246 }
1247
1248 assert(MiddleVPBB->getNumSuccessors() == 2 && "must have 2 successors");
1249
1250 // Add a check in the middle block to see if we have completed all of the
1251 // iterations in the first vector loop.
1252 //
1253 // Three cases:
1254 // 1) If we require a scalar epilogue, the scalar ph must execute. Set the
1255 // condition to false.
1256 // 2) If (N - N%VF) == N, then we *don't* need to run the
1257 // remainder. Thus if tail is to be folded, we know we don't need to run
1258 // the remainder and we can set the condition to true.
1259 // 3) Otherwise, construct a runtime check.
1260
1261 // We use the same DebugLoc as the scalar loop latch terminator instead of
1262 // the corresponding compare because they may have ended up with different
1263 // line numbers and we want to avoid awkward line stepping while debugging.
1264 // E.g., if the compare has got a line number inside the loop.
1265 auto *LatchVPBB = cast<VPBasicBlock>(MiddleVPBB->getSinglePredecessor());
1266 DebugLoc LatchDL = LatchVPBB->getTerminator()->getDebugLoc();
1267 VPBuilder Builder(MiddleVPBB);
1268 VPValue *Cmp;
1269 if (TailFolded)
1270 Cmp = Plan.getTrue();
1271 else
1272 Cmp = Builder.createICmp(CmpInst::ICMP_EQ, Plan.getTripCount(),
1273 &Plan.getVectorTripCount(), LatchDL, "cmp.n");
1274 Builder.createNaryOp(VPInstruction::BranchOnCond, {Cmp}, LatchDL);
1275}
1276
1278 VPDominatorTree VPDT(Plan);
1280 Plan.getEntry());
1281 for (VPBlockBase *HeaderVPB : POT)
1282 if (canonicalHeaderAndLatch(HeaderVPB, VPDT))
1283 createLoopRegion(Plan, HeaderVPB);
1284
1285 VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
1286 TopRegion->setName("vector loop");
1287 TopRegion->getEntryBasicBlock()->setName("vector.body");
1288}
1289
1291 assert(Plan.getExitBlocks().size() == 1 &&
1292 "only a single-exit block is supported currently");
1293 assert(Plan.getExitBlocks().front()->getSinglePredecessor() ==
1294 Plan.getMiddleBlock() &&
1295 "the exit block must have middle block as single predecessor");
1296
1297 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1298 assert(LoopRegion->getSingleSuccessor() == Plan.getMiddleBlock() &&
1299 "The vector loop region must have the middle block as its single "
1300 "successor for now");
1301 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
1302
1303 Header->splitAt(Header->getFirstNonPhi());
1304
1305 // Create the header mask, insert it in the header and branch on it.
1306 auto *IV = new VPWidenCanonicalIVRecipe(
1307 LoopRegion->getCanonicalIV(),
1308 VPIRFlags::WrapFlagsTy(LoopRegion->hasCanonicalIVNUW(), false));
1309 VPBuilder Builder(Header, Header->getFirstNonPhi());
1310 Builder.insert(IV);
1312 VPValue *HeaderMask = Builder.createICmp(CmpInst::ICMP_ULE, IV, BTC);
1313 Builder.createNaryOp(VPInstruction::BranchOnCond, HeaderMask);
1314
1315 VPBasicBlock *OrigLatch = LoopRegion->getExitingBasicBlock();
1316 VPValue *IVInc;
1317 [[maybe_unused]] bool TermBranchOnCount =
1318 match(OrigLatch->getTerminator(),
1320 m_Specific(&Plan.getVectorTripCount())));
1321 assert(TermBranchOnCount &&
1322 match(IVInc, m_Add(m_Specific(LoopRegion->getCanonicalIV()),
1323 m_Specific(&Plan.getVFxUF()))) &&
1324 std::next(IVInc->getDefiningRecipe()->getIterator()) ==
1325 OrigLatch->getTerminator()->getIterator() &&
1326 "Unexpected canonical iv increment");
1327
1328 // Split the latch at the IV update, and branch to it from the header mask.
1329 VPBasicBlock *Latch =
1330 OrigLatch->splitAt(IVInc->getDefiningRecipe()->getIterator());
1331 Latch->setName("vector.latch");
1332 VPBlockUtils::connectBlocks(Header, Latch);
1333
1334 // Collect any values defined in the loop that need a phi. Currently this
1335 // includes header phi backedges and live-outs extracted in the middle block.
1336 // TODO: Handle early exits via Plan.getExitBlocks()
1338 for (VPRecipeBase &R : Header->phis())
1340 NeedsPhi[cast<VPHeaderPHIRecipe>(R).getBackedgeValue()].push_back(&R);
1341
1342 VPValue *V;
1343 for (VPRecipeBase &R : *Plan.getMiddleBlock())
1344 if (match(&R, m_ExtractLastPart(m_VPValue(V))))
1345 NeedsPhi[V].push_back(&R);
1346
1347 // Insert phis for values coming past the end of the tail.
1348 Builder.setInsertPoint(Latch, Latch->begin());
1349 VPTypeAnalysis TypeInfo(Plan);
1350 for (const auto &[V, Users] : NeedsPhi) {
1351 if (isa<VPIRValue>(V))
1352 continue;
1353 VPValue *TailVal =
1355 VPIRFlags Flags;
1357 "Value used by more than two reduction phis?");
1359 auto *RdxPhi =
1360 RedIt != Users.end() ? cast<VPReductionPHIRecipe>(*RedIt) : nullptr;
1361 if (RdxPhi && !RdxPhi->isInLoop()) {
1362 TailVal = RdxPhi;
1363 Flags = *RdxPhi;
1364 }
1365
1366 VPInstruction *Phi = Builder.createScalarPhi({V, TailVal}, {}, "", Flags);
1367 for (VPUser *U : Users)
1368 U->replaceUsesOfWith(V, Phi);
1369 }
1370
1371 // Any extract of the last element must be updated to extract from the last
1372 // active lane of the header mask instead (i.e., the lane corresponding to the
1373 // last active iteration).
1374 Builder.setInsertPoint(Plan.getMiddleBlock()->getTerminator());
1375 for (VPRecipeBase &R : *Plan.getMiddleBlock()) {
1376 VPValue *Op;
1378 continue;
1379
1380 // Compute the index of the last active lane.
1381 VPValue *LastActiveLane = Builder.createLastActiveLane(HeaderMask);
1382 auto *Ext =
1383 Builder.createNaryOp(VPInstruction::ExtractLane, {LastActiveLane, Op});
1384 R.getVPSingleValue()->replaceAllUsesWith(Ext);
1385 }
1386}
1387
1388/// Insert \p CheckBlockVPBB on the edge leading to the vector preheader,
1389/// connecting it to both vector and scalar preheaders. Updates scalar
1390/// preheader phis to account for the new predecessor.
1392 VPBasicBlock *CheckBlockVPBB) {
1393 VPBlockBase *VectorPH = Plan.getVectorPreheader();
1394 auto *ScalarPH = cast<VPBasicBlock>(Plan.getScalarPreheader());
1395 VPBlockBase *PreVectorPH = VectorPH->getSinglePredecessor();
1396 VPBlockUtils::insertOnEdge(PreVectorPH, VectorPH, CheckBlockVPBB);
1397 VPBlockUtils::connectBlocks(CheckBlockVPBB, ScalarPH);
1398 CheckBlockVPBB->swapSuccessors();
1399 unsigned NumPreds = ScalarPH->getNumPredecessors();
1400 for (VPRecipeBase &R : ScalarPH->phis()) {
1401 auto *Phi = cast<VPPhi>(&R);
1402 assert(Phi->getNumIncoming() == NumPreds - 1 &&
1403 "must have incoming values for all predecessors");
1404 Phi->addOperand(Phi->getOperand(NumPreds - 2));
1405 }
1406}
1407
1408// Likelyhood of bypassing the vectorized loop due to a runtime check block,
1409// including memory overlap checks block and wrapping/unit-stride checks block.
1410static constexpr uint32_t CheckBypassWeights[] = {1, 127};
1411
1412/// Create a BranchOnCond terminator in \p CheckBlockVPBB. Optionally adds
1413/// branch weights.
1414static void addBypassBranch(VPlan &Plan, VPBasicBlock *CheckBlockVPBB,
1415 VPValue *Cond, bool AddBranchWeights) {
1417 auto *Term = VPBuilder(CheckBlockVPBB)
1419 if (AddBranchWeights) {
1420 MDBuilder MDB(Plan.getContext());
1421 MDNode *BranchWeights =
1422 MDB.createBranchWeights(CheckBypassWeights, /*IsExpected=*/false);
1423 Term->setMetadata(LLVMContext::MD_prof, BranchWeights);
1424 }
1425}
1426
1428 BasicBlock *CheckBlock,
1429 bool AddBranchWeights) {
1430 VPValue *CondVPV = Plan.getOrAddLiveIn(Cond);
1431 VPBasicBlock *CheckBlockVPBB = Plan.createVPIRBasicBlock(CheckBlock);
1432 insertCheckBlockBeforeVectorLoop(Plan, CheckBlockVPBB);
1433 addBypassBranch(Plan, CheckBlockVPBB, CondVPV, AddBranchWeights);
1434}
1435
1437 VPlan &Plan, ElementCount VF, unsigned UF,
1438 ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue,
1439 bool TailFolded, Loop *OrigLoop, const uint32_t *MinItersBypassWeights,
1441 // Generate code to check if the loop's trip count is less than VF * UF, or
1442 // equal to it in case a scalar epilogue is required; this implies that the
1443 // vector trip count is zero. This check also covers the case where adding one
1444 // to the backedge-taken count overflowed leading to an incorrect trip count
1445 // of zero. In this case we will also jump to the scalar loop.
1446 CmpInst::Predicate CmpPred =
1447 RequiresScalarEpilogue ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
1448 // If tail is to be folded, vector loop takes care of all iterations.
1449 VPValue *TripCountVPV = Plan.getTripCount();
1450 const SCEV *TripCount = vputils::getSCEVExprForVPValue(TripCountVPV, PSE);
1451 Type *TripCountTy = TripCount->getType();
1452 ScalarEvolution &SE = *PSE.getSE();
1453 auto GetMinTripCount = [&]() -> const SCEV * {
1454 // Compute max(MinProfitableTripCount, UF * VF) and return it.
1455 const SCEV *VFxUF =
1456 SE.getElementCount(TripCountTy, (VF * UF), SCEV::FlagNUW);
1457 if (UF * VF.getKnownMinValue() >=
1458 MinProfitableTripCount.getKnownMinValue()) {
1459 // TODO: SCEV should be able to simplify test.
1460 return VFxUF;
1461 }
1462 const SCEV *MinProfitableTripCountSCEV =
1463 SE.getElementCount(TripCountTy, MinProfitableTripCount, SCEV::FlagNUW);
1464 return SE.getUMaxExpr(MinProfitableTripCountSCEV, VFxUF);
1465 };
1466
1467 VPBuilder Builder(CheckBlock);
1468 VPValue *TripCountCheck = Plan.getFalse();
1469 const SCEV *Step = GetMinTripCount();
1470 // TripCountCheck = false, folding tail implies positive vector trip
1471 // count.
1472 if (!TailFolded) {
1473 // TODO: Emit unconditional branch to vector preheader instead of
1474 // conditional branch with known condition.
1475 TripCount = SE.applyLoopGuards(TripCount, OrigLoop);
1476 // Check if the trip count is < the step.
1477 if (SE.isKnownPredicate(CmpPred, TripCount, Step)) {
1478 // TODO: Ensure step is at most the trip count when determining max VF and
1479 // UF, w/o tail folding.
1480 TripCountCheck = Plan.getTrue();
1481 } else if (!SE.isKnownPredicate(CmpInst::getInversePredicate(CmpPred),
1482 TripCount, Step)) {
1483 // Generate the minimum iteration check only if we cannot prove the
1484 // check is known to be true, or known to be false.
1485 // // Try to expand SCEVs to VPInstructions in CheckBlock, or to
1486 // VPExpandSCEV in Entry failing that.
1487 VPValue *MinTripCountVPV = Builder.expandSCEV(Step, DL);
1488 if (!MinTripCountVPV)
1489 MinTripCountVPV = VPBuilder(Plan.getEntry()).createExpandSCEV(Step);
1490 TripCountCheck = Builder.createICmp(
1491 CmpPred, TripCountVPV, MinTripCountVPV, DL, "min.iters.check");
1492 } // else step known to be < trip count, use TripCountCheck preset to false.
1493 }
1494 VPInstruction *Term =
1495 Builder.createNaryOp(VPInstruction::BranchOnCond, {TripCountCheck}, DL);
1497 MDBuilder MDB(Plan.getContext());
1498 MDNode *BranchWeights = MDB.createBranchWeights(
1499 ArrayRef(MinItersBypassWeights, 2), /*IsExpected=*/false);
1500 Term->setMetadata(LLVMContext::MD_prof, BranchWeights);
1501 }
1502}
1503
1505 VPlan &Plan, ElementCount VF, unsigned UF, bool RequiresScalarEpilogue,
1506 Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL,
1508 auto *CheckBlock = Plan.createVPBasicBlock("vector.main.loop.iter.check");
1509 insertCheckBlockBeforeVectorLoop(Plan, CheckBlock);
1511 RequiresScalarEpilogue, /*TailFolded=*/false,
1512 OrigLoop, MinItersBypassWeights, DL, PSE,
1513 CheckBlock);
1514}
1515
1517 VPlan &Plan, Value *VectorTripCount, bool RequiresScalarEpilogue,
1518 ElementCount EpilogueVF, unsigned EpilogueUF, unsigned MainLoopStep,
1519 unsigned EpilogueLoopStep, ScalarEvolution &SE) {
1520 // Add the minimum iteration check for the epilogue vector loop.
1521 VPValue *TC = Plan.getTripCount();
1522 Value *TripCount = TC->getLiveInIRValue();
1523 VPBuilder Builder(cast<VPBasicBlock>(Plan.getEntry()));
1524 VPValue *VFxUF = Builder.createExpandSCEV(SE.getElementCount(
1525 TripCount->getType(), (EpilogueVF * EpilogueUF), SCEV::FlagNUW));
1526 VPValue *Count = Builder.createSub(TC, Plan.getOrAddLiveIn(VectorTripCount),
1527 DebugLoc::getUnknown(), "n.vec.remaining");
1528
1529 // Generate code to check if the loop's trip count is less than VF * UF of
1530 // the vector epilogue loop.
1531 auto P = RequiresScalarEpilogue ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
1532 auto *CheckMinIters = Builder.createICmp(
1533 P, Count, VFxUF, DebugLoc::getUnknown(), "min.epilog.iters.check");
1534 VPInstruction *Branch =
1535 Builder.createNaryOp(VPInstruction::BranchOnCond, CheckMinIters);
1536
1537 // We assume the remaining `Count` is equally distributed in
1538 // [0, MainLoopStep)
1539 // So the probability for `Count < EpilogueLoopStep` should be
1540 // min(MainLoopStep, EpilogueLoopStep) / MainLoopStep
1541 // TODO: Improve the estimate by taking the estimated trip count into
1542 // consideration.
1543 unsigned EstimatedSkipCount = std::min(MainLoopStep, EpilogueLoopStep);
1544 const uint32_t Weights[] = {EstimatedSkipCount,
1545 MainLoopStep - EstimatedSkipCount};
1546 MDBuilder MDB(Plan.getContext());
1547 MDNode *BranchWeights =
1548 MDB.createBranchWeights(Weights, /*IsExpected=*/false);
1549 Branch->setMetadata(LLVMContext::MD_prof, BranchWeights);
1550}
1551
1552/// Find and return the final select instruction of the FindIV result pattern
1553/// for the given \p BackedgeVal:
1554/// select(icmp ne ComputeReductionResult(ReducedIV), Sentinel),
1555/// ComputeReductionResult(ReducedIV), Start.
1557 return cast<VPInstruction>(
1558 vputils::findRecipe(BackedgeVal, [BackedgeVal](VPRecipeBase *R) {
1559 auto *VPI = dyn_cast<VPInstruction>(R);
1560 return VPI &&
1561 matchFindIVResult(VPI, m_Specific(BackedgeVal), m_VPValue());
1562 }));
1563}
1564
1566 auto GetMinOrMaxCompareValue =
1567 [](VPReductionPHIRecipe *RedPhiR) -> VPValue * {
1568 auto *MinOrMaxR =
1569 dyn_cast_or_null<VPRecipeWithIRFlags>(RedPhiR->getBackedgeValue());
1570 if (!MinOrMaxR)
1571 return nullptr;
1572
1573 // Check that MinOrMaxR is a VPWidenIntrinsicRecipe or VPReplicateRecipe
1574 // with an intrinsic that matches the reduction kind.
1575 Intrinsic::ID ExpectedIntrinsicID =
1576 getMinMaxReductionIntrinsicOp(RedPhiR->getRecurrenceKind());
1577 if (!match(MinOrMaxR, m_Intrinsic(ExpectedIntrinsicID)))
1578 return nullptr;
1579
1580 if (MinOrMaxR->getOperand(0) == RedPhiR)
1581 return MinOrMaxR->getOperand(1);
1582
1583 assert(MinOrMaxR->getOperand(1) == RedPhiR &&
1584 "Reduction phi operand expected");
1585 return MinOrMaxR->getOperand(0);
1586 };
1587
1588 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1590 MinOrMaxNumReductionsToHandle;
1591 bool HasUnsupportedPhi = false;
1592 for (auto &R : LoopRegion->getEntryBasicBlock()->phis()) {
1594 continue;
1595 auto *Cur = dyn_cast<VPReductionPHIRecipe>(&R);
1596 if (!Cur) {
1597 // TODO: Also support fixed-order recurrence phis.
1598 HasUnsupportedPhi = true;
1599 continue;
1600 }
1602 Cur->getRecurrenceKind())) {
1603 HasUnsupportedPhi = true;
1604 continue;
1605 }
1606
1607 VPValue *MinOrMaxOp = GetMinOrMaxCompareValue(Cur);
1608 if (!MinOrMaxOp)
1609 return false;
1610
1611 MinOrMaxNumReductionsToHandle.emplace_back(Cur, MinOrMaxOp);
1612 }
1613
1614 if (MinOrMaxNumReductionsToHandle.empty())
1615 return true;
1616
1617 // We won't be able to resume execution in the scalar tail, if there are
1618 // unsupported header phis or there is no scalar tail at all, due to
1619 // tail-folding.
1620 if (HasUnsupportedPhi || !Plan.hasScalarTail())
1621 return false;
1622
1623 /// Check if the vector loop of \p Plan can early exit and restart
1624 /// execution of last vector iteration in the scalar loop. This requires all
1625 /// recipes up to early exit point be side-effect free as they are
1626 /// re-executed. Currently we check that the loop is free of any recipe that
1627 /// may write to memory. Expected to operate on an early VPlan w/o nested
1628 /// regions.
1631 auto *VPBB = cast<VPBasicBlock>(VPB);
1632 for (auto &R : *VPBB) {
1633 if (R.mayWriteToMemory() && !match(&R, m_BranchOnCount()))
1634 return false;
1635 }
1636 }
1637
1638 VPBasicBlock *LatchVPBB = LoopRegion->getExitingBasicBlock();
1639 VPBuilder LatchBuilder(LatchVPBB->getTerminator());
1640 VPValue *AllNaNLanes = nullptr;
1641 SmallPtrSet<VPValue *, 2> RdxResults;
1642 for (const auto &[_, MinOrMaxOp] : MinOrMaxNumReductionsToHandle) {
1643 VPValue *RedNaNLanes =
1644 LatchBuilder.createFCmp(CmpInst::FCMP_UNO, MinOrMaxOp, MinOrMaxOp);
1645 AllNaNLanes = AllNaNLanes ? LatchBuilder.createOr(AllNaNLanes, RedNaNLanes)
1646 : RedNaNLanes;
1647 }
1648
1649 VPValue *AnyNaNLane =
1650 LatchBuilder.createNaryOp(VPInstruction::AnyOf, {AllNaNLanes});
1651 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
1652 VPBuilder MiddleBuilder(MiddleVPBB, MiddleVPBB->begin());
1653 for (const auto &[RedPhiR, _] : MinOrMaxNumReductionsToHandle) {
1655 RedPhiR->getRecurrenceKind()) &&
1656 "unsupported reduction");
1657
1658 // If we exit early due to NaNs, compute the final reduction result based on
1659 // the reduction phi at the beginning of the last vector iteration.
1660 auto *RdxResult = vputils::findComputeReductionResult(RedPhiR);
1661 assert(RdxResult && "must find a ComputeReductionResult");
1662
1663 auto *NewSel = MiddleBuilder.createSelect(AnyNaNLane, RedPhiR,
1664 RdxResult->getOperand(0));
1665 RdxResult->setOperand(0, NewSel);
1666 assert(!RdxResults.contains(RdxResult) && "RdxResult already used");
1667 RdxResults.insert(RdxResult);
1668 }
1669
1670 auto *LatchExitingBranch = LatchVPBB->getTerminator();
1671 assert(match(LatchExitingBranch, m_BranchOnCount(m_VPValue(), m_VPValue())) &&
1672 "Unexpected terminator");
1673 auto *IsLatchExitTaken = LatchBuilder.createICmp(
1674 CmpInst::ICMP_EQ, LatchExitingBranch->getOperand(0),
1675 LatchExitingBranch->getOperand(1));
1676 auto *AnyExitTaken = LatchBuilder.createOr(AnyNaNLane, IsLatchExitTaken);
1677 LatchBuilder.createNaryOp(VPInstruction::BranchOnCond, AnyExitTaken);
1678 LatchExitingBranch->eraseFromParent();
1679
1680 // Update resume phis for inductions in the scalar preheader. If AnyNaNLane is
1681 // true, the resume from the start of the last vector iteration via the
1682 // canonical IV, otherwise from the original value.
1683 auto IsTC = [&Plan](VPValue *V) {
1684 return V == &Plan.getVectorTripCount() || V == Plan.getTripCount();
1685 };
1686 for (auto &R : Plan.getScalarPreheader()->phis()) {
1687 auto *ResumeR = cast<VPPhi>(&R);
1688 VPValue *VecV = ResumeR->getOperand(0);
1689 if (RdxResults.contains(VecV))
1690 continue;
1691 if (auto *DerivedIV = dyn_cast<VPDerivedIVRecipe>(VecV)) {
1692 VPValue *DIVTC = DerivedIV->getOperand(1);
1693 if (DerivedIV->getNumUsers() == 1 && IsTC(DIVTC)) {
1694 auto *NewSel = MiddleBuilder.createSelect(
1695 AnyNaNLane, LoopRegion->getCanonicalIV(), DIVTC);
1696 DerivedIV->moveAfter(&*MiddleBuilder.getInsertPoint());
1697 DerivedIV->setOperand(1, NewSel);
1698 continue;
1699 }
1700 }
1701 // Bail out and abandon the current, partially modified, VPlan if we
1702 // encounter resume phi that cannot be updated yet.
1703 if (!IsTC(VecV)) {
1704 LLVM_DEBUG(dbgs() << "Found resume phi we cannot update for VPlan with "
1705 "FMaxNum/FMinNum reduction.\n");
1706 return false;
1707 }
1708 auto *NewSel = MiddleBuilder.createSelect(
1709 AnyNaNLane, LoopRegion->getCanonicalIV(), VecV);
1710 ResumeR->setOperand(0, NewSel);
1711 }
1712
1713 auto *MiddleTerm = MiddleVPBB->getTerminator();
1714 MiddleBuilder.setInsertPoint(MiddleTerm);
1715 VPValue *MiddleCond = MiddleTerm->getOperand(0);
1716 VPValue *NewCond =
1717 MiddleBuilder.createAnd(MiddleCond, MiddleBuilder.createNot(AnyNaNLane));
1718 MiddleTerm->setOperand(0, NewCond);
1719 return true;
1720}
1721
1723 if (Plan.hasScalarVFOnly())
1724 return false;
1725
1726 // We want to create the following nodes:
1727 // vector.body:
1728 // ...new WidenPHI recipe introduced to keep the mask value for the latest
1729 // iteration where any lane was active.
1730 // mask.phi = phi [ ir<false>, vector.ph ], [ vp<new.mask>, vector.body ]
1731 // ...data.phi (a VPReductionPHIRecipe for a FindLast reduction) already
1732 // exists, but needs updating to use 'new.data' for the backedge value.
1733 // data.phi = phi ir<default.val>, vp<new.data>
1734 //
1735 // ...'data' and 'compare' created by existing nodes...
1736 //
1737 // ...new recipes introduced to determine whether to update the reduction
1738 // values or keep the current one.
1739 // any.active = i1 any-of ir<compare>
1740 // new.mask = select vp<any.active>, ir<compare>, vp<mask.phi>
1741 // new.data = select vp<any.active>, ir<data>, ir<data.phi>
1742 //
1743 // middle.block:
1744 // ...extract-last-active replaces compute-reduction-result.
1745 // result = extract-last-active vp<new.data>, vp<new.mask>, ir<default.val>
1746
1748 for (VPRecipeBase &Phi :
1750 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&Phi);
1752 PhiR->getRecurrenceKind()))
1753 Phis.push_back(PhiR);
1754 }
1755
1756 if (Phis.empty())
1757 return true;
1758
1759 VPValue *HeaderMask = vputils::findHeaderMask(Plan);
1760 for (VPReductionPHIRecipe *PhiR : Phis) {
1761 // Find the condition for the select/blend.
1762 VPValue *BackedgeSelect = PhiR->getBackedgeValue();
1763 VPValue *CondSelect = BackedgeSelect;
1764
1765 // If there's a header mask, the backedge select will not be the find-last
1766 // select.
1767 if (HeaderMask && !match(BackedgeSelect,
1768 m_Select(m_Specific(HeaderMask),
1769 m_VPValue(CondSelect), m_Specific(PhiR))))
1770 return false;
1771
1772 VPValue *Cond = nullptr, *Op1 = nullptr, *Op2 = nullptr;
1773
1774 // If we're matching a blend rather than a select, there should be one
1775 // incoming value which is the data, then all other incoming values should
1776 // be the phi.
1777 auto MatchBlend = [&](VPRecipeBase *R) {
1778 auto *Blend = dyn_cast<VPBlendRecipe>(R);
1779 if (!Blend)
1780 return false;
1781 assert(!Blend->isNormalized() && "must run before blend normalizaion");
1782 unsigned NumIncomingDataValues = 0;
1783 for (unsigned I = 0; I < Blend->getNumIncomingValues(); ++I) {
1784 VPValue *Incoming = Blend->getIncomingValue(I);
1785 if (Incoming != PhiR) {
1786 ++NumIncomingDataValues;
1787 Cond = Blend->getMask(I);
1788 Op1 = Incoming;
1789 Op2 = PhiR;
1790 }
1791 }
1792 return NumIncomingDataValues == 1;
1793 };
1794
1795 VPSingleDefRecipe *SelectR =
1797 if (!match(SelectR,
1798 m_Select(m_VPValue(Cond), m_VPValue(Op1), m_VPValue(Op2))) &&
1799 !MatchBlend(SelectR))
1800 return false;
1801
1802 assert(Cond != HeaderMask && "Cond must not be HeaderMask");
1803
1804 // Find final reduction computation and replace it with an
1805 // extract.last.active intrinsic.
1806 auto *RdxResult =
1808 BackedgeSelect);
1809 assert(RdxResult && "Could not find reduction result");
1810
1811 // Add mask phi.
1812 VPBuilder Builder = VPBuilder::getToInsertAfter(PhiR);
1813 auto *MaskPHI = Builder.createWidenPhi(Plan.getFalse());
1814
1815 // Add select for mask.
1816 Builder.setInsertPoint(SelectR);
1817
1818 if (Op1 == PhiR) {
1819 // Normalize to selecting the data operand when the condition is true by
1820 // swapping operands and negating the condition.
1821 std::swap(Op1, Op2);
1822 Cond = Builder.createNot(Cond);
1823 }
1824 assert(Op2 == PhiR && "data value must be selected if Cond is true");
1825
1826 if (HeaderMask)
1827 Cond = Builder.createLogicalAnd(HeaderMask, Cond);
1828
1829 VPValue *AnyOf = Builder.createNaryOp(VPInstruction::AnyOf, {Cond});
1830 VPValue *MaskSelect = Builder.createSelect(AnyOf, Cond, MaskPHI);
1831 MaskPHI->addOperand(MaskSelect);
1832
1833 // Replace select for data.
1834 VPValue *DataSelect =
1835 Builder.createSelect(AnyOf, Op1, Op2, SelectR->getDebugLoc());
1836 SelectR->replaceAllUsesWith(DataSelect);
1837 PhiR->setBackedgeValue(DataSelect);
1838 SelectR->eraseFromParent();
1839
1840 Builder.setInsertPoint(RdxResult);
1841 auto *ExtractLastActive =
1842 Builder.createNaryOp(VPInstruction::ExtractLastActive,
1843 {PhiR->getStartValue(), DataSelect, MaskSelect},
1844 RdxResult->getDebugLoc());
1845 RdxResult->replaceAllUsesWith(ExtractLastActive);
1846 RdxResult->eraseFromParent();
1847 }
1848
1849 return true;
1850}
1851
1852/// Given a first argmin/argmax pattern with strict predicate consisting of
1853/// 1) a MinOrMax reduction \p MinOrMaxPhiR producing \p MinOrMaxResult,
1854/// 2) a wide induction \p WideIV,
1855/// 3) a FindLastIV reduction \p FindLastIVPhiR using \p WideIV,
1856/// return the smallest index of the FindLastIV reduction result using UMin,
1857/// unless \p MinOrMaxResult equals the start value of its MinOrMax reduction.
1858/// In that case, return the start value of the FindLastIV reduction instead.
1859/// If \p WideIV is not canonical, a new canonical wide IV is added, and the
1860/// final result is scaled back to the non-canonical \p WideIV.
1861/// The final value of the FindLastIV reduction is originally computed using
1862/// \p FindIVSelect, \p FindIVCmp, and \p FindIVRdxResult, which are replaced
1863/// and removed.
1864/// Returns true if the pattern was handled successfully, false otherwise.
1866 VPlan &Plan, VPReductionPHIRecipe *MinOrMaxPhiR,
1867 VPReductionPHIRecipe *FindLastIVPhiR, VPWidenIntOrFpInductionRecipe *WideIV,
1868 VPInstruction *MinOrMaxResult, VPInstruction *FindIVSelect,
1869 VPRecipeBase *FindIVCmp, VPInstruction *FindIVRdxResult) {
1870 assert(!FindLastIVPhiR->isInLoop() && !FindLastIVPhiR->isOrdered() &&
1871 "inloop and ordered reductions not supported");
1872 assert(FindLastIVPhiR->getVFScaleFactor() == 1 &&
1873 "FindIV reduction must not be scaled");
1874
1876 // TODO: Support non (i.e., narrower than) canonical IV types.
1877 // TODO: Emit remarks for failed transformations.
1878 if (Ty != VPTypeAnalysis(Plan).inferScalarType(WideIV))
1879 return false;
1880
1881 auto *FindIVSelectR = cast<VPSingleDefRecipe>(
1882 FindLastIVPhiR->getBackedgeValue()->getDefiningRecipe());
1883 assert(
1884 match(FindIVSelectR, m_Select(m_VPValue(), m_VPValue(), m_VPValue())) &&
1885 "backedge value must be a select");
1886 if (FindIVSelectR->getOperand(1) != WideIV &&
1887 FindIVSelectR->getOperand(2) != WideIV)
1888 return false;
1889
1890 // If the original wide IV is not canonical, create a new one. The canonical
1891 // wide IV is guaranteed to not wrap for all lanes that are active in the
1892 // vector loop.
1893 if (!WideIV->isCanonical()) {
1894 VPIRValue *Zero = Plan.getConstantInt(Ty, 0);
1895 VPIRValue *One = Plan.getConstantInt(Ty, 1);
1896 auto *WidenCanIV = new VPWidenIntOrFpInductionRecipe(
1897 nullptr, Zero, One, WideIV->getVFValue(),
1898 WideIV->getInductionDescriptor(),
1899 VPIRFlags::WrapFlagsTy(/*HasNUW=*/true, /*HasNSW=*/false),
1900 WideIV->getDebugLoc());
1901 WidenCanIV->insertBefore(WideIV);
1902
1903 // Update the select to use the wide canonical IV.
1904 FindIVSelectR->setOperand(FindIVSelectR->getOperand(1) == WideIV ? 1 : 2,
1905 WidenCanIV);
1906 }
1907 FindLastIVPhiR->setOperand(0, Plan.getOrAddLiveIn(PoisonValue::get(Ty)));
1908
1909 // The reduction using MinOrMaxPhiR needs adjusting to compute the correct
1910 // result:
1911 // 1. Find the first canonical indices corresponding to partial min/max
1912 // values, using loop reductions.
1913 // 2. Find which of the partial min/max values are equal to the overall
1914 // min/max value.
1915 // 3. Select among the canonical indices those corresponding to the overall
1916 // min/max value.
1917 // 4. Find the first canonical index of overall min/max and scale it back to
1918 // the original IV using VPDerivedIVRecipe.
1919 // 5. If the overall min/max equals the starting min/max, the condition in
1920 // the loop was always false, due to being strict; return the start value
1921 // of FindLastIVPhiR in that case.
1922 //
1923 // For example, we transforms two independent reduction result computations
1924 // for
1925 //
1926 // <x1> vector loop: {
1927 // vector.body:
1928 // ...
1929 // ir<%iv> = WIDEN-INDUCTION nuw nsw ir<10>, ir<1>, vp<%0>
1930 // WIDEN-REDUCTION-PHI ir<%min.idx> = phi ir<sentinel.min.start>,
1931 // ir<%min.idx.next>
1932 // WIDEN-REDUCTION-PHI ir<%min.val> = phi ir<100>, ir<%min.val.next>
1933 // ....
1934 // WIDEN-INTRINSIC ir<%min.val.next> = call llvm.umin(ir<%min.val>, ir<%l>)
1935 // WIDEN ir<%min.idx.next> = select ir<%cmp>, ir<%iv>, ir<%min.idx>
1936 // ...
1937 // }
1938 // Successor(s): middle.block
1939 //
1940 // middle.block:
1941 // vp<%iv.rdx> = compute-reduction-result (smax) vp<%min.idx.next>
1942 // vp<%min.result> = compute-reduction-result (umin) ir<%min.val.next>
1943 // vp<%cmp> = icmp ne vp<%iv.rdx>, ir<sentinel.min.start>
1944 // vp<%find.iv.result> = select vp<%cmp>, vp<%iv.rdx>, ir<10>
1945 //
1946 //
1947 // Into:
1948 //
1949 // vp<%reduced.min> = compute-reduction-result (umin) ir<%min.val.next>
1950 // vp<%reduced.mins.mask> = icmp eq ir<%min.val.next>, vp<%reduced.min>
1951 // vp<%idxs2reduce> = select vp<%reduced.mins.mask>, ir<%min.idx.next>,
1952 // ir<MaxUInt>
1953 // vp<%reduced.idx> = compute-reduction-result (umin) vp<%idxs2reduce>
1954 // vp<%scaled.idx> = DERIVED-IV ir<20> + vp<%reduced.idx> * ir<1>
1955 // vp<%always.false> = icmp eq vp<%reduced.min>, ir<100>
1956 // vp<%final.idx> = select vp<%always.false>, ir<10>,
1957 // vp<%scaled.idx>
1958
1959 VPBuilder Builder(FindIVRdxResult);
1960 VPValue *MinOrMaxExiting = MinOrMaxResult->getOperand(0);
1961 auto *FinalMinOrMaxCmp =
1962 Builder.createICmp(CmpInst::ICMP_EQ, MinOrMaxExiting, MinOrMaxResult);
1963 VPValue *LastIVExiting = FindIVRdxResult->getOperand(0);
1964 VPValue *MaxIV =
1965 Plan.getConstantInt(APInt::getMaxValue(Ty->getIntegerBitWidth()));
1966 auto *FinalIVSelect =
1967 Builder.createSelect(FinalMinOrMaxCmp, LastIVExiting, MaxIV);
1968 VPIRFlags RdxFlags(RecurKind::UMin, false, false, FastMathFlags());
1969 VPSingleDefRecipe *FinalCanIV = Builder.createNaryOp(
1970 VPInstruction::ComputeReductionResult, {FinalIVSelect}, RdxFlags,
1971 FindIVRdxResult->getDebugLoc());
1972
1973 // If we used a new wide canonical IV convert the reduction result back to the
1974 // original IV scale before the final select.
1975 if (!WideIV->isCanonical()) {
1976 auto *DerivedIVRecipe = new VPDerivedIVRecipe(
1978 nullptr, // No FPBinOp for integer induction
1979 WideIV->getStartValue(), FinalCanIV, WideIV->getStepValue());
1980 DerivedIVRecipe->insertBefore(&*Builder.getInsertPoint());
1981 FinalCanIV = DerivedIVRecipe;
1982 }
1983
1984 // If the final min/max value matches its start value, the condition in the
1985 // loop was always false, i.e. no induction value has been selected. If that's
1986 // the case, set the result of the IV reduction to its start value.
1987 VPValue *AlwaysFalse = Builder.createICmp(CmpInst::ICMP_EQ, MinOrMaxResult,
1988 MinOrMaxPhiR->getStartValue());
1989 VPValue *FinalIV = Builder.createSelect(
1990 AlwaysFalse, FindIVSelect->getOperand(2), FinalCanIV);
1991 FindIVSelect->replaceAllUsesWith(FinalIV);
1992
1993 // Erase the old FindIV result pattern which is now dead.
1994 FindIVSelect->eraseFromParent();
1995 FindIVCmp->eraseFromParent();
1996 FindIVRdxResult->eraseFromParent();
1997 return true;
1998}
1999
2002 Loop *TheLoop) {
2003 for (auto &PhiR : make_early_inc_range(
2005 auto *MinOrMaxPhiR = dyn_cast<VPReductionPHIRecipe>(&PhiR);
2006 // TODO: check for multi-uses in VPlan directly.
2007 if (!MinOrMaxPhiR || !MinOrMaxPhiR->hasUsesOutsideReductionChain())
2008 continue;
2009
2010 // MinOrMaxPhiR has users outside the reduction cycle in the loop. Check if
2011 // the only other user is a FindLastIV reduction. MinOrMaxPhiR must have
2012 // exactly 2 users:
2013 // 1) the min/max operation of the reduction cycle, and
2014 // 2) the compare of a FindLastIV reduction cycle. This compare must match
2015 // the min/max operation - comparing MinOrMaxPhiR with the operand of the
2016 // min/max operation, and be used only by the select of the FindLastIV
2017 // reduction cycle.
2018 RecurKind RdxKind = MinOrMaxPhiR->getRecurrenceKind();
2019 assert(
2021 "only min/max recurrences support users outside the reduction chain");
2022
2023 auto *MinOrMaxOp =
2024 dyn_cast<VPRecipeWithIRFlags>(MinOrMaxPhiR->getBackedgeValue());
2025 if (!MinOrMaxOp)
2026 return false;
2027
2028 // Check that MinOrMaxOp is a VPWidenIntrinsicRecipe or VPReplicateRecipe
2029 // with an intrinsic that matches the reduction kind.
2030 Intrinsic::ID ExpectedIntrinsicID = getMinMaxReductionIntrinsicOp(RdxKind);
2031 if (!match(MinOrMaxOp, m_Intrinsic(ExpectedIntrinsicID)))
2032 return false;
2033
2034 // MinOrMaxOp must have 2 users: 1) MinOrMaxPhiR and 2)
2035 // ComputeReductionResult.
2036 assert(MinOrMaxOp->getNumUsers() == 2 &&
2037 "MinOrMaxOp must have exactly 2 users");
2038 VPValue *MinOrMaxOpValue = MinOrMaxOp->getOperand(0);
2039 if (MinOrMaxOpValue == MinOrMaxPhiR)
2040 MinOrMaxOpValue = MinOrMaxOp->getOperand(1);
2041
2042 VPValue *CmpOpA;
2043 VPValue *CmpOpB;
2044 CmpPredicate Pred;
2046 MinOrMaxPhiR, m_Cmp(Pred, m_VPValue(CmpOpA), m_VPValue(CmpOpB))));
2047 if (!Cmp || Cmp->getNumUsers() != 1 ||
2048 (CmpOpA != MinOrMaxOpValue && CmpOpB != MinOrMaxOpValue))
2049 return false;
2050
2051 if (MinOrMaxOpValue != CmpOpB)
2052 Pred = CmpInst::getSwappedPredicate(Pred);
2053
2054 // MinOrMaxPhiR must have exactly 2 users:
2055 // * MinOrMaxOp,
2056 // * Cmp (that's part of a FindLastIV chain).
2057 if (MinOrMaxPhiR->getNumUsers() != 2)
2058 return false;
2059
2060 VPInstruction *MinOrMaxResult =
2062 assert(is_contained(MinOrMaxPhiR->users(), MinOrMaxOp) &&
2063 "one user must be MinOrMaxOp");
2064 assert(MinOrMaxResult && "MinOrMaxResult must be a user of MinOrMaxOp");
2065
2066 // Cmp must be used by the select of a FindLastIV chain.
2067 VPValue *Sel = dyn_cast<VPSingleDefRecipe>(Cmp->getSingleUser());
2068 VPValue *IVOp, *FindIV;
2069 if (!Sel || Sel->getNumUsers() != 2 ||
2070 !match(Sel,
2072 return false;
2073
2075 std::swap(FindIV, IVOp);
2076 Pred = CmpInst::getInversePredicate(Pred);
2077 }
2078
2079 auto *FindIVPhiR = dyn_cast<VPReductionPHIRecipe>(FindIV);
2081 FindIVPhiR->getRecurrenceKind()))
2082 return false;
2083
2084 assert(!FindIVPhiR->isInLoop() && !FindIVPhiR->isOrdered() &&
2085 "cannot handle inloop/ordered reductions yet");
2086
2087 // Check if FindIVPhiR is a FindLast pattern by checking the MinMaxKind
2088 // on its ComputeReductionResult. SMax/UMax indicates FindLast.
2089 VPInstruction *FindIVResult =
2091 FindIVPhiR->getBackedgeValue());
2092 assert(FindIVResult &&
2093 "must be able to retrieve the FindIVResult VPInstruction");
2094 RecurKind FindIVMinMaxKind = FindIVResult->getRecurKind();
2095 if (FindIVMinMaxKind != RecurKind::SMax &&
2096 FindIVMinMaxKind != RecurKind::UMax)
2097 return false;
2098
2099 // TODO: Support cases where IVOp is the IV increment.
2100 if (!match(IVOp, m_TruncOrSelf(m_VPValue(IVOp))) ||
2102 return false;
2103
2104 // Check if the predicate is compatible with the reduction kind.
2105 bool IsValidKindPred = [RdxKind, Pred]() {
2106 switch (RdxKind) {
2107 case RecurKind::UMin:
2108 return Pred == CmpInst::ICMP_UGE || Pred == CmpInst::ICMP_UGT;
2109 case RecurKind::UMax:
2110 return Pred == CmpInst::ICMP_ULE || Pred == CmpInst::ICMP_ULT;
2111 case RecurKind::SMax:
2112 return Pred == CmpInst::ICMP_SLE || Pred == CmpInst::ICMP_SLT;
2113 case RecurKind::SMin:
2114 return Pred == CmpInst::ICMP_SGE || Pred == CmpInst::ICMP_SGT;
2115 default:
2116 llvm_unreachable("unhandled recurrence kind");
2117 }
2118 }();
2119 if (!IsValidKindPred) {
2120 ORE->emit([&]() {
2122 DEBUG_TYPE, "VectorizationMultiUseReductionPredicate",
2123 TheLoop->getStartLoc(), TheLoop->getHeader())
2124 << "Multi-use reduction with predicate "
2126 << " incompatible with reduction kind";
2127 });
2128 return false;
2129 }
2130
2131 auto *FindIVSelect = findFindIVSelect(FindIVPhiR->getBackedgeValue());
2132 auto *FindIVCmp = FindIVSelect->getOperand(0)->getDefiningRecipe();
2133 auto *FindIVRdxResult = cast<VPInstruction>(FindIVCmp->getOperand(0));
2134 assert(FindIVSelect->getParent() == MinOrMaxResult->getParent() &&
2135 "both results must be computed in the same block");
2136 // Reducing to a scalar min or max value is placed right before reducing to
2137 // its scalar iteration, in order to generate instructions that use both
2138 // their operands.
2139 MinOrMaxResult->moveBefore(*FindIVRdxResult->getParent(),
2140 FindIVRdxResult->getIterator());
2141
2142 bool IsStrictPredicate = ICmpInst::isLT(Pred) || ICmpInst::isGT(Pred);
2143 if (IsStrictPredicate) {
2144 if (!handleFirstArgMinOrMax(Plan, MinOrMaxPhiR, FindIVPhiR,
2146 MinOrMaxResult, FindIVSelect, FindIVCmp,
2147 FindIVRdxResult))
2148 return false;
2149 continue;
2150 }
2151
2152 // The reduction using MinOrMaxPhiR needs adjusting to compute the correct
2153 // result:
2154 // 1. We need to find the last IV for which the condition based on the
2155 // min/max recurrence is true,
2156 // 2. Compare the partial min/max reduction result to its final value and,
2157 // 3. Select the lanes of the partial FindLastIV reductions which
2158 // correspond to the lanes matching the min/max reduction result.
2159 //
2160 // For example, this transforms
2161 // vp<%min.result> = compute-reduction-result ir<%min.val.next>
2162 // vp<%iv.rdx> = compute-reduction-result (smax) vp<%min.idx.next>
2163 // vp<%cmp> = icmp ne vp<%iv.rdx>, SENTINEL
2164 // vp<%find.iv.result> = select vp<%cmp>, vp<%iv.rdx>, ir<0>
2165 //
2166 // into:
2167 //
2168 // vp<min.result> = compute-reduction-result ir<%min.val.next>
2169 // vp<%final.min.cmp> = icmp eq ir<%min.val.next>, vp<min.result>
2170 // vp<%final.iv> = select vp<%final.min.cmp>, vp<%min.idx.next>, SENTINEL
2171 // vp<%iv.rdx> = compute-reduction-result (smax) vp<%final.iv>
2172 // vp<%cmp> = icmp ne vp<%iv.rdx>, SENTINEL
2173 // vp<%find.iv.result> = select vp<%cmp>, vp<%iv.rdx>, ir<0>
2174 //
2175 VPBuilder B(FindIVRdxResult);
2176 VPValue *MinOrMaxExiting = MinOrMaxResult->getOperand(0);
2177 auto *FinalMinOrMaxCmp =
2178 B.createICmp(CmpInst::ICMP_EQ, MinOrMaxExiting, MinOrMaxResult);
2179 VPValue *Sentinel = FindIVCmp->getOperand(1);
2180 VPValue *LastIVExiting = FindIVRdxResult->getOperand(0);
2181 auto *FinalIVSelect =
2182 B.createSelect(FinalMinOrMaxCmp, LastIVExiting, Sentinel);
2183 FindIVRdxResult->setOperand(0, FinalIVSelect);
2184 }
2185 return true;
2186}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
#define _
iv Induction Variable Users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
static constexpr uint32_t MinItersBypassWeights[]
#define I(x, y, z)
Definition MD5.cpp:57
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
static void createLoopRegion(VPlan &Plan, VPBlockBase *HeaderVPB)
Create a new VPRegionBlock for the loop starting at HeaderVPB.
static bool isHeaderBB(BasicBlock *BB, Loop *L)
static bool handleFirstArgMinOrMax(VPlan &Plan, VPReductionPHIRecipe *MinOrMaxPhiR, VPReductionPHIRecipe *FindLastIVPhiR, VPWidenIntOrFpInductionRecipe *WideIV, VPInstruction *MinOrMaxResult, VPInstruction *FindIVSelect, VPRecipeBase *FindIVCmp, VPInstruction *FindIVRdxResult)
Given a first argmin/argmax pattern with strict predicate consisting of 1) a MinOrMax reduction MinOr...
static VPHeaderPHIRecipe * createWidenInductionRecipe(PHINode *Phi, VPPhi *PhiR, VPIRValue *Start, const InductionDescriptor &IndDesc, VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, DebugLoc DL)
Creates a VPWidenIntOrFpInductionRecipe or VPWidenPointerInductionRecipe for Phi based on IndDesc.
static void insertCheckBlockBeforeVectorLoop(VPlan &Plan, VPBasicBlock *CheckBlockVPBB)
Insert CheckBlockVPBB on the edge leading to the vector preheader, connecting it to both vector and s...
static void simplifyLiveInsWithSCEV(VPlan &Plan, PredicatedScalarEvolution &PSE)
Check Plan's live-in and replace them with constants, if they can be simplified via SCEV.
static bool sinkRecurrenceUsersAfterPrevious(VPFirstOrderRecurrencePHIRecipe *FOR, VPRecipeBase *Previous, VPDominatorTree &VPDT)
Try to sink users of FOR after Previous.
static bool tryToSinkOrHoistRecurrenceUsers(VPBasicBlock *HeaderVPBB, VPDominatorTree &VPDT)
Sink users of fixed-order recurrences past or hoist before the recipe defining the previous value,...
static void addBypassBranch(VPlan &Plan, VPBasicBlock *CheckBlockVPBB, VPValue *Cond, bool AddBranchWeights)
Create a BranchOnCond terminator in CheckBlockVPBB.
static bool canonicalHeaderAndLatch(VPBlockBase *HeaderVPB, const VPDominatorTree &VPDT)
Checks if HeaderVPB is a loop header block in the plain CFG; that is, it has exactly 2 predecessors (...
static bool hoistPreviousBeforeFORUsers(VPFirstOrderRecurrencePHIRecipe *FOR, VPRecipeBase *Previous, VPDominatorTree &VPDT)
Try to hoist Previous and its operands before all users of FOR.
static void addInitialSkeleton(VPlan &Plan, Type *InductionTy, PredicatedScalarEvolution &PSE, Loop *TheLoop)
static bool areAllLoadsDereferenceable(VPBasicBlock *HeaderVPBB, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC)
Check if all loads in the loop are dereferenceable.
static VPInstruction * findFindIVSelect(VPValue *BackedgeVal)
Find and return the final select instruction of the FindIV result pattern for the given BackedgeVal: ...
static constexpr uint32_t CheckBypassWeights[]
static void printAfterInitialConstruction(VPlan &)
To make RUN_VPLAN_PASS print initial VPlan.
static void createExtractsForLiveOuts(VPlan &Plan, VPBasicBlock *MiddleVPBB)
Creates extracts for values in Plan defined in a loop region and used outside a loop region.
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
This file contains the declarations of different VPlan-related auxiliary helpers.
This file provides utility VPlan to VPlan transformations.
#define RUN_VPLAN_PASS_NO_VERIFY(PASS,...)
This file contains the declarations of the Vectorization Plan base classes:
static const uint32_t IV[8]
Definition blake3_impl.h:83
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
static LLVM_ABI StringRef getPredicateName(Predicate P)
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:123
static DebugLoc getUnknown()
Definition DebugLoc.h:161
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:205
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:159
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:320
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
static FastMathFlags getFast()
Definition FMF.h:53
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
A struct for saving information about induction variables.
InductionKind getKind() const
const SCEV * getStep() const
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
Value * getStartValue() const
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
std::pair< MDNode *, MDNode * > getNoAliasMetadataFor(const Instruction *OrigInst) const
Returns a pair containing the alias_scope and noalias metadata nodes for OrigInst,...
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:659
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
Metadata node.
Definition Metadata.h:1080
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
iterator find(const KeyT &Key)
Definition MapVector.h:156
iterator end()
Definition MapVector.h:69
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Post-order traversal of a graph.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
static bool isFMulAddIntrinsic(Instruction *I)
Returns true if the instruction is a call to the llvm.fmuladd intrinsic.
FastMathFlags getFastMathFlags() const
static bool isFPMinMaxNumRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating-point minnum/maxnum kind.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
static bool isFindLastRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
TrackingVH< Value > getRecurrenceStartValue() const
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
RecurKind getRecurrenceKind() const
bool isOrdered() const
Expose an ordered FP reduction to the instance users.
static LLVM_ABI bool isFloatingPointRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating point kind.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isIntMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is an integer min/max kind.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
static constexpr auto FlagNUW
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
op_range operands()
Definition User.h:267
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4263
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4338
iterator end()
Definition VPlan.h:4300
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4298
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4351
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:266
VPBasicBlock * splitAt(iterator SplitAt)
Split current block at SplitAt by inserting a new block between the current block and its successors ...
Definition VPlan.cpp:582
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:661
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4329
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:93
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
Definition VPlan.h:314
VPRegionBlock * getParent()
Definition VPlan.h:185
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:236
void setName(const Twine &newName)
Definition VPlan.h:178
size_t getNumSuccessors() const
Definition VPlan.h:236
void swapSuccessors()
Swap successors of the block. The block must have exactly 2 successors.
Definition VPlan.h:336
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition VPlan.h:305
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:221
void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse)
Set two given VPBlockBases IfTrue and IfFalse to be the two successors of this VPBlockBase.
Definition VPlan.h:296
VPBlockBase * getSinglePredecessor() const
Definition VPlan.h:232
void swapPredecessors()
Swap predecessors of the block.
Definition VPlan.h:328
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:216
void setOneSuccessor(VPBlockBase *Successor)
Set a given VPBlockBase Successor as the single successor of this VPBlockBase.
Definition VPlan.h:285
void setParent(VPRegionBlock *P)
Definition VPlan.h:196
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:226
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:210
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
Definition VPlanUtils.h:193
static void insertOnEdge(VPBlockBase *From, VPBlockBase *To, VPBlockBase *BlockPtr)
Inserts BlockPtr on the edge between From and To.
Definition VPlanUtils.h:333
static VPBasicBlock * getPlainCFGMiddleBlock(const VPlan &Plan)
Returns the middle block of Plan in plain CFG form (before regions are formed).
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:241
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:259
static std::pair< VPBasicBlock *, VPBasicBlock * > getPlainCFGHeaderAndLatch(const VPlan &Plan)
Returns the header and latch of the outermost loop of Plan in plain CFG form (before regions are form...
static void transferSuccessors(VPBlockBase *Old, VPBlockBase *New)
Transfer successors from Old to New. New must have no successors.
Definition VPlanUtils.h:279
VPlan-based builder utility analogous to IRBuilder.
VPInstruction * createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createNot(VPValue *Operand, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPBasicBlock::iterator getInsertPoint() const
VPInstruction * createScalarCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, DebugLoc DL, const VPIRMetadata &Metadata={})
VPInstruction * createFCmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new FCmp VPInstruction with predicate Pred and operands A and B.
VPInstructionWithType * createScalarLoad(Type *ResultTy, VPValue *Addr, DebugLoc DL, const VPIRMetadata &Metadata={})
static VPBuilder getToInsertAfter(VPRecipeBase *R)
Create a VPBuilder to insert after R.
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", const VPIRFlags &Flags={})
VPInstruction * createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new ICmp VPInstruction with predicate Pred and operands A and B.
VPInstruction * createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", const VPIRFlags &Flags={})
VPExpandSCEVRecipe * createExpandSCEV(const SCEV *Expr)
void setInsertPoint(VPBasicBlock *TheBB)
This specifies that created VPInstructions should be appended to the end of the specified block.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:559
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:532
A recipe for converting the input value IV value to the corresponding value of an IV with different s...
Definition VPlan.h:4038
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B)
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2395
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2442
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2431
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4416
Class to record and manage LLVM IR flags.
Definition VPlan.h:696
RecurKind getRecurKind() const
Definition VPlan.h:1059
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1227
@ ExtractLastActive
Extracts the last active lane from a set of vectors.
Definition VPlan.h:1325
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1316
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1329
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1270
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:401
VPBasicBlock * getParent()
Definition VPlan.h:476
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:554
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
A recipe for handling reduction phis.
Definition VPlan.h:2789
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2854
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
Definition VPlan.h:2833
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2857
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3150
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4473
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4593
bool hasCanonicalIVNUW() const
Indicates if NUW is set for the canonical IV increment, for loop regions.
Definition VPlan.h:4598
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4585
DebugLoc getDebugLoc() const
Returns the debug location of the VPRegionValue.
Definition VPlanValue.h:234
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:610
An analysis for type-inference for VPValues.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:384
operand_range operands()
Definition VPlanValue.h:455
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:428
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:423
void addOperand(VPValue *Operand)
Definition VPlanValue.h:417
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:143
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:130
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:208
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1511
unsigned getNumUsers() const
Definition VPlanValue.h:115
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser &U, unsigned Idx)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1517
user_range users()
Definition VPlanValue.h:157
A Recipe for widening the canonical induction variable of the vector loop.
Definition VPlan.h:3988
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2503
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2523
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2554
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2601
bool isCanonical() const
Returns true if the induction is canonical, i.e.
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4621
VPIRValue * getLiveIn(Value *V) const
Return the live-in VPIRValue for V, if there is one or nullptr otherwise.
Definition VPlan.h:4946
LLVMContext & getContext() const
Definition VPlan.h:4822
VPBasicBlock * getEntry()
Definition VPlan.h:4717
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4780
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
Definition VPlan.h:4801
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:4917
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:4820
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:4949
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:4770
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4810
VPIRValue * getOrAddLiveIn(Value *V)
Gets the live-in VPIRValue for V or adds a new live-in (if none exists yet) for V.
Definition VPlan.h:4894
VPRegionBlock * createLoopRegion(Type *CanIVTy, DebugLoc DL, const std::string &Name="", VPBlockBase *Entry=nullptr, VPBlockBase *Exiting=nullptr)
Create a new loop region with a canonical IV using CanIVTy and DL.
Definition VPlan.h:4983
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:4920
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1098
void setTripCount(VPValue *NewTripCount)
Set the trip count assuming it is currently null; if it is not - use resetTripCount().
Definition VPlan.h:4787
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4746
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:4972
LLVM_ABI_FOR_TEST VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
Definition VPlan.cpp:1348
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:4914
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4722
bool hasScalarVFOnly() const
Definition VPlan.h:4862
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:4760
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:4766
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4813
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
Definition VPlan.h:5027
VPIRValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given type and value.
Definition VPlan.h:4928
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
VPInstruction_match< VPInstruction::ExtractLastLane, VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > > m_ExtractLastLaneOfLastPart(const Op0_t &Op0)
bool matchFindIVResult(VPInstruction *VPI, Op0_t ReducedIV, Op1_t Start)
Match FindIV result pattern: select(icmp ne ComputeReductionResult(ReducedIV), Sentinel),...
VPInstruction_match< VPInstruction::ExtractLastLane, Op0_t > m_ExtractLastLane(const Op0_t &Op0)
VPInstruction_match< VPInstruction::BranchOnCount > m_BranchOnCount()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > m_ExtractLastPart(const Op0_t &Op0)
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
VPInstruction_match< VPInstruction::BranchOnCond > m_BranchOnCond()
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr)
Get or create a VPValue that corresponds to the expansion of Expr.
bool cannotHoistOrSinkRecipe(const VPRecipeBase &R, bool Sinking=false)
Return true if we do not know how to (mechanically) hoist or sink R.
VPInstruction * findComputeReductionResult(VPReductionPHIRecipe *PhiR)
Find the ComputeReductionResult recipe for PhiR, looking through selects inserted for predicated redu...
VPIRFlags getFlagsFromIndDesc(const InductionDescriptor &ID)
Extracts and returns NoWrap and FastMath flags from the induction binop in ID.
Definition VPlanUtils.h:99
VPRecipeBase * findRecipe(VPValue *Start, PredT Pred)
Search Start's users for a recipe satisfying Pred, looking through recipes with definitions.
Definition VPlanUtils.h:116
VPSingleDefRecipe * findHeaderMask(VPlan &Plan)
Collect the header mask with the pattern: (ICMP_ULE, WideCanonicalIV, backedge-taken-count) TODO: Int...
static VPRecipeBase * findUserOf(VPValue *V, const MatchT &P)
If V is used by a recipe matching pattern P, return it.
Definition VPlanUtils.h:137
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
SmallVector< VPBasicBlock * > vp_rpo_plain_cfg_loop_body(VPBasicBlock *Header)
Returns the VPBasicBlocks forming the loop body of a plain (pre-region) VPlan in reverse post-order s...
Definition VPlanCFG.h:265
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1738
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:840
ReductionStyle getReductionStyle(bool InLoop, bool Ordered, unsigned ScaleFactor)
Definition VPlan.h:2776
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
iterator_range< df_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_depth_first_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order.
Definition VPlanCFG.h:253
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
UncountableExitStyle
Different methods of handling early exits.
Definition VPlan.h:78
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FindIV
FindIV reduction with select(icmp(),x,y) where one of (x,y) is a loop induction variable (increasing ...
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2018
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1771
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2145
LLVM_ABI bool isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT, AssumptionCache *AC=nullptr, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Return true if we can prove that the given load (which is assumed to be within the specified loop) wo...
Definition Loads.cpp:290
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:876
A recipe for handling first-order recurrence phis.
Definition VPlan.h:2727
A VPValue representing a live-in from the input IR or a constant.
Definition VPlanValue.h:246
Type * getType() const
Returns the scalar type of this symbolic value.
Definition VPlanValue.h:294
static void handleUncountableEarlyExits(VPlan &Plan, VPBasicBlock *HeaderVPBB, VPBasicBlock *LatchVPBB, VPBasicBlock *MiddleVPBB, UncountableExitStyle Style)
Update Plan to account for uncountable early exits by introducing appropriate branching logic in the ...
static bool createHeaderPhiRecipes(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, const MapVector< PHINode *, InductionDescriptor > &Inductions, const MapVector< PHINode *, RecurrenceDescriptor > &Reductions, const SmallPtrSetImpl< const PHINode * > &FixedOrderRecurrences, const SmallPtrSetImpl< PHINode * > &InLoopReductions, bool AllowReordering)
Replace VPPhi recipes in Plan's header with corresponding VPHeaderPHIRecipe subclasses for inductions...
static void foldTailByMasking(VPlan &Plan)
Adapts the vector loop region for tail folding by introducing a header mask and conditionally executi...
static void addMinimumVectorEpilogueIterationCheck(VPlan &Plan, Value *VectorTripCount, bool RequiresScalarEpilogue, ElementCount EpilogueVF, unsigned EpilogueUF, unsigned MainLoopStep, unsigned EpilogueLoopStep, ScalarEvolution &SE)
Add a check to Plan to see if the epilogue vector loop should be executed.
static bool handleMultiUseReductions(VPlan &Plan, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Try to legalize reductions with multiple in-loop uses.
static bool handleFindLastReductions(VPlan &Plan)
Check if Plan contains any FindLast reductions.
static void createInLoopReductionRecipes(VPlan &Plan, ElementCount MinVF)
Create VPReductionRecipes for in-loop reductions.
static LLVM_ABI_FOR_TEST std::unique_ptr< VPlan > buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy, PredicatedScalarEvolution &PSE, LoopVersioning *LVer=nullptr)
Create a base VPlan0, serving as the common starting point for all later candidates.
static void addCanonicalIVRecipes(VPlan &Plan, DebugLoc DL)
Add a canonical IV and its increment, using InductionTy and DL to Plan.
static LLVM_ABI_FOR_TEST bool handleEarlyExits(VPlan &Plan, UncountableExitStyle Style, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC)
Update Plan to account for all early exits.
static bool handleMaxMinNumReductions(VPlan &Plan)
Check if Plan contains any FMaxNum or FMinNum reductions.
static LLVM_ABI_FOR_TEST void createLoopRegions(VPlan &Plan)
Replace loops in Plan's flat CFG with VPRegionBlocks, turning Plan's flat CFG into a hierarchical CFG...
static void attachCheckBlock(VPlan &Plan, Value *Cond, BasicBlock *CheckBlock, bool AddBranchWeights)
Wrap runtime check block CheckBlock in a VPIRBB and Cond in a VPValue and connect the block to Plan,...
static void addIterationCountCheckBlock(VPlan &Plan, ElementCount VF, unsigned UF, bool RequiresScalarEpilogue, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE)
Add a new check block before the vector preheader to Plan to check if the main vector loop should be ...
static void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue, bool TailFolded, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE, VPBasicBlock *CheckBlock)
static LLVM_ABI_FOR_TEST void addMiddleCheck(VPlan &Plan, bool TailFolded)
If a check is needed to guard executing the scalar epilogue loop, it will be added to the middle bloc...