Merge remote-tracking branch 'public/master' into vulkan
[mesa.git] / src / gallium / drivers / swr / rasterizer / jitter / scripts / gen_llvm_ir_macros.py
1 # Copyright (C) 2014-2015 Intel Corporation. All Rights Reserved.
2 #
3 # Permission is hereby granted, free of charge, to any person obtaining a
4 # copy of this software and associated documentation files (the "Software"),
5 # to deal in the Software without restriction, including without limitation
6 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
7 # and/or sell copies of the Software, and to permit persons to whom the
8 # Software is furnished to do so, subject to the following conditions:
9 #
10 # The above copyright notice and this permission notice (including the next
11 # paragraph) shall be included in all copies or substantial portions of the
12 # Software.
13 #
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20 # IN THE SOFTWARE.
21
22 #!deps/python32/python.exe
23
24 import os, sys, re
25 import argparse
26 import json as JSON
27 import operator
28
29 header = r"""/****************************************************************************
30 * Copyright (C) 2014-2015 Intel Corporation. All Rights Reserved.
31 *
32 * Permission is hereby granted, free of charge, to any person obtaining a
33 * copy of this software and associated documentation files (the "Software"),
34 * to deal in the Software without restriction, including without limitation
35 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
36 * and/or sell copies of the Software, and to permit persons to whom the
37 * Software is furnished to do so, subject to the following conditions:
38 *
39 * The above copyright notice and this permission notice (including the next
40 * paragraph) shall be included in all copies or substantial portions of the
41 * Software.
42 *
43 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
44 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
45 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
46 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
47 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
48 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
49 * IN THE SOFTWARE.
50 *
51 * @file %s
52 *
53 * @brief auto-generated file
54 *
55 * DO NOT EDIT
56 *
57 ******************************************************************************/
58
59 """
60
61 """
62 """
63 def gen_file_header(filename):
64 global header
65 headerStr = header % filename
66 return headerStr.splitlines()
67
68
69 inst_aliases = {
70 'SHUFFLE_VECTOR': 'VSHUFFLE',
71 'INSERT_ELEMENT': 'VINSERT',
72 'EXTRACT_ELEMENT': 'VEXTRACT',
73 'MEM_SET': 'MEMSET',
74 'MEM_CPY': 'MEMCPY',
75 'MEM_MOVE': 'MEMMOVE',
76 'L_SHR': 'LSHR',
77 'A_SHR': 'ASHR',
78 'BIT_CAST': 'BITCAST',
79 'U_DIV': 'UDIV',
80 'S_DIV': 'SDIV',
81 'U_REM': 'UREM',
82 'S_REM': 'SREM',
83 'BIN_OP': 'BINOP',
84 }
85
86 intrinsics = [
87 ["VGATHERPS", "x86_avx2_gather_d_ps_256", ["src", "pBase", "indices", "mask", "scale"]],
88 ["VGATHERDD", "x86_avx2_gather_d_d_256", ["src", "pBase", "indices", "mask", "scale"]],
89 ["VSQRTPS", "x86_avx_sqrt_ps_256", ["a"]],
90 ["VRSQRTPS", "x86_avx_rsqrt_ps_256", ["a"]],
91 ["VRCPPS", "x86_avx_rcp_ps_256", ["a"]],
92 ["VMINPS", "x86_avx_min_ps_256", ["a", "b"]],
93 ["VMAXPS", "x86_avx_max_ps_256", ["a", "b"]],
94 ["VPMINSD", "x86_avx2_pmins_d", ["a", "b"]],
95 ["VPMAXSD", "x86_avx2_pmaxs_d", ["a", "b"]],
96 ["VROUND", "x86_avx_round_ps_256", ["a", "rounding"]],
97 ["VCMPPS", "x86_avx_cmp_ps_256", ["a", "b", "cmpop"]],
98 ["VBLENDVPS", "x86_avx_blendv_ps_256", ["a", "b", "mask"]],
99 ["BEXTR_32", "x86_bmi_bextr_32", ["src", "control"]],
100 ["VMASKLOADD", "x86_avx2_maskload_d_256", ["src", "mask"]],
101 ["VMASKMOVPS", "x86_avx_maskload_ps_256", ["src", "mask"]],
102 ["VPSHUFB", "x86_avx2_pshuf_b", ["a", "b"]],
103 ["VPMOVSXBD", "x86_avx2_pmovsxbd", ["a"]], # sign extend packed 8bit components
104 ["VPMOVSXWD", "x86_avx2_pmovsxwd", ["a"]], # sign extend packed 16bit components
105 ["VPERMD", "x86_avx2_permd", ["idx", "a"]],
106 ["VCVTPH2PS", "x86_vcvtph2ps_256", ["a"]],
107 ["VCVTPS2PH", "x86_vcvtps2ph_256", ["a", "round"]],
108 ["VHSUBPS", "x86_avx_hsub_ps_256", ["a", "b"]],
109 ["VPTESTC", "x86_avx_ptestc_256", ["a", "b"]],
110 ["VPTESTZ", "x86_avx_ptestz_256", ["a", "b"]],
111 ["VFMADDPS", "x86_fma_vfmadd_ps_256", ["a", "b", "c"]],
112 ["VCVTTPS2DQ", "x86_avx_cvtt_ps2dq_256", ["a"]],
113 ["VMOVMSKPS", "x86_avx_movmsk_ps_256", ["a"]],
114 ["INTERRUPT", "x86_int", ["a"]],
115 ]
116
117 def convert_uppercamel(name):
118 s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
119 return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).upper()
120
121 """
122 Given an input file (e.g. IRBuilder.h) generates function dictionary.
123 """
124 def parse_ir_builder(input_file):
125
126 functions = []
127
128 lines = input_file.readlines()
129
130 idx = 0
131 while idx < len(lines) - 1:
132 line = lines[idx].rstrip()
133 idx += 1
134
135 #match = re.search(r"\*Create", line)
136 match = re.search(r"[\*\s]Create(\w*)\(", line)
137 if match is not None:
138 #print("Line: %s" % match.group(1))
139
140 if re.search(r"^\s*Create", line) is not None:
141 func_sig = lines[idx-2].rstrip() + line
142 else:
143 func_sig = line
144
145 end_of_args = False
146 while not end_of_args:
147 end_paren = re.search(r"\)", line)
148 if end_paren is not None:
149 end_of_args = True
150 else:
151 line = lines[idx].rstrip()
152 func_sig += line
153 idx += 1
154
155 delfunc = re.search(r"LLVM_DELETED_FUNCTION|= delete;", func_sig)
156
157 if not delfunc:
158 func = re.search(r"(.*?)\*[\n\s]*(Create\w*)\((.*?)\)", func_sig)
159 if func is not None:
160
161 return_type = func.group(1).lstrip() + '*'
162 func_name = func.group(2)
163 arguments = func.group(3)
164
165 func_args = ''
166 func_args_nodefs = ''
167
168 num_args = arguments.count(',')
169
170 arg_names = []
171 num_args = 0
172 args = arguments.split(',')
173 for arg in args:
174 arg = arg.lstrip()
175 if arg:
176 if num_args > 0:
177 func_args += ', '
178 func_args_nodefs += ', '
179 func_args += arg
180 func_args_nodefs += arg.split(' =')[0]
181
182 split_args = arg.split('=')
183 arg_name = split_args[0].rsplit(None, 1)[-1]
184
185 #print("Before ArgName = %s" % arg_name)
186
187 reg_arg = re.search(r"[\&\*]*(\w*)", arg_name)
188 if reg_arg:
189 #print("Arg Name = %s" % reg_arg.group(1))
190 arg_names += [reg_arg.group(1)]
191
192 num_args += 1
193
194 ignore = False
195
196 # The following functions need to be ignored.
197 if func_name == 'CreateInsertNUWNSWBinOp':
198 ignore = True
199
200 if func_name == 'CreateMaskedIntrinsic':
201 ignore = True
202
203 # Convert CamelCase to CAMEL_CASE
204 func_mod = re.search(r"Create(\w*)", func_name)
205 if func_mod:
206 func_mod = func_mod.group(1)
207 func_mod = convert_uppercamel(func_mod)
208 if func_mod[0:2] == 'F_' or func_mod[0:2] == 'I_':
209 func_mod = func_mod[0] + func_mod[2:]
210
211 # Substitute alias based on CAMEL_CASE name.
212 func_alias = inst_aliases.get(func_mod)
213 if not func_alias:
214 func_alias = func_mod
215
216 if func_name == 'CreateCall' or func_name == 'CreateGEP':
217 arglist = re.search(r'ArrayRef', func_args)
218 if arglist:
219 func_alias = func_alias + 'A'
220
221 if not ignore:
222 functions.append({
223 "name": func_name,
224 "alias": func_alias,
225 "return": return_type,
226 "args": func_args,
227 "args_nodefs": func_args_nodefs,
228 "arg_names": arg_names
229 })
230
231 return functions
232
233 """
234 Auto-generates macros for LLVM IR
235 """
236 def generate_gen_h(functions, output_file):
237 output_lines = gen_file_header(os.path.basename(output_file.name))
238
239 output_lines += [
240 '#pragma once',
241 '',
242 '//////////////////////////////////////////////////////////////////////////',
243 '/// Auto-generated Builder IR declarations',
244 '//////////////////////////////////////////////////////////////////////////',
245 ]
246
247 for func in functions:
248 name = func['name']
249 if func['alias']:
250 name = func['alias']
251 output_lines += [
252 '%s%s(%s);' % (func['return'], name, func['args'])
253 ]
254
255 output_file.write('\n'.join(output_lines) + '\n')
256
257 """
258 Auto-generates macros for LLVM IR
259 """
260 def generate_gen_cpp(functions, output_file):
261 output_lines = gen_file_header(os.path.basename(output_file.name))
262
263 output_lines += [
264 '#include \"builder.h\"',
265 ''
266 ]
267
268 for func in functions:
269 name = func['name']
270 if func['alias']:
271 name = func['alias']
272
273 args = func['arg_names']
274 func_args = ''
275 first_arg = True
276 for arg in args:
277 if not first_arg:
278 func_args += ', '
279 func_args += arg
280 first_arg = False
281
282 output_lines += [
283 '//////////////////////////////////////////////////////////////////////////',
284 '%sBuilder::%s(%s)' % (func['return'], name, func['args_nodefs']),
285 '{',
286 ' return IRB()->%s(%s);' % (func['name'], func_args),
287 '}',
288 '',
289 ]
290
291 output_file.write('\n'.join(output_lines) + '\n')
292
293 """
294 Auto-generates macros for LLVM IR
295 """
296 def generate_x86_h(output_file):
297 output_lines = gen_file_header(os.path.basename(output_file.name))
298
299 output_lines += [
300 '#pragma once',
301 '',
302 '//////////////////////////////////////////////////////////////////////////',
303 '/// Auto-generated x86 intrinsics',
304 '//////////////////////////////////////////////////////////////////////////',
305 ]
306
307 for inst in intrinsics:
308 #print("Inst: %s, x86: %s numArgs: %d" % (inst[0], inst[1], len(inst[2])))
309
310 args = ''
311 first = True
312 for arg in inst[2]:
313 if not first:
314 args += ', '
315 args += ("Value* %s" % arg)
316 first = False
317
318 output_lines += [
319 'Value *%s(%s);' % (inst[0], args)
320 ]
321
322 output_file.write('\n'.join(output_lines) + '\n')
323
324 """
325 Auto-generates macros for LLVM IR
326 """
327 def generate_x86_cpp(output_file):
328 output_lines = gen_file_header(os.path.basename(output_file.name))
329
330 output_lines += [
331 '#include \"builder.h\"',
332 ''
333 ]
334
335 for inst in intrinsics:
336 #print("Inst: %s, x86: %s numArgs: %d" % (inst[0], inst[1], len(inst[2])))
337
338 args = ''
339 pass_args = ''
340 first = True
341 for arg in inst[2]:
342 if not first:
343 args += ', '
344 pass_args += ', '
345 args += ("Value* %s" % arg)
346 pass_args += arg
347 first = False
348
349 output_lines += [
350 '//////////////////////////////////////////////////////////////////////////',
351 'Value *Builder::%s(%s)' % (inst[0], args),
352 '{',
353 ' Function *func = Intrinsic::getDeclaration(JM()->mpCurrentModule, Intrinsic::%s);' % inst[1],
354 ' return CALL(func, std::initializer_list<Value*>{%s});' % pass_args,
355 '}',
356 '',
357 ]
358
359 output_file.write('\n'.join(output_lines) + '\n')
360
361 """
362 Function which is invoked when this script is started from a command line.
363 Will present and consume a set of arguments which will tell this script how
364 to behave
365 """
366 def main():
367
368 # Parse args...
369 parser = argparse.ArgumentParser()
370 parser.add_argument("--input", "-i", type=argparse.FileType('r'), help="Path to IRBuilder.h", required=False)
371 parser.add_argument("--output", "-o", type=argparse.FileType('w'), help="Path to output file", required=True)
372 parser.add_argument("--gen_h", "-gen_h", help="Generate builder_gen.h", action="store_true", default=False)
373 parser.add_argument("--gen_cpp", "-gen_cpp", help="Generate builder_gen.cpp", action="store_true", default=False)
374 parser.add_argument("--gen_x86_h", "-gen_x86_h", help="Generate x86 intrinsics. No input is needed.", action="store_true", default=False)
375 parser.add_argument("--gen_x86_cpp", "-gen_x86_cpp", help="Generate x86 intrinsics. No input is needed.", action="store_true", default=False)
376 args = parser.parse_args()
377
378 if args.input:
379 functions = parse_ir_builder(args.input)
380
381 if args.gen_h:
382 generate_gen_h(functions, args.output)
383
384 if args.gen_cpp:
385 generate_gen_cpp(functions, args.output)
386 else:
387 if args.gen_x86_h:
388 generate_x86_h(args.output)
389
390 if args.gen_x86_cpp:
391 generate_x86_cpp(args.output)
392
393 if args.gen_h:
394 print("Need to specify --input for --gen_h!")
395
396 if args.gen_cpp:
397 print("Need to specify --input for --gen_cpp!")
398
399 if __name__ == '__main__':
400 main()
401 # END OF FILE