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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
|
using System;
using System.Collections.Generic;
using Microsoft.Boogie.GraphUtil;
using System.Diagnostics.Contracts;
namespace Microsoft.Boogie {
public class UnusedVarEliminator : VariableCollector {
public static void Eliminate(Program program) {
Contract.Requires(program != null);
UnusedVarEliminator elim = new UnusedVarEliminator();
elim.Visit(program);
}
private UnusedVarEliminator()
: base() {
}
public override Implementation VisitImplementation(Implementation node) {
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Implementation>() != null);
//Console.WriteLine("Procedure {0}", node.Name);
Implementation/*!*/ impl = base.VisitImplementation(node);
Contract.Assert(impl != null);
//Console.WriteLine("Old number of local variables = {0}", impl.LocVars.Length);
List<Variable>/*!*/ vars = new List<Variable>();
foreach (Variable/*!*/ var in impl.LocVars) {
Contract.Assert(var != null);
if (usedVars.Contains(var))
vars.Add(var);
}
impl.LocVars = vars;
//Console.WriteLine("New number of local variables = {0}", impl.LocVars.Length);
//Console.WriteLine("---------------------------------");
usedVars.Clear();
return impl;
}
}
public class ModSetCollector : StandardVisitor {
static Procedure enclosingProc;
static Dictionary<Procedure/*!*/, HashSet<Variable/*!*/>/*!*/>/*!*/ modSets;
static HashSet<Procedure> yieldingProcs;
[ContractInvariantMethod]
void ObjectInvariant() {
Contract.Invariant(cce.NonNullDictionaryAndValues(modSets));
Contract.Invariant(Contract.ForAll(modSets.Values, v => cce.NonNullElements(v)));
}
static bool moreProcessingRequired;
public static void DoModSetAnalysis(Program program) {
Contract.Requires(program != null);
if (CommandLineOptions.Clo.Trace)
{
// Console.WriteLine();
// Console.WriteLine("Running modset analysis ...");
// int procCount = 0;
// foreach (Declaration/*!*/ decl in program.TopLevelDeclarations)
// {
// Contract.Assert(decl != null);
// if (decl is Procedure)
// procCount++;
// }
// Console.WriteLine("Number of procedures = {0}", procCount);*/
}
modSets = new Dictionary<Procedure/*!*/, HashSet<Variable/*!*/>/*!*/>();
yieldingProcs = new HashSet<Procedure>();
HashSet<Procedure/*!*/> implementedProcs = new HashSet<Procedure/*!*/>();
foreach (Declaration/*!*/ decl in program.TopLevelDeclarations) {
Contract.Assert(decl != null);
if (decl is Implementation) {
Implementation impl = (Implementation)decl;
if (impl.Proc != null)
implementedProcs.Add(impl.Proc);
}
}
foreach (Declaration/*!*/ decl in program.TopLevelDeclarations) {
Contract.Assert(decl != null);
if (decl is Procedure)
{
if (!implementedProcs.Contains(cce.NonNull((Procedure)decl)))
{
enclosingProc = (Procedure)decl;
foreach (IdentifierExpr/*!*/ expr in enclosingProc.Modifies)
{
Contract.Assert(expr != null);
ProcessVariable(expr.Decl);
}
enclosingProc = null;
}
else
{
modSets.Add(decl as Procedure, new HashSet<Variable>());
}
}
}
moreProcessingRequired = true;
while (moreProcessingRequired) {
moreProcessingRequired = false;
ModSetCollector modSetCollector = new ModSetCollector();
modSetCollector.Visit(program);
}
foreach (Procedure x in modSets.Keys)
{
x.Modifies = new List<IdentifierExpr>();
foreach (Variable v in modSets[x])
{
x.Modifies.Add(new IdentifierExpr(v.tok, v));
}
if (yieldingProcs.Contains(x) && !QKeyValue.FindBoolAttribute(x.Attributes, "yields"))
{
x.AddAttribute("yields");
}
}
if (false /*CommandLineOptions.Clo.Trace*/) {
Console.WriteLine("Number of procedures with nonempty modsets = {0}", modSets.Keys.Count);
foreach (Procedure/*!*/ x in modSets.Keys)
{
Contract.Assert(x != null);
Console.Write("{0} : ", x.Name);
bool first = true;
foreach (Variable/*!*/ y in modSets[x])
{
Contract.Assert(y != null);
if (first)
first = false;
else
Console.Write(", ");
Console.Write("{0}", y.Name);
}
Console.WriteLine("");
}
}
}
public override Implementation VisitImplementation(Implementation node) {
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Implementation>() != null);
enclosingProc = node.Proc;
Implementation/*!*/ ret = base.VisitImplementation(node);
Contract.Assert(ret != null);
enclosingProc = null;
return ret;
}
public override YieldCmd VisitYieldCmd(YieldCmd node)
{
if (!yieldingProcs.Contains(enclosingProc))
{
yieldingProcs.Add(enclosingProc);
moreProcessingRequired = true;
}
return base.VisitYieldCmd(node);
}
public override Cmd VisitAssignCmd(AssignCmd assignCmd) {
//Contract.Requires(assignCmd != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
Cmd ret = base.VisitAssignCmd(assignCmd);
foreach (AssignLhs/*!*/ lhs in assignCmd.Lhss) {
Contract.Assert(lhs != null);
ProcessVariable(lhs.DeepAssignedVariable);
}
return ret;
}
public override Cmd VisitHavocCmd(HavocCmd havocCmd) {
//Contract.Requires(havocCmd != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
Cmd ret = base.VisitHavocCmd(havocCmd);
foreach (IdentifierExpr/*!*/ expr in havocCmd.Vars) {
Contract.Assert(expr != null);
ProcessVariable(expr.Decl);
}
return ret;
}
public override Cmd VisitCallCmd(CallCmd callCmd) {
//Contract.Requires(callCmd != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
Cmd ret = base.VisitCallCmd(callCmd);
foreach (IdentifierExpr ie in callCmd.Outs)
{
if(ie != null) ProcessVariable(ie.Decl);
}
Procedure callee = callCmd.Proc;
if (callee == null)
return ret;
if (modSets.ContainsKey(callee)) {
foreach (Variable var in modSets[callee]) {
ProcessVariable(var);
}
}
if (!yieldingProcs.Contains(enclosingProc) &&
(yieldingProcs.Contains(callCmd.Proc) || callCmd.IsAsync || callCmd.InParallelWith != null))
{
yieldingProcs.Add(enclosingProc);
moreProcessingRequired = true;
}
if (callCmd.IsAsync || callCmd.InParallelWith != null)
{
var curr = callCmd;
while (curr != null)
{
if (!yieldingProcs.Contains(curr.Proc))
{
yieldingProcs.Add(curr.Proc);
moreProcessingRequired = true;
}
curr = curr.InParallelWith;
}
}
return ret;
}
private static void ProcessVariable(Variable var) {
Procedure/*!*/ localProc = cce.NonNull(enclosingProc);
if (var == null)
return;
if (!(var is GlobalVariable))
return;
if (!modSets.ContainsKey(localProc)) {
modSets[localProc] = new HashSet<Variable/*!*/>();
}
if (modSets[localProc].Contains(var))
return;
moreProcessingRequired = true;
modSets[localProc].Add(var);
}
public override Expr VisitCodeExpr(CodeExpr node) {
// don't go into the code expression, since it can only modify variables local to the code expression,
// and the mod-set analysis is interested in global variables
return node;
}
}
public class VariableCollector : StandardVisitor {
public HashSet<Variable/*!*/>/*!*/ usedVars;
public HashSet<Variable/*!*/>/*!*/ oldVarsUsed;
[ContractInvariantMethod]
void ObjectInvariant() {
Contract.Invariant(cce.NonNullElements(usedVars));
Contract.Invariant(cce.NonNullElements(oldVarsUsed));
}
int insideOldExpr;
public VariableCollector() {
usedVars = new System.Collections.Generic.HashSet<Variable/*!*/>();
oldVarsUsed = new System.Collections.Generic.HashSet<Variable/*!*/>();
insideOldExpr = 0;
}
public override Expr VisitOldExpr(OldExpr node) {
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
insideOldExpr++;
node.Expr = this.VisitExpr(node.Expr);
insideOldExpr--;
return node;
}
public override Expr VisitIdentifierExpr(IdentifierExpr node) {
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
if (node.Decl != null) {
usedVars.Add(node.Decl);
if (insideOldExpr > 0) {
oldVarsUsed.Add(node.Decl);
}
}
return node;
}
}
public class BlockCoalescer : StandardVisitor {
public static void CoalesceBlocks(Program program) {
Contract.Requires(program != null);
BlockCoalescer blockCoalescer = new BlockCoalescer();
blockCoalescer.Visit(program);
}
private static HashSet<Block/*!*/>/*!*/ ComputeMultiPredecessorBlocks(Implementation/*!*/ impl) {
Contract.Requires(impl != null);
Contract.Ensures(cce.NonNullElements(Contract.Result<HashSet<Block>>()));
HashSet<Block/*!*/> visitedBlocks = new HashSet<Block/*!*/>();
HashSet<Block/*!*/> multiPredBlocks = new HashSet<Block/*!*/>();
Stack<Block/*!*/> dfsStack = new Stack<Block/*!*/>();
dfsStack.Push(impl.Blocks[0]);
while (dfsStack.Count > 0) {
Block/*!*/ b = dfsStack.Pop();
Contract.Assert(b != null);
if (visitedBlocks.Contains(b)) {
multiPredBlocks.Add(b);
continue;
}
visitedBlocks.Add(b);
if (b.TransferCmd == null)
continue;
if (b.TransferCmd is ReturnCmd)
continue;
Contract.Assert(b.TransferCmd is GotoCmd);
GotoCmd gotoCmd = (GotoCmd)b.TransferCmd;
if (gotoCmd.labelTargets == null)
continue;
foreach (Block/*!*/ succ in gotoCmd.labelTargets) {
Contract.Assert(succ != null);
dfsStack.Push(succ);
}
}
return multiPredBlocks;
}
public override Implementation VisitImplementation(Implementation impl) {
//Contract.Requires(impl != null);
Contract.Ensures(Contract.Result<Implementation>() != null);
//Console.WriteLine("Procedure {0}", impl.Name);
//Console.WriteLine("Initial number of blocks = {0}", impl.Blocks.Count);
HashSet<Block/*!*/> multiPredBlocks = ComputeMultiPredecessorBlocks(impl);
Contract.Assert(cce.NonNullElements(multiPredBlocks));
HashSet<Block/*!*/> visitedBlocks = new HashSet<Block/*!*/>();
HashSet<Block/*!*/> removedBlocks = new HashSet<Block/*!*/>();
Stack<Block/*!*/> dfsStack = new Stack<Block/*!*/>();
dfsStack.Push(impl.Blocks[0]);
while (dfsStack.Count > 0) {
Block/*!*/ b = dfsStack.Pop();
Contract.Assert(b != null);
if (visitedBlocks.Contains(b))
continue;
visitedBlocks.Add(b);
if (b.TransferCmd == null)
continue;
if (b.TransferCmd is ReturnCmd)
continue;
Contract.Assert(b.TransferCmd is GotoCmd);
GotoCmd gotoCmd = (GotoCmd)b.TransferCmd;
if (gotoCmd.labelTargets == null)
continue;
if (gotoCmd.labelTargets.Count == 1) {
Block/*!*/ succ = cce.NonNull(gotoCmd.labelTargets[0]);
if (!multiPredBlocks.Contains(succ)) {
foreach (Cmd/*!*/ cmd in succ.Cmds) {
Contract.Assert(cmd != null);
b.Cmds.Add(cmd);
}
b.TransferCmd = succ.TransferCmd;
if (!b.tok.IsValid && succ.tok.IsValid) {
b.tok = succ.tok;
b.Label = succ.Label;
}
removedBlocks.Add(succ);
dfsStack.Push(b);
visitedBlocks.Remove(b);
continue;
}
}
foreach (Block/*!*/ succ in gotoCmd.labelTargets) {
Contract.Assert(succ != null);
dfsStack.Push(succ);
}
}
List<Block/*!*/> newBlocks = new List<Block/*!*/>();
foreach (Block/*!*/ b in impl.Blocks) {
Contract.Assert(b != null);
if (visitedBlocks.Contains(b) && !removedBlocks.Contains(b)) {
newBlocks.Add(b);
}
}
impl.Blocks = newBlocks;
// Console.WriteLine("Final number of blocks = {0}", impl.Blocks.Count);
return impl;
}
}
public class LiveVariableAnalysis {
public static void ClearLiveVariables(Implementation impl) {
Contract.Requires(impl != null);
foreach (Block/*!*/ block in impl.Blocks) {
Contract.Assert(block != null);
block.liveVarsBefore = null;
}
}
public static void ComputeLiveVariables(Implementation impl) {
Contract.Requires(impl != null);
Microsoft.Boogie.Helpers.ExtraTraceInformation("Starting live variable analysis");
Graph<Block> dag = new Graph<Block>();
dag.AddSource(cce.NonNull(impl.Blocks[0])); // there is always at least one node in the graph
foreach (Block b in impl.Blocks) {
GotoCmd gtc = b.TransferCmd as GotoCmd;
if (gtc != null) {
Contract.Assume(gtc.labelTargets != null);
foreach (Block/*!*/ dest in gtc.labelTargets) {
Contract.Assert(dest != null);
dag.AddEdge(dest, b);
}
}
}
IEnumerable<Block> sortedNodes;
if (CommandLineOptions.Clo.ModifyTopologicalSorting) {
sortedNodes = dag.TopologicalSort(true);
} else {
sortedNodes = dag.TopologicalSort();
}
foreach (Block/*!*/ block in sortedNodes) {
Contract.Assert(block != null);
HashSet<Variable/*!*/>/*!*/ liveVarsAfter = new HashSet<Variable/*!*/>();
if (block.TransferCmd is GotoCmd) {
GotoCmd gotoCmd = (GotoCmd)block.TransferCmd;
if (gotoCmd.labelTargets != null) {
foreach (Block/*!*/ succ in gotoCmd.labelTargets) {
Contract.Assert(succ != null);
Contract.Assert(succ.liveVarsBefore != null);
liveVarsAfter.UnionWith(succ.liveVarsBefore);
}
}
}
List<Cmd> cmds = block.Cmds;
int len = cmds.Count;
for (int i = len - 1; i >= 0; i--) {
if (cmds[i] is CallCmd) {
Procedure/*!*/ proc = cce.NonNull(cce.NonNull((CallCmd/*!*/)cmds[i]).Proc);
if (InterProcGenKill.HasSummary(proc.Name)) {
liveVarsAfter =
InterProcGenKill.PropagateLiveVarsAcrossCall(cce.NonNull((CallCmd/*!*/)cmds[i]), liveVarsAfter);
continue;
}
}
Propagate(cmds[i], liveVarsAfter);
}
block.liveVarsBefore = liveVarsAfter;
}
}
// perform in place update of liveSet
public static void Propagate(Cmd cmd, HashSet<Variable/*!*/>/*!*/ liveSet) {
Contract.Requires(cmd != null);
Contract.Requires(cce.NonNullElements(liveSet));
if (cmd is AssignCmd) {
AssignCmd/*!*/ assignCmd = (AssignCmd)cce.NonNull(cmd);
// I must first iterate over all the targets and remove the live ones.
// After the removals are done, I must add the variables referred on
// the right side of the removed targets
AssignCmd simpleAssignCmd = assignCmd.AsSimpleAssignCmd;
HashSet<int> indexSet = new HashSet<int>();
int index = 0;
foreach (AssignLhs/*!*/ lhs in simpleAssignCmd.Lhss) {
Contract.Assert(lhs != null);
SimpleAssignLhs salhs = lhs as SimpleAssignLhs;
Contract.Assert(salhs != null);
Variable var = salhs.DeepAssignedVariable;
if (var != null && liveSet.Contains(var)) {
indexSet.Add(index);
liveSet.Remove(var);
}
index++;
}
index = 0;
foreach (Expr/*!*/ expr in simpleAssignCmd.Rhss) {
Contract.Assert(expr != null);
if (indexSet.Contains(index)) {
VariableCollector/*!*/ collector = new VariableCollector();
collector.Visit(expr);
liveSet.UnionWith(collector.usedVars);
}
index++;
}
} else if (cmd is HavocCmd) {
HavocCmd/*!*/ havocCmd = (HavocCmd)cmd;
foreach (IdentifierExpr/*!*/ expr in havocCmd.Vars) {
Contract.Assert(expr != null);
if (expr.Decl != null) {
liveSet.Remove(expr.Decl);
}
}
} else if (cmd is PredicateCmd) {
Contract.Assert((cmd is AssertCmd || cmd is AssumeCmd));
PredicateCmd/*!*/ predicateCmd = (PredicateCmd)cce.NonNull(cmd);
if (predicateCmd.Expr is LiteralExpr) {
LiteralExpr le = (LiteralExpr)predicateCmd.Expr;
if (le.IsFalse) {
liveSet.Clear();
}
} else {
VariableCollector/*!*/ collector = new VariableCollector();
collector.Visit(predicateCmd.Expr);
liveSet.UnionWith(collector.usedVars);
}
} else if (cmd is CommentCmd) {
// comments are just for debugging and don't affect verification
} else if (cmd is SugaredCmd) {
SugaredCmd/*!*/ sugCmd = (SugaredCmd)cce.NonNull(cmd);
Propagate(sugCmd.Desugaring, liveSet);
} else if (cmd is StateCmd) {
StateCmd/*!*/ stCmd = (StateCmd)cce.NonNull(cmd);
List<Cmd>/*!*/ cmds = cce.NonNull(stCmd.Cmds);
int len = cmds.Count;
for (int i = len - 1; i >= 0; i--) {
Propagate(cmds[i], liveSet);
}
foreach (Variable/*!*/ v in stCmd.Locals) {
Contract.Assert(v != null);
liveSet.Remove(v);
}
} else {
{
Contract.Assert(false);
throw new cce.UnreachableException();
}
}
}
}
/*
// An idempotent semiring interface
abstract public class Weight {
abstract public Weight! one();
abstract public Weight! zero();
abstract public Weight! extend(Weight! w1, Weight! w2);
abstract public Weight! combine(Weight! w1, Weight! w2);
abstract public Weight! isEqual(Weight! w);
abstract public Weight! projectLocals()
}
*/
// Weight domain for LiveVariableAnalysis (Gen/Kill)
public class GenKillWeight {
// lambda S. (S - kill) union gen
HashSet<Variable/*!*/>/*!*/ gen;
HashSet<Variable/*!*/>/*!*/ kill;
[ContractInvariantMethod]
void ObjectInvariant() {
Contract.Invariant(cce.NonNullElements(gen));
Contract.Invariant(cce.NonNullElements(kill));
Contract.Invariant(oneWeight != null);
Contract.Invariant(zeroWeight != null);
}
bool isZero;
public static GenKillWeight/*!*/ oneWeight = new GenKillWeight(new HashSet<Variable/*!*/>(), new HashSet<Variable/*!*/>());
public static GenKillWeight/*!*/ zeroWeight = new GenKillWeight();
// initializes to zero
public GenKillWeight() {
this.isZero = true;
this.gen = new HashSet<Variable/*!*/>();
this.kill = new HashSet<Variable/*!*/>();
}
public GenKillWeight(HashSet<Variable/*!*/> gen, HashSet<Variable/*!*/> kill) {
Contract.Requires(cce.NonNullElements(gen));
Contract.Requires(cce.NonNullElements(kill));
Contract.Assert(gen != null);
Contract.Assert(kill != null);
this.gen = gen;
this.kill = kill;
this.isZero = false;
}
public static GenKillWeight one() {
Contract.Ensures(Contract.Result<GenKillWeight>() != null);
return oneWeight;
}
public static GenKillWeight zero() {
Contract.Ensures(Contract.Result<GenKillWeight>() != null);
return zeroWeight;
}
public static GenKillWeight extend(GenKillWeight w1, GenKillWeight w2) {
Contract.Requires(w2 != null);
Contract.Requires(w1 != null);
Contract.Ensures(Contract.Result<GenKillWeight>() != null);
if (w1.isZero || w2.isZero)
return zero();
HashSet<Variable> t = new HashSet<Variable>(w2.gen);
t.ExceptWith(w1.kill);
HashSet<Variable> g = new HashSet<Variable>(w1.gen);
g.UnionWith(t);
HashSet<Variable> k = new HashSet<Variable>(w1.kill);
k.UnionWith(w2.kill);
return new GenKillWeight(g, k);
//return new GenKillWeight(w1.gen.Union(w2.gen.Difference(w1.kill)), w1.kill.Union(w2.kill));
}
public static GenKillWeight combine(GenKillWeight w1, GenKillWeight w2) {
Contract.Requires(w2 != null);
Contract.Requires(w1 != null);
Contract.Ensures(Contract.Result<GenKillWeight>() != null);
if (w1.isZero)
return w2;
if (w2.isZero)
return w1;
HashSet<Variable> g = new HashSet<Variable>(w1.gen);
g.UnionWith(w2.gen);
HashSet<Variable> k = new HashSet<Variable>(w1.kill);
k.IntersectWith(w2.kill);
return new GenKillWeight(g, k);
//return new GenKillWeight(w1.gen.Union(w2.gen), w1.kill.Intersection(w2.kill));
}
public static GenKillWeight projectLocals(GenKillWeight w) {
Contract.Requires(w != null);
Contract.Ensures(Contract.Result<GenKillWeight>() != null);
HashSet<Variable/*!*/> gen = new HashSet<Variable>();
foreach (Variable v in w.gen)
{
if (isGlobal(v))
gen.Add(v);
}
HashSet<Variable/*!*/> kill = new HashSet<Variable>();
foreach (Variable v in w.kill)
{
if (isGlobal(v))
kill.Add(v);
}
return new GenKillWeight(gen, kill);
}
public static bool isEqual(GenKillWeight w1, GenKillWeight w2) {
Contract.Requires(w2 != null);
Contract.Requires(w1 != null);
if (w1.isZero)
return w2.isZero;
if (w2.isZero)
return w1.isZero;
return (w1.gen.Equals(w2.gen) && w1.kill.Equals(w2.kill));
}
private static bool isGlobal(Variable v) {
Contract.Requires(v != null);
return (v is GlobalVariable);
}
[Pure]
public override string ToString() {
Contract.Ensures(Contract.Result<string>() != null);
return string.Format("({0},{1})", gen.ToString(), kill.ToString());
}
public HashSet<Variable/*!*/>/*!*/ getLiveVars() {
Contract.Ensures(cce.NonNullElements(Contract.Result<HashSet<Variable>>()));
return gen;
}
public HashSet<Variable/*!*/>/*!*/ getLiveVars(HashSet<Variable/*!*/>/*!*/ lv) {
Contract.Requires(cce.NonNullElements(lv));
Contract.Ensures(cce.NonNullElements(Contract.Result<HashSet<Variable>>()));
HashSet<Variable> temp = new HashSet<Variable>(lv);
temp.ExceptWith(kill);
temp.UnionWith(gen);
return temp;
}
}
public class ICFG {
public Graph<Block/*!*/>/*!*/ graph;
// Map from procedure to the list of blocks that call that procedure
public Dictionary<string/*!*/, List<Block/*!*/>/*!*/>/*!*/ procsCalled;
public HashSet<Block/*!*/>/*!*/ nodes;
public Dictionary<Block/*!*/, HashSet<Block/*!*/>/*!*/>/*!*/ succEdges;
public Dictionary<Block/*!*/, HashSet<Block/*!*/>/*!*/>/*!*/ predEdges;
private Dictionary<Block/*!*/, int>/*!*/ priority;
public HashSet<Block/*!*/>/*!*/ srcNodes;
public HashSet<Block/*!*/>/*!*/ exitNodes;
public Dictionary<Block/*!*/, GenKillWeight/*!*/>/*!*/ weightBefore;
public Dictionary<Block/*!*/, GenKillWeight/*!*/>/*!*/ weightAfter;
public Dictionary<Block/*!*/, HashSet<Variable/*!*/>/*!*/>/*!*/ liveVarsAfter;
public Dictionary<Block/*!*/, HashSet<Variable/*!*/>/*!*/>/*!*/ liveVarsBefore;
public GenKillWeight/*!*/ summary;
public Implementation/*!*/ impl;
[ContractInvariantMethod]
void ObjectInvariant() {
Contract.Invariant(cce.NonNullElements(graph.TopologicalSort()));
Contract.Invariant(cce.NonNullDictionaryAndValues(procsCalled));
Contract.Invariant(cce.NonNullElements(nodes));
Contract.Invariant(cce.NonNullDictionaryAndValues(succEdges));
Contract.Invariant(cce.NonNullDictionaryAndValues(predEdges));
Contract.Invariant(priority != null);
Contract.Invariant(cce.NonNullElements(srcNodes));
Contract.Invariant(cce.NonNullElements(exitNodes));
Contract.Invariant(cce.NonNullDictionaryAndValues(weightBefore));
Contract.Invariant(cce.NonNullDictionaryAndValues(weightAfter));
Contract.Invariant(cce.NonNullDictionaryAndValues(liveVarsAfter));
Contract.Invariant(cce.NonNullDictionaryAndValues(liveVarsBefore));
Contract.Invariant(summary != null);
Contract.Invariant(impl != null);
}
[NotDelayed]
public ICFG(Implementation impl) {
Contract.Requires(impl != null);
this.graph = new Graph<Block/*!*/>();
this.procsCalled = new Dictionary<string/*!*/, List<Block/*!*/>/*!*/>();
this.nodes = new HashSet<Block/*!*/>();
this.succEdges = new Dictionary<Block/*!*/, HashSet<Block/*!*/>/*!*/>();
this.predEdges = new Dictionary<Block/*!*/, HashSet<Block/*!*/>/*!*/>();
this.priority = new Dictionary<Block/*!*/, int>();
this.srcNodes = new HashSet<Block/*!*/>();
this.exitNodes = new HashSet<Block/*!*/>();
this.weightBefore = new Dictionary<Block/*!*/, GenKillWeight/*!*/>();
this.weightAfter = new Dictionary<Block/*!*/, GenKillWeight/*!*/>();
this.liveVarsAfter = new Dictionary<Block/*!*/, HashSet<Variable/*!*/>/*!*/>();
this.liveVarsBefore = new Dictionary<Block/*!*/, HashSet<Variable/*!*/>/*!*/>();
summary = GenKillWeight.zero();
this.impl = impl;
Initialize(impl);
}
private void Initialize(Implementation impl) {
Contract.Requires(impl != null);
addSource(impl.Blocks[0]);
graph.AddSource(impl.Blocks[0]);
foreach (Block/*!*/ b in impl.Blocks) {
Contract.Assert(b != null);
if (b.TransferCmd is ReturnCmd) {
exitNodes.Add(b);
} else {
GotoCmd gc = b.TransferCmd as GotoCmd;
Contract.Assert(gc != null);
Contract.Assert(gc.labelTargets != null);
foreach (Block/*!*/ t in gc.labelTargets) {
Contract.Assert(t != null);
addEdge(b, t);
graph.AddEdge(b, t);
}
}
weightBefore[b] = GenKillWeight.zero();
weightAfter[b] = GenKillWeight.zero();
foreach (Cmd/*!*/ c in b.Cmds) {
Contract.Assert(c != null);
if (c is CallCmd) {
CallCmd/*!*/ cc = cce.NonNull((CallCmd/*!*/)c);
Contract.Assert(cc.Proc != null);
string/*!*/ procName = cc.Proc.Name;
Contract.Assert(procName != null);
if (!procsCalled.ContainsKey(procName)) {
procsCalled.Add(procName, new List<Block/*!*/>());
}
procsCalled[procName].Add(b);
}
}
}
List<Block>/*!*/ sortedNodes;
bool acyclic;
graph.TarjanTopSort(out acyclic, out sortedNodes);
if (!acyclic) {
Console.WriteLine("Warning: graph is not a dag");
}
int num = sortedNodes.Count;
foreach (Block/*!*/ b in sortedNodes) {
Contract.Assert(b != null);
priority.Add(b, num);
num--;
}
}
public int getPriority(Block b) {
Contract.Requires(b != null);
if (priority.ContainsKey(b))
return priority[b];
return Int32.MaxValue;
}
private void addSource(Block b) {
Contract.Requires(b != null);
registerNode(b);
this.srcNodes.Add(b);
}
private void addExit(Block b) {
Contract.Requires(b != null);
registerNode(b);
this.exitNodes.Add(b);
}
private void registerNode(Block b) {
Contract.Requires(b != null);
if (!succEdges.ContainsKey(b)) {
succEdges.Add(b, new HashSet<Block/*!*/>());
}
if (!predEdges.ContainsKey(b)) {
predEdges.Add(b, new HashSet<Block/*!*/>());
}
nodes.Add(b);
}
private void addEdge(Block src, Block tgt) {
Contract.Requires(tgt != null);
Contract.Requires(src != null);
registerNode(src);
registerNode(tgt);
succEdges[src].Add(tgt);
predEdges[tgt].Add(src);
}
}
// Interprocedural Gen/Kill Analysis
public class InterProcGenKill {
Program/*!*/ program;
Dictionary<string/*!*/, ICFG/*!*/>/*!*/ procICFG;
Dictionary<string/*!*/, Procedure/*!*/>/*!*/ name2Proc;
Dictionary<string/*!*/, List<WorkItem/*!*/>/*!*/>/*!*/ callers;
Graph<string/*!*/>/*!*/ callGraph;
Dictionary<string/*!*/, int>/*!*/ procPriority;
int maxBlocksInProc;
WorkList/*!*/ workList;
Implementation/*!*/ mainImpl;
static Dictionary<string/*!*/, HashSet<Variable/*!*/>/*!*/>/*!*/ varsLiveAtExit = new Dictionary<string/*!*/, HashSet<Variable/*!*/>/*!*/>();
static Dictionary<string/*!*/, HashSet<Variable/*!*/>/*!*/>/*!*/ varsLiveAtEntry = new Dictionary<string/*!*/, HashSet<Variable/*!*/>/*!*/>();
static Dictionary<string/*!*/, GenKillWeight/*!*/>/*!*/ varsLiveSummary = new Dictionary<string/*!*/, GenKillWeight/*!*/>();
[ContractInvariantMethod]
void ObjectInvariant() {
Contract.Invariant(workList != null);
Contract.Invariant(mainImpl != null);
Contract.Invariant(program != null);
Contract.Invariant(cce.NonNullDictionaryAndValues(procICFG));
Contract.Invariant(cce.NonNullDictionaryAndValues(name2Proc));
Contract.Invariant(cce.NonNullDictionaryAndValues(callers) &&
Contract.ForAll(callers.Values, v => cce.NonNullElements(v)));
Contract.Invariant(cce.NonNullElements(callGraph.TopologicalSort()));
Contract.Invariant(procPriority != null);
Contract.Invariant(cce.NonNullDictionaryAndValues(varsLiveAtEntry));
Contract.Invariant(cce.NonNullDictionaryAndValues(varsLiveAtExit) &&
Contract.ForAll(varsLiveAtExit.Values, v => cce.NonNullElements(v)));
Contract.Invariant(cce.NonNullDictionaryAndValues(varsLiveSummary));
Contract.Invariant(cce.NonNullDictionaryAndValues(weightCacheAfterCall));
Contract.Invariant(cce.NonNullDictionaryAndValues(weightCacheBeforeCall));
}
[NotDelayed]
public InterProcGenKill(Implementation impl, Program program) {
Contract.Requires(program != null);
Contract.Requires(impl != null);
this.program = program;
procICFG = new Dictionary<string/*!*/, ICFG/*!*/>();
name2Proc = new Dictionary<string/*!*/, Procedure/*!*/>();
workList = new WorkList();
this.callers = new Dictionary<string/*!*/, List<WorkItem/*!*/>/*!*/>();
this.callGraph = new Graph<string/*!*/>();
this.procPriority = new Dictionary<string/*!*/, int>();
this.maxBlocksInProc = 0;
this.mainImpl = impl;
Dictionary<string/*!*/, Implementation/*!*/>/*!*/ name2Impl = new Dictionary<string/*!*/, Implementation/*!*/>();
varsLiveAtExit.Clear();
varsLiveAtEntry.Clear();
varsLiveSummary.Clear();
foreach (Declaration/*!*/ decl in program.TopLevelDeclarations) {
Contract.Assert(decl != null);
if (decl is Implementation) {
Implementation/*!*/ imp = (Implementation/*!*/)cce.NonNull(decl);
name2Impl[imp.Name] = imp;
} else if (decl is Procedure) {
Procedure/*!*/ proc = cce.NonNull(decl as Procedure);
name2Proc[proc.Name] = proc;
}
}
ICFG/*!*/ mainICFG = new ICFG(mainImpl);
Contract.Assert(mainICFG != null);
procICFG.Add(mainICFG.impl.Name, mainICFG);
callGraph.AddSource(mainICFG.impl.Name);
List<ICFG/*!*/>/*!*/ procsToConsider = new List<ICFG/*!*/>();
procsToConsider.Add(mainICFG);
while (procsToConsider.Count != 0) {
ICFG/*!*/ p = procsToConsider[0];
Contract.Assert(p != null);
procsToConsider.RemoveAt(0);
foreach (string/*!*/ callee in p.procsCalled.Keys) {
Contract.Assert(callee != null);
if (!name2Impl.ContainsKey(callee))
continue;
callGraph.AddEdge(p.impl.Name, callee);
if (maxBlocksInProc < p.nodes.Count) {
maxBlocksInProc = p.nodes.Count;
}
if (!callers.ContainsKey(callee)) {
callers.Add(callee, new List<WorkItem/*!*/>());
}
foreach (Block/*!*/ b in p.procsCalled[callee]) {
Contract.Assert(b != null);
callers[callee].Add(new WorkItem(p, b));
}
if (procICFG.ContainsKey(callee))
continue;
ICFG/*!*/ ncfg = new ICFG(name2Impl[callee]);
Contract.Assert(ncfg != null);
procICFG.Add(callee, ncfg);
procsToConsider.Add(ncfg);
}
}
bool acyclic;
List<string>/*!*/ sortedNodes;
callGraph.TarjanTopSort(out acyclic, out sortedNodes);
Contract.Assert(acyclic);
int cnt = 0;
for (int i = sortedNodes.Count - 1; i >= 0; i--) {
string s = sortedNodes[i];
if (s == null)
continue;
procPriority.Add(s, cnt);
cnt++;
}
}
public static HashSet<Variable/*!*/>/*!*/ GetVarsLiveAtExit(Implementation impl, Program prog) {
Contract.Requires(prog != null);
Contract.Requires(impl != null);
Contract.Ensures(cce.NonNullElements(Contract.Result<HashSet<Variable>>()));
if (varsLiveAtExit.ContainsKey(impl.Name)) {
return varsLiveAtExit[impl.Name];
}
// Return default: all globals and out params
HashSet<Variable/*!*/>/*!*/ lv = new HashSet<Variable/*!*/>();
foreach (Variable/*!*/ v in prog.GlobalVariables()) {
Contract.Assert(v != null);
lv.Add(v);
}
foreach (Variable/*!*/ v in impl.OutParams) {
Contract.Assert(v != null);
lv.Add(v);
}
return lv;
}
public static HashSet<Variable/*!*/>/*!*/ GetVarsLiveAtEntry(Implementation impl, Program prog) {
Contract.Requires(prog != null);
Contract.Requires(impl != null);
Contract.Ensures(cce.NonNullElements(Contract.Result<HashSet<Variable>>()));
if (varsLiveAtEntry.ContainsKey(impl.Name)) {
return varsLiveAtEntry[impl.Name];
}
// Return default: all globals and in params
HashSet<Variable/*!*/>/*!*/ lv = new HashSet<Variable/*!*/>();
foreach (Variable/*!*/ v in prog.GlobalVariables()) {
Contract.Assert(v != null);
lv.Add(v);
}
foreach (Variable/*!*/ v in impl.InParams) {
Contract.Assert(v != null);
lv.Add(v);
}
return lv;
}
public static bool HasSummary(string name) {
Contract.Requires(name != null);
return varsLiveSummary.ContainsKey(name);
}
public static HashSet<Variable/*!*/>/*!*/ PropagateLiveVarsAcrossCall(CallCmd cmd, HashSet<Variable/*!*/>/*!*/ lvAfter) {
Contract.Requires(cmd != null);
Contract.Requires(cce.NonNullElements(lvAfter));
Contract.Ensures(cce.NonNullElements(Contract.Result<HashSet<Variable>>()));
Procedure/*!*/ proc = cce.NonNull(cmd.Proc);
if (varsLiveSummary.ContainsKey(proc.Name)) {
GenKillWeight/*!*/ w1 = getWeightBeforeCall(cmd);
Contract.Assert(w1 != null);
GenKillWeight/*!*/ w2 = varsLiveSummary[proc.Name];
Contract.Assert(w2 != null);
GenKillWeight/*!*/ w3 = getWeightAfterCall(cmd);
Contract.Assert(w3 != null);
GenKillWeight/*!*/ w = GenKillWeight.extend(w1, GenKillWeight.extend(w2, w3));
Contract.Assert(w != null);
return w.getLiveVars(lvAfter);
}
HashSet<Variable/*!*/>/*!*/ ret = new HashSet<Variable/*!*/>();
ret.UnionWith(lvAfter);
LiveVariableAnalysis.Propagate(cmd, ret);
return ret;
}
class WorkItem {
public ICFG/*!*/ cfg;
public Block/*!*/ block;
[ContractInvariantMethod]
void ObjectInvariant() {
Contract.Invariant(cfg != null);
Contract.Invariant(block != null);
}
public WorkItem(ICFG cfg, Block block) {
Contract.Requires(block != null);
Contract.Requires(cfg != null);
this.cfg = cfg;
this.block = block;
}
public GenKillWeight getWeightAfter() {
Contract.Ensures(Contract.Result<GenKillWeight>() != null);
return cfg.weightAfter[block];
}
public bool setWeightBefore(GenKillWeight w) {
Contract.Requires(w != null);
GenKillWeight/*!*/ prev = cfg.weightBefore[block];
Contract.Assert(prev != null);
GenKillWeight/*!*/ curr = GenKillWeight.combine(w, prev);
Contract.Assert(curr != null);
if (GenKillWeight.isEqual(prev, curr))
return false;
cfg.weightBefore[block] = curr;
return true;
}
[Pure]
[Reads(ReadsAttribute.Reads.Nothing)]
public override bool Equals(object other) {
WorkItem/*!*/ wi = (WorkItem/*!*/)cce.NonNull(other);
return (wi.cfg == cfg && wi.block == block);
}
[Pure]
public override int GetHashCode() {
return 0;
}
public string getLabel() {
Contract.Ensures(Contract.Result<string>() != null);
return cfg.impl.Name + "::" + block.Label;
}
}
private void AddToWorkList(WorkItem wi) {
Contract.Requires(wi != null);
int i = procPriority[wi.cfg.impl.Name];
int j = wi.cfg.getPriority(wi.block);
int priority = (i * maxBlocksInProc) + j;
workList.Add(wi, priority);
}
private void AddToWorkListReverse(WorkItem wi) {
Contract.Requires(wi != null);
int i = procPriority[wi.cfg.impl.Name];
int j = wi.cfg.getPriority(wi.block);
int priority = (procPriority.Count - i) * maxBlocksInProc + j;
workList.Add(wi, priority);
}
class WorkList {
SortedList<int, int>/*!*/ priorities;
HashSet<string/*!*/>/*!*/ labels;
Dictionary<int, List<WorkItem/*!*/>/*!*/>/*!*/ workList;
[ContractInvariantMethod]
void ObjectInvariant() {
Contract.Invariant(priorities != null);
Contract.Invariant(cce.NonNullElements(labels));
Contract.Invariant(cce.NonNullDictionaryAndValues(workList) &&
Contract.ForAll(workList.Values, v => cce.NonNullElements(v)));
}
public WorkList() {
labels = new HashSet<string/*!*/>();
priorities = new SortedList<int, int>();
workList = new Dictionary<int, List<WorkItem/*!*/>/*!*/>();
}
public void Add(WorkItem wi, int priority) {
Contract.Requires(wi != null);
string/*!*/ lab = wi.getLabel();
Contract.Assert(lab != null);
if (labels.Contains(lab)) {
// Already on worklist
return;
}
labels.Add(lab);
if (!workList.ContainsKey(priority)) {
workList.Add(priority, new List<WorkItem/*!*/>());
}
workList[priority].Add(wi);
if (!priorities.ContainsKey(priority)) {
priorities.Add(priority, 0);
}
priorities[priority] = priorities[priority] + 1;
}
public WorkItem Get() {
Contract.Ensures(Contract.Result<WorkItem>() != null);
// Get minimum priority
int p = cce.NonNull(priorities.Keys)[0];
priorities[p] = priorities[p] - 1;
if (priorities[p] == 0) {
priorities.Remove(p);
}
// Get a WI with this priority
WorkItem/*!*/ wi = workList[p][0];
Contract.Assert(wi != null);
workList[p].RemoveAt(0);
// update labels
labels.Remove(wi.getLabel());
return wi;
}
public int Count {
get {
return labels.Count;
}
}
}
private GenKillWeight getSummary(CallCmd cmd) {
Contract.Requires(cmd != null);
Contract.Ensures(Contract.Result<GenKillWeight>() != null);
Contract.Assert(cmd.Proc != null);
string/*!*/ procName = cmd.Proc.Name;
Contract.Assert(procName != null);
if (procICFG.ContainsKey(procName)) {
ICFG/*!*/ cfg = procICFG[procName];
Contract.Assert(cfg != null);
return GenKillWeight.projectLocals(cfg.summary);
}
{
Contract.Assert(false);
throw new cce.UnreachableException();
}
}
public static void ComputeLiveVars(Implementation impl, Program/*!*/ prog) {
Contract.Requires(prog != null);
Contract.Requires(impl != null);
InterProcGenKill/*!*/ ipgk = new InterProcGenKill(impl, prog);
Contract.Assert(ipgk != null);
ipgk.Compute();
}
public void Compute() {
// Put all exit nodes in the worklist
foreach (ICFG/*!*/ cfg in procICFG.Values) {
Contract.Assert(cfg != null);
foreach (Block/*!*/ eb in cfg.exitNodes) {
Contract.Assert(eb != null);
WorkItem/*!*/ wi = new WorkItem(cfg, eb);
Contract.Assert(wi != null);
cfg.weightAfter[eb] = GenKillWeight.one();
AddToWorkList(wi);
}
}
while (workList.Count != 0) {
WorkItem/*!*/ wi = workList.Get();
Contract.Assert(wi != null);
process(wi);
}
// Propagate LV to all procedures
foreach (ICFG/*!*/ cfg in procICFG.Values) {
Contract.Assert(cfg != null);
foreach (Block/*!*/ b in cfg.nodes) {
Contract.Assert(b != null);
cfg.liveVarsAfter.Add(b, new HashSet<Variable/*!*/>());
cfg.liveVarsBefore.Add(b, new HashSet<Variable/*!*/>());
}
}
ICFG/*!*/ mainCfg = procICFG[mainImpl.Name];
Contract.Assert(mainCfg != null);
foreach (Block/*!*/ eb in mainCfg.exitNodes) {
Contract.Assert(eb != null);
WorkItem/*!*/ wi = new WorkItem(mainCfg, eb);
Contract.Assert(wi != null);
AddToWorkListReverse(wi);
}
while (workList.Count != 0) {
WorkItem/*!*/ wi = workList.Get();
Contract.Assert(wi != null);
processLV(wi);
}
// Set live variable info
foreach (ICFG/*!*/ cfg in procICFG.Values) {
Contract.Assert(cfg != null);
HashSet<Variable/*!*/>/*!*/ lv = new HashSet<Variable/*!*/>();
foreach (Block/*!*/ eb in cfg.exitNodes) {
Contract.Assert(eb != null);
lv.UnionWith(cfg.liveVarsAfter[eb]);
}
varsLiveAtExit.Add(cfg.impl.Name, lv);
lv = new HashSet<Variable/*!*/>();
foreach (Block/*!*/ eb in cfg.srcNodes) {
Contract.Assert(eb != null);
lv.UnionWith(cfg.liveVarsBefore[eb]);
}
varsLiveAtEntry.Add(cfg.impl.Name, lv);
varsLiveSummary.Add(cfg.impl.Name, cfg.summary);
}
/*
foreach(Block/*!*/
/* b in mainImpl.Blocks){
Contract.Assert(b != null);
//Set<Variable!> lv = cfg.weightBefore[b].getLiveVars();
b.liveVarsBefore = procICFG[mainImpl.Name].liveVarsAfter[b];
//foreach(GlobalVariable/*!*/
/* v in program.GlobalVariables()){Contract.Assert(v != null);
// b.liveVarsBefore.Add(v);
//}
}
*/
}
// Called when summaries have already been computed
private void processLV(WorkItem wi) {
Contract.Requires(wi != null);
ICFG/*!*/ cfg = wi.cfg;
Contract.Assert(cfg != null);
Block/*!*/ block = wi.block;
Contract.Assert(block != null);
HashSet<Variable/*!*/>/*!*/ lv = cfg.liveVarsAfter[block];
Contract.Assert(cce.NonNullElements(lv));
// Propagate backwards in the block
HashSet<Variable/*!*/>/*!*/ prop = new HashSet<Variable/*!*/>();
prop.UnionWith(lv);
for (int i = block.Cmds.Count - 1; i >= 0; i--) {
Cmd/*!*/ cmd = block.Cmds[i];
Contract.Assert(cmd != null);
if (cmd is CallCmd) {
string/*!*/ procName = cce.NonNull(cce.NonNull((CallCmd)cmd).Proc).Name;
Contract.Assert(procName != null);
if (procICFG.ContainsKey(procName)) {
ICFG/*!*/ callee = procICFG[procName];
Contract.Assert(callee != null);
// Inter propagation
// Remove local variables; add return variables
HashSet<Variable/*!*/>/*!*/ elv = new HashSet<Variable/*!*/>();
foreach (Variable/*!*/ v in prop) {
Contract.Assert(v != null);
if (v is GlobalVariable)
elv.Add(v);
}
foreach (Variable/*!*/ v in callee.impl.OutParams) {
Contract.Assert(v != null);
elv.Add(v);
}
foreach (Block/*!*/ eb in callee.exitNodes) {
Contract.Assert(eb != null);
callee.liveVarsAfter[eb].UnionWith(elv);
// TODO: check if modified before inserting
AddToWorkListReverse(new WorkItem(callee, eb));
}
// Continue with intra propagation
GenKillWeight/*!*/ summary = getWeightCall(cce.NonNull((CallCmd/*!*/)cmd));
prop = summary.getLiveVars(prop);
} else {
LiveVariableAnalysis.Propagate(cmd, prop);
}
} else {
LiveVariableAnalysis.Propagate(cmd, prop);
}
}
cfg.liveVarsBefore[block].UnionWith(prop);
foreach (Block/*!*/ b in cfg.predEdges[block]) {
Contract.Assert(b != null);
HashSet<Variable/*!*/>/*!*/ prev = cfg.liveVarsAfter[b];
Contract.Assert(cce.NonNullElements(prev));
HashSet<Variable/*!*/>/*!*/ curr = new HashSet<Variable>(prev);
curr.UnionWith(cfg.liveVarsBefore[block]);
Contract.Assert(cce.NonNullElements(curr));
if (curr.Count != prev.Count) {
cfg.liveVarsAfter[b] = curr;
AddToWorkListReverse(new WorkItem(cfg, b));
}
}
}
private void process(WorkItem wi) {
Contract.Requires(wi != null);
GenKillWeight/*!*/ w = wi.getWeightAfter();
Contract.Assert(w != null);
for (int i = wi.block.Cmds.Count - 1; i >= 0; i--) {
Cmd/*!*/ c = wi.block.Cmds[i];
Contract.Assert(c != null);
if (c is CallCmd && procICFG.ContainsKey(cce.NonNull(cce.NonNull((CallCmd)c).Proc).Name)) {
w = GenKillWeight.extend(getWeightCall(cce.NonNull((CallCmd)c)), w);
} else {
GenKillWeight/*!*/ cweight = getWeight(c, wi.cfg.impl, program);
Contract.Assert(cweight != null);
w = GenKillWeight.extend(cweight, w);
}
}
bool change = wi.setWeightBefore(w);
if (change && wi.cfg.srcNodes.Contains(wi.block)) {
GenKillWeight/*!*/ prev = wi.cfg.summary;
Contract.Assert(prev != null);
GenKillWeight/*!*/ curr = GenKillWeight.combine(prev, wi.cfg.weightBefore[wi.block]);
Contract.Assert(curr != null);
if (!GenKillWeight.isEqual(prev, curr)) {
wi.cfg.summary = curr;
// push callers onto the worklist
if (callers.ContainsKey(wi.cfg.impl.Name)) {
foreach (WorkItem/*!*/ caller in callers[wi.cfg.impl.Name]) {
Contract.Assert(caller != null);
AddToWorkList(caller);
}
}
}
}
foreach (Block/*!*/ b in wi.cfg.predEdges[wi.block]) {
Contract.Assert(b != null);
GenKillWeight/*!*/ prev = wi.cfg.weightAfter[b];
Contract.Assert(prev != null);
GenKillWeight/*!*/ curr = GenKillWeight.combine(prev, w);
Contract.Assert(curr != null);
if (!GenKillWeight.isEqual(prev, curr)) {
wi.cfg.weightAfter[b] = curr;
AddToWorkList(new WorkItem(wi.cfg, b));
}
}
}
static Dictionary<Cmd/*!*/, GenKillWeight/*!*/>/*!*/ weightCache = new Dictionary<Cmd/*!*/, GenKillWeight/*!*/>();
private static GenKillWeight getWeight(Cmd cmd) {
Contract.Requires(cmd != null);
Contract.Ensures(Contract.Result<GenKillWeight>() != null);
return getWeight(cmd, null, null);
}
private GenKillWeight getWeightCall(CallCmd cmd) {
Contract.Requires(cmd != null);
Contract.Ensures(Contract.Result<GenKillWeight>() != null);
GenKillWeight/*!*/ w1 = getWeightBeforeCall(cmd);
GenKillWeight/*!*/ w2 = getSummary(cmd);
GenKillWeight/*!*/ w3 = getWeightAfterCall(cmd);
Contract.Assert(w1 != null);
Contract.Assert(w2 != null);
Contract.Assert(w3 != null);
return GenKillWeight.extend(w1, GenKillWeight.extend(w2, w3));
}
private static GenKillWeight getWeight(Cmd cmd, Implementation impl, Program prog) {
Contract.Requires(cmd != null);
Contract.Ensures(Contract.Result<GenKillWeight>() != null);
if (weightCache.ContainsKey(cmd))
return weightCache[cmd];
HashSet<Variable/*!*/>/*!*/ gen = new HashSet<Variable/*!*/>();
HashSet<Variable/*!*/>/*!*/ kill = new HashSet<Variable/*!*/>();
GenKillWeight/*!*/ ret;
if (cmd is AssignCmd) {
AssignCmd/*!*/ assignCmd = (AssignCmd)cmd;
Contract.Assert(cmd != null);
// I must first iterate over all the targets and remove the live ones.
// After the removals are done, I must add the variables referred on
// the right side of the removed targets
foreach (AssignLhs/*!*/ lhs in assignCmd.Lhss) {
Contract.Assert(lhs != null);
Variable var = lhs.DeepAssignedVariable;
if (var != null) {
if (lhs is SimpleAssignLhs) {
// we should only remove non-map target variables because there is an implicit
// read of a map variable in an assignment to it
kill.Add(var);
}
}
}
int index = 0;
foreach (Expr/*!*/ expr in assignCmd.Rhss) {
Contract.Assert(expr != null);
VariableCollector/*!*/ collector = new VariableCollector();
collector.Visit(expr);
gen.UnionWith(collector.usedVars);
AssignLhs lhs = assignCmd.Lhss[index];
if (lhs is MapAssignLhs) {
// If the target is a map, then all indices are also read
MapAssignLhs malhs = (MapAssignLhs)lhs;
foreach (Expr e in malhs.Indexes) {
VariableCollector/*!*/ c = new VariableCollector();
c.Visit(e);
gen.UnionWith(c.usedVars);
}
}
index++;
}
ret = new GenKillWeight(gen, kill);
} else if (cmd is HavocCmd) {
HavocCmd/*!*/ havocCmd = (HavocCmd)cce.NonNull(cmd);
foreach (IdentifierExpr/*!*/ expr in havocCmd.Vars) {
Contract.Assert(expr != null);
if (expr.Decl != null) {
kill.Add(expr.Decl);
}
}
ret = new GenKillWeight(gen, kill);
} else if (cmd is PredicateCmd) {
Contract.Assert((cmd is AssertCmd || cmd is AssumeCmd));
PredicateCmd/*!*/ predicateCmd = (PredicateCmd)cce.NonNull(cmd);
if (predicateCmd.Expr is LiteralExpr && prog != null && impl != null) {
LiteralExpr le = (LiteralExpr)predicateCmd.Expr;
if (le.IsFalse) {
List<GlobalVariable/*!*/>/*!*/ globals = prog.GlobalVariables();
Contract.Assert(cce.NonNullElements(globals));
foreach (Variable/*!*/ v in globals) {
Contract.Assert(v != null);
kill.Add(v);
}
foreach (Variable/*!*/ v in impl.LocVars) {
Contract.Assert(v != null);
kill.Add(v);
}
foreach (Variable/*!*/ v in impl.OutParams) {
Contract.Assert(v != null);
kill.Add(v);
}
}
} else {
VariableCollector/*!*/ collector = new VariableCollector();
collector.Visit(predicateCmd.Expr);
gen.UnionWith(collector.usedVars);
}
ret = new GenKillWeight(gen, kill);
} else if (cmd is CommentCmd) {
ret = new GenKillWeight(gen, kill);
// comments are just for debugging and don't affect verification
} else if (cmd is SugaredCmd) {
SugaredCmd/*!*/ sugCmd = (SugaredCmd)cmd;
Contract.Assert(sugCmd != null);
ret = getWeight(sugCmd.Desugaring, impl, prog);
} else if (cmd is StateCmd) {
StateCmd/*!*/ stCmd = (StateCmd)cmd;
Contract.Assert(stCmd != null);
List<Cmd>/*!*/ cmds = stCmd.Cmds;
Contract.Assert(cmds != null);
int len = cmds.Count;
ret = GenKillWeight.one();
for (int i = len - 1; i >= 0; i--) {
GenKillWeight/*!*/ w = getWeight(cmds[i], impl, prog);
Contract.Assert(w != null);
ret = GenKillWeight.extend(w, ret);
}
foreach (Variable/*!*/ v in stCmd.Locals) {
Contract.Assert(v != null);
kill.Add(v);
}
ret = GenKillWeight.extend(new GenKillWeight(gen, kill), ret);
} else {
{
Contract.Assert(false);
throw new cce.UnreachableException();
}
}
weightCache[cmd] = ret;
return ret;
}
static Dictionary<Cmd/*!*/, GenKillWeight/*!*/>/*!*/ weightCacheAfterCall = new Dictionary<Cmd/*!*/, GenKillWeight/*!*/>();
static Dictionary<Cmd/*!*/, GenKillWeight/*!*/>/*!*/ weightCacheBeforeCall = new Dictionary<Cmd/*!*/, GenKillWeight/*!*/>();
private static GenKillWeight getWeightAfterCall(Cmd cmd) {
Contract.Requires(cmd != null);
Contract.Ensures(Contract.Result<GenKillWeight>() != null);
if (weightCacheAfterCall.ContainsKey(cmd))
return weightCacheAfterCall[cmd];
HashSet<Variable/*!*/>/*!*/ gen = new HashSet<Variable/*!*/>();
HashSet<Variable/*!*/>/*!*/ kill = new HashSet<Variable/*!*/>();
Contract.Assert(cmd is CallCmd);
CallCmd/*!*/ ccmd = cce.NonNull((CallCmd)cmd);
foreach (IdentifierExpr/*!*/ ie in ccmd.Outs) {
Contract.Assert(ie != null);
if (ie.Decl != null)
kill.Add(ie.Decl);
}
// Variables in ensures are considered as "read"
foreach (Ensures/*!*/ re in cce.NonNull(ccmd.Proc).Ensures) {
Contract.Assert(re != null);
VariableCollector/*!*/ collector = new VariableCollector();
collector.Visit(re.Condition);
foreach (Variable/*!*/ v in collector.usedVars) {
Contract.Assert(v != null);
if (v is GlobalVariable) {
gen.Add(v);
}
}
}
GenKillWeight/*!*/ ret = new GenKillWeight(gen, kill);
Contract.Assert(ret != null);
weightCacheAfterCall[cmd] = ret;
return ret;
}
private static GenKillWeight getWeightBeforeCall(Cmd cmd) {
Contract.Requires(cmd != null);
Contract.Ensures(Contract.Result<GenKillWeight>() != null);
Contract.Assert((cmd is CallCmd));
if (weightCacheBeforeCall.ContainsKey(cmd))
return weightCacheBeforeCall[cmd];
HashSet<Variable/*!*/>/*!*/ gen = new HashSet<Variable/*!*/>();
HashSet<Variable/*!*/>/*!*/ kill = new HashSet<Variable/*!*/>();
CallCmd/*!*/ ccmd = cce.NonNull((CallCmd/*!*/)cmd);
foreach (Expr/*!*/ expr in ccmd.Ins) {
Contract.Assert(expr != null);
VariableCollector/*!*/ collector = new VariableCollector();
collector.Visit(expr);
gen.UnionWith(collector.usedVars);
}
Contract.Assert(ccmd.Proc != null);
// Variables in requires are considered as "read"
foreach (Requires/*!*/ re in ccmd.Proc.Requires) {
Contract.Assert(re != null);
VariableCollector/*!*/ collector = new VariableCollector();
collector.Visit(re.Condition);
foreach (Variable/*!*/ v in collector.usedVars) {
Contract.Assert(v != null);
if (v is GlobalVariable) {
gen.Add(v);
}
}
}
// Old variables in ensures are considered as "read"
foreach (Ensures/*!*/ re in ccmd.Proc.Ensures) {
Contract.Assert(re != null);
VariableCollector/*!*/ collector = new VariableCollector();
collector.Visit(re.Condition);
foreach (Variable/*!*/ v in collector.oldVarsUsed) {
Contract.Assert(v != null);
if (v is GlobalVariable) {
gen.Add(v);
}
}
}
GenKillWeight/*!*/ ret = new GenKillWeight(gen, kill);
Contract.Assert(ret != null);
weightCacheAfterCall[cmd] = ret;
return ret;
}
}
}
|