build_llvm.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (C) 2019 Intel Corporation. All rights reserved.
  4. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  5. #
  6. import argparse
  7. import os
  8. import pathlib
  9. import shlex
  10. import shutil
  11. import subprocess
  12. import sys
  13. def clone_llvm(dst_dir, llvm_repo, llvm_branch):
  14. """
  15. any error will raise CallProcessError
  16. """
  17. llvm_dir = dst_dir.joinpath("llvm").resolve()
  18. if not llvm_dir.exists():
  19. print(f"Clone llvm to {llvm_dir} ...")
  20. GIT_CLONE_CMD = f"git clone --depth 1 --branch {llvm_branch} {llvm_repo} llvm"
  21. subprocess.check_output(shlex.split(GIT_CLONE_CMD), cwd=dst_dir)
  22. else:
  23. print(f"There is an LLVM local repo in {llvm_dir}, clean and keep using it")
  24. return llvm_dir
  25. def build_llvm(llvm_dir, platform, backends, projects):
  26. LLVM_COMPILE_OPTIONS = [
  27. '-DCMAKE_BUILD_TYPE:STRING="Release"',
  28. "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
  29. "-DLLVM_APPEND_VC_REV:BOOL=ON",
  30. "-DLLVM_BUILD_BENCHMARKS:BOOL=OFF",
  31. "-DLLVM_BUILD_DOCS:BOOL=OFF",
  32. "-DLLVM_BUILD_EXAMPLES:BOOL=OFF",
  33. "-DLLVM_BUILD_LLVM_DYLIB:BOOL=OFF",
  34. "-DLLVM_BUILD_TESTS:BOOL=OFF",
  35. "-DLLVM_CCACHE_BUILD:BOOL=OFF",
  36. "-DLLVM_ENABLE_BINDINGS:BOOL=OFF",
  37. "-DLLVM_ENABLE_IDE:BOOL=OFF",
  38. "-DLLVM_ENABLE_TERMINFO:BOOL=OFF",
  39. "-DLLVM_ENABLE_ZLIB:BOOL=OFF",
  40. "-DLLVM_INCLUDE_BENCHMARKS:BOOL=OFF",
  41. "-DLLVM_INCLUDE_DOCS:BOOL=OFF",
  42. "-DLLVM_INCLUDE_EXAMPLES:BOOL=OFF",
  43. "-DLLVM_INCLUDE_UTILS:BOOL=OFF",
  44. "-DLLVM_INCLUDE_TESTS:BOOL=OFF",
  45. "-DLLVM_BUILD_TESTS:BOOL=OFF",
  46. "-DLLVM_OPTIMIZED_TABLEGEN:BOOL=ON",
  47. ]
  48. LLVM_EXTRA_COMPILE_OPTIONS = {
  49. "arc": [
  50. '-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD:STRING="ARC"',
  51. "-DLLVM_ENABLE_LIBICUUC:BOOL=OFF",
  52. "-DLLVM_ENABLE_LIBICUDATA:BOOL=OFF",
  53. ],
  54. "xtensa": [
  55. '-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD:STRING="Xtensa"',
  56. ],
  57. "windows": [
  58. "-DCMAKE_INSTALL_PREFIX=LLVM-install",
  59. ],
  60. "default": [],
  61. }
  62. LLVM_TARGETS_TO_BUILD = [
  63. '-DLLVM_TARGETS_TO_BUILD:STRING="' + ";".join(backends) + '"'
  64. if backends
  65. else '-DLLVM_TARGETS_TO_BUILD:STRING="AArch64;ARM;Mips;RISCV;X86"'
  66. ]
  67. LLVM_PROJECTS_TO_BUILD = [
  68. '-DLLVM_ENABLE_PROJECTS:STRING="' + ";".join(projects) + '"' if projects else ""
  69. ]
  70. # lldb project requires libxml2
  71. LLVM_LIBXML2_OPTION = [
  72. "-DLLVM_ENABLE_LIBXML2:BOOL=" + ("ON" if "lldb" in projects else "OFF")
  73. ]
  74. # enabling LLVM_INCLUDE_TOOLS will increase ~300M to the final package
  75. LLVM_INCLUDE_TOOLS_OPTION = [
  76. "-DLLVM_INCLUDE_TOOLS:BOOL=ON" if projects else "-DLLVM_INCLUDE_TOOLS:BOOL=OFF"
  77. ]
  78. if not llvm_dir.exists():
  79. raise Exception(f"{llvm_dir} doesn't exist")
  80. build_dir = llvm_dir.joinpath(
  81. "win32build" if "windows" == platform else "build"
  82. ).resolve()
  83. build_dir.mkdir(exist_ok=True)
  84. lib_llvm_core_library = build_dir.joinpath("lib/libLLVMCore.a").resolve()
  85. if lib_llvm_core_library.exists():
  86. print(f"Please remove {build_dir} manually and try again")
  87. return build_dir
  88. compile_options = " ".join(
  89. LLVM_COMPILE_OPTIONS
  90. + LLVM_LIBXML2_OPTION
  91. + LLVM_EXTRA_COMPILE_OPTIONS.get(
  92. platform, LLVM_EXTRA_COMPILE_OPTIONS["default"]
  93. )
  94. + LLVM_TARGETS_TO_BUILD
  95. + LLVM_PROJECTS_TO_BUILD
  96. + LLVM_INCLUDE_TOOLS_OPTION
  97. )
  98. CONFIG_CMD = f"cmake {compile_options} ../llvm " + (
  99. "-A x64" if "windows" == platform else ""
  100. )
  101. print(f"{CONFIG_CMD}")
  102. subprocess.check_call(shlex.split(CONFIG_CMD), cwd=build_dir)
  103. BUILD_CMD = f"cmake --build . --target package --parallel {os.cpu_count()}" + (
  104. " --config Release" if "windows" == platform else ""
  105. )
  106. subprocess.check_call(shlex.split(BUILD_CMD), cwd=build_dir)
  107. return build_dir
  108. def repackage_llvm(llvm_dir):
  109. build_dir = llvm_dir.joinpath("./build").resolve()
  110. packs = [f for f in build_dir.glob("LLVM-13*.tar.gz")]
  111. if len(packs) > 1:
  112. raise Exception("Find more than one LLVM-13*.tar.gz")
  113. if not packs:
  114. return
  115. llvm_package = packs[0].name
  116. # mv build/LLVM-13.0.0*.gz .
  117. shutil.move(str(build_dir.joinpath(llvm_package).resolve()), str(llvm_dir))
  118. # rm -r build
  119. shutil.rmtree(str(build_dir))
  120. # mkdir build
  121. build_dir.mkdir()
  122. # tar xf ./LLVM-13.0.0-*.tar.gz --strip-components=1 --directory=build
  123. CMD = f"tar xf {llvm_dir.joinpath(llvm_package).resolve()} --strip-components=1 --directory={build_dir}"
  124. subprocess.check_call(shlex.split(CMD), cwd=llvm_dir)
  125. def main():
  126. parser = argparse.ArgumentParser(description="build necessary LLVM libraries")
  127. parser.add_argument(
  128. "--platform",
  129. type=str,
  130. choices=["android", "arc", "darwin", "linux", "windows", "xtensa"],
  131. help="identify current platform",
  132. )
  133. parser.add_argument(
  134. "--arch",
  135. nargs="+",
  136. type=str,
  137. choices=[
  138. "AArch64",
  139. "ARC",
  140. "ARM",
  141. "Mips",
  142. "RISCV",
  143. "WebAssembly",
  144. "X86",
  145. "Xtensa",
  146. ],
  147. help="identify LLVM supported backends, separate by space, like '--arch ARM Mips X86'",
  148. )
  149. parser.add_argument(
  150. "--project",
  151. nargs="+",
  152. type=str,
  153. default="",
  154. choices=["clang", "lldb"],
  155. help="identify extra LLVM projects, separate by space, like '--project clang lldb'",
  156. )
  157. options = parser.parse_args()
  158. print(f"options={options}")
  159. # if the "platform" is not identified in the command line option,
  160. # detect it
  161. if not options.platform:
  162. if sys.platform.startswith("win32") or sys.platform.startswith("msys"):
  163. platform = "windows"
  164. elif sys.platform.startswith("darwin"):
  165. platform = "darwin"
  166. else:
  167. platform = "linux"
  168. else:
  169. platform = options.platform
  170. print(f"========== Build LLVM for {platform} ==========\n")
  171. llvm_repo_and_branch = {
  172. "arc": {
  173. "repo": "https://github.com/llvm/llvm-project.git",
  174. "branch": "release/13.x",
  175. },
  176. "xtensa": {
  177. "repo": "https://github.com/espressif/llvm-project.git",
  178. "branch": "xtensa_release_11.0.0",
  179. },
  180. "default": {
  181. "repo": "https://github.com/llvm/llvm-project.git",
  182. "branch": "release/13.x",
  183. },
  184. }
  185. # retrieve the real file
  186. current_file = pathlib.Path(__file__)
  187. if current_file.is_symlink():
  188. current_file = pathlib.Path(os.readlink(current_file))
  189. current_dir = current_file.parent.resolve()
  190. deps_dir = current_dir.joinpath("../core/deps").resolve()
  191. try:
  192. print(f"==================== CLONE LLVM ====================")
  193. llvm_info = llvm_repo_and_branch.get(platform, llvm_repo_and_branch["default"])
  194. llvm_dir = clone_llvm(deps_dir, llvm_info["repo"], llvm_info["branch"])
  195. print()
  196. print(f"==================== BUILD LLVM ====================")
  197. build_llvm(llvm_dir, platform, options.arch, options.project)
  198. print()
  199. print(f"==================== PACKAGE LLVM ====================")
  200. repackage_llvm(llvm_dir)
  201. print()
  202. return True
  203. except subprocess.CalledProcessError:
  204. return False
  205. if __name__ == "__main__":
  206. sys.exit(0 if main() else 1)