Bug type: crash
Component: SLPVectorizer
Bug location: llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp: tryToReduce
Issue title: clang crashes on valid code at -O{s,2,3} on x86_64-linux-gnu: Assertion `TE->isSame(VL) && "Expected same scalars."' failed
Labels: llvm:SLPVectorizer
crash
generated by fuzzer
Reported by: zhendongsu

It appears to be a recent regression as it doesn't reproduce with 19.1.0 and earlier.

Compiler Explorer: https://godbolt.org/z/6ca9841xE

```
[512] % clangtk -v
clang version 21.0.0git (https://github.com/llvm/llvm-project.git 7612dcc6e8d8e7f19b364084effbb01946294720)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /local/suz-local/software/local/clang-trunk/bin
Build config: +assertions
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/10
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/11
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/9
Selected GCC installation: /usr/lib/gcc/x86_64-linux-gnu/11
Candidate multilib: .;@m64
Selected multilib: .;@m64
[513] % 
[513] % clangtk -O3 small.c
clang-21: /local/suz-local/software/clangbuild/llvm-project/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp:3011: llvm::slpvectorizer::BoUpSLP::TreeEntry* llvm::slpvectorizer::BoUpSLP::getVectorizedOperand(llvm::slpvectorizer::BoUpSLP::TreeEntry*, unsigned int): Assertion `TE->isSame(VL) && "Expected same scalars."' failed.
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace, preprocessed source, and associated run script.
Stack dump:
0.	Program arguments: /local/suz-local/software/local/clang-trunk/bin/clang-21 -cc1 -triple x86_64-unknown-linux-gnu -emit-obj -dumpdir a- -disable-free -clear-ast-before-backend -main-file-name small.c -mrelocation-model pic -pic-level 2 -pic-is-pie -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/local/suz-local/software/emitesting/bugs/20250201-clangtk-m64-O3-build-174536/delta -fcoverage-compilation-dir=/local/suz-local/software/emitesting/bugs/20250201-clangtk-m64-O3-build-174536/delta -resource-dir /local/suz-local/software/local/clang-trunk/lib/clang/21 -I /usr/local/include -I /local/suz-local/software/local/include -internal-isystem /local/suz-local/software/local/clang-trunk/lib/clang/21/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O3 -ferror-limit 19 -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fcolor-diagnostics -vectorize-loops -vectorize-slp -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/small-b035e7.o -x c small.c
1.	<eof> parser at end of file
2.	Optimizer
3.	Running pass "function<eager-inv>(float2int,lower-constant-intrinsics,chr,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<O3>,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 "small.c"
4.	Running pass "slp-vectorizer" on function "main"
 #0 0x00005596296c84af llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x479d4af)
 #1 0x00005596296c5c84 SignalHandler(int) Signals.cpp:0:0
 #2 0x00007fe817057420 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x14420)
 #3 0x00007fe816a8e00b raise /build/glibc-LcI20x/glibc-2.31/signal/../sysdeps/unix/sysv/linux/raise.c:51:1
 #4 0x00007fe816a6d859 abort /build/glibc-LcI20x/glibc-2.31/stdlib/abort.c:81:7
 #5 0x00007fe816a6d729 get_sysdep_segment_value /build/glibc-LcI20x/glibc-2.31/intl/loadmsgcat.c:509:8
 #6 0x00007fe816a6d729 _nl_load_domain /build/glibc-LcI20x/glibc-2.31/intl/loadmsgcat.c:970:34
 #7 0x00007fe816a7efd6 (/lib/x86_64-linux-gnu/libc.so.6+0x33fd6)
 #8 0x000055962b1df5c7 llvm::slpvectorizer::BoUpSLP::getSpillCost() (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x62b45c7)
 #9 0x000055962b243030 llvm::slpvectorizer::BoUpSLP::getTreeCost(llvm::ArrayRef<llvm::Value*>) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x6318030)
#10 0x000055962b247f34 (anonymous namespace)::HorizontalReduction::tryToReduce(llvm::slpvectorizer::BoUpSLP&, llvm::DataLayout const&, llvm::TargetTransformInfo*, llvm::TargetLibraryInfo const&, llvm::AssumptionCache*) SLPVectorizer.cpp:0:0
#11 0x000055962b24a205 llvm::SLPVectorizerPass::vectorizeHorReduction(llvm::PHINode*, llvm::Instruction*, llvm::BasicBlock*, llvm::slpvectorizer::BoUpSLP&, llvm::SmallVectorImpl<llvm::WeakTrackingVH>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x631f205)
#12 0x000055962b24ee25 bool llvm::SLPVectorizerPass::vectorizeCmpInsts<std::reverse_iterator<llvm::CmpInst* const*>>(llvm::iterator_range<std::reverse_iterator<llvm::CmpInst* const*>>, llvm::BasicBlock*, llvm::slpvectorizer::BoUpSLP&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x6323e25)
#13 0x000055962b24fedb llvm::SLPVectorizerPass::vectorizeChainsInBlock(llvm::BasicBlock*, llvm::slpvectorizer::BoUpSLP&)::'lambda3'(bool)::operator()(bool) const SLPVectorizer.cpp:0:0
#14 0x000055962b253720 llvm::SLPVectorizerPass::vectorizeChainsInBlock(llvm::BasicBlock*, llvm::slpvectorizer::BoUpSLP&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x6328720)
#15 0x000055962b259f46 llvm::SLPVectorizerPass::runImpl(llvm::Function&, llvm::ScalarEvolution*, llvm::TargetTransformInfo*, llvm::TargetLibraryInfo*, llvm::AAResults*, llvm::LoopInfo*, llvm::DominatorTree*, llvm::AssumptionCache*, llvm::DemandedBits*, llvm::OptimizationRemarkEmitter*) (.part.0) SLPVectorizer.cpp:0:0
#16 0x000055962b25aaa3 llvm::SLPVectorizerPass::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x632faa3)
#17 0x000055962ac7c7e6 llvm::detail::PassModel<llvm::Function, llvm::SLPVectorizerPass, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x5d517e6)
#18 0x000055962903ed49 llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x4113d49)
#19 0x000055962693a376 llvm::detail::PassModel<llvm::Function, llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x1a0f376)
#20 0x000055962903d5b2 llvm::ModuleToFunctionPassAdaptor::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x41125b2)
#21 0x0000559626938aa6 llvm::detail::PassModel<llvm::Module, llvm::ModuleToFunctionPassAdaptor, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x1a0daa6)
#22 0x000055962903cfd1 llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x4111fd1)
#23 0x0000559629991596 (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
#24 0x0000559629995253 clang::emitBackendOutput(clang::CompilerInstance&, clang::CodeGenOptions&, 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*) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x4a6a253)
#25 0x000055962a09f2ce clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x51742ce)
#26 0x000055962ba0f29c clang::ParseAST(clang::Sema&, bool, bool) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x6ae429c)
#27 0x000055962a09f708 clang::CodeGenAction::ExecuteAction() (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x5174708)
#28 0x000055962a3719d9 clang::FrontendAction::Execute() (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x54469d9)
#29 0x000055962a2f25be clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x53c75be)
#30 0x000055962a466746 clang::ExecuteCompilerInvocation(clang::CompilerInstance*) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x553b746)
#31 0x00005596264d4a87 cc1_main(llvm::ArrayRef<char const*>, char const*, void*) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x15a9a87)
#32 0x00005596264cc33a ExecuteCC1Tool(llvm::SmallVectorImpl<char const*>&, llvm::ToolContext const&) driver.cpp:0:0
#33 0x00005596264d0471 clang_main(int, char**, llvm::ToolContext const&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x15a5471)
#34 0x00005596263bb29b main (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x149029b)
#35 0x00007fe816a6f083 __libc_start_main /build/glibc-LcI20x/glibc-2.31/csu/../csu/libc-start.c:342:3
#36 0x00005596264cbdce _start (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x15a0dce)
clangtk: error: unable to execute command: Aborted
clangtk: error: clang frontend command failed due to signal (use -v to see invocation)
clang version 21.0.0git (https://github.com/llvm/llvm-project.git 7612dcc6e8d8e7f19b364084effbb01946294720)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /local/suz-local/software/local/clang-trunk/bin
Build config: +assertions
clangtk: note: diagnostic msg: 
********************

PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
Preprocessed source(s) and associated run script(s) are located at:
clangtk: note: diagnostic msg: /tmp/small-401f68.c
clangtk: note: diagnostic msg: /tmp/small-401f68.sh
clangtk: note: diagnostic msg: 

********************
[514] % 
[514] % cat small.c
int a, b, c, d, e;
volatile int f;
int main() {
  int h = 0, j, k, l;
  if (d) {
    h = c;
    if (f)
      goto i;
    if (f)
      goto i;
  }
  l = j = k = d;
  if (!b)
  i:
    (l | (h | j) | k) && f;
  if (a != e)
    goto i;
  return 0;
}
```




Comments: author: dtcxzyw
body: Reduced reproducer: https://godbolt.org/z/TWadzP8Gc


Fix patch:
commit 0c70a26f46e4efd5a29eb281ff99d2cf7f04c6f6
Author: Alexey Bataev <a.bataev@outlook.com>
Date:   Mon Feb 3 04:37:49 2025 -0800

    [SLP]Clear root node reordering only if the root node is not re-used in graph
    
    The reordering of the root node can be safely cleared only if the root
    node is not reused, otherwise the graph might be broken
    
    Fixes #125357

diff --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
index 4f83b9cfa18d..539c9227af7e 100644
--- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -20147,7 +20147,7 @@ public:
         }
         V.reorderTopToBottom();
         // No need to reorder the root node at all.
-        V.reorderBottomToTop(/*IgnoreReorder=*/true);
+        V.reorderBottomToTop(!V.doesRootHaveInTreeUses());
         // Keep extracted other reduction values, if they are used in the
         // vectorization trees.
         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(


Regression tests:
file: llvm/test/Transforms/SLPVectorizer/X86/root-node-reordered-reused.ll
commands: opt -S --passes=slp-vectorizer -mtriple=x86_64-unknown-linux-gnu < %s
tests: test_name: <module>
test_body: ; ModuleID = 'test.ll'
source_filename = "test.c"
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 i32 @main(i32 %0) {
entry:
  %tobool.not = icmp eq i32 %0, 0
  br i1 %tobool.not, label %if.end6, label %if.then

if.then:                                          ; preds = %entry
  br i1 %tobool.not, label %if.end, label %i

if.end:                                           ; preds = %if.then
  br i1 %tobool.not, label %if.end6, label %i

if.end6:                                          ; preds = %if.end, %entry
  %h.0 = phi i32 [ %0, %if.end ], [ 0, %entry ]
  br i1 %tobool.not, label %i, label %if.end13

i:                                                ; preds = %if.end13, %if.end6, %if.end, %if.then
  %h.1 = phi i32 [ %0, %if.then ], [ %h.2, %if.end13 ], [ %0, %if.end ], [ %h.0, %if.end6 ]
  %j.0 = phi i32 [ undef, %if.then ], [ %j.1, %if.end13 ], [ undef, %if.end ], [ %0, %if.end6 ]
  %k.0 = phi i32 [ undef, %if.then ], [ %k.1, %if.end13 ], [ undef, %if.end ], [ %0, %if.end6 ]
  %l.0 = phi i32 [ undef, %if.then ], [ %l.1, %if.end13 ], [ undef, %if.end ], [ %0, %if.end6 ]
  %or = or i32 %j.0, %h.1
  %or9 = or i32 %or, %k.0
  %or10 = or i32 %or9, %l.0
  %tobool11.not = icmp eq i32 %or10, 0
  br i1 %tobool11.not, label %if.end13, label %land.rhs

land.rhs:                                         ; preds = %i
  br label %if.end13

if.end13:                                         ; preds = %i, %land.rhs, %if.end6
  %h.2 = phi i32 [ %h.0, %if.end6 ], [ %h.1, %land.rhs ], [ %h.1, %i ]
  %j.1 = phi i32 [ %0, %if.end6 ], [ %j.0, %land.rhs ], [ %j.0, %i ]
  %k.1 = phi i32 [ %0, %if.end6 ], [ %k.0, %land.rhs ], [ %k.0, %i ]
  %l.1 = phi i32 [ %0, %if.end6 ], [ %l.0, %land.rhs ], [ %l.0, %i ]
  br i1 true, label %if.end15, label %i

if.end15:                                         ; preds = %if.end13
  ret i32 0

; uselistorder directives
  uselistorder i32 %k.0, { 1, 2, 0 }
  uselistorder i32 %l.0, { 1, 2, 0 }
}