[SystemZ][ZOS] Prefer -nostdlib++ as opposed to -nodefaultlibs when building c++ libraries

Let's use -nostdlib++ rather than -nodefaultlibs when building libc++/libc++abi/libunwind libraries. The default is -nostdlib++ if supported by a build compiler like it is the case with clang, otherwise -nodefaultlibs is used as before.

This change is needed to avoid additional changes at the link step and not to increase the maintenance costs. If clang with -nodefaultlibs is used all the libraries which are removed but required would have to be manually added in. This set of libraries are unique and will send out.

The propose change will allow to make the link step simple for other platforms as well.

Reviewed By: #libc, #libc_abi, ldionne

Differential Revision: https://reviews.llvm.org/D95875

GitOrigin-RevId: 5f9be2c3e37c0428ba56876dd84af04b8d9d8915
diff --git a/cmake/config-ix.cmake b/cmake/config-ix.cmake
index 15b5208..7f1cecb 100644
--- a/cmake/config-ix.cmake
+++ b/cmake/config-ix.cmake
@@ -14,16 +14,26 @@
   endif ()
 endif ()
 
-# libc++abi is built with -nodefaultlibs, so we want all our checks to also
-# use this option, otherwise we may end up with an inconsistency between
+# libc++abi is using -nostdlib++ at the link step when available,
+# otherwise -nodefaultlibs is used. We want all our checks to also
+# use one of these options, otherwise we may end up with an inconsistency between
 # the flags we think we require during configuration (if the checks are
 # performed without -nodefaultlibs) and the flags that are actually
 # required during compilation (which has the -nodefaultlibs). libc is
 # required for the link to go through. We remove sanitizers from the
 # configuration checks to avoid spurious link errors.
-check_c_compiler_flag(-nodefaultlibs LIBCXXABI_HAS_NODEFAULTLIBS_FLAG)
-if (LIBCXXABI_HAS_NODEFAULTLIBS_FLAG)
-  set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -nodefaultlibs")
+
+check_c_compiler_flag(-nostdlib++ LIBCXXABI_SUPPORTS_NOSTDLIBXX_FLAG)
+if (LIBCXXABI_SUPPORTS_NOSTDLIBXX_FLAG)
+  set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -nostdlib++")
+else()
+  check_c_compiler_flag(-nodefaultlibs LIBCXXABI_SUPPORTS_NODEFAULTLIBS_FLAG)
+  if (LIBCXXABI_SUPPORTS_NODEFAULTLIBS_FLAG)
+    set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -nodefaultlibs")
+  endif()
+endif()
+
+if (LIBCXXABI_SUPPORTS_NOSTDLIBXX_FLAG OR LIBCXXABI_SUPPORTS_NODEFAULTLIBS_FLAG)
   if (LIBCXXABI_HAS_C_LIB)
     list(APPEND CMAKE_REQUIRED_LIBRARIES c)
   endif ()
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index a8e12aa..9003f79 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -109,7 +109,11 @@
 endif ()
 
 # Setup flags.
-add_link_flags_if_supported(-nodefaultlibs)
+if (LIBCXXABI_SUPPORTS_NOSTDLIBXX_FLAG)
+  add_link_flags_if_supported(-nostdlib++)
+else()
+  add_link_flags_if_supported(-nodefaultlibs)
+endif()
 
 if ( APPLE )
   if (LLVM_USE_SANITIZER)