forked from microsoft/DirectXShaderCompiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhctdb_instrhelp.py
More file actions
2010 lines (1746 loc) · 65.5 KB
/
hctdb_instrhelp.py
File metadata and controls
2010 lines (1746 loc) · 65.5 KB
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) Microsoft Corporation. All rights reserved.
# This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
import argparse
import functools
import collections
from hctdb import *
import json
import os
# get db singletons
g_db_dxil = None
def get_db_dxil():
global g_db_dxil
if g_db_dxil is None:
g_db_dxil = db_dxil()
return g_db_dxil
# opcode data contains fixed opcode assignments for HLSL intrinsics.
g_hlsl_opcode_data = None
def get_hlsl_opcode_data():
global g_hlsl_opcode_data
if g_hlsl_opcode_data is None:
# Load the intrinsic opcodes from the JSON file.
json_filepath = os.path.join(
os.path.dirname(__file__), "hlsl_intrinsic_opcodes.json"
)
try:
with open(json_filepath, "r") as file:
g_hlsl_opcode_data = json.load(file)
except FileNotFoundError:
print(f"File not found: {json_filepath}")
except json.JSONDecodeError as e:
print(f"Error decoding JSON from {json_filepath}: {e}")
if not g_hlsl_opcode_data:
g_hlsl_opcode_data = {}
return g_hlsl_opcode_data
g_db_hlsl = None
def get_db_hlsl():
global g_db_hlsl
if g_db_hlsl is None:
thisdir = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(thisdir, "gen_intrin_main.txt"), "r") as f:
g_db_hlsl = db_hlsl(f, get_hlsl_opcode_data())
return g_db_hlsl
def format_comment(prefix, val):
"Formats a value with a line-comment prefix."
result = ""
line_width = 80
content_width = line_width - len(prefix)
l = len(val)
while l:
if l < content_width:
result += prefix + val.strip()
result += "\n"
l = 0
else:
split_idx = val.rfind(" ", 0, content_width)
result += prefix + val[:split_idx].strip()
result += "\n"
val = val[split_idx + 1 :]
l = len(val)
return result
def format_rst_table(list_of_tuples):
"Produces a reStructuredText simple table from the specified list of tuples."
# Calculate widths.
widths = None
for t in list_of_tuples:
if widths is None:
widths = [0] * len(t)
for i, v in enumerate(t):
widths[i] = max(widths[i], len(str(v)))
# Build banner line.
banner = ""
for i, w in enumerate(widths):
if i > 0:
banner += " "
banner += "=" * w
banner += "\n"
# Build the result.
result = banner
for i, t in enumerate(list_of_tuples):
for j, v in enumerate(t):
if j > 0:
result += " "
result += str(v)
result += " " * (widths[j] - len(str(v)))
result = result.rstrip()
result += "\n"
if i == 0:
result += banner
result += banner
return result
def build_range_tuples(i):
"Produces a list of tuples with contiguous ranges in the input list."
i = sorted(i)
low_bound = None
high_bound = None
for val in i:
if low_bound is None:
low_bound = val
high_bound = val
else:
assert not high_bound is None
if val == high_bound + 1:
high_bound = val
else:
yield (low_bound, high_bound)
low_bound = val
high_bound = val
if not low_bound is None:
yield (low_bound, high_bound)
def build_range_code(var, i):
"Produces a fragment of code that tests whether the variable name matches values in the given range."
ranges = build_range_tuples(i)
result = ""
for r in ranges:
if r[0] == r[1]:
cond = var + " == " + str(r[0])
else:
cond = "(%d <= %s && %s <= %d)" % (r[0], var, var, r[1])
if result == "":
result = cond
else:
result = result + " || " + cond
return result
class db_docsref_gen:
"A generator of reference documentation."
def __init__(self, db):
self.db = db
instrs = [i for i in self.db.instr if i.is_dxil_op]
instrs = sorted(
instrs,
key=lambda v: ("" if v.category == None else v.category) + "." + v.name,
)
self.instrs = instrs
val_rules = sorted(
db.val_rules,
key=lambda v: ("" if v.category == None else v.category) + "." + v.name,
)
self.val_rules = val_rules
def print_content(self):
self.print_header()
self.print_body()
self.print_footer()
def print_header(self):
print("<!DOCTYPE html>")
print("<html><head><title>DXIL Reference</title>")
print("<style>body { font-family: Verdana; font-size: small; }</style>")
print("</head><body><h1>DXIL Reference</h1>")
self.print_toc("Instructions", "i", self.instrs)
self.print_toc("Rules", "r", self.val_rules)
def print_body(self):
self.print_instruction_details()
self.print_valrule_details()
def print_instruction_details(self):
print("<h2>Instruction Details</h2>")
for i in self.instrs:
print("<h3><a name='i%s'>%s</a></h3>" % (i.name, i.name))
print("<div>Opcode: %d. This instruction %s.</div>" % (i.dxil_opid, i.doc))
if i.remarks:
# This is likely a .rst fragment, but this will do for now.
print("<div> " + i.remarks + "</div>")
print("<div>Operands:</div>")
print("<ul>")
for o in i.ops:
if o.pos == 0:
print("<li>result: %s - %s</li>" % (o.llvm_type, o.doc))
else:
enum_desc = (
""
if o.enum_name == ""
else " one of %s: %s"
% (
o.enum_name,
",".join(db.enum_idx[o.enum_name].value_names()),
)
)
print(
"<li>%d - %s: %s%s%s</li>"
% (
o.pos - 1,
o.name,
o.llvm_type,
"" if o.doc == "" else " - " + o.doc,
enum_desc,
)
)
print("</ul>")
print("<div><a href='#Instructions'>(top)</a></div>")
def print_valrule_details(self):
print("<h2>Rule Details</h2>")
for i in self.val_rules:
print("<h3><a name='r%s'>%s</a></h3>" % (i.name, i.name))
print("<div>" + i.doc + "</div>")
print("<div><a href='#Rules'>(top)</a></div>")
def print_toc(self, name, aprefix, values):
print("<h2><a name='" + name + "'>" + name + "</a></h2>")
last_category = ""
for i in values:
if i.category != last_category:
if last_category != None:
print("</ul>")
print("<div><b>%s</b></div><ul>" % i.category)
last_category = i.category
print("<li><a href='#" + aprefix + "%s'>%s</a></li>" % (i.name, i.name))
print("</ul>")
def print_footer(self):
print("</body></html>")
class db_instrhelp_gen:
"A generator of instruction helper classes."
def __init__(self, db):
self.db = db
TypeInfo = collections.namedtuple("TypeInfo", "name bits")
self.llvm_type_map = {
"i1": TypeInfo("bool", 1),
"i8": TypeInfo("int8_t", 8),
"u8": TypeInfo("uint8_t", 8),
"i32": TypeInfo("int32_t", 32),
"u32": TypeInfo("uint32_t", 32),
}
self.IsDxilOpFuncCallInst = "hlsl::OP::IsDxilOpFuncCallInst"
def print_content(self):
self.print_header()
self.print_body()
self.print_footer()
def print_header(self):
print(
"///////////////////////////////////////////////////////////////////////////////"
)
print(
"// //"
)
print(
"// Copyright (C) Microsoft Corporation. All rights reserved. //"
)
print(
"// DxilInstructions.h //"
)
print(
"// //"
)
print(
"// This file provides a library of instruction helper classes. //"
)
print(
"// //"
)
print(
"// MUCH WORK YET TO BE DONE - EXPECT THIS WILL CHANGE - GENERATED FILE //"
)
print(
"// //"
)
print(
"///////////////////////////////////////////////////////////////////////////////"
)
print("")
print("// TODO: add correct include directives")
print("// TODO: add accessors with values")
print("// TODO: add validation support code, including calling into right fn")
print("// TODO: add type hierarchy")
print("namespace hlsl {")
def bool_lit(self, val):
return "true" if val else "false"
def op_type(self, o):
if o.llvm_type in self.llvm_type_map:
return self.llvm_type_map[o.llvm_type].name
raise ValueError(
"Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name)
)
def op_size(self, o):
if o.llvm_type in self.llvm_type_map:
return self.llvm_type_map[o.llvm_type].bits
raise ValueError(
"Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name)
)
def op_const_expr(self, o):
return (
"(%s)(llvm::dyn_cast<llvm::ConstantInt>(Instr->getOperand(%d))->getZExtValue())"
% (self.op_type(o), o.pos - 1)
)
def op_set_const_expr(self, o):
type_size = self.op_size(o)
return (
"llvm::Constant::getIntegerValue(llvm::IntegerType::get(Instr->getContext(), %d), llvm::APInt(%d, (uint64_t)val))"
% (type_size, type_size)
)
def print_body(self):
for i in self.db.instr:
if i.is_reserved:
continue
if i.inst_helper_prefix:
struct_name = "%s_%s" % (i.inst_helper_prefix, i.name)
elif i.is_dxil_op:
struct_name = "DxilInst_%s" % i.name
else:
struct_name = "LlvmInst_%s" % i.name
if i.doc:
print("/// This instruction %s" % i.doc)
print("struct %s {" % struct_name)
print(" llvm::Instruction *Instr;")
print(" // Construction and identification")
print(" %s(llvm::Instruction *pInstr) : Instr(pInstr) {}" % struct_name)
print(" operator bool() const {")
if i.is_dxil_op:
op_name = i.fully_qualified_name()
print(
" return %s(Instr, %s);" % (self.IsDxilOpFuncCallInst, op_name)
)
else:
print(
" return Instr->getOpcode() == llvm::Instruction::%s;" % i.name
)
print(" }")
print(" // Validation support")
print(
" bool isAllowed() const { return %s; }" % self.bool_lit(i.is_allowed)
)
if i.is_dxil_op:
print(" bool isArgumentListValid() const {")
print(
" if (%d != llvm::dyn_cast<llvm::CallInst>(Instr)->getNumArgOperands()) return false;"
% (len(i.ops) - 1)
)
print(" return true;")
# TODO - check operand types
print(" }")
print(" // Metadata")
print(
" bool requiresUniformInputs() const { return %s; }"
% self.bool_lit(i.requires_uniform_inputs)
)
EnumWritten = False
for o in i.ops:
if o.pos > 1: # 0 is return type, 1 is DXIL OP id
if not EnumWritten:
print(" // Operand indexes")
print(" enum OperandIdx {")
EnumWritten = True
print(" arg_%s = %d," % (o.name, o.pos - 1))
if EnumWritten:
print(" };")
AccessorsWritten = False
for o in i.ops:
if o.pos > 1: # 0 is return type, 1 is DXIL OP id
if not AccessorsWritten:
print(" // Accessors")
AccessorsWritten = True
print(
" llvm::Value *get_%s() const { return Instr->getOperand(%d); }"
% (o.name, o.pos - 1)
)
print(
" void set_%s(llvm::Value *val) { Instr->setOperand(%d, val); }"
% (o.name, o.pos - 1)
)
if o.is_const:
if o.llvm_type in self.llvm_type_map:
print(
" %s get_%s_val() const { return %s; }"
% (self.op_type(o), o.name, self.op_const_expr(o))
)
print(
" void set_%s_val(%s val) { Instr->setOperand(%d, %s); }"
% (
o.name,
self.op_type(o),
o.pos - 1,
self.op_set_const_expr(o),
)
)
print("};")
print("")
def print_footer(self):
print("} // namespace hlsl")
class db_enumhelp_gen:
"A generator of enumeration declarations."
def __init__(self, db):
self.db = db
# Some enums should get a last enum marker.
self.lastEnumNames = {"OpCode": "NumOpCodes", "OpCodeClass": "NumOpClasses"}
def print_enum(self, e, **kwargs):
print("// %s" % e.doc)
print("enum class %s : unsigned {" % e.name)
hide_val = kwargs.get("hide_val", False)
sorted_values = e.values
if kwargs.get("sort_val", True):
sorted_values = sorted(
e.values,
key=lambda v: ("" if v.category == None else v.category) + "." + v.name,
)
last_category = None
for v in sorted_values:
if v.category != last_category:
if last_category != None:
print("")
print(" // %s" % v.category)
last_category = v.category
line_format = " {name}"
if not e.is_internal and not hide_val:
line_format += " = {value}"
line_format += ","
if v.doc:
line_format += " // {doc}"
print(line_format.format(name=v.name, value=v.value, doc=v.doc))
if e.name in self.lastEnumNames:
lastName = self.lastEnumNames[e.name]
versioned = [
"%s_Dxil_%d_%d = %d," % (lastName, major, minor, info[lastName])
for (major, minor), info in sorted(self.db.dxil_version_info.items())
if lastName in info
]
if versioned:
print("")
for val in versioned:
print(" " + val)
print("")
print(
" "
+ lastName
+ " = "
+ str(len(sorted_values))
+ " // exclusive last value of enumeration"
)
print("};")
def print_rdat_enum(self, e, **kwargs):
nodef = kwargs.get("nodef", False)
for v in e.values:
line_format = (
"RDAT_ENUM_VALUE_NODEF({name})"
if nodef
else "RDAT_ENUM_VALUE({value}, {name})"
)
if v.doc:
line_format += " // {doc}"
print(line_format.format(name=v.name, value=v.value, doc=v.doc))
def print_content(self):
for e in sorted(self.db.enums, key=lambda e: e.name):
self.print_enum(e)
class db_oload_gen:
"A generator of overload tables."
def __init__(self, db):
self.db = db
instrs = [i for i in self.db.instr if i.is_dxil_op]
self.instrs = sorted(instrs, key=lambda i: i.dxil_opid)
# Allow these to be overridden by external scripts.
self.OP = "OP"
self.OC = "OC"
self.OCC = "OCC"
def print_content(self):
self.print_opfunc_props()
print("...")
self.print_opfunc_table()
def print_opfunc_props(self):
print(
"const {OP}::OpCodeProperty {OP}::m_OpCodeProps[(unsigned){OP}::OpCode::NumOpCodes] = {{".format(
OP=self.OP
)
)
print(
"// OpCode OpCode name, OpCodeClass OpCodeClass name, void, h, f, d, i1, i8, i16, i32, i64, udt, obj, function attribute"
)
# Example formatted string:
# { OC::TempRegLoad, "TempRegLoad", OCC::TempRegLoad, "tempRegLoad", false, true, true, false, true, false, true, true, false, Attribute::ReadOnly, },
# 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
last_category = None
# overload types are a string of (v)oid, (h)alf, (f)loat, (d)ouble, (1)-bit, (8)-bit, (w)ord, (i)nt, (l)ong, u(dt)
f = lambda i, c: "true" if i.oload_types.find(c) >= 0 else "false"
lower_exceptions = {
"CBufferLoad": "cbufferLoad",
"CBufferLoadLegacy": "cbufferLoadLegacy",
"GSInstanceID": "gsInstanceID",
}
lower_fn = (
lambda t: lower_exceptions[t]
if t in lower_exceptions
else t[:1].lower() + t[1:]
)
attr_dict = {
"": "None",
"ro": "ReadOnly",
"rn": "ReadNone",
"amo": "ArgMemOnly",
"nd": "NoDuplicate",
"nr": "NoReturn",
"wv": "None",
}
attr_fn = lambda i: "Attribute::" + attr_dict[i.fn_attr] + ","
for i in self.instrs:
if last_category != i.category:
if last_category != None:
print("")
print(
" // {category:118} void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute".format(
category=i.category
)
)
last_category = i.category
print(
" {{ {OC}::{name:24} {quotName:27} {OCC}::{className:25} {classNameQuot:28} {{{v:>6},{h:>6},{f:>6},{d:>6},{b:>6},{e:>6},{w:>6},{i:>6},{l:>6},{u:>6},{o:>6}}}, {attr:20} }},".format(
name=i.name + ",",
quotName='"' + i.name + '",',
className=i.dxil_class + ",",
classNameQuot='"' + lower_fn(i.dxil_class) + '",',
v=f(i, "v"),
h=f(i, "h"),
f=f(i, "f"),
d=f(i, "d"),
b=f(i, "1"),
e=f(i, "8"),
w=f(i, "w"),
i=f(i, "i"),
l=f(i, "l"),
u=f(i, "u"),
o=f(i, "o"),
attr=attr_fn(i),
OC=self.OC,
OCC=self.OCC,
)
)
print("};")
def print_opfunc_table(self):
# Print the table for OP::GetOpFunc
op_type_texts = {
"$cb": "CBRT(pETy);",
"$o": "A(pETy);",
"$r": "RRT(pETy);",
"d": "A(pF64);",
"dims": "A(pDim);",
"f": "A(pF32);",
"h": "A(pF16);",
"i1": "A(pI1);",
"i16": "A(pI16);",
"i32": "A(pI32);",
"i32c": "A(pI32C);",
"i64": "A(pI64);",
"i8": "A(pI8);",
"$u4": "A(pI4S);",
"pf32": "A(pPF32);",
"res": "A(pRes);",
"splitdouble": "A(pSDT);",
"twoi32": "A(p2I32);",
"twof32": "A(p2F32);",
"twof16": "A(p2F16);",
"twoi16": "A(p2I16);",
"threei32": "A(p3I32);",
"threef32": "A(p3F32);",
"fouri32": "A(p4I32);",
"fourf32": "A(p4F32);",
"fouri16": "A(p4I16);",
"fourf16": "A(p4F16);",
"u32": "A(pI32);",
"u64": "A(pI64);",
"u8": "A(pI8);",
"v": "A(pV);",
"$vec4": "VEC4(pETy);",
"w": "A(pWav);",
"SamplePos": "A(pPos);",
"udt": "A(udt);",
"obj": "A(obj);",
"resproperty": "A(resProperty);",
"resbind": "A(resBind);",
"waveMat": "A(pWaveMatPtr);",
"waveMatProps": "A(pWaveMatProps);",
"$gsptr": "A(pGSEltPtrTy);",
"nodehandle": "A(pNodeHandle);",
"noderecordhandle": "A(pNodeRecordHandle);",
"nodeproperty": "A(nodeProperty);",
"noderecordproperty": "A(nodeRecordProperty);",
"hit_object": "A(pHit);",
}
last_category = None
for i in self.instrs:
if last_category != i.category:
if last_category != None:
print("")
print(" // %s" % i.category)
last_category = i.category
line = " case OpCode::{name:24}".format(name=i.name + ":")
for index, o in enumerate(i.ops):
assert (
o.llvm_type in op_type_texts
), "llvm type %s in instruction %s is unknown" % (o.llvm_type, i.name)
op_type_text = op_type_texts[o.llvm_type]
if index == 0:
line = line + "{val:13}".format(val=op_type_text)
else:
line = line + "{val:9}".format(val=op_type_text)
line = line + "break;"
print(line)
def print_opfunc_oload_type(self):
# Print the function for OP::GetOverloadType
elt_ty = "$o"
res_ret_ty = "$r"
cb_ret_ty = "$cb"
udt_ty = "udt"
obj_ty = "obj"
vec_ty = "$vec"
gsptr_ty = "$gsptr"
last_category = None
index_dict = collections.OrderedDict()
ptr_index_dict = collections.OrderedDict()
single_dict = collections.OrderedDict()
struct_list = []
for instr in self.instrs:
ret_ty = instr.ops[0].llvm_type
# Skip case return type is overload type
if ret_ty == elt_ty:
continue
if ret_ty == res_ret_ty:
struct_list.append(instr.name)
continue
if ret_ty == cb_ret_ty:
struct_list.append(instr.name)
continue
if ret_ty.startswith(vec_ty):
struct_list.append(instr.name)
continue
in_param_ty = False
# Try to find elt_ty in parameter types.
for index, op in enumerate(instr.ops):
# Skip return type.
if op.pos == 0:
continue
# Skip dxil opcode.
if op.pos == 1:
continue
op_type = op.llvm_type
if op_type == elt_ty:
# Skip return op
index = index - 1
if index not in index_dict:
index_dict[index] = [instr.name]
else:
index_dict[index].append(instr.name)
in_param_ty = True
break
if op_type == gsptr_ty:
# Skip return op
index = index - 1
if index not in ptr_index_dict:
ptr_index_dict[index] = [instr.name]
else:
ptr_index_dict[index].append(instr.name)
in_param_ty = True
break
if op_type == udt_ty or op_type == obj_ty:
# Skip return op
index = index - 1
if index not in index_dict:
index_dict[index] = [instr.name]
else:
index_dict[index].append(instr.name)
in_param_ty = True
if in_param_ty:
continue
# No overload, just return the single oload_type.
assert len(instr.oload_types) == 1, "overload no elt_ty %s" % (instr.name)
ty = instr.oload_types[0]
type_code_texts = {
"d": "Type::getDoubleTy(Ctx)",
"f": "Type::getFloatTy(Ctx)",
"h": "Type::getHalfTy",
"1": "IntegerType::get(Ctx, 1)",
"8": "IntegerType::get(Ctx, 8)",
"w": "IntegerType::get(Ctx, 16)",
"i": "IntegerType::get(Ctx, 32)",
"l": "IntegerType::get(Ctx, 64)",
"v": "Type::getVoidTy(Ctx)",
"u": "Type::getInt32PtrTy(Ctx)",
"o": "Type::getInt32PtrTy(Ctx)",
}
assert ty in type_code_texts, "llvm type %s is unknown" % (ty)
ty_code = type_code_texts[ty]
if ty_code not in single_dict:
single_dict[ty_code] = [instr.name]
else:
single_dict[ty_code].append(instr.name)
for index, opcodes in index_dict.items():
line = ""
for opcode in opcodes:
line = line + "case OpCode::{name}".format(name=opcode + ":\n")
line = (
line
+ " if (FT->getNumParams() <= "
+ str(index)
+ ") return nullptr;\n"
)
line = line + " return FT->getParamType(" + str(index) + ");"
print(line)
# ptr_index_dict for overload based on pointer element type
for index, opcodes in ptr_index_dict.items():
line = ""
for opcode in opcodes:
line = line + "case OpCode::{name}".format(name=opcode + ":\n")
line = (
line
+ " if (FT->getNumParams() <= "
+ str(index)
+ ") return nullptr;\n"
)
line = (
line
+ " return FT->getParamType("
+ str(index)
+ ")->getPointerElementType();"
)
print(line)
for code, opcodes in single_dict.items():
line = ""
for opcode in opcodes:
line = line + "case OpCode::{name}".format(name=opcode + ":\n")
line = line + " return " + code + ";"
print(line)
line = ""
for opcode in struct_list:
line = line + "case OpCode::{name}".format(name=opcode + ":\n")
line = line + "{\n"
line = line + " StructType *ST = cast<StructType>(Ty);\n"
line = line + " return ST->getElementType(0);\n"
line = line + "}"
print(line)
class db_valfns_gen:
"A generator of validation functions."
def __init__(self, db):
self.db = db
def print_content(self):
self.print_header()
self.print_body()
def print_header(self):
print(
"///////////////////////////////////////////////////////////////////////////////"
)
print(
"// Instruction validation functions. //"
)
def bool_lit(self, val):
return "true" if val else "false"
def op_type(self, o):
if o.llvm_type == "i8":
return "int8_t"
if o.llvm_type == "u8":
return "uint8_t"
raise ValueError(
"Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name)
)
def op_const_expr(self, o):
if o.llvm_type == "i8" or o.llvm_type == "u8":
return (
"(%s)(llvm::dyn_cast<llvm::ConstantInt>(Instr->getOperand(%d))->getZExtValue())"
% (self.op_type(o), o.pos - 1)
)
raise ValueError(
"Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name)
)
def print_body(self):
llvm_instrs = [i for i in self.db.instr if i.is_allowed and not i.is_dxil_op]
print("static bool IsLLVMInstructionAllowed(llvm::Instruction &I) {")
self.print_comment(
" // ",
"Allow: %s"
% ", ".join([i.name + "=" + str(i.llvm_id) for i in llvm_instrs]),
)
print(" unsigned op = I.getOpcode();")
print(" return %s;" % build_range_code("op", [i.llvm_id for i in llvm_instrs]))
print("}")
print("")
def print_comment(self, prefix, val):
print(format_comment(prefix, val))
class macro_table_gen:
"A generator for macro tables."
def format_row(self, row, widths, sep=", "):
frow = [
str(item) + sep + (" " * (width - len(item)))
for item, width in list(zip(row, widths))[:-1]
] + [str(row[-1])]
return "".join(frow)
def format_table(self, table, *args, **kwargs):
widths = [
functools.reduce(max, [len(row[i]) for row in table], 1)
for i in range(len(table[0]))
]
formatted = []
for row in table:
formatted.append(self.format_row(row, widths, *args, **kwargs))
return formatted
def print_table(self, table, macro_name):
formatted = self.format_table(table)
print(
"// %s\n" % formatted[0]
+ "#define %s(ROW) \\\n" % macro_name
+ " \\\n".join([" ROW(%s)" % frow for frow in formatted[1:]])
)
class db_sigpoint_gen(macro_table_gen):
"A generator for SigPoint tables."
def __init__(self, db):
self.db = db
def print_sigpoint_table(self):
self.print_table(self.db.sigpoint_table, "DO_SIGPOINTS")
def print_interpretation_table(self):
self.print_table(self.db.interpretation_table, "DO_INTERPRETATION_TABLE")
def print_content(self):
self.print_sigpoint_table()
self.print_interpretation_table()
class string_output:
def __init__(self):
self.val = ""
def write(self, text):
self.val = self.val + str(text)
def __str__(self):
return self.val
def run_with_stdout(fn):
import sys
_stdout_saved = sys.stdout
so = string_output()
try:
sys.stdout = so
fn()
finally:
sys.stdout = _stdout_saved
return str(so)
def get_hlsl_intrinsic_stats():
db = get_db_hlsl()
longest_fn = db.intrinsics[0]
longest_param = None
longest_arglist_fn = db.intrinsics[0]
for i in sorted(db.intrinsics, key=lambda x: x.key):
# Get some values for maximum lengths.
if len(i.name) > len(longest_fn.name):
longest_fn = i
for p_idx, p in enumerate(i.params):
if p_idx > 0 and (
longest_param is None or len(p.name) > len(longest_param.name)
):
longest_param = p
if len(i.params) > len(longest_arglist_fn.params):
longest_arglist_fn = i
result = ""
for k in sorted(db.namespaces.keys()):
v = db.namespaces[k]
result += "static const UINT g_u%sCount = %d;\n" % (k, len(v.intrinsics))
result += "\n"
# NOTE:The min limits are needed to support allowing intrinsics in the extension mechanism that use longer values than the builtin hlsl intrisics.
# TODO: remove code which dependent on g_MaxIntrinsic*.
MIN_FUNCTION_NAME_LENTH = 44
MIN_PARAM_NAME_LENTH = 48
MIN_PARAM_COUNT = 29
max_fn_name = longest_fn.name
max_fn_name_len = len(longest_fn.name)
max_param_name = longest_param.name
max_param_name_len = len(longest_param.name)
max_param_count_name = longest_arglist_fn.name
max_param_count = len(longest_arglist_fn.params) - 1
if max_fn_name_len < MIN_FUNCTION_NAME_LENTH:
max_fn_name_len = MIN_FUNCTION_NAME_LENTH
max_fn_name = "MIN_FUNCTION_NAME_LENTH"
if max_param_name_len < MIN_PARAM_NAME_LENTH:
max_param_name_len = MIN_PARAM_NAME_LENTH
max_param_name = "MIN_PARAM_NAME_LENTH"
if max_param_count < MIN_PARAM_COUNT:
max_param_count = MIN_PARAM_COUNT
max_param_count_name = "MIN_PARAM_COUNT"
result += (
"static const int g_MaxIntrinsicName = %d; // Count of characters for longest intrinsic name - '%s'\n"
% (max_fn_name_len, max_fn_name)
)
result += (
"static const int g_MaxIntrinsicParamName = %d; // Count of characters for longest intrinsic parameter name - '%s'\n"
% (max_param_name_len, max_param_name)
)
result += (
"static const int g_MaxIntrinsicParamCount = %d; // Count of parameters (without return) for longest intrinsic argument list - '%s'\n"
% (max_param_count, max_param_count_name)
)
return result
def get_hlsl_intrinsics():
db = get_db_hlsl()
result = ""
last_ns = ""
ns_table = ""
is_vk_table = False # SPIRV Change
id_prefix = ""
arg_idx = 0
opcode_namespace = db.opcode_namespace
for i in sorted(db.intrinsics, key=lambda x: x.key):
if last_ns != i.ns:
last_ns = i.ns
id_prefix = (
"IOP" if last_ns == "Intrinsics" or last_ns == "VkIntrinsics" else "MOP"
) # SPIRV Change
if len(ns_table):
result += ns_table + "};\n"
# SPIRV Change Starts