Stop the build if the linker produces an error code. Otherwise, the numbers in
the linker's error message can be misinterpreted as a linker version number, the
build completes successfully, and the resulting compiler doesn't work because
the supposed linker version number is invalid.

https://github.com/llvm/llvm-project/issues/186194

Also share linker version code between clang and flang; part of:

https://github.com/llvm/llvm-project/commit/3bc71c2abfa00413fd15cf0e5c08af6ec0d4768b

Also print the detected linker version when configuring flang, as was done for
clang in part of:

https://github.com/llvm/llvm-project/commit/633e3dacf27ea4950b7067803502490597ba96e0
--- a/cmake/Modules/GetDarwinLinkerVersion.cmake
+++ b/cmake/Modules/GetDarwinLinkerVersion.cmake
@@ -3,9 +3,9 @@
   set(LINK_VERSION)
   set(LD_V_OUTPUT)
   execute_process(
-    COMMAND sh -c "${CMAKE_LINKER} -v 2>&1 | head -1"
+    COMMAND "${CMAKE_LINKER}" -v
     RESULT_VARIABLE HAD_ERROR
-    OUTPUT_VARIABLE LD_V_OUTPUT
+    ERROR_VARIABLE LD_V_OUTPUT
     )
   if (HAD_ERROR)
     message(FATAL_ERROR "${CMAKE_LINKER} failed with status ${HAD_ERROR}")
--- a/flang/CMakeLists.txt
+++ b/flang/CMakeLists.txt
@@ -57,6 +57,7 @@
 
 # Must go below project(..)
 include(GNUInstallDirs)
+include(GetDarwinLinkerVersion)
 
 # MSVC + clang-cl build requires clang_rt.builtin.${target} library
 if (MSVC AND CMAKE_CXX_COMPILER_ID MATCHES Clang)
@@ -450,20 +451,8 @@
 # Determine HOST_LINK_VERSION on Darwin.
 set(HOST_LINK_VERSION)
 if (APPLE)
-  set(LD_V_OUTPUT)
-  execute_process(
-    COMMAND sh -c "${CMAKE_LINKER} -v 2>&1 | head -1"
-    RESULT_VARIABLE HAD_ERROR
-    OUTPUT_VARIABLE LD_V_OUTPUT)
-  if (NOT HAD_ERROR)
-    if ("${LD_V_OUTPUT}" MATCHES ".*ld64-([0-9.]+).*")
-      string(REGEX REPLACE ".*ld64-([0-9.]+).*" "\\1" HOST_LINK_VERSION ${LD_V_OUTPUT})
-    elseif ("${LD_V_OUTPUT}" MATCHES "[^0-9]*([0-9.]+).*")
-      string(REGEX REPLACE "[^0-9]*([0-9.]+).*" "\\1" HOST_LINK_VERSION ${LD_V_OUTPUT})
-    endif()
-  else()
-    message(FATAL_ERROR "${CMAKE_LINKER} failed with status ${HAD_ERROR}")
-  endif()
+  get_darwin_linker_version(HOST_LINK_VERSION)
+  message(STATUS "Host linker version: ${HOST_LINK_VERSION}")
 endif()
 
 include(AddFlang)
