diff --git a/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp b/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp --- a/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp +++ b/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp @@ -6677,13 +6677,15 @@ AddRec->getOperand(0)->getType())); const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); SCEVExpander Expander(SE, DL, "lsr_fold_term_cond"); + if (!Expander.isSafeToExpand(TermValueS)) + return false; - // TODO: Right now we limit the phi node to help the folding be of a start - // value of getelementptr. We can extend to any kinds of IV as long as it is - // an affine AddRec. Add a switch to cover more types of instructions here - // and down in the actual transformation. - return Expander.isSafeToExpand(TermValueS) && - isa(PN.getIncomingValueForBlock(LoopPreheader)); + Value *StartValue = PN.getIncomingValueForBlock(LoopPreheader); + // Note: Expanding more types of StartValue requires corresponding change + // for `TypeToExpand` below + if (isa(StartValue) || isa(StartValue)) + return true; + return false; }; PHINode *ToFold = nullptr; @@ -6810,8 +6812,16 @@ SCEVExpanderCleaner ExpCleaner(Expander); // Create new terminating value at loop header - GetElementPtrInst *StartValueGEP = cast(StartValue); - Type *PtrTy = StartValueGEP->getPointerOperand()->getType(); + Type *TypeToExpand = nullptr; + if (isa(StartValue)) { + TypeToExpand = + cast(StartValue)->getPointerOperandType(); + } else if (isa(StartValue)) { + TypeToExpand = StartValue->getType(); + } else { + llvm_unreachable("Unhandled type should be guarded by IsToHelpFold " + "under canFoldTermCondOfLoop"); + } const SCEV *BECount = SE.getBackedgeTakenCount(L); const SCEVAddRecExpr *AddRec = @@ -6831,7 +6841,7 @@ Changed = true; NumTermFold++; - Value *TermValue = Expander.expandCodeFor(TermValueS, PtrTy, + Value *TermValue = Expander.expandCodeFor(TermValueS, TypeToExpand, LoopPreheader->getTerminator()); LLVM_DEBUG(dbgs() << "Start value of new term-cond phi-node:\n"