[llvm] [VPlan] Explicitly unroll replicate-regions without live-outs by VF. (PR #170212)

via llvm-commits llvm-commits at lists.llvm.org
Wed Mar 25 16:48:17 PDT 2026


================
@@ -616,44 +652,169 @@ cloneForLane(VPlan &Plan, VPBuilder &Builder, Type *IdxTy,
     if (auto *Steps = dyn_cast<VPScalarIVStepsRecipe>(New)) {
       // Skip lane 0: an absent start index is implicitly zero.
       unsigned KnownLane = Lane.getKnownLane();
-      if (KnownLane != 0) {
-        VPTypeAnalysis TypeInfo(Plan);
-        Type *BaseIVTy = TypeInfo.inferScalarType(DefR->getOperand(0));
-
-        VPValue *StartIndex = Steps->getStartIndex();
-        VPValue *LaneOffset;
-        unsigned AddOp;
-        VPIRFlags Flags;
-        if (BaseIVTy->isFloatingPointTy()) {
-          int SignedLane = static_cast<int>(KnownLane);
-          if (!StartIndex && Steps->getInductionOpcode() == Instruction::FSub)
-            SignedLane = -SignedLane;
-          LaneOffset =
-              Plan.getOrAddLiveIn(ConstantFP::get(BaseIVTy, SignedLane));
-          AddOp = Steps->getInductionOpcode();
-          Flags = VPIRFlags(FastMathFlags());
-        } else {
-          unsigned BaseIVBits = BaseIVTy->getScalarSizeInBits();
-          LaneOffset = Plan.getConstantInt(APInt(BaseIVBits, KnownLane,
-                                                 /*isSigned*/ false,
-                                                 /*implicitTrunc*/ true));
-          AddOp = Instruction::Add;
-          Flags = VPIRFlags(VPIRFlags::WrapFlagsTy(false, false));
-        }
-
-        if (StartIndex) {
-          VPBuilder LaneBuilder(DefR);
-          LaneOffset =
-              LaneBuilder.createNaryOp(AddOp, {StartIndex, LaneOffset}, Flags);
-        }
-        Steps->setStartIndex(LaneOffset);
-      }
+      if (KnownLane != 0)
+        addLaneToStartIndex(Steps, KnownLane, Plan, DefR);
     }
   }
   New->insertBefore(DefR);
   return New;
 }
 
+/// Convert recipes in region blocks to operate on a single lane 0.
+/// VPReplicateRecipes are converted to single-scalar ones, branch-on-mask is
+/// converted into BranchOnCond and extracts are created as needed.
+static void convertRecipesInRegionBlocksToSingleScalar(VPlan &Plan, Type *IdxTy,
+                                                       VPBlockBase *Entry) {
+  VPValue *Idx0 = Plan.getZero(IdxTy);
+  for (VPBlockBase *VPB : vp_depth_first_shallow(Entry)) {
+    for (VPRecipeBase &OldR : make_early_inc_range(cast<VPBasicBlock>(*VPB))) {
+      VPBuilder Builder(&OldR);
+      assert(!match(&OldR, m_ExtractElement(m_VPValue(), m_VPValue())) &&
+             "must not contain extracts before conversion");
+      for (const auto &[I, Op] : enumerate(OldR.operands())) {
+        // Skip operands that don't need extraction: values defined in the
+        // same block (already scalar), or values that are already single
+        // scalars.
+        auto *DefR = Op->getDefiningRecipe();
+        if ((DefR && DefR->getParent() == VPB) || vputils::isSingleScalar(Op))
+          continue;
+
+        // Extract lane zero from values defined outside the region.
+        VPValue *Extract = Builder.createNaryOp(Instruction::ExtractElement,
+                                                {Op, Idx0}, OldR.getDebugLoc());
+        OldR.setOperand(I, Extract);
+      }
+
+      if (auto *RepR = dyn_cast<VPReplicateRecipe>(&OldR)) {
+        auto *NewR =
+            new VPReplicateRecipe(RepR->getUnderlyingInstr(), RepR->operands(),
+                                  /* IsSingleScalar=*/true, /*Mask=*/nullptr,
+                                  *RepR, *RepR, RepR->getDebugLoc());
+        NewR->insertBefore(RepR);
+        RepR->replaceAllUsesWith(NewR);
+        RepR->eraseFromParent();
+      } else if (auto *BranchOnMask = dyn_cast<VPBranchOnMaskRecipe>(&OldR)) {
+        Builder.createNaryOp(VPInstruction::BranchOnCond,
+                             {BranchOnMask->getOperand(0)},
+                             BranchOnMask->getDebugLoc());
+        BranchOnMask->eraseFromParent();
+      } else {
+        assert((isa<VPScalarIVStepsRecipe>(OldR) ||
+                (isa<VPInstruction>(OldR) &&
+                 vputils::isSingleScalar(OldR.getVPSingleValue()))) &&
+               "unexpected unhandled recipe");
+      }
+    }
+  }
+}
+
+/// Update recipes in the cloned blocks rooted at \p NewEntry to match \p Lane,
+/// using the original blocks rooted at \p OldEntry as reference.
+static void processLaneForReplicateRegion(VPlan &Plan, Type *IdxTy,
+                                          unsigned Lane, VPBasicBlock *OldEntry,
+                                          VPBasicBlock *NewEntry) {
+  DenseMap<VPValue *, VPValue *> Old2NewVPValues;
+  VPValue *IdxLane = Plan.getConstantInt(IdxTy, Lane);
+  for (const auto &[OldBB, NewBB] :
+       zip_equal(vp_depth_first_shallow(OldEntry),
+                 vp_depth_first_shallow(NewEntry))) {
+    for (auto &&[OldR, NewR] :
+         zip_equal(*cast<VPBasicBlock>(OldBB), *cast<VPBasicBlock>(NewBB))) {
+      for (const auto &[OldV, NewV] :
+           zip_equal(OldR.definedValues(), NewR.definedValues()))
+        Old2NewVPValues[OldV] = NewV;
+
+      if (auto *Steps = dyn_cast<VPScalarIVStepsRecipe>(&NewR))
+        addLaneToStartIndex(Steps, Lane, Plan, Steps);
+      else if (match(&NewR, m_ExtractElement(m_VPValue(), m_ZeroInt())))
+        NewR.setOperand(1, IdxLane);
+
+      // Remap operands to use lane-specific values.
+      for (const auto &[I, OldOp] : enumerate(NewR.operands())) {
+        // Use cloned value if operand was defined in the region.
+        if (auto *NewOp = Old2NewVPValues.lookup(OldOp))
+          NewR.setOperand(I, NewOp);
+      }
+    }
+  }
+}
+
+/// Dissolve a single replicate region by replicating its blocks for each lane
+/// of \p VF. The region is disconnected, its blocks are reparented, cloned for
+/// each lane, and reconnected in sequence.
+static void dissolveReplicateRegion(VPRegionBlock *Region, ElementCount VF,
+                                    VPlan &Plan, Type *IdxTy) {
+  VPBlockBase *FirstLaneRegionEntry = Region->getEntry();
+  VPBlockBase *FirstLaneRegionExiting = Region->getExiting();
+
+  // Disconnect and dissolve the region.
+  VPBlockBase *Predecessor = Region->getSinglePredecessor();
+  assert(Predecessor && "Replicate region must have a single predecessor");
+  VPBlockBase *Successor = Region->getSingleSuccessor();
+  assert(Successor && "Replicate region must have a single successor");
+  VPBlockUtils::disconnectBlocks(Predecessor, Region);
+  VPBlockUtils::disconnectBlocks(Region, Successor);
+
+  VPRegionBlock *ParentRegion = Region->getParent();
+  for (VPBlockBase *VPB : vp_depth_first_shallow(FirstLaneRegionEntry))
+    VPB->setParent(ParentRegion);
+
+  // Process the original blocks for lane 0: converting their recipes to
+  // single-scalar.
+  convertRecipesInRegionBlocksToSingleScalar(Plan, IdxTy, FirstLaneRegionEntry);
+
+  // Clone converted blocks for remaining lanes and process each in reverse
+  // order, connecting each lane's Exiting block to the subsequent lane's entry.
+  VPBlockBase *NextLaneRegionEntry = Successor;
----------------
ayalz wrote:

```suggestion
  VPBlockBase *NextLaneEntry = Successor;
```

https://github.com/llvm/llvm-project/pull/170212


More information about the llvm-commits mailing list