blob: 19f3819b301ce656fbd2db1b8d4f42918a572385 [file] [log] [blame]
Chris Bienemanae543392015-12-16 01:02:44 +00001#===- perf-helper.py - Clang Python Bindings -----------------*- python -*--===#
2#
3# The LLVM Compiler Infrastructure
4#
5# This file is distributed under the University of Illinois Open Source
6# License. See LICENSE.TXT for details.
7#
8#===------------------------------------------------------------------------===#
9
Chris Bieneman6c33fc12016-01-15 21:30:06 +000010from __future__ import print_function
11
Chris Bienemanae543392015-12-16 01:02:44 +000012import sys
13import os
14import subprocess
Chris Bienemand8b5bde2016-01-15 21:21:12 +000015import argparse
16import time
17import bisect
Chris Bieneman12fd02d2016-03-21 22:37:14 +000018import shlex
19
20test_env = { 'PATH' : os.environ['PATH'] }
Chris Bienemanae543392015-12-16 01:02:44 +000021
Chris Bienemand8b5bde2016-01-15 21:21:12 +000022def findFilesWithExtension(path, extension):
23 filenames = []
Chris Bienemanae543392015-12-16 01:02:44 +000024 for root, dirs, files in os.walk(path):
25 for filename in files:
Chris Bienemand8b5bde2016-01-15 21:21:12 +000026 if filename.endswith(extension):
27 filenames.append(os.path.join(root, filename))
28 return filenames
Chris Bienemanae543392015-12-16 01:02:44 +000029
30def clean(args):
Chris Bienemand8b5bde2016-01-15 21:21:12 +000031 if len(args) != 2:
Chris Bieneman6c33fc12016-01-15 21:30:06 +000032 print('Usage: %s clean <path> <extension>\n' % __file__ +
33 '\tRemoves all files with extension from <path>.')
Chris Bienemanae543392015-12-16 01:02:44 +000034 return 1
Chris Bienemand8b5bde2016-01-15 21:21:12 +000035 for filename in findFilesWithExtension(args[0], args[1]):
36 os.remove(filename)
Chris Bienemanae543392015-12-16 01:02:44 +000037 return 0
38
39def merge(args):
40 if len(args) != 3:
Chris Bieneman6c33fc12016-01-15 21:30:06 +000041 print('Usage: %s clean <llvm-profdata> <output> <path>\n' % __file__ +
42 '\tMerges all profraw files from path into output.')
Chris Bienemanae543392015-12-16 01:02:44 +000043 return 1
44 cmd = [args[0], 'merge', '-o', args[1]]
Chris Bienemand8b5bde2016-01-15 21:21:12 +000045 cmd.extend(findFilesWithExtension(args[2], "profraw"))
Chris Bienemanae543392015-12-16 01:02:44 +000046 subprocess.check_call(cmd)
47 return 0
48
Chris Bienemand8b5bde2016-01-15 21:21:12 +000049def dtrace(args):
50 parser = argparse.ArgumentParser(prog='perf-helper dtrace',
51 description='dtrace wrapper for order file generation')
52 parser.add_argument('--buffer-size', metavar='size', type=int, required=False,
53 default=1, help='dtrace buffer size in MB (default 1)')
54 parser.add_argument('--use-oneshot', required=False, action='store_true',
55 help='Use dtrace\'s oneshot probes')
56 parser.add_argument('--use-ustack', required=False, action='store_true',
57 help='Use dtrace\'s ustack to print function names')
Chris Bieneman12fd02d2016-03-21 22:37:14 +000058 parser.add_argument('--cc1', required=False, action='store_true',
59 help='Execute cc1 directly (don\'t profile the driver)')
Chris Bienemand8b5bde2016-01-15 21:21:12 +000060 parser.add_argument('cmd', nargs='*', help='')
61
62 # Use python's arg parser to handle all leading option arguments, but pass
63 # everything else through to dtrace
64 first_cmd = next(arg for arg in args if not arg.startswith("--"))
65 last_arg_idx = args.index(first_cmd)
66
67 opts = parser.parse_args(args[:last_arg_idx])
68 cmd = args[last_arg_idx:]
69
Chris Bieneman12fd02d2016-03-21 22:37:14 +000070 if opts.cc1:
71 cmd = get_cc1_command_for_args(cmd, test_env)
72
Chris Bienemand8b5bde2016-01-15 21:21:12 +000073 if opts.use_oneshot:
74 target = "oneshot$target:::entry"
75 else:
76 target = "pid$target:::entry"
77 predicate = '%s/probemod=="%s"/' % (target, os.path.basename(args[0]))
78 log_timestamp = 'printf("dtrace-TS: %d\\n", timestamp)'
79 if opts.use_ustack:
80 action = 'ustack(1);'
81 else:
82 action = 'printf("dtrace-Symbol: %s\\n", probefunc);'
83 dtrace_script = "%s { %s; %s }" % (predicate, log_timestamp, action)
84
85 dtrace_args = []
86 if not os.geteuid() == 0:
Chris Bieneman6c33fc12016-01-15 21:30:06 +000087 print(
88 'Script must be run as root, or you must add the following to your sudoers:'
89 + '%%admin ALL=(ALL) NOPASSWD: /usr/sbin/dtrace')
Chris Bienemand8b5bde2016-01-15 21:21:12 +000090 dtrace_args.append("sudo")
91
92 dtrace_args.extend((
93 'dtrace', '-xevaltime=exec',
94 '-xbufsize=%dm' % (opts.buffer_size),
95 '-q', '-n', dtrace_script,
96 '-c', ' '.join(cmd)))
97
98 if sys.platform == "darwin":
99 dtrace_args.append('-xmangled')
100
101 f = open("%d.dtrace" % os.getpid(), "w")
102 start_time = time.time()
103 subprocess.check_call(dtrace_args, stdout=f, stderr=subprocess.PIPE)
104 elapsed = time.time() - start_time
Chris Bieneman6c33fc12016-01-15 21:30:06 +0000105 print("... data collection took %.4fs" % elapsed)
Chris Bienemand8b5bde2016-01-15 21:21:12 +0000106
107 return 0
108
Chris Bieneman12fd02d2016-03-21 22:37:14 +0000109def get_cc1_command_for_args(cmd, env):
110 # Find the cc1 command used by the compiler. To do this we execute the
111 # compiler with '-###' to figure out what it wants to do.
112 cmd = cmd + ['-###']
113 cc_output = check_output(cmd, stderr=subprocess.STDOUT, env=env).strip()
114 cc_commands = []
115 for ln in cc_output.split('\n'):
116 # Filter out known garbage.
117 if (ln == 'Using built-in specs.' or
118 ln.startswith('Configured with:') or
119 ln.startswith('Target:') or
120 ln.startswith('Thread model:') or
121 ln.startswith('InstalledDir:') or
122 ' version ' in ln):
123 continue
124 cc_commands.append(ln)
125
126 if len(cc_commands) != 1:
127 print('Fatal error: unable to determine cc1 command: %r' % cc_output)
128 exit(1)
129
130 cc1_cmd = shlex.split(cc_commands[0])
131 if not cc1_cmd:
132 print('Fatal error: unable to determine cc1 command: %r' % cc_output)
133 exit(1)
134
135 return cc1_cmd
136
137def cc1(args):
138 parser = argparse.ArgumentParser(prog='perf-helper cc1',
139 description='cc1 wrapper for order file generation')
140 parser.add_argument('cmd', nargs='*', help='')
141
142 # Use python's arg parser to handle all leading option arguments, but pass
143 # everything else through to dtrace
144 first_cmd = next(arg for arg in args if not arg.startswith("--"))
145 last_arg_idx = args.index(first_cmd)
146
147 opts = parser.parse_args(args[:last_arg_idx])
148 cmd = args[last_arg_idx:]
149
150 # clear the profile file env, so that we don't generate profdata
151 # when capturing the cc1 command
152 cc1_env = test_env
153 cc1_env["LLVM_PROFILE_FILE"] = "driver.prfraw"
154 cc1_cmd = get_cc1_command_for_args(cmd, cc1_env)
155 os.remove("driver.prfraw")
156
157 subprocess.check_call(cc1_cmd)
158 return 0;
159
Chris Bienemand8b5bde2016-01-15 21:21:12 +0000160def parse_dtrace_symbol_file(path, all_symbols, all_symbols_set,
161 missing_symbols, opts):
162 def fix_mangling(symbol):
163 if sys.platform == "darwin":
164 if symbol[0] != '_' and symbol != 'start':
165 symbol = '_' + symbol
166 return symbol
167
168 def get_symbols_with_prefix(symbol):
169 start_index = bisect.bisect_left(all_symbols, symbol)
170 for s in all_symbols[start_index:]:
171 if not s.startswith(symbol):
172 break
173 yield s
174
175 # Extract the list of symbols from the given file, which is assumed to be
176 # the output of a dtrace run logging either probefunc or ustack(1) and
177 # nothing else. The dtrace -xdemangle option needs to be used.
178 #
179 # This is particular to OS X at the moment, because of the '_' handling.
180 with open(path) as f:
181 current_timestamp = None
182 for ln in f:
183 # Drop leading and trailing whitespace.
184 ln = ln.strip()
185 if not ln.startswith("dtrace-"):
186 continue
187
188 # If this is a timestamp specifier, extract it.
189 if ln.startswith("dtrace-TS: "):
190 _,data = ln.split(': ', 1)
191 if not data.isdigit():
Chris Bieneman6c33fc12016-01-15 21:30:06 +0000192 print("warning: unrecognized timestamp line %r, ignoring" % ln,
193 file=sys.stderr)
Chris Bienemand8b5bde2016-01-15 21:21:12 +0000194 continue
195 current_timestamp = int(data)
196 continue
197 elif ln.startswith("dtrace-Symbol: "):
198
199 _,ln = ln.split(': ', 1)
200 if not ln:
201 continue
202
203 # If there is a '`' in the line, assume it is a ustack(1) entry in
204 # the form of <modulename>`<modulefunc>, where <modulefunc> is never
205 # truncated (but does need the mangling patched).
206 if '`' in ln:
207 yield (current_timestamp, fix_mangling(ln.split('`',1)[1]))
208 continue
209
210 # Otherwise, assume this is a probefunc printout. DTrace on OS X
211 # seems to have a bug where it prints the mangled version of symbols
212 # which aren't C++ mangled. We just add a '_' to anything but start
213 # which doesn't already have a '_'.
214 symbol = fix_mangling(ln)
215
216 # If we don't know all the symbols, or the symbol is one of them,
217 # just return it.
218 if not all_symbols_set or symbol in all_symbols_set:
219 yield (current_timestamp, symbol)
220 continue
221
222 # Otherwise, we have a symbol name which isn't present in the
223 # binary. We assume it is truncated, and try to extend it.
224
225 # Get all the symbols with this prefix.
226 possible_symbols = list(get_symbols_with_prefix(symbol))
227 if not possible_symbols:
228 continue
229
230 # If we found too many possible symbols, ignore this as a prefix.
231 if len(possible_symbols) > 100:
Chris Bieneman6c33fc12016-01-15 21:30:06 +0000232 print( "warning: ignoring symbol %r " % symbol +
233 "(no match and too many possible suffixes)", file=sys.stderr)
Chris Bienemand8b5bde2016-01-15 21:21:12 +0000234 continue
235
236 # Report that we resolved a missing symbol.
237 if opts.show_missing_symbols and symbol not in missing_symbols:
Chris Bieneman6c33fc12016-01-15 21:30:06 +0000238 print("warning: resolved missing symbol %r" % symbol, file=sys.stderr)
Chris Bienemand8b5bde2016-01-15 21:21:12 +0000239 missing_symbols.add(symbol)
240
241 # Otherwise, treat all the possible matches as having occurred. This
242 # is an over-approximation, but it should be ok in practice.
243 for s in possible_symbols:
244 yield (current_timestamp, s)
245
246def check_output(*popen_args, **popen_kwargs):
247 p = subprocess.Popen(stdout=subprocess.PIPE, *popen_args, **popen_kwargs)
248 stdout,stderr = p.communicate()
249 if p.wait() != 0:
250 raise RuntimeError("process failed")
251 return stdout
252
253def uniq(list):
254 seen = set()
255 for item in list:
256 if item not in seen:
257 yield item
258 seen.add(item)
259
260def form_by_call_order(symbol_lists):
261 # Simply strategy, just return symbols in order of occurrence, even across
262 # multiple runs.
263 return uniq(s for symbols in symbol_lists for s in symbols)
264
265def form_by_call_order_fair(symbol_lists):
266 # More complicated strategy that tries to respect the call order across all
267 # of the test cases, instead of giving a huge preference to the first test
268 # case.
269
270 # First, uniq all the lists.
271 uniq_lists = [list(uniq(symbols)) for symbols in symbol_lists]
272
273 # Compute the successors for each list.
274 succs = {}
275 for symbols in uniq_lists:
276 for a,b in zip(symbols[:-1], symbols[1:]):
277 succs[a] = items = succs.get(a, [])
278 if b not in items:
279 items.append(b)
280
281 # Emit all the symbols, but make sure to always emit all successors from any
282 # call list whenever we see a symbol.
283 #
284 # There isn't much science here, but this sometimes works better than the
285 # more naive strategy. Then again, sometimes it doesn't so more research is
286 # probably needed.
287 return uniq(s
288 for symbols in symbol_lists
289 for node in symbols
290 for s in ([node] + succs.get(node,[])))
291
292def form_by_frequency(symbol_lists):
293 # Form the order file by just putting the most commonly occurring symbols
294 # first. This assumes the data files didn't use the oneshot dtrace method.
295
296 counts = {}
297 for symbols in symbol_lists:
298 for a in symbols:
299 counts[a] = counts.get(a,0) + 1
300
301 by_count = counts.items()
302 by_count.sort(key = lambda (_,n): -n)
303 return [s for s,n in by_count]
304
305def form_by_random(symbol_lists):
306 # Randomize the symbols.
307 merged_symbols = uniq(s for symbols in symbol_lists
308 for s in symbols)
309 random.shuffle(merged_symbols)
310 return merged_symbols
311
312def form_by_alphabetical(symbol_lists):
313 # Alphabetize the symbols.
314 merged_symbols = list(set(s for symbols in symbol_lists for s in symbols))
315 merged_symbols.sort()
316 return merged_symbols
317
318methods = dict((name[len("form_by_"):],value)
319 for name,value in locals().items() if name.startswith("form_by_"))
320
321def genOrderFile(args):
322 parser = argparse.ArgumentParser(
323 "%prog [options] <dtrace data file directories>]")
324 parser.add_argument('input', nargs='+', help='')
325 parser.add_argument("--binary", metavar="PATH", type=str, dest="binary_path",
326 help="Path to the binary being ordered (for getting all symbols)",
327 default=None)
328 parser.add_argument("--output", dest="output_path",
329 help="path to output order file to write", default=None, required=True,
330 metavar="PATH")
331 parser.add_argument("--show-missing-symbols", dest="show_missing_symbols",
332 help="show symbols which are 'fixed up' to a valid name (requires --binary)",
333 action="store_true", default=None)
334 parser.add_argument("--output-unordered-symbols",
335 dest="output_unordered_symbols_path",
336 help="write a list of the unordered symbols to PATH (requires --binary)",
337 default=None, metavar="PATH")
338 parser.add_argument("--method", dest="method",
339 help="order file generation method to use", choices=methods.keys(),
340 default='call_order')
341 opts = parser.parse_args(args)
342
343 # If the user gave us a binary, get all the symbols in the binary by
344 # snarfing 'nm' output.
345 if opts.binary_path is not None:
346 output = check_output(['nm', '-P', opts.binary_path])
347 lines = output.split("\n")
348 all_symbols = [ln.split(' ',1)[0]
349 for ln in lines
350 if ln.strip()]
Chris Bieneman6c33fc12016-01-15 21:30:06 +0000351 print("found %d symbols in binary" % len(all_symbols))
Chris Bienemand8b5bde2016-01-15 21:21:12 +0000352 all_symbols.sort()
353 else:
354 all_symbols = []
355 all_symbols_set = set(all_symbols)
356
357 # Compute the list of input files.
358 input_files = []
359 for dirname in opts.input:
360 input_files.extend(findFilesWithExtension(dirname, "dtrace"))
361
362 # Load all of the input files.
Chris Bieneman6c33fc12016-01-15 21:30:06 +0000363 print("loading from %d data files" % len(input_files))
Chris Bienemand8b5bde2016-01-15 21:21:12 +0000364 missing_symbols = set()
365 timestamped_symbol_lists = [
366 list(parse_dtrace_symbol_file(path, all_symbols, all_symbols_set,
367 missing_symbols, opts))
368 for path in input_files]
369
370 # Reorder each symbol list.
371 symbol_lists = []
372 for timestamped_symbols_list in timestamped_symbol_lists:
373 timestamped_symbols_list.sort()
374 symbol_lists.append([symbol for _,symbol in timestamped_symbols_list])
375
376 # Execute the desire order file generation method.
377 method = methods.get(opts.method)
378 result = list(method(symbol_lists))
379
380 # Report to the user on what percentage of symbols are present in the order
381 # file.
382 num_ordered_symbols = len(result)
383 if all_symbols:
Chris Bieneman6c33fc12016-01-15 21:30:06 +0000384 print("note: order file contains %d/%d symbols (%.2f%%)" % (
Chris Bienemand8b5bde2016-01-15 21:21:12 +0000385 num_ordered_symbols, len(all_symbols),
Chris Bieneman6c33fc12016-01-15 21:30:06 +0000386 100.*num_ordered_symbols/len(all_symbols)), file=sys.stderr)
Chris Bienemand8b5bde2016-01-15 21:21:12 +0000387
388 if opts.output_unordered_symbols_path:
389 ordered_symbols_set = set(result)
390 with open(opts.output_unordered_symbols_path, 'w') as f:
391 f.write("\n".join(s for s in all_symbols if s not in ordered_symbols_set))
392
393 # Write the order file.
394 with open(opts.output_path, 'w') as f:
395 f.write("\n".join(result))
396 f.write("\n")
397
398 return 0
399
400commands = {'clean' : clean,
401 'merge' : merge,
402 'dtrace' : dtrace,
Chris Bieneman12fd02d2016-03-21 22:37:14 +0000403 'cc1' : cc1,
Chris Bienemand8b5bde2016-01-15 21:21:12 +0000404 'gen-order-file' : genOrderFile}
Chris Bienemanae543392015-12-16 01:02:44 +0000405
406def main():
407 f = commands[sys.argv[1]]
408 sys.exit(f(sys.argv[2:]))
409
410if __name__ == '__main__':
411 main()