Guest User

chromium/src/tools/clang/scripts/build.py

a guest
Jul 29th, 2022
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 53.87 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # Copyright 2019 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5.  
  6. """This script is used to build clang binaries. It is used by package.py to
  7. create the prebuilt binaries downloaded by update.py and used by developers.
  8.  
  9. The expectation is that update.py downloads prebuilt binaries for everyone, and
  10. nobody should run this script as part of normal development.
  11. """
  12.  
  13. from __future__ import print_function
  14.  
  15. import argparse
  16. import glob
  17. import io
  18. import json
  19. import os
  20. import pipes
  21. import platform
  22. import re
  23. import shutil
  24. import subprocess
  25. import sys
  26. import tempfile
  27.  
  28. from update import (CDS_URL, CHROMIUM_DIR, CLANG_REVISION, LLVM_BUILD_DIR,
  29. FORCE_HEAD_REVISION_FILE, PACKAGE_VERSION, RELEASE_VERSION,
  30. STAMP_FILE, THIS_DIR, DownloadUrl, DownloadAndUnpack,
  31. EnsureDirExists, ReadStampFile, RmTree, WriteStampFile)
  32.  
  33. # Path constants. (All of these should be absolute paths.)
  34. THIRD_PARTY_DIR = os.path.join(CHROMIUM_DIR, 'third_party')
  35. LLVM_DIR = os.path.join(THIRD_PARTY_DIR, 'llvm')
  36. COMPILER_RT_DIR = os.path.join(LLVM_DIR, 'compiler-rt')
  37. LLVM_BOOTSTRAP_DIR = os.path.join(THIRD_PARTY_DIR, 'llvm-bootstrap')
  38. LLVM_BOOTSTRAP_INSTALL_DIR = os.path.join(THIRD_PARTY_DIR,
  39. 'llvm-bootstrap-install')
  40. LLVM_INSTRUMENTED_DIR = os.path.join(THIRD_PARTY_DIR, 'llvm-instrumented')
  41. LLVM_PROFDATA_FILE = os.path.join(LLVM_INSTRUMENTED_DIR, 'profdata.prof')
  42. LLVM_BUILD_TOOLS_DIR = os.path.abspath(
  43. os.path.join(LLVM_DIR, '..', 'llvm-build-tools'))
  44. ANDROID_NDK_DIR = os.path.join(
  45. CHROMIUM_DIR, 'third_party', 'android_ndk')
  46. FUCHSIA_SDK_DIR = os.path.join(CHROMIUM_DIR, 'third_party', 'fuchsia-sdk',
  47. 'sdk')
  48. PINNED_CLANG_DIR = os.path.join(LLVM_BUILD_TOOLS_DIR, 'pinned-clang')
  49.  
  50. BUG_REPORT_URL = ('https://crbug.com and run'
  51. ' tools/clang/scripts/process_crashreports.py'
  52. ' (only works inside Google) which will upload a report')
  53.  
  54. win_sdk_dir = None
  55. def GetWinSDKDir():
  56. """Get the location of the current SDK."""
  57. global win_sdk_dir
  58. if win_sdk_dir:
  59. return win_sdk_dir
  60.  
  61. # Don't let vs_toolchain overwrite our environment.
  62. environ_bak = os.environ
  63.  
  64. sys.path.append(os.path.join(CHROMIUM_DIR, 'build'))
  65. import vs_toolchain
  66. win_sdk_dir = vs_toolchain.SetEnvironmentAndGetSDKDir()
  67. msvs_version = vs_toolchain.GetVisualStudioVersion()
  68.  
  69. if bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1'))):
  70. dia_path = os.path.join(win_sdk_dir, '..', 'DIA SDK', 'bin', 'amd64')
  71. else:
  72. if 'GYP_MSVS_OVERRIDE_PATH' not in os.environ:
  73. vs_path = vs_toolchain.DetectVisualStudioPath()
  74. else:
  75. vs_path = os.environ['GYP_MSVS_OVERRIDE_PATH']
  76. dia_path = os.path.join(vs_path, 'DIA SDK', 'bin', 'amd64')
  77.  
  78. os.environ = environ_bak
  79. return win_sdk_dir
  80.  
  81.  
  82. def RunCommand(command, msvc_arch=None, env=None, fail_hard=True):
  83. """Run command and return success (True) or failure; or if fail_hard is
  84. True, exit on failure. If msvc_arch is set, runs the command in a
  85. shell with the msvc tools for that architecture."""
  86.  
  87. if msvc_arch and sys.platform == 'win32':
  88. command = [os.path.join(GetWinSDKDir(), 'bin', 'SetEnv.cmd'),
  89. "/" + msvc_arch, '&&'] + command
  90.  
  91. # https://docs.python.org/2/library/subprocess.html:
  92. # "On Unix with shell=True [...] if args is a sequence, the first item
  93. # specifies the command string, and any additional items will be treated as
  94. # additional arguments to the shell itself. That is to say, Popen does the
  95. # equivalent of:
  96. # Popen(['/bin/sh', '-c', args[0], args[1], ...])"
  97. #
  98. # We want to pass additional arguments to command[0], not to the shell,
  99. # so manually join everything into a single string.
  100. # Annoyingly, for "svn co url c:\path", pipes.quote() thinks that it should
  101. # quote c:\path but svn can't handle quoted paths on Windows. Since on
  102. # Windows follow-on args are passed to args[0] instead of the shell, don't
  103. # do the single-string transformation there.
  104. if sys.platform != 'win32':
  105. command = ' '.join([pipes.quote(c) for c in command])
  106. print('Running', command)
  107. if subprocess.call(command, env=env, shell=True) == 0:
  108. return True
  109. print('Failed.')
  110. if fail_hard:
  111. sys.exit(1)
  112. return False
  113.  
  114.  
  115. def CopyFile(src, dst):
  116. """Copy a file from src to dst."""
  117. print("Copying %s to %s" % (src, dst))
  118. shutil.copy(src, dst)
  119.  
  120.  
  121. def CopyDirectoryContents(src, dst):
  122. """Copy the files from directory src to dst."""
  123. dst = os.path.realpath(dst) # realpath() in case dst ends in /..
  124. EnsureDirExists(dst)
  125. for f in os.listdir(src):
  126. CopyFile(os.path.join(src, f), dst)
  127.  
  128.  
  129. def CheckoutLLVM(commit, dir):
  130. """Checkout the LLVM monorepo at a certain git commit in dir. Any local
  131. modifications in dir will be lost."""
  132.  
  133. print('Checking out LLVM monorepo %s into %s' % (commit, dir))
  134.  
  135. # Try updating the current repo if it exists and has no local diff.
  136. if os.path.isdir(dir):
  137. os.chdir(dir)
  138. # git diff-index --quiet returns success when there is no diff.
  139. # Also check that the first commit is reachable.
  140. if (RunCommand(['git', 'diff-index', '--quiet', 'HEAD'], fail_hard=False)
  141. and RunCommand(['git', 'fetch'], fail_hard=False)
  142. and RunCommand(['git', 'checkout', commit], fail_hard=False)):
  143. return
  144.  
  145. # If we can't use the current repo, delete it.
  146. os.chdir(CHROMIUM_DIR) # Can't remove dir if we're in it.
  147. print('Removing %s.' % dir)
  148. RmTree(dir)
  149.  
  150. clone_cmd = ['git', 'clone', 'https://github.com/llvm/llvm-project/', dir]
  151.  
  152. if RunCommand(clone_cmd, fail_hard=False):
  153. os.chdir(dir)
  154. if RunCommand(['git', 'checkout', commit], fail_hard=False):
  155. return
  156.  
  157. print('CheckoutLLVM failed.')
  158. sys.exit(1)
  159.  
  160.  
  161. def UrlOpen(url):
  162. # TODO(crbug.com/1067752): Use urllib once certificates are fixed.
  163. return subprocess.check_output(['curl', '--silent', url],
  164. universal_newlines=True)
  165.  
  166.  
  167. def GetLatestLLVMCommit():
  168. """Get the latest commit hash in the LLVM monorepo."""
  169. ref = json.loads(
  170. UrlOpen(('https://api.github.com/repos/'
  171. 'llvm/llvm-project/git/refs/heads/main')))
  172. assert ref['object']['type'] == 'commit'
  173. return ref['object']['sha']
  174.  
  175.  
  176. def GetCommitDescription(commit):
  177. """Get the output of `git describe`.
  178.  
  179. Needs to be called from inside the git repository dir."""
  180. git_exe = 'git.bat' if sys.platform.startswith('win') else 'git'
  181. return subprocess.check_output(
  182. [git_exe, 'describe', '--long', '--abbrev=8', commit],
  183. universal_newlines=True).rstrip()
  184.  
  185.  
  186. def AddCMakeToPath(args):
  187. """Download CMake and add it to PATH."""
  188. if args.use_system_cmake:
  189. return
  190.  
  191. if sys.platform == 'win32':
  192. zip_name = 'cmake-3.23.0-windows-x86_64.zip'
  193. dir_name = ['cmake-3.23.0-windows-x86_64', 'bin']
  194. elif sys.platform == 'darwin':
  195. zip_name = 'cmake-3.23.0-macos-universal.tar.gz'
  196. dir_name = ['cmake-3.23.0-macos-universal', 'CMake.app', 'Contents', 'bin']
  197. else:
  198. zip_name = 'cmake-3.23.0-linux-x86_64.tar.gz'
  199. dir_name = ['cmake-3.23.0-linux-x86_64', 'bin']
  200.  
  201. cmake_dir = os.path.join(LLVM_BUILD_TOOLS_DIR, *dir_name)
  202. if not os.path.exists(cmake_dir):
  203. DownloadAndUnpack(CDS_URL + '/tools/' + zip_name, LLVM_BUILD_TOOLS_DIR)
  204. os.environ['PATH'] = cmake_dir + os.pathsep + os.environ.get('PATH', '')
  205.  
  206.  
  207. def AddGnuWinToPath():
  208. """Download some GNU win tools and add them to PATH."""
  209. if sys.platform != 'win32':
  210. return
  211.  
  212. gnuwin_dir = os.path.join(LLVM_BUILD_TOOLS_DIR, 'gnuwin')
  213. GNUWIN_VERSION = '14'
  214. GNUWIN_STAMP = os.path.join(gnuwin_dir, 'stamp')
  215. if ReadStampFile(GNUWIN_STAMP) == GNUWIN_VERSION:
  216. print('GNU Win tools already up to date.')
  217. else:
  218. zip_name = 'gnuwin-%s.zip' % GNUWIN_VERSION
  219. DownloadAndUnpack(CDS_URL + '/tools/' + zip_name, LLVM_BUILD_TOOLS_DIR)
  220. WriteStampFile(GNUWIN_VERSION, GNUWIN_STAMP)
  221.  
  222. os.environ['PATH'] = gnuwin_dir + os.pathsep + os.environ.get('PATH', '')
  223.  
  224. # find.exe, mv.exe and rm.exe are from MSYS (see crrev.com/389632). MSYS uses
  225. # Cygwin under the hood, and initializing Cygwin has a race-condition when
  226. # getting group and user data from the Active Directory is slow. To work
  227. # around this, use a horrible hack telling it not to do that.
  228. # See https://crbug.com/905289
  229. etc = os.path.join(gnuwin_dir, '..', '..', 'etc')
  230. EnsureDirExists(etc)
  231. with open(os.path.join(etc, 'nsswitch.conf'), 'w') as f:
  232. f.write('passwd: files\n')
  233. f.write('group: files\n')
  234.  
  235.  
  236. def AddZlibToPath():
  237. """Download and build zlib, and add to PATH."""
  238. zlib_dir = os.path.join(LLVM_BUILD_TOOLS_DIR, 'zlib-1.2.11')
  239. if os.path.exists(zlib_dir):
  240. RmTree(zlib_dir)
  241. zip_name = 'zlib-1.2.11.tar.gz'
  242. DownloadAndUnpack(CDS_URL + '/tools/' + zip_name, LLVM_BUILD_TOOLS_DIR)
  243. os.chdir(zlib_dir)
  244. zlib_files = [
  245. 'adler32', 'compress', 'crc32', 'deflate', 'gzclose', 'gzlib', 'gzread',
  246. 'gzwrite', 'inflate', 'infback', 'inftrees', 'inffast', 'trees',
  247. 'uncompr', 'zutil'
  248. ]
  249. cl_flags = [
  250. '/nologo', '/O2', '/DZLIB_DLL', '/c', '/D_CRT_SECURE_NO_DEPRECATE',
  251. '/D_CRT_NONSTDC_NO_DEPRECATE'
  252. ]
  253. RunCommand(
  254. ['cl.exe'] + [f + '.c' for f in zlib_files] + cl_flags, msvc_arch='x64')
  255. RunCommand(
  256. ['lib.exe'] + [f + '.obj'
  257. for f in zlib_files] + ['/nologo', '/out:zlib.lib'],
  258. msvc_arch='x64')
  259. # Remove the test directory so it isn't found when trying to find
  260. # test.exe.
  261. shutil.rmtree('test')
  262.  
  263. os.environ['PATH'] = zlib_dir + os.pathsep + os.environ.get('PATH', '')
  264. return zlib_dir
  265.  
  266.  
  267. def BuildLibXml2():
  268. """Download and build libxml2"""
  269. # The .tar.gz on GCS was uploaded as follows.
  270. # The gitlab page has more up-to-date packages than http://xmlsoft.org/,
  271. # and the official releases on xmlsoft.org are only available over ftp too.
  272. # $ VER=v2.9.12
  273. # $ curl -O \
  274. # https://gitlab.gnome.org/GNOME/libxml2/-/archive/$VER/libxml2-$VER.tar.gz
  275. # $ gsutil cp -n -a public-read libxml2-$VER.tar.gz \
  276. # gs://chromium-browser-clang/tools
  277.  
  278. libxml2_version = 'libxml2-v2.9.12'
  279. libxml2_dir = os.path.join(LLVM_BUILD_TOOLS_DIR, libxml2_version)
  280. if os.path.exists(libxml2_dir):
  281. RmTree(libxml2_dir)
  282. zip_name = libxml2_version + '.tar.gz'
  283. DownloadAndUnpack(CDS_URL + '/tools/' + zip_name, LLVM_BUILD_TOOLS_DIR)
  284. os.chdir(libxml2_dir)
  285. os.mkdir('build')
  286. os.chdir('build')
  287.  
  288. libxml2_install_dir = os.path.join(libxml2_dir, 'build', 'install')
  289.  
  290. # Disable everything except WITH_TREE and WITH_OUTPUT, both needed by LLVM's
  291. # WindowsManifestMerger.
  292. # Also enable WITH_THREADS, else libxml doesn't compile on Linux.
  293. RunCommand(
  294. [
  295. 'cmake',
  296. '-GNinja',
  297. '-DCMAKE_BUILD_TYPE=Release',
  298. '-DCMAKE_INSTALL_PREFIX=install',
  299. # The mac_arm bot builds a clang arm binary, but currently on an intel
  300. # host. If we ever move it to run on an arm mac, this can go. We
  301. # could pass this only if args.build_mac_arm, but libxml is small, so
  302. # might as well build it universal always for a few years.
  303. '-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64',
  304. '-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded', # /MT to match LLVM.
  305. '-DBUILD_SHARED_LIBS=OFF',
  306. '-DLIBXML2_WITH_C14N=OFF',
  307. '-DLIBXML2_WITH_CATALOG=OFF',
  308. '-DLIBXML2_WITH_DEBUG=OFF',
  309. '-DLIBXML2_WITH_DOCB=OFF',
  310. '-DLIBXML2_WITH_FTP=OFF',
  311. '-DLIBXML2_WITH_HTML=OFF',
  312. '-DLIBXML2_WITH_HTTP=OFF',
  313. '-DLIBXML2_WITH_ICONV=OFF',
  314. '-DLIBXML2_WITH_ICU=OFF',
  315. '-DLIBXML2_WITH_ISO8859X=OFF',
  316. '-DLIBXML2_WITH_LEGACY=OFF',
  317. '-DLIBXML2_WITH_LZMA=OFF',
  318. '-DLIBXML2_WITH_MEM_DEBUG=OFF',
  319. '-DLIBXML2_WITH_MODULES=OFF',
  320. '-DLIBXML2_WITH_OUTPUT=ON',
  321. '-DLIBXML2_WITH_PATTERN=OFF',
  322. '-DLIBXML2_WITH_PROGRAMS=OFF',
  323. '-DLIBXML2_WITH_PUSH=OFF',
  324. '-DLIBXML2_WITH_PYTHON=OFF',
  325. '-DLIBXML2_WITH_READER=OFF',
  326. '-DLIBXML2_WITH_REGEXPS=OFF',
  327. '-DLIBXML2_WITH_RUN_DEBUG=OFF',
  328. '-DLIBXML2_WITH_SAX1=OFF',
  329. '-DLIBXML2_WITH_SCHEMAS=OFF',
  330. '-DLIBXML2_WITH_SCHEMATRON=OFF',
  331. '-DLIBXML2_WITH_TESTS=OFF',
  332. '-DLIBXML2_WITH_THREADS=ON',
  333. '-DLIBXML2_WITH_THREAD_ALLOC=OFF',
  334. '-DLIBXML2_WITH_TREE=ON',
  335. '-DLIBXML2_WITH_VALID=OFF',
  336. '-DLIBXML2_WITH_WRITER=OFF',
  337. '-DLIBXML2_WITH_XINCLUDE=OFF',
  338. '-DLIBXML2_WITH_XPATH=OFF',
  339. '-DLIBXML2_WITH_XPTR=OFF',
  340. '-DLIBXML2_WITH_ZLIB=OFF',
  341. '-DLLVM_CCACHE_BUILD=ON',
  342. '-DCMAKE_C_COMPILER=/usr/lib/llvm-15/bin/clang',
  343. '-DCMAKE_CXX_COMPILER=/usr/lib/llvm-15/bin/clang++',
  344. '-DCMAKE_AR=/usr/lib/llvm-15/bin/llvm-ar',
  345. '-DCMAKE_LINKER=/usr/lib/llvm-15/bin/ld.lld',
  346. '-DCMAKE_NM=/usr/lib/llvm-15/bin/llvm-nm',
  347. '-DCMAKE_OBJDUMP=/usr/lib/llvm-15/bin/llvm-objdump',
  348. '-DCMAKE_RANLIB=/usr/lib/llvm-15/bin/llvm-ranlib',
  349. '-DCMAKE_ASM_FLAGS_RELEASE=-O3 -DNDEBUG -w -march=znver2 -ffp-contract=fast -fdata-sections -ffunction-sections -fno-unique-section-names -fmerge-all-constants -mllvm -polly -mllvm -polly-detect-profitability-min-per-loop-insts=40 -mllvm -polly-invariant-load-hoisting -mllvm -polly-vectorizer=stripmine',
  350. '-DCMAKE_C_FLAGS_RELEASE=-O3 -DNDEBUG -w -march=znver2 -ffp-contract=fast -fdata-sections -ffunction-sections -fno-unique-section-names -fmerge-all-constants -mllvm -polly -mllvm -polly-detect-profitability-min-per-loop-insts=40 -mllvm -polly-invariant-load-hoisting -mllvm -polly-vectorizer=stripmine',
  351. '-DCMAKE_CXX_FLAGS_RELEASE=-O3 -DNDEBUG -w -march=znver2 -ffp-contract=fast -fdata-sections -ffunction-sections -fno-unique-section-names -fmerge-all-constants -mllvm -polly -mllvm -polly-detect-profitability-min-per-loop-insts=40 -mllvm -polly-invariant-load-hoisting -mllvm -polly-vectorizer=stripmine',
  352. '-DCMAKE_EXE_LINKER_FLAGS_RELEASE=-Wl,-O2 -Wl,--gc-sections -Wl,--icf=all',
  353. '-DCMAKE_SHARED_LINKER_FLAGS_RELEASE=-Wl,-O2 -Wl,--gc-sections -Wl,--icf=all',
  354. '-DCMAKE_MODULE_LINKER_FLAGS_RELEASE=-Wl,-O2 -Wl,--gc-sections -Wl,--icf=all',
  355. '..',
  356. ],
  357. msvc_arch='x64')
  358. RunCommand(['ninja', 'install'], msvc_arch='x64')
  359.  
  360. libxml2_include_dir = os.path.join(libxml2_install_dir, 'include', 'libxml2')
  361. if sys.platform == 'win32':
  362. libxml2_lib = os.path.join(libxml2_install_dir, 'lib', 'libxml2s.lib')
  363. else:
  364. libxml2_lib = os.path.join(libxml2_install_dir, 'lib', 'libxml2.a')
  365. extra_cmake_flags = [
  366. '-DLLVM_ENABLE_LIBXML2=FORCE_ON',
  367. '-DLIBXML2_INCLUDE_DIR=' + libxml2_include_dir.replace('\\', '/'),
  368. '-DLIBXML2_LIBRARIES=' + libxml2_lib.replace('\\', '/'),
  369. ]
  370. extra_cflags = ['-DLIBXML_STATIC']
  371.  
  372. return extra_cmake_flags, extra_cflags
  373.  
  374.  
  375. def DownloadRPMalloc():
  376. """Download rpmalloc."""
  377. rpmalloc_dir = os.path.join(LLVM_BUILD_TOOLS_DIR, 'rpmalloc')
  378. if os.path.exists(rpmalloc_dir):
  379. RmTree(rpmalloc_dir)
  380.  
  381. # Using rpmalloc bc1923f rather than the latest release (1.4.1) because
  382. # it contains the fix for https://github.com/mjansson/rpmalloc/pull/186
  383. # which would cause lld to deadlock.
  384. # The zip file was created and uploaded as follows:
  385. # $ mkdir rpmalloc
  386. # $ curl -L https://github.com/mjansson/rpmalloc/archive/bc1923f436539327707b08ef9751a7a87bdd9d2f.tar.gz \
  387. # | tar -C rpmalloc --strip-components=1 -xzf -
  388. # $ GZIP=-9 tar vzcf rpmalloc-bc1923f.tgz rpmalloc
  389. # $ gsutil.py cp -n -a public-read rpmalloc-bc1923f.tgz \
  390. # gs://chromium-browser-clang/tools/
  391. zip_name = 'rpmalloc-bc1923f.tgz'
  392. DownloadAndUnpack(CDS_URL + '/tools/' + zip_name, LLVM_BUILD_TOOLS_DIR)
  393. rpmalloc_dir = rpmalloc_dir.replace('\\', '/')
  394. return rpmalloc_dir
  395.  
  396.  
  397. def DownloadPinnedClang():
  398. # The update.py in this current revision may have a patched revision while
  399. # building new clang packages. Get update.py off HEAD~ to pull the current
  400. # pinned clang.
  401. if not os.path.exists(PINNED_CLANG_DIR):
  402. os.mkdir(os.path.join(PINNED_CLANG_DIR))
  403.  
  404. script_path = os.path.join(PINNED_CLANG_DIR, 'update.py')
  405.  
  406. with open(script_path, 'w') as f:
  407. subprocess.check_call(
  408. ['git', 'show', 'HEAD~:tools/clang/scripts/update.py'],
  409. stdout=f,
  410. cwd=CHROMIUM_DIR)
  411. print("Running pinned update.py")
  412. subprocess.check_call(
  413. [sys.executable, script_path, '--output-dir=' + PINNED_CLANG_DIR])
  414.  
  415.  
  416. # TODO(crbug.com/929645): Remove once we don't need gcc's libstdc++.
  417. def MaybeDownloadHostGcc(args):
  418. """Download a modern GCC host compiler on Linux."""
  419. assert sys.platform.startswith('linux')
  420. if args.gcc_toolchain:
  421. return
  422. gcc_dir = os.path.join(LLVM_BUILD_TOOLS_DIR, 'gcc-10.2.0-bionic')
  423. if os.path.isdir(gcc_dir):
  424. RmTree(gcc_dir) # TODO(thakis): Remove this branch after a few weeks.
  425. if not os.path.exists(gcc_dir):
  426. DownloadAndUnpack(CDS_URL + '/tools/gcc-10.2.0-bionic.tgz', gcc_dir)
  427. args.gcc_toolchain = gcc_dir
  428.  
  429.  
  430. def VerifyVersionOfBuiltClangMatchesVERSION():
  431. """Checks that `clang --version` outputs RELEASE_VERSION. If this
  432. fails, update.RELEASE_VERSION is out-of-date and needs to be updated (possibly
  433. in an `if args.llvm_force_head_revision:` block inupdate. main() first)."""
  434. clang = os.path.join(LLVM_BUILD_DIR, 'bin', 'clang')
  435. if sys.platform == 'win32':
  436. clang += '-cl.exe'
  437. version_out = subprocess.check_output([clang, '--version'],
  438. universal_newlines=True)
  439. version_out = re.match(r'clang version ([0-9.]+)', version_out).group(1)
  440. if version_out != RELEASE_VERSION:
  441. print(('unexpected clang version %s (not %s), '
  442. 'update RELEASE_VERSION in update.py')
  443. % (version_out, RELEASE_VERSION))
  444. sys.exit(1)
  445.  
  446.  
  447. def VerifyZlibSupport():
  448. """Check that clang was built with zlib support enabled."""
  449. clang = os.path.join(LLVM_BUILD_DIR, 'bin', 'clang')
  450. test_file = '/dev/null'
  451. if sys.platform == 'win32':
  452. clang += '.exe'
  453. test_file = 'nul'
  454.  
  455. print('Checking for zlib support')
  456. clang_out = subprocess.check_output([
  457. clang, '-target', 'x86_64-unknown-linux-gnu', '-gz', '-c', '-###', '-x',
  458. 'c', test_file
  459. ],
  460. stderr=subprocess.STDOUT,
  461. universal_newlines=True)
  462. if (re.search(r'--compress-debug-sections', clang_out)):
  463. print('OK')
  464. else:
  465. print(('Failed to detect zlib support!\n\n(driver output: %s)') % clang_out)
  466. sys.exit(1)
  467.  
  468.  
  469. # TODO(https://crbug.com/1286289): remove once Chrome targets don't rely on
  470. # libstdc++.so existing in the clang package.
  471. def CopyLibstdcpp(args, build_dir):
  472. if not args.gcc_toolchain:
  473. return
  474. # Find libstdc++.so.6
  475. libstdcpp = subprocess.check_output([
  476. os.path.join(args.gcc_toolchain, 'bin', 'g++'),
  477. '-print-file-name=libstdc++.so.6'
  478. ],
  479. universal_newlines=True).rstrip()
  480.  
  481. EnsureDirExists(os.path.join(build_dir, 'lib'))
  482. CopyFile(libstdcpp, os.path.join(build_dir, 'lib'))
  483.  
  484.  
  485. def compiler_rt_cmake_flags(*, sanitizers, profile):
  486. # Don't set -DCOMPILER_RT_BUILD_BUILTINS=ON/OFF as it interferes with the
  487. # runtimes logic of building builtins.
  488. args = [
  489. # Build crtbegin/crtend. It's just two tiny TUs, so just enable this
  490. # everywhere, even though we only need it on Linux.
  491. 'COMPILER_RT_BUILD_CRT=ON',
  492. 'COMPILER_RT_BUILD_LIBFUZZER=OFF',
  493. 'COMPILER_RT_BUILD_MEMPROF=OFF',
  494. 'COMPILER_RT_BUILD_ORC=OFF',
  495. 'COMPILER_RT_BUILD_PROFILE=' + ('ON' if profile else 'OFF'),
  496. 'COMPILER_RT_BUILD_SANITIZERS=' + ('ON' if sanitizers else 'OFF'),
  497. 'COMPILER_RT_BUILD_XRAY=OFF',
  498. # See crbug.com/1205046: don't build scudo (and others we don't need).
  499. 'COMPILER_RT_SANITIZERS_TO_BUILD=asan;dfsan;msan;hwasan;tsan;cfi',
  500. # We explicitly list all targets we want to build, do not autodetect
  501. # targets.
  502. 'COMPILER_RT_DEFAULT_TARGET_ONLY=ON',
  503. ]
  504. return args
  505.  
  506.  
  507. def gn_arg(v):
  508. if v == 'True':
  509. return True
  510. if v == 'False':
  511. return False
  512. raise argparse.ArgumentTypeError('Expected one of %r or %r' % (
  513. 'True', 'False'))
  514.  
  515.  
  516. def main():
  517. parser = argparse.ArgumentParser(description='Build Clang.')
  518. parser.add_argument('--bootstrap', action='store_true',
  519. help='first build clang with CC, then with itself.')
  520. parser.add_argument('--build-mac-arm', action='store_true',
  521. help='Build arm binaries. Only valid on macOS.')
  522. parser.add_argument('--disable-asserts', action='store_true',
  523. help='build with asserts disabled')
  524. parser.add_argument('--host-cc',
  525. help='build with host C compiler, requires --host-cxx as '
  526. 'well')
  527. parser.add_argument('--host-cxx',
  528. help='build with host C++ compiler, requires --host-cc '
  529. 'as well')
  530. parser.add_argument('--gcc-toolchain', help='what gcc toolchain to use for '
  531. 'building; --gcc-toolchain=/opt/foo picks '
  532. '/opt/foo/bin/gcc')
  533. parser.add_argument('--pgo', action='store_true', help='build with PGO')
  534. parser.add_argument('--thinlto',
  535. action='store_true',
  536. help='build with ThinLTO')
  537. parser.add_argument('--llvm-force-head-revision', action='store_true',
  538. help='build the latest revision')
  539. parser.add_argument('--run-tests', action='store_true',
  540. help='run tests after building')
  541. parser.add_argument('--skip-build', action='store_true',
  542. help='do not build anything')
  543. parser.add_argument('--skip-checkout', action='store_true',
  544. help='do not create or update any checkouts')
  545. parser.add_argument('--build-dir',
  546. help='Override build directory')
  547. parser.add_argument('--extra-tools', nargs='*', default=[],
  548. help='select additional chrome tools to build')
  549. parser.add_argument('--use-system-cmake', action='store_true',
  550. help='use the cmake from PATH instead of downloading '
  551. 'and using prebuilt cmake binaries')
  552. parser.add_argument('--with-android', type=gn_arg, nargs='?', const=True,
  553. help='build the Android ASan runtime (linux only)',
  554. default=sys.platform.startswith('linux'))
  555. parser.add_argument('--with-fuchsia',
  556. type=gn_arg,
  557. nargs='?',
  558. const=True,
  559. help='build the Fuchsia runtimes (linux and mac only)',
  560. default=sys.platform.startswith('linux')
  561. or sys.platform.startswith('darwin'))
  562. parser.add_argument('--without-android', action='store_false',
  563. help='don\'t build Android ASan runtime (linux only)',
  564. dest='with_android')
  565. parser.add_argument('--without-fuchsia', action='store_false',
  566. help='don\'t build Fuchsia clang_rt runtime (linux/mac)',
  567. dest='with_fuchsia',
  568. default=sys.platform in ('linux2', 'darwin'))
  569. args = parser.parse_args()
  570.  
  571. global CLANG_REVISION, PACKAGE_VERSION, LLVM_BUILD_DIR
  572.  
  573. # TODO(crbug.com/1347737): Remove in next Clang roll.
  574. if args.llvm_force_head_revision:
  575. global RELEASE_VERSION
  576. RELEASE_VERSION = '16.0.0'
  577. old_lib_dir = os.path.join(LLVM_BUILD_DIR, 'lib', 'clang', '15.0.0')
  578. if (os.path.isdir(old_lib_dir)):
  579. print('Removing old lib dir: ', old_lib_dir)
  580. RmTree(old_lib_dir)
  581.  
  582. if (args.pgo or args.thinlto) and not args.bootstrap:
  583. print('--pgo/--thinlto requires --bootstrap')
  584. return 1
  585. if args.with_android and not os.path.exists(ANDROID_NDK_DIR):
  586. print('Android NDK not found at ' + ANDROID_NDK_DIR)
  587. print('The Android NDK is needed to build a Clang whose -fsanitize=address')
  588. print('works on Android. See ')
  589. print('https://www.chromium.org/developers/how-tos/android-build-instructions')
  590. print('for how to install the NDK, or pass --without-android.')
  591. return 1
  592.  
  593. if args.with_fuchsia and not os.path.exists(FUCHSIA_SDK_DIR):
  594. print('Fuchsia SDK not found at ' + FUCHSIA_SDK_DIR)
  595. print('The Fuchsia SDK is needed to build libclang_rt for Fuchsia.')
  596. print('Install the Fuchsia SDK by adding fuchsia to the ')
  597. print('target_os section in your .gclient and running hooks, ')
  598. print('or pass --without-fuchsia.')
  599. print(
  600. 'https://chromium.googlesource.com/chromium/src/+/main/docs/fuchsia/build_instructions.md'
  601. )
  602. print('for general Fuchsia build instructions.')
  603. return 1
  604.  
  605. if args.build_mac_arm and sys.platform != 'darwin':
  606. print('--build-mac-arm only valid on macOS')
  607. return 1
  608. if args.build_mac_arm and platform.machine() == 'arm64':
  609. print('--build-mac-arm only valid on intel to cross-build arm')
  610. return 1
  611.  
  612. # Don't buffer stdout, so that print statements are immediately flushed.
  613. # LLVM tests print output without newlines, so with buffering they won't be
  614. # immediately printed.
  615. major, _, _, _, _ = sys.version_info
  616. if major == 3:
  617. # Python3 only allows unbuffered output for binary streams. This
  618. # workaround comes from https://stackoverflow.com/a/181654/4052492.
  619. sys.stdout = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0),
  620. write_through=True)
  621. else:
  622. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
  623.  
  624. # The gnuwin package also includes curl, which is needed to interact with the
  625. # github API below.
  626. # TODO(crbug.com/1067752): Use urllib once certificates are fixed, and
  627. # move this down to where we fetch other build tools.
  628. AddGnuWinToPath()
  629.  
  630.  
  631. if args.build_dir:
  632. LLVM_BUILD_DIR = args.build_dir
  633.  
  634. if args.llvm_force_head_revision:
  635. checkout_revision = GetLatestLLVMCommit()
  636. else:
  637. checkout_revision = CLANG_REVISION
  638.  
  639. if not args.skip_checkout:
  640. CheckoutLLVM(checkout_revision, LLVM_DIR)
  641.  
  642. if args.llvm_force_head_revision:
  643. CLANG_REVISION = GetCommitDescription(checkout_revision)
  644. PACKAGE_VERSION = '%s-0' % CLANG_REVISION
  645.  
  646. print('Locally building clang %s...' % PACKAGE_VERSION)
  647. WriteStampFile('', STAMP_FILE)
  648. WriteStampFile('', FORCE_HEAD_REVISION_FILE)
  649.  
  650. AddCMakeToPath(args)
  651.  
  652.  
  653. if args.skip_build:
  654. return 0
  655.  
  656. # The variable "lld" is only used on Windows because only there does setting
  657. # CMAKE_LINKER have an effect: On Windows, the linker is called directly,
  658. # while elsewhere it's called through the compiler driver, and we pass
  659. # -fuse-ld=lld there to make the compiler driver call the linker (by setting
  660. # LLVM_ENABLE_LLD).
  661. cc, cxx, lld = None, None, None
  662.  
  663. cflags = []
  664. cxxflags = []
  665. ldflags = []
  666.  
  667. targets = 'AArch64;ARM;Mips;PowerPC;RISCV;SystemZ;WebAssembly;X86'
  668.  
  669. projects = 'clang;lld;polly;bolt'
  670. runtimes = 'compiler-rt'
  671.  
  672. base_cmake_args = [
  673. '-GNinja',
  674. '-DCMAKE_BUILD_TYPE=Release',
  675. '-DLLVM_ENABLE_ASSERTIONS=%s' % ('OFF' if args.disable_asserts else 'ON'),
  676. '-DLLVM_ENABLE_PROJECTS=' + projects,
  677. '-DLLVM_ENABLE_RUNTIMES=' + runtimes,
  678. '-DLLVM_TARGETS_TO_BUILD=' + targets,
  679. # PIC needed for Rust build (links LLVM into shared object)
  680. '-DLLVM_ENABLE_PIC=ON',
  681. '-DLLVM_ENABLE_UNWIND_TABLES=OFF',
  682. '-DLLVM_ENABLE_TERMINFO=OFF',
  683. '-DLLVM_ENABLE_Z3_SOLVER=OFF',
  684. '-DCLANG_PLUGIN_SUPPORT=OFF',
  685. '-DCLANG_ENABLE_STATIC_ANALYZER=OFF',
  686. '-DCLANG_ENABLE_ARCMT=OFF',
  687. '-DBUG_REPORT_URL=' + BUG_REPORT_URL,
  688. # Don't run Go bindings tests; PGO makes them confused.
  689. '-DLLVM_INCLUDE_GO_TESTS=OFF',
  690. # See crbug.com/1126219: Use native symbolizer instead of DIA
  691. '-DLLVM_ENABLE_DIA_SDK=OFF',
  692. # The default value differs per platform, force it off everywhere.
  693. '-DLLVM_ENABLE_PER_TARGET_RUNTIME_DIR=OFF',
  694. # Don't use curl.
  695. '-DLLVM_ENABLE_CURL=OFF',
  696. # Build libclang.a as well as libclang.so
  697. '-DLIBCLANG_BUILD_STATIC=ON',
  698. "-DLLVM_INCLUDE_BENCHMARKS=OFF",
  699. '-DLLVM_INCLUDE_EXAMPLES=OFF',
  700. '-DLLVM_INCLUDE_TESTS=OFF',
  701. '-DLLVM_POLLY_LINK_INTO_TOOLS=ON',
  702. "-DLLVM_ENABLE_EH=OFF",
  703. '-DLLVM_ENABLE_RTTI=OFF',
  704. '-DLLVM_CCACHE_BUILD=ON',
  705. '-DCMAKE_C_COMPILER=/usr/lib/llvm-15/bin/clang',
  706. '-DCMAKE_CXX_COMPILER=/usr/lib/llvm-15/bin/clang++',
  707. '-DCMAKE_AR=/usr/lib/llvm-15/bin/llvm-ar',
  708. '-DCMAKE_LINKER=/usr/lib/llvm-15/bin/ld.lld',
  709. '-DCMAKE_NM=/usr/lib/llvm-15/bin/llvm-nm',
  710. '-DCMAKE_OBJDUMP=/usr/lib/llvm-15/bin/llvm-objdump',
  711. '-DCMAKE_RANLIB=/usr/lib/llvm-15/bin/llvm-ranlib',
  712. '-DCMAKE_ASM_FLAGS_RELEASE=-O3 -DNDEBUG -w -march=znver2 -ffp-contract=fast -fdata-sections -ffunction-sections -fno-unique-section-names -fmerge-all-constants -flto=thin -fsplit-lto-unit',
  713. '-DCMAKE_C_FLAGS_RELEASE=-O3 -DNDEBUG -w -march=znver2 -ffp-contract=fast -fdata-sections -ffunction-sections -fno-unique-section-names -fmerge-all-constants -flto=thin -fsplit-lto-unit',
  714. '-DCMAKE_CXX_FLAGS_RELEASE=-O3 -DNDEBUG -w -march=znver2 -ffp-contract=fast -fdata-sections -ffunction-sections -fno-unique-section-names -flto=thin -fsplit-lto-unit',
  715. '-DCMAKE_EXE_LINKER_FLAGS_RELEASE=-Wl,-O2 -Wl,--gc-sections -Wl,--icf=all -flto=thin -fwhole-program-vtables -Wl,-mllvm,-import-instr-limit=30 -Wl,--lto-O3 -Wl,--thinlto-jobs=16 -Wl,--thinlto-cache-dir=/tmp/thinlto-cache -Wl,--thinlto-cache-policy=cache_size_bytes=100g -Wl,-mllvm,-polly -Wl,-mllvm,-polly-detect-profitability-min-per-loop-insts=40 -Wl,-mllvm,-polly-invariant-load-hoisting -Wl,-mllvm,-polly-vectorizer=stripmine',
  716. '-DCMAKE_SHARED_LINKER_FLAGS_RELEASE=-Wl,-O2 -Wl,--gc-sections -Wl,--icf=all -flto=thin -fwhole-program-vtables -Wl,-mllvm,-import-instr-limit=30 -Wl,--lto-O3 -Wl,--thinlto-jobs=16 -Wl,--thinlto-cache-dir=/tmp/thinlto-cache -Wl,--thinlto-cache-policy=cache_size_bytes=100g -Wl,-mllvm,-polly -Wl,-mllvm,-polly-detect-profitability-min-per-loop-insts=40 -Wl,-mllvm,-polly-invariant-load-hoisting -Wl,-mllvm,-polly-vectorizer=stripmine',
  717. '-DCMAKE_MODULE_LINKER_FLAGS_RELEASE=-Wl,-O2 -Wl,--gc-sections -Wl,--icf=all -flto=thin -fwhole-program-vtables -Wl,-mllvm,-import-instr-limit=30 -Wl,--lto-O3 -Wl,--thinlto-jobs=16 -Wl,--thinlto-cache-dir=/tmp/thinlto-cache -Wl,--thinlto-cache-policy=cache_size_bytes=100g -Wl,-mllvm,-polly -Wl,-mllvm,-polly-detect-profitability-min-per-loop-insts=40 -Wl,-mllvm,-polly-invariant-load-hoisting -Wl,-mllvm,-polly-vectorizer=stripmine',
  718. '-DLLVM_PARALLEL_LINK_JOBS=2',
  719. ]
  720.  
  721. if sys.platform == 'darwin':
  722. isysroot = subprocess.check_output(['xcrun', '--show-sdk-path'],
  723. universal_newlines=True).rstrip()
  724.  
  725. # clang only automatically links to libc++ when targeting OS X 10.9+, so
  726. # add stdlib=libc++ explicitly so clang can run on OS X versions as old as
  727. # 10.7.
  728. cxxflags += ['-stdlib=libc++']
  729. ldflags += ['-stdlib=libc++']
  730.  
  731.  
  732. # See https://crbug.com/1302636#c49 - #c56 -- intercepting crypt_r() does not
  733. # work with the sysroot for not fully understood reasons. Disable it.
  734. sanitizers_override = [
  735. '-DSANITIZER_OVERRIDE_INTERCEPTORS',
  736. '-I' + os.path.join(THIS_DIR, 'sanitizers'),
  737. ]
  738. cflags += sanitizers_override
  739. cxxflags += sanitizers_override
  740.  
  741. if args.host_cc or args.host_cxx:
  742. assert args.host_cc and args.host_cxx, \
  743. "--host-cc and --host-cxx need to be used together"
  744. cc = args.host_cc
  745. cxx = args.host_cxx
  746. else:
  747. DownloadPinnedClang()
  748. if sys.platform == 'win32':
  749. cc = os.path.join(PINNED_CLANG_DIR, 'bin', 'clang-cl.exe')
  750. cxx = os.path.join(PINNED_CLANG_DIR, 'bin', 'clang-cl.exe')
  751. lld = os.path.join(PINNED_CLANG_DIR, 'bin', 'lld-link.exe')
  752. # CMake has a hard time with backslashes in compiler paths:
  753. # https://stackoverflow.com/questions/13050827
  754. cc = cc.replace('\\', '/')
  755. cxx = cxx.replace('\\', '/')
  756. lld = lld.replace('\\', '/')
  757. else:
  758. cc = os.path.join(PINNED_CLANG_DIR, 'bin', 'clang')
  759. cxx = os.path.join(PINNED_CLANG_DIR, 'bin', 'clang++')
  760.  
  761. if sys.platform.startswith('linux'):
  762. MaybeDownloadHostGcc(args)
  763. base_cmake_args += [ '-DLLVM_STATIC_LINK_CXX_STDLIB=ON' ]
  764.  
  765. if sys.platform != 'darwin':
  766. # The host clang has lld, but self-hosting with lld is still slightly
  767. # broken on mac.
  768. # TODO: check if this works now.
  769. base_cmake_args.append('-DLLVM_ENABLE_LLD=ON')
  770.  
  771. if sys.platform.startswith('linux'):
  772. # Download sysroots. This uses basically Chromium's sysroots, but with
  773. # minor changes:
  774. # - glibc version bumped to 2.18 to make __cxa_thread_atexit_impl
  775. # work (clang can require 2.18; chromium currently doesn't)
  776. # - libcrypt.so.1 reversioned so that crypt() is picked up from glibc
  777. # The sysroot was built at
  778. # https://chromium-review.googlesource.com/c/chromium/src/+/3684954/1
  779. # and the hashes here are from sysroots.json in that CL.
  780. toolchain_bucket = 'https://commondatastorage.googleapis.com/chrome-linux-sysroot/toolchain/'
  781.  
  782. # amd64
  783. # hash from https://chromium-review.googlesource.com/c/chromium/src/+/3684954/1/build/linux/sysroot_scripts/sysroots.json#3
  784. toolchain_hash = '2028cdaf24259d23adcff95393b8cc4f0eef714b'
  785. toolchain_name = 'debian_bullseye_amd64_sysroot'
  786. U = toolchain_bucket + toolchain_hash + '/' + toolchain_name + '.tar.xz'
  787. sysroot_amd64 = os.path.join(LLVM_BUILD_TOOLS_DIR, toolchain_name)
  788. DownloadAndUnpack(U, sysroot_amd64)
  789.  
  790. # i386
  791. # hash from https://chromium-review.googlesource.com/c/chromium/src/+/3684954/1/build/linux/sysroot_scripts/sysroots.json#23
  792. toolchain_hash = 'a033618b5e092c86e96d62d3c43f7363df6cebe7'
  793. toolchain_name = 'debian_bullseye_i386_sysroot'
  794. U = toolchain_bucket + toolchain_hash + '/' + toolchain_name + '.tar.xz'
  795. sysroot_i386 = os.path.join(LLVM_BUILD_TOOLS_DIR, toolchain_name)
  796. DownloadAndUnpack(U, sysroot_i386)
  797.  
  798. # arm
  799. # hash from https://chromium-review.googlesource.com/c/chromium/src/+/3684954/1/build/linux/sysroot_scripts/sysroots.json#8
  800. toolchain_hash = '0b9a3c54d2d5f6b1a428369aaa8d7ba7b227f701'
  801. toolchain_name = 'debian_bullseye_arm_sysroot'
  802. U = toolchain_bucket + toolchain_hash + '/' + toolchain_name + '.tar.xz'
  803. sysroot_arm = os.path.join(LLVM_BUILD_TOOLS_DIR, toolchain_name)
  804. DownloadAndUnpack(U, sysroot_arm)
  805.  
  806. # arm64
  807. # hash from https://chromium-review.googlesource.com/c/chromium/src/+/3684954/1/build/linux/sysroot_scripts/sysroots.json#12
  808. toolchain_hash = '0e28d9832614729bb5b731161ff96cb4d516f345'
  809. toolchain_name = 'debian_bullseye_arm64_sysroot'
  810. U = toolchain_bucket + toolchain_hash + '/' + toolchain_name + '.tar.xz'
  811. sysroot_arm64 = os.path.join(LLVM_BUILD_TOOLS_DIR, toolchain_name)
  812. DownloadAndUnpack(U, sysroot_arm64)
  813.  
  814. # Add the sysroot to base_cmake_args.
  815. if platform.machine() == 'aarch64':
  816. base_cmake_args.append('-DCMAKE_SYSROOT=' + sysroot_arm64)
  817. else:
  818. # amd64 is the default toolchain.
  819. base_cmake_args.append('-DCMAKE_SYSROOT=' + sysroot_amd64)
  820.  
  821. if sys.platform == 'win32':
  822. base_cmake_args.append('-DLLVM_USE_CRT_RELEASE=MT')
  823.  
  824. # Require zlib compression.
  825. zlib_dir = AddZlibToPath()
  826. cflags.append('-I' + zlib_dir)
  827. cxxflags.append('-I' + zlib_dir)
  828. ldflags.append('-LIBPATH:' + zlib_dir)
  829.  
  830. # Use rpmalloc. For faster ThinLTO linking.
  831. rpmalloc_dir = DownloadRPMalloc()
  832. base_cmake_args.append('-DLLVM_INTEGRATED_CRT_ALLOC=' + rpmalloc_dir)
  833.  
  834. # Statically link libxml2 to make lld-link not require mt.exe on Windows,
  835. # and to make sure lld-link output on other platforms is identical to
  836. # lld-link on Windows (for cross-builds).
  837. libxml_cmake_args, libxml_cflags = BuildLibXml2()
  838. base_cmake_args += libxml_cmake_args
  839. cflags += libxml_cflags
  840. cxxflags += libxml_cflags
  841.  
  842. if args.bootstrap:
  843. print('Building bootstrap compiler')
  844. if os.path.exists(LLVM_BOOTSTRAP_DIR):
  845. RmTree(LLVM_BOOTSTRAP_DIR)
  846. EnsureDirExists(LLVM_BOOTSTRAP_DIR)
  847. os.chdir(LLVM_BOOTSTRAP_DIR)
  848.  
  849. projects = 'clang'
  850. runtimes = ''
  851. if args.pgo or sys.platform == 'darwin':
  852. # Need libclang_rt.profile for PGO.
  853. # On macOS, the bootstrap toolchain needs to have compiler-rt because
  854. # dsymutil's link needs libclang_rt.osx.a. Only the x86_64 osx
  855. # libraries are needed though, and only libclang_rt (i.e.
  856. # COMPILER_RT_BUILD_BUILTINS).
  857. runtimes += ';compiler-rt'
  858. if sys.platform != 'darwin':
  859. projects += ';lld'
  860.  
  861. bootstrap_targets = 'X86'
  862. if sys.platform == 'darwin':
  863. # Need ARM and AArch64 for building the ios clang_rt.
  864. bootstrap_targets += ';ARM;AArch64'
  865. bootstrap_args = base_cmake_args + [
  866. '-DLLVM_TARGETS_TO_BUILD=' + bootstrap_targets,
  867. '-DLLVM_ENABLE_PROJECTS=' + projects,
  868. '-DLLVM_ENABLE_RUNTIMES=' + runtimes,
  869. '-DCMAKE_INSTALL_PREFIX=' + LLVM_BOOTSTRAP_INSTALL_DIR,
  870. '-DCMAKE_C_FLAGS=' + ' '.join(cflags),
  871. '-DCMAKE_CXX_FLAGS=' + ' '.join(cxxflags),
  872. '-DCMAKE_EXE_LINKER_FLAGS=' + ' '.join(ldflags),
  873. '-DCMAKE_SHARED_LINKER_FLAGS=' + ' '.join(ldflags),
  874. '-DCMAKE_MODULE_LINKER_FLAGS=' + ' '.join(ldflags),
  875. # Ignore args.disable_asserts for the bootstrap compiler.
  876. '-DLLVM_ENABLE_ASSERTIONS=ON',
  877. ]
  878. # PGO needs libclang_rt.profile but none of the other compiler-rt stuff.
  879. bootstrap_args.extend([
  880. '-D' + f
  881. for f in compiler_rt_cmake_flags(sanitizers=False, profile=args.pgo)
  882. ])
  883. if sys.platform == 'darwin':
  884. bootstrap_args.extend([
  885. '-DCOMPILER_RT_ENABLE_IOS=OFF',
  886. '-DCOMPILER_RT_ENABLE_WATCHOS=OFF',
  887. '-DCOMPILER_RT_ENABLE_TVOS=OFF',
  888. ])
  889. if platform.machine() == 'arm64':
  890. bootstrap_args.extend(['-DDARWIN_osx_ARCHS=arm64'])
  891. else:
  892. bootstrap_args.extend(['-DDARWIN_osx_ARCHS=x86_64'])
  893.  
  894. if cc is not None: bootstrap_args.append('-DCMAKE_C_COMPILER=' + cc)
  895. if cxx is not None: bootstrap_args.append('-DCMAKE_CXX_COMPILER=' + cxx)
  896. if lld is not None: bootstrap_args.append('-DCMAKE_LINKER=' + lld)
  897. RunCommand(['cmake'] + bootstrap_args + [os.path.join(LLVM_DIR, 'llvm')],
  898. msvc_arch='x64')
  899. RunCommand(['ninja'], msvc_arch='x64')
  900. if args.run_tests:
  901. RunCommand(['ninja', 'check-all'], msvc_arch='x64')
  902. RunCommand(['ninja', 'install'], msvc_arch='x64')
  903.  
  904. if sys.platform == 'win32':
  905. cc = os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'bin', 'clang-cl.exe')
  906. cxx = os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'bin', 'clang-cl.exe')
  907. lld = os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'bin', 'lld-link.exe')
  908. # CMake has a hard time with backslashes in compiler paths:
  909. # https://stackoverflow.com/questions/13050827
  910. cc = cc.replace('\\', '/')
  911. cxx = cxx.replace('\\', '/')
  912. lld = lld.replace('\\', '/')
  913. else:
  914. cc = os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'bin', 'clang')
  915. cxx = os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'bin', 'clang++')
  916.  
  917. print('Bootstrap compiler installed.')
  918.  
  919. if args.pgo:
  920. print('Building instrumented compiler')
  921. if os.path.exists(LLVM_INSTRUMENTED_DIR):
  922. RmTree(LLVM_INSTRUMENTED_DIR)
  923. EnsureDirExists(LLVM_INSTRUMENTED_DIR)
  924. os.chdir(LLVM_INSTRUMENTED_DIR)
  925.  
  926. projects = 'clang'
  927.  
  928. instrument_args = base_cmake_args + [
  929. '-DLLVM_ENABLE_PROJECTS=' + projects,
  930. '-DCMAKE_C_FLAGS=' + ' '.join(cflags),
  931. '-DCMAKE_CXX_FLAGS=' + ' '.join(cxxflags),
  932. '-DCMAKE_EXE_LINKER_FLAGS=' + ' '.join(ldflags),
  933. '-DCMAKE_SHARED_LINKER_FLAGS=' + ' '.join(ldflags),
  934. '-DCMAKE_MODULE_LINKER_FLAGS=' + ' '.join(ldflags),
  935. # Build with instrumentation.
  936. '-DLLVM_BUILD_INSTRUMENTED=IR',
  937. ]
  938. # Build with the bootstrap compiler.
  939. if cc is not None: instrument_args.append('-DCMAKE_C_COMPILER=' + cc)
  940. if cxx is not None: instrument_args.append('-DCMAKE_CXX_COMPILER=' + cxx)
  941. if lld is not None: instrument_args.append('-DCMAKE_LINKER=' + lld)
  942.  
  943. RunCommand(['cmake'] + instrument_args + [os.path.join(LLVM_DIR, 'llvm')],
  944. msvc_arch='x64')
  945. RunCommand(['ninja', 'clang'], msvc_arch='x64')
  946. print('Instrumented compiler built.')
  947.  
  948. # Train by building some C++ code.
  949. #
  950. # pgo_training-1.ii is a preprocessed (on Linux) version of
  951. # src/third_party/blink/renderer/core/layout/layout_object.cc, selected
  952. # because it's a large translation unit in Blink, which is normally the
  953. # slowest part of Chromium to compile. Using this, we get ~20% shorter
  954. # build times for Linux, Android, and Mac, which is also what we got when
  955. # training by actually building a target in Chromium. (For comparison, a
  956. # C++-y "Hello World" program only resulted in 14% faster builds.)
  957. # See https://crbug.com/966403#c16 for all numbers.
  958. #
  959. # Although the training currently only exercises Clang, it does involve LLVM
  960. # internals, and so LLD also benefits when used for ThinLTO links.
  961. #
  962. # NOTE: Tidy uses binaries built with this profile, but doesn't seem to
  963. # gain much from it. If tidy's execution time becomes a concern, it might
  964. # be good to investigate that.
  965. #
  966. # TODO(hans): Enhance the training, perhaps by including preprocessed code
  967. # from more platforms, and by doing some linking so that lld can benefit
  968. # from PGO as well. Perhaps the training could be done asynchronously by
  969. # dedicated buildbots that upload profiles to the cloud.
  970. training_source = 'pgo_training-1.ii'
  971. with open(training_source, 'wb') as f:
  972. DownloadUrl(CDS_URL + '/' + training_source, f)
  973. train_cmd = [os.path.join(LLVM_INSTRUMENTED_DIR, 'bin', 'clang++'),
  974. '-target', 'x86_64-unknown-unknown', '-O2', '-g', '-std=c++14',
  975. '-fno-exceptions', '-fno-rtti', '-w', '-c', training_source]
  976. if sys.platform == 'darwin':
  977. train_cmd.extend(['-stdlib=libc++', '-isysroot', isysroot])
  978. RunCommand(train_cmd, msvc_arch='x64')
  979.  
  980. # Merge profiles.
  981. profdata = os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'bin', 'llvm-profdata')
  982. RunCommand([profdata, 'merge', '-output=' + LLVM_PROFDATA_FILE] +
  983. glob.glob(os.path.join(LLVM_INSTRUMENTED_DIR, 'profiles',
  984. '*.profraw')), msvc_arch='x64')
  985. print('Profile generated.')
  986.  
  987. deployment_target = '10.7'
  988.  
  989. # If building at head, define a macro that plugins can use for #ifdefing
  990. # out code that builds at head, but not at CLANG_REVISION or vice versa.
  991. if args.llvm_force_head_revision:
  992. cflags += ['-DLLVM_FORCE_HEAD_REVISION']
  993. cxxflags += ['-DLLVM_FORCE_HEAD_REVISION']
  994.  
  995. # Build PDBs for archival on Windows. Don't use RelWithDebInfo since it
  996. # has different optimization defaults than Release.
  997. # Also disable stack cookies (/GS-) for performance.
  998. if sys.platform == 'win32':
  999. cflags += ['/Zi', '/GS-']
  1000. cxxflags += ['/Zi', '/GS-']
  1001. ldflags += ['/DEBUG', '/OPT:REF', '/OPT:ICF']
  1002.  
  1003. deployment_env = None
  1004. if deployment_target:
  1005. deployment_env = os.environ.copy()
  1006. deployment_env['MACOSX_DEPLOYMENT_TARGET'] = deployment_target
  1007.  
  1008. print('Building final compiler.')
  1009.  
  1010. default_tools = []
  1011. chrome_tools = list(set(default_tools + args.extra_tools))
  1012. if cc is not None: base_cmake_args.append('-DCMAKE_C_COMPILER=' + cc)
  1013. if cxx is not None: base_cmake_args.append('-DCMAKE_CXX_COMPILER=' + cxx)
  1014. if lld is not None: base_cmake_args.append('-DCMAKE_LINKER=' + lld)
  1015. cmake_args = base_cmake_args + [
  1016. '-DCMAKE_C_FLAGS=' + ' '.join(cflags),
  1017. '-DCMAKE_CXX_FLAGS=' + ' '.join(cxxflags),
  1018. '-DCMAKE_EXE_LINKER_FLAGS=' + ' '.join(ldflags),
  1019. '-DCMAKE_SHARED_LINKER_FLAGS=' + ' '.join(ldflags),
  1020. '-DCMAKE_MODULE_LINKER_FLAGS=' + ' '.join(ldflags),
  1021. '-DCMAKE_INSTALL_PREFIX=' + LLVM_BUILD_DIR,
  1022. '-DLLVM_EXTERNAL_PROJECTS=chrometools',
  1023. '-DLLVM_EXTERNAL_CHROMETOOLS_SOURCE_DIR=' +
  1024. os.path.join(CHROMIUM_DIR, 'tools', 'clang'),
  1025. '-DCHROMIUM_TOOLS=%s' % ';'.join(chrome_tools)]
  1026. if args.pgo:
  1027. cmake_args.append('-DLLVM_PROFDATA_FILE=' + LLVM_PROFDATA_FILE)
  1028. if args.thinlto:
  1029. cmake_args.append('-DLLVM_ENABLE_LTO=Thin')
  1030. if sys.platform == 'win32':
  1031. cmake_args.append('-DLLVM_ENABLE_ZLIB=FORCE_ON')
  1032.  
  1033. if args.build_mac_arm:
  1034. assert platform.machine() != 'arm64', 'build_mac_arm for cross build only'
  1035. cmake_args += [
  1036. '-DCMAKE_OSX_ARCHITECTURES=arm64', '-DCMAKE_SYSTEM_NAME=Darwin'
  1037. ]
  1038.  
  1039. # The default LLVM_DEFAULT_TARGET_TRIPLE depends on the host machine.
  1040. # Set it explicitly to make the build of clang more hermetic, and also to
  1041. # set it to arm64 when cross-building clang for mac/arm.
  1042. if sys.platform == 'darwin':
  1043. if args.build_mac_arm or platform.machine() == 'arm64':
  1044. cmake_args.append('-DLLVM_DEFAULT_TARGET_TRIPLE=arm64-apple-darwin')
  1045. else:
  1046. cmake_args.append('-DLLVM_DEFAULT_TARGET_TRIPLE=x86_64-apple-darwin')
  1047. elif sys.platform.startswith('linux'):
  1048. if platform.machine() == 'aarch64':
  1049. cmake_args.append(
  1050. '-DLLVM_DEFAULT_TARGET_TRIPLE=aarch64-unknown-linux-gnu')
  1051. elif platform.machine() == 'riscv64':
  1052. cmake_args.append(
  1053. '-DLLVM_DEFAULT_TARGET_TRIPLE=riscv64-unknown-linux-gnu')
  1054. else:
  1055. cmake_args.append('-DLLVM_DEFAULT_TARGET_TRIPLE=x86_64-unknown-linux-gnu')
  1056. cmake_args.append('-DLLVM_ENABLE_PER_TARGET_RUNTIME_DIR=ON')
  1057. elif sys.platform == 'win32':
  1058. cmake_args.append('-DLLVM_DEFAULT_TARGET_TRIPLE=x86_64-pc-windows-msvc')
  1059.  
  1060. # List of (triple, list of CMake vars without '-D').
  1061. runtimes_triples_args = []
  1062.  
  1063. if sys.platform.startswith('linux'):
  1064. runtimes_triples_args.append(
  1065. ('i386-unknown-linux-gnu',
  1066. compiler_rt_cmake_flags(sanitizers=True, profile=True) + [
  1067. 'CMAKE_SYSROOT=%s' % sysroot_i386,
  1068. ]))
  1069. runtimes_triples_args.append(
  1070. ('x86_64-unknown-linux-gnu',
  1071. compiler_rt_cmake_flags(sanitizers=True, profile=True) + [
  1072. 'CMAKE_SYSROOT=%s' % sysroot_amd64,
  1073. ]))
  1074. runtimes_triples_args.append(
  1075. # Using "armv7a-unknown-linux-gnueabhihf" confuses the compiler-rt
  1076. # builtins build, since compiler-rt/cmake/builtin-config-ix.cmake
  1077. # doesn't include "armv7a" in its `ARM32` list.
  1078. # TODO(thakis): It seems to work for everything else though, see try
  1079. # results on
  1080. # https://chromium-review.googlesource.com/c/chromium/src/+/3702739/4
  1081. # Maybe it should work for builtins too?
  1082. ('armv7-unknown-linux-gnueabihf',
  1083. compiler_rt_cmake_flags(sanitizers=True, profile=True) + [
  1084. 'CMAKE_SYSROOT=%s' % sysroot_arm,
  1085. ]))
  1086. runtimes_triples_args.append(
  1087. ('aarch64-unknown-linux-gnu',
  1088. compiler_rt_cmake_flags(sanitizers=True, profile=True) + [
  1089. 'CMAKE_SYSROOT=%s' % sysroot_arm64,
  1090. ]))
  1091. elif sys.platform == 'win32':
  1092. runtimes_triples_args.append(
  1093. ('i386-pc-windows-msvc',
  1094. compiler_rt_cmake_flags(sanitizers=False, profile=True) + [
  1095. 'LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=OFF',
  1096. ]))
  1097. runtimes_triples_args.append(
  1098. ('x86_64-pc-windows-msvc',
  1099. compiler_rt_cmake_flags(sanitizers=True, profile=True) + [
  1100. 'LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=OFF',
  1101. ]))
  1102. elif sys.platform == 'darwin':
  1103. compiler_rt_args = [
  1104. 'SANITIZER_MIN_OSX_VERSION=10.7',
  1105. 'COMPILER_RT_ENABLE_MACCATALYST=ON',
  1106. 'COMPILER_RT_ENABLE_IOS=ON',
  1107. 'COMPILER_RT_ENABLE_WATCHOS=OFF',
  1108. 'COMPILER_RT_ENABLE_TVOS=OFF',
  1109. 'DARWIN_ios_ARCHS=arm64',
  1110. 'DARWIN_iossim_ARCHS=arm64;x86_64',
  1111. 'DARWIN_osx_ARCHS=arm64;x86_64',
  1112. ] + compiler_rt_cmake_flags(sanitizers=True, profile=True)
  1113. # compiler-rt is built for all platforms/arches with a single
  1114. # configuration, we should only specify one target triple. 'default' is
  1115. # specially handled.
  1116. runtimes_triples_args.append(('default', compiler_rt_args))
  1117.  
  1118. if args.with_android:
  1119. toolchain_dir = ANDROID_NDK_DIR + '/toolchains/llvm/prebuilt/linux-x86_64'
  1120. for target_arch in ['aarch64', 'arm', 'i686', 'x86_64']:
  1121. target_triple = target_arch
  1122. if target_arch == 'arm':
  1123. target_triple = 'armv7'
  1124. api_level = '19'
  1125. if target_arch == 'aarch64' or target_arch == 'x86_64':
  1126. api_level = '21'
  1127. target_triple += '-linux-android' + api_level
  1128. cflags = [
  1129. '--sysroot=%s/sysroot' % toolchain_dir,
  1130.  
  1131. # We don't have an unwinder ready, and don't need it either.
  1132. '--unwindlib=none',
  1133. ]
  1134.  
  1135. if target_arch == 'aarch64':
  1136. # Use PAC/BTI instructions for AArch64
  1137. cflags += [ '-mbranch-protection=standard' ]
  1138.  
  1139. android_args = compiler_rt_cmake_flags(sanitizers=True, profile=True) + [
  1140. 'LLVM_ENABLE_RUNTIMES=compiler-rt',
  1141. # On Android, we want DWARF info for the builtins for unwinding. See
  1142. # crbug.com/1311807.
  1143. 'CMAKE_BUILD_TYPE=RelWithDebInfo',
  1144. 'CMAKE_C_FLAGS=' + ' '.join(cflags),
  1145. 'CMAKE_CXX_FLAGS=' + ' '.join(cflags),
  1146. 'CMAKE_ASM_FLAGS=' + ' '.join(cflags),
  1147. 'COMPILER_RT_USE_BUILTINS_LIBRARY=ON',
  1148. 'SANITIZER_CXX_ABI=libcxxabi',
  1149. 'CMAKE_SHARED_LINKER_FLAGS=-Wl,-u__cxa_demangle',
  1150. 'ANDROID=1',
  1151. 'LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=OFF',
  1152. 'LLVM_INCLUDE_TESTS=OFF',
  1153. # This prevents static_asserts from firing in 32-bit builds.
  1154. # TODO: remove once we only support API >=24.
  1155. 'ANDROID_NATIVE_API_LEVEL=' + api_level,
  1156. ]
  1157.  
  1158. runtimes_triples_args.append((target_triple, android_args))
  1159.  
  1160. if args.with_fuchsia:
  1161. # Fuchsia links against libclang_rt.builtins-<arch>.a instead of libgcc.a.
  1162. for target_arch in ['aarch64', 'x86_64']:
  1163. fuchsia_arch_name = {'aarch64': 'arm64', 'x86_64': 'x64'}[target_arch]
  1164. toolchain_dir = os.path.join(
  1165. FUCHSIA_SDK_DIR, 'arch', fuchsia_arch_name, 'sysroot')
  1166. target_triple = target_arch + '-unknown-fuchsia'
  1167. # Build the Fuchsia profile and asan runtimes. This is done after the rt
  1168. # builtins have been created because the CMake build runs link checks that
  1169. # require that the builtins already exist to succeed.
  1170. # TODO(thakis): Figure out why this doesn't build with the stage0
  1171. # compiler in arm cross builds.
  1172. build_profile = target_arch == 'x86_64' and not args.build_mac_arm
  1173. # Build the asan runtime only on non-Mac platforms. Macs are excluded
  1174. # because the asan install changes library RPATHs which CMake only
  1175. # supports on ELF platforms and MacOS uses Mach-O instead of ELF.
  1176. build_sanitizers = build_profile and sys.platform != 'darwin'
  1177. # TODO(thakis): Might have to pass -B here once sysroot contains
  1178. # binaries (e.g. gas for arm64?)
  1179. fuchsia_args = compiler_rt_cmake_flags(
  1180. sanitizers=build_sanitizers, profile=build_profile
  1181. ) + [
  1182. 'LLVM_ENABLE_RUNTIMES=compiler-rt',
  1183. 'CMAKE_SYSTEM_NAME=Fuchsia',
  1184. 'CMAKE_SYSROOT=%s' % toolchain_dir,
  1185. # TODO(thakis|scottmg): Use PER_TARGET_RUNTIME_DIR for all platforms.
  1186. # https://crbug.com/882485.
  1187. 'LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=ON',
  1188. ]
  1189. if build_sanitizers:
  1190. fuchsia_args.append('SANITIZER_NO_UNDEFINED_SYMBOLS=OFF')
  1191.  
  1192. runtimes_triples_args.append((target_triple, fuchsia_args))
  1193.  
  1194. # Convert FOO=BAR CMake flags per triple into
  1195. # -DBUILTINS_$triple_FOO=BAR/-DRUNTIMES_$triple_FOO=BAR and build up
  1196. # -DLLVM_BUILTIN_TARGETS/-DLLVM_RUNTIME_TARGETS.
  1197. all_triples = ''
  1198. for (triple, a) in runtimes_triples_args:
  1199. all_triples += ';' + triple
  1200. for arg in a:
  1201. assert not arg.startswith('-')
  1202. # 'default' is specially handled to pass through relevant CMake flags.
  1203. if triple == 'default':
  1204. cmake_args.append('-D' + arg)
  1205. else:
  1206. cmake_args.append('-DBUILTINS_' + triple + '_' + arg)
  1207. cmake_args.append('-DRUNTIMES_' + triple + '_' + arg)
  1208. cmake_args.append('-DLLVM_BUILTIN_TARGETS=' + all_triples)
  1209. cmake_args.append('-DLLVM_RUNTIME_TARGETS=' + all_triples)
  1210.  
  1211. if os.path.exists(LLVM_BUILD_DIR):
  1212. RmTree(LLVM_BUILD_DIR)
  1213. EnsureDirExists(LLVM_BUILD_DIR)
  1214. os.chdir(LLVM_BUILD_DIR)
  1215. RunCommand(['cmake'] + cmake_args + [os.path.join(LLVM_DIR, 'llvm')],
  1216. msvc_arch='x64',
  1217. env=deployment_env)
  1218. CopyLibstdcpp(args, LLVM_BUILD_DIR)
  1219. RunCommand(['ninja'], msvc_arch='x64')
  1220.  
  1221. if chrome_tools:
  1222. # If any Chromium tools were built, install those now.
  1223. RunCommand(['ninja', 'cr-install'], msvc_arch='x64')
  1224.  
  1225. if not args.build_mac_arm:
  1226. VerifyVersionOfBuiltClangMatchesVERSION()
  1227. VerifyZlibSupport()
  1228.  
  1229. # Run tests.
  1230. if (not args.build_mac_arm and
  1231. (args.run_tests or args.llvm_force_head_revision)):
  1232. RunCommand(['ninja', '-C', LLVM_BUILD_DIR, 'cr-check-all'], msvc_arch='x64')
  1233.  
  1234. if not args.build_mac_arm and args.run_tests:
  1235. env = None
  1236. if sys.platform.startswith('linux'):
  1237. env = os.environ.copy()
  1238. # See SANITIZER_OVERRIDE_INTERCEPTORS above: We disable crypt_r()
  1239. # interception, so its tests can't pass.
  1240. env['LIT_FILTER_OUT'] = ('^SanitizerCommon-(a|l|m|ub|t)san-x86_64-Linux' +
  1241. ' :: Linux/crypt_r.cpp$')
  1242. RunCommand(['ninja', '-C', LLVM_BUILD_DIR, 'check-all'],
  1243. env=env,
  1244. msvc_arch='x64')
  1245.  
  1246. WriteStampFile(PACKAGE_VERSION, STAMP_FILE)
  1247. WriteStampFile(PACKAGE_VERSION, FORCE_HEAD_REVISION_FILE)
  1248. print('Clang build was successful.')
  1249. return 0
  1250.  
  1251.  
  1252. if __name__ == '__main__':
  1253. sys.exit(main())
  1254.  
Add Comment
Please, Sign In to add comment