-
Notifications
You must be signed in to change notification settings - Fork 197
/
run-clang-tidy.py
259 lines (222 loc) · 8.03 KB
/
run-clang-tidy.py
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# Copyright (c) 2020, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import print_function
import sys
import re
import os
import subprocess
import argparse
import json
import multiprocessing as mp
EXPECTED_VERSION = "8.0.1"
VERSION_REGEX = re.compile(r" LLVM version ([0-9.]+)")
GPU_ARCH_REGEX = re.compile(r"sm_(\d+)")
SPACES = re.compile(r"\s+")
SEPARATOR = "-" * 16
def parse_args():
argparser = argparse.ArgumentParser("Runs clang-tidy on a project")
argparser.add_argument("-cdb", type=str, default="compile_commands.json",
help="Path to cmake-generated compilation database")
argparser.add_argument("-exe", type=str, default="clang-tidy",
help="Path to clang-tidy exe")
argparser.add_argument("-ignore", type=str, default="[.]cu$",
help="Regex used to ignore files from checking")
argparser.add_argument("-select", type=str, default=None,
help="Regex used to select files for checking")
argparser.add_argument("-j", type=int, default=-1,
help="Number of parallel jobs to launch.")
args = argparser.parse_args()
if args.j <= 0:
args.j = mp.cpu_count()
args.ignore_compiled = re.compile(args.ignore) if args.ignore else None
args.select_compiled = re.compile(args.select) if args.select else None
ret = subprocess.check_output("%s --version" % args.exe, shell=True)
ret = ret.decode("utf-8")
version = VERSION_REGEX.search(ret)
if version is None:
raise Exception("Failed to figure out clang-tidy version!")
version = version.group(1)
if version != EXPECTED_VERSION:
raise Exception("clang-tidy exe must be v%s found '%s'" % \
(EXPECTED_VERSION, version))
if not os.path.exists(args.cdb):
raise Exception("Compilation database '%s' missing" % args.cdb)
return args
def list_all_cmds(cdb):
with open(cdb, "r") as fp:
return json.load(fp)
def get_gpu_archs(command):
archs = []
for loc in range(len(command)):
if command[loc] != "-gencode":
continue
arch_flag = command[loc + 1]
match = GPU_ARCH_REGEX.search(arch_flag)
if match is not None:
archs.append("--cuda-gpu-arch=sm_%s" % match.group(1))
return archs
def get_index(arr, item):
try:
return arr.index(item)
except:
return -1
def remove_item(arr, item):
loc = get_index(arr, item)
if loc >= 0:
del arr[loc]
return loc
def remove_item_plus_one(arr, item):
loc = get_index(arr, item)
if loc >= 0:
del arr[loc + 1]
del arr[loc]
return loc
def get_clang_includes(exe):
dir = os.getenv("CONDA_PREFIX")
if dir is None:
ret = subprocess.check_output("which %s 2>&1" % exe, shell=True)
ret = ret.decode("utf-8")
dir = os.path.dirname(os.path.dirname(ret))
header = os.path.join(dir, "include", "ClangHeaders")
return ["-I", header]
def get_tidy_args(cmd, exe):
command, file = cmd["command"], cmd["file"]
is_cuda = file.endswith(".cu")
command = re.split(SPACES, command)
# compiler is always clang++!
command[0] = "clang++"
# remove compilation and output targets from the original command
remove_item_plus_one(command, "-c")
remove_item_plus_one(command, "-o")
if is_cuda:
# replace nvcc's "-gencode ..." with clang's "--cuda-gpu-arch ..."
archs = get_gpu_archs(command)
command.extend(archs)
while True:
loc = remove_item_plus_one(command, "-gencode")
if loc < 0:
break
# "-x cuda" is the right usage in clang
loc = get_index(command, "-x")
if loc >= 0:
command[loc + 1] = "cuda"
remove_item_plus_one(command, "-ccbin")
remove_item(command, "--expt-extended-lambda")
remove_item(command, "--diag_suppress=unrecognized_gcc_pragma")
command.extend(get_clang_includes(exe))
return command, is_cuda
def run_clang_tidy_command(tidy_cmd):
cmd = " ".join(tidy_cmd)
result = subprocess.run(cmd, check=False, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
status = result.returncode == 0
if status:
out = ""
else:
out = "CMD: " + cmd
out += result.stdout.decode("utf-8").rstrip()
return status, out
def run_clang_tidy(cmd, args):
command, is_cuda = get_tidy_args(cmd, args.exe)
tidy_cmd = [args.exe, "-header-filter=.*raft/cpp/.*", cmd["file"], "--", ]
tidy_cmd.extend(command)
status = True
out = ""
if is_cuda:
tidy_cmd.append("--cuda-device-only")
tidy_cmd.append(cmd["file"])
ret, out1 = run_clang_tidy_command(tidy_cmd)
out += out1
out += "%s" % SEPARATOR
if not ret:
status = ret
tidy_cmd[-2] = "--cuda-host-only"
ret, out1 = run_clang_tidy_command(tidy_cmd)
if not ret:
status = ret
out += out1
else:
tidy_cmd.append(cmd["file"])
ret, out1 = run_clang_tidy_command(tidy_cmd)
if not ret:
status = ret
out += out1
return status, out, cmd["file"]
# yikes! global var :(
results = []
def collect_result(result):
global results
results.append(result)
def print_result(passed, stdout, file):
status_str = "PASSED" if passed else "FAILED"
print("%s File:%s %s %s" % (SEPARATOR, file, status_str, SEPARATOR))
if stdout:
print(stdout)
print("%s File:%s ENDS %s" % (SEPARATOR, file, SEPARATOR))
def print_results():
global results
status = True
for passed, stdout, file in results:
print_result(passed, stdout, file)
if not passed:
status = False
return status
# mostly used for debugging purposes
def run_sequential(args, all_files):
status = True
# actual tidy checker
for cmd in all_files:
# skip files that we don't want to look at
if args.ignore_compiled is not None and \
re.search(args.ignore_compiled, cmd["file"]) is not None:
continue
if args.select_compiled is not None and \
re.search(args.select_compiled, cmd["file"]) is None:
continue
passed, stdout, file = run_clang_tidy(cmd, args)
print_result(passed, stdout, file)
if not passed:
status = False
return status
def run_parallel(args, all_files):
pool = mp.Pool(args.j)
# actual tidy checker
for cmd in all_files:
# skip files that we don't want to look at
if args.ignore_compiled is not None and \
re.search(args.ignore_compiled, cmd["file"]) is not None:
continue
if args.select_compiled is not None and \
re.search(args.select_compiled, cmd["file"]) is None:
continue
pool.apply_async(run_clang_tidy, args=(cmd, args),
callback=collect_result)
pool.close()
pool.join()
return print_results()
def main():
args = parse_args()
# Attempt to making sure that we run this script from root of repo always
if not os.path.exists(".git"):
raise Exception("This needs to always be run from the root of repo")
all_files = list_all_cmds(args.cdb)
if args.j == 1:
status = run_sequential(args, all_files)
else:
status = run_parallel(args, all_files)
if not status:
raise Exception("clang-tidy failed! Refer to the errors above.")
if __name__ == "__main__":
main()