-
Notifications
You must be signed in to change notification settings - Fork 129
/
asmtool.py
executable file
·2250 lines (1940 loc) · 95.7 KB
/
asmtool.py
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
#!/usr/bin/env python3
# Port of shadertool to DX11. I thought long and hard about adapting shadertool
# to work with both, but eventually decided to make a clean start since there
# are quite a few differences between DX9 and DX11 shaders, and this way I
# could take a clean slate with some of the lessons learned working on
# shadertool and hlsltool and have cleaner code from the beginning. Some code
# from shadertool and hlsltool is still reused. Like hlsltool this is intended
# to use an approach based purely on pattern matching instead of the parser in
# shadertool, which may not be as powerful, but should be simpler.
import sys, os, re, collections, argparse, itertools, copy, textwrap
import shadertool, hlsltool
from shadertool import debug, debug_verbose, component_set_to_string
from shadertool import vanity_comment, tool_name, expand_wildcards
from shadertool import game_git_dir, collected_errors, show_collected_errors
from hlsltool import cb_offset, cb_matrix
cbuffer_entry_pattern_cache = {}
def cbuffer_entry_pattern(type, name):
try:
return cbuffer_entry_pattern_cache[(type, name)]
except KeyError:
pattern = re.compile(r'''
^ \s* // \s*
{0} \s+ {1};
\s* // \s*
Offset: \s+ (?P<offset>\d+)
\s+
Size: \s+ (?P<size>\d+)
(?: \s+ \[(?P<unused>unused)\] )?
\s* $
'''.format(type, name), re.VERBOSE | re.MULTILINE)
cbuffer_entry_pattern_cache[(type, name)] = pattern
return pattern
struct_entry_pattern_cache = {}
def struct_entry_pattern(struct, type, entry):
try:
return struct_entry_pattern_cache[(struct, type, entry)]
except KeyError:
pattern = re.compile(r'''
// \s Resource \s bind \s info \s for \s (?P<bind_name>\S+) \s* \n
// \s* {{ \s* \n
// \s* \n
// \s* struct \s+ {0} \s* \n
// \s* {{ \s* \n
[^}}]*
// \s* {1} \s+ {2}; \s* // \s* Offset: \s+ (?P<offset>\d+) \s* \n
[^}}]*
// \s* }} \s+ [$]Element; \s* // \s* Offset: \s+ 0 \s+ Size: \s+ (?P<size>\d+) \s* \n
// \s* \n
// \s* }}
'''.format(struct, type, entry), re.VERBOSE | re.MULTILINE)
struct_entry_pattern_cache[(struct, type, entry)] = pattern
return pattern
resource_bind_pattern_cache = {}
def resource_bind_pattern(name, type=None, format=None, dim=None):
try:
return resource_bind_pattern_cache[name]
except KeyError:
pattern = re.compile(r'''
^ \s* //
\s* {0} (?#name)
\s+ {1} (?#type)
\s+ {2} (?#format)
\s+ {3} (?#dim)
\s+ (?P<slot>\d+)
\s+ (?P<elements>\d+)
\s* $
'''.format(
name,
type or r'(?P<type>\S+)',
format or r'(?P<format>\S+)',
dim or r'(?P<dim>\S+)'
), re.VERBOSE | re.MULTILINE)
resource_bind_pattern_cache[name] = pattern
return pattern
resource_bindings_pattern = re.compile(r'// Resource Bindings:')
def cbuffer_bind_pattern(cb_name):
return resource_bind_pattern(cb_name, 'cbuffer', 'NA', 'NA')
def struct_bind_pattern(cb_name):
return resource_bind_pattern(cb_name, 'texture', 'struct', 'r/o')
cbuffer_pattern = re.compile(r'// cbuffer (?P<name>.+)\n// {$', re.MULTILINE)
struct_pattern = re.compile(r'// Resource bind info for (?P<name>.+)\n// {$', re.MULTILINE)
class Instruction(hlsltool.Instruction):
pattern = re.compile(r'''
\s*
\S
.*
$
''', re.MULTILINE | re.VERBOSE)
class AssignmentInstruction(hlsltool.AssignmentInstruction, Instruction):
pattern = re.compile(r'''
\s*
(?P<instruction>\S+)
\s+
(?P<lval>\S+)
\s* , \s*
(?P<rval>\S.*)
\s*
$
''', re.MULTILINE | re.VERBOSE)
def __init__(self, text, instruction, lval, rval):
Instruction.__init__(self, text)
self.instruction = instruction
self.lval = hlsltool.expression_as_single_register(lval)
self.rval = rval.strip()
def writes(self, variable, components=None):
return hlsltool.regs_overlap(self.lval, variable, components)
def reads(self, variable, components=None):
return hlsltool.register_in_expression(self.rval, variable, components)
def is_noop(self):
return False
def replace_rval_reg(self, old, new):
indent = self.text[:self.text.find(self.instruction)]
text = '{}{} {}, {}'.format(indent, self.instruction, self.lval, self.rval.replace(old, new))
match = self.__class__.pattern.match(text)
return self.__class__(match.group(), **match.groupdict())
class MovInstruction(AssignmentInstruction):
pattern = re.compile(r'''
\s*
(?P<instruction>mov)
\s+
(?P<lval>\S+)
\s* , \s*
(?P<rval>\S+)
\s*
$
''', re.MULTILINE | re.VERBOSE)
def __init__(self, text, instruction, lval, rval):
AssignmentInstruction.__init__(self, text, instruction, lval, rval) # rval is text for consistency
self.rarg = hlsltool.expression_as_single_register(rval) or rval # rarg is Register if possible
class ResourceLoadInstruction(AssignmentInstruction):
pattern = re.compile(r'''
\s*
(?P<instruction>[a-zA-Z_]+
\s*
(?:
\(
[^)]+
\)
)+
)
\s*
(?P<lval>\S+)
\s* , \s*
(?P<rval>\S.*)
\s*
$
''', re.MULTILINE | re.VERBOSE)
class SampleLIndexableInstruction(ResourceLoadInstruction):
pattern = re.compile(r'''
\s*
(?P<instruction>sample_l_indexable
\s*
\(
[^)]+
\)
\(
[^)]+
\)
)
\s*
(?P<lval>\S+)
\s* , \s*
(?P<rval>
(?P<arg1>\S+)
\s* , \s*
(?P<arg2>\S+)
\s* , \s*
(?P<arg3>\S+)
\s* , \s*
(?P<arg4>\S+)
)
\s*
$
''', re.MULTILINE | re.VERBOSE)
def __init__(self, text, instruction, lval, rval, arg1, arg2, arg3, arg4):
AssignmentInstruction.__init__(self, text, instruction, lval, rval)
self.rargs = tuple(map(lambda x: hlsltool.expression_as_single_register(x) or x, (arg1, arg2, arg3, arg4)))
class SampleIndexableInstruction(ResourceLoadInstruction):
pattern = re.compile(r'''
\s*
(?P<instruction>sample_indexable
\s*
\(
[^)]+
\)
\(
[^)]+
\)
)
\s*
(?P<lval>\S+)
\s* , \s*
(?P<rval>
(?P<arg1>\S+)
\s* , \s*
(?P<arg2>\S+)
\s* , \s*
(?P<arg3>\S+)
)
\s*
$
''', re.MULTILINE | re.VERBOSE)
def __init__(self, text, instruction, lval, rval, arg1, arg2, arg3):
AssignmentInstruction.__init__(self, text, instruction, lval, rval)
self.rargs = tuple(map(lambda x: hlsltool.expression_as_single_register(x) or x, (arg1, arg2, arg3)))
class LoadStructuredInstruction(ResourceLoadInstruction):
pattern = re.compile(r'''
\s*
(?P<instruction>ld_structured_indexable
\s*
\(
[^)]+
\)
\(
[^)]+
\)
)
\s*
(?P<lval>\S+)
\s* , \s*
(?P<rval>
(?P<arg1>\S+)
\s* , \s*
(?P<arg2>\S+)
\s* , \s*
(?P<arg3>\S+)
)
\s*
$
''', re.MULTILINE | re.VERBOSE)
def __init__(self, text, instruction, lval, rval, arg1, arg2, arg3):
AssignmentInstruction.__init__(self, text, instruction, lval, rval)
self.rargs = tuple(map(lambda x: hlsltool.expression_as_single_register(x) or x, (arg1, arg2, arg3)))
class TwoArgAssignmentInstruction(AssignmentInstruction):
@staticmethod
def mkpattern(instruction):
return re.compile(r'''
\s*
(?P<instruction>{})
\s+
(?P<lval>\S+)
\s* , \s*
(?P<rval>
(?P<arg1>\S+)
\s* , \s*
(?P<arg2>\S+)
)
\s*
$
'''.format(instruction), re.MULTILINE | re.VERBOSE)
def __init__(self, text, instruction, lval, rval, arg1, arg2):
AssignmentInstruction.__init__(self, text, instruction, lval, rval)
self.rargs = tuple(map(lambda x: hlsltool.expression_as_single_register(x) or x, (arg1, arg2)))
class DP2Instruction(TwoArgAssignmentInstruction):
pattern = TwoArgAssignmentInstruction.mkpattern('dp2')
class DP3Instruction(TwoArgAssignmentInstruction):
pattern = TwoArgAssignmentInstruction.mkpattern('dp3')
class DP4Instruction(TwoArgAssignmentInstruction):
pattern = TwoArgAssignmentInstruction.mkpattern('dp4')
class AddInstruction(TwoArgAssignmentInstruction, hlsltool.AddInstruction):
pattern = TwoArgAssignmentInstruction.mkpattern('add')
class MulInstruction(TwoArgAssignmentInstruction, hlsltool.MultiplyInstruction):
pattern = TwoArgAssignmentInstruction.mkpattern('mul')
class DivInstruction(TwoArgAssignmentInstruction):
pattern = TwoArgAssignmentInstruction.mkpattern('div')
class MinInstruction(TwoArgAssignmentInstruction):
pattern = TwoArgAssignmentInstruction.mkpattern('min')
class MaxInstruction(TwoArgAssignmentInstruction):
pattern = TwoArgAssignmentInstruction.mkpattern('max')
class ReciprocalInstruction(TwoArgAssignmentInstruction, hlsltool.ReciprocalInstruction):
pattern = re.compile(r'''
\s*
(?P<instruction>div)
\s+
(?P<lval>\S+)
\s* , \s*
(?P<rval>
(?P<arg1>l\(1.0+, \s* 1.0+, \s* 1.0+, \s* 1.0+\))
\s* , \s*
(?P<arg2>\S+)
)
\s*
$
''', re.MULTILINE | re.VERBOSE)
class MADInstruction(AssignmentInstruction, hlsltool.MADInstruction):
pattern = re.compile(r'''
\s*
(?P<instruction>mad)
\s+
(?P<lval>\S+)
\s* , \s*
(?P<rval>
(?P<arg1>\S+)
\s* , \s*
(?P<arg2>\S+)
\s* , \s*
(?P<arg3>\S+)
)
\s*
$
''', re.MULTILINE | re.VERBOSE)
def __init__(self, text, instruction, lval, rval, arg1, arg2, arg3):
AssignmentInstruction.__init__(self, text, instruction, lval, rval)
self.rargs = tuple(map(lambda x: hlsltool.expression_as_single_register(x) or x, (arg1, arg2, arg3)))
class Declaration(Instruction):
pattern = re.compile(r'''
\s*
dcl_.*
$
''', re.MULTILINE | re.VERBOSE)
def __eq__(self, other):
return self.text == other.text
class ICBDeclaration(Declaration):
pattern = re.compile(r'''
\s*
dcl_immediateConstantBuffer
\s*
\{
.*
\}
\s*
$
''', re.MULTILINE | re.VERBOSE | re.DOTALL)
class CBDeclaration(Declaration):
pattern = re.compile(r'''
\s*
dcl_constantbuffer
\s*
cb(?P<cb>\d+)
\[
(?P<size>\d+)
\],
\s*
(?P<access_pattern>\S+)
\s*
$
''', re.MULTILINE | re.VERBOSE | re.DOTALL | re.IGNORECASE)
def __init__(self, text, cb, size, access_pattern):
Declaration.__init__(self, text)
self.cb = int(cb)
self.size = int(size)
self.access_pattern = access_pattern
def __str__(self):
return '\ndcl_constantbuffer cb%d[%d], %s' % (self.cb, self.size, self.access_pattern)
class TempsDeclaration(Declaration):
pattern = re.compile(r'''
\s*
dcl_temps
\s+
(?P<temps>\d+)
\s*
$
''', re.MULTILINE | re.VERBOSE)
def __init__(self, text, temps):
Declaration.__init__(self, text)
self.temps = int(temps)
def __str__(self):
return '\ndcl_temps %d' % self.temps
class SVOutputDeclaration(Declaration):
pattern = re.compile(r'''
\s*
dcl_output_s[ig]v
\s+
(?P<register>o[^,]+)
\s*
,
\s*
(?P<system_value>\S+)
\s*
$
''', re.MULTILINE | re.VERBOSE)
def __init__(self, text, register, system_value):
Declaration.__init__(self, text)
self.register = hlsltool.expression_as_single_register(register)
self.system_value = system_value
class ReturnInstruction(Instruction):
pattern = re.compile(r'''
\s*
ret
.*
$
''', re.MULTILINE | re.VERBOSE)
specific_instructions = (
ICBDeclaration,
CBDeclaration,
TempsDeclaration,
SVOutputDeclaration,
Declaration,
ReturnInstruction,
SampleIndexableInstruction,
SampleLIndexableInstruction,
LoadStructuredInstruction,
ResourceLoadInstruction,
DP4Instruction,
DP3Instruction,
DP2Instruction,
AddInstruction,
MulInstruction,
ReciprocalInstruction,
DivInstruction,
MADInstruction,
MovInstruction,
MinInstruction,
MaxInstruction,
AssignmentInstruction,
)
class ASMShader(hlsltool.Shader):
shader_model_pattern = re.compile(r'^[vhdgpc]s_[45]_[01]$', re.MULTILINE)
def __init__(self, filename):
hlsltool.Shader.__init__(self, filename, args)
self.temps = None
self.early_insert_pos = 0
self.shader_model_match = self.shader_model_pattern.search(self.text)
self.shader_model = self.shader_model_match.group()
self.declarations_txt = self.text[:self.shader_model_match.start()]
body_txt = self.text[self.shader_model_match.end() : ]
self.split_instructions(body_txt)
self.process_declarations()
def InstructionFactory(self, text, pos):
match = hlsltool.Comment.pattern.match(text, pos)
if match is not None:
return hlsltool.Comment(match.group()), match.end()
for specific_instruction in specific_instructions:
match = specific_instruction.pattern.match(text, pos)
if match is not None:
return specific_instruction(match.group(), **match.groupdict()), match.end()
match = Instruction.pattern.match(text, pos)
if match is not None:
return Instruction(match.group()), match.end()
return None, pos
def MovInstruction(self, dst, mask, src, swiz):
return 'mov %s.%s, %s.%s' % (dst, mask, src, swiz)
def process_declarations(self):
self.declarations = []
self.sv_outputs = {}
while self.instructions:
instruction = self.instructions[0]
if not isinstance(instruction, (Declaration, hlsltool.Comment)):
break
self.declarations.append(self.instructions.pop(0))
if isinstance(instruction, TempsDeclaration):
if self.temps:
raise SyntaxError("Bad shader: Multiple dcl_temps: %s" % instruction)
self.temps = instruction
elif isinstance(instruction, SVOutputDeclaration):
self.sv_outputs[instruction.system_value] = instruction
for instruction in self.instructions:
if isinstance(instruction, Declaration):
raise SyntaxError("Bad shader: Mixed declarations with code: %s" % instruction)
def parse_isgn(self):
search_str = textwrap.dedent('''
// Input signature:
//
// Name Index Mask Register SysValue Format Used
// -------------------- ----- ------ -------- -------- ------- ------
''')
signature_pattern = re.compile(r'''
^ \/\/
\s+ (?P<name>\w+)
\s+ (?P<index>\d+)
\s+ (?P<mask>[x ][y ][z ][w ])
\s+ (?P<register>\d+)
\s+ (?P<sysvalue>\w+)
\s+ (?P<format>\w+)
\s* (?P<used>[xyzw ]*)
$''', re.VERBOSE)
SignatureEntry = collections.namedtuple('Input', 'Name Index Mask Register SysValue Format Used end'.split())
self.isgn = []
pos = self.declarations_txt.find(search_str)
if pos == -1:
return
pos = pos + len(search_str)
while pos != -1:
new_pos = self.declarations_txt.find('\n', pos)
line = self.declarations_txt[pos:new_pos]
match = signature_pattern.match(line)
if match is None:
return pos
(name, index, mask, register, sysvalue, format, used) = match.groups()
(index, register) = map(int, (index, register))
self.isgn.append(SignatureEntry(name, index, mask, register, sysvalue, format, used, new_pos + 1))
pos = new_pos + 1
assert(False)
def append_isgn_entry(self, isgn_end_pos, name, index, mask, register, sysvalue, format, used):
# // Name Index Mask Register SysValue Format Used
# // -------------------- ----- ------ -------- -------- ------- ------
x = '// {Name:<20} {Index:>5} {Mask:>4} {Register:>8} {SysValue:>8} {Format:>7} {Used:>4}\n'.format(
Name=name, Index=index, Mask=mask, Register=register, SysValue=sysvalue, Format=format, Used=used)
self.declarations_txt = self.declarations_txt[:isgn_end_pos] + x + self.declarations_txt[isgn_end_pos:]
def add_ps_texcoord_input(self, texcoord, components, format='float', comment=None):
assert(components == 1)
self.parse_isgn()
texcoords = filter(lambda x: x.Name == 'TEXCOORD', self.isgn)
texcoords = sorted(texcoords, key = lambda x: x.Index)
if list(filter(lambda x: x.Index == texcoord, texcoords)):
raise KeyError('Shader already has TEXCOORD{}'.format(texcoord))
last_texcoord = texcoords[-1]
assert(last_texcoord.Mask == 'xyz ') # FIXME: Handle inserting in other cases
assert(last_texcoord.Index < texcoord) # FIXME: Handle inserting before other texcoords
reg_no = last_texcoord.Register # FIXME: Increment register if could not merge
mask = ' w'
pos = last_texcoord.end
self.append_isgn_entry(pos, 'TEXCOORD', texcoord, mask, reg_no, 'NONE', format, mask)
self.insert_decl()
if comment:
self.insert_decl('// ' + comment)
reg = 'v{}.{}'.format(reg_no, mask.strip())
self.insert_decl('dcl_input_ps linear ' + reg)
return reg
def find_reg_from_column_major_matrix_multiply(self, cb):
results = self.scan_shader(cb, write=False, instr_type=DP4Instruction)
if len(results) != 1:
debug_verbose(0, '%s read from %i instructions (only exactly 1 read currently supported)' % (cb, len(results)))
return None
(line, instr) = results[0]
if instr.rargs[0].variable == cb:
reg = instr.rargs[1]
elif instr.rargs[1].variable == cb:
reg = instr.rargs[0]
else:
assert(False)
return reg, line
def lookup_output_position(self):
return self.sv_outputs['position'].register.variable
def remap_components(self, frm, to):
ret = ['x'] * 4
assert(len(frm) == len(to))
for i in range(len(to)):
ret[{'x': 0, 'y': 1, 'z': 2, 'w': 3}[to[i]]] = frm[i]
return ''.join(ret)
def hlsl_swizzle(self, mask, swizzle):
# HLSL style swizzle from assembly style swizzle
return shadertool.asm_hlsl_swizzle(mask, swizzle)
def asm_swizzle(self, mask, swizzle):
# Assembly style swizzle from HLSL style swizzle
if len(mask) == 1:
assert(len(swizzle) == 1)
return swizzle
# DX11 shaders must always use exactly 1 or 4 component swizzles
ret = list('xxxx')
for (i, component) in enumerate(mask):
ret[{
'x': 0,
'y': 1,
'z': 2,
'w': 3,
}[component]] = swizzle[i]
return ''.join(ret)
def find_cb_declaration(self, cb):
for declaration in self.declarations:
if not isinstance(declaration, CBDeclaration):
continue
if declaration.cb != cb:
continue
return declaration
def adjust_cb_size(self, cb, size):
declaration = self.find_cb_declaration(cb)
if declaration:
size = (size + 15) // 16
if (declaration.size >= size):
return
debug_verbose(0, 'Resizing cb{0}[{1}] declaration to cb{0}[{2}]'.format(cb, declaration.size, size))
declaration.size = size
def find_cb_entry(self, type, name, used = None):
match = self.find_header(cbuffer_entry_pattern(type, name))
debug_verbose(2, match.group())
offset = int(match.group('offset'))
is_used = not match.group('unused')
if used is not None and used != is_used:
raise KeyError()
pos = self.declarations_txt.rfind('// cbuffer ', 0, match.start())
if pos == -1:
raise KeyError()
match = cbuffer_pattern.match(self.declarations_txt, pos)
if match is None:
raise KeyError()
cb_name = match.group('name')
# TODO: cb_size = find last offset + size
match = cbuffer_bind_pattern(cb_name).search(self.declarations_txt, pos)
if match is None:
raise KeyError()
debug_verbose(2, match.group())
cb = int(match.group('slot'))
# TODO: self.adjust_cb_size(cb, cb_size)
return cb, offset
def find_struct_entry(self, struct, type, entry):
match = self.find_header(struct_entry_pattern(struct, type, entry))
debug_verbose(2, match.group())
offset = int(match.group('offset'))
bind_name = match.group('bind_name')
match = struct_bind_pattern(bind_name).search(self.declarations_txt, match.end())
if match is None:
raise KeyError()
debug_verbose(2, match.group())
slot = int(match.group('slot'))
return slot, offset
def scan_structure_loads(self, slot, offset):
results = self.scan_shader('t%d' % slot, write=False, instr_type=LoadStructuredInstruction)
loff = 'l(%d)' % offset
for (line, instr) in results:
if instr.rargs[1] == loff:
yield (line, instr)
def find_texture(self, name, type='texture', format=None, dim=None):
match = self.find_header(resource_bind_pattern(name, type, format, dim))
return 't' + match.group('slot')
def find_col_major_matrix_multiply(shader, matrix):
# TODO: this is quite strict at the moment, and could be relaxed to support
# matrix multiplies that are done out of order or interleaved with
# unrelated instructions.
results = shader.scan_shader(matrix, write = False, instr_type = DP4Instruction)
if len(results) != 4:
debug_verbose(0, 'Matrix not used expected number of times')
raise KeyError()
# Only checks xyz go to same output variable - w often goes to another:
if any([ r.instruction.lval.variable != results[0].instruction.lval.variable for r in results[:3] ]):
debug_verbose(0, 'Matrix writing to differing output variables')
raise KeyError()
if any([ results[n].line != results[n+1].line - 1 for n in range(3) ]):
debug_verbose(0, 'Matrix not used in sequence')
raise KeyError()
return results
def insert_instr(self, pos, instruction=None, comment=None):
off = 0
if comment is not None:
self.instructions.insert(pos + off, hlsltool.Comment('\n// %s' % comment))
off += 1
if instruction is not None:
self.instructions.insert(pos + off, Instruction('\n' + instruction))
off += 1
if comment is None and instruction is None:
self.instructions.insert(pos + off, hlsltool.Comment('\n'))
off += 1
return off
def insert_decl(self, declaration=None, comment=None):
if comment is not None:
self.declarations.append(hlsltool.Comment('\n// %s' % comment))
if declaration is not None:
d = Declaration('\n' + declaration)
if d not in self.declarations:
self.declarations.append(d)
if comment is None and declaration is None:
self.declarations.append(hlsltool.Comment('\n'))
def allocate_temp_reg(self):
if self.temps is None:
self.temps = TempsDeclaration('dcl_temps 0')
self.declarations.append(self.temps)
temp = self.temps.temps
self.temps.temps += 1
return 'r%d' % temp
def insert_stereo_params(self):
if self.inserted_stereo_params:
return 0
self.inserted_stereo_params = True
self.stereo_params_reg = self.allocate_temp_reg()
self.insert_decl()
self.insert_decl('dcl_resource_texture2d (float,float,float,float) t125', '3DMigoto StereoParams:')
off = self.early_insert_instr()
off += self.early_insert_instr('ld_indexable(texture2d)(float,float,float,float) {0}.xyzw, l(0, 0, 0, 0), t125.xyzw'.format(self.stereo_params_reg))
off += self.early_insert_instr()
return off
def insert_ini_params(self, idx):
if self.inserted_ini_params[idx]:
return 0
self.inserted_ini_params[idx] = True
self.ini_params_reg[idx] = self.allocate_temp_reg()
if not self.inserted_ini_params_decl:
self.inserted_ini_params_decl = True
self.insert_decl()
self.insert_decl('dcl_resource_texture1d (float,float,float,float) t120', '3DMigoto IniParams:')
off = self.early_insert_instr()
off += self.early_insert_instr('ld_indexable(texture1d)(float,float,float,float) {0}.xyzw, l({1}, 0, 0, 0), t120.xyzw'.format(self.ini_params_reg[idx], idx))
off += self.early_insert_instr()
return off
def insert_halo_fix_code(self, pos, temp_reg):
off = 0
off += self.insert_instr(pos + off, 'ne {0}.w, {1}.w, l(1.0)'.format(self.stereo_params_reg, temp_reg.variable))
off += self.insert_instr(pos + off, 'if_nz {0}.w'.format(self.stereo_params_reg))
off += self.insert_instr(pos + off, ' add {0}.w, {1}.w, -{0}.y'.format(self.stereo_params_reg, temp_reg.variable))
off += self.insert_instr(pos + off, ' mad {1}.x, {0}.w, {0}.x, {1}.x'.format(self.stereo_params_reg, temp_reg.variable))
off += self.insert_instr(pos + off, 'endif')
return off
def __str__(self):
s = self.declarations_txt
s += self.shader_model_match.group()
for instr in self.declarations:
s += str(instr)
for instr in self.instructions:
s += str(instr)
return s
def fix_unusual_halo_with_inconsistent_w_optimisation(shader):
# Fixes the following unusual halo pattern seen in Stranded Deep / Unity
# 5.4, where o0 is the output position - the output position assumes that
# the input W == 1 and optimises out the multiplication by it, yet the
# result is then stored in a texcoord without the same optimisation.
# add o0.xyzw, r0.xyzw, cb3[3].xyzw
# mad r0.xyzw, cb3[3].xyzw, v0.wwww, r0.xyzw
# mad o1.xy, v3.xyxx, cb0[13].xyxx, cb0[13].zwzz
try:
pos_out = shader.lookup_output_position()
except KeyError:
debug("Shader has no output position (tesselation?)")
return
results = shader.scan_shader(pos_out, components='xyzw', write=True)
if not results:
debug("Couldn't find write to output position register")
return
if len(results) > 1:
debug_verbose(0, "Can't autofix a vertex shader writing to output position from multiple instructions")
return
(output_line, output_instr) = results[0]
if not isinstance(output_instr, AddInstruction):
debug_verbose(-1, 'Output not using add: %s' % output_instr.strip())
return
temp_reg, mvp_row4 = output_instr.rargs
if not temp_reg.variable.startswith('r'):
mvp_row4, temp_reg = temp_reg, mvp_row4
if not temp_reg.variable.startswith('r'):
debug_verbose(-1, 'Output not added from a temporary register and matrix: %s' % output_instr.strip())
return
if temp_reg.components != 'xyzw':
debug_verbose(-1, 'Temp reg did not use all components: %s' % output_instr.strip())
return
if mvp_row4.components != 'xyzw':
debug_verbose(-1, 'MVP row4 did not use all components: %s' % output_instr.strip())
return
results = shader.scan_shader(temp_reg.variable, components='xyzw', write=False, start=output_line + 1, stop=True)
if not results:
debug_verbose(-1, 'Temp register not used')
return
(line, instr) = results[0]
if not isinstance(instr, MADInstruction):
debug_verbose(-1, 'Temp register not used in mad: %s' % instr.strip())
return
if instr.rargs[2] != temp_reg:
debug_verbose(-1, 'Temp register not used in expected location of mad instruction: %s' % instr.strip())
return
if instr.rargs[0] != mvp_row4 and instr.rargs[1] != mvp_row4:
debug_verbose(-1, 'MVP row4 was not used in mad instruction: %s' % instr.strip())
return
off = shader.insert_stereo_params()
# We could probably insert this on the following line and skip
# adding/subtracting the 4th row, but I have a haunch this might catch a
# few more variants if the result is directly stored in a texcoord.
off += shader.insert_vanity_comment(line + off, 'Unusual halo fix (inconsistent W optimisation) inserted with')
off += shader.insert_multiple_lines(line + off, '''
add {temp_reg}.xyzw, {temp_reg}.xyzw, {mvp_row4}.xyzw
add {stereo}.w, {temp_reg}.w, -{stereo}.y
mad {temp_reg}.x, {stereo}.w, {stereo}.x, {temp_reg}.x
add {temp_reg}.xyzw, {temp_reg}.xyzw, -{mvp_row4}.xyzw
'''.format(
temp_reg = temp_reg.variable,
mvp_row4 = mvp_row4.variable,
stereo = shader.stereo_params_reg
))
shader.autofixed = True
def remap_cb(shader, cb, sb, start_offset=0, dest_offset=0, length=4096):
assert(shader.shader_model.endswith('_4_0') or shader.shader_model.endswith('_5_0'))
cb_declaration = shader.find_cb_declaration(cb)
if not cb_declaration:
debug_verbose(0, 'Constant buffer cb{cb} declaration not found'.format(cb=cb))
return
# Structured buffers max stride is 2048. While it seems to still assemble
# and run ok if we ignore that, let's play it safe and use the structure
# index to give us access to anything above the 2048 mark:
stride = min(cb_declaration.size * 16, 2048)
pattern = re.compile(r'''
cb{cb}\[ (?P<index>\d+) \]
'''.format(cb = cb), re.VERBOSE | re.MULTILINE)
cb_refs = set()
for instr in shader.instructions:
for reg in hlsltool.find_regs_in_expression(str(instr)):
match = pattern.match(reg.variable)
if match:
idx = int(match.group('index'))
if idx >= start_offset and idx < start_offset + length:
cb_refs.add(idx)
if start_offset == 0 and length == 4096:
src_offset_txt = ''
elif length == 1:
src_offset_txt = '[{}]'.format(start_offset)
else:
src_offset_txt = '[{}:{}]'.format(start_offset, start_offset + length)
if dest_offset == start_offset:
dst_offset_txt = ''
elif length == 1:
dst_offset_txt = '[{}]'.format(dest_offset)
else:
dst_offset_txt = '[{}:{}]'.format(dest_offset, dest_offset + length)
if not cb_refs:
debug_verbose(0, 'No constant buffer cb{cb}{offset} references found'.format(cb=cb, offset=src_offset_txt))
return
shader.insert_decl('dcl_resource_structured t{sb}, {stride}'.format(sb = sb, stride = stride))
shader.early_insert_vanity_comment('cb{cb}{src_offset} remapped to t{sb}{dst_offset} with'.
format(cb=cb, sb=sb, src_offset=src_offset_txt, dst_offset=dst_offset_txt))
for cb_idx in sorted(cb_refs):
reg = shader.allocate_temp_reg()
cb_offset = int(cb_idx) * 16
adjusted_offset = cb_offset + (dest_offset - start_offset) * 16
structure_idx = adjusted_offset // stride
structure_offset = adjusted_offset % stride
if shader.shader_model.endswith('_4_0'):
shader.early_insert_instr(
'ld_structured {reg}.xyzw, l({idx}), l({offset}), t{sb}.xyzw' \
.format(idx = structure_idx, offset = structure_offset, reg = reg, sb = sb))
elif shader.shader_model.endswith('_5_0'):
shader.early_insert_instr(
'ld_structured_indexable(structured_buffer, stride={stride})(mixed,mixed,mixed,mixed) {reg}.xyzw, l({idx}), l({offset}), t{sb}.xyzw' \
.format(idx = structure_idx, offset = structure_offset, stride = stride, reg = reg, sb = sb))
shader.replace_reg('cb{cb}[{idx}]'.format(cb=cb, idx=cb_idx), reg)
shader.early_insert_instr()
shader.autofixed = True
def disable_driver_stereo_cb(shader):
if not shader.shader_model.startswith('vs_') and not shader.shader_model.startswith('ds_'):
debug_verbose(0, 'Disabling the driver stereo correction is only applicable to vertex and domain shaders')
return
cb = args.disable_driver_stereo_cb
cb_declaration = shader.find_cb_declaration(cb)
if cb_declaration:
debug_verbose(0, 'Shader already declares cb{}'.format(cb))
return
shader.insert_decl('// Disables driver stereo correction:')
shader.insert_decl('dcl_constantbuffer cb{}[4], immediateIndexed'.format(cb))
# Not counting this as autofixed since we expect to be doing something else
# as well. Important for UE4 autofix script.
def fix_unity_lighting_ps(shader):
if args.fix_unity_lighting_ps[:-1] != 'TEXCOORD':
debug('ERROR: --fix-unity-lighting-ps must take a TEXCOORD')
return
try:
_CameraToWorld = cb_matrix(*shader.find_unity_cb_entry(shadertool.unity_CameraToWorld, 'matrix'))
_ZBufferParams_cb, _ZBufferParams_offset = shader.find_unity_cb_entry(shadertool.unity_ZBufferParams, 'constant')
_ZBufferParams = cb_offset(_ZBufferParams_cb, _ZBufferParams_offset)
except KeyError:
debug_verbose(0, 'Shader does not have all required values for the Unity lighting fix')
return
# XXX: Directional lighting shaders seem to have a bogus _ZBufferParams!
try:
match = shader.find_header(shadertool.unity_headers_attached)
except KeyError:
debug('Skipping possible depth buffer source - shader does not have Unity headers attached so unable to check what kind of lighting shader it is')
has_unity_headers = False
else:
has_unity_headers = True
try:
match = shader.find_header(shadertool.unity_shader_directional_lighting)
except KeyError:
try:
match = shader.find_header(shadertool.unity_CameraDepthTexture)
except KeyError:
debug_verbose(0, 'Shader does not use _CameraDepthTexture')
return
_CameraDepthTexture = 't' + match.group('texture')
else:
_CameraDepthTexture = None
debug_verbose(0, '_CameraToWorld in %s, _ZBufferParams in %s' % (_CameraToWorld, _ZBufferParams))
fov_reg = shader.add_ps_texcoord_input(int(args.fix_unity_lighting_ps[-1]), 1,
comment='New input from vertex shader with unity_CameraInvProjection[0].x:')