Debian Codegraph @

src/nouveau/compiler/latencies/lat_rs_gen.py

raw
1 #! /usr/bin/env python3
2 #
3 # Copyright © 2024 Collabora Ltd. and Red Hat Inc.
4 # SPDX-License-Identifier: MIT
5
6 # This script takes a list of Rust files, each of the form nvh_path_to_mod.rs
7 # and constructs a lib.rs which puts each of them in ::path::to::mod.
8
9 import argparse
10 import csv
11 import os
12 import sys
13
14 from mako import template
15
16 TEMPLATE_RS = template.Template(text="""\
17 // Copyright 2024 Red Hat Inc.
18 // SPDX-License-Identifier: MIT
19
20 // This file is generated by lat_rs_gen.py. DO NOT EDIT!
21 #![allow(unused_variables)]
22
23 const fn pred(has_pred: bool, a: u32, b: u32) -> u32 {
24 if has_pred {
25 a + b
26 } else {
27 b
28 }
29 }
30
31 % for reg_file, cats in file_cats.items():
32 <% enum_name = to_camel(reg_file) + 'Latency' + sm.upper() %>
33 #[derive(PartialEq)]
34 pub enum ${enum_name} {
35 % for category in cats[0].header.cats:
36 ${to_camel(category)},
37 % endfor
38 }
39
40 impl ${to_camel(reg_file)}Latency${sm.upper()} {
41 % for bigcat in cats:
42 pub fn ${bigcat.header.latcat}(
43 ${bigcat.header.cat0}: ${enum_name},
44 ${bigcat.header.cat1}: ${enum_name},
45 has_pred: bool
46 ) -> u32 {
47 use ${enum_name}::*;
48 match ${bigcat.header.cat1} {
49 % for cat in bigcat.header.cats:
50 #[allow(clippy::match_single_binding)]
51 ${to_camel(cat)} => match ${bigcat.header.cat0} {
52 <% has_non = False %>
53 % for cat2 in bigcat.header.cats:
54 % if bigcat.fields[loop.parent.index].flds[cat2].pred == True:
55 ${to_camel(cat2)} => pred(
56 has_pred,
57 ${bigcat.fields[loop.parent.index].flds[cat2].value},
58 ${bigcat.fields[loop.parent.index].flds[cat2].pred_val}
59 ),
60 % elif bigcat.fields[loop.parent.index].flds[cat2].value != "none":
61 ${to_camel(cat2)} => ${bigcat.fields[loop.parent.index].flds[cat2].value},
62 % else:
63 <% has_none = True %>
64 % endif
65 % endfor
66 % if has_none:
67 _ => panic!("Illegal ${bigcat.header.cat0} value in ${bigcat.header.latcat} for ${to_camel(cat)}"),
68 % endif
69 }
70 % endfor
71 }
72 }
73 % endfor
74 }
75
76 % endfor
77 """)
78
79 ## A mere convenience to convert snake_case to CamelCase. Numbers are prefixed
80 ## with "_".
81 def to_camel(snake_str):
82 result = ''.join(word.title() for word in snake_str.split('_'))
83 return result if not result[0].isdigit() else '_' + result
84
85 def reader(csvfile):
86 """Wrapper around csv.reader that skips comments and blanks."""
87 # csv.reader actually reads the file one line at a time (it was designed to
88 # open excel generated sheets), so hold the file until all of the lines are
89 # read.
90 with open(csvfile, 'r') as f:
91 for line in csv.reader(f):
92 if line and not line[0].startswith('#'):
93 yield line
94
95 class Fld(object):
96 def __init__(self, line):
97 if "none" in line:
98 self.valid = False
99 else:
100 self.valid = True
101 self.pred = False
102 if "+" in line:
103 self.pred = True
104 part = line.split("+")
105 self.value = part[0]
106 self.pred_val = part[1]
107 elif " & sb" in line:
108 self.scoreboard = True
109 self.value = line.removesuffix(" & sb");
110 else:
111 self.scoreboard = False
112 self.value = line.strip()
113
114 class Header(object):
115 def __init__(self, line):
116 self.latcat = line[0].strip()
117 self.cats = line[1:]
118
119 if self.latcat == "raw":
120 self.cat0 = "writer"
121 self.cat1 = "reader"
122 elif self.latcat == "war":
123 self.cat0 = "reader"
124 self.cat1 = "writer"
125 elif self.latcat == "waw":
126 self.cat0 = "writer1"
127 self.cat1 = "writer2"
128
129
130 class Fields(object):
131 def __init__(self, header, line):
132 self.fldcat = line[0].strip()
133 self.flds = {}
134 for index, cat in enumerate(header.cats):
135 self.flds[cat] = Fld(line[index + 1])
136
137 class Category(object):
138 def __init__(self, header, fields):
139 self.header = header
140 self.fields = fields
141
142 lattypes = ["reg", "ureg", "pred", "upred"]
143
144 def emit_cats(dirname, f, sm, lat):
145 cats = []
146 for index, cat in enumerate(["raw", "war", "waw"]):
147 first_line = False
148 fields = []
149 for l in reader(dirname + "sm" + sm + "/" + lat + "_" + cat + ".csv"):
150 if first_line == False:
151 header = Header(l)
152 first_line = True
153 else:
154 fields.append(Fields(header, l))
155 cats.append(Category(header, fields))
156
157 try:
158 f.write(TEMPLATE_RS.render(lat=lat, sm=sm, cats=cats))
159 except Exception:
160 # In the event there's an error, this imports some helpers from mako
161 # to print a useful stack trace and prints it, then exits with
162 # status 1, if python is run with debug; otherwise it just raises
163 # the exception
164 import sys
165 from mako import exceptions
166 print(exceptions.text_error_template().render(), file=sys.stderr)
167 sys.exit(1)
168
169 def emit_sm(dirname, f, sm):
170 for lat in lattypes:
171 emit_cats(dirname, f, sm, lat)
172
173 def main():
174 parser = argparse.ArgumentParser()
175 parser.add_argument('-p', '--import-path', required=True)
176 parser.add_argument('--out-rs', required=True, help='Output Rust file.')
177 parser.add_argument('--sm', help='SM', required=True)
178 parser.add_argument('csv_files', metavar='FILE', nargs='*',
179 action='append',
180 help='Input CSV filename')
181
182 args = parser.parse_args()
183
184 sys.path.insert(0, args.import_path)
185 import util
186
187 file_cats = {}
188 for csv_file in args.csv_files[0]:
189 split = os.path.basename(csv_file).removesuffix('.csv').split('_')
190 assert len(split) == 2
191 reg_file = split[0]
192 latcat = split[1]
193
194 r = reader(csv_file)
195 header = Header(next(r))
196 fields = [Fields(header, l) for l in r]
197
198 cat = Category(header, fields)
199 file_cats.setdefault(reg_file, []).append(cat)
200
201 environment = dict(
202 sm=args.sm,
203 file_cats=file_cats,
204 to_camel=to_camel,
205 )
206 util.write_template_rs(args.out_rs, TEMPLATE_RS, environment)
207
208 if __name__ == '__main__':
209 main()