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
#[allow(unused_imports)]
use log::{debug, info, log, warn};
use crate::{
function_data_builder::FunctionDataBuilder,
function_target::{FunctionData, FunctionTarget},
function_target_pipeline::{
FunctionTargetProcessor, FunctionTargetsHolder, FunctionVariant, VerificationFlavor,
},
options::ProverOptions,
stackless_bytecode::{BorrowNode, Bytecode, Operation, PropKind},
usage_analysis,
verification_analysis_v2::InvariantAnalysisData,
};
use itertools::Itertools;
#[cfg(invariant_trace)]
use move_model::ty::TypeDisplayContext;
use move_model::{
ast::{ConditionKind, Exp, GlobalInvariant},
exp_generator::ExpGenerator,
model::{FunId, FunctionEnv, GlobalEnv, GlobalId, Loc, QualifiedId, QualifiedInstId, StructId},
pragmas::CONDITION_ISOLATED_PROP,
spec_translator::{SpecTranslator, TranslatedSpec},
ty::{Type, TypeUnificationAdapter, Variance},
};
use std::collections::{BTreeMap, BTreeSet};
const GLOBAL_INVARIANT_FAILS_MESSAGE: &str = "global memory invariant does not hold";
pub struct GlobalInvariantInstrumentationProcessorV2 {}
impl GlobalInvariantInstrumentationProcessorV2 {
pub fn new() -> Box<Self> {
Box::new(Self {})
}
}
impl FunctionTargetProcessor for GlobalInvariantInstrumentationProcessorV2 {
fn process(
&self,
targets: &mut FunctionTargetsHolder,
fun_env: &FunctionEnv<'_>,
data: FunctionData,
) -> FunctionData {
if fun_env.is_native() || fun_env.is_intrinsic() {
return data;
}
if !data.variant.is_verified() {
return data;
}
let target = FunctionTarget::new(fun_env, &data);
let Analyzer { plain, func_insts } = Analyzer::analyze(&target);
let env = target.global_env();
let mut func_variants = vec![];
for (i, (ty_args, mut global_ids)) in func_insts.into_iter().enumerate() {
let variant_data = data.fork_with_instantiation(
env,
&ty_args,
FunctionVariant::Verification(VerificationFlavor::Instantiated(i)),
);
global_ids.extend(plain.clone().into_iter());
func_variants.push((variant_data, global_ids));
}
let main = Instrumenter::run(fun_env, data, plain);
for (variant_data, variant_global_invariants) in func_variants {
let variant = Instrumenter::run(fun_env, variant_data, variant_global_invariants);
targets.insert_target_data(
&fun_env.get_qualified_id(),
variant.variant.clone(),
variant,
);
}
main
}
fn name(&self) -> String {
"global_invariant_instrumenter_v2".to_string()
}
}
struct Analyzer {
plain: BTreeSet<GlobalId>,
func_insts: BTreeMap<Vec<Type>, BTreeSet<GlobalId>>,
}
impl Analyzer {
pub fn analyze(target: &FunctionTarget) -> Self {
let mut analyzer = Self {
plain: BTreeSet::new(),
func_insts: BTreeMap::new(),
};
analyzer.collect_related_global_invariants(target);
analyzer
}
fn collect_related_global_invariants(&mut self, target: &FunctionTarget) {
let env = target.global_env();
let mut invariants_for_used_memory = BTreeSet::new();
for mem in usage_analysis::get_memory_usage(target).accessed.all.iter() {
invariants_for_used_memory.extend(env.get_global_invariants_for_memory(mem));
}
for invariant_id in invariants_for_used_memory {
self.check_global_invariant_applicability(
target,
env.get_global_invariant(invariant_id).unwrap(),
);
}
}
fn check_global_invariant_applicability(
&mut self,
target: &FunctionTarget,
invariant: &GlobalInvariant,
) {
let mut is_generic = false;
let mut func_insts = BTreeSet::new();
let fun_mems = &usage_analysis::get_memory_usage(target).accessed.all;
let fun_arity = target.get_type_parameters().len();
for inv_mem in &invariant.mem_usage {
for fun_mem in fun_mems.iter() {
if inv_mem.module_id != fun_mem.module_id || inv_mem.id != fun_mem.id {
continue;
}
let adapter =
TypeUnificationAdapter::new_vec(&fun_mem.inst, &inv_mem.inst, true, true);
let rel = adapter.unify(Variance::Allow, false);
match rel {
None => continue,
Some((subs_fun, _)) => {
if subs_fun.is_empty() {
is_generic = true;
} else {
func_insts.insert(Type::type_param_map_to_inst(fun_arity, subs_fun));
}
}
}
}
}
for inst in func_insts {
self.func_insts
.entry(inst)
.or_insert_with(BTreeSet::new)
.insert(invariant.id);
}
if is_generic {
self.plain.insert(invariant.id);
}
}
}
struct Instrumenter<'a> {
options: &'a ProverOptions,
builder: FunctionDataBuilder<'a>,
_function_inst: Vec<Type>,
used_memory: BTreeSet<QualifiedInstId<StructId>>,
related_invariants: BTreeSet<GlobalId>,
saved_from_before_instr_or_call: Option<(TranslatedSpec, BTreeSet<GlobalId>)>,
}
impl<'a> Instrumenter<'a> {
fn run(
fun_env: &FunctionEnv<'a>,
data: FunctionData,
related_invariants: BTreeSet<GlobalId>,
) -> FunctionData {
if !data.variant.is_verified() {
return data;
}
let global_env = fun_env.module_env.env;
let options = ProverOptions::get(global_env);
let function_inst = data.get_type_instantiation(fun_env);
let builder = FunctionDataBuilder::new(fun_env, data);
let used_memory: BTreeSet<_> = usage_analysis::get_memory_usage(&builder.get_target())
.accessed
.get_all_inst(&function_inst);
#[cfg(invariant_trace)]
{
let tctx = TypeDisplayContext::WithEnv {
env: global_env,
type_param_names: None,
};
println!(
"{}<{}>: {}",
builder.data.variant,
function_inst
.iter()
.map(|t| t.display(&tctx).to_string())
.join(","),
used_memory
.iter()
.map(|m| global_env.display(m).to_string())
.join(",")
);
}
let mut instrumenter = Instrumenter {
options: options.as_ref(),
builder,
_function_inst: function_inst,
used_memory,
related_invariants,
saved_from_before_instr_or_call: None,
};
instrumenter.instrument(global_env);
instrumenter.builder.data
}
fn instrument(&mut self, global_env: &GlobalEnv) {
let fun_env = self.builder.fun_env;
let fun_id = fun_env.get_qualified_id();
let inv_ana_data = global_env.get_extension::<InvariantAnalysisData>().unwrap();
let disabled_inv_fun_set = &inv_ana_data.disabled_inv_fun_set;
let non_inv_fun_set = &inv_ana_data.non_inv_fun_set;
let target_invariants = &inv_ana_data.target_invariants;
let disabled_invs_for_fun = &inv_ana_data.disabled_invs_for_fun;
let old_code = std::mem::take(&mut self.builder.data.code);
let mut entrypoint_invariants = self.filter_entrypoint_invariants(&self.related_invariants);
if non_inv_fun_set.contains(&fun_id) {
if let Some(invs_disabled) = disabled_invs_for_fun.get(&fun_id) {
entrypoint_invariants = entrypoint_invariants
.difference(invs_disabled)
.cloned()
.collect();
}
}
let xlated_spec = self.translate_invariants(&entrypoint_invariants);
self.assert_or_assume_translated_invariants(
&xlated_spec.invariants,
&entrypoint_invariants,
PropKind::Assume,
);
if disabled_inv_fun_set.contains(&fun_id) {
let (global_target_invs, _update_target_invs) =
self.separate_update_invariants(target_invariants);
let return_invariants: BTreeSet<_> = global_target_invs
.difference(&entrypoint_invariants)
.cloned()
.collect();
let xlated_spec = self.translate_invariants(&return_invariants);
self.assert_or_assume_translated_invariants(
&xlated_spec.invariants,
&return_invariants,
PropKind::Assume,
);
}
for bc in old_code {
self.instrument_bytecode(bc, fun_id, &inv_ana_data, &entrypoint_invariants);
}
}
fn filter_entrypoint_invariants(
&self,
related_invariants: &BTreeSet<GlobalId>,
) -> BTreeSet<GlobalId> {
let env = self.builder.global_env();
let module_env = &self.builder.fun_env.module_env;
related_invariants
.iter()
.filter_map(|id| {
env.get_global_invariant(*id).filter(|inv| {
matches!(inv.kind, ConditionKind::GlobalInvariant(..))
&& module_env.is_transitive_dependency(inv.declaring_module)
&& !module_env
.env
.is_property_true(&inv.properties, CONDITION_ISOLATED_PROP)
.unwrap_or(false)
})
})
.map(|inv| inv.id)
.collect()
}
fn instrument_bytecode(
&mut self,
bc: Bytecode,
fun_id: QualifiedId<FunId>,
inv_ana_data: &InvariantAnalysisData,
entrypoint_invariants: &BTreeSet<GlobalId>,
) {
use BorrowNode::*;
use Bytecode::*;
use Operation::*;
let target_invariants = &inv_ana_data.target_invariants;
let disabled_inv_fun_set = &inv_ana_data.disabled_inv_fun_set;
let always_check_invs: BTreeSet<GlobalId>;
if let Some(disabled_invs) = &inv_ana_data.disabled_invs_for_fun.get(&fun_id) {
always_check_invs = entrypoint_invariants
.difference(disabled_invs)
.cloned()
.collect();
} else {
always_check_invs = entrypoint_invariants.clone();
}
match &bc {
Call(_, _, WriteBack(GlobalRoot(mem), ..), ..) => {
self.emit_invariants_for_bytecode(
&bc,
&fun_id,
inv_ana_data,
mem,
&always_check_invs,
);
}
Call(_, _, MoveTo(mid, sid, inst), ..) | Call(_, _, MoveFrom(mid, sid, inst), ..) => {
let mem = mid.qualified_inst(*sid, inst.to_owned());
self.emit_invariants_for_bytecode(
&bc,
&fun_id,
inv_ana_data,
&mem,
&always_check_invs,
);
}
Call(_, _, OpaqueCallBegin(module_id, id, _), _, _) => {
self.assume_invariants_for_opaque_begin(
module_id.qualified(*id),
entrypoint_invariants,
inv_ana_data,
);
self.builder.emit(bc);
}
Call(_, _, OpaqueCallEnd(module_id, id, _), _, _) => {
self.builder.emit(bc.clone());
self.assert_invariants_for_opaque_end(module_id.qualified(*id), inv_ana_data)
}
Call(_, _, Function(module_id, id, _), _, _) => {
self.assume_invariants_for_opaque_begin(
module_id.qualified(*id),
entrypoint_invariants,
inv_ana_data,
);
self.builder.emit(bc.clone());
self.assert_invariants_for_opaque_end(module_id.qualified(*id), inv_ana_data)
}
Ret(_, _) => {
if disabled_inv_fun_set.contains(&fun_id) {
let (global_target_invs, _update_target_invs) =
self.separate_update_invariants(target_invariants);
let xlated_spec = self.translate_invariants(&global_target_invs);
self.assert_or_assume_translated_invariants(
&xlated_spec.invariants,
&global_target_invs,
PropKind::Assert,
);
}
self.builder.emit(bc);
}
_ => self.builder.emit(bc),
}
}
fn assume_invariants_for_opaque_begin(
&mut self,
called_fun_id: QualifiedId<FunId>,
entrypoint_invariants: &BTreeSet<GlobalId>,
inv_ana_data: &InvariantAnalysisData,
) {
let target_invariants = &inv_ana_data.target_invariants;
let disabled_inv_fun_set = &inv_ana_data.disabled_inv_fun_set;
let non_inv_fun_set = &inv_ana_data.non_inv_fun_set;
let funs_that_modify_inv = &inv_ana_data.funs_that_modify_inv;
let fun_id = self.builder.fun_env.get_qualified_id();
if !disabled_inv_fun_set.contains(&fun_id)
&& !non_inv_fun_set.contains(&fun_id)
&& non_inv_fun_set.contains(&called_fun_id)
{
let (global_invs, _update_invs) = self.separate_update_invariants(target_invariants);
let modified_invs =
self.get_invs_modified_by_fun(&global_invs, called_fun_id, funs_that_modify_inv);
self.emit_assumes_and_saves_before_bytecode(modified_invs, entrypoint_invariants);
}
}
fn assert_invariants_for_opaque_end(
&mut self,
called_fun_id: QualifiedId<FunId>,
inv_ana_data: &InvariantAnalysisData,
) {
let disabled_inv_fun_set = &inv_ana_data.disabled_inv_fun_set;
let non_inv_fun_set = &inv_ana_data.non_inv_fun_set;
let fun_id = self.builder.fun_env.get_qualified_id();
if !disabled_inv_fun_set.contains(&fun_id)
&& !non_inv_fun_set.contains(&fun_id)
&& non_inv_fun_set.contains(&called_fun_id)
{
self.emit_asserts_after_bytecode();
}
}
fn emit_invariants_for_bytecode(
&mut self,
bc: &Bytecode,
fun_id: &QualifiedId<FunId>,
inv_ana_data: &InvariantAnalysisData,
mem: &QualifiedInstId<StructId>,
entrypoint_invariants: &BTreeSet<GlobalId>,
) {
let target_invariants = &inv_ana_data.target_invariants;
let env = self.builder.global_env();
let mut modified_invariants: BTreeSet<GlobalId> = env
.get_global_invariants_for_memory(mem)
.intersection(target_invariants)
.copied()
.collect();
if let Some(disabled_invs) = &inv_ana_data.disabled_invs_for_fun.get(fun_id) {
modified_invariants = modified_invariants
.difference(disabled_invs)
.cloned()
.collect();
}
self.emit_assumes_and_saves_before_bytecode(modified_invariants, entrypoint_invariants);
self.builder.emit(bc.clone());
self.emit_asserts_after_bytecode();
}
fn emit_assumes_and_saves_before_bytecode(
&mut self,
modified_invs: BTreeSet<GlobalId>,
entrypoint_invariants: &BTreeSet<GlobalId>,
) {
let mut xlated_invs = self.translate_invariants(&modified_invs);
let (global_invs, _update_invs) = self.separate_update_invariants(&modified_invs);
let modified_assumes: BTreeSet<GlobalId> = global_invs
.difference(entrypoint_invariants)
.cloned()
.collect();
self.assert_or_assume_translated_invariants(
&xlated_invs.invariants,
&modified_assumes,
PropKind::Assume,
);
self.emit_state_saves_for_update_invs(&mut xlated_invs);
if self.saved_from_before_instr_or_call.is_none() {
self.saved_from_before_instr_or_call = Some((xlated_invs, modified_invs));
} else {
panic!("self.saved_from_pre should be None");
}
}
fn emit_asserts_after_bytecode(&mut self) {
if let Some((xlated_invs, modified_invs)) =
std::mem::take(&mut self.saved_from_before_instr_or_call)
{
self.assert_or_assume_translated_invariants(
&xlated_invs.invariants,
&modified_invs,
PropKind::Assert,
);
} else {
panic!("saved_from_pre should be Some");
}
}
fn separate_update_invariants(
&self,
invariants: &BTreeSet<GlobalId>,
) -> (BTreeSet<GlobalId>, BTreeSet<GlobalId>) {
let global_env = self.builder.fun_env.module_env.env;
let mut global_invs: BTreeSet<GlobalId> = BTreeSet::new();
let mut update_invs: BTreeSet<GlobalId> = BTreeSet::new();
for inv_id in invariants {
let inv = global_env.get_global_invariant(*inv_id).unwrap();
if matches!(inv.kind, ConditionKind::GlobalInvariantUpdate(..)) {
update_invs.insert(*inv_id);
} else {
global_invs.insert(*inv_id);
}
}
(global_invs, update_invs)
}
fn get_invs_modified_by_fun(
&self,
inv_set: &BTreeSet<GlobalId>,
fun_id: QualifiedId<FunId>,
funs_that_modify_inv: &BTreeMap<GlobalId, BTreeSet<QualifiedId<FunId>>>,
) -> BTreeSet<GlobalId> {
let mut modified_inv_set: BTreeSet<GlobalId> = BTreeSet::new();
for inv_id in inv_set {
if let Some(fun_id_set) = funs_that_modify_inv.get(inv_id) {
if fun_id_set.contains(&fun_id) {
modified_inv_set.insert(*inv_id);
}
}
}
modified_inv_set
}
fn emit_state_saves_for_update_invs(&mut self, xlated_spec: &mut TranslatedSpec) {
self.builder
.set_next_debug_comment("state save for global update invariants".to_string());
for (mem, label) in std::mem::take(&mut xlated_spec.saved_memory) {
self.builder
.emit_with(|id| Bytecode::SaveMem(id, label, mem));
}
for (var, label) in std::mem::take(&mut xlated_spec.saved_spec_vars) {
self.builder
.emit_with(|id| Bytecode::SaveSpecVar(id, label, var));
}
self.builder.clear_next_debug_comment();
}
fn assert_or_assume_translated_invariants(
&mut self,
xlated_invariants: &[(Loc, GlobalId, Exp)],
inv_set: &BTreeSet<GlobalId>,
prop_kind: PropKind,
) {
let global_env = self.builder.global_env();
for (loc, mid, cond) in xlated_invariants {
if inv_set.contains(mid) {
if inv_set.contains(mid)
&& matches!(prop_kind, PropKind::Assume)
&& matches!(
global_env.get_global_invariant(*mid).unwrap().kind,
ConditionKind::GlobalInvariantUpdate(..)
)
{
panic!("Not allowed to assume update invariant");
}
self.emit_invariant(loc, cond, prop_kind);
}
}
}
fn emit_invariant(&mut self, loc: &Loc, cond: &Exp, prop_kind: PropKind) {
self.builder.set_next_debug_comment(format!(
"global invariant {}",
loc.display(self.builder.global_env())
));
if prop_kind == PropKind::Assert {
self.builder
.set_loc_and_vc_info(loc.clone(), GLOBAL_INVARIANT_FAILS_MESSAGE);
}
self.builder
.emit_with(|id| Bytecode::Prop(id, prop_kind, cond.clone()));
}
fn translate_invariants(&mut self, invs: &BTreeSet<GlobalId>) -> TranslatedSpec {
let inst_invs = self.compute_instances_for_invariants(invs);
SpecTranslator::translate_invariants_by_id(
self.options.auto_trace_level.invariants(),
&mut self.builder,
inst_invs.into_iter(),
)
}
fn compute_instances_for_invariants(
&self,
invs: &BTreeSet<GlobalId>,
) -> Vec<(GlobalId, Vec<Type>)> {
invs.iter()
.map(|id| {
let inv = self.builder.global_env().get_global_invariant(*id).unwrap();
self.compute_invariant_instances(inv).into_iter()
})
.flatten()
.collect()
}
fn compute_invariant_instances(
&self,
inv: &GlobalInvariant,
) -> BTreeSet<(GlobalId, Vec<Type>)> {
let arity = match &inv.kind {
ConditionKind::GlobalInvariant(ps) | ConditionKind::GlobalInvariantUpdate(ps) => {
ps.len() as u16
}
_ => 0,
};
if arity == 0 {
return vec![(inv.id, vec![])].into_iter().collect();
}
let mut per_type_param_insts = BTreeMap::new();
for inv_mem in &inv.mem_usage {
for fun_mem in &self.used_memory {
let adapter = TypeUnificationAdapter::new_vec(
&fun_mem.inst,
&inv_mem.inst,
false,
true,
);
#[cfg(invariant_trace)]
println!(
"{} =?= {} for inv {}",
self.builder.global_env().display(fun_mem),
self.builder.global_env().display(inv_mem),
inv.loc.display(self.builder.global_env())
);
let rel = adapter.unify(Variance::Allow, false);
match rel {
None => continue,
Some((_, subst_rhs)) => {
#[cfg(invariant_trace)]
println!("unifies {:?}", subst_rhs);
for (k, v) in subst_rhs {
per_type_param_insts
.entry(k)
.or_insert_with(BTreeSet::new)
.insert(v);
}
}
}
}
}
let mut all_insts = BTreeSet::new();
if (0..arity).collect::<BTreeSet<_>>() == per_type_param_insts.keys().cloned().collect() {
for inst in per_type_param_insts
.values()
.map(|tys| tys.iter().cloned())
.multi_cartesian_product()
{
all_insts.insert((inv.id, inst));
}
}
all_insts
}
}