Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Vectorize/VPlanConstruction.cpp
213799 views
//===-- VPlanConstruction.cpp - Transforms for initial VPlan construction -===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file9/// This file implements transforms for initial VPlan construction.10///11//===----------------------------------------------------------------------===//1213#include "LoopVectorizationPlanner.h"14#include "VPlan.h"15#include "VPlanCFG.h"16#include "VPlanDominatorTree.h"17#include "VPlanPatternMatch.h"18#include "VPlanTransforms.h"19#include "llvm/Analysis/LoopInfo.h"20#include "llvm/Analysis/LoopIterator.h"21#include "llvm/Analysis/ScalarEvolution.h"22#include "llvm/IR/MDBuilder.h"2324#define DEBUG_TYPE "vplan"2526using namespace llvm;27using namespace VPlanPatternMatch;2829namespace {30// Class that is used to build the plain CFG for the incoming IR.31class PlainCFGBuilder {32// The outermost loop of the input loop nest considered for vectorization.33Loop *TheLoop;3435// Loop Info analysis.36LoopInfo *LI;3738// Vectorization plan that we are working on.39std::unique_ptr<VPlan> Plan;4041// Builder of the VPlan instruction-level representation.42VPBuilder VPIRBuilder;4344// NOTE: The following maps are intentionally destroyed after the plain CFG45// construction because subsequent VPlan-to-VPlan transformation may46// invalidate them.47// Map incoming BasicBlocks to their newly-created VPBasicBlocks.48DenseMap<BasicBlock *, VPBasicBlock *> BB2VPBB;49// Map incoming Value definitions to their newly-created VPValues.50DenseMap<Value *, VPValue *> IRDef2VPValue;5152// Hold phi node's that need to be fixed once the plain CFG has been built.53SmallVector<PHINode *, 8> PhisToFix;5455// Utility functions.56void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB);57void fixHeaderPhis();58VPBasicBlock *getOrCreateVPBB(BasicBlock *BB);59#ifndef NDEBUG60bool isExternalDef(Value *Val);61#endif62VPValue *getOrCreateVPOperand(Value *IRVal);63void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB);6465public:66PlainCFGBuilder(Loop *Lp, LoopInfo *LI)67: TheLoop(Lp), LI(LI), Plan(std::make_unique<VPlan>(Lp)) {}6869/// Build plain CFG for TheLoop and connect it to Plan's entry.70std::unique_ptr<VPlan> buildPlainCFG();71};72} // anonymous namespace7374// Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB75// must have no predecessors.76void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) {77// Collect VPBB predecessors.78SmallVector<VPBlockBase *, 2> VPBBPreds;79for (BasicBlock *Pred : predecessors(BB))80VPBBPreds.push_back(getOrCreateVPBB(Pred));81VPBB->setPredecessors(VPBBPreds);82}8384static bool isHeaderBB(BasicBlock *BB, Loop *L) {85return L && BB == L->getHeader();86}8788// Add operands to VPInstructions representing phi nodes from the input IR.89void PlainCFGBuilder::fixHeaderPhis() {90for (auto *Phi : PhisToFix) {91assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode.");92VPValue *VPVal = IRDef2VPValue[Phi];93assert(isa<VPWidenPHIRecipe>(VPVal) &&94"Expected WidenPHIRecipe for phi node.");95auto *VPPhi = cast<VPWidenPHIRecipe>(VPVal);96assert(VPPhi->getNumOperands() == 0 &&97"Expected VPInstruction with no operands.");98assert(isHeaderBB(Phi->getParent(), LI->getLoopFor(Phi->getParent())) &&99"Expected Phi in header block.");100assert(Phi->getNumOperands() == 2 &&101"header phi must have exactly 2 operands");102for (BasicBlock *Pred : predecessors(Phi->getParent()))103VPPhi->addOperand(104getOrCreateVPOperand(Phi->getIncomingValueForBlock(Pred)));105}106}107108// Create a new empty VPBasicBlock for an incoming BasicBlock or retrieve an109// existing one if it was already created.110VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {111if (auto *VPBB = BB2VPBB.lookup(BB)) {112// Retrieve existing VPBB.113return VPBB;114}115116// Create new VPBB.117StringRef Name = BB->getName();118LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << Name << "\n");119VPBasicBlock *VPBB = Plan->createVPBasicBlock(Name);120BB2VPBB[BB] = VPBB;121return VPBB;122}123124#ifndef NDEBUG125// Return true if \p Val is considered an external definition. An external126// definition is either:127// 1. A Value that is not an Instruction. This will be refined in the future.128// 2. An Instruction that is outside of the IR region represented in VPlan,129// i.e., is not part of the loop nest.130bool PlainCFGBuilder::isExternalDef(Value *Val) {131// All the Values that are not Instructions are considered external132// definitions for now.133Instruction *Inst = dyn_cast<Instruction>(Val);134if (!Inst)135return true;136137// Check whether Instruction definition is in loop body.138return !TheLoop->contains(Inst);139}140#endif141142// Create a new VPValue or retrieve an existing one for the Instruction's143// operand \p IRVal. This function must only be used to create/retrieve VPValues144// for *Instruction's operands* and not to create regular VPInstruction's. For145// the latter, please, look at 'createVPInstructionsForVPBB'.146VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) {147auto VPValIt = IRDef2VPValue.find(IRVal);148if (VPValIt != IRDef2VPValue.end())149// Operand has an associated VPInstruction or VPValue that was previously150// created.151return VPValIt->second;152153// Operand doesn't have a previously created VPInstruction/VPValue. This154// means that operand is:155// A) a definition external to VPlan,156// B) any other Value without specific representation in VPlan.157// For now, we use VPValue to represent A and B and classify both as external158// definitions. We may introduce specific VPValue subclasses for them in the159// future.160assert(isExternalDef(IRVal) && "Expected external definition as operand.");161162// A and B: Create VPValue and add it to the pool of external definitions and163// to the Value->VPValue map.164VPValue *NewVPVal = Plan->getOrAddLiveIn(IRVal);165IRDef2VPValue[IRVal] = NewVPVal;166return NewVPVal;167}168169// Create new VPInstructions in a VPBasicBlock, given its BasicBlock170// counterpart. This function must be invoked in RPO so that the operands of a171// VPInstruction in \p BB have been visited before (except for Phi nodes).172void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,173BasicBlock *BB) {174VPIRBuilder.setInsertPoint(VPBB);175// TODO: Model and preserve debug intrinsics in VPlan.176for (Instruction &InstRef : BB->instructionsWithoutDebug(false)) {177Instruction *Inst = &InstRef;178179// There shouldn't be any VPValue for Inst at this point. Otherwise, we180// visited Inst when we shouldn't, breaking the RPO traversal order.181assert(!IRDef2VPValue.count(Inst) &&182"Instruction shouldn't have been visited.");183184if (auto *Br = dyn_cast<BranchInst>(Inst)) {185// Conditional branch instruction are represented using BranchOnCond186// recipes.187if (Br->isConditional()) {188VPValue *Cond = getOrCreateVPOperand(Br->getCondition());189VPIRBuilder.createNaryOp(VPInstruction::BranchOnCond, {Cond}, Inst);190}191192// Skip the rest of the Instruction processing for Branch instructions.193continue;194}195196if (auto *SI = dyn_cast<SwitchInst>(Inst)) {197SmallVector<VPValue *> Ops = {getOrCreateVPOperand(SI->getCondition())};198for (auto Case : SI->cases())199Ops.push_back(getOrCreateVPOperand(Case.getCaseValue()));200VPIRBuilder.createNaryOp(Instruction::Switch, Ops, Inst);201continue;202}203204VPSingleDefRecipe *NewR;205if (auto *Phi = dyn_cast<PHINode>(Inst)) {206// Phi node's operands may have not been visited at this point. We create207// an empty VPInstruction that we will fix once the whole plain CFG has208// been built.209NewR = new VPWidenPHIRecipe(Phi, nullptr, Phi->getDebugLoc(), "vec.phi");210VPBB->appendRecipe(NewR);211if (isHeaderBB(Phi->getParent(), LI->getLoopFor(Phi->getParent()))) {212// Header phis need to be fixed after the VPBB for the latch has been213// created.214PhisToFix.push_back(Phi);215} else {216// Add operands for VPPhi in the order matching its predecessors in217// VPlan.218DenseMap<const VPBasicBlock *, VPValue *> VPPredToIncomingValue;219for (unsigned I = 0; I != Phi->getNumOperands(); ++I) {220VPPredToIncomingValue[BB2VPBB[Phi->getIncomingBlock(I)]] =221getOrCreateVPOperand(Phi->getIncomingValue(I));222}223for (VPBlockBase *Pred : VPBB->getPredecessors())224NewR->addOperand(225VPPredToIncomingValue.lookup(Pred->getExitingBasicBlock()));226}227} else {228// Translate LLVM-IR operands into VPValue operands and set them in the229// new VPInstruction.230SmallVector<VPValue *, 4> VPOperands;231for (Value *Op : Inst->operands())232VPOperands.push_back(getOrCreateVPOperand(Op));233234// Build VPInstruction for any arbitrary Instruction without specific235// representation in VPlan.236NewR = cast<VPInstruction>(237VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst));238}239240IRDef2VPValue[Inst] = NewR;241}242}243244// Main interface to build the plain CFG.245std::unique_ptr<VPlan> PlainCFGBuilder::buildPlainCFG() {246VPIRBasicBlock *Entry = cast<VPIRBasicBlock>(Plan->getEntry());247BB2VPBB[Entry->getIRBasicBlock()] = Entry;248for (VPIRBasicBlock *ExitVPBB : Plan->getExitBlocks())249BB2VPBB[ExitVPBB->getIRBasicBlock()] = ExitVPBB;250251// 1. Scan the body of the loop in a topological order to visit each basic252// block after having visited its predecessor basic blocks. Create a VPBB for253// each BB and link it to its successor and predecessor VPBBs. Note that254// predecessors must be set in the same order as they are in the incomming IR.255// Otherwise, there might be problems with existing phi nodes and algorithm256// based on predecessors traversal.257258// Loop PH needs to be explicitly visited since it's not taken into account by259// LoopBlocksDFS.260BasicBlock *ThePreheaderBB = TheLoop->getLoopPreheader();261assert((ThePreheaderBB->getTerminator()->getNumSuccessors() == 1) &&262"Unexpected loop preheader");263for (auto &I : *ThePreheaderBB) {264if (I.getType()->isVoidTy())265continue;266IRDef2VPValue[&I] = Plan->getOrAddLiveIn(&I);267}268269LoopBlocksRPO RPO(TheLoop);270RPO.perform(LI);271272for (BasicBlock *BB : RPO) {273// Create or retrieve the VPBasicBlock for this BB.274VPBasicBlock *VPBB = getOrCreateVPBB(BB);275// Set VPBB predecessors in the same order as they are in the incoming BB.276setVPBBPredsFromBB(VPBB, BB);277278// Create VPInstructions for BB.279createVPInstructionsForVPBB(VPBB, BB);280281// Set VPBB successors. We create empty VPBBs for successors if they don't282// exist already. Recipes will be created when the successor is visited283// during the RPO traversal.284if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {285SmallVector<VPBlockBase *> Succs = {286getOrCreateVPBB(SI->getDefaultDest())};287for (auto Case : SI->cases())288Succs.push_back(getOrCreateVPBB(Case.getCaseSuccessor()));289VPBB->setSuccessors(Succs);290continue;291}292auto *BI = cast<BranchInst>(BB->getTerminator());293unsigned NumSuccs = succ_size(BB);294if (NumSuccs == 1) {295VPBB->setOneSuccessor(getOrCreateVPBB(BB->getSingleSuccessor()));296continue;297}298assert(BI->isConditional() && NumSuccs == 2 && BI->isConditional() &&299"block must have conditional branch with 2 successors");300301BasicBlock *IRSucc0 = BI->getSuccessor(0);302BasicBlock *IRSucc1 = BI->getSuccessor(1);303VPBasicBlock *Successor0 = getOrCreateVPBB(IRSucc0);304VPBasicBlock *Successor1 = getOrCreateVPBB(IRSucc1);305VPBB->setTwoSuccessors(Successor0, Successor1);306}307308for (auto *EB : Plan->getExitBlocks())309setVPBBPredsFromBB(EB, EB->getIRBasicBlock());310311// 2. The whole CFG has been built at this point so all the input Values must312// have a VPlan counterpart. Fix VPlan header phi by adding their313// corresponding VPlan operands.314fixHeaderPhis();315316Plan->getEntry()->setOneSuccessor(getOrCreateVPBB(TheLoop->getHeader()));317Plan->getEntry()->setPlan(&*Plan);318319// Fix VPlan loop-closed-ssa exit phi's by adding incoming operands to the320// VPIRInstructions wrapping them.321// // Note that the operand order corresponds to IR predecessor order, and may322// need adjusting when VPlan predecessors are added, if an exit block has323// multiple predecessor.324for (auto *EB : Plan->getExitBlocks()) {325for (VPRecipeBase &R : EB->phis()) {326auto *PhiR = cast<VPIRPhi>(&R);327PHINode &Phi = PhiR->getIRPhi();328assert(PhiR->getNumOperands() == 0 &&329"no phi operands should be added yet");330for (BasicBlock *Pred : predecessors(EB->getIRBasicBlock()))331PhiR->addOperand(332getOrCreateVPOperand(Phi.getIncomingValueForBlock(Pred)));333}334}335336LLVM_DEBUG(Plan->setName("Plain CFG\n"); dbgs() << *Plan);337return std::move(Plan);338}339340std::unique_ptr<VPlan> VPlanTransforms::buildPlainCFG(Loop *TheLoop,341LoopInfo &LI) {342PlainCFGBuilder Builder(TheLoop, &LI);343return Builder.buildPlainCFG();344}345346/// Checks if \p HeaderVPB is a loop header block in the plain CFG; that is, it347/// has exactly 2 predecessors (preheader and latch), where the block348/// dominates the latch and the preheader dominates the block. If it is a349/// header block return true and canonicalize the predecessors of the header350/// (making sure the preheader appears first and the latch second) and the351/// successors of the latch (making sure the loop exit comes first). Otherwise352/// return false.353static bool canonicalHeaderAndLatch(VPBlockBase *HeaderVPB,354const VPDominatorTree &VPDT) {355ArrayRef<VPBlockBase *> Preds = HeaderVPB->getPredecessors();356if (Preds.size() != 2)357return false;358359auto *PreheaderVPBB = Preds[0];360auto *LatchVPBB = Preds[1];361if (!VPDT.dominates(PreheaderVPBB, HeaderVPB) ||362!VPDT.dominates(HeaderVPB, LatchVPBB)) {363std::swap(PreheaderVPBB, LatchVPBB);364365if (!VPDT.dominates(PreheaderVPBB, HeaderVPB) ||366!VPDT.dominates(HeaderVPB, LatchVPBB))367return false;368369// Canonicalize predecessors of header so that preheader is first and370// latch second.371HeaderVPB->swapPredecessors();372for (VPRecipeBase &R : cast<VPBasicBlock>(HeaderVPB)->phis())373R.swapOperands();374}375376// The two successors of conditional branch match the condition, with the377// first successor corresponding to true and the second to false. We378// canonicalize the successors of the latch when introducing the region, such379// that the latch exits the region when its condition is true; invert the380// original condition if the original CFG branches to the header on true.381// Note that the exit edge is not yet connected for top-level loops.382if (LatchVPBB->getSingleSuccessor() ||383LatchVPBB->getSuccessors()[0] != HeaderVPB)384return true;385386assert(LatchVPBB->getNumSuccessors() == 2 && "Must have 2 successors");387auto *Term = cast<VPBasicBlock>(LatchVPBB)->getTerminator();388assert(cast<VPInstruction>(Term)->getOpcode() ==389VPInstruction::BranchOnCond &&390"terminator must be a BranchOnCond");391auto *Not = new VPInstruction(VPInstruction::Not, {Term->getOperand(0)});392Not->insertBefore(Term);393Term->setOperand(0, Not);394LatchVPBB->swapSuccessors();395396return true;397}398399/// Create a new VPRegionBlock for the loop starting at \p HeaderVPB.400static void createLoopRegion(VPlan &Plan, VPBlockBase *HeaderVPB) {401auto *PreheaderVPBB = HeaderVPB->getPredecessors()[0];402auto *LatchVPBB = HeaderVPB->getPredecessors()[1];403404VPBlockUtils::disconnectBlocks(PreheaderVPBB, HeaderVPB);405VPBlockUtils::disconnectBlocks(LatchVPBB, HeaderVPB);406VPBlockBase *LatchExitVPB = LatchVPBB->getSingleSuccessor();407assert(LatchExitVPB && "Latch expected to be left with a single successor");408409// Create an empty region first and insert it between PreheaderVPBB and410// LatchExitVPB, taking care to preserve the original predecessor & successor411// order of blocks. Set region entry and exiting after both HeaderVPB and412// LatchVPBB have been disconnected from their predecessors/successors.413auto *R = Plan.createVPRegionBlock("", false /*isReplicator*/);414VPBlockUtils::insertOnEdge(LatchVPBB, LatchExitVPB, R);415VPBlockUtils::disconnectBlocks(LatchVPBB, R);416VPBlockUtils::connectBlocks(PreheaderVPBB, R);417R->setEntry(HeaderVPB);418R->setExiting(LatchVPBB);419420// All VPBB's reachable shallowly from HeaderVPB belong to the current region.421for (VPBlockBase *VPBB : vp_depth_first_shallow(HeaderVPB))422VPBB->setParent(R);423}424425// Add the necessary canonical IV and branch recipes required to control the426// loop.427static void addCanonicalIVRecipes(VPlan &Plan, VPBasicBlock *HeaderVPBB,428VPBasicBlock *LatchVPBB, Type *IdxTy,429DebugLoc DL) {430Value *StartIdx = ConstantInt::get(IdxTy, 0);431auto *StartV = Plan.getOrAddLiveIn(StartIdx);432433// Add a VPCanonicalIVPHIRecipe starting at 0 to the header.434auto *CanonicalIVPHI = new VPCanonicalIVPHIRecipe(StartV, DL);435HeaderVPBB->insert(CanonicalIVPHI, HeaderVPBB->begin());436437// We are about to replace the branch to exit the region. Remove the original438// BranchOnCond, if there is any.439if (!LatchVPBB->empty() &&440match(&LatchVPBB->back(), m_BranchOnCond(m_VPValue())))441LatchVPBB->getTerminator()->eraseFromParent();442443VPBuilder Builder(LatchVPBB);444// Add a VPInstruction to increment the scalar canonical IV by VF * UF.445// Initially the induction increment is guaranteed to not wrap, but that may446// change later, e.g. when tail-folding, when the flags need to be dropped.447auto *CanonicalIVIncrement = Builder.createOverflowingOp(448Instruction::Add, {CanonicalIVPHI, &Plan.getVFxUF()}, {true, false}, DL,449"index.next");450CanonicalIVPHI->addOperand(CanonicalIVIncrement);451452// Add the BranchOnCount VPInstruction to the latch.453Builder.createNaryOp(VPInstruction::BranchOnCount,454{CanonicalIVIncrement, &Plan.getVectorTripCount()}, DL);455}456457void VPlanTransforms::prepareForVectorization(458VPlan &Plan, Type *InductionTy, PredicatedScalarEvolution &PSE,459bool RequiresScalarEpilogueCheck, bool TailFolded, Loop *TheLoop,460DebugLoc IVDL, bool HasUncountableEarlyExit, VFRange &Range) {461VPDominatorTree VPDT;462VPDT.recalculate(Plan);463464VPBlockBase *HeaderVPB = Plan.getEntry()->getSingleSuccessor();465canonicalHeaderAndLatch(HeaderVPB, VPDT);466VPBlockBase *LatchVPB = HeaderVPB->getPredecessors()[1];467468VPBasicBlock *VecPreheader = Plan.createVPBasicBlock("vector.ph");469VPBlockUtils::insertBlockAfter(VecPreheader, Plan.getEntry());470471VPBasicBlock *MiddleVPBB = Plan.createVPBasicBlock("middle.block");472// The canonical LatchVPB has the header block as last successor. If it has473// another successor, this successor is an exit block - insert middle block on474// its edge. Otherwise, add middle block as another successor retaining header475// as last.476if (LatchVPB->getNumSuccessors() == 2) {477VPBlockBase *LatchExitVPB = LatchVPB->getSuccessors()[0];478VPBlockUtils::insertOnEdge(LatchVPB, LatchExitVPB, MiddleVPBB);479} else {480VPBlockUtils::connectBlocks(LatchVPB, MiddleVPBB);481LatchVPB->swapSuccessors();482}483484addCanonicalIVRecipes(Plan, cast<VPBasicBlock>(HeaderVPB),485cast<VPBasicBlock>(LatchVPB), InductionTy, IVDL);486487[[maybe_unused]] bool HandledUncountableEarlyExit = false;488// Disconnect all early exits from the loop leaving it with a single exit from489// the latch. Early exits that are countable are left for a scalar epilog. The490// condition of uncountable early exits (currently at most one is supported)491// is fused into the latch exit, and used to branch from middle block to the492// early exit destination.493for (VPIRBasicBlock *EB : Plan.getExitBlocks()) {494for (VPBlockBase *Pred : to_vector(EB->getPredecessors())) {495if (Pred == MiddleVPBB)496continue;497if (HasUncountableEarlyExit) {498assert(!HandledUncountableEarlyExit &&499"can handle exactly one uncountable early exit");500handleUncountableEarlyExit(cast<VPBasicBlock>(Pred), EB, Plan,501cast<VPBasicBlock>(HeaderVPB),502cast<VPBasicBlock>(LatchVPB), Range);503HandledUncountableEarlyExit = true;504} else {505for (VPRecipeBase &R : EB->phis())506cast<VPIRPhi>(&R)->removeIncomingValueFor(Pred);507}508cast<VPBasicBlock>(Pred)->getTerminator()->eraseFromParent();509VPBlockUtils::disconnectBlocks(Pred, EB);510}511}512513assert((!HasUncountableEarlyExit || HandledUncountableEarlyExit) &&514"missed an uncountable exit that must be handled");515516// Create SCEV and VPValue for the trip count.517// We use the symbolic max backedge-taken-count, which works also when518// vectorizing loops with uncountable early exits.519const SCEV *BackedgeTakenCountSCEV = PSE.getSymbolicMaxBackedgeTakenCount();520assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCountSCEV) &&521"Invalid loop count");522ScalarEvolution &SE = *PSE.getSE();523const SCEV *TripCount = SE.getTripCountFromExitCount(BackedgeTakenCountSCEV,524InductionTy, TheLoop);525Plan.setTripCount(526vputils::getOrCreateVPValueForSCEVExpr(Plan, TripCount, SE));527528VPBasicBlock *ScalarPH = Plan.createVPBasicBlock("scalar.ph");529VPBlockUtils::connectBlocks(ScalarPH, Plan.getScalarHeader());530531// The connection order corresponds to the operands of the conditional branch,532// with the middle block already connected to the exit block.533VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);534// Also connect the entry block to the scalar preheader.535// TODO: Also introduce a branch recipe together with the minimum trip count536// check.537VPBlockUtils::connectBlocks(Plan.getEntry(), ScalarPH);538Plan.getEntry()->swapSuccessors();539540// If MiddleVPBB has a single successor then the original loop does not exit541// via the latch and the single successor must be the scalar preheader.542// There's no need to add a runtime check to MiddleVPBB.543if (MiddleVPBB->getNumSuccessors() == 1) {544assert(MiddleVPBB->getSingleSuccessor() == ScalarPH &&545"must have ScalarPH as single successor");546return;547}548549assert(MiddleVPBB->getNumSuccessors() == 2 && "must have 2 successors");550551// Add a check in the middle block to see if we have completed all of the552// iterations in the first vector loop.553//554// Three cases:555// 1) If we require a scalar epilogue, the scalar ph must execute. Set the556// condition to false.557// 2) If (N - N%VF) == N, then we *don't* need to run the558// remainder. Thus if tail is to be folded, we know we don't need to run559// the remainder and we can set the condition to true.560// 3) Otherwise, construct a runtime check.561562// We use the same DebugLoc as the scalar loop latch terminator instead of563// the corresponding compare because they may have ended up with different564// line numbers and we want to avoid awkward line stepping while debugging.565// E.g., if the compare has got a line number inside the loop.566DebugLoc LatchDL = TheLoop->getLoopLatch()->getTerminator()->getDebugLoc();567VPBuilder Builder(MiddleVPBB);568VPValue *Cmp;569if (!RequiresScalarEpilogueCheck)570Cmp = Plan.getOrAddLiveIn(ConstantInt::getFalse(571IntegerType::getInt1Ty(TripCount->getType()->getContext())));572else if (TailFolded)573Cmp = Plan.getOrAddLiveIn(ConstantInt::getTrue(574IntegerType::getInt1Ty(TripCount->getType()->getContext())));575else576Cmp = Builder.createICmp(CmpInst::ICMP_EQ, Plan.getTripCount(),577&Plan.getVectorTripCount(), LatchDL, "cmp.n");578Builder.createNaryOp(VPInstruction::BranchOnCond, {Cmp}, LatchDL);579}580581void VPlanTransforms::createLoopRegions(VPlan &Plan) {582VPDominatorTree VPDT;583VPDT.recalculate(Plan);584for (VPBlockBase *HeaderVPB : vp_post_order_shallow(Plan.getEntry()))585if (canonicalHeaderAndLatch(HeaderVPB, VPDT))586createLoopRegion(Plan, HeaderVPB);587588VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();589TopRegion->setName("vector loop");590TopRegion->getEntryBasicBlock()->setName("vector.body");591}592593// Likelyhood of bypassing the vectorized loop due to a runtime check block,594// including memory overlap checks block and wrapping/unit-stride checks block.595static constexpr uint32_t CheckBypassWeights[] = {1, 127};596597void VPlanTransforms::attachCheckBlock(VPlan &Plan, Value *Cond,598BasicBlock *CheckBlock,599bool AddBranchWeights) {600VPValue *CondVPV = Plan.getOrAddLiveIn(Cond);601VPBasicBlock *CheckBlockVPBB = Plan.createVPIRBasicBlock(CheckBlock);602VPBlockBase *VectorPH = Plan.getVectorPreheader();603VPBlockBase *ScalarPH = Plan.getScalarPreheader();604VPBlockBase *PreVectorPH = VectorPH->getSinglePredecessor();605VPBlockUtils::insertOnEdge(PreVectorPH, VectorPH, CheckBlockVPBB);606VPBlockUtils::connectBlocks(CheckBlockVPBB, ScalarPH);607CheckBlockVPBB->swapSuccessors();608609// We just connected a new block to the scalar preheader. Update all610// VPPhis by adding an incoming value for it, replicating the last value.611unsigned NumPredecessors = ScalarPH->getNumPredecessors();612for (VPRecipeBase &R : cast<VPBasicBlock>(ScalarPH)->phis()) {613assert(isa<VPPhi>(&R) && "Phi expected to be VPPhi");614assert(cast<VPPhi>(&R)->getNumIncoming() == NumPredecessors - 1 &&615"must have incoming values for all operands");616R.addOperand(R.getOperand(NumPredecessors - 2));617}618619VPIRMetadata VPBranchWeights;620auto *Term = VPBuilder(CheckBlockVPBB)621.createNaryOp(VPInstruction::BranchOnCond, {CondVPV},622Plan.getCanonicalIV()->getDebugLoc());623if (AddBranchWeights) {624MDBuilder MDB(Plan.getScalarHeader()->getIRBasicBlock()->getContext());625MDNode *BranchWeights =626MDB.createBranchWeights(CheckBypassWeights, /*IsExpected=*/false);627Term->addMetadata(LLVMContext::MD_prof, BranchWeights);628}629}630631bool VPlanTransforms::handleMaxMinNumReductions(VPlan &Plan) {632auto GetMinMaxCompareValue = [](VPReductionPHIRecipe *RedPhiR) -> VPValue * {633auto *MinMaxR = dyn_cast<VPRecipeWithIRFlags>(634RedPhiR->getBackedgeValue()->getDefiningRecipe());635if (!MinMaxR)636return nullptr;637638auto *RepR = dyn_cast<VPReplicateRecipe>(MinMaxR);639if (!isa<VPWidenIntrinsicRecipe>(MinMaxR) &&640!(RepR && isa<IntrinsicInst>(RepR->getUnderlyingInstr())))641return nullptr;642643#ifndef NDEBUG644Intrinsic::ID RdxIntrinsicId =645RedPhiR->getRecurrenceKind() == RecurKind::FMaxNum ? Intrinsic::maxnum646: Intrinsic::minnum;647assert((isa<VPWidenIntrinsicRecipe>(MinMaxR) &&648cast<VPWidenIntrinsicRecipe>(MinMaxR)->getVectorIntrinsicID() ==649RdxIntrinsicId) ||650(RepR &&651cast<IntrinsicInst>(RepR->getUnderlyingInstr())->getIntrinsicID() ==652RdxIntrinsicId) &&653"Intrinsic did not match recurrence kind");654#endif655656if (MinMaxR->getOperand(0) == RedPhiR)657return MinMaxR->getOperand(1);658659assert(MinMaxR->getOperand(1) == RedPhiR &&660"Reduction phi operand expected");661return MinMaxR->getOperand(0);662};663664VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();665VPReductionPHIRecipe *RedPhiR = nullptr;666bool HasUnsupportedPhi = false;667for (auto &R : LoopRegion->getEntryBasicBlock()->phis()) {668if (isa<VPCanonicalIVPHIRecipe, VPWidenIntOrFpInductionRecipe>(&R))669continue;670auto *Cur = dyn_cast<VPReductionPHIRecipe>(&R);671if (!Cur) {672// TODO: Also support fixed-order recurrence phis.673HasUnsupportedPhi = true;674continue;675}676// For now, only a single reduction is supported.677// TODO: Support multiple MaxNum/MinNum reductions and other reductions.678if (RedPhiR)679return false;680if (Cur->getRecurrenceKind() != RecurKind::FMaxNum &&681Cur->getRecurrenceKind() != RecurKind::FMinNum) {682HasUnsupportedPhi = true;683continue;684}685RedPhiR = Cur;686}687688if (!RedPhiR)689return true;690691// We won't be able to resume execution in the scalar tail, if there are692// unsupported header phis or there is no scalar tail at all, due to693// tail-folding.694if (HasUnsupportedPhi || !Plan.hasScalarTail())695return false;696697VPValue *MinMaxOp = GetMinMaxCompareValue(RedPhiR);698if (!MinMaxOp)699return false;700701RecurKind RedPhiRK = RedPhiR->getRecurrenceKind();702assert((RedPhiRK == RecurKind::FMaxNum || RedPhiRK == RecurKind::FMinNum) &&703"unsupported reduction");704705/// Check if the vector loop of \p Plan can early exit and restart706/// execution of last vector iteration in the scalar loop. This requires all707/// recipes up to early exit point be side-effect free as they are708/// re-executed. Currently we check that the loop is free of any recipe that709/// may write to memory. Expected to operate on an early VPlan w/o nested710/// regions.711for (VPBlockBase *VPB : vp_depth_first_shallow(712Plan.getVectorLoopRegion()->getEntryBasicBlock())) {713auto *VPBB = cast<VPBasicBlock>(VPB);714for (auto &R : *VPBB) {715if (R.mayWriteToMemory() &&716!match(&R, m_BranchOnCount(m_VPValue(), m_VPValue())))717return false;718}719}720721VPBasicBlock *LatchVPBB = LoopRegion->getExitingBasicBlock();722VPBuilder Builder(LatchVPBB->getTerminator());723auto *LatchExitingBranch = cast<VPInstruction>(LatchVPBB->getTerminator());724assert(LatchExitingBranch->getOpcode() == VPInstruction::BranchOnCount &&725"Unexpected terminator");726auto *IsLatchExitTaken =727Builder.createICmp(CmpInst::ICMP_EQ, LatchExitingBranch->getOperand(0),728LatchExitingBranch->getOperand(1));729730VPValue *IsNaN = Builder.createFCmp(CmpInst::FCMP_UNO, MinMaxOp, MinMaxOp);731VPValue *AnyNaN = Builder.createNaryOp(VPInstruction::AnyOf, {IsNaN});732auto *AnyExitTaken =733Builder.createNaryOp(Instruction::Or, {AnyNaN, IsLatchExitTaken});734Builder.createNaryOp(VPInstruction::BranchOnCond, AnyExitTaken);735LatchExitingBranch->eraseFromParent();736737// If we exit early due to NaNs, compute the final reduction result based on738// the reduction phi at the beginning of the last vector iteration.739auto *RdxResult = find_singleton<VPSingleDefRecipe>(740RedPhiR->users(), [](VPUser *U, bool) -> VPSingleDefRecipe * {741auto *VPI = dyn_cast<VPInstruction>(U);742if (VPI && VPI->getOpcode() == VPInstruction::ComputeReductionResult)743return VPI;744return nullptr;745});746747auto *MiddleVPBB = Plan.getMiddleBlock();748Builder.setInsertPoint(MiddleVPBB, MiddleVPBB->begin());749auto *NewSel =750Builder.createSelect(AnyNaN, RedPhiR, RdxResult->getOperand(1));751RdxResult->setOperand(1, NewSel);752753auto *ScalarPH = Plan.getScalarPreheader();754// Update resume phis for inductions in the scalar preheader. If AnyNaN is755// true, the resume from the start of the last vector iteration via the756// canonical IV, otherwise from the original value.757for (auto &R : ScalarPH->phis()) {758auto *ResumeR = cast<VPPhi>(&R);759VPValue *VecV = ResumeR->getOperand(0);760if (VecV == RdxResult)761continue;762if (auto *DerivedIV = dyn_cast<VPDerivedIVRecipe>(VecV)) {763if (DerivedIV->getNumUsers() == 1 &&764DerivedIV->getOperand(1) == &Plan.getVectorTripCount()) {765auto *NewSel = Builder.createSelect(AnyNaN, Plan.getCanonicalIV(),766&Plan.getVectorTripCount());767DerivedIV->moveAfter(&*Builder.getInsertPoint());768DerivedIV->setOperand(1, NewSel);769continue;770}771}772// Bail out and abandon the current, partially modified, VPlan if we773// encounter resume phi that cannot be updated yet.774if (VecV != &Plan.getVectorTripCount()) {775LLVM_DEBUG(dbgs() << "Found resume phi we cannot update for VPlan with "776"FMaxNum/FMinNum reduction.\n");777return false;778}779auto *NewSel = Builder.createSelect(AnyNaN, Plan.getCanonicalIV(), VecV);780ResumeR->setOperand(0, NewSel);781}782783auto *MiddleTerm = MiddleVPBB->getTerminator();784Builder.setInsertPoint(MiddleTerm);785VPValue *MiddleCond = MiddleTerm->getOperand(0);786VPValue *NewCond = Builder.createAnd(MiddleCond, Builder.createNot(AnyNaN));787MiddleTerm->setOperand(0, NewCond);788return true;789}790791792