diff --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp --- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp +++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp @@ -4291,14 +4291,11 @@ // Reductions do not have to start at zero. They can start with // any loop invariant values. - BasicBlock *Latch = OrigLoop->getLoopLatch(); - Value *LoopVal = OrigPhi->getIncomingValueForBlock(Latch); - for (unsigned Part = 0; Part < UF; ++Part) { - Value *VecRdxPhi = State.get(PhiR->getVPValue(), Part); - Value *Val = State.get(State.Plan->getVPValue(LoopVal), Part); - cast(VecRdxPhi) - ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch()); + Value *VecRdxPhi = State.get(PhiR->getVPValue(0), Part); + cast(VecRdxPhi)->addIncoming( + State.get(PhiR->getOperand(1), Part), + LI->getLoopFor(LoopVectorBody)->getLoopLatch()); } // Before each round, move the insertion point right between @@ -8813,6 +8810,18 @@ RecipeBuilder.recordRecipeOf(Entry.first); RecipeBuilder.recordRecipeOf(Entry.second); } + + SmallVector PhisToFix; + BasicBlock *OrigLatch = OrigLoop->getLoopLatch(); + for (PHINode &Phi : OrigLoop->getHeader()->phis()) { + if (!Legal->isReductionVariable(&Phi)) + continue; + PhisToFix.push_back(&Phi); + RecipeBuilder.recordRecipeOf(&Phi); + RecipeBuilder.recordRecipeOf( + cast(Phi.getIncomingValueForBlock(OrigLatch))); + } + for (auto &Reduction : CM.getInLoopReductionChains()) { PHINode *Phi = Reduction.first; RecurKind Kind = Legal->getReductionVars()[Phi].getRecurrenceKind(); @@ -8920,6 +8929,14 @@ } } + for (PHINode *PN : PhisToFix) { + VPWidenPHIRecipe *R = cast(RecipeBuilder.getRecipe(PN)); + VPRecipeBase *IncR = RecipeBuilder.getRecipe( + cast(PN->getIncomingValueForBlock(OrigLatch))); + assert(IncR->getNumDefinedValues() == 1); + R->addOperand(IncR->getVPValue(0)); + } + // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks // may also be empty, such as the last one VPBB, reflecting original // basic-blocks with no recipes. diff --git a/llvm/test/Transforms/LoopVectorize/vplan-printing.ll b/llvm/test/Transforms/LoopVectorize/vplan-printing.ll --- a/llvm/test/Transforms/LoopVectorize/vplan-printing.ll +++ b/llvm/test/Transforms/LoopVectorize/vplan-printing.ll @@ -79,7 +79,7 @@ ; CHECK: VPlan 'Initial VPlan for VF={4},UF>=1' { ; CHECK-NEXT: for.body: ; CHECK-NEXT: WIDEN-INDUCTION %iv = phi %iv.next, 0 -; CHECK-NEXT: WIDEN-PHI %red = phi %red.next, 0.000000e+00 +; CHECK-NEXT: WIDEN-PHI ir<%red> = phi ir<0.000000e+00>, ir<%red.next> ; CHECK-NEXT: CLONE ir<%arrayidx> = getelementptr ir<%y>, ir<%iv> ; CHECK-NEXT: WIDEN ir<%lv> = load ir<%arrayidx> ; CHECK-NEXT: REDUCE ir<%red.next> = ir<%red> + reduce.fadd (ir<%lv>)