-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathctree.py
5060 lines (4429 loc) · 171 KB
/
ctree.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
# © 2021-2023 Intel Corporation
# SPDX-License-Identifier: MPL-2.0
# Intermediate representation of the device model
import os.path
import re
import abc
import collections
import operator
import itertools
import math
from functools import reduce
from contextlib import nullcontext
from dml import objects, symtab, logging, crep, serialize
from .logging import *
from .messages import *
from .output import out, quote_filename
from .types import *
from .expr import *
from .expr_util import *
from .slotsmeta import auto_init
from . import dmlparse, output
import dml.globals
# set from codegen.py
codegen_call_expr = None
__all__ = (
'endian_convert_expr',
'source_for_assignment',
'Location',
'ExpressionSymbol',
'LiteralSymbol',
'mkCompound',
'mkNull', 'Null',
'mkLabel',
'mkUnrolledLoop',
'mkGoto',
'mkReturnFromInline',
'mkThrow',
'mkGotoBreak',
'mkTryCatch',
'mkInline',
'mkInlinedMethod',
'mkComment',
'mkAssert',
'mkReturn',
'mkDelete',
'mkExpressionStatement',
'mkAfter',
'mkAfterOnHook',
'mkImmediateAfter',
'mkIf',
'mkWhile',
'mkDoWhile',
'mkFor',
'mkForeachSequence', 'ForeachSequence',
'mkSwitch',
'mkSubsequentCases',
'mkCase',
'mkDefault',
'mkVectorForeach',
'mkBreak',
'mkContinue',
'mkAssignStatement',
'mkCopyData',
'mkIfExpr', 'IfExpr',
#'BinOp',
#'Test',
#'Flag',
#'Logical',
'mkAnd',
'mkOr',
#'Compare',
'mkLessThan',
'mkLessThanOrEquals',
'mkGreaterThan',
'mkGreaterThanOrEquals',
'mkEquals',
'mkNotEquals',
#'BitBinOp',
'mkBitAnd',
'mkBitOr', 'BitOr', 'BitOr_dml12',
'mkBitXOr',
'BitShift',
'mkShL',
'mkShR',
#'ArithBinOp',
'mkMult',
'mkDiv',
'mkMod',
'mkAdd',
'mkSubtract',
'mkAssignOp',
'mkAddressOf',
'mkDereference',
'mkNot',
'mkBitNot',
'mkUnaryMinus',
'mkUnaryPlus',
'mkPreInc',
'mkPreDec',
'mkPostInc',
'mkPostDec',
'mkMethodPresent',
'mkBitSlice',
'InterfaceMethodRef',
'mkHookSendNowRef', 'HookSendNowRef',
'mkHookSendNowApply', 'HookSendNowApply',
'mkHookSendRef', 'HookSendRef',
'mkHookSendApply', 'HookSendApply',
'mkNew',
#'Constant',
'mkIntegerConstant', 'IntegerConstant',
'mkIntegerLiteral',
'mkFloatConstant', 'FloatConstant',
'mkStringConstant', 'StringConstant',
'AbstractList',
'mkList', 'List',
'mkSequenceLength',
'mkObjectList',
'mkEachIn', 'EachIn',
'mkBoolConstant',
'mkUndefined', 'Undefined',
'TraitParameter',
'TraitSessionRef',
'TraitHookRef',
'TraitHookArrayRef',
'TraitMethodRef',
'TraitMethodIndirect',
'TraitMethodDirect',
'mkTraitUpcast',
'TraitUpcast',
'TraitObjectCast',
'ObjIdentity',
'TraitObjIdentity',
'ObjTraitRef',
'NodeArrayRef',
'SessionVariableRef',
'mkNodeRef', 'NodeRef',
'Variable',
'mkLocalVariable',
'mkStaticVariable',
'mkSubRef',
'mkIndex',
'mkCast',
'Cast',
'mkInlinedParam',
'InvalidSymbol',
'mkQName', 'QName',
'mkDeviceObject',
'LogGroup',
'mkStructDefinition',
'mkDeclaration',
'mkCText',
'Initializer', 'ExpressionInitializer', 'CompoundInitializer',
'DesignatedStructInitializer', 'MemsetInitializer',
'as_bool',
'as_int',
'sym_declaration',
'lookup_var',
'log_statement',
'all_index_exprs',
'get_anonymized_name',
'mkHiddenName', 'HiddenName',
'mkHiddenQName', 'HiddenQName',
)
def assert_type(site, expr, type):
if not isinstance(expr, type):
raise ICE(site, repr(expr)+" is not a "+repr(type))
def comparable_types(expr1, expr2, equality):
"Check if two expressions can be compared"
typ1 = realtype(expr1.ctype())
typ2 = realtype(expr2.ctype())
if typ1.is_arith and typ2.is_arith:
return True
if isinstance(typ1, (TPtr, TArray)) and isinstance(typ2, (TPtr, TArray)):
return True
if equality and isinstance(typ1, TBool) and isinstance(typ2, TBool):
return True
return False
def assert_comparable_types(site, expr1, expr2, equality):
"Assert that two expressions can be compared"
if not comparable_types(expr1, expr2, equality):
typ1 = realtype(expr1.ctype())
typ2 = realtype(expr2.ctype())
raise EILLCOMP(site, expr1, typ1, expr2, typ2)
class ExpressionSymbol(symtab.Symbol):
"""A symbol that corresponds to an expression."""
def __init__(self, name, expr, site):
super(ExpressionSymbol, self).__init__(name, value = expr, site = site)
@property
def type(self):
return self.value.ctype()
def expr(self, site):
expr = self.value.copy(site)
expr.incref()
return expr
class LiteralSymbol(symtab.Symbol):
"A symbol with corresponds directly to an opaque C identifier"
def __init__(self, name, type, site, crep=None):
super(LiteralSymbol, self).__init__(name, value = crep or name,
site = site)
self.type = type
def expr(self, site):
return mkLit(site, self.value, self.type)
class Location(object):
__slots__ = ('node', 'indices')
def __init__(self, node, indices):
self.node = node
# Many functions take an 'indices' arg derived from
# Location.indices; we generally allow such functions to assume
# that indices are either TInt or StaticIndex.
assert all(isinstance(e, StaticIndex)
or isinstance(realtype(e.ctype()), TInt)
for e in indices)
self.indices = indices
def __repr__(self):
return 'Location(%r, %r)' % (self.node, self.indices)
def method(self):
if isinstance(self.node, objects.Method):
return self.node
else:
return None
#
# Statements
#
class ControlFlow(object):
'''Represents the set of possible ways execution can proceed, within
the same method, after execution of a statement:
- fallthrough: may proceed to the following statement.
- throw: may throw
- br: may break an enclosing switch or loop
Note that returning from the method, crashing, or entering an
infinite loop count as equivalent here.
Note also that 'continue' statements are not represented for in a
control flow. This is because their jump destination is already is
known to be reachable; since a 'continue' cannot fall through and don't
add any new path for execution to proceed, it can be
considered equivalent to a false assertion for the purposes of
our control flow analysis.'''
__slots__ = ('fallthrough', 'throw', 'br')
def __init__(self, **args):
for prop in self.__slots__:
setattr(self, prop, False)
for prop in args:
# will trigger error if a kw arg is misspelt
setattr(self, prop, args[prop])
def __repr__(self):
return 'ControlFlow(%s)' % (
', '.join('%s=%r' % (prop, getattr(self, prop))
for prop in self.__slots__))
def union(self, other, **args):
'''A control flow with the union of exit paths from two control flows.
Keyword args provide explicit overrides.'''
for prop in self.__slots__:
args.setdefault(prop, getattr(self, prop) or getattr(other, prop))
return ControlFlow(**args)
def replace(self, **args):
'''Return a copy of this flow, with selected properties overridden'''
for prop in self.__slots__:
args.setdefault(prop, getattr(self, prop))
return ControlFlow(**args)
class Statement(Code):
slots = ('context',)
# True if the statement declares a symbol in the containing scope
is_declaration = False
is_empty = False
def __init__(self, site):
self.site = site
self.context = ErrorContext.current()
@abc.abstractmethod
def toc(self): pass
def toc_inline(self): return self.toc()
def control_flow(self):
'''Rudimentary control flow analysis: Return a ControlFlow object
indicating how this statement affects the control flow.
The analysis is used to prove that control cannot reach the
end of the method, i.e., that either a return statement is
reached, an uncaught exception is reached, or an infinite loop
is entered.
The analysis is conjectured to be sound, i.e., if our analysis
deduces that control cannot reach the end of a method, then
this can be trusted.
The analysis is also rather simple and limited: one can
construct code where a proper analysis of the full control
flow graph would prove that control cannot reach the end of
the method, but where our analysis fails to prove this. For an
example, see test/1.4/errors/T_ENORET_throw_after_break.dml.'''
return ControlFlow(fallthrough=True)
class Compound(Statement):
@auto_init
def __init__(self, site, substatements):
assert isinstance(substatements, list)
def toc(self):
out('{\n', postindent = 1)
self.toc_inline()
out('}\n', preindent = -1)
def toc_inline(self):
for substatement in self.substatements:
substatement.toc()
def control_flow(self):
acc = ControlFlow(fallthrough=True)
for sub in self.substatements:
flow = sub.control_flow()
acc = acc.union(flow, fallthrough=flow.fallthrough)
if not acc.fallthrough:
return acc
return acc
def mkCompound(site, statements):
"Create a simplified Compound() from a list of ctree.Statement"
collapsed = []
for stmt in statements:
if (isinstance(stmt, Compound)
and not any(subsub.is_declaration
for subsub in stmt.substatements)):
collapsed.extend(stmt.substatements)
elif not stmt.is_empty:
collapsed.append(stmt)
if len(collapsed) == 1 and not collapsed[0].is_declaration:
return collapsed[0]
elif collapsed:
return Compound(site, collapsed)
else:
return mkNull(site)
class Null(Statement):
is_empty = True
def toc_inline(self):
pass
def toc(self):
if self.site:
self.linemark()
out(';\n')
mkNull = Null
class Label(Statement):
def __init__(self, site, label, unused=False):
Statement.__init__(self, site)
self.label = label
self.unused = unused
def toc(self):
out('%s: %s;\n' % (self.label, 'UNUSED'*self.unused), preindent = -1,
postindent = 1)
mkLabel = Label
class UnrolledLoop(Statement):
@auto_init
def __init__(self, site, substatements, break_label):
assert isinstance(substatements, list)
def toc(self):
self.linemark()
out('{\n', postindent = 1)
self.toc_inline()
out('}\n', preindent = -1)
def toc_inline(self):
for substatement in self.substatements:
substatement.toc()
if self.break_label is not None:
self.linemark()
out(f'{self.break_label}: UNUSED;\n')
def control_flow(self):
bodyflow = mkCompound(self.site, self.substatements).control_flow()
return bodyflow.replace(fallthrough=(bodyflow.fallthrough
or bodyflow.br), br=False)
mkUnrolledLoop = UnrolledLoop
class Goto(Statement):
@auto_init
def __init__(self, site, label): pass
def toc(self):
out('goto %s;\n' % (self.label,))
def control_flow(self):
raise ICE(self.site, 'goto is 1.2 only, control_flow() is 1.4+ only')
mkGoto = Goto
class ReturnFromInline(Goto):
def control_flow(self):
return ControlFlow()
mkReturnFromInline = ReturnFromInline
class Throw(Goto):
def control_flow(self):
return ControlFlow(throw=True)
mkThrow = Throw
class GotoBreak(Goto):
def control_flow(self):
return ControlFlow(br=True)
mkGotoBreak = GotoBreak
class TryCatch(Statement):
'''A DML try/catch statement. Catch block is represented as an if (false)
block with a catch label, to which Throw statements inside will go.'''
@auto_init
def __init__(self, site, label, tryblock, catchblock): pass
def toc_inline(self):
self.tryblock.toc()
if (dml.globals.dml_version != (1, 2)
and not self.tryblock.control_flow().fallthrough):
out('%s: ;\n' % (self.label,))
self.catchblock.toc()
else:
# Our fallthrough analysis is more conservative than Coverity's
coverity_marker('unreachable', site=self.site)
out('if (false) {\n')
out('%s: ;\n' % (self.label,), postindent=1)
self.catchblock.toc_inline()
out('}\n', preindent=-1)
def toc(self):
out('{\n', postindent = 1)
self.toc_inline()
out('}\n', preindent = -1)
def control_flow(self):
tryflow = self.tryblock.control_flow()
if not tryflow.throw:
# catch block is dead
return tryflow
catchflow = self.catchblock.control_flow()
return tryflow.union(catchflow, throw=catchflow.throw)
def mkTryCatch(site, label, tryblock, catchblock):
if not label:
return tryblock
return TryCatch(site, label, tryblock, catchblock)
class Inline(Statement):
@auto_init
def __init__(self, site, str): pass
def toc(self):
out(self.str + '\n')
mkInline = Inline
class InlinedMethod(Statement):
'''Wraps the body of an inlined method, to protect it from analysis'''
@auto_init
def __init__(self, site, method, body): pass
def toc(self):
self.body.toc()
def toc_inline(self):
self.body.toc_inline()
def control_flow(self):
return ControlFlow(fallthrough=True, throw=self.method.throws)
mkInlinedMethod = InlinedMethod
class Comment(Statement):
@auto_init
def __init__(self, site, str): pass
def toc(self):
# self.linemark()
out('/* %s */\n' % self.str)
mkComment = Comment
class Assert(Statement):
@auto_init
def __init__(self, site, expr): pass
def toc(self):
out('DML_ASSERT("%s", %d, %s);\n'
% (quote_filename(self.site.filename()),
self.site.lineno, self.expr.read()))
def control_flow(self):
return ControlFlow(
fallthrough=bool(not self.expr.constant or self.expr.value))
def mkAssert(site, expr):
return Assert(site, expr)
class Return(Statement):
@auto_init
def __init__(self, site, expr): pass
def toc(self):
self.linemark()
if self.expr is None:
out('return;\n')
else:
out('return %s;\n' % self.expr.read())
def control_flow(self):
return ControlFlow()
def mkReturn(site, expr, rettype=None):
if rettype and not dml.globals.compat_dml12_int(site):
expr = source_for_assignment(site, rettype, expr)
return Return(site, expr)
class Delete(Statement):
@auto_init
def __init__(self, site, expr): pass
def toc(self):
out('MM_FREE(%s);\n' % self.expr.read())
def mkDelete(site, expr):
return Delete(site, expr)
class ExpressionStatement(Statement):
@auto_init
def __init__(self, site, expr): pass
def toc(self):
#if not self.site:
# print 'NOSITE', str(self), repr(self)
self.linemark()
# out('/* %s */\n' % repr(self))
s = self.expr.discard()
out(s+';\n')
def mkExpressionStatement(site, expr):
if isinstance(expr, Constant):
return mkNull(site)
return ExpressionStatement(site, expr)
def toc_constsafe_pointer_assignment(site, source, target, typ):
target_val = mkDereference(site,
Cast(site, mkLit(site, target, TPtr(void)), TPtr(typ)))
mkAssignStatement(site, target_val,
ExpressionInitializer(mkLit(site, source, typ))).toc()
class After(Statement):
@auto_init
def __init__(self, site, unit, delay, domains, info, indices,
args_init):
crep.require_dev(site)
def toc(self):
self.linemark()
objarg = '&_dev->obj'
out(f'if (SIM_object_clock({objarg}) == NULL)\n', postindent=1)
out(f'''SIM_log_error({objarg}, 0, "Attribute 'queue' is '''
+ '''not set, ignoring delayed call");\n''')
out('else {\n', preindent=-1, postindent=1)
if self.indices or self.info.args_type or self.domains:
out('_simple_event_data_t *_data = MM_ZALLOC(1, '
+ '_simple_event_data_t);\n')
if self.indices:
out(f'uint32 *_event_indices = MM_MALLOC({len(self.indices)}, '
+ 'uint32);\n')
for (i, index_expr) in enumerate(self.indices):
out(f'_event_indices[{i}] = {index_expr.read()};\n')
out('_data->indices = _event_indices;\n')
args_type = self.info.args_type
if args_type:
out('%s = %s;\n'
% (args_type.declaration('_event_args'),
self.args_init.args_init()))
out('_data->args = MM_MALLOC(1, %s);\n'
% (args_type.declaration(''),))
toc_constsafe_pointer_assignment(self.site, '_event_args',
'_data->args', args_type)
if self.domains:
out('_identity_t *_event_domains = '
+ f'MM_MALLOC({len(self.domains)}, _identity_t);\n')
for (i, domain) in enumerate(self.domains):
out(f'_event_domains[{i}] = {domain.read()};\n')
out(f'_data->no_domains = {len(self.domains)};\n')
out('_data->domains = _event_domains;\n')
data = '(lang_void *)_data'
else:
data = 'NULL'
out(f'SIM_event_post_{self.unit}(SIM_object_clock({objarg}), '
+ f'{crep.get_evclass(self.info.key)}, {objarg}, '
+ f'{self.delay.read()}, {data});\n')
out("}\n", preindent = -1)
mkAfter = After
def resolve_hookref(hookref):
return ('&_dev->' + crep.cref_hook(hookref.hook, hookref.indices)
if isinstance(hookref, HookRef) else
f'_DML_resolve_hookref(_dev, _hook_aux_infos, {hookref.read()})')
class AfterOnHook(Statement):
slots = ('info',)
@auto_init
def __init__(self, site, domains, hookref_expr, info, indices,
args_init):
crep.require_dev(site)
def toc(self):
self.linemark()
hookref = resolve_hookref(self.hookref_expr)
indices = ('(const uint32 []) {%s}'
% (', '.join(i.read() for i in self.indices),)
if self.indices else 'NULL')
args = ('(%s){%s}'
% (TArray(self.info.args_type,
mkIntegerLiteral(self.site, 1)).declaration(''),
self.args_init.args_init())
if self.info.args_type else 'NULL')
domains = ('(const _identity_t []) {%s}'
% (', '.join(domain.read() for domain in self.domains),)
if self.domains else 'NULL')
out(f'_DML_attach_callback_to_hook({hookref}, '
+ f'&_after_on_hook_infos[{self.info.uniq}], {indices}, '
+ f'{len(self.indices)}, {args}, {domains}, '
+ f'{len(self.domains)});\n')
mkAfterOnHook = AfterOnHook
class ImmediateAfter(Statement):
@auto_init
def __init__(self, site, domains, info, indices, args_init):
crep.require_dev(site)
def toc(self):
self.linemark()
indices = ('(const uint32 []) {%s}'
% (', '.join(i.read() for i in self.indices),)
if self.indices else 'NULL')
if self.info.args_type is not None:
args = ('(%s){%s}'
% (TArray(self.info.args_type,
mkIntegerLiteral(self.site, 1)).declaration(''),
self.args_init.args_init()))
args_size = f'sizeof({self.info.args_type.declaration("")})'
else:
(args, args_size) = ('NULL', '0')
domains = ('(const _identity_t []) {%s}'
% (', '.join(domain.read() for domain in self.domains),)
if self.domains else 'NULL')
out('_DML_post_immediate_after('
+ '&_dev->obj, _dev->_immediate_after_state, '
+ f'{self.info.cident_callback}, {indices}, {len(self.indices)}, '
+ f'{args}, {args_size}, {domains}, {len(self.domains)});\n')
mkImmediateAfter = ImmediateAfter
class If(Statement):
@auto_init
def __init__(self, site, cond, truebranch, falsebranch):
assert_type(site, cond.ctype(), TBool)
assert_type(site, truebranch, Statement)
assert_type(site, falsebranch, (Statement, type(None)))
def toc(self):
self.linemark()
out('if ('+self.cond.read()+') {\n', postindent = 1)
self.truebranch.toc_inline()
if isinstance(self.falsebranch, If):
out('} else ', preindent = -1)
if dml.globals.linemarks:
out('\n')
self.falsebranch.toc()
elif self.falsebranch:
out('} else {\n', preindent = -1, postindent = 1)
self.falsebranch.toc_inline()
out('}\n', preindent = -1)
else:
out('}\n', preindent = -1)
def control_flow(self):
a = self.truebranch.control_flow()
b = (self.falsebranch.control_flow() if self.falsebranch
else ControlFlow(fallthrough=True))
return a.union(b)
def mkIf(site, cond, truebranch, falsebranch = None):
assert isinstance(cond.ctype(), TBool)
if cond.constant:
if cond.value:
return truebranch
elif falsebranch:
return falsebranch
else:
return mkNull(site)
return If(site, cond, truebranch, falsebranch)
class While(Statement):
@auto_init
def __init__(self, site, cond, stmt):
assert_type(site, cond.ctype(), TBool)
assert_type(site, stmt, Statement)
def toc(self):
self.linemark()
# out('/* %s */\n' % repr(self))
out('while ('+self.cond.read()+') {\n', postindent = 1)
self.stmt.toc_inline()
out('}\n', preindent = -1)
def control_flow(self):
bodyflow = self.stmt.control_flow()
if self.cond.constant:
if self.cond.value:
# infinite loop
return bodyflow.replace(fallthrough=bodyflow.br, br=False)
else:
# dead body
return ControlFlow(fallthrough=True)
else:
# fallthrough is possible if condition is initially false
return bodyflow.replace(fallthrough=True, br=False)
def mkWhile(site, expr, stmt):
return While(site, expr, stmt)
class DoWhile(Statement):
@auto_init
def __init__(self, site, cond, stmt):
assert_type(site, cond.ctype(), TBool)
assert_type(site, stmt, Statement)
def toc(self):
self.linemark()
# out('/* %s */\n' % repr(self))
out('do {\n', postindent = 1)
self.stmt.toc_inline()
out('} while ('+self.cond.read()+');\n', preindent = -1)
def control_flow(self):
bodyflow = self.stmt.control_flow()
if self.cond.constant and self.cond.value:
# infinite loop
return bodyflow.replace(fallthrough=bodyflow.br, br=False)
else:
return bodyflow.replace(
fallthrough=bodyflow.fallthrough or bodyflow.br, br=False)
def mkDoWhile(site, expr, stmt):
return DoWhile(site, expr, stmt)
class For(Statement):
@auto_init
def __init__(self, site, pres, cond, posts, stmt):
assert_type(site, cond.ctype(), TBool)
assert_type(site, stmt, Statement)
def toc(self):
self.linemark()
out('for (%s; %s; ' % (", ".join(pre.discard()
for pre in self.pres),
self.cond.read()))
if all(isinstance(post, ExpressionStatement) for post in self.posts):
# common case: all post statements are expressions, so
# traditional for loop can be produced
out(', '.join(post.expr.discard() for post in self.posts))
else:
# general case: arbitrary statements in post code;
# encapsulate in a statement expression
out('({\n', postindent = 1)
for post in self.posts:
post.toc()
out(' })', preindent = -1)
out(') {\n', postindent = 1)
self.stmt.toc_inline()
out('}\n', preindent = -1)
def control_flow(self):
bodyflow = self.stmt.control_flow()
if self.cond.constant:
if self.cond.value:
# infinite loop
return bodyflow.replace(fallthrough=bodyflow.br, br=False)
else:
# dead body
return ControlFlow(fallthrough=True)
else:
# fallthrough is possible if condition is initially false
return bodyflow.replace(fallthrough=True, br=False)
def mkFor(site, pres, expr, posts, stmt):
return For(site, pres, expr, posts, stmt)
class ForeachSequence(Statement):
@staticmethod
def itervar_initializer(site, trait):
trait_type = TTrait(trait)
vtable_init = ExpressionInitializer(mkLit(site, '_list.vtable',
trait_type))
list_id_init = ExpressionInitializer(mkLit(site, '_list.id',
TInt(32, False)))
inner_idx_init = ExpressionInitializer(mkLit(site, '_inner_idx',
TInt(32, False)))
obj_ref_init = CompoundInitializer(site,
[list_id_init, inner_idx_init])
return CompoundInitializer(site, [vtable_init, obj_ref_init])
@auto_init
def __init__(self, site, trait, each_in_expr, body, break_label): pass
def toc(self):
self.linemark()
out('{\n', postindent=1)
self.linemark()
out(f'_each_in_t __each_in_expr = {self.each_in_expr.read()};\n')
coverity_marker('unreachable', site=self.site)
out('for (uint32 _outer_idx = 0; _outer_idx < __each_in_expr.num; '
+ '++_outer_idx) {\n', postindent=1)
out(f'_vtable_list_t _list = {EachIn.array_ident(self.trait)}'
+ '[__each_in_expr.base_idx + _outer_idx];\n')
out('uint32 _num = _list.num / __each_in_expr.array_size;\n')
out('uint32 _start = _num * __each_in_expr.array_idx;\n')
coverity_marker('unreachable', site=self.site)
out('for (uint32 _inner_idx = _start; _inner_idx < _start + _num; '
+ '++_inner_idx) {\n', postindent=1)
self.body.toc_inline()
out('}\n', preindent=-1)
out('}\n', preindent=-1)
if self.break_label is not None:
self.linemark()
out(f'{self.break_label}: UNUSED;\n', preindent=-1, postindent = 1)
out('}\n', preindent=-1)
def control_flow(self):
bodyflow = self.body.control_flow()
# fallthrough is possible if the sequence is empty
return bodyflow.replace(fallthrough=True, br=False)
mkForeachSequence = ForeachSequence
class Switch(Statement):
@auto_init
def __init__(self, site, expr, stmt):
assert_type(site, expr, Expression)
assert_type(site, stmt, Statement)
def toc(self):
self.linemark()
# out('/* %s */\n' % repr(self))
out('switch ('+self.expr.read()+') {\n', postindent = 1)
self.stmt.toc_inline()
out('}\n', preindent = -1)
def control_flow(self):
assert self.site.dml_version() != (1, 2)
# guaranteed by grammar in DML 1.4.
assert isinstance(self.stmt, Compound)
found_default = False
# The possible exit paths from the sequence of statements
# processed so far
flow = ControlFlow(fallthrough=True)
for stmt in self.stmt.substatements:
if (isinstance(stmt, Default)
or (isinstance(stmt, SubsequentCases)
and stmt.has_default)):
found_default = True
if isinstance(stmt, (Default, Case, SubsequentCases)):
flow = flow.replace(fallthrough=True)
elif flow.fallthrough:
f = stmt.control_flow()
flow = flow.union(f, fallthrough=f.fallthrough)
return flow.replace(
fallthrough=flow.fallthrough or flow.br or not found_default,
br=False)
def mkSwitch(site, expr, stmt):
return Switch(site, as_int(expr), stmt)
class SubsequentCases(Statement):
@auto_init
def __init__(self, site, cases, has_default):
assert len(self.cases) > 0
def toc(self):
for (i, case) in enumerate(self.cases):
assert isinstance(case, (Case, Default))
site_linemark(case.site)
semi = ';' * (i == len(self.cases) - 1)
if isinstance(case, Case):
out(f'case {case.expr.read()}:{semi}\n', preindent = -1,
postindent = 1)
else:
out(f'default:{semi}\n', preindent = -1, postindent = 1)
mkSubsequentCases = SubsequentCases
class Case(Statement):
@auto_init
def __init__(self, site, expr): pass
def toc(self):
self.linemark()
out('case %s: ;\n' % self.expr.read(), preindent = -1, postindent = 1)
mkCase = Case
class Default(Statement):
@auto_init
def __init__(self, site): pass
def toc(self):
self.linemark()
out('default: ;\n', preindent = -1, postindent = 1)
mkDefault = Default
class VectorForeach(Statement):
@auto_init
def __init__(self, site, vect, var, stmt): pass
def toc(self):
out('VFOREACH(%s, %s) {\n' % (self.vect.read(), self.var.read()),
postindent = 1)
self.stmt.toc_inline()
out('}\n', preindent = -1)
def control_flow(self):
flow = self.stmt.control_flow()
return flow.replace(fallthrough=flow.fallthrough or flow.br, br=False)
def mkVectorForeach(site, vect, var, stmt):
return VectorForeach(site, vect, var, stmt)
class Break(Statement):
def toc(self):
out('break;\n')
def control_flow(self):
return ControlFlow(br=True)
mkBreak = Break
class Continue(Statement):
def toc(self):
out('continue;\n')
def control_flow(self):
return ControlFlow()
mkContinue = Continue
class AssignStatement(Statement):
@auto_init
def __init__(self, site, target, initializer):
assert isinstance(initializer, Initializer)
def toc(self):
out('{\n', postindent=1)
self.toc_inline()
out('}\n', preindent=-1)
def toc_inline(self):
self.initializer.assign_to(self.target, self.target.ctype())
mkAssignStatement = AssignStatement
def mkCopyData(site, source, target):
"Convert a copy statement to intermediate representation"
assignexpr = mkAssignOp(site, target, source)
return mkExpressionStatement(site, assignexpr)
#
# Expressions
#
def as_bool(e):
"Change this expression to a boolean expression, if possible"
t = e.ctype()
if isinstance(t, TBool):
return e
elif t.is_int and t.bits == 1:
if logging.show_porting and (isinstance(e, NodeRef)
or isinstance(e, LocalVariable)):
report(PBITNEQ(dmlparse.start_site(e.site),
dmlparse.end_site(e.site)))
return mkFlag(e.site, e)
elif isinstance(t, TPtr):
return mkNotEquals(e.site, e,
Lit(None, 'NULL', TPtr(TVoid()), 1))
else:
report(ENBOOL(e))
return mkBoolConstant(e.site, False)
def as_int(e):
"""Change this expression to a TInt type, if possible