https://github.com/tatsuhito-fj created https://github.com/llvm/llvm-project/pull/244546
Add a scope option to SimplifyHLFIRIntrinsics and adjust the pipeline to enable SUM expansion at -O0 while keeping other intrinsic expansions conditional on array expression optimization. This makes simple summation the default for SUM expansion across optimization levels. Previously, floating-point SUM used the runtime's Kahan summation at -O0, whereas -O1 and higher generally generated loops with simple sequential addition. This expansion substituted a different algorithm rather than inlining the runtime implementation, causing numerical results to depend on the optimization level. Add -fcompensated-sum to preserve the runtime's compensated algorithm for REAL and COMPLEX SUM. When enabled, exclude SUM from HLFIR intrinsic simplification and prevent SimplifyIntrinsics from replacing real SUM runtime calls with uncompensated reduction loops. Fixes #176282 >From 130736c2945f21bdb278b4914f4daab46846fc9f Mon Sep 17 00:00:00 2001 From: Tatsuhito Abe <[email protected]> Date: Tue, 10 Nov 2026 15:00:28 +0900 Subject: [PATCH] [Flang] Use simple summation by default at all optimization levels Add a scope option to SimplifyHLFIRIntrinsics and adjust the pipeline to enable SUM expansion at -O0 while keeping other intrinsic expansions conditional on array expression optimization. This makes simple summation the default for SUM expansion across optimization levels. Previously, floating-point SUM used the runtime's Kahan summation at -O0, whereas -O1 and higher generally generated loops with simple sequential addition. This expansion substituted a different algorithm rather than inlining the runtime implementation, causing numerical results to depend on the optimization level. Add -fcompensated-sum to preserve the runtime's compensated algorithm for REAL and COMPLEX SUM. When enabled, exclude SUM from HLFIR intrinsic simplification and prevent SimplifyIntrinsics from replacing real SUM runtime calls with uncompensated reduction loops. Fixes #176282 --- clang/include/clang/Options/FlangOptions.td | 3 + clang/lib/Driver/ToolChains/Flang.cpp | 2 + .../include/flang/Frontend/CodeGenOptions.def | 1 + flang/include/flang/Optimizer/HLFIR/Passes.h | 11 +++ flang/include/flang/Optimizer/HLFIR/Passes.td | 25 +++++- .../flang/Optimizer/Transforms/Passes.td | 6 +- flang/include/flang/Tools/CrossToolHelpers.h | 2 + flang/lib/Frontend/CompilerInvocation.cpp | 3 + flang/lib/Frontend/FrontendActions.cpp | 1 + .../Transforms/SimplifyHLFIRIntrinsics.cpp | 88 +++++++++++-------- flang/lib/Optimizer/Passes/Pipelines.cpp | 24 +++-- .../Transforms/SimplifyIntrinsics.cpp | 3 + flang/test/Driver/array-runtime.f90 | 32 +++++-- flang/test/Driver/compensated-sum.f90 | 14 +++ .../test/Driver/mlir-debug-pass-pipeline.f90 | 5 ++ .../HLFIR/simplify-hlfir-intrinsics-scope.fir | 36 ++++++++ .../parallel-private-reduction-worstcase.f90 | 47 ++++++---- flang/test/Integration/compensated-sum.f90 | 60 +++++++++++++ .../simplifyintrinsics-compensated-sum.fir | 39 ++++++++ 19 files changed, 331 insertions(+), 71 deletions(-) create mode 100644 flang/test/Driver/compensated-sum.f90 create mode 100644 flang/test/HLFIR/simplify-hlfir-intrinsics-scope.fir create mode 100644 flang/test/Integration/compensated-sum.f90 create mode 100644 flang/test/Transforms/simplifyintrinsics-compensated-sum.fir diff --git a/clang/include/clang/Options/FlangOptions.td b/clang/include/clang/Options/FlangOptions.td index ad39d052bee6af..e1b8c2c42e6e6a 100644 --- a/clang/include/clang/Options/FlangOptions.td +++ b/clang/include/clang/Options/FlangOptions.td @@ -335,6 +335,9 @@ def fcheck_integer_mod_zero_divisor : Flag<["-"], "fcheck-integer-mod-zero-divisor">, Group<f_Group>, HelpText<"Check for a zero divisor in integer MOD and MODULO">; +def fcompensated_sum : Flag<["-"], "fcompensated-sum">, Group<f_Group>, + HelpText<"Use compensated algorithm for SUM intrinsic for REAL and COMPLEX types">; + defm fp_sum_reassociation : BoolOptionWithoutMarshalling< "f", "fp-sum-reassociation", diff --git a/clang/lib/Driver/ToolChains/Flang.cpp b/clang/lib/Driver/ToolChains/Flang.cpp index 522907b58022fb..ed3cbbfe06abf5 100644 --- a/clang/lib/Driver/ToolChains/Flang.cpp +++ b/clang/lib/Driver/ToolChains/Flang.cpp @@ -391,6 +391,8 @@ void Flang::addCodegenOptions(const ArgList &Args, Args.AddLastArg(CmdArgs, options::OPT_ffp_sum_reassociation, options::OPT_fno_fp_sum_reassociation); + Args.AddLastArg(CmdArgs, options::OPT_fcompensated_sum); + Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names, options::OPT_fno_unique_internal_linkage_names); diff --git a/flang/include/flang/Frontend/CodeGenOptions.def b/flang/include/flang/Frontend/CodeGenOptions.def index 5043003feec1df..423ff7b0eda288 100644 --- a/flang/include/flang/Frontend/CodeGenOptions.def +++ b/flang/include/flang/Frontend/CodeGenOptions.def @@ -65,6 +65,7 @@ CODEGENOPT(DebugInfoForProfiling, 1, 0) ///< Emit extra debug info to make samp CODEGENOPT(PseudoProbeForProfiling, 1, 0) ///< Emit pseudo probes for sample profiling. CODEGENOPT(UniqueInternalLinkageNames, 1, 0) ///< Append MD5 hash to internal linkage symbols. CODEGENOPT(ImplicitDefaultMapperAllocatableMembers, 1, 1) ///< Map allocatable members in generated OpenMP default mappers. +CODEGENOPT(CompensatedSum, 1, 0) ///< Use compensated algorithm for SUM for REAL and COMPLEX. CODEGENOPT(Underscoring, 1, 1) ENUM_CODEGENOPT(FPMaxminBehavior, Fortran::common::FPMaxminBehavior, 2, Fortran::common::FPMaxminBehavior::Legacy) diff --git a/flang/include/flang/Optimizer/HLFIR/Passes.h b/flang/include/flang/Optimizer/HLFIR/Passes.h index d009a31582470a..3d9e4b12e06ff5 100644 --- a/flang/include/flang/Optimizer/HLFIR/Passes.h +++ b/flang/include/flang/Optimizer/HLFIR/Passes.h @@ -21,6 +21,17 @@ #include <memory> namespace hlfir { + /// Specifies the scope to which SimplifyHLFIRIntrinsics applies. + enum class HLFIRIntrinsicSimplificationScope { + /// Apply SimplifyHLFIRIntrinsics to all intrinsics. + All, + /// Apply SimplifyHLFIRIntrinsics only to sum intrinsics. + SumOnly, + /// Apply SimplifyHLFIRIntrinsics to all intrinsics except sum intrinsics. + ExceptSum, + /// Do not apply SimplifyHLFIRIntrinsics to any intrinsics. + None, + }; #define GEN_PASS_DECL #define GEN_PASS_REGISTRATION #include "flang/Optimizer/HLFIR/Passes.h.inc" diff --git a/flang/include/flang/Optimizer/HLFIR/Passes.td b/flang/include/flang/Optimizer/HLFIR/Passes.td index e0221c655834fe..b31f0ca75a6a63 100644 --- a/flang/include/flang/Optimizer/HLFIR/Passes.td +++ b/flang/include/flang/Optimizer/HLFIR/Passes.td @@ -75,7 +75,30 @@ def SimplifyHLFIRIntrinsics : Pass<"simplify-hlfir-intrinsics"> { clEnumValN(Fortran::common::FPMaxminBehavior::Extremum, "extremum", "arith.max/minimumf"), clEnumValN(Fortran::common::FPMaxminBehavior::ExtremeNum, - "extremenum", "arith.max/minnumf"))}]>]; + "extremenum", "arith.max/minnumf"))}]>, + Option<"scope", "scope", + "::hlfir::HLFIRIntrinsicSimplificationScope", + /*default=*/"::hlfir::HLFIRIntrinsicSimplificationScope::" + "All", + "Select which HLFIR intrinsic operations to simplify", + [{::llvm::cl::values( + clEnumValN( + ::hlfir::HLFIRIntrinsicSimplificationScope::All, + "all", + "Simplify all supported HLFIR intrinsic operations"), + clEnumValN( + ::hlfir::HLFIRIntrinsicSimplificationScope::SumOnly, + "only-sum", + "Simplify only hlfir.sum operations"), + clEnumValN( + ::hlfir::HLFIRIntrinsicSimplificationScope::ExceptSum, + "except-sum", + "Simplify all supported HLFIR intrinsic operations " + "except hlfir.sum"), + clEnumValN( + ::hlfir::HLFIRIntrinsicSimplificationScope::None, + "none", + "Do not simplify any HLFIR intrinsic operations"))}]>]; } def ExpressionSimplification : Pass<"hlfir-expression-simplification"> { diff --git a/flang/include/flang/Optimizer/Transforms/Passes.td b/flang/include/flang/Optimizer/Transforms/Passes.td index 34354eb3f6fede..55480d2cc308ae 100644 --- a/flang/include/flang/Optimizer/Transforms/Passes.td +++ b/flang/include/flang/Optimizer/Transforms/Passes.td @@ -298,7 +298,11 @@ def SimplifyIntrinsics : Pass<"simplify-intrinsics", "mlir::ModuleOp"> { let options = [ Option<"enableExperimental", "enable-experimental", "bool", /*default=*/"false", - "Enable experimental code that may not always work correctly"> + "Enable experimental code that may not always work correctly">, + Option<"compensatedSum", "compensated-sum", "bool", + /*default=*/"false", + "Preserve runtime calls that use compensated summation for " + "floating-point SUM"> ]; } diff --git a/flang/include/flang/Tools/CrossToolHelpers.h b/flang/include/flang/Tools/CrossToolHelpers.h index 0b11c6be04946c..4f66cff187c998 100644 --- a/flang/include/flang/Tools/CrossToolHelpers.h +++ b/flang/include/flang/Tools/CrossToolHelpers.h @@ -150,11 +150,13 @@ struct MLIRToLLVMPassPipelineConfig : public FlangEPCallBacks { SplitDwarfFile = opts.SplitDwarfFile; DwarfDebugFlags = opts.DwarfDebugFlags; DebugNameTable = opts.getDebugNameTable(); + CompensatedSum = opts.CompensatedSum; } llvm::OptimizationLevel OptLevel; ///< optimisation level /// Enable HLFIR optimizations; expensive ones still require O3. bool optimizeArrayExpression; + bool CompensatedSum = false; ///< Preserve compensated real/complex SUM. bool StackArrays = false; ///< convert memory allocations to alloca. bool EnableSafeTrampoline{false}; ///< Use runtime trampoline pool (W^X). bool Underscoring = true; ///< add underscores to function names. diff --git a/flang/lib/Frontend/CompilerInvocation.cpp b/flang/lib/Frontend/CompilerInvocation.cpp index efbb938f6b5975..dc4ebdd74cc0ae 100644 --- a/flang/lib/Frontend/CompilerInvocation.cpp +++ b/flang/lib/Frontend/CompilerInvocation.cpp @@ -605,6 +605,9 @@ static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts, << arg->getAsString(args) << arg->getValue(); } } + + if (args.hasArg(clang::options::OPT_fcompensated_sum)) + opts.CompensatedSum = 1; } /// Parses all target input arguments and populates the target diff --git a/flang/lib/Frontend/FrontendActions.cpp b/flang/lib/Frontend/FrontendActions.cpp index d7f6658668a40c..1bf5d4787911ce 100644 --- a/flang/lib/Frontend/FrontendActions.cpp +++ b/flang/lib/Frontend/FrontendActions.cpp @@ -650,6 +650,7 @@ void CodeGenAction::lowerHLFIRToFIR() { if (ci.getInvocation().getLangOpts().OpenMPSimd) enableOpenMP = fir::EnableOpenMP::Simd; MLIRToLLVMPassPipelineConfig config(level); + config.CompensatedSum = opts.CompensatedSum; config.fpMaxminBehavior = ci.getInvocation().getLoweringOpts().getFPMaxminBehavior(); // Give plugins a chance to register passes at the extension points. diff --git a/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp b/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp index 9fbc05dda264a6..34495e836f82f8 100644 --- a/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp +++ b/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp @@ -3442,44 +3442,56 @@ class SimplifyHLFIRIntrinsics mlir::GreedySimplifyRegionLevel::Disabled); mlir::RewritePatternSet patterns(context); - patterns.insert<TransposeAsElementalConversion>(context); - patterns.insert<ReductionConversion<hlfir::SumOp>>(context); - patterns.insert<ReductionConversion<hlfir::ProductOp>>(context); - patterns.insert<ArrayShiftConversion<hlfir::CShiftOp>>(context); - patterns.insert<ArrayShiftConversion<hlfir::EOShiftOp>>(context); - patterns.insert<CmpCharOpConversion>(context); - patterns.insert<IndexOpConversion>(context); - patterns.insert<CharTrimOpConversion>(context); - patterns.insert<MatmulConversion<hlfir::MatmulTransposeOp>>(context); - patterns.insert<ReductionConversion<hlfir::CountOp>>(context); - patterns.insert<ReductionConversion<hlfir::AnyOp>>(context); - patterns.insert<ReductionConversion<hlfir::AllOp>>(context); - patterns.insert<ExtremumReductionConversion<hlfir::MaxlocOp>>( - context, this->fpMaxminBehavior); - patterns.insert<ExtremumReductionConversion<hlfir::MinlocOp>>( - context, this->fpMaxminBehavior); - patterns.insert<ExtremumReductionConversion<hlfir::MaxvalOp>>( - context, this->fpMaxminBehavior); - patterns.insert<ExtremumReductionConversion<hlfir::MinvalOp>>( - context, this->fpMaxminBehavior); - - // If forceMatmulAsElemental is false, then hlfir.matmul inlining - // will introduce hlfir.eval_in_mem operation with new memory side - // effects. This conflicts with CSE and optimized bufferization, e.g.: - // A(1:N,1:N) = A(1:N,1:N) - MATMUL(...) - // If we introduce hlfir.eval_in_mem before CSE, then the current - // MLIR CSE won't be able to optimize the trivial loads of 'N' value - // that happen before and after hlfir.matmul. - // If 'N' loads are not optimized, then the optimized bufferization - // won't be able to prove that the slices of A are identical - // on both sides of the assignment. - // This is actually the CSE problem, but we can work it around - // for the time being. - if (forceMatmulAsElemental || this->allowNewSideEffects) - patterns.insert<MatmulConversion<hlfir::MatmulOp>>(context); - - patterns.insert<DotProductConversion>(context); - patterns.insert<ReshapeAsElementalConversion>(context); + + const bool simplifySum = + this->scope == hlfir::HLFIRIntrinsicSimplificationScope::All || + this->scope == hlfir::HLFIRIntrinsicSimplificationScope::SumOnly; + const bool simplifyOtherIntrinsics = + this->scope == hlfir::HLFIRIntrinsicSimplificationScope::All || + this->scope == hlfir::HLFIRIntrinsicSimplificationScope::ExceptSum; + + if (simplifySum) + patterns.insert<ReductionConversion<hlfir::SumOp>>(context); + + if (simplifyOtherIntrinsics) { + patterns.insert<TransposeAsElementalConversion>(context); + patterns.insert<ReductionConversion<hlfir::ProductOp>>(context); + patterns.insert<ArrayShiftConversion<hlfir::CShiftOp>>(context); + patterns.insert<ArrayShiftConversion<hlfir::EOShiftOp>>(context); + patterns.insert<CmpCharOpConversion>(context); + patterns.insert<IndexOpConversion>(context); + patterns.insert<CharTrimOpConversion>(context); + patterns.insert<MatmulConversion<hlfir::MatmulTransposeOp>>(context); + patterns.insert<ReductionConversion<hlfir::CountOp>>(context); + patterns.insert<ReductionConversion<hlfir::AnyOp>>(context); + patterns.insert<ReductionConversion<hlfir::AllOp>>(context); + patterns.insert<ExtremumReductionConversion<hlfir::MaxlocOp>>( + context, this->fpMaxminBehavior); + patterns.insert<ExtremumReductionConversion<hlfir::MinlocOp>>( + context, this->fpMaxminBehavior); + patterns.insert<ExtremumReductionConversion<hlfir::MaxvalOp>>( + context, this->fpMaxminBehavior); + patterns.insert<ExtremumReductionConversion<hlfir::MinvalOp>>( + context, this->fpMaxminBehavior); + + // If forceMatmulAsElemental is false, then hlfir.matmul inlining + // will introduce hlfir.eval_in_mem operation with new memory side + // effects. This conflicts with CSE and optimized bufferization, e.g.: + // A(1:N,1:N) = A(1:N,1:N) - MATMUL(...) + // If we introduce hlfir.eval_in_mem before CSE, then the current + // MLIR CSE won't be able to optimize the trivial loads of 'N' value + // that happen before and after hlfir.matmul. + // If 'N' loads are not optimized, then the optimized bufferization + // won't be able to prove that the slices of A are identical + // on both sides of the assignment. + // This is actually the CSE problem, but we can work it around + // for the time being. + if (forceMatmulAsElemental || this->allowNewSideEffects) + patterns.insert<MatmulConversion<hlfir::MatmulOp>>(context); + + patterns.insert<DotProductConversion>(context); + patterns.insert<ReshapeAsElementalConversion>(context); + } if (mlir::failed(mlir::applyPatternsGreedily( getOperation(), std::move(patterns), config))) { diff --git a/flang/lib/Optimizer/Passes/Pipelines.cpp b/flang/lib/Optimizer/Passes/Pipelines.cpp index 55a0b85618a707..919f2f6ff4e5ba 100644 --- a/flang/lib/Optimizer/Passes/Pipelines.cpp +++ b/flang/lib/Optimizer/Passes/Pipelines.cpp @@ -12,6 +12,7 @@ #include "flang/Optimizer/Passes/Pipelines.h" #include "flang/Optimizer/Builder/MIFCommon.h" #include "flang/Optimizer/Dialect/FIROps.h" +#include "flang/Optimizer/HLFIR/Passes.h" #include "flang/Optimizer/OpenACC/Passes.h" #include "mlir/Conversion/Passes.h" #include "mlir/Dialect/LLVMIR/Transforms/Passes.h" @@ -208,7 +209,8 @@ void createDefaultFIRPreCFGOptimizerPassPipeline( pm.addPass(fir::createSimplifyRegionLite()); if (pc.OptLevel != llvm::OptimizationLevel::O0) { // These passes may increase code size. - pm.addPass(fir::createSimplifyIntrinsics()); + pm.addPass(fir::createSimplifyIntrinsics( + {/*enableExperimental=*/false, pc.CompensatedSum})); pm.addPass(fir::createAlgebraicSimplificationPass(config)); if (enableConstantArgumentGlobalisation) pm.addPass(fir::createConstantArgumentGlobalisationOpt()); @@ -318,11 +320,21 @@ void createHLFIRToFIRPassPipeline(mlir::PassManager &pm, addNestedPassToAllTopLevelOperations<PassConstructor>( pm, hlfir::createExpressionSimplification); addCanonicalizerPassWithoutRegionSimplification(pm); - addNestedPassToAllTopLevelOperations(pm, [&]() { - return hlfir::createSimplifyHLFIRIntrinsics( - {/*allowNewSideEffects=*/false, config.fpMaxminBehavior}); - }); } + + using ScopeKind = hlfir::HLFIRIntrinsicSimplificationScope; + ScopeKind scope; + if (config.CompensatedSum) + scope = + config.optimizeArrayExpression ? ScopeKind::ExceptSum : ScopeKind::None; + else + scope = + config.optimizeArrayExpression ? ScopeKind::All : ScopeKind::SumOnly; + + addNestedPassToAllTopLevelOperations(pm, [&]() { + return hlfir::createSimplifyHLFIRIntrinsics( + {/*allowNewSideEffects=*/false, config.fpMaxminBehavior, scope}); + }); addNestedPassToAllTopLevelOperations<PassConstructor>( pm, hlfir::createInlineElementals); addNestedPassToAllTopLevelOperations<PassConstructor>( @@ -334,7 +346,7 @@ void createHLFIRToFIRPassPipeline(mlir::PassManager &pm, // and allow introducing operations with new side effects. addNestedPassToAllTopLevelOperations(pm, [&]() { return hlfir::createSimplifyHLFIRIntrinsics( - {/*allowNewSideEffects=*/true, config.fpMaxminBehavior}); + {/*allowNewSideEffects=*/true, config.fpMaxminBehavior, scope}); }); addNestedPassToAllTopLevelOperations<PassConstructor>( pm, hlfir::createPropagateFortranVariableAttributes); diff --git a/flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp b/flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp index 78cb92ed9a8fa5..5a983942fef227 100644 --- a/flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp +++ b/flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp @@ -1290,6 +1290,9 @@ void SimplifyIntrinsicsPass::runOnOperation() { // int dim, const Descriptor *mask) // if (funcName.starts_with(RTNAME_STRING(Sum))) { + if (this->compensatedSum && call.getNumResults() == 1 && + mlir::isa<mlir::FloatType>(call.getResult(0).getType())) + return; simplifyIntOrFloatReduction(call, kindMap, genRuntimeSumBody); return; } diff --git a/flang/test/Driver/array-runtime.f90 b/flang/test/Driver/array-runtime.f90 index 9acec878fb3da2..e20f201c800f05 100644 --- a/flang/test/Driver/array-runtime.f90 +++ b/flang/test/Driver/array-runtime.f90 @@ -1,5 +1,6 @@ -! Numeric broadcasts to non-allocatable arrays are expanded even at -O0. -! Other array operations retain the optimization-level-dependent default. +! Numeric broadcasts to non-allocatable arrays and SUM reductions are expanded +! even at -O0. Other array operations retain the optimization-level-dependent +! default. ! RUN: %flang_fc1 -emit-fir -O0 %s -o - | FileCheck %s --check-prefixes=ALL,RUNTIME ! RUN: %flang_fc1 -emit-fir -O1 %s -o - | FileCheck %s --check-prefixes=ALL,EXPAND ! RUN: %flang_fc1 -emit-fir -O2 %s -o - | FileCheck %s --check-prefixes=ALL,EXPAND @@ -52,14 +53,27 @@ subroutine array_expression(x, y, z) ! EXPAND-NOT: fir.call @_FortranAAssign ! ALL: return -function reduction(x) - real :: x(:), reduction - reduction = sum(x) +function sum_reduction(x) + real :: x(:), sum_reduction + sum_reduction = sum(x) end function -! ALL-LABEL: func{{(\.func)?}} @_QPreduction( -! RUNTIME: fir.call @_FortranASumReal4 -! EXPAND-NOT: fir.call @_FortranASum +! ALL-LABEL: func{{(\.func)?}} @_QPsum_reduction( +! ALL-NOT: fir.call @_FortranASum +! ALL: fir.do_loop +! ALL: arith.addf +! ALL-NOT: fir.call @_FortranASum +! ALL: return + +function product_reduction(x) + real :: x(:), product_reduction + product_reduction = product(x) +end function + +! ALL-LABEL: func{{(\.func)?}} @_QPproduct_reduction( +! RUNTIME: fir.call @_FortranAProductReal4 +! EXPAND-NOT: fir.call @_FortranAProduct ! EXPAND: fir.do_loop -! EXPAND-NOT: fir.call @_FortranASum +! EXPAND: arith.mulf +! EXPAND-NOT: fir.call @_FortranAProduct ! ALL: return diff --git a/flang/test/Driver/compensated-sum.f90 b/flang/test/Driver/compensated-sum.f90 new file mode 100644 index 00000000000000..f9a56b78821a9a --- /dev/null +++ b/flang/test/Driver/compensated-sum.f90 @@ -0,0 +1,14 @@ +! Test driver handling of -fcompensated-sum. + +! RUN: %flang -fsyntax-only -### %s -o %t 2>&1 \ +! RUN: | FileCheck %s --check-prefix=OMITTED + +! RUN: %flang -fsyntax-only -### %s -o %t 2>&1 \ +! RUN: -fcompensated-sum \ +! RUN: | FileCheck %s --check-prefix=ENABLED + +! OMITTED: "-fc1" +! OMITTED-NOT: "-fcompensated-sum" + +! ENABLED: "-fc1" +! ENABLED: "-fcompensated-sum" diff --git a/flang/test/Driver/mlir-debug-pass-pipeline.f90 b/flang/test/Driver/mlir-debug-pass-pipeline.f90 index 25fdc4ee557809..b395d4974e74b6 100644 --- a/flang/test/Driver/mlir-debug-pass-pipeline.f90 +++ b/flang/test/Driver/mlir-debug-pass-pipeline.f90 @@ -29,22 +29,27 @@ ! ALL: Fortran::lower::VerifierPass ! ALL-NEXT: Pipeline Collection : ['fir.global', 'func.func', 'omp.declare_mapper', 'omp.declare_reduction', 'omp.private'] ! ALL-NEXT: 'fir.global' Pipeline +! ALL-NEXT: SimplifyHLFIRIntrinsics ! ALL-NEXT: InlineElementals ! ALL-NEXT: SeparateAllocatableAssign ! ALL-NEXT: InlineHLFIRAssign ! ALL-NEXT: 'func.func' Pipeline +! ALL-NEXT: SimplifyHLFIRIntrinsics ! ALL-NEXT: InlineElementals ! ALL-NEXT: SeparateAllocatableAssign ! ALL-NEXT: InlineHLFIRAssign ! ALL-NEXT: 'omp.declare_mapper' Pipeline +! ALL-NEXT: SimplifyHLFIRIntrinsics ! ALL-NEXT: InlineElementals ! ALL-NEXT: SeparateAllocatableAssign ! ALL-NEXT: InlineHLFIRAssign ! ALL-NEXT: 'omp.declare_reduction' Pipeline +! ALL-NEXT: SimplifyHLFIRIntrinsics ! ALL-NEXT: InlineElementals ! ALL-NEXT: SeparateAllocatableAssign ! ALL-NEXT: InlineHLFIRAssign ! ALL-NEXT: 'omp.private' Pipeline +! ALL-NEXT: SimplifyHLFIRIntrinsics ! ALL-NEXT: InlineElementals ! ALL-NEXT: SeparateAllocatableAssign ! ALL-NEXT: InlineHLFIRAssign diff --git a/flang/test/HLFIR/simplify-hlfir-intrinsics-scope.fir b/flang/test/HLFIR/simplify-hlfir-intrinsics-scope.fir new file mode 100644 index 00000000000000..3ddde409f94207 --- /dev/null +++ b/flang/test/HLFIR/simplify-hlfir-intrinsics-scope.fir @@ -0,0 +1,36 @@ +// Test the scope option of --simplify-hlfir-intrinsics. +// RUN: fir-opt %s --simplify-hlfir-intrinsics | FileCheck %s --check-prefixes=ALL,SUM-SIMPLIFY,OTHER-SIMPLIFY +// RUN: fir-opt %s --simplify-hlfir-intrinsics=scope=all | FileCheck %s --check-prefixes=ALL,SUM-SIMPLIFY,OTHER-SIMPLIFY +// RUN: fir-opt %s --simplify-hlfir-intrinsics=scope=only-sum | FileCheck %s --check-prefixes=ALL,SUM-SIMPLIFY,OTHER-KEEP +// RUN: fir-opt %s --simplify-hlfir-intrinsics=scope=except-sum | FileCheck %s --check-prefixes=ALL,SUM-KEEP,OTHER-SIMPLIFY +// RUN: fir-opt %s --simplify-hlfir-intrinsics=scope=none | FileCheck %s --check-prefixes=ALL,SUM-KEEP,OTHER-KEEP + +func.func @sum_real(%arg0: !fir.box<!fir.array<?xf32>>) -> f32 { + %res = hlfir.sum %arg0 : (!fir.box<!fir.array<?xf32>>) -> f32 + return %res : f32 +} +// ALL-LABEL: func.func @sum_real( +// SUM-SIMPLIFY-NOT: hlfir.sum +// SUM-SIMPLIFY: fir.do_loop +// SUM-SIMPLIFY-NOT: hlfir.sum +// SUM-SIMPLIFY: arith.addf +// SUM-SIMPLIFY-NOT: hlfir.sum +// SUM-KEEP-NOT: fir.do_loop +// SUM-KEEP: hlfir.sum %{{.*}} : (!fir.box<!fir.array<?xf32>>) -> f32 +// SUM-KEEP-NOT: fir.do_loop +// ALL: return + +func.func @product_real(%arg0: !fir.box<!fir.array<?xf32>>) -> f32 { + %res = hlfir.product %arg0 : (!fir.box<!fir.array<?xf32>>) -> f32 + return %res : f32 +} +// ALL-LABEL: func.func @product_real( +// OTHER-SIMPLIFY-NOT: hlfir.product +// OTHER-SIMPLIFY: fir.do_loop +// OTHER-SIMPLIFY-NOT: hlfir.product +// OTHER-SIMPLIFY: arith.mulf +// OTHER-SIMPLIFY-NOT: hlfir.product +// OTHER-KEEP-NOT: fir.do_loop +// OTHER-KEEP: hlfir.product %{{.*}} : (!fir.box<!fir.array<?xf32>>) -> f32 +// OTHER-KEEP-NOT: fir.do_loop +// ALL: return diff --git a/flang/test/Integration/OpenMP/parallel-private-reduction-worstcase.f90 b/flang/test/Integration/OpenMP/parallel-private-reduction-worstcase.f90 index 4f86c590b7e959..21392f4f1e46d7 100644 --- a/flang/test/Integration/OpenMP/parallel-private-reduction-worstcase.f90 +++ b/flang/test/Integration/OpenMP/parallel-private-reduction-worstcase.f90 @@ -162,17 +162,26 @@ subroutine worst_case(a, b, c, d) ! CHECK-NEXT: br label %omp.par.region60 ! CHECK: omp.par.region60: ; preds = %omp.par.region59 -! [call SUM runtime function] +! [begin loop implementing SUM] +! CHECK: br label %omp.par.region61 + +! CHECK: omp.par.region61: ; preds = %omp.par.region62, %omp.par.region60 +! CHECK-NEXT: %{{.*}} = phi i64 +! CHECK-NEXT: %{{.*}} = phi float +! CHECK-NEXT: %{{.*}} = phi i64 +! CHECK: br i1 %{{.*}}, label %omp.par.region62, label %omp.par.region63 + +! CHECK: omp.par.region63: ; preds = %omp.par.region61 ! [if (sum(a) == 1)] -! CHECK: br i1 %{{.*}}, label %omp.par.region61, label %omp.par.region62 +! CHECK: br i1 %{{.*}}, label %omp.par.region64, label %omp.par.region65 -! CHECK: omp.par.region62: ; preds = %omp.par.region60 -! CHECK-NEXT: br label %omp.par.region63 +! CHECK: omp.par.region65: ; preds = %omp.par.region63 +! CHECK-NEXT: br label %omp.par.region66 -! CHECK: omp.par.region63: ; preds = %omp.par.region62 +! CHECK: omp.par.region66: ; preds = %omp.par.region65 ! CHECK-NEXT: br label %omp.region.cont58 -! CHECK: omp.region.cont58: ; preds = %omp.par.region63 +! CHECK: omp.region.cont58: ; preds = %omp.par.region66 ! [omp parallel region done, call into the runtime to complete reduction] ! CHECK: %[[VAL_233:.*]] = call i32 @__kmpc_reduce( ! CHECK: switch i32 %[[VAL_233]], label %reduce.finalize [ @@ -189,7 +198,7 @@ subroutine worst_case(a, b, c, d) ! [various blocks implementing the reduction] -! CHECK: omp.region.cont68: ; preds = +! CHECK: omp.region.cont71: ; preds = ! CHECK-NEXT: %{{.*}} = phi ptr ! CHECK-NEXT: call void @__kmpc_end_reduce( ! CHECK-NEXT: br label %reduce.finalize @@ -206,23 +215,29 @@ subroutine worst_case(a, b, c, d) ! CHECK: omp.reduction.cleanup: ; preds = %.fini ! [null check] -! CHECK: br i1 %{{.*}}, label %omp.reduction.cleanup74, label %omp.reduction.cleanup75 +! CHECK: br i1 %{{.*}}, label %omp.reduction.cleanup77, label %omp.reduction.cleanup78 -! CHECK: omp.reduction.cleanup75: ; preds = %omp.reduction.cleanup74, %omp.reduction.cleanup -! CHECK-NEXT: br label %omp.region.cont73 +! CHECK: omp.reduction.cleanup78: ; preds = %omp.reduction.cleanup77, %omp.reduction.cleanup +! CHECK-NEXT: br label %omp.region.cont76 -! CHECK: omp.region.cont73: ; preds = %omp.reduction.cleanup75 +! CHECK: omp.region.cont76: ; preds = %omp.reduction.cleanup78 ! CHECK-NEXT: %{{.*}} = load ptr, ptr -! CHECK-NEXT: br label %omp.reduction.cleanup77 +! CHECK-NEXT: br label %omp.reduction.cleanup80 -! CHECK: omp.reduction.cleanup77: ; preds = %omp.region.cont73 +! CHECK: omp.reduction.cleanup80: ; preds = %omp.region.cont76 ! [null check] -! CHECK: br i1 %{{.*}}, label %omp.reduction.cleanup78, label %omp.reduction.cleanup79 +! CHECK: br i1 %{{.*}}, label %omp.reduction.cleanup81, label %omp.reduction.cleanup82 -! CHECK: omp.par.region61: ; preds = %omp.par.region60 +! CHECK: omp.par.region64: ; preds = %omp.par.region63 ! CHECK-NEXT: call void @_FortranAStopStatement ! CHECK-NEXT: unreachable +! CHECK: omp.par.region62: ; preds = %omp.par.region61 +! [add an array element to the SUM accumulator] +! CHECK: %{{.*}} = load float, ptr %{{.*}}, align 4 +! CHECK-NEXT: %{{.*}} = fadd contract float %{{.*}}, %{{.*}} +! CHECK: br label %omp.par.region61 + ! CHECK: omp.reduction.neutral55: ; preds = %omp.reduction.neutral54 ! CHECK: store float 0.000000e+00, ptr %{{.*}}, align 4 ! CHECK: br label %omp.reduction.neutral54 @@ -273,5 +288,5 @@ subroutine worst_case(a, b, c, d) ! [var extent was non-zero: malloc a private array] ! CHECK: br label %omp.private.init5 -! CHECK: omp.par.exit.exitStub: ; preds = %omp.region.cont83 +! CHECK: omp.par.exit.exitStub: ; preds = %omp.region.cont86 ! CHECK-NEXT: ret void diff --git a/flang/test/Integration/compensated-sum.f90 b/flang/test/Integration/compensated-sum.f90 new file mode 100644 index 00000000000000..cb6c2d8c03e587 --- /dev/null +++ b/flang/test/Integration/compensated-sum.f90 @@ -0,0 +1,60 @@ +!===----------------------------------------------------------------------===! +! This directory can be used to add Integration tests involving multiple +! stages of the compiler (for eg. from Fortran to LLVM IR). It should not +! contain executable tests. We should only add tests here sparingly and only +! if there is no other way to test. Repeat this message in each test that is +! added to this directory and sub-directories. +!===----------------------------------------------------------------------===! + +! RUN: %flang_fc1 -emit-llvm -O0 %s -o - \ +! RUN: | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE +! RUN: %flang_fc1 -emit-llvm -O1 %s -o - \ +! RUN: | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE +! RUN: %flang_fc1 -emit-llvm -O2 %s -o - \ +! RUN: | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE +! RUN: %flang_fc1 -emit-llvm -O3 %s -o - \ +! RUN: | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-INLINE +! RUN: %flang_fc1 -emit-llvm -O0 -fcompensated-sum %s -o - \ +! RUN: | FileCheck %s --check-prefixes=CHECK,INT-RUNTIME,FP-RUNTIME +! RUN: %flang_fc1 -emit-llvm -O1 -fcompensated-sum %s -o - \ +! RUN: | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-RUNTIME +! RUN: %flang_fc1 -emit-llvm -O2 -fcompensated-sum %s -o - \ +! RUN: | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-RUNTIME +! RUN: %flang_fc1 -emit-llvm -O3 -fcompensated-sum %s -o - \ +! RUN: | FileCheck %s --check-prefixes=CHECK,INT-INLINE,FP-RUNTIME + +integer function sum_integer(x) + integer, intent(in) :: x(10) + sum_integer = sum(x) +end function + +! CHECK-LABEL: define {{.*}}@sum_integer_( +! INT-INLINE-NOT: @_FortranASumInteger4( +! INT-INLINE: add {{.*}}i32 +! INT-INLINE-NOT: @_FortranASumInteger4( +! INT-RUNTIME: call i32 @_FortranASumInteger4( +! CHECK: ret i32 + +real function sum_real(x) + real, intent(in) :: x(10) + sum_real = sum(x) +end function + +! CHECK-LABEL: define {{.*}}@sum_real_( +! FP-INLINE-NOT: @_FortranASumReal4( +! FP-INLINE: fadd{{.*}}float +! FP-INLINE-NOT: @_FortranASumReal4( +! FP-RUNTIME: call {{.*}}@_FortranASumReal4( +! CHECK: ret float + +complex function sum_complex(x) + complex, intent(in) :: x(10) + sum_complex = sum(x) +end function + +! CHECK-LABEL: define {{.*}}@sum_complex_( +! FP-INLINE-NOT: @_FortranACppSumComplex4( +! FP-INLINE: fadd{{.*}}float +! FP-INLINE-NOT: @_FortranACppSumComplex4( +! FP-RUNTIME: call void @_FortranACppSumComplex4( +! CHECK: ret diff --git a/flang/test/Transforms/simplifyintrinsics-compensated-sum.fir b/flang/test/Transforms/simplifyintrinsics-compensated-sum.fir new file mode 100644 index 00000000000000..f3450a046448ee --- /dev/null +++ b/flang/test/Transforms/simplifyintrinsics-compensated-sum.fir @@ -0,0 +1,39 @@ +// RUN: fir-opt --simplify-intrinsics %s | FileCheck %s --check-prefixes=CHECK,PLAIN +// RUN: fir-opt --simplify-intrinsics="compensated-sum=false" %s | FileCheck %s --check-prefixes=CHECK,PLAIN +// RUN: fir-opt --simplify-intrinsics="compensated-sum=true" %s | FileCheck %s --check-prefixes=CHECK,COMPENSATED + +// When compensated-sum is true, disable floating-point SUM simplification +// while still attempting to simplify integer SUM. +func.func @compensated_sum_mixed(%array: !fir.ref<!fir.array<10x10xf32>>, + %integers: !fir.ref<!fir.array<10xi32>>) -> (f32, i32) { + %c10 = arith.constant 10 : index + %c0 = arith.constant 0 : index + %dim = fir.convert %c0 : (index) -> i32 + %line = arith.constant 1 : i32 + %file = fir.zero_bits !fir.ref<i8> + %absent = fir.absent !fir.box<i1> + %mask = fir.convert %absent : (!fir.box<i1>) -> !fir.box<none> + + %shape2d = fir.shape %c10, %c10 : (index, index) -> !fir.shape<2> + %box2d = fir.embox %array(%shape2d) : (!fir.ref<!fir.array<10x10xf32>>, !fir.shape<2>) -> !fir.box<!fir.array<10x10xf32>> + %array_box = fir.convert %box2d : (!fir.box<!fir.array<10x10xf32>>) -> !fir.box<none> + %sum_real = fir.call @_FortranASumReal4(%array_box, %file, %line, %dim, %mask) : (!fir.box<none>, !fir.ref<i8>, i32, i32, !fir.box<none>) -> f32 + + %shape1d = fir.shape %c10 : (index) -> !fir.shape<1> + %ibox = fir.embox %integers(%shape1d) : (!fir.ref<!fir.array<10xi32>>, !fir.shape<1>) -> !fir.box<!fir.array<10xi32>> + %integer_box = fir.convert %ibox : (!fir.box<!fir.array<10xi32>>) -> !fir.box<none> + %sum_integer = fir.call @_FortranASumInteger4(%integer_box, %file, %line, %dim, %mask) : (!fir.box<none>, !fir.ref<i8>, i32, i32, !fir.box<none>) -> i32 + + return %sum_real, %sum_integer : f32, i32 +} + +// CHECK-LABEL: func.func @compensated_sum_mixed( +// PLAIN: %[[SUM_REAL:.*]] = fir.call @_FortranASumReal4x2_simplified(%{{.*}}) : (!fir.box<none>) -> f32 +// PLAIN-NOT: fir.call @_FortranASumReal{{[0-9]+}}( +// COMPENSATED: %[[SUM_REAL:.*]] = fir.call @_FortranASumReal4(%{{.*}}) : (!fir.box<none>, !fir.ref<i8>, i32, i32, !fir.box<none>) -> f32 +// COMPENSATED-NOT: _FortranASumReal{{.*}}_simplified +// CHECK: %[[SUM_INTEGER:.*]] = fir.call @_FortranASumInteger4x1_simplified(%{{.*}}) : (!fir.box<none>) -> i32 +// CHECK: return %[[SUM_REAL]], %[[SUM_INTEGER]] : f32, i32 + +func.func private @_FortranASumReal4(!fir.box<none>, !fir.ref<i8>, i32, i32, !fir.box<none>) -> f32 attributes {fir.runtime} +func.func private @_FortranASumInteger4(!fir.box<none>, !fir.ref<i8>, i32, i32, !fir.box<none>) -> i32 attributes {fir.runtime} _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
