clang_configuration.bzl 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. # Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. # Exceptions. See /LICENSE for license information.
  3. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. """Starlark repository rules to configure Clang (and LLVM) toolchain for Bazel.
  5. These rules should be run from the `WORKSPACE` file to substitute appropriate
  6. configured values into a `clang_detected_variables.bzl` file that can be used
  7. by the actual toolchain configuration.
  8. """
  9. def _run(repository_ctx, cmd):
  10. """Runs the provided `cmd`, checks for failure, and returns the result."""
  11. exec_result = repository_ctx.execute(cmd)
  12. if exec_result.return_code != 0:
  13. fail("Command failed with return code {0}: {1}\n{2}".format(
  14. exec_result.return_code,
  15. str(cmd),
  16. exec_result.stderr,
  17. ))
  18. return exec_result
  19. def _clang_version(version_output):
  20. """Returns version information, or a (None, "unknown") tuple if not found.
  21. Returns both the major version number (16) and the full version number for
  22. caching.
  23. """
  24. clang_version = None
  25. clang_version_for_cache = "unknown"
  26. version_prefix = "clang version "
  27. version_start = version_output.find(version_prefix)
  28. if version_start == -1:
  29. # No version
  30. return (clang_version, clang_version_for_cache)
  31. version_start += len(version_prefix)
  32. # Find the newline.
  33. version_newline = version_output.find("\n", version_start)
  34. if version_newline == -1:
  35. return (clang_version, clang_version_for_cache)
  36. clang_version_for_cache = version_output[version_start:version_newline]
  37. # Find a dot to indicate something like 'clang version 16.0.1', and grab the
  38. # major version.
  39. version_dot = version_output.find(".", version_start)
  40. if version_dot != -1 and version_dot < version_newline:
  41. clang_version = int(version_output[version_start:version_dot])
  42. return (clang_version, clang_version_for_cache)
  43. def _detect_system_clang(repository_ctx):
  44. """Detects whether the system-provided clang can be used.
  45. Returns a tuple of (is_clang, environment).
  46. """
  47. # If the user provides an explicit `CC` environment variable, use that as
  48. # the compiler. This should point at the `clang` executable to use.
  49. cc = repository_ctx.os.environ.get("CC")
  50. cc_path = None
  51. if cc:
  52. cc_path = repository_ctx.path(cc)
  53. if not cc_path.exists:
  54. cc_path = repository_ctx.which(cc)
  55. if not cc_path:
  56. cc_path = repository_ctx.which("clang")
  57. if not cc_path:
  58. fail("Cannot find clang or CC (%s); either correct your path or set the CC environment variable" % cc)
  59. version_output = _run(repository_ctx, [cc_path, "--version"]).stdout
  60. if "clang" not in version_output:
  61. fail("Searching for clang or CC (%s), and found (%s), which is not a Clang compiler" % (cc, cc_path))
  62. clang_version, clang_version_for_cache = _clang_version(version_output)
  63. return (cc_path.realpath, clang_version, clang_version_for_cache)
  64. def _compute_clang_resource_dir(repository_ctx, clang):
  65. """Runs the `clang` binary to get its resource dir."""
  66. output = _run(
  67. repository_ctx,
  68. [clang, "-no-canonical-prefixes", "--print-resource-dir"],
  69. ).stdout
  70. # The only line printed is this path.
  71. return output.splitlines()[0]
  72. def _compute_mac_os_sysroot(repository_ctx):
  73. """Runs `xcrun` to extract the correct sysroot."""
  74. xcrun = repository_ctx.which("xcrun")
  75. if not xcrun:
  76. fail("`xcrun` not found: is Xcode installed?")
  77. output = _run(repository_ctx, [xcrun, "--show-sdk-path"]).stdout
  78. return output.splitlines()[0]
  79. def _compute_bsd_sysroot(repository_ctx):
  80. """Look around for sysroot. Return root (/) if nothing found."""
  81. # Try it-just-works for CMake users.
  82. default = "/"
  83. sysroot = repository_ctx.os.environ.get("CMAKE_SYSROOT", default)
  84. sysroot_path = repository_ctx.path(sysroot)
  85. if sysroot_path.exists:
  86. return sysroot_path.realpath
  87. return default
  88. # File content used when computing search paths. This additionally verifies that
  89. # libc++ is installed.
  90. _CLANG_INCLUDE_FILE_CONTENT = """
  91. #if __has_include(<version>)
  92. #include <version>
  93. #endif
  94. #ifndef _LIBCPP_STD_VER
  95. #error "No libc++ install found!"
  96. #endif
  97. """
  98. def _compute_clang_cpp_include_search_paths(repository_ctx, clang, sysroot):
  99. """Runs the `clang` binary and extracts the include search paths.
  100. Returns the resulting paths as a list of strings.
  101. """
  102. # Create a file for Clang to use as input.
  103. repository_ctx.file("_temp", _CLANG_INCLUDE_FILE_CONTENT)
  104. input_file = repository_ctx.path("_temp")
  105. # The only way to get this out of Clang currently is to parse the verbose
  106. # output of the compiler when it is compiling C++ code.
  107. cmd = [
  108. clang,
  109. # Avoid canonicalizing away symlinks.
  110. "-no-canonical-prefixes",
  111. # Extract verbose output.
  112. "-v",
  113. # Just parse the input, don't generate outputs.
  114. "-fsyntax-only",
  115. # Force the language to be C++.
  116. "-x",
  117. "c++",
  118. # Use the input file.
  119. input_file,
  120. # Always use libc++.
  121. "-stdlib=libc++",
  122. ]
  123. # We need to use a sysroot to correctly represent a run on macOS.
  124. if repository_ctx.os.name.lower().startswith("mac os"):
  125. if not sysroot:
  126. fail("Must provide a sysroot on macOS!")
  127. cmd.append("--sysroot=" + sysroot)
  128. # Note that verbose output is on stderr, not stdout!
  129. output = _run(repository_ctx, cmd).stderr.splitlines()
  130. # Return the list of directories printed for system headers. These are the
  131. # only ones that Bazel needs us to manually provide. We find these by
  132. # searching for a begin and end marker. We also have to strip off a leading
  133. # space from each path.
  134. include_begin = output.index("#include <...> search starts here:") + 1
  135. include_end = output.index("End of search list.", include_begin)
  136. # Suffix present on framework paths.
  137. framework_suffix = " (framework directory)"
  138. return [
  139. repository_ctx.path(s.lstrip(" ").removesuffix(framework_suffix))
  140. for s in output[include_begin:include_end]
  141. ]
  142. def _configure_clang_toolchain_impl(repository_ctx):
  143. # First just symlink in the untemplated parts of the toolchain repo.
  144. repository_ctx.symlink(repository_ctx.attr._clang_toolchain_build, "BUILD")
  145. repository_ctx.symlink(
  146. repository_ctx.attr._clang_cc_toolchain_config,
  147. "cc_toolchain_config.bzl",
  148. )
  149. # Find a Clang C++ compiler, and where it lives. We need to walk symlinks
  150. # here as the other LLVM tools may not be symlinked into the PATH even if
  151. # `clang` is. We also insist on finding the basename of `clang++` as that is
  152. # important for C vs. C++ compiles.
  153. (clang, clang_version, clang_version_for_cache) = _detect_system_clang(
  154. repository_ctx,
  155. )
  156. if clang_version and clang_version < 16:
  157. fail("Found clang {0}. ".format(clang_version) +
  158. "Carbon requires clang >=16. See " +
  159. "https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/contribution_tools.md#old-llvm-versions")
  160. clang_cpp = clang.dirname.get_child("clang++")
  161. # Compute the various directories used by Clang.
  162. resource_dir = _compute_clang_resource_dir(repository_ctx, clang_cpp)
  163. sysroot_dir = None
  164. if repository_ctx.os.name.lower().startswith("mac os"):
  165. sysroot_dir = _compute_mac_os_sysroot(repository_ctx)
  166. if repository_ctx.os.name == "freebsd":
  167. sysroot_dir = _compute_bsd_sysroot(repository_ctx)
  168. include_dirs = _compute_clang_cpp_include_search_paths(
  169. repository_ctx,
  170. clang_cpp,
  171. sysroot_dir,
  172. )
  173. # We expect that the LLVM binutils live adjacent to llvm-ar.
  174. # First look for llvm-ar adjacent to clang, so that if found,
  175. # it is most likely to match the same version as clang.
  176. # Otherwise, try PATH.
  177. ar_path = clang.dirname.get_child("llvm-ar")
  178. if not ar_path.exists:
  179. ar_path = repository_ctx.which("llvm-ar")
  180. if not ar_path:
  181. fail("`llvm-ar` not found in PATH or adjacent to clang")
  182. # By default Windows uses '\' in its paths. These will be
  183. # interpreted as escape characters and fail the build, thus
  184. # we must manually replace the backslashes with '/'
  185. if repository_ctx.os.name.lower().startswith("windows"):
  186. resource_dir = resource_dir.replace("\\", "/")
  187. include_dirs = [str(s).replace("\\", "/") for s in include_dirs]
  188. repository_ctx.template(
  189. "clang_detected_variables.bzl",
  190. repository_ctx.attr._clang_detected_variables_template,
  191. substitutions = {
  192. "{CLANG_BINDIR}": str(clang.dirname),
  193. "{CLANG_INCLUDE_DIRS_LIST}": str(
  194. [str(path) for path in include_dirs],
  195. ),
  196. "{CLANG_RESOURCE_DIR}": resource_dir,
  197. "{CLANG_VERSION_FOR_CACHE}": clang_version_for_cache.replace('"', "_").replace("\\", "_"),
  198. "{CLANG_VERSION}": str(clang_version),
  199. "{LLVM_BINDIR}": str(ar_path.dirname),
  200. "{LLVM_SYMBOLIZER}": str(ar_path.dirname.get_child("llvm-symbolizer")),
  201. "{SYSROOT}": str(sysroot_dir),
  202. },
  203. executable = False,
  204. )
  205. configure_clang_toolchain = repository_rule(
  206. implementation = _configure_clang_toolchain_impl,
  207. configure = True,
  208. local = True,
  209. attrs = {
  210. "_clang_cc_toolchain_config": attr.label(
  211. default = Label(
  212. "//bazel/cc_toolchains:clang_cc_toolchain_config.bzl",
  213. ),
  214. allow_single_file = True,
  215. ),
  216. "_clang_detected_variables_template": attr.label(
  217. default = Label(
  218. "//bazel/cc_toolchains:clang_detected_variables.tpl.bzl",
  219. ),
  220. allow_single_file = True,
  221. ),
  222. "_clang_toolchain_build": attr.label(
  223. default = Label("//bazel/cc_toolchains:clang_toolchain.BUILD"),
  224. allow_single_file = True,
  225. ),
  226. },
  227. environ = ["CC"],
  228. )
  229. clang_toolchain_extension = module_extension(
  230. implementation = lambda ctx: configure_clang_toolchain(name = "bazel_cc_toolchain"),
  231. )