-
Notifications
You must be signed in to change notification settings - Fork 108
/
program_analysis.ML
2326 lines (2152 loc) · 89.3 KB
/
program_analysis.ML
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 2020, Data61, CSIRO (ABN 41 687 119 230)
*
* SPDX-License-Identifier: BSD-2-Clause
*)
signature PROGRAM_ANALYSIS =
sig
type 'ce ctype = 'ce Absyn.ctype
type expr = Absyn.expr
type ecenv = Absyn.ecenv
type s2s_config = {anon_vars : bool, owners : string list,
allow_underscore_idents : bool,
munge_info_fname : string option}
type 'a rcd_env = (string * (string * 'a) list) list
type senv = int ctype rcd_env
(* Information necessary for name and definition generation.
- `src_name` is the name as it appears in the original source file, or a
synthetic name for return variables.
- `isa_name` is the munged name without the trailing `_'` suffixes (e.g.
`x___int` for a source variable called `x`).
- `alias` indicates if we should generate an abbreviation that aliases the
source name to the munged name. *)
type nm_info = {src_name : string, isa_name : MString.t, alias: bool}
type var_info
val is_global : var_info -> bool
val srcname : var_info -> string
val fullname : var_info -> string
val get_mname : var_info -> MString.t
val get_vi_fname : var_info -> string option
val get_vi_type : var_info -> int ctype
val get_vi_senv : var_info -> senv
val get_vi_attrs : var_info -> StmtDecl.gcc_attribute list
val declpos : var_info -> Region.t
val vi_compare : var_info * var_info -> order
datatype modify_var = M of var_info | TheHeap | PhantomState
| GhostState | AllGlobals
val mvar_compare : modify_var * modify_var -> order
val mvar_toString : modify_var -> string
structure MVar_Table : TABLE where type key = modify_var
datatype fncall_type = DirectCall of string
| FnPtrCall of int ctype * int ctype list
val fncall_cmp : fncall_type * fncall_type -> order
type csenv
val cse2ecenv : csenv -> ecenv
val get_array_mentions : csenv -> (int ctype * int) Binaryset.set
val get_senv : csenv -> senv
val get_rettype : string -> csenv -> int ctype option
val get_heaptypes : csenv -> int ctype Binaryset.set
val compute_callgraphs : csenv ->
{callgraph: string Binaryset.set Symtab.table,
callers : string Binaryset.set Symtab.table}
val get_addressed : csenv -> expr list MSymTab.table
val get_callers : csenv -> string Binaryset.set Symtab.table
val get_typedefs : csenv -> int ctype Symtab.table list
val get_vars : csenv -> var_info list Symtab.table
val get_globals : csenv -> var_info list
val get_globinits : csenv -> Absyn.expr MSymTab.table
val get_mangled_vars : csenv -> var_info list Symtab.table
val get_params : string -> csenv -> var_info list option
val get_embedded_fncalls : csenv -> fncall_type Binaryset.set
val get_addressed_vis : csenv -> var_info list
val get_vi_nm_info : csenv -> var_info -> nm_info
val get_modifies : csenv -> string -> modify_var Binaryset.set option
val get_functions : csenv -> string list
val get_fninfo : csenv -> (int ctype * bool * var_info list) Symtab.table
val get_hpfninfo : csenv -> Absyn.ext_decl Symtab.table
val update_hpfninfo0 : Absyn.ext_decl -> Absyn.ext_decl Symtab.table ->
Absyn.ext_decl Symtab.table
val get_defined_functions : csenv -> Region.Wrap.region Symtab.table
val get_read_globals : csenv -> modify_var Binaryset.set Symtab.table
val is_recursivefn : csenv -> string -> bool
val mvar_traverse : csenv -> csenv
val get_modified_global_locns : csenv -> string Binaryset.set MVar_Table.table
val calc_untouched_globals : csenv -> int ctype MSymTab.table
val fndes_callinfo : csenv -> expr -> fncall_type * (int ctype * int ctype list)
val fns_by_type : csenv -> int ctype * int ctype list -> string list
val cse_typing : csenv -> expr -> int ctype
val process_decls : s2s_config -> Absyn.ext_decl list ->
((Absyn.ext_decl list * Absyn.statement list) * csenv)
val function_specs : csenv -> Absyn.fnspec list Symtab.table
val sizeof : csenv -> int ctype -> int
val alignof : csenv -> int ctype -> int
val offset : csenv -> int ctype list -> int -> int
(* [offset csenv flds i]
given flds, a list of types (a structure's fields),
return offset in bytes of field with number i (indexing from
zero). offset env flds 0 always equals 0. *)
type asm_stmt_elements = (string * bool * expr option * expr list)
val split_asm_stmt : Absyn.statement_node -> asm_stmt_elements
val merge_asm_stmt : asm_stmt_elements -> Absyn.statement_node
val get_globals_rcd : csenv -> senv
type mungedb = {fun_name: string option, nm_info: nm_info} list
(* Returns the variable name munging information for all variables. *)
val get_mungedb : csenv -> mungedb
(* Writes the contents of the mungedb to a string list.
The list has one human-readable string per C declaration, sorted
alphabetically, with the following format per line:
C variable '{c_source_name}' \
declared {decl_info} -> Isabelle state field '{isabelle_name}' \
and {abbreviation_info}
Where:
- {c_source_name} is the name of the variable in the C source.
- {decl_info} indicates whether the variable was declared globally,
and if not then which function it was declared in.
- {isabelle_name} is the type-mangled name that we use in Isabelle
(e.g. "foo___int").
- {abbreviation_info} indicates whether an Isabelle abbreviation
was created between the short C name and the long Isabelle name.
For an example, see `./.testfiles/jiraver1241.thy`.
*)
val render_mungedb : mungedb -> string list
(* Writes the mungedb to the file specified in `munge_info_fname` (see
type s2s_config). *)
val export_mungedb : csenv -> unit
end
structure ProgramAnalysis : PROGRAM_ANALYSIS =
struct
open Absyn NameGeneration
type program = ext_decl list
type s2s_config = {anon_vars : bool, owners : string list,
allow_underscore_idents : bool, munge_info_fname : string option}
fun fname_str NONE = NameGeneration.initialisation_function
| fname_str (SOME f) = f
(* ----------------------------------------------------------------------
Collect all of a program's variables
The variables collected will be analysed to generate an appropriate
VCG environment state-space
---------------------------------------------------------------------- *)
type 'a rcd_env = (string * (string * 'a) list) list
type senv = int ctype rcd_env
datatype var_info =
VI of {name : string,
return_var : bool,
vtype : int ctype,
struct_env : senv,
(* Name of the function in which this variable was declared (if
any). *)
fname : string option,
proto_param : bool,
munged_name : MString.t,
declared_at : Region.t,
attrs : gcc_attribute list}
type nm_info = {src_name : string, isa_name : MString.t, alias: bool}
fun viToString (VI {name, fname,...}) =
case fname of
NONE => "global "^name
| SOME f => name ^ " (in " ^ f ^")"
val fullname = viToString
fun srcname (VI{name,...}) = name
fun get_mname (VI {munged_name, ...}) = munged_name
fun get_vi_fname (VI {fname,...}) = fname
fun get_vi_type (VI {vtype,...}) = vtype
fun get_vi_senv (VI {struct_env,...}) = struct_env
fun declpos (VI {declared_at,...}) = declared_at
fun vi_compare(VI vi1, VI vi2) = let
val ocmp = option_compare and pcmp = pair_compare and scmp = String.compare
val mscmp = MString.compare
in
pcmp (ocmp scmp, pcmp (scmp, mscmp))
((#fname vi1, (#name vi1, #munged_name vi1)),
(#fname vi2, (#name vi2, #munged_name vi2)))
end
(* name will be NameGeneration.return_var_name if the variable is a
"return" variable. There will be at least one such per function,
unless the function returns "void".
fname is NONE if the variable is global, "return" variables are not
global.
The struct_env is the structure type environment that is in force at the
point of the variable's declaration. This allows the consumer of this
data to figure out what is meant by a Struct s type.
return_var is true if the variable is a return variable.
proto_param is true if the variable has been created from a
prototype function declaration; such names can be overridden if a
function definition later occurs.
*)
fun is_global (VI r) = case #fname r of NONE => true | _ => false
fun fnToString NONE = "at global level"
| fnToString (SOME s) = "in function "^s
fun types_compatible global ty1 ty2 =
(* All locals need to be fully specified, but global arrays are special. *)
if not global then ty1 = ty2
else
case (ty1, ty2) of
(Array(ty1', sz1), Array(ty2', sz2)) =>
(ty1' = ty2') andalso (sz1 = sz2 orelse sz1 = NONE orelse sz2 = NONE)
| _ => ty1 = ty2
fun max_type ty1 ty2 =
(* assumes types are compatible *)
case (ty1, ty2) of
(Array(_, NONE), _) => ty2
| (_, Array(_, NONE)) => ty1
| _ => ty1
fun vars_compatible vi1 vi2 =
get_mname vi1 <> get_mname vi2 orelse
is_global vi1 <> is_global vi2 orelse
types_compatible (is_global vi1) (get_vi_type vi1) (get_vi_type vi2)
(* ----------------------------------------------------------------------
vars field contains list of all variables of a given original name
that are encountered.
scope contains a stack of varinfo information, where top element
of the stack is the current scope (innermost block).
variables in these tables are indexed by their original names.
---------------------------------------------------------------------- *)
datatype modify_var = M of var_info | TheHeap | PhantomState
| GhostState | AllGlobals
(* the AllGlobals summary is used in initial analysis of function bodies.
Underspecified operations modify AllGlobals rather than listing all the
actual globals, so that globals which are never *explicitly* modified can
still be candidates for const promotion. AllGlobals is expanded out once that
is done. *)
fun mvar_compare (mv1, mv2) = let
fun mvid (M _) = 1
| mvid TheHeap = 2
| mvid PhantomState = 3
| mvid GhostState = 4
| mvid AllGlobals = 5
fun mvc2 (M vi1, M vi2) = vi_compare (vi1, vi2)
| mvc2 _ = EQUAL
val id1 = mvid mv1
val id2 = mvid mv2
in if id1 < id2 then LESS else (if id1 > id2
then GREATER
else mvc2 (mv1, mv2)) end
fun mvar_toString TheHeap = "<the heap>"
| mvar_toString (M vi) = MString.dest (get_mname vi)
| mvar_toString PhantomState = "<phantom state>"
| mvar_toString GhostState = "<ghost state>"
| mvar_toString AllGlobals = "<*>"
structure MVar_Table = Table(struct type key = modify_var
val ord = mvar_compare
end)
datatype fncall_type = DirectCall of string
| FnPtrCall of int ctype * int ctype list
val tycmp = ctype_compare Int.compare
val funtycmp = pair_compare (tycmp, list_compare tycmp)
fun fncall_cmp (f1,f2) =
case (f1, f2) of
(DirectCall s1, DirectCall s2) => String.compare(s1, s2)
| (DirectCall _, _) => LESS
| (_, DirectCall _) => GREATER
| (FnPtrCall x, FnPtrCall y) => funtycmp (x,y)
structure TypesTab = Table(struct type key = int ctype * int ctype list
val ord = funtycmp
end)
datatype csenv (* CalculateState environment *) =
CSE of {senv : senv, allow_underscore_idents : bool,
anon_vars : bool,
fninfo : (int ctype * bool * var_info list) Symtab.table,
hpfninfo : Absyn.ext_decl Symtab.table,
vars : var_info list Symtab.table,
(* A mapping from declared (source) variable name to a mangled
name. `local_aliases[src] = mn` implies that `src` should become
an abbreviation for `mn`. *)
local_aliases : MString.t Symtab.table,
(* A mapping from mangled variable names to the matching variable
declarations. `demangle_table[long_name][5]` is a variable which
received the mangled name `long_name`.
Excludes global vars, anonymous local vars, and return vars. *)
mangled_vars : var_info list Symtab.table,
scope : var_info Symtab.table list,
array_mentions : (int ctype * int) Binaryset.set,
enumenv : string wrap list *
(IntInf.int * string option) Symtab.table,
globinits : Absyn.expr MSymTab.table,
heaptypes : int ctype Binaryset.set,
call_info : fncall_type Binaryset.set Symtab.table,
caller_info : string Binaryset.set Symtab.table,
addressed : expr list MSymTab.table,
embedded_fncalls : fncall_type Binaryset.set,
recursive_functions : string Binaryset.set,
defined_functions : Region.Wrap.region Symtab.table,
modifies : modify_var Binaryset.set Symtab.table,
modify_locs : string Binaryset.set MVar_Table.table,
read_globals : modify_var Binaryset.set Symtab.table,
typedefs : int ctype Symtab.table list,
fnspecs : fnspec list Symtab.table,
owners : string list,
munge_info_fname : string option}
fun get_vars (CSE {vars,...}) = vars
fun get_mangled_vars (CSE {mangled_vars, ...}) = mangled_vars
fun get_senv (CSE {senv,...}) = senv
fun get_scope (CSE {scope,...}) = scope
fun get_fulleenv (CSE {enumenv,...}) = enumenv
fun get_globinits (CSE {globinits,...}) = globinits
fun get_enumenv cse = #2 (get_fulleenv cse)
fun get_fninfo (CSE {fninfo, ...}) = fninfo
fun get_hpfninfo (CSE {hpfninfo, ...}) = hpfninfo
fun get_rettype fnname (CSE {fninfo,...}) =
Option.map #1 (Symtab.lookup fninfo fnname)
fun get_params fname (CSE {fninfo,...}) =
Option.map #3 (Symtab.lookup fninfo fname)
fun get_callgraph (CSE {call_info,...}) = call_info
fun get_callers (CSE {caller_info,...}) = caller_info
fun get_modifies (CSE {modifies,...}) fname = Symtab.lookup modifies fname
fun get_defined_functions (CSE {defined_functions = d, ...}) = d
fun get_typedefs (CSE {typedefs,...}) = typedefs
fun get_read_globals (CSE {read_globals,...}) = read_globals
fun get_anon_vars (CSE {anon_vars, ...}) = anon_vars
fun get_owners (CSE{owners,...}) = owners
fun get_allow_underscores(CSE{allow_underscore_idents = aui,...}) = aui
fun get_fields cse s = valOf (StrictCBasics.assoc(get_senv cse, s))
handle Option =>
raise Fail ("get_fields: no fields for "^s)
fun get_array_mentions (CSE {array_mentions,...}) = array_mentions
fun get_heaptypes (CSE {heaptypes,...}) = heaptypes
fun get_addressed (CSE {addressed,...}) = addressed
fun get_embedded_fncalls (CSE {embedded_fncalls, ...}) = embedded_fncalls
fun get_globals (CSE {vars,...}) = let
fun innerfold (vi,acc) =
if is_global vi andalso not (function_type (get_vi_type vi)) then
vi::acc
else acc
fun foldthis (_, vilist) acc = List.foldl innerfold acc vilist
in
List.rev (Symtab.fold foldthis vars [])
end
fun get_functions (CSE {fninfo,...}) = Symtab.keys fninfo
fun function_specs (CSE {fnspecs,...}) = fnspecs
fun is_recursivefn (CSE {recursive_functions,...}) s =
Binaryset.member(recursive_functions, s)
fun get_modified_global_locns (CSE {modify_locs,...}) = modify_locs
fun emptycse ({anon_vars,owners,allow_underscore_idents = aui,munge_info_fname,...} : s2s_config)=
CSE {senv = [], anon_vars = anon_vars, allow_underscore_idents = aui,
vars = Symtab.empty, local_aliases = Symtab.empty, mangled_vars = Symtab.empty,
scope = [Symtab.empty],
fninfo = Symtab.empty, hpfninfo = Symtab.empty,
enumenv = ([],Symtab.empty),
heaptypes = Binaryset.empty (ctype_compare Int.compare),
array_mentions = Binaryset.empty (pair_compare
(ctype_compare Int.compare,
Int.compare)),
call_info = Symtab.empty,
caller_info = Symtab.empty,
addressed = MSymTab.empty,
defined_functions = Symtab.empty,
embedded_fncalls = Binaryset.empty fncall_cmp,
recursive_functions = Binaryset.empty String.compare,
modifies = Symtab.empty, modify_locs = MVar_Table.empty,
typedefs = [], fnspecs = Symtab.empty, read_globals = Symtab.empty,
globinits = MSymTab.empty, owners = owners, munge_info_fname = munge_info_fname}
fun cons h t = h::t
fun get_addressed_vis (CSE {vars, addressed, ...}) = let
fun innerfold (vi,acc) =
if is_global vi andalso MSymTab.defined addressed (get_mname vi) then
vi::acc
else acc
fun foldthis (_, vis) acc = List.foldl innerfold acc vis
in
Symtab.fold foldthis vars []
end
local
open FunctionalRecordUpdate
(* see http://mlton.org/FunctionalRecordUpdate *)
fun cse_makeUpdate z = makeUpdate26 z
fun update_CSE z = let
fun from senv aui anon_vars fninfo hpfninfo vars local_aliases mangled_vars scope enumenv
array_mentions
heaptypes call_info addressed embedded_fncalls modifies
defined_functions recursive_functions caller_info
modify_locs typedefs fnspecs read_globals globinits owners munge_info_fname =
{senv = senv, anon_vars = anon_vars, fninfo = fninfo, vars = vars,
local_aliases = local_aliases, mangled_vars = mangled_vars, hpfninfo = hpfninfo,
scope = scope, enumenv = enumenv, array_mentions = array_mentions,
heaptypes = heaptypes, call_info = call_info, addressed = addressed,
embedded_fncalls = embedded_fncalls, modifies = modifies,
defined_functions = defined_functions, allow_underscore_idents = aui,
recursive_functions = recursive_functions, caller_info = caller_info,
modify_locs = modify_locs, typedefs = typedefs, fnspecs = fnspecs,
read_globals = read_globals, globinits = globinits, owners = owners,
munge_info_fname = munge_info_fname}
(* fields in reverse order to above *)
fun from' munge_info_fname owners globinits read_globals fnspecs typedefs modify_locs caller_info
recursive_functions defined_functions modifies embedded_fncalls
addressed call_info heaptypes array_mentions enumenv scope mangled_vars
local_aliases vars
hpfninfo fninfo anon_vars aui senv =
{senv = senv, anon_vars = anon_vars, fninfo = fninfo, vars = vars, scope = scope,
hpfninfo = hpfninfo, local_aliases = local_aliases, mangled_vars = mangled_vars,
allow_underscore_idents = aui,
enumenv = enumenv, array_mentions = array_mentions,
heaptypes = heaptypes, call_info = call_info, addressed = addressed,
embedded_fncalls = embedded_fncalls, modifies = modifies,
defined_functions = defined_functions,
recursive_functions = recursive_functions, caller_info = caller_info,
modify_locs = modify_locs, typedefs = typedefs, fnspecs = fnspecs,
read_globals = read_globals, globinits = globinits, owners = owners,
munge_info_fname = munge_info_fname}
fun to f {senv, anon_vars, fninfo, vars, local_aliases, mangled_vars, scope,
enumenv, array_mentions,
heaptypes, hpfninfo, munge_info_fname,
call_info, addressed, embedded_fncalls, modifies,
defined_functions, recursive_functions, caller_info,
modify_locs, typedefs, fnspecs, read_globals, globinits,owners,
allow_underscore_idents = aui} =
f senv aui anon_vars fninfo hpfninfo vars local_aliases mangled_vars scope enumenv
array_mentions
heaptypes call_info addressed embedded_fncalls modifies
defined_functions recursive_functions caller_info
modify_locs typedefs fnspecs read_globals globinits owners munge_info_fname
in
cse_makeUpdate (from, from', to)
end z
fun vi_makeUpdate z = makeUpdate9 z
fun update_VI z = let
fun from name return_var vtype struct_env fname proto_param
munged_name declared_at attrs =
{name = name, return_var = return_var, vtype = vtype,
struct_env = struct_env, fname = fname, declared_at = declared_at,
proto_param = proto_param, munged_name = munged_name,
attrs = attrs}
fun from' attrs declared_at munged_name proto_param fname struct_env
vtype return_var name =
{name = name, return_var = return_var, vtype = vtype,
struct_env = struct_env, fname = fname, declared_at = declared_at,
proto_param = proto_param, munged_name = munged_name,
attrs = attrs}
fun to f {name, return_var, vtype, struct_env, fname, proto_param,
munged_name, declared_at, attrs} =
f name return_var vtype struct_env fname proto_param
munged_name declared_at attrs
in
vi_makeUpdate (from, from', to)
end z
in
fun cse_fupdvars f (CSE cse) =
CSE (update_CSE cse (U #vars (f (#vars cse))) $$)
fun cse_fupdlocal_aliases f (CSE cse) =
CSE (update_CSE cse (U #local_aliases (f (#local_aliases cse))) $$)
fun cse_fupdmangled_vars f (CSE cse) =
CSE (update_CSE cse (U #mangled_vars (f (#mangled_vars cse))) $$)
fun cse_fupdfninfo f (CSE cse) =
CSE (update_CSE cse (U #fninfo (f (#fninfo cse))) $$)
fun cse_fupdhpfninfo f (CSE cse) =
CSE (update_CSE cse (U #hpfninfo (f (#hpfninfo cse))) $$)
fun cse_fupdscope f (CSE cse) =
CSE (update_CSE cse (U #scope (f (#scope cse))) $$)
fun cse_fupdsenv f (CSE cse) =
CSE (update_CSE cse (U #senv (f (#senv cse))) $$)
fun cse_fupdenumenv f (CSE cse) =
CSE (update_CSE cse (U #enumenv (f (#enumenv cse))) $$)
fun cse_fupdarray_mentions f (CSE cse) =
CSE (update_CSE cse (U #array_mentions (f (#array_mentions cse))) $$)
fun cse_fupdheaptypes f (CSE cse) =
CSE (update_CSE cse (U #heaptypes (f (#heaptypes cse))) $$)
fun cse_fupdcallgraph f (CSE cse) =
CSE (update_CSE cse (U #call_info (f (#call_info cse))) $$)
fun cse_fupdcaller_info f (CSE cse) =
CSE (update_CSE cse (U #caller_info (f (#caller_info cse))) $$)
fun cse_fupdaddressed f (CSE cse) =
CSE (update_CSE cse (U #addressed (f (#addressed cse))) $$)
fun cse_fupdembedded_fncalls f (CSE cse) =
CSE (update_CSE cse (U #embedded_fncalls (f (#embedded_fncalls cse))) $$)
fun cse_fupdmodifies f (CSE cse) =
CSE (update_CSE cse (U #modifies (f (#modifies cse))) $$)
fun cse_fupdmodifylocs f (CSE cse) =
CSE (update_CSE cse (U #modify_locs (f (#modify_locs cse))) $$)
fun cse_fupdread_globals f (CSE cse) =
CSE (update_CSE cse (U #read_globals (f (#read_globals cse))) $$)
fun cse_fupddefined_functions f (CSE cse) =
CSE (update_CSE cse (U #defined_functions (f (#defined_functions cse))) $$)
fun cse_fupdrecursive_functions f (CSE cse) =
CSE (update_CSE cse (U #recursive_functions (f (#recursive_functions cse))) $$)
fun cse_fupdfnspecs f (CSE cse) =
CSE (update_CSE cse (U #fnspecs (f (#fnspecs cse))) $$)
fun cse_fupdglobinits f (CSE cse) =
CSE (update_CSE cse (U #globinits (f (#globinits cse))) $$)
fun upd_mname mname (VI vi) =
VI (update_VI vi (U #munged_name mname) $$)
fun vi_upd_type ty (VI vi) =
VI (update_VI vi (U #vtype ty) $$)
end;
fun get_vi_attrs (VI vi) = #attrs vi
fun fns_by_type cse (retty, ptyps) = let
val fninfo = get_fninfo cse
fun listcmp x =
case x of
([], []) => true
| (ctyp::ctyps, vi::vis) => ctyp = get_vi_type vi andalso
listcmp (ctyps, vis)
| _ => false
fun foldthis (nm, (nm_retty, _, ps)) acc =
if nm_retty = retty andalso listcmp (ptyps, ps) then nm::acc
else acc
in
Symtab.fold foldthis fninfo []
end
fun new_call {caller, callee} cse = let
val cse' = cse_fupdcallgraph
(Symtab.map_default (caller, Binaryset.empty fncall_cmp)
(fn s => Binaryset.add(s,callee)))
cse
in
case callee of
DirectCall somefn =>
cse_fupdcaller_info
(Symtab.map_default (somefn, Binaryset.empty String.compare)
(fn s => Binaryset.add(s,caller))) cse'
| _ => cse'
end
fun mk_recursive f =
cse_fupdrecursive_functions (fn s => Binaryset.add(s,f))
fun new_embedded_fncall s cse =
cse_fupdembedded_fncalls (fn set => Binaryset.add(set,s)) cse
fun new_addressed vi expr =
cse_fupdaddressed (MSymTab.map_default (get_mname vi, []) (cons expr))
fun new_array tysz =
cse_fupdarray_mentions (fn s => Binaryset.add(s,tysz))
fun add_heaptype ty env = let
val htypes = get_heaptypes env
in
if Binaryset.member(htypes, ty) then env
else let
val env' = cse_fupdheaptypes (fn s => Binaryset.add(s, ty)) env
in
case ty of
Ptr ty0 => add_heaptype ty0 env'
| Array(ty0, _) => add_heaptype ty0 env'
| StructTy s => let
in
case StrictCBasics.assoc (get_senv env', s) of
NONE => (* do nothing for the moment, thus env, not env' *) env
| SOME flds =>
List.foldl (fn ((_, fldty), env) => add_heaptype fldty env)
env'
flds
end
| _ => env'
end
end
fun update_hpfninfo0 d tab =
case d of
FnDefn((_, fname), _, _, _) => Symtab.update(node fname,d) tab
| Decl d0 => let
in
case node d0 of
ExtFnDecl(ed0 as {name = name_w,...}) => let
val name = node name_w
in
case Symtab.lookup tab name of
NONE => Symtab.update(name, d) tab
| SOME (FnDefn _) => tab
| SOME (Decl d1) => let
in
case node d1 of
ExtFnDecl {specs,name,rettype,params} => let
val newd0 = {rettype=rettype,name=name,params=params,
specs=merge_specs (#specs ed0) specs}
val newd = wrap(ExtFnDecl newd0, left d0, right d0)
in
Symtab.update (node name, Decl newd) tab
end
| _ => tab
end
end
| _ => tab
end
fun update_hpfninfo d = cse_fupdhpfninfo (update_hpfninfo0 d)
fun insert_fnretty (s, ty, env) = let
open Feedback
fun upd tab =
case Symtab.lookup tab (node s) of
NONE => (informStr (6, "Recording return type of "^ tyname ty^
" for function "^ node s);
Symtab.update(node s,(ty,true,[])) tab)
(* insert dummy values for parameters *)
| SOME (ty',_,_) => if ty = ty' then tab
else
(Feedback.errorStr'(left s, right s,
"Incompatible return type");
tab)
in
cse_fupdfninfo upd env
end
fun new_defined_fn s =
cse_fupddefined_functions (Symtab.update(node s, Region.Wrap.region s))
fun set_proto_params fname ps env = let
fun upd tab =
case Symtab.lookup tab fname of
NONE => raise Fail "set_proto_params: This should never happen"
| SOME(retty,protop,_) => if not protop then tab
else Symtab.update(fname,(retty,true,ps)) tab
in
cse_fupdfninfo upd env
end
fun set_defn_params fname ps env = let
fun upd tab =
case Symtab.lookup tab fname of
NONE => raise Fail "set_defn_params: This should never happen"
| SOME (retty,_,_) => Symtab.update(fname, (retty,false,ps)) tab
in
cse_fupdfninfo upd env
end
fun add_modification fname vi env = let
val dflt = Binaryset.empty mvar_compare
val dflt_locs = Binaryset.empty String.compare
fun add e set = Binaryset.add(set,e)
in
(cse_fupdmodifies (Symtab.map_default (fname, dflt) (add vi)) o
cse_fupdmodifylocs (MVar_Table.map_default (vi,dflt_locs) (add fname)))
env
end
fun add_read fname mvi env = let
val dflt = Binaryset.empty mvar_compare
fun add e set = Binaryset.add(set, e)
in
cse_fupdread_globals (Symtab.map_default (fname,dflt) (add mvi)) env
end
fun calc_untouched_globals cse = let
open MSymTab
fun mydelete (t,e) = delete_safe e t
val all_globals = let
fun foldthis (vi as VI vr, tab) =
if #return_var vr then tab
else
update (get_mname vi, get_vi_type vi) tab
in
List.foldl foldthis empty (get_globals cse)
end
val remove_modified = let
fun foldthis (mvar, _) set =
case mvar of
M vi => mydelete(set, get_mname vi)
| _ => set
in
MVar_Table.fold foldthis (get_modified_global_locns cse)
end
val remove_addressed = let
fun foldthis (k, _) set = mydelete(set, k)
in
MSymTab.fold foldthis (get_addressed cse)
end
in
all_globals
|> remove_modified
|> remove_addressed
end
fun get_vi_nm_info (CSE cse) (VI {name, munged_name, ...}) : nm_info =
let
val alias =
case Symtab.lookup (#local_aliases cse) name of
SOME mn => mn = munged_name
| NONE => false
in
{src_name = name, isa_name = munged_name, alias = alias}
end
(* ML computation of alignment and type sizes *)
val ti = IntInf.toInt
fun ialignof ity = let
open ImplementationNumbers
in
case ity of
Char => ti 1
| Short => ti (shortWidth div CHAR_BIT)
| Int => ti (intWidth div CHAR_BIT)
| Long => ti (longWidth div CHAR_BIT)
| LongLong => ti (llongWidth div CHAR_BIT)
end
fun roundup base n = if n mod base = 0 then n else (n div base + 1) * base
fun maxl [] = 0
| maxl (h::t) = let val m = maxl t in if h > m then h else m end
fun alignof cse ty : Int.int = let
open ImplementationNumbers
in
case ty of
Signed i => ialignof i
| Unsigned i => ialignof i
| PlainChar => 1
| Ptr _ => IntInf.toInt (ptrWidth div CHAR_BIT)
| StructTy s => maxl (map (alignof cse o #2) (get_fields cse s))
| Array(base, _) => alignof cse base
| EnumTy _ => alignof cse (Signed Int)
| Ident _ => raise Fail "ProgramAnalysis.alignof: typedefs need to be \
\compiled out"
| Function _ => raise Fail "ProgramAnalysis.alignof: functions have no \
\alignment"
| Bitfield _ => raise Fail "ProgramAnalysis.alignof: bitfields have no \
\alignment"
| Void => raise Fail "ProgramAnalysis.alignof: void has no alignment"
| _ => raise Fail ("ProgramAnalysis.alignof: no alignment for "^tyname ty)
end
fun offset cse tylist n = let
val offset = offset cse
in
if n = 0 then 0
else if length tylist <= n then 0
else let
val offn' = offset tylist (n - 1)
val tyn' = List.nth(tylist, n - 1)
val tyn = List.nth(tylist, n)
val b = offn' + sizeof cse tyn'
in
roundup (alignof cse tyn) b
end
end
and strsize cse s : Int.int = let
val flds = map #2 (get_fields cse s)
val a = maxl (map (alignof cse) flds)
val lastn = length flds - 1
val lastty = List.last flds
val off = offset cse flds lastn
in
roundup a (off + sizeof cse lastty)
end
and sizeof cse ty = Absyn.sizeof (strsize cse) ty
fun cse2ecenv cse = CE {enumenv = get_enumenv cse,
typing = cse_typing cse,
structsize = strsize cse}
and cse_typing cse e = let
val scopes = get_scope cse
fun var_typing [] _ = NONE
| var_typing (tab::rest) s =
case Symtab.lookup tab s of
NONE => var_typing rest s
| SOME vi => SOME (get_vi_type vi)
handle Empty => raise Fail "Empty vi-list in cse_typing"
in
ExpressionTyping.expr_type (cse2ecenv cse)
(get_senv cse)
(var_typing scopes)
e
end
fun fndes_callinfo cse e =
case (cse_typing cse e, enode e) of
(Function x, Var(s, _)) => let
in
(DirectCall s, x)
end
| (ty, _) => let
in
case ty of
Function x => (FnPtrCall x, x)
| Ptr (Function x) => (FnPtrCall x, x)
| _ => raise eFail (e, "Function designator has bad type ("^
tyname ty ^ ")")
end
fun process_enumdecl (enameopt_w,econsts) env = let
fun mk_ecenv (set, enum_tab) = CE {enumenv = enum_tab,
typing = cse_typing env, structsize = strsize env}
fun foldthis ((ecn_w, eopt), (i, set, enum_tab)) =
case List.find (fn sw => node sw = node ecn_w) set of
SOME first => (Feedback.errorStr'(left ecn_w, right ecn_w,
"Re-using enum const (" ^ node ecn_w ^
") from "^
Region.toString
(Region.Wrap.region first));
(i, set, enum_tab))
| NONE => let
val e_val = case eopt of
NONE => i
| SOME e => consteval (mk_ecenv (set, enum_tab)) e
val tab' = Symtab.update(node ecn_w, (e_val, node enameopt_w)) enum_tab
in
(e_val + 1, ecn_w::set, tab')
end
val (set0, enum_tab0) = get_fulleenv env
val (_, set', enum_tab') = List.foldl foldthis (0,set0,enum_tab0) econsts
in
cse_fupdenumenv (K (set', enum_tab')) env
end
fun process_type (posrange as (l,r)) (ty, env) =
case ty of
Array(elty, sz_opt) => let
val env' = process_type posrange (elty, env)
val ecenv = cse2ecenv env
val ti = IntInf.toInt
in
case sz_opt of
NONE => env'
| SOME sz_e => let
val sz_i = ti (consteval ecenv sz_e)
in
if sz_i < 1 then let
val region = Region.make{left=l,right=r}
in
raise Fail ("Array in area "^Region.toString region^
" has non-positive size "^Int.toString sz_i)
end
else
new_array (constify_abtype ecenv elty, sz_i) env'
end
end
| Ptr ty' => let
val ty'' = constify_abtype (cse2ecenv env) ty'
in
process_type posrange (ty',add_heaptype ty'' env)
end
| _ => env
fun check_uscore_ok s = let
val s = NameGeneration.rmUScoreSafety s
in
s <> "" andalso String.sub(s,0) <> #"_"
end
fun newstr_decl (nm, flds0 : (expr ctype * string wrap) list) cse = let
open NameGeneration
fun foldthis ((cty,fldnm),acc) =
process_type (left fldnm, right fldnm) (cty, acc)
val cse = List.foldl foldthis cse flds0
val ecenv = cse2ecenv cse
fun uscore_check i nmty s =
if get_allow_underscores cse orelse check_uscore_ok (node s) then ()
else
Feedback.errorStr'(left s, right s,
rmUScoreSafety (i (node s)) ^
" is an illegal name for a structure " ^nmty)
val flds =
map (fn (ty,s) =>
((uscore_check unC_field_name "field" s; node s),
remove_enums (constify_abtype ecenv ty)))
flds0
val _ = uscore_check unC_struct_name "tag" nm
in
cse_fupdsenv (fn rest => (node nm, flds) :: rest) cse
end
fun find_scoped_vdecl name scope = let
fun recurse i scope =
case scope of
[] => NONE
| (db::rest) => let
in
case Symtab.lookup db name of
NONE => recurse (i + 1) rest
| SOME vi => let
val fnm = case get_vi_fname vi of NONE => "<global>" | SOME s => s
in
Feedback.informStr(10, "find_scoped_vdecl: Found "^fnm^":"^name^
" at depth "^Int.toString i);
SOME (i,vi)
end
end
in
recurse 0 scope
end
val new_scope = cse_fupdscope (fn l => Symtab.empty :: l)
val pop_scope = cse_fupdscope tl
fun fupd_hd _ [] = raise Fail "fupd_hd: empty list"
| fupd_hd f (h :: t) = f h :: t
fun fupd_last _ [] = raise Fail "fupd_last: empty list"
| fupd_last f [h] = [f h]
| fupd_last f (h1::t) = h1::fupd_last f t
fun pluck _ [] = NONE
| pluck P (h::t) = if P h then SOME(h,t)
else case pluck P t of
NONE => NONE
| SOME (e,rest) => SOME (e, h::rest)
(* `munge_insert` adds a newly declared variable to the map of all seen variables,
and to the current scope. If a global of the same name and incompatible type
is encountered, we show an error.
Every local variable gets appended with its type. We generate convenient aliases for the
first occurences later.*)
fun munge_insert (v as VI vrec) cse = let
val v_table = get_vars cse
fun prepend_insert (n,vi) = Symtab.map_default (n,[]) (fn t => vi::t)
val name = #name vrec
fun merge_global_vis v1 v2 = let
val ty1 = get_vi_type v1
val ty2 = get_vi_type v2
in
vi_upd_type (max_type ty1 ty2) v1
end
fun same_global v' =
is_global v' andalso srcname v' = name andalso get_mname v' = get_mname v
fun vars_add v1 vlist =
if not (is_global v1) then prepend_insert(name,v1)
else
case pluck same_global vlist of
NONE => Symtab.update(name, v::vlist)
| SOME (v2, rest) => Symtab.update(name, merge_global_vis v1 v2::rest)
fun scope_add v1 tab =
if not (is_global v1) then Symtab.update(name, v1) tab
else
case Symtab.lookup tab name of
NONE => Symtab.update(name, v1) tab
| SOME v2 => Symtab.update(name, merge_global_vis v1 v2) tab
val scope = fupd_hd
val full_name =
(* - Return vars have their own name mangling, so we don't do more here.
- If the use of a global array `int ga[]` comes after the declaration
but before the definition, that use site would see the (eventually