Bug type: crash
Component: LoopVectorize
Bug location: llvm/lib/Transforms/Vectorize/LoopVectorize.cpp: InnerLoopVectorizer::fixVectorizedLoop
Issue title: [clang] Crash at -O2: Assertion `isAvailableAtLoopEntry(LHS, L) && "LHS is not available at Loop Entry"' failed.
Labels: release:backport
vectorizers
crash
regression:18
Reported by: cardigan1008

This code crashes at `-O2`: 
```c
int a, e;
int *b;
short c[];
short d;
void f() {
  int g;
  for (;;)
    for (; a - 3 + g < 6; g = g + 1)
      c[g] = d;
}
void h();
void i() {
  h();
  f();
}
void h() {
  e = 0;
  for (; e <= 50; ++e) {
    int *j = &a;
    *j = *b + e;
  }
}
```

Compiler Explorer: https://godbolt.org/z/jfo65eK9x

Crash:
```console
clang: /root/llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp:11744: bool llvm::ScalarEvolution::isLoopEntryGuardedByCond(const llvm::Loop*, llvm::CmpInst::Predicate, const llvm::SCEV*, const llvm::SCEV*): Assertion `isAvailableAtLoopEntry(LHS, L) && "LHS is not available at Loop Entry"' failed.
```
Backtrace:
```console
Stack dump:
0.	Program arguments: /opt/compiler-explorer/clang-assertions-trunk/bin/clang -gdwarf-4 -g -o /app/output.s -mllvm --x86-asm-syntax=intel -fno-verbose-asm -S --gcc-toolchain=/opt/compiler-explorer/gcc-snapshot -fcolor-diagnostics -fno-crash-diagnostics -O2 -Wall -Wextra -fno-strict-aliasing <source>
1.	<eof> parser at end of file
2.	Optimizer
3.	Running pass "function<eager-inv>(float2int,lower-constant-intrinsics,loop(loop-rotate<header-duplication;no-prepare-for-lto>,loop-deletion),loop-distribute,inject-tli-mappings,loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>,infer-alignment,loop-load-elim,instcombine<max-iterations=1;no-verify-fixpoint>,simplifycfg<bonus-inst-threshold=1;forward-switch-cond;switch-range-to-icmp;switch-to-lookup;no-keep-loops;hoist-common-insts;no-hoist-loads-stores-with-cond-faulting;sink-common-insts;speculate-blocks;simplify-cond-branch;no-speculate-unpredictables>,slp-vectorizer,vector-combine,instcombine<max-iterations=1;no-verify-fixpoint>,loop-unroll<O2>,transform-warning,sroa<preserve-cfg>,infer-alignment,instcombine<max-iterations=1;no-verify-fixpoint>,loop-mssa(licm<allowspeculation>),alignment-from-assumptions,loop-sink,instsimplify,div-rem-pairs,tailcallelim,simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;hoist-loads-stores-with-cond-faulting;no-sink-common-insts;speculate-blocks;simplify-cond-branch;speculate-unpredictables>)" on module "<source>"
4.	Running pass "loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>" on function "i"
 #0 0x0000000003c19758 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x3c19758)
 #1 0x0000000003c17464 llvm::sys::CleanupOnSignal(unsigned long) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x3c17464)
 #2 0x0000000003b649c8 CrashRecoverySignalHandler(int) CrashRecoveryContext.cpp:0:0
 #3 0x000079aa17242520 (/lib/x86_64-linux-gnu/libc.so.6+0x42520)
 #4 0x000079aa172969fc pthread_kill (/lib/x86_64-linux-gnu/libc.so.6+0x969fc)
 #5 0x000079aa17242476 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x42476)
 #6 0x000079aa172287f3 abort (/lib/x86_64-linux-gnu/libc.so.6+0x287f3)
 #7 0x000079aa1722871b (/lib/x86_64-linux-gnu/libc.so.6+0x2871b)
 #8 0x000079aa17239e96 (/lib/x86_64-linux-gnu/libc.so.6+0x39e96)
 #9 0x0000000002c90a7b llvm::ScalarEvolution::isLoopEntryGuardedByCond(llvm::Loop const*, llvm::CmpInst::Predicate, llvm::SCEV const*, llvm::SCEV const*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x2c90a7b)
#10 0x0000000002ca6d97 llvm::ScalarEvolution::getTripCountFromExitCount(llvm::SCEV const*, llvm::Type*, llvm::Loop const*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x2ca6d97)
#11 0x00000000058449e4 llvm::VPlan::createInitialVPlan(llvm::Type*, llvm::PredicatedScalarEvolution&, bool, bool, llvm::Loop*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x58449e4)
#12 0x000000000572a8ce llvm::LoopVectorizationPlanner::tryToBuildVPlanWithVPRecipes(llvm::VFRange&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x572a8ce)
#13 0x000000000572dd5a llvm::LoopVectorizationPlanner::buildVPlansWithVPRecipes(llvm::ElementCount, llvm::ElementCount) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x572dd5a)
#14 0x000000000572e24f llvm::LoopVectorizationPlanner::plan(llvm::ElementCount, unsigned int) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x572e24f)
#15 0x000000000573044f llvm::LoopVectorizePass::processLoop(llvm::Loop*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x573044f)
#16 0x0000000005732a89 llvm::LoopVectorizePass::runImpl(llvm::Function&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x5732a89)
#17 0x00000000057330c3 llvm::LoopVectorizePass::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x57330c3)
#18 0x0000000005283abe llvm::detail::PassModel<llvm::Function, llvm::LoopVectorizePass, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x5283abe)
#19 0x00000000035c8550 llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x35c8550)
#20 0x00000000010fa0ee llvm::detail::PassModel<llvm::Function, llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x10fa0ee)
#21 0x00000000035c6e6b llvm::ModuleToFunctionPassAdaptor::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x35c6e6b)
#22 0x00000000010f977e llvm::detail::PassModel<llvm::Module, llvm::ModuleToFunctionPassAdaptor, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x10f977e)
#23 0x00000000035c6870 llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x35c6870)
#24 0x0000000003eca382 (anonymous namespace)::EmitAssemblyHelper::RunOptimizationPipeline(clang::BackendAction, std::unique_ptr<llvm::raw_pwrite_stream, std::default_delete<llvm::raw_pwrite_stream>>&, std::unique_ptr<llvm::ToolOutputFile, std::default_delete<llvm::ToolOutputFile>>&, clang::BackendConsumer*) BackendUtil.cpp:0:0
#25 0x0000000003ecdbfd clang::EmitBackendOutput(clang::DiagnosticsEngine&, clang::HeaderSearchOptions const&, clang::CodeGenOptions const&, clang::TargetOptions const&, clang::LangOptions const&, llvm::StringRef, llvm::Module*, clang::BackendAction, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>, std::unique_ptr<llvm::raw_pwrite_stream, std::default_delete<llvm::raw_pwrite_stream>>, clang::BackendConsumer*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x3ecdbfd)
#26 0x000000000459e07e clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x459e07e)
#27 0x000000000655704c clang::ParseAST(clang::Sema&, bool, bool) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x655704c)
#28 0x000000000459e458 clang::CodeGenAction::ExecuteAction() (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x459e458)
#29 0x0000000004856fc9 clang::FrontendAction::Execute() (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x4856fc9)
#30 0x00000000047d989e clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x47d989e)
#31 0x000000000494267e clang::ExecuteCompilerInvocation(clang::CompilerInstance*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x494267e)
#32 0x0000000000cb92df cc1_main(llvm::ArrayRef<char const*>, char const*, void*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0xcb92df)
#33 0x0000000000cb0d7a ExecuteCC1Tool(llvm::SmallVectorImpl<char const*>&, llvm::ToolContext const&) driver.cpp:0:0
#34 0x00000000045e2229 void llvm::function_ref<void ()>::callback_fn<clang::driver::CC1Command::Execute(llvm::ArrayRef<std::optional<llvm::StringRef>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>*, bool*) const::'lambda'()>(long) Job.cpp:0:0
#35 0x0000000003b64e74 llvm::CrashRecoveryContext::RunSafely(llvm::function_ref<void ()>) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x3b64e74)
#36 0x00000000045e281f clang::driver::CC1Command::Execute(llvm::ArrayRef<std::optional<llvm::StringRef>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>*, bool*) const (.part.0) Job.cpp:0:0
#37 0x00000000045a7f3d clang::driver::Compilation::ExecuteCommand(clang::driver::Command const&, clang::driver::Command const*&, bool) const (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x45a7f3d)
#38 0x00000000045a902d clang::driver::Compilation::ExecuteJobs(clang::driver::JobList const&, llvm::SmallVectorImpl<std::pair<int, clang::driver::Command const*>>&, bool) const (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x45a902d)
#39 0x00000000045b0565 clang::driver::Driver::ExecuteCompilation(clang::driver::Compilation&, llvm::SmallVectorImpl<std::pair<int, clang::driver::Command const*>>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x45b0565)
#40 0x0000000000cb6123 clang_main(int, char**, llvm::ToolContext const&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0xcb6123)
#41 0x0000000000b84564 main (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0xb84564)
#42 0x000079aa17229d90 (/lib/x86_64-linux-gnu/libc.so.6+0x29d90)
#43 0x000079aa17229e40 __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x29e40)
#44 0x0000000000cb0825 _start (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0xcb0825)
```


Comments: author: shafik
body: Looks like a clang-18 regression: https://godbolt.org/z/K7MMKxjzb
author: dtcxzyw
body: Reduced reproducer: https://godbolt.org/z/s4G9Yb1vG
```
; bin/opt -passes="print<scalar-evolution>,loop-vectorize" test.ll -S
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
target triple = "x86_64-unknown-linux-gnu"

define void @i(ptr %p) {
entry:
  br label %for.body.i

for.body.i:                                       ; preds = %for.body.i, %entry
  %0 = phi i32 [ 0, %entry ], [ %inc.i, %for.body.i ]
  %1 = load i32, ptr %p, align 4
  %add.i = add i32 %1, %0
  %inc.i = add i32 %0, 1
  %exitcond.not.i = icmp eq i32 %0, 1
  br i1 %exitcond.not.i, label %for.cond.i.preheader, label %for.body.i

for.cond.i.preheader:                             ; preds = %for.body.i
  br label %for.cond.i

for.cond.i.loopexit:                              ; preds = %for.body.i1
  br label %for.cond.i

for.cond.i:                                       ; preds = %for.cond.i.loopexit, %for.cond.i.preheader
  br label %for.body.i1

for.body.i1:                                      ; preds = %for.body.i1, %for.cond.i
  %indvars.iv.i = phi i64 [ %indvars.iv.next.i, %for.body.i1 ], [ 0, %for.cond.i ]
  %indvars4.i = trunc i64 %indvars.iv.i to i32
  %indvars.iv.next.i = add i64 %indvars.iv.i, 1
  %add.reass.i = add i32 %add.i, %indvars4.i
  %cmp.i = icmp slt i32 %add.reass.i, 0
  br i1 %cmp.i, label %for.body.i1, label %for.cond.i.loopexit
}

```
author: fhahn
body: Thanks, let me take a look

Fix patch:
commit 3706dfef660097f24fb5efbac0d7f14b424492ed
Author: Florian Hahn <flo@fhahn.com>
Date:   Mon Feb 10 16:29:42 2025 +0000

    [LV] Forget LCSSA phi with new pred before other SCEV invalidation. (#119897)
    
    `forgetLcssaPhiWithNewPredecessor` performs additional invalidation if
    there is an existing SCEV for the phi, but earlier
    `forgetBlockAndLoopDispositions` or `forgetLoop` may already invalidate
    the SCEV for the phi.
    
    Change the order to first call `forgetLcssaPhiWithNewPredecessor` to
    ensure it runs before its SCEV gets invalidated too eagerly.
    
    Fixes https://github.com/llvm/llvm-project/issues/119665.
    
    PR: https://github.com/llvm/llvm-project/pull/119897

diff --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
index 610e4904a80a..f2241be60ce0 100644
--- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
@@ -2937,10 +2937,6 @@ void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
   if (EnableVPlanNativePath)
     fixNonInductionPHIs(State);
 
-  // Forget the original basic block.
-  PSE.getSE()->forgetLoop(OrigLoop);
-  PSE.getSE()->forgetBlockAndLoopDispositions();
-
   // After vectorization, the exit blocks of the original loop will have
   // additional predecessors. Invalidate SCEVs for the exit phis in case SE
   // looked through single-entry phis.
@@ -2950,6 +2946,10 @@ void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
     for (PHINode &PN : Exit->phis())
       PSE.getSE()->forgetLcssaPhiWithNewPredecessor(OrigLoop, &PN);
 
+  // Forget the original basic block.
+  PSE.getSE()->forgetLoop(OrigLoop);
+  PSE.getSE()->forgetBlockAndLoopDispositions();
+
   // Don't apply optimizations below when no vector region remains, as they all
   // require a vector loop at the moment.
   if (!State.Plan->getVectorLoopRegion())


Regression tests:
file: llvm/test/Transforms/LoopVectorize/invalidate-scev-at-scope-after-vectorization.ll
commands: opt -passes='print<scalar-evolution>,loop-vectorize' -force-vector-width=4 -scalar-evolution-classify-expressions=false -S %s
tests: test_name: <module>
test_body: 
; Test case for https://github.com/llvm/llvm-project/issues/119665.

; %loop.2's backedge-taken-count depends on %add.1 from %loop.1 via its
; corresponding SCEV at the scope of %loop.2. After vectorizing %loop.1, %add.1
; isn't available at the entry of %loop.2 anymore and %add.1 at %loop.2's scope
; must be invalidated, as well as %loop.2's backedge-taken count.
define void @test_invalidate_scevs_at_scope(ptr %p) {
;
entry:
  br label %loop.1

loop.1:
  %iv.1 = phi i32 [ 0, %entry ], [ %iv.1.next, %loop.1 ]
  %1 = load i32, ptr %p, align 4
  %add.1 = add i32 %1, %iv.1
  %iv.1.next = add i32 %iv.1, 1
  %c.1 = icmp eq i32 %iv.1, 100
  br i1 %c.1, label %exit.1, label %loop.1

exit.1:
  %add.lcssa = phi i32 [ %add.1, %loop.1 ]
  br label %loop.2

loop.2:
  %iv.2 = phi i64 [ 0, %exit.1 ], [ %iv.2.next, %loop.2 ]
  %iv.2.trunc = trunc i64 %iv.2 to i32
  %iv.2.next = add i64 %iv.2, 1
  %gep = getelementptr inbounds i64, ptr %p, i64 %iv.2
  store i64 %iv.2, ptr %gep
  %add.2 = add i32 %add.lcssa, %iv.2.trunc
  %c.2 = icmp slt i32 %add.2, 100
  br i1 %c.2, label %loop.2, label %exit.2

exit.2:
  ret void
}

;.
;.