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
use crate::{
function_target::{FunctionData, FunctionTarget},
print_targets_for_test,
stackless_bytecode_generator::StacklessBytecodeGenerator,
stackless_control_flow_graph::generate_cfg_in_dot_format,
};
use core::fmt;
use itertools::Itertools;
use log::debug;
use move_model::model::{FunId, FunctionEnv, GlobalEnv, QualifiedId};
use std::{collections::BTreeMap, fmt::Formatter, fs};
#[derive(Debug, Default)]
pub struct FunctionTargetsHolder {
targets: BTreeMap<QualifiedId<FunId>, BTreeMap<FunctionVariant, FunctionData>>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum VerificationFlavor {
Regular,
Instantiated(usize),
Inconsistency(Box<VerificationFlavor>),
}
impl std::fmt::Display for VerificationFlavor {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
VerificationFlavor::Regular => write!(f, ""),
VerificationFlavor::Instantiated(index) => {
write!(f, "instantiated_{}", index)
}
VerificationFlavor::Inconsistency(flavor) => write!(f, "inconsistency_{}", flavor),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum FunctionVariant {
Baseline,
Verification(VerificationFlavor),
}
impl FunctionVariant {
pub fn is_verified(&self) -> bool {
matches!(self, FunctionVariant::Verification(..))
}
}
impl std::fmt::Display for FunctionVariant {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
use FunctionVariant::*;
match self {
Baseline => write!(f, "baseline"),
Verification(VerificationFlavor::Regular) => write!(f, "verification"),
Verification(v) => write!(f, "verification[{}]", v),
}
}
}
pub trait FunctionTargetProcessor {
fn process(
&self,
_targets: &mut FunctionTargetsHolder,
_fun_env: &FunctionEnv<'_>,
_data: FunctionData,
) -> FunctionData {
unimplemented!()
}
fn process_and_maybe_remove(
&self,
targets: &mut FunctionTargetsHolder,
func_env: &FunctionEnv<'_>,
data: FunctionData,
) -> Option<FunctionData> {
Some(self.process(targets, func_env, data))
}
fn name(&self) -> String;
fn initialize(&self, _env: &GlobalEnv, _targets: &mut FunctionTargetsHolder) {}
fn finalize(&self, _env: &GlobalEnv, _targets: &mut FunctionTargetsHolder) {}
fn is_single_run(&self) -> bool {
false
}
fn run(&self, _env: &GlobalEnv, _targets: &mut FunctionTargetsHolder) {
unimplemented!()
}
fn dump_result(
&self,
_f: &mut Formatter<'_>,
_env: &GlobalEnv,
_targets: &FunctionTargetsHolder,
) -> fmt::Result {
Ok(())
}
}
pub struct ProcessorResultDisplay<'a> {
pub env: &'a GlobalEnv,
pub targets: &'a FunctionTargetsHolder,
pub processor: &'a dyn FunctionTargetProcessor,
}
impl<'a> fmt::Display for ProcessorResultDisplay<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.processor.dump_result(f, self.env, self.targets)
}
}
#[derive(Default)]
pub struct FunctionTargetPipeline {
processors: Vec<Box<dyn FunctionTargetProcessor>>,
}
impl FunctionTargetsHolder {
pub fn get_funs(&self) -> impl Iterator<Item = QualifiedId<FunId>> + '_ {
self.targets.keys().cloned()
}
pub fn get_funs_and_variants(
&self,
) -> impl Iterator<Item = (QualifiedId<FunId>, FunctionVariant)> + '_ {
self.targets
.iter()
.flat_map(|(id, vs)| vs.keys().map(move |v| (*id, v.clone())))
}
pub fn add_target(&mut self, func_env: &FunctionEnv<'_>) {
let generator = StacklessBytecodeGenerator::new(func_env);
let data = generator.generate_function();
self.targets
.entry(func_env.get_qualified_id())
.or_default()
.insert(FunctionVariant::Baseline, data);
}
pub fn get_target<'env>(
&'env self,
func_env: &'env FunctionEnv<'env>,
variant: &FunctionVariant,
) -> FunctionTarget<'env> {
let data = self
.get_data(&func_env.get_qualified_id(), variant)
.unwrap_or_else(|| {
panic!(
"expected function target: {} ({:?})",
func_env.get_full_name_str(),
variant
)
});
FunctionTarget::new(func_env, data)
}
pub fn get_target_variants(&self, func_env: &FunctionEnv<'_>) -> Vec<FunctionVariant> {
self.targets
.get(&func_env.get_qualified_id())
.expect("function targets exist")
.keys()
.cloned()
.collect_vec()
}
pub fn get_targets<'env>(
&'env self,
func_env: &'env FunctionEnv<'env>,
) -> Vec<(FunctionVariant, FunctionTarget<'env>)> {
self.targets
.get(&func_env.get_qualified_id())
.expect("function targets exist")
.iter()
.map(|(v, d)| (v.clone(), FunctionTarget::new(func_env, d)))
.collect_vec()
}
pub fn get_data(
&self,
id: &QualifiedId<FunId>,
variant: &FunctionVariant,
) -> Option<&FunctionData> {
self.targets.get(id).and_then(|vs| vs.get(variant))
}
pub fn get_data_mut(
&mut self,
id: &QualifiedId<FunId>,
variant: &FunctionVariant,
) -> Option<&mut FunctionData> {
self.targets.get_mut(id).and_then(|vs| vs.get_mut(variant))
}
pub fn remove_target_data(
&mut self,
id: &QualifiedId<FunId>,
variant: &FunctionVariant,
) -> FunctionData {
self.targets
.get_mut(id)
.expect("function target exists")
.remove(variant)
.expect("variant exists")
}
pub fn insert_target_data(
&mut self,
id: &QualifiedId<FunId>,
variant: FunctionVariant,
data: FunctionData,
) {
self.targets.entry(*id).or_default().insert(variant, data);
}
fn process(&mut self, func_env: &FunctionEnv<'_>, processor: &dyn FunctionTargetProcessor) {
let id = func_env.get_qualified_id();
for variant in self.get_target_variants(func_env) {
let data = self.remove_target_data(&id, &variant);
if let Some(processed_data) = processor.process_and_maybe_remove(self, func_env, data) {
self.insert_target_data(&id, variant, processed_data);
}
}
}
}
impl FunctionTargetPipeline {
pub fn add_processor(&mut self, processor: Box<dyn FunctionTargetProcessor>) {
self.processors.push(processor)
}
pub fn last_processor(&self) -> &dyn FunctionTargetProcessor {
self.processors
.iter()
.last()
.expect("pipeline not empty")
.as_ref()
}
pub fn sort_targets_in_topological_order<'env>(
env: &'env GlobalEnv,
targets: &FunctionTargetsHolder,
) -> Vec<FunctionEnv<'env>> {
let mut worklist = vec![];
for fun in targets.get_funs() {
let fun_env = env.get_function(fun);
worklist.push((
fun,
fun_env.get_called_functions().into_iter().collect_vec(),
));
}
let mut to_remove = vec![];
let mut topological_order = vec![];
loop {
let last = worklist.last();
if last.is_none() {
break;
}
if !last.unwrap().1.is_empty() {
for (_f, f_callees) in &mut worklist {
for f in &to_remove {
f_callees.retain(|e| e != f);
}
}
worklist
.sort_by(|(_, callees1), (_, callees2)| callees2.len().cmp(&callees1.len()));
}
let (call_id, callees) = worklist.pop().unwrap();
to_remove.push(call_id);
let func_env = env.get_function(call_id);
if !callees.is_empty() {
unimplemented!(
"Recursion or mutual recursion detected in {:?}. \
Make sure that all analyses in processors are prepared to handle recursion",
func_env.get_identifier()
);
}
topological_order.push(func_env);
}
topological_order
}
pub fn run_with_hook<H1, H2>(
&self,
env: &GlobalEnv,
targets: &mut FunctionTargetsHolder,
hook_before_pipeline: H1,
hook_after_each_processor: H2,
) where
H1: Fn(&FunctionTargetsHolder),
H2: Fn(usize, &dyn FunctionTargetProcessor, &FunctionTargetsHolder),
{
let topological_order = Self::sort_targets_in_topological_order(env, targets);
hook_before_pipeline(targets);
for (step_count, processor) in self.processors.iter().enumerate() {
if processor.is_single_run() {
processor.run(env, targets);
} else {
processor.initialize(env, targets);
for func_env in &topological_order {
targets.process(func_env, processor.as_ref());
}
processor.finalize(env, targets);
}
hook_after_each_processor(step_count + 1, processor.as_ref(), targets);
}
}
pub fn run(&self, env: &GlobalEnv, targets: &mut FunctionTargetsHolder) {
self.run_with_hook(env, targets, |_| {}, |_, _, _| {})
}
pub fn run_with_dump(
&self,
env: &GlobalEnv,
targets: &mut FunctionTargetsHolder,
dump_base_name: &str,
dump_cfg: bool,
) {
self.run_with_hook(
env,
targets,
|holders| {
Self::dump_to_file(
dump_base_name,
0,
"stackless",
&Self::get_pre_pipeline_dump(env, holders),
)
},
|step_count, processor, holders| {
let suffix = processor.name();
Self::dump_to_file(
dump_base_name,
step_count,
&suffix,
&Self::get_per_processor_dump(env, holders, processor),
);
if dump_cfg {
Self::dump_cfg(env, holders, dump_base_name, step_count, &suffix);
}
},
);
}
fn print_targets(env: &GlobalEnv, name: &str, targets: &FunctionTargetsHolder) -> String {
print_targets_for_test(env, &format!("after processor `{}`", name), targets)
}
fn get_pre_pipeline_dump(env: &GlobalEnv, targets: &FunctionTargetsHolder) -> String {
Self::print_targets(env, "stackless", targets)
}
fn get_per_processor_dump(
env: &GlobalEnv,
targets: &FunctionTargetsHolder,
processor: &dyn FunctionTargetProcessor,
) -> String {
let mut dump = format!(
"{}",
ProcessorResultDisplay {
env,
targets,
processor
}
);
if !processor.is_single_run() {
if !dump.is_empty() {
dump = format!("\n\n{}", dump);
}
dump.push_str(&Self::print_targets(env, &processor.name(), targets));
}
dump
}
fn dump_to_file(base_name: &str, step_count: usize, suffix: &str, content: &str) {
let dump = format!("{}\n", content.trim());
let file_name = format!("{}_{}_{}.bytecode", base_name, step_count, suffix);
debug!("dumping bytecode to `{}`", file_name);
fs::write(&file_name, &dump).expect("dumping bytecode");
}
fn dump_cfg(
env: &GlobalEnv,
targets: &FunctionTargetsHolder,
base_name: &str,
step_count: usize,
suffix: &str,
) {
for (fun_id, variants) in &targets.targets {
let func_env = env.get_function(*fun_id);
let func_name = func_env.get_full_name_str();
let func_name = func_name.replace("::", "__");
for (variant, data) in variants {
if !data.code.is_empty() {
let dot_file = format!(
"{}_{}_{}_{}_{}_cfg.dot",
base_name, step_count, suffix, func_name, variant
);
debug!("generating dot graph for cfg in `{}`", dot_file);
let func_target = FunctionTarget::new(&func_env, data);
let dot_graph = generate_cfg_in_dot_format(&func_target);
fs::write(&dot_file, &dot_graph).expect("generating dot file for CFG");
}
}
}
}
}