1 1.1 mrg #!/usr/bin/env python3 2 1.1.1.6 mrg 3 1.1.1.6 mrg # Copyright (C) 2016-2024 Free Software Foundation, Inc. 4 1.1 mrg # 5 1.1 mrg # Script to analyze results of our branch prediction heuristics 6 1.1 mrg # 7 1.1 mrg # This file is part of GCC. 8 1.1 mrg # 9 1.1 mrg # GCC is free software; you can redistribute it and/or modify it under 10 1.1 mrg # the terms of the GNU General Public License as published by the Free 11 1.1 mrg # Software Foundation; either version 3, or (at your option) any later 12 1.1 mrg # version. 13 1.1 mrg # 14 1.1 mrg # GCC is distributed in the hope that it will be useful, but WITHOUT ANY 15 1.1 mrg # WARRANTY; without even the implied warranty of MERCHANTABILITY or 16 1.1 mrg # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 17 1.1 mrg # for more details. 18 1.1 mrg # 19 1.1 mrg # You should have received a copy of the GNU General Public License 20 1.1 mrg # along with GCC; see the file COPYING3. If not see 21 1.1.1.6 mrg # <http://www.gnu.org/licenses/>. 22 1.1 mrg # 23 1.1 mrg # 24 1.1 mrg # 25 1.1 mrg # This script is used to calculate two basic properties of the branch prediction 26 1.1 mrg # heuristics - coverage and hitrate. Coverage is number of executions 27 1.1 mrg # of a given branch matched by the heuristics and hitrate is probability 28 1.1 mrg # that once branch is predicted as taken it is really taken. 29 1.1 mrg # 30 1.1 mrg # These values are useful to determine the quality of given heuristics. 31 1.1 mrg # Hitrate may be directly used in predict.def. 32 1.1 mrg # 33 1.1 mrg # Usage: 34 1.1 mrg # Step 1: Compile and profile your program. You need to use -fprofile-generate 35 1.1 mrg # flag to get the profiles. 36 1.1 mrg # Step 2: Make a reference run of the intrumented application. 37 1.1 mrg # Step 3: Compile the program with collected profile and dump IPA profiles 38 1.1 mrg # (-fprofile-use -fdump-ipa-profile-details) 39 1.1 mrg # Step 4: Collect all generated dump files: 40 1.1 mrg # find . -name '*.profile' | xargs cat > dump_file 41 1.1 mrg # Step 5: Run the script: 42 1.1 mrg # ./analyze_brprob.py dump_file 43 1.1 mrg # and read results. Basically the following table is printed: 44 1.1 mrg # 45 1.1 mrg # HEURISTICS BRANCHES (REL) HITRATE COVERAGE (REL) 46 1.1 mrg # early return (on trees) 3 0.2% 35.83% / 93.64% 66360 0.0% 47 1.1 mrg # guess loop iv compare 8 0.6% 53.35% / 53.73% 11183344 0.0% 48 1.1 mrg # call 18 1.4% 31.95% / 69.95% 51880179 0.2% 49 1.1 mrg # loop guard 23 1.8% 84.13% / 84.85% 13749065956 42.2% 50 1.1 mrg # opcode values positive (on trees) 42 3.3% 15.71% / 84.81% 6771097902 20.8% 51 1.1 mrg # opcode values nonequal (on trees) 226 17.6% 72.48% / 72.84% 844753864 2.6% 52 1.1 mrg # loop exit 231 18.0% 86.97% / 86.98% 8952666897 27.5% 53 1.1 mrg # loop iterations 239 18.6% 91.10% / 91.10% 3062707264 9.4% 54 1.1 mrg # DS theory 281 21.9% 82.08% / 83.39% 7787264075 23.9% 55 1.1 mrg # no prediction 293 22.9% 46.92% / 70.70% 2293267840 7.0% 56 1.1 mrg # guessed loop iterations 313 24.4% 76.41% / 76.41% 10782750177 33.1% 57 1.1 mrg # first match 708 55.2% 82.30% / 82.31% 22489588691 69.0% 58 1.1 mrg # combined 1282 100.0% 79.76% / 81.75% 32570120606 100.0% 59 1.1 mrg # 60 1.1 mrg # 61 1.1 mrg # The heuristics called "first match" is a heuristics used by GCC branch 62 1.1 mrg # prediction pass and it predicts 55.2% branches correctly. As you can, 63 1.1 mrg # the heuristics has very good covertage (69.05%). On the other hand, 64 1.1 mrg # "opcode values nonequal (on trees)" heuristics has good hirate, but poor 65 1.1 mrg # coverage. 66 1.1 mrg 67 1.1 mrg import sys 68 1.1 mrg import os 69 1.1 mrg import re 70 1.1 mrg import argparse 71 1.1 mrg 72 1.1 mrg from math import * 73 1.1 mrg 74 1.1 mrg counter_aggregates = set(['combined', 'first match', 'DS theory', 75 1.1 mrg 'no prediction']) 76 1.1.1.4 mrg hot_threshold = 10 77 1.1 mrg 78 1.1 mrg def percentage(a, b): 79 1.1 mrg return 100.0 * a / b 80 1.1 mrg 81 1.1 mrg def average(values): 82 1.1 mrg return 1.0 * sum(values) / len(values) 83 1.1 mrg 84 1.1 mrg def average_cutoff(values, cut): 85 1.1 mrg l = len(values) 86 1.1 mrg skip = floor(l * cut / 2) 87 1.1 mrg if skip > 0: 88 1.1 mrg values.sort() 89 1.1 mrg values = values[skip:-skip] 90 1.1 mrg return average(values) 91 1.1 mrg 92 1.1 mrg def median(values): 93 1.1 mrg values.sort() 94 1.1 mrg return values[int(len(values) / 2)] 95 1.1 mrg 96 1.1.1.4 mrg class PredictDefFile: 97 1.1.1.4 mrg def __init__(self, path): 98 1.1.1.4 mrg self.path = path 99 1.1.1.4 mrg self.predictors = {} 100 1.1.1.4 mrg 101 1.1.1.4 mrg def parse_and_modify(self, heuristics, write_def_file): 102 1.1.1.4 mrg lines = [x.rstrip() for x in open(self.path).readlines()] 103 1.1.1.4 mrg 104 1.1.1.4 mrg p = None 105 1.1.1.4 mrg modified_lines = [] 106 1.1.1.5 mrg for i, l in enumerate(lines): 107 1.1.1.4 mrg if l.startswith('DEF_PREDICTOR'): 108 1.1.1.5 mrg next_line = lines[i + 1] 109 1.1.1.5 mrg if l.endswith(','): 110 1.1.1.5 mrg l += next_line 111 1.1.1.4 mrg m = re.match('.*"(.*)".*', l) 112 1.1.1.4 mrg p = m.group(1) 113 1.1.1.4 mrg elif l == '': 114 1.1.1.4 mrg p = None 115 1.1.1.4 mrg 116 1.1.1.4 mrg if p != None: 117 1.1.1.4 mrg heuristic = [x for x in heuristics if x.name == p] 118 1.1.1.4 mrg heuristic = heuristic[0] if len(heuristic) == 1 else None 119 1.1.1.4 mrg 120 1.1.1.4 mrg m = re.match('.*HITRATE \(([^)]*)\).*', l) 121 1.1.1.4 mrg if (m != None): 122 1.1.1.4 mrg self.predictors[p] = int(m.group(1)) 123 1.1.1.4 mrg 124 1.1.1.4 mrg # modify the line 125 1.1.1.4 mrg if heuristic != None: 126 1.1.1.4 mrg new_line = (l[:m.start(1)] 127 1.1.1.4 mrg + str(round(heuristic.get_hitrate())) 128 1.1.1.4 mrg + l[m.end(1):]) 129 1.1.1.4 mrg l = new_line 130 1.1.1.4 mrg p = None 131 1.1.1.4 mrg elif 'PROB_VERY_LIKELY' in l: 132 1.1.1.4 mrg self.predictors[p] = 100 133 1.1.1.4 mrg modified_lines.append(l) 134 1.1.1.4 mrg 135 1.1.1.4 mrg # save the file 136 1.1.1.4 mrg if write_def_file: 137 1.1.1.4 mrg with open(self.path, 'w+') as f: 138 1.1.1.4 mrg for l in modified_lines: 139 1.1.1.4 mrg f.write(l + '\n') 140 1.1.1.4 mrg class Heuristics: 141 1.1.1.4 mrg def __init__(self, count, hits, fits): 142 1.1.1.4 mrg self.count = count 143 1.1.1.4 mrg self.hits = hits 144 1.1.1.4 mrg self.fits = fits 145 1.1.1.4 mrg 146 1.1 mrg class Summary: 147 1.1 mrg def __init__(self, name): 148 1.1 mrg self.name = name 149 1.1.1.4 mrg self.edges= [] 150 1.1.1.4 mrg 151 1.1.1.4 mrg def branches(self): 152 1.1.1.4 mrg return len(self.edges) 153 1.1.1.4 mrg 154 1.1.1.4 mrg def hits(self): 155 1.1.1.4 mrg return sum([x.hits for x in self.edges]) 156 1.1.1.4 mrg 157 1.1.1.4 mrg def fits(self): 158 1.1.1.4 mrg return sum([x.fits for x in self.edges]) 159 1.1.1.4 mrg 160 1.1.1.4 mrg def count(self): 161 1.1.1.4 mrg return sum([x.count for x in self.edges]) 162 1.1.1.4 mrg 163 1.1.1.4 mrg def successfull_branches(self): 164 1.1.1.4 mrg return len([x for x in self.edges if 2 * x.hits >= x.count]) 165 1.1 mrg 166 1.1 mrg def get_hitrate(self): 167 1.1.1.4 mrg return 100.0 * self.hits() / self.count() 168 1.1 mrg 169 1.1 mrg def get_branch_hitrate(self): 170 1.1.1.4 mrg return 100.0 * self.successfull_branches() / self.branches() 171 1.1 mrg 172 1.1 mrg def count_formatted(self): 173 1.1.1.4 mrg v = self.count() 174 1.1.1.4 mrg for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']: 175 1.1 mrg if v < 1000: 176 1.1 mrg return "%3.2f%s" % (v, unit) 177 1.1 mrg v /= 1000.0 178 1.1 mrg return "%.1f%s" % (v, 'Y') 179 1.1 mrg 180 1.1.1.4 mrg def count(self): 181 1.1.1.4 mrg return sum([x.count for x in self.edges]) 182 1.1.1.4 mrg 183 1.1.1.4 mrg def print(self, branches_max, count_max, predict_def): 184 1.1.1.4 mrg # filter out most hot edges (if requested) 185 1.1.1.4 mrg self.edges = sorted(self.edges, reverse = True, key = lambda x: x.count) 186 1.1.1.4 mrg if args.coverage_threshold != None: 187 1.1.1.4 mrg threshold = args.coverage_threshold * self.count() / 100 188 1.1.1.4 mrg edges = [x for x in self.edges if x.count < threshold] 189 1.1.1.4 mrg if len(edges) != 0: 190 1.1.1.4 mrg self.edges = edges 191 1.1.1.4 mrg 192 1.1.1.4 mrg predicted_as = None 193 1.1.1.4 mrg if predict_def != None and self.name in predict_def.predictors: 194 1.1.1.4 mrg predicted_as = predict_def.predictors[self.name] 195 1.1.1.4 mrg 196 1.1 mrg print('%-40s %8i %5.1f%% %11.2f%% %7.2f%% / %6.2f%% %14i %8s %5.1f%%' % 197 1.1.1.4 mrg (self.name, self.branches(), 198 1.1.1.4 mrg percentage(self.branches(), branches_max), 199 1.1 mrg self.get_branch_hitrate(), 200 1.1 mrg self.get_hitrate(), 201 1.1.1.4 mrg percentage(self.fits(), self.count()), 202 1.1.1.4 mrg self.count(), self.count_formatted(), 203 1.1.1.4 mrg percentage(self.count(), count_max)), end = '') 204 1.1.1.4 mrg 205 1.1.1.4 mrg if predicted_as != None: 206 1.1.1.4 mrg print('%12i%% %5.1f%%' % (predicted_as, 207 1.1.1.4 mrg self.get_hitrate() - predicted_as), end = '') 208 1.1.1.4 mrg else: 209 1.1.1.4 mrg print(' ' * 20, end = '') 210 1.1.1.4 mrg 211 1.1.1.4 mrg # print details about the most important edges 212 1.1.1.4 mrg if args.coverage_threshold == None: 213 1.1.1.4 mrg edges = [x for x in self.edges[:100] if x.count * hot_threshold > self.count()] 214 1.1.1.4 mrg if args.verbose: 215 1.1.1.4 mrg for c in edges: 216 1.1.1.4 mrg r = 100.0 * c.count / self.count() 217 1.1.1.4 mrg print(' %.0f%%:%d' % (r, c.count), end = '') 218 1.1.1.4 mrg elif len(edges) > 0: 219 1.1.1.4 mrg print(' %0.0f%%:%d' % (100.0 * sum([x.count for x in edges]) / self.count(), len(edges)), end = '') 220 1.1.1.4 mrg 221 1.1.1.4 mrg print() 222 1.1 mrg 223 1.1 mrg class Profile: 224 1.1 mrg def __init__(self, filename): 225 1.1 mrg self.filename = filename 226 1.1 mrg self.heuristics = {} 227 1.1 mrg self.niter_vector = [] 228 1.1 mrg 229 1.1 mrg def add(self, name, prediction, count, hits): 230 1.1 mrg if not name in self.heuristics: 231 1.1 mrg self.heuristics[name] = Summary(name) 232 1.1 mrg 233 1.1 mrg s = self.heuristics[name] 234 1.1 mrg 235 1.1 mrg if prediction < 50: 236 1.1 mrg hits = count - hits 237 1.1 mrg remaining = count - hits 238 1.1.1.4 mrg fits = max(hits, remaining) 239 1.1 mrg 240 1.1.1.4 mrg s.edges.append(Heuristics(count, hits, fits)) 241 1.1 mrg 242 1.1 mrg def add_loop_niter(self, niter): 243 1.1 mrg if niter > 0: 244 1.1 mrg self.niter_vector.append(niter) 245 1.1 mrg 246 1.1 mrg def branches_max(self): 247 1.1.1.4 mrg return max([v.branches() for k, v in self.heuristics.items()]) 248 1.1 mrg 249 1.1 mrg def count_max(self): 250 1.1.1.4 mrg return max([v.count() for k, v in self.heuristics.items()]) 251 1.1 mrg 252 1.1.1.4 mrg def print_group(self, sorting, group_name, heuristics, predict_def): 253 1.1 mrg count_max = self.count_max() 254 1.1 mrg branches_max = self.branches_max() 255 1.1 mrg 256 1.1.1.4 mrg sorter = lambda x: x.branches() 257 1.1 mrg if sorting == 'branch-hitrate': 258 1.1 mrg sorter = lambda x: x.get_branch_hitrate() 259 1.1 mrg elif sorting == 'hitrate': 260 1.1 mrg sorter = lambda x: x.get_hitrate() 261 1.1 mrg elif sorting == 'coverage': 262 1.1 mrg sorter = lambda x: x.count 263 1.1 mrg elif sorting == 'name': 264 1.1 mrg sorter = lambda x: x.name.lower() 265 1.1 mrg 266 1.1.1.4 mrg print('%-40s %8s %6s %12s %18s %14s %8s %6s %12s %6s %s' % 267 1.1 mrg ('HEURISTICS', 'BRANCHES', '(REL)', 268 1.1.1.4 mrg 'BR. HITRATE', 'HITRATE', 'COVERAGE', 'COVERAGE', '(REL)', 269 1.1.1.4 mrg 'predict.def', '(REL)', 'HOT branches (>%d%%)' % hot_threshold)) 270 1.1 mrg for h in sorted(heuristics, key = sorter): 271 1.1.1.4 mrg h.print(branches_max, count_max, predict_def) 272 1.1 mrg 273 1.1 mrg def dump(self, sorting): 274 1.1 mrg heuristics = self.heuristics.values() 275 1.1 mrg if len(heuristics) == 0: 276 1.1 mrg print('No heuristics available') 277 1.1 mrg return 278 1.1 mrg 279 1.1.1.4 mrg predict_def = None 280 1.1.1.4 mrg if args.def_file != None: 281 1.1.1.4 mrg predict_def = PredictDefFile(args.def_file) 282 1.1.1.4 mrg predict_def.parse_and_modify(heuristics, args.write_def_file) 283 1.1.1.4 mrg 284 1.1 mrg special = list(filter(lambda x: x.name in counter_aggregates, 285 1.1 mrg heuristics)) 286 1.1 mrg normal = list(filter(lambda x: x.name not in counter_aggregates, 287 1.1 mrg heuristics)) 288 1.1 mrg 289 1.1.1.4 mrg self.print_group(sorting, 'HEURISTICS', normal, predict_def) 290 1.1 mrg print() 291 1.1.1.4 mrg self.print_group(sorting, 'HEURISTIC AGGREGATES', special, predict_def) 292 1.1 mrg 293 1.1 mrg if len(self.niter_vector) > 0: 294 1.1 mrg print ('\nLoop count: %d' % len(self.niter_vector)), 295 1.1 mrg print(' avg. # of iter: %.2f' % average(self.niter_vector)) 296 1.1 mrg print(' median # of iter: %.2f' % median(self.niter_vector)) 297 1.1 mrg for v in [1, 5, 10, 20, 30]: 298 1.1 mrg cut = 0.01 * v 299 1.1 mrg print(' avg. (%d%% cutoff) # of iter: %.2f' 300 1.1 mrg % (v, average_cutoff(self.niter_vector, cut))) 301 1.1 mrg 302 1.1 mrg parser = argparse.ArgumentParser() 303 1.1 mrg parser.add_argument('dump_file', metavar = 'dump_file', 304 1.1 mrg help = 'IPA profile dump file') 305 1.1 mrg parser.add_argument('-s', '--sorting', dest = 'sorting', 306 1.1 mrg choices = ['branches', 'branch-hitrate', 'hitrate', 'coverage', 'name'], 307 1.1 mrg default = 'branches') 308 1.1.1.4 mrg parser.add_argument('-d', '--def-file', help = 'path to predict.def') 309 1.1.1.4 mrg parser.add_argument('-w', '--write-def-file', action = 'store_true', 310 1.1.1.4 mrg help = 'Modify predict.def file in order to set new numbers') 311 1.1.1.4 mrg parser.add_argument('-c', '--coverage-threshold', type = int, 312 1.1.1.4 mrg help = 'Ignore edges that have percentage coverage >= coverage-threshold') 313 1.1.1.4 mrg parser.add_argument('-v', '--verbose', action = 'store_true', help = 'Print verbose informations') 314 1.1 mrg 315 1.1 mrg args = parser.parse_args() 316 1.1 mrg 317 1.1.1.4 mrg profile = Profile(args.dump_file) 318 1.1 mrg loop_niter_str = ';; profile-based iteration count: ' 319 1.1.1.4 mrg 320 1.1.1.4 mrg for l in open(args.dump_file): 321 1.1.1.4 mrg if l.startswith(';;heuristics;'): 322 1.1.1.4 mrg parts = l.strip().split(';') 323 1.1.1.4 mrg assert len(parts) == 8 324 1.1.1.4 mrg name = parts[3] 325 1.1.1.4 mrg prediction = float(parts[6]) 326 1.1.1.4 mrg count = int(parts[4]) 327 1.1.1.4 mrg hits = int(parts[5]) 328 1.1 mrg 329 1.1 mrg profile.add(name, prediction, count, hits) 330 1.1 mrg elif l.startswith(loop_niter_str): 331 1.1 mrg v = int(l[len(loop_niter_str):]) 332 1.1 mrg profile.add_loop_niter(v) 333 1.1 mrg 334 1.1 mrg profile.dump(args.sorting) 335