From 913db72d121bd45c669a27d2d4ae9ee544dbefde Mon Sep 17 00:00:00 2001
From: Rafael Kitover <rkitover@gmail.com>
Date: Fri, 26 Aug 2022 17:09:06 +0000
Subject: [PATCH] build: check that -mtune=znver3 is supported

On gcc/clang check that the -mtune=znver3 compiler flag is supported, on
Debian 11 it is not and this breaks everything.

If it is not supported fallback to znver2, znver1, skylake-avx512 then
skylake in that order.

Signed-off-by: Rafael Kitover <rkitover@gmail.com>
---
 CMakeLists.txt | 29 ++++++++++++++++++++++++++---
 1 file changed, 26 insertions(+), 3 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4cce3f8e..b6ca6d3b 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -609,6 +609,8 @@ if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID STREQUAL Clang)
     # Common flags.
     set(MY_C_FLAGS -pipe -Wno-unused-command-line-argument -Wformat -Wformat-security -feliminate-unused-debug-types)
 
+    include(CheckCXXCompilerFlag)
+
     # Optimize for Core2 and tune for Rocketlake on macOS and Zen3 for the rest
     # on X86_64.
     if(X86_64)
@@ -616,7 +618,30 @@ if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID STREQUAL Clang)
         if(APPLE)
             set(MY_C_FLAGS ${MY_C_FLAGS} -mtune=rocketlake)
         else()
-            set(MY_C_FLAGS ${MY_C_FLAGS} -mtune=znver3)
+            check_cxx_compiler_flag("-mtune=znver3" ZEN3_TUNE_FLAG)
+            if(ZEN3_TUNE_FLAG)
+                set(MY_C_FLAGS ${MY_C_FLAGS} -mtune=znver3)
+            else()
+                check_cxx_compiler_flag("-mtune=znver2" ZEN2_TUNE_FLAG)
+                if(ZEN2_TUNE_FLAG)
+                    set(MY_C_FLAGS ${MY_C_FLAGS} -mtune=znver2)
+                else()
+                    check_cxx_compiler_flag("-mtune=znver1" ZEN1_TUNE_FLAG)
+                    if(ZEN1_TUNE_FLAG)
+                        set(MY_C_FLAGS ${MY_C_FLAGS} -mtune=znver1)
+                    else()
+                        check_cxx_compiler_flag("-mtune=skylake-avx512" SKYLAKE_AVX512_TUNE_FLAG)
+                        if(SKYLAKE_AVX512_TUNE_FLAG)
+                            set(MY_C_FLAGS ${MY_C_FLAGS} -mtune=skylake-avx512)
+                        else()
+                            check_cxx_compiler_flag("-mtune=skylake" SKYLAKE_TUNE_FLAG)
+                            if(SKYLAKE_TUNE_FLAG)
+                                set(MY_C_FLAGS ${MY_C_FLAGS} -mtune=skylake)
+                            endif()
+                        endif()
+                    endif()
+                endif()
+            endif()
         endif()
     # Optimize for pentium-mmx and tune for Core2 on X86_32.
     elseif(X86_32)
@@ -630,8 +655,6 @@ if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID STREQUAL Clang)
         set(MY_C_DBG_FLAGS -g -fno-omit-frame-pointer)
     endif()
 
-    include(CheckCXXCompilerFlag)
-
     if(ENABLE_ASAN)
         string(TOLOWER ${CMAKE_BUILD_TYPE} build)
         if(NOT build STREQUAL "debug")