LLVM 24.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/ADT/Sequence.h"
26#include "llvm/Analysis/Loads.h"
33#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/MDBuilder.h"
35#include "llvm/Support/Debug.h"
39
40#define DEBUG_TYPE "vplan"
41
42using namespace llvm;
43using namespace LoopVectorizationUtils;
44using namespace VPlanPatternMatch;
45
46namespace {
47// Class that is used to build the plain CFG for the incoming IR.
48class PlainCFGBuilder {
49 // The outermost loop of the input loop nest considered for vectorization.
50 Loop *TheLoop;
51
52 // Loop Info analysis.
53 LoopInfo *LI;
54
55 // Loop versioning for alias metadata.
56 LoopVersioning *LVer;
57
58 // Lazily provides branch probabilities for the incoming IR.
59 function_ref<const BranchProbabilityInfo &()> GetBPI;
60
61 // The BranchProbabilityInfo returned by GetBPI, cached on first use.
62 const BranchProbabilityInfo *BPI = nullptr;
63
64 // Vectorization plan that we are working on.
65 std::unique_ptr<VPlan> Plan;
66
67 // Builder of the VPlan instruction-level representation.
68 VPBuilder VPIRBuilder;
69
70 // NOTE: The following maps are intentionally destroyed after the plain CFG
71 // construction because subsequent VPlan-to-VPlan transformation may
72 // invalidate them.
73 // Map incoming BasicBlocks to their newly-created VPBasicBlocks.
75 // Map incoming Value definitions to their newly-created VPValues.
76 DenseMap<Value *, VPValue *> IRDef2VPValue;
77
78 // Hold phi node's that need to be fixed once the plain CFG has been built.
80
81 // Utility functions.
82 void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB);
83 void fixHeaderPhis();
84 VPBasicBlock *getOrCreateVPBB(BasicBlock *BB);
85 VPValue *getOrCreateVPOperand(Value *IRVal);
86 void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB);
87 VPIRMetadata getTerminatorMetadata(Instruction &Term);
88
89public:
90 PlainCFGBuilder(Loop *Lp, LoopInfo *LI, LoopVersioning *LVer, Type *IdxTy,
91 function_ref<const BranchProbabilityInfo &()> GetBPI)
92 : TheLoop(Lp), LI(LI), LVer(LVer), GetBPI(GetBPI),
93 Plan(std::make_unique<VPlan>(Lp, IdxTy)) {}
94
95 /// Build plain CFG for TheLoop and connect it to Plan's entry.
96 std::unique_ptr<VPlan> buildPlainCFG();
97};
98} // anonymous namespace
99
100// Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB
101// must have no predecessors.
102void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) {
103 // Collect VPBB predecessors.
105 for (BasicBlock *Pred : predecessors(BB))
106 VPBBPreds.push_back(getOrCreateVPBB(Pred));
107 VPBB->setPredecessors(VPBBPreds);
108}
109
110static bool isHeaderBB(BasicBlock *BB, Loop *L) {
111 return L && BB == L->getHeader();
112}
113
114// Add operands to VPInstructions representing phi nodes from the input IR.
115void PlainCFGBuilder::fixHeaderPhis() {
116 for (auto *Phi : PhisToFix) {
117 assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode.");
118 VPValue *VPVal = IRDef2VPValue[Phi];
119 assert(isa<VPPhi>(VPVal) && "Expected VPPhi for phi node.");
120 auto *PhiR = cast<VPPhi>(VPVal);
121 assert(PhiR->getNumOperands() == 0 && "Expected VPPhi with no operands.");
122 assert(isHeaderBB(Phi->getParent(), LI->getLoopFor(Phi->getParent())) &&
123 "Expected Phi in header block.");
124 assert(Phi->getNumOperands() == 2 &&
125 "header phi must have exactly 2 operands");
126 for (BasicBlock *Pred : predecessors(Phi->getParent()))
127 PhiR->addIncoming(
128 getOrCreateVPOperand(Phi->getIncomingValueForBlock(Pred)));
129 }
130}
131
132// Create a new empty VPBasicBlock for an incoming BasicBlock or retrieve an
133// existing one if it was already created.
134VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {
135 if (auto *VPBB = BB2VPBB.lookup(BB)) {
136 // Retrieve existing VPBB.
137 return VPBB;
138 }
139
140 // Create new VPBB.
141 StringRef Name = BB->getName();
142 LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << Name << "\n");
143 VPBasicBlock *VPBB = Plan->createVPBasicBlock(Name);
144 BB2VPBB[BB] = VPBB;
145 return VPBB;
146}
147
148// Create a new VPValue or retrieve an existing one for the Instruction's
149// operand \p IRVal. This function must only be used to create/retrieve VPValues
150// for *Instruction's operands* and not to create regular VPInstruction's. For
151// the latter, please, look at 'createVPInstructionsForVPBB'.
152VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) {
153 auto VPValIt = IRDef2VPValue.find(IRVal);
154 if (VPValIt != IRDef2VPValue.end())
155 // Operand has an associated VPInstruction or VPValue that was previously
156 // created.
157 return VPValIt->second;
158
159 // Operand doesn't have a previously created VPInstruction/VPValue. This
160 // means that operand is:
161 // A) a definition external to VPlan,
162 // B) any other Value without specific representation in VPlan.
163 // For now, we use VPValue to represent A and B and classify both as external
164 // definitions, i.e. Values that are not Instructions or Instructions outside
165 // the loop nest. We may introduce specific VPValue subclasses for them in the
166 // future.
167 assert((!isa<Instruction>(IRVal) ||
168 !TheLoop->contains(cast<Instruction>(IRVal))) &&
169 "Expected external definition as operand.");
170
171 // A and B: Create VPValue and add it to the pool of external definitions and
172 // to the Value->VPValue map.
173 VPValue *NewVPVal = Plan->getOrAddLiveIn(IRVal);
174 IRDef2VPValue[IRVal] = NewVPVal;
175 return NewVPVal;
176}
177
178// Returns the metadata to preserve for terminator \p Term.
179VPIRMetadata PlainCFGBuilder::getTerminatorMetadata(Instruction &Term) {
180 VPIRMetadata MD(Term);
181 if (MD.getMetadata(LLVMContext::MD_prof))
182 return MD;
183 // Estimates are only read for edges inside the loop region.
184 if (!TheLoop->isInnermost() || Term.getParent() == TheLoop->getLoopLatch())
185 return MD;
186 // The weights describe the edges leaving Term in the order of its successors,
187 // matching the successor order of the VPBasicBlock created for Term's parent.
188 if (!BPI)
189 BPI = &GetBPI();
190 auto Weights = map_to_vector(seq(Term.getNumSuccessors()), [&](unsigned I) {
191 return BPI->getEdgeProbability(Term.getParent(), I).getNumerator();
192 });
193 MD.setEstimatedBranchWeights(
194 MDBuilder(Plan->getContext()).createBranchWeights(Weights));
195 return MD;
196}
197
198// Create new VPInstructions in a VPBasicBlock, given its BasicBlock
199// counterpart. This function must be invoked in RPO so that the operands of a
200// VPInstruction in \p BB have been visited before (except for Phi nodes).
201void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,
202 BasicBlock *BB) {
203 VPIRBuilder.setInsertPoint(VPBB);
204 // TODO: Model and preserve debug intrinsics in VPlan.
205 for (Instruction &InstRef : *BB) {
206 Instruction *Inst = &InstRef;
207
208 // There shouldn't be any VPValue for Inst at this point. Otherwise, we
209 // visited Inst when we shouldn't, breaking the RPO traversal order.
210 assert(!IRDef2VPValue.count(Inst) &&
211 "Instruction shouldn't have been visited.");
212
213 if (isa<UncondBrInst>(Inst))
214 // Skip the rest of the Instruction processing for Branch instructions.
215 continue;
216
217 if (auto *Br = dyn_cast<CondBrInst>(Inst)) {
218 // Conditional branch instruction are represented using BranchOnCond
219 // recipes.
220 VPValue *Cond = getOrCreateVPOperand(Br->getCondition());
221 VPIRBuilder.createNaryOp(VPInstruction::BranchOnCond, {Cond}, Inst, {},
222 getTerminatorMetadata(*Inst),
223 Inst->getDebugLoc());
224 continue;
225 }
226
227 if (auto *SI = dyn_cast<SwitchInst>(Inst)) {
228 // Don't emit recipes for unconditional switch instructions.
229 if (SI->getNumCases() == 0)
230 continue;
231 SmallVector<VPValue *> Ops = {getOrCreateVPOperand(SI->getCondition())};
232 for (auto Case : SI->cases())
233 Ops.push_back(getOrCreateVPOperand(Case.getCaseValue()));
234 VPIRBuilder.createNaryOp(Instruction::Switch, Ops, Inst, {},
235 getTerminatorMetadata(*Inst),
236 Inst->getDebugLoc());
237 continue;
238 }
239
240 VPSingleDefRecipe *NewR;
241 if (auto *Phi = dyn_cast<PHINode>(Inst)) {
242 // Phi node's operands may not have been visited at this point. We create
243 // an empty VPInstruction that we will fix once the whole plain CFG has
244 // been built.
245 NewR = VPIRBuilder.createScalarPhi({}, Phi->getDebugLoc(), "vec.phi",
246 *Phi, Phi->getType());
247 NewR->setUnderlyingValue(Phi);
248 if (isHeaderBB(Phi->getParent(), LI->getLoopFor(Phi->getParent()))) {
249 // Header phis need to be fixed after the VPBB for the latch has been
250 // created.
251 PhisToFix.push_back(Phi);
252 } else {
253 // Add operands for VPPhi in the order matching its predecessors in
254 // VPlan.
255 DenseMap<const VPBasicBlock *, VPValue *> VPPredToIncomingValue;
256 for (unsigned I = 0; I != Phi->getNumOperands(); ++I) {
257 VPPredToIncomingValue[BB2VPBB[Phi->getIncomingBlock(I)]] =
258 getOrCreateVPOperand(Phi->getIncomingValue(I));
259 }
260 for (VPBlockBase *Pred : VPBB->getPredecessors())
261 cast<VPPhi>(NewR)->addIncoming(
262 VPPredToIncomingValue.lookup(Pred->getExitingBasicBlock()));
263 }
264 } else {
265 // Build VPIRMetadata from the instruction and add loop versioning
266 // metadata for loads and stores.
267 VPIRMetadata MD(*Inst);
268 if (isa<LoadInst, StoreInst>(Inst) && LVer) {
269 const auto &[AliasScopeMD, NoAliasMD] =
270 LVer->getNoAliasMetadataFor(Inst);
271 if (AliasScopeMD)
272 MD.setMetadata(LLVMContext::MD_alias_scope, AliasScopeMD);
273 if (NoAliasMD)
274 MD.setMetadata(LLVMContext::MD_noalias, NoAliasMD);
275 }
276
278 "legality must reject aggregate-producing insertvalue");
279 // Translate LLVM-IR operands into VPValue operands and set them in the
280 // new VPInstruction.
281 SmallVector<VPValue *, 4> VPOperands;
282 for (Value *Op : Inst->operands())
283 VPOperands.push_back(getOrCreateVPOperand(Op));
284 if (auto *EVI = dyn_cast<ExtractValueInst>(Inst))
285 for (unsigned Idx : EVI->indices())
286 VPOperands.push_back(Plan->getConstantInt(32, Idx));
287 VPIRAttributes Attrs;
288 if (auto *CI = dyn_cast<CallInst>(Inst))
289 Attrs = VPIRAttributes(CI->getAttributes());
290 NewR = VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst,
291 VPIRFlags(*Inst), MD, Inst->getDebugLoc(),
292 "", Inst->getType(), Attrs);
293 }
294
295 IRDef2VPValue[Inst] = NewR;
296 }
297}
298
299// Main interface to build the plain CFG.
300std::unique_ptr<VPlan> PlainCFGBuilder::buildPlainCFG() {
301 VPIRBasicBlock *Entry = cast<VPIRBasicBlock>(Plan->getEntry());
302 BB2VPBB[Entry->getIRBasicBlock()] = Entry;
303 for (VPIRBasicBlock *ExitVPBB : Plan->getExitBlocks())
304 BB2VPBB[ExitVPBB->getIRBasicBlock()] = ExitVPBB;
305
306 // 1. Scan the body of the loop in a topological order to visit each basic
307 // block after having visited its predecessor basic blocks. Create a VPBB for
308 // each BB and link it to its successor and predecessor VPBBs. Note that
309 // predecessors must be set in the same order as they are in the incomming IR.
310 // Otherwise, there might be problems with existing phi nodes and algorithm
311 // based on predecessors traversal.
312
313 // Loop PH needs to be explicitly visited since it's not taken into account by
314 // LoopBlocksDFS.
315 BasicBlock *ThePreheaderBB = TheLoop->getLoopPreheader();
316 assert((ThePreheaderBB->getTerminator()->getNumSuccessors() == 1) &&
317 "Unexpected loop preheader");
318 for (auto &I : *ThePreheaderBB) {
319 if (I.getType()->isVoidTy())
320 continue;
321 IRDef2VPValue[&I] = Plan->getOrAddLiveIn(&I);
322 }
323
324 LoopBlocksRPO RPO(TheLoop);
325 RPO.perform(LI);
326
327 for (BasicBlock *BB : RPO) {
328 // Create or retrieve the VPBasicBlock for this BB.
329 VPBasicBlock *VPBB = getOrCreateVPBB(BB);
330 // Set VPBB predecessors in the same order as they are in the incoming BB.
331 setVPBBPredsFromBB(VPBB, BB);
332
333 // Create VPInstructions for BB.
334 createVPInstructionsForVPBB(VPBB, BB);
335
336 // Set VPBB successors. We create empty VPBBs for successors if they don't
337 // exist already. Recipes will be created when the successor is visited
338 // during the RPO traversal.
339 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
341 getOrCreateVPBB(SI->getDefaultDest())};
342 for (auto Case : SI->cases())
343 Succs.push_back(getOrCreateVPBB(Case.getCaseSuccessor()));
344 VPBB->setSuccessors(Succs);
345 continue;
346 }
347 if (auto *BI = dyn_cast<UncondBrInst>(BB->getTerminator())) {
348 VPBB->setOneSuccessor(getOrCreateVPBB(BI->getSuccessor()));
349 continue;
350 }
351 auto *BI = cast<CondBrInst>(BB->getTerminator());
352 BasicBlock *IRSucc0 = BI->getSuccessor(0);
353 BasicBlock *IRSucc1 = BI->getSuccessor(1);
354 VPBasicBlock *Successor0 = getOrCreateVPBB(IRSucc0);
355 VPBasicBlock *Successor1 = getOrCreateVPBB(IRSucc1);
356 VPBB->setTwoSuccessors(Successor0, Successor1);
357 }
358
359 for (auto *EB : Plan->getExitBlocks())
360 setVPBBPredsFromBB(EB, EB->getIRBasicBlock());
361
362 // 2. The whole CFG has been built at this point so all the input Values must
363 // have a VPlan counterpart. Fix VPlan header phi by adding their
364 // corresponding VPlan operands.
365 fixHeaderPhis();
366
367 Plan->getEntry()->setOneSuccessor(getOrCreateVPBB(TheLoop->getHeader()));
368 Plan->getEntry()->setPlan(&*Plan);
369
370 // Fix VPlan loop-closed-ssa exit phi's by adding incoming operands to the
371 // VPIRInstructions wrapping them.
372 // // Note that the operand order corresponds to IR predecessor order, and may
373 // need adjusting when VPlan predecessors are added, if an exit block has
374 // multiple predecessor.
375 for (auto *EB : Plan->getExitBlocks()) {
376 for (VPIRPhi &PhiR : map_range(EB->phis(), CastTo<VPIRPhi>)) {
377 PHINode &Phi = PhiR.getIRPhi();
378 assert(PhiR.getNumOperands() == 0 &&
379 "no phi operands should be added yet");
380 for (BasicBlock *Pred : predecessors(EB->getIRBasicBlock()))
381 PhiR.addIncoming(
382 getOrCreateVPOperand(Phi.getIncomingValueForBlock(Pred)));
383 }
384 }
385
386 LLVM_DEBUG(Plan->setName("Plain CFG\n"); dbgs() << *Plan);
387 return std::move(Plan);
388}
389
390/// Checks if \p HeaderVPB is a loop header block in the plain CFG; that is, it
391/// has exactly 2 predecessors (preheader and latch), where the block
392/// dominates the latch and the preheader dominates the block. If it is a
393/// header block return true and canonicalize the predecessors of the header
394/// (making sure the preheader appears first and the latch second) and the
395/// successors of the latch (making sure the loop exit comes first). Otherwise
396/// return false.
398 const VPDominatorTree &VPDT) {
399 ArrayRef<VPBlockBase *> Preds = HeaderVPB->getPredecessors();
400 if (Preds.size() != 2)
401 return false;
402
403 auto *PreheaderVPBB = Preds[0];
404 auto *LatchVPBB = Preds[1];
405 if (!VPDT.dominates(PreheaderVPBB, HeaderVPB) ||
406 !VPDT.dominates(HeaderVPB, LatchVPBB)) {
407 std::swap(PreheaderVPBB, LatchVPBB);
408
409 if (!VPDT.dominates(PreheaderVPBB, HeaderVPB) ||
410 !VPDT.dominates(HeaderVPB, LatchVPBB))
411 return false;
412
413 // Canonicalize predecessors of header so that preheader is first and
414 // latch second.
415 HeaderVPB->swapPredecessors();
416 for (VPRecipeBase &R : cast<VPBasicBlock>(HeaderVPB)->phis())
417 R.swapOperands();
418 }
419
420 // The two successors of conditional branch match the condition, with the
421 // first successor corresponding to true and the second to false. We
422 // canonicalize the successors of the latch when introducing the region, such
423 // that the latch exits the region when its condition is true; invert the
424 // original condition if the original CFG branches to the header on true.
425 // Note that the exit edge is not yet connected for top-level loops.
426 if (LatchVPBB->getSingleSuccessor() ||
427 LatchVPBB->getSuccessors()[0] != HeaderVPB)
428 return true;
429
430 assert(LatchVPBB->getNumSuccessors() == 2 && "Must have 2 successors");
431 auto *Term = cast<VPBasicBlock>(LatchVPBB)->getTerminator();
432 assert(cast<VPInstruction>(Term)->getOpcode() ==
434 "terminator must be a BranchOnCond");
435 auto *Not = new VPInstruction(VPInstruction::Not, {Term->getOperand(0)});
436 Not->insertBefore(Term);
437 Term->setOperand(0, Not);
438 LatchVPBB->swapSuccessors();
439
440 return true;
441}
442
443/// Create a new VPRegionBlock for the loop starting at \p HeaderVPB. For the
444/// outermost loop adjust the regions exiting terminator to be based on the
445/// canonical IV.
446static void createLoopRegion(VPlan &Plan, VPBlockBase *HeaderVPB, DebugLoc DL) {
447 auto *PreheaderVPBB = HeaderVPB->getPredecessors()[0];
448 auto *LatchVPBB = cast<VPBasicBlock>(HeaderVPB->getPredecessors()[1]);
449 auto *OutermostHeaderVPBB =
451
452 VPBlockUtils::disconnectBlocks(PreheaderVPBB, HeaderVPB);
453 VPBlockUtils::disconnectBlocks(LatchVPBB, HeaderVPB);
454
455 // Create an empty region first and insert it between PreheaderVPBB and
456 // the exit blocks, taking care to preserve the original predecessor &
457 // successor order of blocks. Set region entry and exiting after both
458 // HeaderVPB and LatchVPBB have been disconnected from their
459 // predecessors/successors. Only the outermost loop has a canonical IV. Nested
460 // loops are assigned a canonical IV of null type and unknown debug location.
461 bool IsOutermost = HeaderVPB == OutermostHeaderVPBB;
462 Type *CanIVTy = nullptr;
463 if (IsOutermost)
464 CanIVTy = Plan.getVectorTripCount().getType();
465 else
467 auto *R = Plan.createLoopRegion(CanIVTy, DL);
468
469 // Transfer latch's successors to the region.
471
472 VPBlockUtils::connectBlocks(PreheaderVPBB, R);
473 R->setEntry(HeaderVPB);
474 R->setExiting(LatchVPBB);
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 if (!IsOutermost)
481 return;
482
483 auto *LatchTerm = LatchVPBB->getTerminator();
484 VPBuilder Builder(LatchTerm);
485 // Add a VPInstruction to increment the scalar canonical IV by VF * UF.
486 // Initially the induction increment is guaranteed to not wrap, but that may
487 // change later, e.g. when tail-folding, when the flags need to be dropped.
488 auto *CanonicalIVIncrement = Builder.createAdd(
489 R->getCanonicalIV(), &Plan.getVFxUF(), DL, "index.next", {true, false});
490
491 if (match(LatchTerm, m_BranchOnTwoConds())) {
492 auto *IsLatchExitTaken = Builder.createICmp(
493 CmpInst::ICMP_EQ, CanonicalIVIncrement, &Plan.getVectorTripCount());
494 LatchTerm->setOperand(1, IsLatchExitTaken);
495 } else {
496 // We are replacing the branch to exit the region. Remove the original
497 // BranchOnCond.
498 assert(match(LatchTerm, m_BranchOnCond()) && "Unexpected terminator");
499 DebugLoc LatchDL = LatchTerm->getDebugLoc();
500 Builder.createNaryOp(VPInstruction::BranchOnCount,
501 {CanonicalIVIncrement, &Plan.getVectorTripCount()},
502 LatchDL);
503 LatchTerm->eraseFromParent();
504 }
505}
506
507/// Creates extracts for values in \p Plan defined in a loop region and used
508/// outside a loop region.
509static void createExtractsForLiveOuts(VPlan &Plan, VPBasicBlock *MiddleVPBB) {
510 VPBuilder B(MiddleVPBB->getFirstNonPhi());
511 for (VPBasicBlock *EB : Plan.getExitBlocks()) {
512 if (!is_contained(EB->predecessors(), MiddleVPBB))
513 continue;
514
515 for (VPIRPhi &ExitIRI : map_range(EB->phis(), CastTo<VPIRPhi>)) {
516 VPValue *Exiting = ExitIRI.getIncomingValueForBlock(MiddleVPBB);
517 if (isa<VPIRValue>(Exiting))
518 continue;
519 Exiting = B.createNaryOp(VPInstruction::ExtractLastPart, Exiting);
520 Exiting = B.createNaryOp(VPInstruction::ExtractLastLane, Exiting);
521 ExitIRI.setIncomingValueForBlock(MiddleVPBB, Exiting);
522 }
523 }
524}
525
526static void addInitialSkeleton(VPlan &Plan, Type *InductionTy,
527 PredicatedScalarEvolution &PSE, Loop *TheLoop) {
528 VPDominatorTree VPDT(Plan);
529
530 auto *HeaderVPBB = cast<VPBasicBlock>(Plan.getEntry()->getSingleSuccessor());
531 if (TheLoop->isInnermost()) {
532 canonicalHeaderAndLatch(HeaderVPBB, VPDT);
533 } else {
534 // When vectorizing outer loops, canonicalize all loops up front.
536 for (VPBlockBase *VPB : Blocks)
537 canonicalHeaderAndLatch(VPB, VPDT);
538 }
539 auto *LatchVPBB = cast<VPBasicBlock>(HeaderVPBB->getPredecessors()[1]);
540
541 VPBasicBlock *VecPreheader = Plan.createVPBasicBlock("vector.ph");
542 VPBlockUtils::insertBlockAfter(VecPreheader, Plan.getEntry());
543
544 VPBasicBlock *MiddleVPBB = Plan.createVPBasicBlock("middle.block");
545 // The canonical LatchVPBB has the header block as last successor. If it has
546 // another successor, this successor is an exit block - insert middle block on
547 // its edge. Otherwise, add middle block as another successor retaining header
548 // as last. In the latter case, the latch has no conditional terminator yet,
549 // so insert a placeholder BranchOnCond that always continues to the header.
550 // It will be canonicalized to a BranchOnCount later
551 if (LatchVPBB->getNumSuccessors() == 2) {
552 VPBlockBase *LatchExitVPB = LatchVPBB->getSuccessors()[0];
553 VPBlockUtils::insertOnEdge(LatchVPBB, LatchExitVPB, MiddleVPBB);
554 } else {
555 VPBlockUtils::connectBlocks(LatchVPBB, MiddleVPBB);
556 LatchVPBB->swapSuccessors();
558 {Plan.getFalse()});
559 }
560
561 // Create SCEV and VPValue for the trip count.
562 // We use the symbolic max backedge-taken-count, which works also when
563 // vectorizing loops with uncountable early exits.
564 const SCEV *BackedgeTakenCountSCEV = PSE.getSymbolicMaxBackedgeTakenCount();
565 assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCountSCEV) &&
566 "Invalid backedge-taken count");
567 ScalarEvolution &SE = *PSE.getSE();
568 const SCEV *TripCount = SE.getTripCountFromExitCount(BackedgeTakenCountSCEV,
569 InductionTy, TheLoop);
571
572 VPBasicBlock *ScalarPH = Plan.createVPBasicBlock("scalar.ph");
574
575 // The connection order corresponds to the operands of the conditional branch,
576 // with the middle block already connected to the exit block.
577 VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
578 // Also connect the entry block to the scalar preheader.
579 // TODO: Also introduce a branch recipe together with the minimum trip count
580 // check.
581 VPBlockUtils::connectBlocks(Plan.getEntry(), ScalarPH);
582 Plan.getEntry()->swapSuccessors();
583
584 createExtractsForLiveOuts(Plan, MiddleVPBB);
585
586 // Create resume phis in the scalar preheader for each phi in the scalar loop.
587 // Their incoming value from the vector loop will be the last lane of the
588 // corresponding vector loop header phi.
589 VPBuilder MiddleBuilder(MiddleVPBB->getFirstNonPhi());
590 VPBuilder ScalarPHBuilder(ScalarPH);
591 assert(equal(ScalarPH->getPredecessors(),
592 ArrayRef<VPBlockBase *>({MiddleVPBB, Plan.getEntry()})) &&
593 "unexpected predecessor order of scalar ph");
594 for (const auto &[PhiR, ScalarPhiR] :
595 zip_equal(HeaderVPBB->phis(), Plan.getScalarHeader()->phis())) {
596 auto *VectorPhiR = cast<VPPhi>(&PhiR);
597 VPValue *BackedgeVal = VectorPhiR->getOperand(1);
598 VPValue *ResumeFromVectorLoop =
599 MiddleBuilder.createNaryOp(VPInstruction::ExtractLastPart, BackedgeVal);
600 ResumeFromVectorLoop = MiddleBuilder.createNaryOp(
601 VPInstruction::ExtractLastLane, ResumeFromVectorLoop);
602 // Create scalar resume phi, with the first operand being the incoming value
603 // from the middle block and the second operand coming from the entry block.
604 auto *ResumePhiR = ScalarPHBuilder.createScalarPhi(
605 {ResumeFromVectorLoop, VectorPhiR->getOperand(0)},
606 VectorPhiR->getDebugLoc());
607 cast<VPIRPhi>(&ScalarPhiR)->addIncoming(ResumePhiR);
608 }
609}
610
611/// To make RUN_VPLAN_PASS print initial VPlan.
613
614std::unique_ptr<VPlan> VPlanTransforms::buildVPlan0(
615 Loop *TheLoop, LoopInfo &LI, Type *InductionTy,
617 function_ref<const BranchProbabilityInfo &()> GetBPI) {
618 PlainCFGBuilder Builder(TheLoop, &LI, LVer, InductionTy, GetBPI);
619 std::unique_ptr<VPlan> VPlan0 = Builder.buildPlainCFG();
620 addInitialSkeleton(*VPlan0, InductionTy, PSE, TheLoop);
621 simplifyLiveInsWithSCEV(*VPlan0, PSE);
622
624 return VPlan0;
625}
626
630 auto Frequencies = vputils::computeExecutionFrequencies(Blocks);
631 LLVMContext &Ctx = Plan.getContext();
632 for (VPBasicBlock *VPBB : Blocks) {
633 std::optional<VPExecutionFrequency> Freq = Frequencies.lookup(VPBB);
635 VPI.setExecutionFrequency(Freq, Ctx);
636 }
637}
638
639/// Creates a VPWidenIntOrFpInductionRecipe or VPWidenPointerInductionRecipe
640/// for \p Phi based on \p IndDesc.
641static VPHeaderPHIRecipe *
643 const InductionDescriptor &IndDesc, VPlan &Plan,
644 PredicatedScalarEvolution &PSE, Loop &OrigLoop,
645 DebugLoc DL) {
646 [[maybe_unused]] ScalarEvolution &SE = *PSE.getSE();
647 assert(SE.isLoopInvariant(IndDesc.getStep(), &OrigLoop) &&
648 "step must be loop invariant");
649 assert((Plan.getLiveIn(IndDesc.getStartValue()) == Start ||
650 (SE.isSCEVable(IndDesc.getStartValue()->getType()) &&
651 PSE.getSCEV(IndDesc.getStartValue()) ==
652 vputils::getSCEVExprForVPValue(Start, PSE))) &&
653 "Start VPValue must match IndDesc's start value");
654
655 VPValue *Step =
657
658 VPValue *BackedgeVal = PhiR->getOperand(1);
659 // Replace live-out extracts of WideIV's backedge value by ExitingIVValue
660 // recipes. optimizeInductionLiveOutUsers will later compute the proper
661 // DerivedIV.
662 //
663 // For an IV that requires SCEV predicate, keep extracting the exit values
664 // from the loop directly, as the pre-computed exit value as-is would be
665 // incorrect outside the loop.
666 auto ReplaceExtractsWithExitingIVValueIfPossible = [&](VPWidenInductionRecipe
667 *WideIV) {
668 bool IsPredicated = !WideIV->getNoWrapPredicates().empty();
669 for (VPUser *U : to_vector(BackedgeVal->users())) {
671 continue;
672 auto *ExtractLastPart = cast<VPInstruction>(U);
673 VPUser *ExtractLastPartUser = ExtractLastPart->getSingleUser();
674 assert(ExtractLastPartUser && "must have a single user");
675 if (!match(ExtractLastPartUser, m_ExtractLastLane(m_VPValue())))
676 continue;
677 auto *ExtractLastLane = cast<VPInstruction>(ExtractLastPartUser);
678 assert(is_contained(ExtractLastLane->getParent()->successors(),
679 Plan.getScalarPreheader()) &&
680 "last lane must be extracted in the middle block");
681 // Keep the vector extract for exit-block live-out uses of a predicated
682 // IV.
683 if (IsPredicated &&
684 any_of(ExtractLastLane->users(), [&](VPUser *LaneUser) {
685 auto *R = cast<VPRecipeBase>(LaneUser);
686 return Plan.isExitBlock(R->getParent());
687 }))
688 continue;
689 VPBuilder Builder(ExtractLastLane);
690 ExtractLastLane->replaceAllUsesWith(
691 Builder.createNaryOp(VPInstruction::ExitingIVValue, {WideIV}));
692 ExtractLastLane->eraseFromParent();
693 ExtractLastPart->eraseFromParent();
694 }
695 };
696
698 auto *WideIV = new VPWidenPointerInductionRecipe(
699 Phi, Start, Step, &Plan.getVFxUF(), IndDesc, DL);
700 ReplaceExtractsWithExitingIVValueIfPossible(WideIV);
701 return WideIV;
702 }
703
706 "must have an integer or float induction at this point");
707
708 // Update wide induction increments to use the same step as the corresponding
709 // wide induction. This enables detecting induction increments directly in
710 // VPlan and removes redundant splats.
711 if (match(BackedgeVal, m_Add(m_Specific(PhiR), m_VPValue())))
712 BackedgeVal->getDefiningRecipe()->setOperand(1, Step);
713
714 // It is always safe to copy over the NoWrap and FastMath flags. In
715 // particular, when folding tail by masking, the masked-off lanes are never
716 // used, so it is safe.
717 VPIRFlags Flags = vputils::getFlagsForInduction(IndDesc, PhiR);
718
719 auto *WideIV = new VPWidenIntOrFpInductionRecipe(
720 Phi, Start, Step, &Plan.getVF(), IndDesc, Flags, DL);
721
722 ReplaceExtractsWithExitingIVValueIfPossible(WideIV);
723 return WideIV;
724}
725
726/// Try to sink users of \p FOR after \p Previous. \returns true if sinking
727/// succeeded or was not necessary, and false otherwise.
728static bool
730 VPRecipeBase *Previous,
731 const VPDominatorTree &VPDT) {
732 // Collect recipes that need sinking.
735 Seen.insert(Previous);
736 auto TryToPushSinkCandidate = [&](VPRecipeBase *SinkCandidate) {
737 // The previous value must not depend on the users of the recurrence phi.
738 // In that case, FOR is not a fixed order recurrence.
739 if (SinkCandidate == Previous)
740 return false;
741
742 if (isa<VPHeaderPHIRecipe>(SinkCandidate) ||
743 !Seen.insert(SinkCandidate).second ||
744 VPDT.properlyDominates(Previous, SinkCandidate))
745 return true;
746
747 if (vputils::cannotHoistOrSinkRecipe(*SinkCandidate, /*Sinking=*/true))
748 return false;
749
750 WorkList.push_back(SinkCandidate);
751 return true;
752 };
753
754 // Recursively sink users of FOR after Previous.
755 WorkList.push_back(FOR);
756 for (unsigned I = 0; I != WorkList.size(); ++I) {
757 VPRecipeBase *Current = WorkList[I];
758 assert(Current->getNumDefinedValues() == 1 &&
759 "only recipes with a single defined value expected");
760
761 for (VPUser *User : Current->getVPSingleValue()->users()) {
762 if (!TryToPushSinkCandidate(cast<VPRecipeBase>(User)))
763 return false;
764 }
765 }
766
767 // Keep recipes to sink ordered by dominance so earlier instructions are
768 // processed first.
769 sort(WorkList, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
770 return VPDT.properlyDominates(A, B);
771 });
772
773 for (VPRecipeBase *SinkCandidate : WorkList) {
774 if (SinkCandidate == FOR)
775 continue;
776
777 SinkCandidate->moveAfter(Previous);
778 Previous = SinkCandidate;
779 }
780 return true;
781}
782
783/// Try to hoist \p Previous and its operands before all users of \p FOR.
784/// \returns true if hoisting succeeded or was not necessary, and false
785/// otherwise.
787 VPRecipeBase *Previous,
788 const VPDominatorTree &VPDT) {
790 return false;
791
792 // Collect recipes that need hoisting.
793 SmallVector<VPRecipeBase *> HoistCandidates;
795 // Find the closest hoist point by looking at all users of FOR and selecting
796 // the recipe dominating all other users.
797 VPRecipeBase *HoistPoint = nullptr;
799 if (!HoistPoint || VPDT.properlyDominates(R, HoistPoint))
800 HoistPoint = R;
801 }
802 // Dominance is only a partial order, so the users of FOR may not have a
803 // single user dominating all others. Bail out in that case.
804 if (!HoistPoint || HoistPoint->isPhi() ||
805 any_of(FOR->users(), [&VPDT, HoistPoint](VPUser *U) {
806 auto *R = cast<VPRecipeBase>(U);
807 return HoistPoint != R && !VPDT.properlyDominates(HoistPoint, R);
808 }))
809 return false;
810
811 auto NeedsHoisting = [HoistPoint, &VPDT,
812 &Visited](VPValue *HoistCandidateV) -> VPRecipeBase * {
813 VPRecipeBase *HoistCandidate = HoistCandidateV->getDefiningRecipe();
814 if (!HoistCandidate)
815 return nullptr;
816 // Hoist candidate was already visited, no need to hoist.
817 if (!Visited.insert(HoistCandidate).second)
818 return nullptr;
819 // If we reached a recipe that dominates HoistPoint, we don't need to
820 // hoist the recipe.
821 if (VPDT.properlyDominates(HoistCandidate, HoistPoint))
822 return nullptr;
823 return HoistCandidate;
824 };
825
826 if (!NeedsHoisting(Previous->getVPSingleValue()))
827 return true;
828
829 // Recursively try to hoist Previous and its operands before all users of
830 // FOR.
831 HoistCandidates.push_back(Previous);
832
833 for (unsigned I = 0; I != HoistCandidates.size(); ++I) {
834 VPRecipeBase *Current = HoistCandidates[I];
835 assert(Current->getNumDefinedValues() == 1 &&
836 "only recipes with a single defined value expected");
838 return false;
839
840 for (VPValue *Op : Current->operands()) {
841 // If we reach FOR, it means the original Previous depends on some other
842 // recurrence that in turn depends on FOR. If that is the case, we would
843 // also need to hoist recipes involving the other FOR, which may break
844 // dependencies.
845 if (Op == FOR)
846 return false;
847
848 if (auto *R = NeedsHoisting(Op)) {
849 // Bail out if the recipe defines multiple values.
850 // TODO: Hoisting such recipes requires additional handling.
851 if (R->getNumDefinedValues() != 1)
852 return false;
853 HoistCandidates.push_back(R);
854 }
855 }
856 }
857
858 // Moving a candidate to HoistPoint keeps it dominating its other users only
859 // if HoistPoint dominates the candidate's current position.
860 if (any_of(HoistCandidates, [&VPDT, HoistPoint](VPRecipeBase *R) {
861 return !VPDT.properlyDominates(HoistPoint, R);
862 }))
863 return false;
864
865 // Order recipes to hoist by dominance so earlier instructions are processed
866 // first.
867 sort(HoistCandidates, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
868 return VPDT.properlyDominates(A, B);
869 });
870
871 for (VPRecipeBase *HoistCandidate : HoistCandidates) {
872 HoistCandidate->moveBefore(HoistPoint->getIterator());
873 }
874
875 return true;
876}
877
878/// Sink users of fixed-order recurrences past or hoist before the recipe
879/// defining the previous value, introduce FirstOrderRecurrenceSplice
880/// VPInstructions, and replace FOR uses. Returns false if hoisting or sinking
881/// fails.
883 const VPDominatorTree &VPDT) {
884 auto FORs = to_vector(make_pointer_range(
886 for (VPFirstOrderRecurrencePHIRecipe *FOR : FORs) {
887 // Follow through FOR phi chains to find the actual Previous recipe.
888 // Fixed-order recurrences do not contain cycles, so this loop is
889 // guaranteed to terminate.
890#ifndef NDEBUG
892#endif
893 VPRecipeBase *Previous = FOR->getBackedgeValue()->getDefiningRecipe();
894 while (auto *PrevPhi =
896 assert(PrevPhi->getParent() == FOR->getParent() &&
897 "PrevPhi must be in same block as FOR");
898 assert(SeenPhis.insert(PrevPhi).second &&
899 "PrevPhi must not be visited multiple times");
900 Previous = PrevPhi->getBackedgeValue()->getDefiningRecipe();
901 }
902
903 VPBasicBlock::iterator InsertPt = FOR->getParent()->getFirstNonPhi();
904 if (Previous) {
905 // Sink FOR users after Previous or hoist Previous before FOR users.
906 if (!sinkRecurrenceUsersAfterPrevious(FOR, Previous, VPDT) &&
907 !hoistPreviousBeforeFORUsers(FOR, Previous, VPDT))
908 return false;
909 InsertPt = isa<VPHeaderPHIRecipe>(Previous)
910 ? Previous->getParent()->getFirstNonPhi()
911 : std::next(Previous->getIterator());
912 }
913
914 // Create FirstOrderRecurrenceSplice and replace FOR uses.
915 VPBuilder LoopBuilder(InsertPt);
916 auto *RecurSplice =
918 {FOR, FOR->getBackedgeValue()});
919 FOR->replaceUsesWithIf(RecurSplice, not_equal_to(RecurSplice));
920 }
921
922 return true;
923}
924
926 VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop,
931 &ConditionalInductions,
932 const SmallPtrSetImpl<const PHINode *> &FixedOrderRecurrences,
933 const SmallPtrSetImpl<PHINode *> &InLoopReductions, bool AllowReordering) {
934 // Retrieve the header manually from the intial plain-CFG VPlan.
935 auto [HeaderVPBB, LatchVPBB] = VPBlockUtils::getPlainCFGHeaderAndLatch(Plan);
936 assert(VPDT.dominates(HeaderVPBB, LatchVPBB) &&
937 "header must dominate its latch");
938
939 auto CreateHeaderPhiRecipe = [&](VPPhi *PhiR) -> VPHeaderPHIRecipe * {
940 // TODO: Gradually replace uses of underlying instruction by analyses on
941 // VPlan.
942 auto *Phi = cast<PHINode>(PhiR->getUnderlyingInstr());
943 assert(PhiR->getNumOperands() == 2 &&
944 "Must have 2 operands for header phis");
945
946 // Extract common values once.
947 VPIRValue *Start = cast<VPIRValue>(PhiR->getOperand(0));
948 VPValue *BackedgeValue = PhiR->getOperand(1);
949
950 if (FixedOrderRecurrences.contains(Phi)) {
951 // TODO: Currently fixed-order recurrences are modeled as chains of
952 // first-order recurrences. If there are no users of the intermediate
953 // recurrences in the chain, the fixed order recurrence should be
954 // modeled directly, enabling more efficient codegen.
955 return new VPFirstOrderRecurrencePHIRecipe(Phi, *Start, *BackedgeValue);
956 }
957
958 auto InductionIt = Inductions.find(Phi);
959 if (InductionIt != Inductions.end())
960 return createWidenInductionRecipe(Phi, PhiR, Start, InductionIt->second,
961 Plan, PSE, OrigLoop,
962 PhiR->getDebugLoc());
963
964 auto ConditionalInductionIt = ConditionalInductions.find(Phi);
965 if (ConditionalInductionIt != ConditionalInductions.end()) {
966 const ConditionalInductionDescriptor &CondID =
967 ConditionalInductionIt->second;
968 return new VPConditionalInductionPHIRecipe(*Phi, *Start, *BackedgeValue,
969 CondID.getStepSCEV());
970 }
971
972 assert(Reductions.contains(Phi) && "only reductions are expected now");
973 const RecurrenceDescriptor &RdxDesc = Reductions.lookup(Phi);
975 Phi->getIncomingValueForBlock(OrigLoop.getLoopPreheader()) &&
976 "incoming value must match start value");
977 // Will be updated later to >1 if reduction is partial.
978 unsigned ScaleFactor = 1;
979 bool UseOrderedReductions = !AllowReordering && RdxDesc.isOrdered();
980 return new VPReductionPHIRecipe(
981 Phi, RdxDesc.getRecurrenceKind(), *Start, *BackedgeValue,
982 getReductionStyle(InLoopReductions.contains(Phi), UseOrderedReductions,
983 ScaleFactor),
984 Phi->getType()->isFloatingPointTy() ? RdxDesc.getFastMathFlags()
985 : VPIRFlags(),
987 };
988
989 for (VPPhi &PhiR :
990 make_early_inc_range(map_range(HeaderVPBB->phis(), CastTo<VPPhi>))) {
991 VPHeaderPHIRecipe *HeaderPhiR = CreateHeaderPhiRecipe(&PhiR);
992 HeaderPhiR->insertBefore(&PhiR);
993 PhiR.replaceAllUsesWith(HeaderPhiR);
994 PhiR.eraseFromParent();
995 }
996
997 if (!tryToSinkOrHoistRecurrenceUsers(HeaderVPBB, VPDT)) {
999 "Failed to sink or hoist user of first-order recurrence",
1000 "CannotSinkHoistFORUser", ORE, &OrigLoop);
1001 return false;
1002 }
1003
1004 // Skip renaming resume phi recipes, if any header phi has been removed.
1005 if (range_size(HeaderVPBB->phis()) !=
1007 return true;
1008 for (const auto &[HeaderPhiR, ScalarPhiR] :
1009 zip_equal(HeaderVPBB->phis(), Plan.getScalarPreheader()->phis())) {
1010 auto *ResumePhiR = cast<VPPhi>(&ScalarPhiR);
1011 if (isa<VPFirstOrderRecurrencePHIRecipe>(&HeaderPhiR)) {
1012 ResumePhiR->setName("scalar.recur.init");
1013 auto *ExtractLastLane = cast<VPInstruction>(ResumePhiR->getOperand(0));
1014 ExtractLastLane->setName("vector.recur.extract");
1015 continue;
1016 }
1017 ResumePhiR->setName(isa<VPWidenInductionRecipe>(HeaderPhiR)
1018 ? "bc.resume.val"
1019 : "bc.merge.rdx");
1020 }
1021 return true;
1022}
1023
1026 bool OptForSize,
1027 unsigned SCEVCheckThreshold,
1029 Loop *TheLoop) {
1030 // Collect which wide IVs have predicates and add them to PSE.
1031 auto [HeaderVPBB, _] = VPBlockUtils::getPlainCFGHeaderAndLatch(Plan);
1033 for (VPWidenInductionRecipe &WideIV :
1034 make_isa_range<VPWidenInductionRecipe>(HeaderVPBB->phis())) {
1035 if (WideIV.getNoWrapPredicates().empty())
1036 continue;
1037 PredicatedIVs.insert(&WideIV);
1038 for (const auto *P : WideIV.getNoWrapPredicates())
1039 PSE.addPredicate(*P);
1040 }
1041
1042 unsigned TotalComplexity = PSE.getPredicate().getComplexity();
1043 if (TotalComplexity && OptForSize) {
1044 LLVM_DEBUG(
1045 dbgs() << "LV: Not vectorizing: SCEV predicates needed for induction "
1046 "but optimizing for size\n");
1048 "Runtime SCEV check is required with -Os/-Oz",
1049 "runtime SCEV checks needed but optimizing for size",
1050 "CantVersionLoopWithOptForSize", ORE, TheLoop);
1051 return false;
1052 }
1053
1054 if (TotalComplexity > SCEVCheckThreshold) {
1055 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Too many SCEV checks needed ("
1056 << TotalComplexity << " > " << SCEVCheckThreshold
1057 << ")\n");
1059 "Too many SCEV checks needed",
1060 "Too many SCEV assumptions need to be made and checked at runtime",
1061 "TooManySCEVRunTimeChecks", ORE, TheLoop);
1062 return false;
1063 }
1064
1065 return true;
1066}
1067
1069 ElementCount MinVF) {
1072
1073 for (VPRecipeBase &R : Header->phis()) {
1074 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
1075 if (!PhiR || !PhiR->isInLoop() || (MinVF.isScalar() && !PhiR->isOrdered()))
1076 continue;
1077
1078 RecurKind Kind = PhiR->getRecurrenceKind();
1082 "AnyOf and Find reductions are not allowed for in-loop reductions");
1083
1084 bool IsFPRecurrence =
1086 FastMathFlags FMFs =
1087 IsFPRecurrence ? FastMathFlags::getFast() : FastMathFlags();
1088
1089 // Collect the chain of "link" recipes for the reduction starting at PhiR.
1091 Worklist.insert(PhiR);
1092 for (unsigned I = 0; I != Worklist.size(); ++I) {
1093 VPSingleDefRecipe *Cur = Worklist[I];
1094 for (VPSingleDefRecipe *UserRecipe :
1096 if (!UserRecipe->getParent()->getEnclosingLoopRegion()) {
1097 assert((UserRecipe->getParent() == Plan.getMiddleBlock() ||
1098 UserRecipe->getParent() == Plan.getScalarPreheader()) &&
1099 "U must be either in the loop region, the middle block or the "
1100 "scalar preheader.");
1101 continue;
1102 }
1103
1104 // Stores using instructions will be sunk later.
1105 if (match(UserRecipe, m_VPInstruction<Instruction::Store>()))
1106 continue;
1107 Worklist.insert(UserRecipe);
1108 }
1109 }
1110
1111 // Visit operation "Links" along the reduction chain top-down starting from
1112 // the phi until LoopExitValue. We keep track of the previous item
1113 // (PreviousLink) to tell which of the two operands of a Link will remain
1114 // scalar and which will be reduced. For minmax by select(cmp), Link will be
1115 // the select instructions. A blend of the in-loop reduction phi is folded
1116 // to its non-phi operand; all links are masked by the blend's mask for that
1117 // operand instead, as the chain only contributes on that edge.
1118 VPValue *BlendMask = nullptr;
1119 VPBasicBlock *BlendVPBB = nullptr;
1120 auto BlendIt = find_if(Worklist, IsaPred<VPBlendRecipe>);
1121 if (BlendIt != Worklist.end()) {
1122 auto *Blend = cast<VPBlendRecipe>(*BlendIt);
1123 assert(Blend->getNumIncomingValues() == 2 &&
1124 "Blend must have 2 incoming values");
1125 unsigned ChainIdx = Blend->getIncomingValue(0) == PhiR ? 1 : 0;
1126 assert(Blend->getIncomingValue(1 - ChainIdx) == PhiR &&
1127 "PhiR must be an operand of the blend");
1128 BlendMask = Blend->getMask(ChainIdx);
1129 BlendVPBB = Blend->getParent();
1130 Blend->replaceAllUsesWith(Blend->getIncomingValue(ChainIdx));
1131 ToDelete.push_back(Blend);
1132 Worklist.erase(BlendIt);
1133 }
1134
1135 VPSingleDefRecipe *PreviousLink = PhiR; // Aka Worklist[0].
1136 for (VPSingleDefRecipe *CurrentLink : drop_begin(Worklist)) {
1137 if (IsFPRecurrence) {
1138 FastMathFlags CurFMF =
1139 cast<VPRecipeWithIRFlags>(CurrentLink)->getFastMathFlagsOrNone();
1140 if (match(CurrentLink, m_Select(m_VPValue(), m_VPValue(), m_VPValue())))
1141 CurFMF |= cast<VPRecipeWithIRFlags>(CurrentLink->getOperand(0))
1142 ->getFastMathFlagsOrNone();
1143 FMFs &= CurFMF;
1144 }
1145
1146 Instruction *CurrentLinkI = CurrentLink->getUnderlyingInstr();
1147
1148 // Recognize a call to the llvm.fmuladd intrinsic.
1149 bool IsFMulAdd = Kind == RecurKind::FMulAdd;
1150 VPValue *VecOp;
1151 VPBasicBlock *LinkVPBB = BlendVPBB ? BlendVPBB : CurrentLink->getParent();
1152 if (IsFMulAdd) {
1154 "Expected current VPInstruction to be a call to the "
1155 "llvm.fmuladd intrinsic");
1156 assert(CurrentLink->getOperand(2) == PreviousLink &&
1157 "expected a call where the previous link is the added operand");
1158
1159 // If the instruction is a call to the llvm.fmuladd intrinsic then we
1160 // need to create an fmul recipe (multiplying the first two operands of
1161 // the fmuladd together) to use as the vector operand for the fadd
1162 // reduction.
1163 auto *FMulRecipe = new VPInstruction(
1164 Instruction::FMul,
1165 {CurrentLink->getOperand(0), CurrentLink->getOperand(1)},
1166 CurrentLinkI->getFastMathFlags());
1167 FMulRecipe->insertBefore(CurrentLink);
1168 VecOp = FMulRecipe;
1169 } else if (Kind == RecurKind::AddChainWithSubs &&
1170 match(CurrentLink, m_Sub(m_VPValue(), m_VPValue()))) {
1171 Type *PhiTy = PhiR->getScalarType();
1172 auto *Zero = Plan.getConstantInt(PhiTy, 0);
1173 VPBuilder Builder(CurrentLink);
1174 auto *Sub = Builder.createSub(Zero, CurrentLink->getOperand(1),
1175 CurrentLinkI->getDebugLoc());
1176 Sub->setUnderlyingValue(CurrentLinkI);
1177 VecOp = Sub;
1178 } else {
1179 // Index of the first operand which holds a non-mask vector operand.
1180 unsigned IndexOfFirstOperand = 0;
1182 if (match(CurrentLink, m_Cmp(m_VPValue(), m_VPValue())))
1183 continue;
1184 assert(match(CurrentLink,
1186 "must be a select recipe");
1187 IndexOfFirstOperand = 1;
1188 }
1189 // Note that for non-commutable operands (cmp-selects), the semantics of
1190 // the cmp-select are captured in the recurrence kind.
1191 unsigned VecOpId =
1192 CurrentLink->getOperand(IndexOfFirstOperand) == PreviousLink
1193 ? IndexOfFirstOperand + 1
1194 : IndexOfFirstOperand;
1195 VecOp = CurrentLink->getOperand(VecOpId);
1196 assert(
1197 VecOp != PreviousLink &&
1198 CurrentLink->getOperand(
1199 cast<VPInstruction>(CurrentLink)->getNumOperandsWithoutMask() -
1200 1 - (VecOpId - IndexOfFirstOperand)) == PreviousLink &&
1201 "PreviousLink must be the operand other than VecOp");
1202 }
1203
1204 assert(PhiR->getVFScaleFactor() == 1 &&
1205 "inloop reductions must be unscaled");
1206 VPValue *CondOp =
1207 BlendMask ? BlendMask : cast<VPInstruction>(CurrentLink)->getMask();
1208 auto *RedRecipe = new VPReductionRecipe(
1209 Kind, FMFs, CurrentLinkI, PreviousLink, VecOp, CondOp,
1210 getReductionStyle(/*IsInLoop=*/true, PhiR->isOrdered(), 1),
1211 CurrentLinkI->getDebugLoc());
1212 // Append the recipe to the end of the VPBasicBlock because we need to
1213 // ensure that it comes after all of it's inputs, including CondOp.
1214 // Delete CurrentLink as it will be invalid if its operand is replaced
1215 // with a reduction defined at the bottom of the block in the next link.
1216 if (LinkVPBB->getNumSuccessors() == 0)
1217 RedRecipe->insertBefore(&*std::prev(std::prev(LinkVPBB->end())));
1218 else
1219 LinkVPBB->appendRecipe(RedRecipe);
1220
1221 CurrentLink->replaceAllUsesWith(RedRecipe);
1222 // Move any store recipes using the RedRecipe that appear before it in the
1223 // same block to just after the RedRecipe. With a blend, the RedRecipe is
1224 // placed in the blend's block, after stores in earlier blocks, so move
1225 // all of them.
1226 for (VPRecipeBase *UserR : make_early_inc_range(
1227 make_isa_range<VPRecipeBase>(RedRecipe->users()))) {
1228 if (!BlendVPBB && UserR->getParent() != LinkVPBB)
1229 continue;
1231 continue;
1232 assert(UserR->getOperand(0) == RedRecipe &&
1233 UserR->getOperand(1)->isDefinedOutsideLoopRegions() &&
1234 "only invariant stores of the reduction can be moved");
1235 UserR->moveAfter(RedRecipe);
1236 }
1237 ToDelete.push_back(CurrentLink);
1238 // The compare of a min/max select is dead once the select is replaced,
1239 // and may use RedRecipe before its definition.
1241 VPValue *Cmp = CurrentLink->getOperand(0);
1242 assert(Cmp->hasOneUse() && "compare must only be used by the select");
1243 ToDelete.push_back(Cmp->getDefiningRecipe());
1244 }
1245 PreviousLink = RedRecipe;
1246 }
1247 }
1248
1249 for (VPRecipeBase *R : ToDelete)
1250 R->eraseFromParent();
1251}
1252
1254 Loop *TheLoop,
1256 DominatorTree &DT,
1257 AssumptionCache *AC) {
1258 ScalarEvolution &SE = *PSE.getSE();
1259 const DataLayout &DL = TheLoop->getHeader()->getDataLayout();
1260 for (VPBasicBlock *VPBB : vp_rpo_plain_cfg_loop_body(HeaderVPBB)) {
1261 for (VPRecipeBase &R : *VPBB) {
1262 // Pseudo-probes are profiling placeholders with side effects but no real
1263 // memory access. They are modeled as reading inaccessible memory, so skip
1264 // them here to stay consistent with isReadOnlyLoop(), which classifies
1265 // such loops as read-only.
1267 continue;
1268 auto *VPI = dyn_cast<VPInstruction>(&R);
1269 if (!VPI || VPI->getOpcode() != Instruction::Load) {
1270 assert(!R.mayReadFromMemory() && "unexpected recipe reading memory");
1271 continue;
1272 }
1273
1274 // Get the pointer SCEV for dereferenceability checking.
1275 VPValue *Ptr = VPI->getOperand(0);
1276 const SCEV *PtrSCEV = vputils::getSCEVExprForVPValue(Ptr, PSE, TheLoop);
1277 if (isa<SCEVCouldNotCompute>(PtrSCEV)) {
1278 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Found non-dereferenceable "
1279 "load with SCEVCouldNotCompute pointer\n");
1280 return false;
1281 }
1282
1283 // Check dereferenceability using the SCEV-based version.
1284 Type *LoadTy = VPI->getScalarType();
1285 const SCEV *SizeSCEV =
1286 SE.getStoreSizeOfExpr(DL.getIndexType(PtrSCEV->getType()), LoadTy);
1287 auto *Load = cast<LoadInst>(VPI->getUnderlyingValue());
1289 if (isDereferenceableAndAlignedInLoop(PtrSCEV, Load->getAlign(), SizeSCEV,
1290 TheLoop, SE, DT, AC, &Preds))
1291 continue;
1292
1293 return false;
1294 }
1295 }
1296 return true;
1297}
1298
1300 auto *MiddleVPBB = VPBlockUtils::getPlainCFGMiddleBlock(Plan);
1301 // Disconnect countable early exits from the loop, leaving it with a single
1302 // exit from the latch. Countable early exits are left for a scalar epilog.
1303 for (auto [EarlyExitingVPBB, EB] : vputils::getEarlyExits(Plan, MiddleVPBB)) {
1304 // Remove phi operands for the early exiting block.
1305 for (VPIRPhi &ExitIRI : map_range(EB->phis(), CastTo<VPIRPhi>))
1306 ExitIRI.removeIncomingValueFor(EarlyExitingVPBB);
1307 EarlyExitingVPBB->getTerminator()->eraseFromParent();
1308 VPBlockUtils::disconnectBlocks(EarlyExitingVPBB, EB);
1309 }
1310}
1311
1313 auto *MiddleVPBB = VPBlockUtils::getPlainCFGMiddleBlock(Plan);
1314 // If MiddleVPBB has a single successor then the original loop does not exit
1315 // via the latch and the single successor must be the scalar preheader.
1316 // There's no need to add a runtime check to MiddleVPBB.
1317 if (MiddleVPBB->getNumSuccessors() == 1) {
1318 assert(MiddleVPBB->getSingleSuccessor() == Plan.getScalarPreheader() &&
1319 "must have ScalarPH as single successor");
1320 return;
1321 }
1322
1323 assert(MiddleVPBB->getNumSuccessors() == 2 && "must have 2 successors");
1324
1325 // Add a check in the middle block to see if we have completed all of the
1326 // iterations in the first vector loop.
1327 //
1328 // Three cases:
1329 // 1) If we require a scalar epilogue, the scalar ph must execute. Set the
1330 // condition to false.
1331 // 2) If (N - N%VF) == N, then we *don't* need to run the
1332 // remainder. Thus if tail is to be folded, we know we don't need to run
1333 // the remainder and we can set the condition to true.
1334 // 3) Otherwise, construct a runtime check.
1335
1336 // We use the same DebugLoc as the scalar loop latch terminator instead of
1337 // the corresponding compare because they may have ended up with different
1338 // line numbers and we want to avoid awkward line stepping while debugging.
1339 // E.g., if the compare has got a line number inside the loop.
1340 auto *LatchVPBB = cast<VPBasicBlock>(MiddleVPBB->getSinglePredecessor());
1341 DebugLoc LatchDL = LatchVPBB->getTerminator()->getDebugLoc();
1342 VPBuilder Builder(MiddleVPBB);
1343 VPValue *Cmp =
1344 Builder.createICmp(CmpInst::ICMP_EQ, Plan.getTripCount(),
1345 &Plan.getVectorTripCount(), LatchDL, "cmp.n");
1346 Builder.createNaryOp(VPInstruction::BranchOnCond, {Cmp}, LatchDL);
1347}
1348
1350 VPDominatorTree VPDT(Plan);
1352 Plan.getEntry());
1353 // Headers and latches have been canonicalized by addInitialSkeleton.
1354 for (VPBlockBase *HeaderVPB : POT) {
1355 if (!VPBlockUtils::isHeader(HeaderVPB, VPDT))
1356 continue;
1357 assert(HeaderVPB->getPredecessors()[1]->getSuccessors().back() ==
1358 HeaderVPB &&
1359 "latch must have the header as last successor");
1360 createLoopRegion(Plan, HeaderVPB, DL);
1361 }
1362
1363 VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
1364 TopRegion->setName("vector loop");
1365 TopRegion->getEntryBasicBlock()->setName("vector.body");
1366}
1367
1369 assert(Plan.getExitBlocks().size() == 1 &&
1370 "only a single-exit block is supported currently");
1371 assert(Plan.getExitBlocks().front()->getSinglePredecessor() ==
1372 Plan.getMiddleBlock() &&
1373 "the exit block must have middle block as single predecessor");
1374
1375 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1376 assert(LoopRegion->getSingleSuccessor() == Plan.getMiddleBlock() &&
1377 "The vector loop region must have the middle block as its single "
1378 "successor for now");
1379 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
1380
1381 Header->splitAt(Header->getFirstNonPhi());
1382
1383 // Abstract header mask, materialized into concrete recipes later.
1384 VPValue *HeaderMask = LoopRegion->createHeaderMask();
1385 VPBuilder Builder(Header->getFirstNonPhi());
1386 Builder.createNaryOp(VPInstruction::BranchOnCond, HeaderMask);
1387
1388 VPBasicBlock *OrigLatch = LoopRegion->getExitingBasicBlock();
1389 VPValue *IVInc;
1390 [[maybe_unused]] bool TermBranchOnCount =
1391 match(OrigLatch->getTerminator(),
1393 m_Specific(&Plan.getVectorTripCount())));
1394 assert(TermBranchOnCount &&
1395 match(IVInc, m_Add(m_Specific(LoopRegion->getCanonicalIV()),
1396 m_Specific(&Plan.getVFxUF()))) &&
1397 std::next(IVInc->getDefiningRecipe()->getIterator()) ==
1398 OrigLatch->getTerminator()->getIterator() &&
1399 "Unexpected canonical iv increment");
1400
1401 // Split the latch at the IV update, and branch to it from the header mask.
1402 VPBasicBlock *Latch =
1403 OrigLatch->splitAt(IVInc->getDefiningRecipe()->getIterator());
1404 Latch->setName("vector.latch");
1405 VPBlockUtils::connectBlocks(Header, Latch);
1406
1407 // Collect any values defined in the loop that need a phi, that is header phis
1408 // and any value defined n the loop and used in the middle block.
1409 // TODO: Handle early exits via Plan.getExitBlocks()
1411 auto CollectBypassedOperands = [&](VPRecipeBase &R) {
1412 for (VPValue *Op : R.operands()) {
1413 auto *DefR = Op->getDefiningRecipe();
1414 if (DefR && DefR->getParent()->getEnclosingLoopRegion() == LoopRegion &&
1415 !is_contained({Header, Latch}, DefR->getParent()))
1416 NeedsPhi[Op].push_back(&R);
1417 }
1418 };
1419 for (VPRecipeBase &R : Header->phis())
1420 CollectBypassedOperands(R);
1421 for (VPRecipeBase &R : *Plan.getMiddleBlock())
1422 CollectBypassedOperands(R);
1423
1424 // Insert phis for values coming past the end of the tail.
1425 Builder.setInsertPoint(Latch->begin());
1426 for (const auto &[V, Users] : NeedsPhi) {
1427 VPValue *TailVal = Plan.getPoison(V->getScalarType());
1428 std::optional<VPIRFlags> Flags;
1430 "Value used by more than two reduction phis?");
1432 auto *RdxPhi =
1433 RedIt != Users.end() ? cast<VPReductionPHIRecipe>(*RedIt) : nullptr;
1434 if (RdxPhi && !RdxPhi->isInLoop()) {
1435 TailVal = RdxPhi;
1436 Flags = *RdxPhi;
1437 }
1438
1439 VPInstruction *Phi = Builder.createScalarPhi({V, TailVal}, {}, "", Flags);
1440 for (VPUser *U : Users)
1441 U->replaceUsesOfWith(V, Phi);
1442 }
1443
1444 // Any extract of the last element must be updated to extract from the last
1445 // active lane of the header mask instead (i.e., the lane corresponding to the
1446 // last active iteration).
1447 Builder.setInsertPoint(Plan.getMiddleBlock()->getTerminator());
1448 for (VPRecipeBase &R : *Plan.getMiddleBlock()) {
1449 VPValue *Op;
1451 continue;
1452
1453 // Compute the index of the last active lane.
1454 VPValue *LastActiveLane = Builder.createLastActiveLane(HeaderMask);
1455 auto *Ext =
1456 Builder.createNaryOp(VPInstruction::ExtractLane, {LastActiveLane, Op});
1457 R.getVPSingleValue()->replaceAllUsesWith(Ext);
1458 }
1459
1460 // VectorTripCount now equals TripCount so simplify the MiddleVPBB branch.
1464 m_Specific(&Plan.getVectorTripCount())))) &&
1465 "Unexpected MiddleVPBB branch");
1466 Plan.getMiddleBlock()->getTerminator()->setOperand(0, Plan.getTrue());
1467}
1468
1469/// Add an incoming value to all phis in \p VPBB for its just-added last
1470/// predecessor, re-using the value of the previously last one.
1472 for (VPPhi &Phi : map_range(VPBB->phis(), CastTo<VPPhi>)) {
1473 assert(Phi.getNumIncoming() == VPBB->getNumPredecessors() - 1 &&
1474 "must have incoming values for all predecessors but the new one");
1475 Phi.addIncoming(Phi.getIncomingValue(Phi.getNumIncoming() - 1));
1476 }
1477}
1478
1479/// Insert \p CheckBlockVPBB on the edge leading to the vector preheader,
1480/// connecting it to both vector and scalar preheaders. Updates scalar
1481/// preheader phis to account for the new predecessor.
1483 VPBasicBlock *CheckBlockVPBB) {
1484 VPBlockBase *VectorPH = Plan.getVectorPreheader();
1485 auto *ScalarPH = cast<VPBasicBlock>(Plan.getScalarPreheader());
1486 VPBlockBase *PreVectorPH = VectorPH->getSinglePredecessor();
1487 VPBlockUtils::insertOnEdge(PreVectorPH, VectorPH, CheckBlockVPBB);
1488 VPBlockUtils::connectBlocks(CheckBlockVPBB, ScalarPH);
1489 CheckBlockVPBB->swapSuccessors();
1491}
1492
1493VPIRBasicBlock *
1495 VPBasicBlock *MainCheck) {
1496 VPBasicBlock *VectorPH = EpiPlan.getVectorPreheader();
1497 assert(VectorPH && VectorPH->phis().empty() &&
1498 "vector preheader must exist and have no phis to update");
1499 auto *MainScalarPH = cast<VPIRBasicBlock>(MainPlan.getScalarPreheader());
1500 assert(MainScalarPH->getIRBasicBlock()->phis().empty() &&
1501 "MainPlan must not have generated phis in its scalar preheader");
1502 auto *EpilogueCheck =
1503 EpiPlan.createEmptyVPIRBasicBlock(MainScalarPH->getIRBasicBlock());
1504 VPBlockUtils::reassociateBlocks(EpiPlan.getEntry(), EpilogueCheck);
1505
1506 // Map blocks from MainPlan to new, empty VPIRBasicBlocks in EpiPlan, so the
1507 // skeleton CFG can be modeled explicitly. MainPlan's entry maps to EpiPlan's
1508 // now-disconnected entry and its scalar PH to EpilogueCheck.
1509 VPBlockBase *MainEntry = MainPlan.getEntry();
1511 MainToEpiVPBB[MainEntry] = EpiPlan.getEntry();
1513 MainEntry);
1515 // Skip entry block and exit blocks/scalar loop header; they are already
1516 // modeled in the epilogue plan.
1517 if (VPBB != MainEntry && VPBB != MainScalarPH && VPBB->hasSuccessors())
1518 MainToEpiVPBB[VPBB] =
1519 EpiPlan.createEmptyVPIRBasicBlock(VPBB->getIRBasicBlock());
1520 MainToEpiVPBB[MainScalarPH] = EpilogueCheck;
1521
1522 // First, connect the edges from the bypass blocks (minimum iteration checks,
1523 // runtime checks) to the scalar preheader, in reverse order, to preserve the
1524 // predecessor order of the generated IR. The middle block is the first
1525 // predecessor. MainCheck only bypasses the main vector loop; connect it to
1526 // the epilogue vector preheader instead.
1527 VPBasicBlock *EpiScalarPH = EpiPlan.getScalarPreheader();
1528 for (VPBlockBase *MainVPBB :
1529 reverse(drop_begin(MainScalarPH->predecessors()))) {
1530 VPBlockBase *EpiVPBB = MainToEpiVPBB.lookup(MainVPBB);
1531 if (MainVPBB == MainCheck) {
1532 VPBlockUtils::connectBlocks(EpiVPBB, VectorPH);
1533 continue;
1534 }
1535 VPBlockUtils::connectBlocks(EpiVPBB, EpiScalarPH);
1536 addIncomingForLastPredecessor(EpiScalarPH);
1537 }
1538
1539 // Mirror MainPlan's CFG, skipping the bypass edges connected above, which
1540 // come first, edges to blocks not modeled in EpiPlan and the main vector
1541 // loop's back-edge (to a block earlier in RPO), so EpiPlan contains no loop
1542 // it does not own.
1544 for (auto &[MainVPBB, EpiVPBB] : drop_end(MainToEpiVPBB)) {
1545 Visited.insert(MainVPBB);
1546 for (VPBlockBase *Succ :
1547 drop_begin(MainVPBB->getSuccessors(), EpiVPBB->getNumSuccessors()))
1548 if (auto *SuccVPBB = MainToEpiVPBB.lookup(Succ);
1549 SuccVPBB && !Visited.contains(Succ))
1550 VPBlockUtils::connectBlocks(EpiVPBB, SuccVPBB);
1551 }
1552 return EpilogueCheck;
1553}
1554
1555// Likelyhood of bypassing the vectorized loop due to a runtime check block,
1556// including memory overlap checks block and wrapping/unit-stride checks block.
1557static constexpr uint32_t CheckBypassWeights[] = {1, 127};
1558
1559/// Create a BranchOnCond terminator in \p CheckBlockVPBB. Optionally adds
1560/// branch weights.
1561static void addBypassBranch(VPlan &Plan, VPBasicBlock *CheckBlockVPBB,
1562 VPValue *Cond, bool AddBranchWeights) {
1564 auto *Term = VPBuilder(CheckBlockVPBB)
1566 if (AddBranchWeights) {
1567 MDBuilder MDB(Plan.getContext());
1568 MDNode *BranchWeights =
1569 MDB.createBranchWeights(CheckBypassWeights, /*IsExpected=*/false);
1570 Term->setMetadata(LLVMContext::MD_prof, BranchWeights);
1571 }
1572}
1573
1575 VPBasicBlock *CheckBlock,
1576 bool AddBranchWeights) {
1577 insertCheckBlockBeforeVectorLoop(Plan, CheckBlock);
1578 addBypassBranch(Plan, CheckBlock, Cond, AddBranchWeights);
1579}
1580
1582 BasicBlock *CheckBlock,
1583 bool AddBranchWeights) {
1584 VPValue *CondVPV = Plan.getOrAddLiveIn(Cond);
1585 VPBasicBlock *CheckBlockVPBB = Plan.createVPIRBasicBlock(CheckBlock);
1586 attachVPCheckBlock(Plan, CondVPV, CheckBlockVPBB, AddBranchWeights);
1587}
1588
1589/// Generate recipes for the memory runtime checks \p Checks of \p TheLoop
1590/// using \p Builder and return the condition that is true if any check fails.
1592 VPSCEVExpander &Expander,
1594 const Loop *TheLoop, ScalarEvolution &SE,
1595 DebugLoc DL) {
1596 // Expand each group's bounds once so all checks reuse the same frozen values.
1598 std::tuple<VPValue *, VPValue *, const SCEV *>, 8>
1599 GroupToBounds;
1600 for (const auto &[A, B] : Checks) {
1601 for (const RuntimeCheckingPtrGroup *CG : {A, B}) {
1602 if (GroupToBounds.contains(CG))
1603 continue;
1604 auto [Low, High, Stride] = getRuntimeCheckBounds(
1605 CG, TheLoop, SE, VectorizerParams::HoistRuntimeChecks);
1606 VPValue *Start = Expander.expand(Low);
1607 VPValue *End = Expander.expand(High);
1608 if (CG->NeedsFreeze) {
1609 Start = Builder.createFreeze(Start, DL);
1610 End = Builder.createFreeze(End, DL);
1611 }
1612 GroupToBounds[CG] = {Start, End, Stride};
1613 }
1614 }
1615
1616 VPValue *Cond = Plan.getFalse();
1617 SmallPtrSet<const SCEV *, 4> CheckedStrides;
1618 for (const auto &[A, B] : Checks) {
1619 auto [AStart, AEnd, AStride] = GroupToBounds[A];
1620 auto [BStart, BEnd, BStride] = GroupToBounds[B];
1621 // Compare B's bounds in A's address space, see addRuntimeChecks.
1622 Type *PtrTy = AStart->getScalarType();
1623 if (BStart->getScalarType() != PtrTy) {
1624 BStart = Builder.createScalarCast(Instruction::AddrSpaceCast, BStart,
1625 PtrTy, DL);
1626 BEnd =
1627 Builder.createScalarCast(Instruction::AddrSpaceCast, BEnd, PtrTy, DL);
1628 }
1629 VPValue *Bound0 =
1630 Builder.createICmp(CmpInst::ICMP_ULT, AStart, BEnd, DL, "bound0");
1631 VPValue *Bound1 =
1632 Builder.createICmp(CmpInst::ICMP_ULT, BStart, AEnd, DL, "bound1");
1633 VPValue *IsConflict =
1634 Builder.createAnd(Bound0, Bound1, DL, "found.conflict");
1635 for (const SCEV *Stride : {AStride, BStride}) {
1636 if (!Stride || !CheckedStrides.insert(Stride).second)
1637 continue;
1638 VPValue *StrideV = Expander.expand(Stride);
1639 VPValue *IsNegative = Builder.createICmp(
1640 CmpInst::ICMP_SLT, StrideV, Plan.getZero(StrideV->getScalarType()),
1641 DL, "stride.check");
1642 IsConflict = Builder.createOr(IsConflict, IsNegative, DL);
1643 }
1644 Cond = Builder.createOr(Cond, IsConflict, DL, "conflict.rdx");
1645 }
1646 return Cond;
1647}
1648
1649/// Generate recipes for the memory runtime difference checks \p Checks using
1650/// \p Builder and return the condition that is true if any check fails. Each
1651/// difference is compared against a threshold derived from \p VF and \p UF.
1653 VPSCEVExpander &Expander,
1656 unsigned UF, DebugLoc DL) {
1657 // Set of operand pairs of already created compares, to allow detecting and
1658 // re-using redundant compares.
1660 VPValue *Cond = Plan.getFalse();
1661 for (const auto &[SrcStart, SinkStart, AccessSize, NeedsFreeze] : Checks) {
1662 assert(UF * AccessSize > 0 &&
1663 "Threshold must be non-zero to use diff-check");
1664 Type *Ty = SinkStart->getType();
1665 const SCEV *TotalAccessSize = SE.getElementCount(Ty, VF * UF * AccessSize);
1666 const SCEV *ThresholdMinusOneSCEV =
1667 SE.getMinusSCEV(TotalAccessSize, SE.getOne(Ty));
1668 const SCEV *DiffSCEV = SE.getMinusSCEV(SinkStart, SrcStart);
1669
1670 // If the same compare has already been created earlier, there is no need to
1671 // check it again.
1672 if (!SeenCompares.insert({DiffSCEV, ThresholdMinusOneSCEV}).second)
1673 continue;
1674
1675 VPValue *ThresholdMinusOne = Expander.expand(ThresholdMinusOneSCEV);
1676 VPValue *Diff = Expander.expand(DiffSCEV);
1677 // Use (Diff - 1) <u (Threshold - 1), equivalent to 0 <u Diff <u Threshold,
1678 // to exclude Diff == 0 (equal pointers are safe).
1679 VPValue *DiffMinusOne =
1680 Builder.createSub(Diff, Plan.getConstantInt(Ty, 1), DL);
1681 VPValue *IsConflict = Builder.createICmp(
1682 CmpInst::ICMP_ULT, DiffMinusOne, ThresholdMinusOne, DL, "diff.check");
1683 if (NeedsFreeze)
1684 IsConflict = Builder.createFreeze(IsConflict, DL, "diff.check.fr");
1685 Cond = Builder.createOr(Cond, IsConflict, DL, "conflict.rdx");
1686 }
1687 return Cond;
1688}
1689
1691 VPlan &Plan, const RuntimePointerChecking &RtPtrChecking,
1692 const Loop *TheLoop, ScalarEvolution &SE, ElementCount VF, unsigned UF,
1693 bool AddBranchWeights) {
1694 assert(!RtPtrChecking.getChecks().empty() && "No checks to generate");
1695
1696 DebugLoc DL = TheLoop->getStartLoc();
1697 auto *MemCheckVPBB = Plan.createVPBasicBlock("vector.memcheck");
1698 VPBuilder Builder(MemCheckVPBB);
1699 VPSCEVExpander Expander(Builder, SE, DL, TheLoop->getParentLoop(),
1700 /*SafeUDivMode=*/true);
1701 auto DiffChecks = RtPtrChecking.getDiffChecks();
1702 VPValue *Cond =
1703 DiffChecks
1704 ? createDiffRuntimeChecks(Plan, Builder, Expander, *DiffChecks, SE,
1705 VF, UF, DL)
1706 : createRuntimeChecks(Plan, Builder, Expander,
1707 RtPtrChecking.getChecks(), TheLoop, SE, DL);
1708 attachVPCheckBlock(Plan, Cond, MemCheckVPBB, AddBranchWeights);
1709}
1710
1712 VPlan &Plan, ElementCount VF, unsigned UF,
1713 ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue,
1714 bool TailFolded, Loop *OrigLoop, const uint32_t *MinItersBypassWeights,
1716 // Generate code to check if the loop's trip count is less than VF * UF, or
1717 // equal to it in case a scalar epilogue is required; this implies that the
1718 // vector trip count is zero. This check also covers the case where adding one
1719 // to the backedge-taken count overflowed leading to an incorrect trip count
1720 // of zero. In this case we will also jump to the scalar loop.
1721 CmpInst::Predicate CmpPred =
1722 RequiresScalarEpilogue ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
1723 // If tail is to be folded, vector loop takes care of all iterations.
1724 VPValue *TripCountVPV = Plan.getTripCount();
1725 const SCEV *TripCount = vputils::getSCEVExprForVPValue(TripCountVPV, PSE);
1726 Type *TripCountTy = TripCount->getType();
1727 ScalarEvolution &SE = *PSE.getSE();
1728 auto GetMinTripCount = [&]() -> const SCEV * {
1729 // Compute max(MinProfitableTripCount, UF * VF) and return it.
1730 const SCEV *VFxUF =
1731 SE.getElementCount(TripCountTy, (VF * UF), SCEV::FlagNUW);
1732 if (UF * VF.getKnownMinValue() >=
1733 MinProfitableTripCount.getKnownMinValue()) {
1734 // TODO: SCEV should be able to simplify test.
1735 return VFxUF;
1736 }
1737 const SCEV *MinProfitableTripCountSCEV =
1738 SE.getElementCount(TripCountTy, MinProfitableTripCount, SCEV::FlagNUW);
1739 return SE.getUMaxExpr(MinProfitableTripCountSCEV, VFxUF);
1740 };
1741
1742 VPBuilder Builder(CheckBlock);
1743 VPValue *TripCountCheck = Plan.getFalse();
1744 const SCEV *Step = GetMinTripCount();
1745 // TripCountCheck = false, folding tail implies positive vector trip
1746 // count.
1747 if (!TailFolded) {
1748 // TODO: Emit unconditional branch to vector preheader instead of
1749 // conditional branch with known condition.
1750 TripCount = SE.applyLoopGuards(TripCount, OrigLoop);
1751 // Check if the trip count is < the step.
1752 if (SE.isKnownPredicate(CmpPred, TripCount, Step)) {
1753 // TODO: Ensure step is at most the trip count when determining max VF and
1754 // UF, w/o tail folding.
1755 TripCountCheck = Plan.getTrue();
1756 } else if (!SE.isKnownPredicate(CmpInst::getInversePredicate(CmpPred),
1757 TripCount, Step)) {
1758 // Generate the minimum iteration check only if we cannot prove the
1759 // check is known to be true, or known to be false.
1760 VPValue *MinTripCountVPV =
1761 VPSCEVExpander(Builder, *PSE.getSE(), DL).expand(Step);
1762 TripCountCheck = Builder.createICmp(
1763 CmpPred, TripCountVPV, MinTripCountVPV, DL, "min.iters.check");
1764 } // else step known to be < trip count, use TripCountCheck preset to false.
1765 }
1766 VPInstruction *Term =
1767 Builder.createNaryOp(VPInstruction::BranchOnCond, {TripCountCheck}, DL);
1769 MDBuilder MDB(Plan.getContext());
1770 MDNode *BranchWeights = MDB.createBranchWeights(
1771 ArrayRef(MinItersBypassWeights, 2), /*IsExpected=*/false);
1772 Term->setMetadata(LLVMContext::MD_prof, BranchWeights);
1773 }
1774}
1775
1777 VPlan &Plan, ElementCount VF, unsigned UF, bool RequiresScalarEpilogue,
1778 Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL,
1780 auto *CheckBlock = Plan.createVPBasicBlock("vector.main.loop.iter.check");
1781 insertCheckBlockBeforeVectorLoop(Plan, CheckBlock);
1783 RequiresScalarEpilogue, /*TailFolded=*/false,
1784 OrigLoop, MinItersBypassWeights, DL, PSE,
1785 CheckBlock);
1786}
1787
1789 VPlan &Plan, VPValue *MainVectorTripCount, bool RequiresScalarEpilogue,
1790 ElementCount EpilogueVF, unsigned MainLoopStep, unsigned EpilogueLoopStep,
1791 ScalarEvolution &SE) {
1792 // Add the minimum iteration check for the epilogue vector loop.
1793 auto *EpilogueCheck =
1795
1796 // A tail-folded epilogue handles any number of remaining iterations, so the
1797 // epilogue check never branches to the scalar preheader.
1798 if (Plan.hasTailFolded()) {
1799 assert(!RequiresScalarEpilogue &&
1800 "Expected no scalar epilogue for tail-folded plan");
1801 VPBuilder(EpilogueCheck)
1803 return;
1804 }
1805
1806 VPBuilder Builder(cast<VPBasicBlock>(Plan.getEntry()));
1807 VPValue *TC = Plan.getTripCount();
1808 VPValue *VFxUF = Builder.createExpandSCEV(
1809 SE.getElementCount(TC->getScalarType(), EpilogueVF, SCEV::FlagNUW));
1810 Builder.setInsertPoint(EpilogueCheck);
1811 VPValue *Count = Builder.createSub(TC, MainVectorTripCount,
1812 DebugLoc::getUnknown(), "n.vec.remaining");
1813
1814 // Generate code to check if the loop's trip count is less than VF * UF of
1815 // the vector epilogue loop.
1816 auto P = RequiresScalarEpilogue ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
1817 auto *CheckMinIters = Builder.createICmp(
1818 P, Count, VFxUF, DebugLoc::getUnknown(), "min.epilog.iters.check");
1819 VPInstruction *Branch =
1820 Builder.createNaryOp(VPInstruction::BranchOnCond, CheckMinIters);
1821
1822 // We assume the remaining `Count` is equally distributed in
1823 // [0, MainLoopStep)
1824 // So the probability for `Count < EpilogueLoopStep` should be
1825 // min(MainLoopStep, EpilogueLoopStep) / MainLoopStep
1826 // TODO: Improve the estimate by taking the estimated trip count into
1827 // consideration.
1828 unsigned EstimatedSkipCount = std::min(MainLoopStep, EpilogueLoopStep);
1829 const uint32_t Weights[] = {EstimatedSkipCount,
1830 MainLoopStep - EstimatedSkipCount};
1831 MDBuilder MDB(Plan.getContext());
1832 MDNode *BranchWeights =
1833 MDB.createBranchWeights(Weights, /*IsExpected=*/false);
1834 Branch->setMetadata(LLVMContext::MD_prof, BranchWeights);
1835}
1836
1837/// Find and return the final select instruction of the FindIV result pattern
1838/// for the given \p BackedgeVal:
1839/// select(icmp ne ComputeReductionResult(ReducedIV), Sentinel),
1840/// ComputeReductionResult(ReducedIV), Start.
1843 BackedgeVal,
1844 match_fn(m_FindIVResult(m_Specific(BackedgeVal), m_VPValue())));
1845}
1846
1848 auto GetMinOrMaxCompareValue =
1849 [](VPReductionPHIRecipe *RedPhiR) -> VPValue * {
1851 RedPhiR->getRecurrenceKind())) {
1852 // TODO: Support non-constant and NaN start values.
1853 auto *StartC = dyn_cast<VPConstant>(RedPhiR->getStartValue());
1854 if (!StartC || !isa<ConstantFP>(StartC->getConstant()) ||
1855 StartC->getConstant()->isNaN())
1856 return nullptr;
1857
1858 // FMinSelectNoFMF/FMaxSelectNoFMF must select between RedPhiR and the new
1859 // element Op, based on a compare of the two.
1860 VPValue *Op, *A, *B;
1861 if (match(RedPhiR->getBackedgeValue(),
1863 m_VPValue(A), m_VPValue(B))) &&
1864 ((A == RedPhiR && B == Op) || (A == Op && B == RedPhiR)))
1865 return Op;
1866 return nullptr;
1867 }
1868
1869 auto *MinOrMaxR =
1870 dyn_cast_or_null<VPRecipeWithIRFlags>(RedPhiR->getBackedgeValue());
1871 if (!MinOrMaxR)
1872 return nullptr;
1873
1874 // Check that MinOrMaxR is a VPWidenIntrinsicRecipe or VPReplicateRecipe
1875 // with an intrinsic that matches the reduction kind.
1876 Intrinsic::ID ExpectedIntrinsicID =
1877 getMinMaxReductionIntrinsicOp(RedPhiR->getRecurrenceKind());
1878 if (!match(MinOrMaxR, m_Intrinsic(ExpectedIntrinsicID)))
1879 return nullptr;
1880
1881 // MinOrMaxR must combine RedPhiR directly with the new element, as the NaN
1882 // check added below only covers the other operand.
1883 // TODO: Support multi-step min/max chains (e.g. maxnum(l, maxnum(k, phi)))
1884 // by checking all operands feeding the chain for NaNs.
1885 if (MinOrMaxR->getOperand(0) == RedPhiR)
1886 return MinOrMaxR->getOperand(1);
1887 if (MinOrMaxR->getOperand(1) == RedPhiR)
1888 return MinOrMaxR->getOperand(0);
1889 return nullptr;
1890 };
1891
1892 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1894 MinOrMaxNumReductionsToHandle;
1895 bool HasUnsupportedPhi = false;
1896 for (auto &R : LoopRegion->getEntryBasicBlock()->phis()) {
1898 continue;
1899 auto *Cur = dyn_cast<VPReductionPHIRecipe>(&R);
1900 if (!Cur) {
1901 // TODO: Also support fixed-order recurrence phis.
1902 HasUnsupportedPhi = true;
1903 continue;
1904 }
1905 RecurKind Kind = Cur->getRecurrenceKind();
1908 HasUnsupportedPhi = true;
1909 continue;
1910 }
1911
1912 VPValue *MinOrMaxOp = GetMinOrMaxCompareValue(Cur);
1913 if (!MinOrMaxOp)
1914 return false;
1915
1916 MinOrMaxNumReductionsToHandle.emplace_back(Cur, MinOrMaxOp);
1917 }
1918
1919 if (MinOrMaxNumReductionsToHandle.empty())
1920 return true;
1921
1922 // We won't be able to resume execution in the scalar tail, if there are
1923 // unsupported header phis or there is no scalar tail at all, due to
1924 // tail-folding.
1925 if (HasUnsupportedPhi || !Plan.hasScalarTail())
1926 return false;
1927
1928 // TODO: Support loops with uncountable early exits; their latch is not
1929 // terminated by BranchOnCount.
1930 VPBasicBlock *LatchVPBB = LoopRegion->getExitingBasicBlock();
1931 if (!match(LatchVPBB->getTerminator(), m_BranchOnCount()))
1932 return false;
1933
1934 /// Check if the vector loop of \p Plan can early exit and restart
1935 /// execution of last vector iteration in the scalar loop. This requires all
1936 /// recipes up to early exit point be side-effect free as they are
1937 /// re-executed. Currently we check that the loop is free of any recipe that
1938 /// may write to memory. Expected to operate on an early VPlan w/o nested
1939 /// regions.
1940 for (VPBasicBlock *VPBB :
1943 for (auto &R : *VPBB) {
1944 if (R.mayWriteToMemory() && !match(&R, m_BranchOnCount()))
1945 return false;
1946 }
1947 }
1948
1949 // Freeze MinOrMaxOps since:
1950 // * multiple uses are introduced and the value may be undef
1951 // * they feed into a branch condition, so block poison propagation to
1952 // prevent immediate UB
1953 for (auto &[Phi, MinOrMaxOp] : MinOrMaxNumReductionsToHandle) {
1954 VPRecipeBase *MinOrMaxR = Phi->getBackedgeValue()->getDefiningRecipe();
1955 // For select-based min/max, insert the freeze before the compare, which
1956 // also uses MinOrMaxOp.
1957 VPRecipeBase *CmpR = MinOrMaxR;
1959 Phi->getRecurrenceKind()))
1960 CmpR = MinOrMaxR->getOperand(0)->getDefiningRecipe();
1961 VPInstruction *Freeze = VPBuilder(CmpR).createFreeze(MinOrMaxOp);
1962 MinOrMaxR->replaceUsesOfWith(MinOrMaxOp, Freeze);
1963 CmpR->replaceUsesOfWith(MinOrMaxOp, Freeze);
1964 MinOrMaxOp = Freeze;
1965 }
1966
1967 VPBuilder LatchBuilder(LatchVPBB->getTerminator());
1968 VPValue *AllNaNLanes = nullptr;
1969 SmallPtrSet<VPValue *, 2> RdxResults;
1970 for (const auto &[RedPhiR, MinOrMaxOp] : MinOrMaxNumReductionsToHandle) {
1971 VPValue *RedNaNLanes =
1972 LatchBuilder.createFCmp(CmpInst::FCMP_UNO, MinOrMaxOp, MinOrMaxOp);
1974 RedPhiR->getRecurrenceKind())) {
1975 // Without NaNs, select-based min/max can only pick a different value
1976 // than the scalar loop if zeros of both signs are combined. Exit on -0.0
1977 // inputs, or on +0.0 inputs if the start value is -0.0.
1978 unsigned BitWidth = RedPhiR->getScalarType()->getScalarSizeInBits();
1979 auto *IntTy = IntegerType::get(Plan.getContext(), BitWidth);
1980 auto *StartC = cast<VPConstant>(RedPhiR->getStartValue())->getConstant();
1981 APInt ExitZero = StartC->isNegativeZeroValue()
1984 VPValue *InputBits;
1985 if (Plan.hasScalarVFOnly())
1986 InputBits = LatchBuilder.createScalarCast(
1987 Instruction::BitCast, MinOrMaxOp, IntTy, DebugLoc::getUnknown());
1988 else
1989 InputBits = LatchBuilder.createWidenCast(Instruction::BitCast,
1990 MinOrMaxOp, IntTy);
1991 VPValue *IsExitZero = LatchBuilder.createICmp(
1992 CmpInst::ICMP_EQ, InputBits, Plan.getConstantInt(ExitZero));
1993 RedNaNLanes = LatchBuilder.createOr(RedNaNLanes, IsExitZero);
1994 }
1995 AllNaNLanes = AllNaNLanes ? LatchBuilder.createOr(AllNaNLanes, RedNaNLanes)
1996 : RedNaNLanes;
1997 }
1998
1999 VPValue *AnyNaNLane =
2000 LatchBuilder.createNaryOp(VPInstruction::AnyOf, {AllNaNLanes});
2001 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
2002 VPBuilder MiddleBuilder(MiddleVPBB->begin());
2003 for (const auto &[RedPhiR, _] : MinOrMaxNumReductionsToHandle) {
2004 RecurKind Kind = RedPhiR->getRecurrenceKind();
2007 "unsupported reduction");
2008
2009 // If we exit early due to NaNs or signed zeros, compute the final reduction
2010 // result based on the reduction phi at the beginning of the last vector
2011 // iteration.
2012 auto *RdxResult = vputils::findComputeReductionResult(RedPhiR);
2013 assert(RdxResult && "must find a ComputeReductionResult");
2014
2015 // Lanes may hold the start value or inputs the scalar loop does not select
2016 // at that point, so drop nnan/ninf from the selects of RedPhiR (the min/max
2017 // and the header mask select with tail folding) and ninf from the result.
2018 // The reduced lanes cannot be NaN, as the start value is not NaN and NaN
2019 // inputs exit early. Set nnan on the result, so combining lanes does not
2020 // need fmin/fmax libcalls, which may not be available.
2022 for (VPUser *U : RedPhiR->users())
2023 if (match(U, m_Select(m_VPValue(), m_VPValue(), m_VPValue())))
2024 cast<VPRecipeWithIRFlags>(U)->dropPoisonGeneratingFlags();
2025 FastMathFlags FMFs = RdxResult->getFastMathFlagsOrNone();
2026 FMFs.setNoInfs(false);
2027 FMFs.setNoNaNs();
2028 RdxResult->setFastMathFlags(FMFs);
2029 }
2030
2031 auto *NewSel = MiddleBuilder.createSelect(AnyNaNLane, RedPhiR,
2032 RdxResult->getOperand(0));
2033 RdxResult->setOperand(0, NewSel);
2034 assert(!RdxResults.contains(RdxResult) && "RdxResult already used");
2035 RdxResults.insert(RdxResult);
2036 }
2037
2038 auto *LatchExitingBranch = LatchVPBB->getTerminator();
2039 assert(match(LatchExitingBranch, m_BranchOnCount(m_VPValue(), m_VPValue())) &&
2040 "Unexpected terminator");
2041 auto *IsLatchExitTaken = LatchBuilder.createICmp(
2042 CmpInst::ICMP_EQ, LatchExitingBranch->getOperand(0),
2043 LatchExitingBranch->getOperand(1));
2044 auto *AnyExitTaken = LatchBuilder.createOr(AnyNaNLane, IsLatchExitTaken);
2045 LatchBuilder.createNaryOp(VPInstruction::BranchOnCond, AnyExitTaken);
2046 LatchExitingBranch->eraseFromParent();
2047
2048 // Update resume phis for inductions in the scalar preheader. If AnyNaNLane is
2049 // true, the resume from the start of the last vector iteration via the
2050 // canonical IV, otherwise from the original value.
2051 auto IsTC = [&Plan](VPValue *V) {
2052 return V == &Plan.getVectorTripCount() || V == Plan.getTripCount();
2053 };
2054 for (VPPhi &ResumeR :
2056 VPValue *VecV = ResumeR.getOperand(0);
2057 if (RdxResults.contains(VecV))
2058 continue;
2059 if (auto *DerivedIV = dyn_cast<VPDerivedIVRecipe>(VecV)) {
2060 VPValue *DIVTC = DerivedIV->getOperand(1);
2061 if (DerivedIV->hasOneUse() && IsTC(DIVTC)) {
2062 auto *NewSel = MiddleBuilder.createSelect(
2063 AnyNaNLane, LoopRegion->getCanonicalIV(), DIVTC);
2064 DerivedIV->moveAfter(MiddleBuilder.getRecipeAtInsertPoint());
2065 DerivedIV->setOperand(1, NewSel);
2066 continue;
2067 }
2068 }
2069 // Bail out and abandon the current, partially modified, VPlan if we
2070 // encounter resume phi that cannot be updated yet.
2071 if (!IsTC(VecV)) {
2072 LLVM_DEBUG(dbgs() << "Found resume phi we cannot update for VPlan with "
2073 "FMaxNum/FMinNum reduction.\n");
2074 return false;
2075 }
2076 auto *NewSel = MiddleBuilder.createSelect(
2077 AnyNaNLane, LoopRegion->getCanonicalIV(), VecV);
2078 ResumeR.setOperand(0, NewSel);
2079 }
2080
2081 auto *MiddleTerm = MiddleVPBB->getTerminator();
2082 MiddleBuilder.setInsertPoint(MiddleTerm);
2083 VPValue *MiddleCond = MiddleTerm->getOperand(0);
2084 VPValue *NewCond =
2085 MiddleBuilder.createAnd(MiddleCond, MiddleBuilder.createNot(AnyNaNLane));
2086 MiddleTerm->setOperand(0, NewCond);
2087 return true;
2088}
2089
2091 // We want to create the following nodes:
2092 // vector.body:
2093 // ...new WidenPHI recipe introduced to keep the mask value for the latest
2094 // iteration where any lane was active.
2095 // mask.phi = phi [ ir<false>, vector.ph ], [ vp<new.mask>, vector.body ]
2096 // ...data.phi (a VPReductionPHIRecipe for a FindLast reduction) already
2097 // exists, but needs updating to use 'new.data' for the backedge value.
2098 // data.phi = phi ir<default.val>, vp<new.data>
2099 //
2100 // ...'data' and 'compare' created by existing nodes...
2101 //
2102 // ...new recipes introduced to determine whether to update the reduction
2103 // values or keep the current one.
2104 // any.active = i1 any-of ir<compare>
2105 // new.mask = select vp<any.active>, ir<compare>, vp<mask.phi>
2106 // new.data = select vp<any.active>, ir<data>, ir<data.phi>
2107 //
2108 // middle.block:
2109 // ...extract-last-active replaces compute-reduction-result.
2110 // result = extract-last-active vp<new.data>, vp<new.mask>, ir<default.val>
2111
2116 PhiR.getRecurrenceKind()))
2117 Phis.push_back(&PhiR);
2118 }
2119
2120 if (Phis.empty())
2121 return true;
2122
2123 VPValue *HeaderMask = Plan.getVectorLoopRegion()->getHeaderMask();
2124 for (VPReductionPHIRecipe *PhiR : Phis) {
2125 // Find the condition for the select/blend.
2126 VPValue *BackedgeSelect = PhiR->getBackedgeValue();
2127 VPValue *CondSelect = BackedgeSelect;
2128
2129 // If there's a header mask, the backedge select will not be the find-last
2130 // select.
2131 if (HeaderMask &&
2132 !match(BackedgeSelect,
2133 m_SelectLike(m_Specific(HeaderMask), m_VPValue(CondSelect),
2134 m_Specific(PhiR))))
2135 return false;
2136
2137 VPValue *Cond = nullptr, *Op1 = nullptr, *Op2 = nullptr;
2138
2139 // If we're matching a blend rather than a select, there should be one
2140 // incoming value which is the data, then all other incoming values should
2141 // be the phi.
2142 auto MatchBlend = [&](VPRecipeBase *R) {
2143 auto *Blend = dyn_cast<VPBlendRecipe>(R);
2144 if (!Blend)
2145 return false;
2146 assert(!Blend->isNormalized() && "must run before blend normalizaion");
2147 unsigned NumIncomingDataValues = 0;
2148 for (unsigned I = 0; I < Blend->getNumIncomingValues(); ++I) {
2149 VPValue *Incoming = Blend->getIncomingValue(I);
2150 if (Incoming != PhiR) {
2151 ++NumIncomingDataValues;
2152 Cond = Blend->getMask(I);
2153 Op1 = Incoming;
2154 Op2 = PhiR;
2155 }
2156 }
2157 return NumIncomingDataValues == 1;
2158 };
2159
2160 VPSingleDefRecipe *SelectR =
2162 if (!match(SelectR,
2163 m_Select(m_VPValue(Cond), m_VPValue(Op1), m_VPValue(Op2))) &&
2164 !MatchBlend(SelectR))
2165 return false;
2166
2167 // Bail out if PhiR has users other than the find-last select/blend and the
2168 // header mask select, e.g. nested blends. Then the data operand may be PhiR
2169 // on some paths and Cond does not determine the lanes to update.
2170 if (any_of(PhiR->users(), [&](VPUser *U) {
2171 return U != SelectR && U != BackedgeSelect->getDefiningRecipe();
2172 }))
2173 return false;
2174
2175 assert(Cond != HeaderMask && "Cond must not be HeaderMask");
2176
2177 // Find final reduction computation and replace it with an
2178 // extract.last.active intrinsic.
2179 auto *RdxResult =
2181 assert(RdxResult && "Could not find reduction result");
2182
2183 // Add mask phi.
2184 VPBuilder Builder = VPBuilder::getToInsertAfter(PhiR);
2185 auto *MaskPHI = Builder.createWidenPhi(Plan.getFalse());
2186
2187 // Add select for mask.
2188 Builder.setInsertPoint(SelectR);
2189
2190 if (Op1 == PhiR) {
2191 // Normalize to selecting the data operand when the condition is true by
2192 // swapping operands and negating the condition.
2193 std::swap(Op1, Op2);
2194 Cond = Builder.createNot(Cond);
2195 }
2196 assert(Op2 == PhiR && "data value must be selected if Cond is true");
2197
2198 if (HeaderMask)
2199 Cond = Builder.createLogicalAnd(HeaderMask, Cond);
2200
2201 Cond = Builder.createFreeze(Cond);
2202 VPValue *AnyOf = Builder.createNaryOp(VPInstruction::AnyOf, Cond);
2203 VPValue *MaskSelect = Builder.createSelect(AnyOf, Cond, MaskPHI);
2204 MaskPHI->addIncoming(MaskSelect);
2205
2206 // Replace select for data.
2207 VPValue *DataSelect =
2208 Builder.createSelect(AnyOf, Op1, Op2, SelectR->getDebugLoc());
2209 SelectR->replaceAllUsesWith(DataSelect);
2210 PhiR->setBackedgeValue(DataSelect);
2211 SelectR->eraseFromParent();
2212
2213 Builder.setInsertPoint(RdxResult);
2214 auto *ExtractLastActive =
2215 Builder.createNaryOp(VPInstruction::ExtractLastActive,
2216 {PhiR->getStartValue(), DataSelect, MaskSelect},
2217 RdxResult->getDebugLoc());
2218 RdxResult->replaceAllUsesWith(ExtractLastActive);
2219 RdxResult->eraseFromParent();
2220 }
2221
2222 return true;
2223}
2224
2225/// Given a first argmin/argmax pattern with strict predicate consisting of
2226/// 1) a MinOrMax reduction \p MinOrMaxPhiR producing \p MinOrMaxResult,
2227/// 2) a wide induction \p WideIV,
2228/// 3) a FindLastIV reduction \p FindLastIVPhiR using \p WideIV,
2229/// return the smallest index of the FindLastIV reduction result using UMin,
2230/// unless \p MinOrMaxResult equals the start value of its MinOrMax reduction.
2231/// In that case, return the start value of the FindLastIV reduction instead.
2232/// If \p WideIV is not canonical, a new canonical wide IV is added, and the
2233/// final result is scaled back to the non-canonical \p WideIV.
2234/// The final value of the FindLastIV reduction is originally computed using
2235/// \p FindIVSelect, \p FindIVCmp, and \p FindIVRdxResult, which are replaced
2236/// and removed.
2237/// Returns true if the pattern was handled successfully, false otherwise.
2239 VPlan &Plan, VPReductionPHIRecipe *MinOrMaxPhiR,
2240 VPReductionPHIRecipe *FindLastIVPhiR, VPWidenIntOrFpInductionRecipe *WideIV,
2241 VPInstruction *MinOrMaxResult, VPInstruction *FindIVSelect,
2242 VPRecipeBase *FindIVCmp, VPInstruction *FindIVRdxResult) {
2243 assert(!FindLastIVPhiR->isInLoop() && !FindLastIVPhiR->isOrdered() &&
2244 "inloop and ordered reductions not supported");
2245 assert(FindLastIVPhiR->getVFScaleFactor() == 1 &&
2246 "FindIV reduction must not be scaled");
2247
2248 // TODO: support for FP in handleFirstArgMinOrMax
2250 MinOrMaxPhiR->getRecurrenceKind()))
2251 return false;
2252
2254 // TODO: Support non (i.e., narrower than) canonical IV types.
2255 // TODO: Emit remarks for failed transformations.
2256 if (Ty != WideIV->getScalarType())
2257 return false;
2258
2259 VPValue *HeaderMask = Plan.getVectorLoopRegion()->getHeaderMask();
2260 auto *BackedgeVal = FindLastIVPhiR->getBackedgeValue();
2261 auto *FindIVSelectVal = BackedgeVal;
2262 if (HeaderMask && !match(BackedgeVal, m_Select(m_Specific(HeaderMask),
2263 m_VPValue(FindIVSelectVal),
2264 m_Specific(FindLastIVPhiR))))
2265 return false;
2266 auto *FindIVSelectR =
2267 cast<VPSingleDefRecipe>(FindIVSelectVal->getDefiningRecipe());
2268
2269 assert(
2270 match(FindIVSelectR, m_Select(m_VPValue(), m_VPValue(), m_VPValue())) &&
2271 "backedge value must be a select");
2272 if (FindIVSelectR->getOperand(1) != WideIV &&
2273 FindIVSelectR->getOperand(2) != WideIV)
2274 return false;
2275
2276 // If the original wide IV is not canonical, create a new one. The canonical
2277 // wide IV is guaranteed to not wrap for all lanes that are active in the
2278 // vector loop.
2279 if (!WideIV->isCanonical()) {
2280 VPIRValue *Zero = Plan.getConstantInt(Ty, 0);
2281 VPIRValue *One = Plan.getConstantInt(Ty, 1);
2282 auto *WidenCanIV = new VPWidenIntOrFpInductionRecipe(
2283 nullptr, Zero, One, WideIV->getVFValue(),
2284 WideIV->getInductionDescriptor(),
2285 VPIRFlags::WrapFlagsTy(/*HasNUW=*/true, /*HasNSW=*/false),
2286 WideIV->getDebugLoc());
2287 WidenCanIV->insertBefore(WideIV);
2288
2289 // Update the select to use the wide canonical IV.
2290 FindIVSelectR->setOperand(FindIVSelectR->getOperand(1) == WideIV ? 1 : 2,
2291 WidenCanIV);
2292 }
2293 FindLastIVPhiR->setOperand(0, Plan.getPoison(Ty));
2294
2295 // The reduction using MinOrMaxPhiR needs adjusting to compute the correct
2296 // result:
2297 // 1. Find the first canonical indices corresponding to partial min/max
2298 // values, using loop reductions.
2299 // 2. Find which of the partial min/max values are equal to the overall
2300 // min/max value.
2301 // 3. Select among the canonical indices those corresponding to the overall
2302 // min/max value.
2303 // 4. Find the first canonical index of overall min/max and scale it back to
2304 // the original IV using VPDerivedIVRecipe.
2305 // 5. If the overall min/max equals the starting min/max, the condition in
2306 // the loop was always false, due to being strict; return the start value
2307 // of FindLastIVPhiR in that case.
2308 //
2309 // For example, we transforms two independent reduction result computations
2310 // for
2311 //
2312 // <x1> vector loop: {
2313 // vector.body:
2314 // ...
2315 // ir<%iv> = WIDEN-INDUCTION nuw nsw ir<10>, ir<1>, vp<%0>
2316 // WIDEN-REDUCTION-PHI ir<%min.idx> = phi ir<sentinel.min.start>,
2317 // ir<%min.idx.next>
2318 // WIDEN-REDUCTION-PHI ir<%min.val> = phi ir<100>, ir<%min.val.next>
2319 // ....
2320 // WIDEN-INTRINSIC ir<%min.val.next> = call llvm.umin(ir<%min.val>, ir<%l>)
2321 // WIDEN ir<%min.idx.next> = select ir<%cmp>, ir<%iv>, ir<%min.idx>
2322 // ...
2323 // }
2324 // Successor(s): middle.block
2325 //
2326 // middle.block:
2327 // vp<%iv.rdx> = compute-reduction-result (smax) vp<%min.idx.next>
2328 // vp<%min.result> = compute-reduction-result (umin) ir<%min.val.next>
2329 // vp<%cmp> = icmp ne vp<%iv.rdx>, ir<sentinel.min.start>
2330 // vp<%find.iv.result> = select vp<%cmp>, vp<%iv.rdx>, ir<10>
2331 //
2332 //
2333 // Into:
2334 //
2335 // vp<%reduced.min> = compute-reduction-result (umin) ir<%min.val.next>
2336 // vp<%reduced.mins.mask> = icmp eq ir<%min.val.next>, vp<%reduced.min>
2337 // vp<%idxs2reduce> = select vp<%reduced.mins.mask>, ir<%min.idx.next>,
2338 // ir<MaxUInt>
2339 // vp<%reduced.idx> = compute-reduction-result (umin) vp<%idxs2reduce>
2340 // vp<%scaled.idx> = DERIVED-IV ir<20> + vp<%reduced.idx> * ir<1>
2341 // vp<%always.false> = icmp eq vp<%reduced.min>, ir<100>
2342 // vp<%final.idx> = select vp<%always.false>, ir<10>,
2343 // vp<%scaled.idx>
2344
2345 VPBuilder Builder(FindIVRdxResult);
2346 VPValue *MinOrMaxExiting = MinOrMaxResult->getOperand(0);
2347 auto *FinalMinOrMaxCmp =
2348 Builder.createICmp(CmpInst::ICMP_EQ, MinOrMaxExiting, MinOrMaxResult);
2349 VPValue *LastIVExiting = FindIVRdxResult->getOperand(0);
2350 VPValue *MaxIV =
2351 Plan.getConstantInt(APInt::getMaxValue(Ty->getIntegerBitWidth()));
2352 auto *FinalIVSelect =
2353 Builder.createSelect(FinalMinOrMaxCmp, LastIVExiting, MaxIV);
2354 VPIRFlags RdxFlags(RecurKind::UMin, false, false, FastMathFlags());
2355 VPSingleDefRecipe *FinalCanIV = Builder.createNaryOp(
2356 VPInstruction::ComputeReductionResult, {FinalIVSelect}, RdxFlags,
2357 FindIVRdxResult->getDebugLoc());
2358
2359 // If we used a new wide canonical IV convert the reduction result back to the
2360 // original IV scale before the final select.
2361 if (!WideIV->isCanonical()) {
2362 auto *DerivedIVRecipe = new VPDerivedIVRecipe(
2364 nullptr, // No FPBinOp for integer induction
2365 WideIV->getStartValue(), FinalCanIV, WideIV->getStepValue());
2366 DerivedIVRecipe->insertBefore(Builder.getRecipeAtInsertPoint());
2367 FinalCanIV = DerivedIVRecipe;
2368 }
2369
2370 // If the final min/max value matches its start value, the condition in the
2371 // loop was always false, i.e. no induction value has been selected. If that's
2372 // the case, set the result of the IV reduction to its start value.
2373 VPValue *AlwaysFalse = Builder.createICmp(CmpInst::ICMP_EQ, MinOrMaxResult,
2374 MinOrMaxPhiR->getStartValue());
2375 VPValue *FinalIV = Builder.createSelect(
2376 AlwaysFalse, FindIVSelect->getOperand(2), FinalCanIV);
2377 FindIVSelect->replaceAllUsesWith(FinalIV);
2378
2379 // Erase the old FindIV result pattern which is now dead.
2380 FindIVSelect->eraseFromParent();
2381 FindIVCmp->eraseFromParent();
2382 FindIVRdxResult->eraseFromParent();
2383 return true;
2384}
2385
2388 Loop *TheLoop) {
2389 for (auto &PhiR : make_early_inc_range(
2391 auto *MinOrMaxPhiR = dyn_cast<VPReductionPHIRecipe>(&PhiR);
2392 // TODO: check for multi-uses in VPlan directly.
2393 if (!MinOrMaxPhiR || !MinOrMaxPhiR->hasUsesOutsideReductionChain())
2394 continue;
2395
2396 // MinOrMaxPhiR has users outside the reduction cycle in the loop. Check if
2397 // the only other user is a FindLastIV reduction. MinOrMaxPhiR must have
2398 // exactly 2 users if not tailfolded:
2399 // 1) the min/max operation of the reduction cycle, and
2400 // 2) the compare of a FindLastIV reduction cycle. This compare must match
2401 // the min/max operation - comparing MinOrMaxPhiR with the operand of the
2402 // min/max operation, and be used only by the select of the FindLastIV
2403 // reduction cycle.
2404 // There is an additional user if the tail was folded:
2405 // 3) the select operation of the vector.latch block. This select uses the
2406 // original MinOrMaxPhiR if the mask is zero.
2407 RecurKind RdxKind = MinOrMaxPhiR->getRecurrenceKind();
2408 assert(
2410 "only min/max recurrences support users outside the reduction chain");
2411
2412 auto *MinOrMaxBackedgeR =
2413 dyn_cast<VPRecipeWithIRFlags>(MinOrMaxPhiR->getBackedgeValue());
2414 if (!MinOrMaxBackedgeR)
2415 return false;
2416
2417 // If the tail was folded then the backedge won't be the
2418 // reduction-intrinsic but the select in the vector.latch block that wraps
2419 // the reduction-intrinsic.
2420 auto *MinOrMaxOp = MinOrMaxBackedgeR;
2421 VPValue *HeaderMask = Plan.getVectorLoopRegion()->getHeaderMask();
2422 VPValue *MinOrMaxTailfold;
2423 if (HeaderMask) {
2424 if (!match(MinOrMaxBackedgeR, m_SelectLike(m_Specific(HeaderMask),
2425 m_VPValue(MinOrMaxTailfold),
2426 m_Specific(MinOrMaxPhiR))))
2427 return false;
2428
2429 MinOrMaxOp = dyn_cast<VPRecipeWithIRFlags>(MinOrMaxTailfold);
2430 if (!MinOrMaxOp)
2431 return false;
2432 }
2433
2434 // Check that MinOrMaxOp is a VPWidenIntrinsicRecipe or
2435 // VPReplicateRecipe with an intrinsic that matches the reduction kind.
2436 Intrinsic::ID ExpectedIntrinsicID = getMinMaxReductionIntrinsicOp(RdxKind);
2437 if (!match(MinOrMaxOp, m_Intrinsic(ExpectedIntrinsicID)))
2438 return false;
2439
2440 // Tailfolded MinOrMaxOp should only feed into the predicated
2441 // select MinOrMaxBackedgeR.
2442 assert((!HeaderMask || MinOrMaxOp->getNumUsers() == 1) &&
2443 "Tailfolded MinOrMaxOp must have exactly 1 user");
2444 // MinOrMaxBackedgeR must have 2 users: 1) MinOrMaxPhiR and 2)
2445 // ComputeReductionResult.
2446 assert(MinOrMaxBackedgeR->getNumUsers() == 2 &&
2447 "MinOrMaxBackedgeR must have exactly 2 users");
2448 // MinOrMaxOp must combine MinOrMaxPhiR directly with the new element;
2449 // reject multi-step min/max chains (e.g. max(l, max(k, phi))), which
2450 // this transform does not handle.
2451 VPValue *MinOrMaxOpValue;
2452 if (MinOrMaxOp->getOperand(0) == MinOrMaxPhiR)
2453 MinOrMaxOpValue = MinOrMaxOp->getOperand(1);
2454 else if (MinOrMaxOp->getOperand(1) == MinOrMaxPhiR)
2455 MinOrMaxOpValue = MinOrMaxOp->getOperand(0);
2456 else
2457 return false;
2458
2459 VPValue *CmpOpA;
2460 VPValue *CmpOpB;
2461 CmpPredicate Pred;
2463 MinOrMaxPhiR, m_Cmp(Pred, m_VPValue(CmpOpA), m_VPValue(CmpOpB)));
2464 if (!Cmp || Cmp->getNumUsers() != 1 ||
2465 (CmpOpA != MinOrMaxOpValue && CmpOpB != MinOrMaxOpValue))
2466 return false;
2467
2468 if (MinOrMaxOpValue != CmpOpB)
2469 Pred = CmpInst::getSwappedPredicate(Pred);
2470
2471 // MinOrMaxPhiR must have exactly 2 users if not tailfolded:
2472 // * MinOrMaxOp,
2473 // * Cmp (that's part of a FindLastIV chain).
2474 // Also an additional third user if it is tailfolded:
2475 // * Predicated HEADER-MASK select in the vector.latch block.
2476 if (MinOrMaxPhiR->getNumUsers() != (HeaderMask ? 3 : 2))
2477 return false;
2478
2479 VPInstruction *MinOrMaxResult =
2481 MinOrMaxBackedgeR);
2482 assert(MinOrMaxResult &&
2483 "MinOrMaxResult must be a user of MinOrMaxBackedgeR");
2484
2485 // Cmp must be used by the select of a FindLastIV chain.
2486 VPValue *Sel = dyn_cast<VPSingleDefRecipe>(Cmp->getSingleUser());
2487 VPValue *IVOp, *FindIV;
2488 if (!Sel || (Sel->getNumUsers() != (HeaderMask ? 1 : 2)) ||
2489 !match(Sel,
2491 return false;
2492
2494 std::swap(FindIV, IVOp);
2495 Pred = CmpInst::getInversePredicate(Pred);
2496 }
2497
2498 auto *FindIVPhiR = dyn_cast<VPReductionPHIRecipe>(FindIV);
2500 FindIVPhiR->getRecurrenceKind()))
2501 return false;
2502
2503 assert(!FindIVPhiR->isInLoop() && !FindIVPhiR->isOrdered() &&
2504 "cannot handle inloop/ordered reductions yet");
2505
2506 // Check if FindIVPhiR is a FindLast pattern by checking the MinMaxKind
2507 // on its ComputeReductionResult. SMax/UMax indicates FindLast.
2508 VPInstruction *FindIVResult =
2510 FindIVPhiR->getBackedgeValue());
2511 assert(FindIVResult &&
2512 "must be able to retrieve the FindIVResult VPInstruction");
2513 RecurKind FindIVMinMaxKind = FindIVResult->getRecurKind();
2514 if (FindIVMinMaxKind != RecurKind::SMax &&
2515 FindIVMinMaxKind != RecurKind::UMax)
2516 return false;
2517
2518 // TODO: Support cases where IVOp is the IV increment.
2519 if (!match(IVOp, m_TruncOrSelf(m_VPValue(IVOp))) ||
2521 return false;
2522
2523 // Check if the predicate is compatible with the reduction kind.
2524 bool IsValidKindPred = [RdxKind, Pred]() {
2525 switch (RdxKind) {
2526 case RecurKind::UMin:
2527 return Pred == CmpInst::ICMP_UGE || Pred == CmpInst::ICMP_UGT;
2528 case RecurKind::UMax:
2529 return Pred == CmpInst::ICMP_ULE || Pred == CmpInst::ICMP_ULT;
2530 case RecurKind::SMax:
2531 return Pred == CmpInst::ICMP_SLE || Pred == CmpInst::ICMP_SLT;
2532 case RecurKind::SMin:
2533 return Pred == CmpInst::ICMP_SGE || Pred == CmpInst::ICMP_SGT;
2534 case RecurKind::FMax:
2536 return Pred == CmpInst::FCMP_OLE || Pred == CmpInst::FCMP_OLT;
2537 case RecurKind::FMin:
2539 return Pred == CmpInst::FCMP_OGE || Pred == CmpInst::FCMP_OGT;
2540 // minnum and maxnum need special handling due to expected sNaN behaviour
2541 // minimum and maximum return NaN if either input is a NAN
2542 case RecurKind::FMinNum:
2543 case RecurKind::FMaxNum:
2546 return false;
2547 default:
2548 llvm_unreachable("unhandled recurrence kind");
2549 }
2550 }();
2551 if (!IsValidKindPred) {
2552 ORE->emit([&]() {
2554 DEBUG_TYPE, "VectorizationMultiUseReductionPredicate",
2555 TheLoop->getStartLoc(), TheLoop->getHeader())
2556 << "Multi-use reduction with predicate "
2558 << " incompatible with reduction kind";
2559 });
2560 return false;
2561 }
2562
2563 if (RdxKind == RecurKind::FMaximumNum ||
2564 RdxKind == RecurKind::FMinimumNum) {
2565 auto *StartC = dyn_cast<VPConstant>(MinOrMaxPhiR->getStartValue());
2566 if (!StartC || StartC->getConstant()->isNaN())
2567 return false;
2568 }
2569
2570 auto *FindIVSelect = findFindIVSelect(FindIVPhiR->getBackedgeValue());
2571 auto *FindIVCmp = FindIVSelect->getOperand(0)->getDefiningRecipe();
2572 auto *FindIVRdxResult = cast<VPInstruction>(FindIVCmp->getOperand(0));
2573 assert(FindIVSelect->getParent() == MinOrMaxResult->getParent() &&
2574 "both results must be computed in the same block");
2575 // Reducing to a scalar min or max value is placed right before reducing to
2576 // its scalar iteration, in order to generate instructions that use both
2577 // their operands.
2578 MinOrMaxResult->moveBefore(FindIVRdxResult->getIterator());
2579
2580 bool IsStrictPredicate = CmpInst::isStrictPredicate(Pred);
2581 if (IsStrictPredicate) {
2582 if (!handleFirstArgMinOrMax(Plan, MinOrMaxPhiR, FindIVPhiR,
2584 MinOrMaxResult, FindIVSelect, FindIVCmp,
2585 FindIVRdxResult))
2586 return false;
2587 continue;
2588 }
2589
2590 // The reduction using MinOrMaxPhiR needs adjusting to compute the correct
2591 // result:
2592 // 1. We need to find the last IV for which the condition based on the
2593 // min/max recurrence is true,
2594 // 2. Compare the partial min/max reduction result to its final value and,
2595 // 3. Select the lanes of the partial FindLastIV reductions which
2596 // correspond to the lanes matching the min/max reduction result.
2597 //
2598 // For example, this transforms
2599 // vp<%min.result> = compute-reduction-result ir<%min.val.next>
2600 // vp<%iv.rdx> = compute-reduction-result (smax) vp<%min.idx.next>
2601 // vp<%cmp> = icmp ne vp<%iv.rdx>, SENTINEL
2602 // vp<%find.iv.result> = select vp<%cmp>, vp<%iv.rdx>, ir<0>
2603 //
2604 // into:
2605 //
2606 // vp<min.result> = compute-reduction-result ir<%min.val.next>
2607 // vp<%final.min.cmp> = icmp eq ir<%min.val.next>, vp<min.result>
2608 // vp<%final.iv> = select vp<%final.min.cmp>, vp<%min.idx.next>, SENTINEL
2609 // vp<%iv.rdx> = compute-reduction-result (smax) vp<%final.iv>
2610 // vp<%cmp> = icmp ne vp<%iv.rdx>, SENTINEL
2611 // vp<%find.iv.result> = select vp<%cmp>, vp<%iv.rdx>, ir<0>
2612 //
2613 VPBuilder B(FindIVRdxResult);
2614 VPValue *MinOrMaxExiting = MinOrMaxResult->getOperand(0);
2615 auto *FinalMinOrMaxCmp =
2617 ? B.createICmp(CmpInst::ICMP_EQ, MinOrMaxExiting, MinOrMaxResult)
2618 : B.createFCmp(CmpInst::FCMP_OEQ, MinOrMaxExiting, MinOrMaxResult);
2619 VPValue *Sentinel = FindIVCmp->getOperand(1);
2620 VPValue *LastIVExiting = FindIVRdxResult->getOperand(0);
2621 auto *FinalIVSelect =
2622 B.createSelect(FinalMinOrMaxCmp, LastIVExiting, Sentinel);
2623 FindIVRdxResult->setOperand(0, FinalIVSelect);
2624 }
2625 return true;
2626}
2627
2629 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
2630 VPValue *HeaderMask = LoopRegion->getHeaderMask();
2631 Type *I1Ty = IntegerType::getInt1Ty(Plan.getContext());
2632
2633 VPBuilder Builder(Plan.getVectorPreheader());
2634 auto *AliasMask = Builder.createNaryOp(
2635 VPInstruction::IncomingAliasMask, {}, nullptr, {}, {},
2636 DebugLoc::getUnknown(), "incoming.alias.mask", I1Ty);
2637
2638 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
2639 Builder = VPBuilder(Header->getFirstNonPhi());
2640
2641 // Update all existing users of the header mask to "HeaderMask & AliasMask".
2642 auto *ClampedHeaderMask = Builder.createAnd(HeaderMask, AliasMask);
2643 HeaderMask->replaceUsesWithIf(ClampedHeaderMask,
2644 not_equal_to(ClampedHeaderMask));
2645}
SDValue Pred
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[]
SmallVector< MachineOperand, 4 > Cond
This file provides a LoopVectorizationPlanner class.
static constexpr uint32_t MinItersBypassWeights[]
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t High
#define P(N)
Provides some synthesis utilities to produce sequences of values.
This file defines less commonly used SmallVector utilities.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
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 addIncomingForLastPredecessor(VPBasicBlock *VPBB)
Add an incoming value to all phis in VPBB for its just-added last predecessor, re-using the value of ...
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 addBypassBranch(VPlan &Plan, VPBasicBlock *CheckBlockVPBB, VPValue *Cond, bool AddBranchWeights)
Create a BranchOnCond terminator in CheckBlockVPBB.
static VPValue * createDiffRuntimeChecks(VPlan &Plan, VPBuilder &Builder, VPSCEVExpander &Expander, ArrayRef< PointerDiffInfo > Checks, ScalarEvolution &SE, ElementCount VF, unsigned UF, DebugLoc DL)
Generate recipes for the memory runtime difference checks Checks using Builder and return the conditi...
static bool sinkRecurrenceUsersAfterPrevious(VPFirstOrderRecurrencePHIRecipe *FOR, VPRecipeBase *Previous, const VPDominatorTree &VPDT)
Try to sink users of FOR after Previous.
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 void addInitialSkeleton(VPlan &Plan, Type *InductionTy, PredicatedScalarEvolution &PSE, Loop *TheLoop)
static bool hoistPreviousBeforeFORUsers(VPFirstOrderRecurrencePHIRecipe *FOR, VPRecipeBase *Previous, const VPDominatorTree &VPDT)
Try to hoist Previous and its operands before all users of FOR.
static void createLoopRegion(VPlan &Plan, VPBlockBase *HeaderVPB, DebugLoc DL)
Create a new VPRegionBlock for the loop starting at HeaderVPB.
static VPInstruction * findFindIVSelect(VPValue *BackedgeVal)
Find and return the final select instruction of the FindIV result pattern for the given BackedgeVal: ...
static bool tryToSinkOrHoistRecurrenceUsers(VPBasicBlock *HeaderVPBB, const VPDominatorTree &VPDT)
Sink users of fixed-order recurrences past or hoist before the recipe defining the previous value,...
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.
static VPValue * createRuntimeChecks(VPlan &Plan, VPBuilder &Builder, VPSCEVExpander &Expander, ArrayRef< RuntimePointerCheck > Checks, const Loop *TheLoop, ScalarEvolution &SE, DebugLoc DL)
Generate recipes for the memory runtime checks Checks of TheLoop using Builder and return the conditi...
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:
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
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:61
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:236
Analysis providing branch probability information.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ 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
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ 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)
bool isStrictPredicate() const
Definition InstrTypes.h:906
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Describes a conditional induction variable: an induction variable that is updated only on loop iterat...
const SCEV * getStepSCEV() const
Returns a SCEV expression for the step of the conditional induction PHI.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getUnknown()
Definition DebugLoc.h:153
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
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:793
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:122
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
void setNoNaNs(bool B=true)
Definition FMF.h:78
static FastMathFlags getFast()
Definition FMF.h:50
void setNoInfs(bool B=true)
Definition FMF.h:81
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.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
BlockT * getHeader() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
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...
LLVM_ABI 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
LLVM_ABI DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:688
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:1087
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
ValueT lookup(const KeyT &Key) const
Definition MapVector.h:111
iterator find(const KeyT &Key)
Definition MapVector.h:157
iterator end()
Definition MapVector.h:70
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.
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 ...
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
static bool isFPMinMaxSelectNoFMFRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a select-based floating-point min/max kind lacking nnan or nsz...
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(cond,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 LLVM_ABI bool isIntegerRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is an integer kind.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
std::optional< ArrayRef< PointerDiffInfo > > getDiffChecks() const
const SmallVectorImpl< RuntimePointerCheck > & getChecks() const
Returns the checks that generateChecks created.
virtual unsigned getComplexity() const
Returns the estimated complexity of this predicate.
This class represents an analyzed expression in the program.
static constexpr auto FlagNUW
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEVFlags Flags=SCEV::FlagNone)
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
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 * 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 const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, unsigned Depth=0)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
A vector that has set insertion semantics.
Definition SetVector.h:57
iterator erase(const_iterator I)
Erase a single element from the set vector.
Definition SetVector.h:211
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
iterator end()
Get an iterator to the end of the SetVector.
Definition SetVector.h:118
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:295
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
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
op_range operands()
Definition User.h:267
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4509
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4590
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4540
iterator end()
Definition VPlan.h:4550
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4548
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4603
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:225
VPBasicBlock * splitAt(iterator SplitAt)
Split current block at SplitAt by inserting a new block between the current block and its successors ...
Definition VPlan.cpp:524
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:603
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:79
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
Definition VPlan.h:289
VPRegionBlock * getParent()
Definition VPlan.h:177
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:195
void setName(const Twine &newName)
Definition VPlan.h:170
size_t getNumSuccessors() const
Definition VPlan.h:227
void swapSuccessors()
Swap successors of the block. The block must have exactly 2 successors.
Definition VPlan.h:311
size_t getNumPredecessors() const
Definition VPlan.h:228
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition VPlan.h:280
bool hasSuccessors() const
Returns true if this block has any successors.
Definition VPlan.h:205
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:212
void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse)
Set two given VPBlockBases IfTrue and IfFalse to be the two successors of this VPBlockBase.
Definition VPlan.h:271
VPBlockBase * getSinglePredecessor() const
Definition VPlan.h:223
void swapPredecessors()
Swap predecessors of the block.
Definition VPlan.h:303
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:180
void setOneSuccessor(VPBlockBase *Successor)
Set a given VPBlockBase Successor as the single successor of this VPBlockBase.
Definition VPlan.h:260
void setParent(VPRegionBlock *P)
Definition VPlan.h:187
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:217
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:201
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:467
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
Definition VPlanUtils.h:349
static void insertOnEdge(VPBlockBase *From, VPBlockBase *To, VPBlockBase *BlockPtr)
Inserts BlockPtr on the edge between From and To.
Definition VPlanUtils.h:482
static VPBasicBlock * getPlainCFGMiddleBlock(const VPlan &Plan)
Returns the middle block of Plan in plain CFG form (before regions are formed).
static bool isHeader(const VPBlockBase *VPB, const VPDominatorTree &VPDT)
Returns true if VPB is a loop header, based on regions or VPDT in their absence.
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:394
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:412
static void reassociateBlocks(VPBlockBase *Old, VPBlockBase *New)
Reassociate all the blocks connected to Old so that they now point to New.
Definition VPlanUtils.h:430
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:444
VPInstruction * createFreeze(VPValue *Op, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
static VPBuilderBase getToInsertAfter(VPRecipeBase *R)
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< VPIRFlags > Flags=std::nullopt, Type *ResultTy=nullptr)
Create a phi with IncomingValues, using the default flags for the result type, unless Flags is set.
VPInstruction * createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPWidenCastRecipe * createWidenCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy)
VPRecipeBase * getRecipeAtInsertPoint() const
Get the recipe at the current insert point or nullptr if the insert point is the end of the block.
VPInstruction * createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< VPIRFlags > Flags=std::nullopt)
Create a select of TrueVal and FalseVal based on Cond, using the default flags for the result type,...
VPInstruction * createScalarCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, DebugLoc DL, std::optional< VPIRFlags > Flags=std::nullopt, const VPIRMetadata &Metadata={})
VPInstruction * createNot(VPValue *Operand, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
void setInsertPoint(const VPInsertPoint &IP)
Set the current insert point.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr, const VPIRAttributes &Attrs={})
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
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.
VPInstruction * createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
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.
A recipe for handling scalar conditional induction PHIs.
Definition VPlan.h:2971
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:572
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:545
A recipe for converting Current into Start + Current * Step.
Definition VPlan.h:4280
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
LLVM_ABI_FOR_TEST bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B) const
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2473
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2513
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2502
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4668
Class to record and manage LLVM IR flags.
Definition VPlan.h:667
RecurKind getRecurKind() const
Definition VPlan.h:1017
Helper to manage IR metadata for recipes.
Definition VPlan.h:1140
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1310
@ ExtractLastActive
Extracts the last active lane from a set of vectors.
Definition VPlan.h:1424
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1414
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1428
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1368
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1673
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:386
void moveBefore(RecipeListTy::iterator I)
Unlink this recipe and insert it before I.
RecipeListTy::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
bool isPhi() const
Returns true for PHI-like recipes.
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:531
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:349
A recipe for handling reduction phis.
Definition VPlan.h:2864
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2936
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:2920
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2939
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2933
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3291
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4740
VPRegionValue * createHeaderMask()
Create the header mask for the region and return it.
Definition VPlan.h:4887
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4868
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4860
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4873
DebugLoc getDebugLoc() const
Returns the debug location of the VPRegionValue.
Definition VPlanValue.h:262
Lightweight SCEV-to-VPlan expander.
Definition VPlanUtils.h:286
VPValue * expand(const SCEV *S)
Expand S into recipes and live-ins using the builder.
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:589
Type * getType() const
Returns the scalar type of this symbolic value.
Definition VPlanValue.h:227
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:396
void replaceUsesOfWith(VPValue *From, VPValue *To)
Replaces all uses of From in the VPUser with To.
Definition VPlan.cpp:1501
operand_range operands()
Definition VPlanValue.h:472
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:445
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:437
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:139
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:120
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser *U)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1474
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:204
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1468
unsigned getNumUsers() const
Definition VPlanValue.h:115
user_range users()
Definition VPlanValue.h:157
Base class for widened induction (VPWidenIntOrFpInductionRecipe and VPWidenPointerInductionRecipe),...
Definition VPlan.h:2531
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2571
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2588
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2617
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:4927
VPIRValue * getLiveIn(Value *V) const
Return the live-in VPIRValue for V, if there is one or nullptr otherwise.
Definition VPlan.h:5257
LLVMContext & getContext() const
Definition VPlan.h:5124
VPBasicBlock * getEntry()
Definition VPlan.h:5019
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:5091
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:5223
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5122
VPIRBasicBlock * createEmptyVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock wrapping IRBB, but do not create VPIRInstructions wrapping the instructions i...
Definition VPlan.cpp:1304
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5251
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:5085
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:5112
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:5200
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:5296
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5226
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1058
void setTripCount(VPValue *NewTripCount)
Set the trip count assuming it is currently null; if it is not - use resetTripCount().
Definition VPlan.h:5098
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:5061
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:5283
LLVM_ABI_FOR_TEST VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
Definition VPlan.cpp:1312
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:5220
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:5024
bool hasScalarVFOnly() const
Definition VPlan.h:5168
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:5075
bool hasTailFolded() const
Returns true if the vector loop region is tail-folded.
Definition VPlan.h:5040
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:5081
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:5115
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
Definition VPlan.h:5345
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:5234
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
void reportVectorizationFailure(const StringRef DebugMsg, const StringRef OREMsg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, const Loop *TheLoop, Instruction *I=nullptr)
Reports a vectorization failure: print DebugMsg for debugging purposes along with the corresponding o...
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.
CmpClass_match< LHS, RHS, CmpInst, true > m_c_Cmp(const LHS &L, const RHS &R)
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
SelectLike_match< CondTy, LTy, RTy > m_SelectLike(const CondTy &C, const LTy &TrueC, const RTy &FalseC)
Matches a value that behaves like a boolean-controlled select, i.e.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
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)
auto m_FindIVResult(Op0_t ReducedIV, Op1_t Start)
Match FindIV result pattern: select(icmp ne ComputeReductionResult(ReducedIV), Sentinel),...
RecipeTy * findSingleUser(VPValue *V, const MatchT &P)
Return the sole user of V matching pattern P, casting it to RecipeTy, or nullptr.
VPInstruction_match< VPInstruction::BranchOnTwoConds > m_BranchOnTwoConds()
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
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...
SmallVector< std::pair< VPBasicBlock *, VPIRBasicBlock * > > getEarlyExits(const VPlan &Plan, const VPBlockBase *MiddleVPBB)
Returns the (early exiting block, exit block) pairs of Plan, i.e.
DenseMap< const VPBasicBlock *, std::optional< VPExecutionFrequency > > computeExecutionFrequencies(ArrayRef< VPBasicBlock * > Blocks)
Computes for each block in Blocks, which must be in reverse post-order, the frequency with which it e...
RecipeTy * findUserRecursively(VPValue *Start, PredT Pred)
Search Start's users for a recipe satisfying Pred, looking through recipes with definitions.
Definition VPlanUtils.h:155
VPIRFlags getFlagsForInduction(const InductionDescriptor &ID, const VPPhi *PhiR)
Extracts and returns NoWrap flags from PhiR and fast-math flags from ID.
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, bool ExpandInIR=false)
Get or create a VPValue that corresponds to the expansion of Expr.
LLVM_ABI_FOR_TEST 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:316
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:262
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2196
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:856
ReductionStyle getReductionStyle(bool InLoop, bool Ordered, unsigned ScaleFactor)
Definition VPlan.h:2851
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
VPBuilderBase<> VPBuilder
Definition VPlan.h:65
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
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:649
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:250
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
constexpr size_t range_size(R &&Range)
Returns the size of the Range, i.e., the number of elements.
Definition STLExtras.h:1710
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMinimumNum
FP min with llvm.minimumnum semantics.
@ FindIV
FindIV reduction with select(icmp(),x,y) where one of (x,y) is a loop induction variable (increasing ...
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ AnyOf
AnyOf reduction with select(cond,x,y) where one of (x,y) is loop invariant, and both x and y are inte...
@ FMax
FP max as select(cmp()) with nnan/nsz, or llvm.maxnum.
@ FMaximum
FP max with llvm.maximum semantics.
@ 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()).
@ FMin
FP min as select(cmp()) with nnan/nsz, or llvm.minnum.
@ FMinNum
FP min with llvm.minnum semantics including NaNs.
@ Sub
Subtraction of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
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:2035
LLVM_ABI RuntimeCheckBounds getRuntimeCheckBounds(const RuntimeCheckingPtrGroup *CG, const Loop *TheLoop, ScalarEvolution &SE, bool HoistRuntimeChecks)
Return the bounds of CG in TheLoop.
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:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
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:2162
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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:307
constexpr detail::CastFunc< To > CastTo
Definition Casting.h:884
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:881
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344
A recipe for handling first-order recurrence phis.
Definition VPlan.h:2802
An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use cast/dyn_cast/isa and exec...
Definition VPlan.h:1790
A VPValue representing a live-in from the input IR or a constant.
Definition VPlanValue.h:274
static void simplifyLiveInsWithSCEV(VPlan &Plan, PredicatedScalarEvolution &PSE)
Check Plan's live-ins and replace them with constants, if they can be simplified via SCEV.
static void addMinimumVectorEpilogueIterationCheck(VPlan &Plan, VPValue *MainVectorTripCount, bool RequiresScalarEpilogue, ElementCount EpilogueVF, unsigned MainLoopStep, unsigned EpilogueLoopStep, ScalarEvolution &SE)
Add a check to Plan to see if the epilogue vector loop should be executed.
static void foldTailByMasking(VPlan &Plan)
Adapts the vector loop region for tail folding by introducing a header mask and conditionally executi...
static bool handleMultiUseReductions(VPlan &Plan, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Try to legalize reductions with multiple in-loop uses.
static void recordExecutionFrequencies(VPlan &Plan)
Add execution frequencies to each recipe in the loop body of Plan.
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 bool createHeaderPhiRecipes(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, OptimizationRemarkEmitter *ORE, const VPDominatorTree &VPDT, const MapVector< PHINode *, InductionDescriptor > &Inductions, const MapVector< PHINode *, RecurrenceDescriptor > &Reductions, const MapVector< PHINode *, ConditionalInductionDescriptor > &ConditionalInductions, 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 LLVM_ABI_FOR_TEST void createLoopRegions(VPlan &Plan, DebugLoc DL)
Replace loops in Plan's flat CFG with VPRegionBlocks, turning Plan's flat CFG into a hierarchical CFG...
static VPIRBasicBlock * modelGeneratedMainLoopBlocks(VPlan &EpiPlan, VPlan &MainPlan, VPBasicBlock *MainCheck)
Model the blocks the executed MainPlan generated for the main vector loop in EpiPlan during epilogue ...
static LLVM_ABI_FOR_TEST void addMiddleCheck(VPlan &Plan)
If a check is needed to guard executing the scalar epilogue loop, it will be added to the middle bloc...
static void attachAliasMaskToHeaderMask(VPlan &Plan)
Attaches the alias-mask to the existing header-mask.
static bool areAllLoadsDereferenceable(VPBasicBlock *HeaderVPBB, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC)
Check if all loads in the loop are dereferenceable.
static LLVM_ABI_FOR_TEST std::unique_ptr< VPlan > buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy, PredicatedScalarEvolution &PSE, LoopVersioning *LVer=nullptr, function_ref< const BranchProbabilityInfo &()> GetBPI=nullptr)
Create a base VPlan0, serving as the common starting point for all later candidates.
static bool handleMaxMinNumReductions(VPlan &Plan)
Check if Plan contains any FMaxNum, FMinNum, FMaxSelectNoFMF or FMinSelectNoFMF reductions.
static void attachCheckBlock(VPlan &Plan, Value *Cond, BasicBlock *CheckBlock, bool AddBranchWeights)
static LLVM_ABI_FOR_TEST void handleCountableEarlyExits(VPlan &Plan)
Disconnect countable early exits from the loop.
static bool finalizeSCEVPredicates(VPlan &Plan, PredicatedScalarEvolution &PSE, bool OptForSize, unsigned SCEVCheckThreshold, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Finalize SCEV predicates by adding induction predicates from Plan to PSE and checking constraints.
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 attachMemoryChecks(VPlan &Plan, const RuntimePointerChecking &RtPtrChecking, const Loop *TheLoop, ScalarEvolution &SE, ElementCount VF, unsigned UF, bool AddBranchWeights)
Generate the memory runtime checks of RtPtrChecking for TheLoop as recipes and attach the check block...
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 void attachVPCheckBlock(VPlan &Plan, VPValue *Cond, VPBasicBlock *CheckBlock, bool AddBranchWeights)
Connect CheckBlock to Plan, branching on Cond.
static LLVM_ABI bool HoistRuntimeChecks