File: get_llvm_flags.py

package info (click to toggle)
perfetto 54.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 133,812 kB
  • sloc: cpp: 338,350; python: 74,464; sql: 46,895; ansic: 18,340; javascript: 2,557; java: 2,160; sh: 1,444; yacc: 776; xml: 563; makefile: 226
file content (77 lines) | stat: -rw-r--r-- 2,324 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import sys
import subprocess
import os


def run_llvm_config(args):
  """
  Runs llvm-config with the given arguments and returns its stripped stdout.
  Exits the script if llvm-config is not found or returns an error.
  """
  try:
    return subprocess.check_output(
        ["llvm-config"] + args,
        text=True,  # Decode output as text (Python 3)
    ).strip()
  except (subprocess.CalledProcessError, FileNotFoundError) as e:
    sys.stderr.write(f"Error: Failed to run 'llvm-config {' '.join(args)}'.\n")
    if isinstance(e, subprocess.CalledProcessError):
      sys.stderr.write(f"STDOUT: {e.stdout}\n")
      sys.stderr.write(f"STDERR: {e.stderr}\n")
    else:  # FileNotFoundError
      sys.stderr.write(
          "Ensure 'llvm-config' is installed and in your system's PATH.\n")
    sys.exit(1)


def format_gn_list(items):
  """Formats a Python list into a GN-compatible list string, removing duplicates and sorting."""
  if not items:
    return "[]"
  return "[\n" + ",\n".join(
      f'  "{item}"' for item in sorted(list(set(items)))) + "\n]"


def main():
  llvm_include_dir = run_llvm_config(["--includedir"])
  cxxflags_raw = run_llvm_config(["--cxxflags"])

  defines_list = []
  cflags_list = []

  for flag in cxxflags_raw.split():
    if flag.startswith('-D'):
      defines_list.append(flag[2:])
    elif not flag.startswith('-I'):
      cflags_list.append(flag)

  cflags_list.insert(0, f'-isystem{llvm_include_dir}')

  # Get ALL flags and library names needed for SHARED linking
  ldflags_and_libs_raw = run_llvm_config(
      ["--ldflags", "--libs", "--link-shared", "symbolize"])

  ldflags_list = []
  libs_list = []

  for part in ldflags_and_libs_raw.split():
    if part.startswith('-L'):
      # Add library search paths (e.g., "-L/usr/lib/llvm-19/lib")
      ldflags_list.append(part)
    elif part.startswith('-l'):
      # Add library names (e.g., "LLVM-19", "z")
      libs_list.append(part[2:])
    else:
      # Add other miscellaneous flags
      ldflags_list.append(part)

  # Print output in GN-compatible format
  print(f"defines = {format_gn_list(defines_list)}")
  print(f"cflags = {format_gn_list(cflags_list)}")
  print(f"libs = {format_gn_list(libs_list)}")
  print(f"ldflags = {format_gn_list(ldflags_list)}")
  return 0


if __name__ == '__main__':
  sys.exit(main())