forked from roc-lang/roc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdrop_specialization.rs
More file actions
1704 lines (1512 loc) · 68.1 KB
/
drop_specialization.rs
File metadata and controls
1704 lines (1512 loc) · 68.1 KB
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
// This program was written by Jelle Teeuwissen within a final
// thesis project of the Computing Science master program at Utrecht
// University under supervision of Wouter Swierstra (w.s.swierstra@uu.nl).
// Implementation based of Drop Specialization from Perceus: Garbage Free Reference Counting with Reuse
// https://www.microsoft.com/en-us/research/uploads/prod/2021/06/perceus-pldi21.pdf
#![allow(clippy::too_many_arguments)]
use std::cmp::{self, Ord};
use std::iter::Iterator;
use bumpalo::collections::vec::Vec;
use bumpalo::collections::CollectIn;
use roc_module::low_level::LowLevel;
use roc_module::symbol::{IdentIds, ModuleId, Symbol};
use crate::ir::{
BranchInfo, Call, CallType, ErasedField, Expr, JoinPointId, ListLiteralElement, ModifyRc, Proc,
ProcLayout, Stmt, UpdateModeId,
};
use crate::layout::{
Builtin, InLayout, Layout, LayoutInterner, LayoutRepr, STLayoutInterner, UnionLayout,
};
use bumpalo::Bump;
use roc_collections::MutMap;
/**
Try to find increments of symbols followed by decrements of the symbol they were indexed out of (their parent).
Then inline the decrement operation of the parent and removing matching pairs of increments and decrements.
*/
pub fn specialize_drops<'a, 'i>(
arena: &'a Bump,
layout_interner: &'i mut STLayoutInterner<'a>,
home: ModuleId,
ident_ids: &'i mut IdentIds,
procs: &mut MutMap<(Symbol, ProcLayout<'a>), Proc<'a>>,
) {
for ((_symbol, proc_layout), proc) in procs.iter_mut() {
let mut environment = DropSpecializationEnvironment::new(arena, home, proc_layout.result);
specialize_drops_proc(arena, layout_interner, ident_ids, &mut environment, proc);
}
}
fn specialize_drops_proc<'a, 'i>(
arena: &'a Bump,
layout_interner: &'i mut STLayoutInterner<'a>,
ident_ids: &'i mut IdentIds,
environment: &mut DropSpecializationEnvironment<'a>,
proc: &mut Proc<'a>,
) {
for (layout, symbol) in proc.args.iter().copied() {
environment.add_symbol_layout(symbol, layout);
}
let new_body =
specialize_drops_stmt(arena, layout_interner, ident_ids, environment, &proc.body);
proc.body = new_body.clone();
}
fn specialize_drops_stmt<'a, 'i>(
arena: &'a Bump,
layout_interner: &'i mut STLayoutInterner<'a>,
ident_ids: &'i mut IdentIds,
environment: &mut DropSpecializationEnvironment<'a>,
stmt: &Stmt<'a>,
) -> &'a Stmt<'a> {
match stmt {
Stmt::Let(binding, expr @ Expr::Call(call), layout, continuation) => {
environment.add_symbol_layout(*binding, *layout);
macro_rules! alloc_let_with_continuation {
($environment:expr) => {{
let new_continuation = specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
$environment,
continuation,
);
arena.alloc(Stmt::Let(*binding, expr.clone(), *layout, new_continuation))
}};
}
match call.call_type.clone().replace_lowlevel_wrapper() {
CallType::LowLevel {
op: LowLevel::ListGetUnsafe,
..
} => {
let [structure, index] = match call.arguments {
[structure, index] => [structure, index],
_ => unreachable!("List get should have two arguments"),
};
environment.add_list_child_symbol(*structure, *binding, index);
alloc_let_with_continuation!(environment)
}
// Check whether the increments can be passed to the continuation.
CallType::LowLevel { op, .. } => match low_level_no_rc(&op) {
// It should be safe to pass the increments to the continuation.
RC::NoRc => alloc_let_with_continuation!(environment),
// We probably should not pass the increments to the continuation.
RC::Rc | RC::Uknown => {
let incremented_symbols = environment.incremented_symbols.drain();
let new_stmt = alloc_let_with_continuation!(environment);
// The new_environment might have inserted increments that were set to 0 before. We need to add th
for (symbol, increment) in incremented_symbols.map.into_iter() {
environment
.incremented_symbols
.insert_count(symbol, increment);
}
new_stmt
}
},
_ => {
// Calls can modify the RC of the symbol.
// If we move a increment of children after the function,
// the function might deallocate the child before we can use it after the function.
// If we move the decrement of the parent to before the function,
// the parent might be deallocated before the function can use it.
// Thus forget everything about any increments.
let incremented_symbols = environment.incremented_symbols.drain();
let new_stmt = alloc_let_with_continuation!(environment);
// The new_environment might have inserted increments that were set to 0 before. We need to add th
for (symbol, increment) in incremented_symbols.map.into_iter() {
environment
.incremented_symbols
.insert_count(symbol, increment);
}
new_stmt
}
}
}
Stmt::Let(_, _, _, _) => {
use Expr::*;
// to prevent stack overflows, try to use an explicit stack to accumulate a bunch of
// Let statements. Call expressions require more logic and are never put on this stack
let mut stack = vec![];
let mut stmt = stmt;
while let Stmt::Let(binding, expr, layout, continuation) = stmt {
environment.add_symbol_layout(*binding, *layout);
// update the environment based on the expr
match expr {
Call(_) => {
// Expr::Call is tricky and we are lazy and handle it elsewhere. it
// ends a chain of eligible Let statements.
break;
}
Literal(crate::ir::Literal::Int(i)) => {
environment
.symbol_index
.insert(*binding, i128::from_ne_bytes(*i) as u64);
}
Literal(_) => { /* do nothing */ }
Tag {
tag_id,
arguments: children,
..
} => {
environment.symbol_tag.insert(*binding, *tag_id);
for (index, child) in children.iter().enumerate() {
environment.add_union_child(*binding, *child, *tag_id, index as u64);
}
}
Struct(children) => {
for (index, child) in children.iter().enumerate() {
environment.add_struct_child(*binding, *child, index as u64);
}
}
StructAtIndex {
index, structure, ..
} => {
environment.add_struct_child(*structure, *binding, *index);
// TODO do we need to remove the indexed value to prevent it from being dropped sooner?
// It will only be dropped sooner if the reference count is 1. Which can only happen if there is no increment before.
// So we should be fine.
}
UnionAtIndex {
structure,
tag_id,
index,
..
} => {
// TODO perhaps we need the union_layout later as well? if so, create a new function/map to store it.
environment.add_union_child(*structure, *binding, *tag_id, *index);
// Generated code might know the tag of the union without switching on it.
// So if we UnionAtIndex, we must know the tag and we can use it to specialize the drop.
environment.symbol_tag.insert(*structure, *tag_id);
}
GetElementPointer {
structure, indices, ..
} => {
// Generated code might know the tag of the union without switching on it.
// So if we GetElementPointer, we must know the tag and we can use it to specialize the drop.
environment.symbol_tag.insert(*structure, indices[0] as u16);
}
Array {
elems: children, ..
} => {
let it =
children
.iter()
.enumerate()
.filter_map(|(index, child)| match child {
ListLiteralElement::Literal(_) => None,
ListLiteralElement::Symbol(s) => Some((index, s)),
});
for (index, child) in it {
environment.add_list_child(*binding, *child, index as u64);
}
}
ErasedMake { value, callee: _ } => {
if let Some(value) = value {
environment.add_struct_child(*binding, *value, 0);
}
}
ErasedLoad { symbol, field } => {
match field {
ErasedField::Value => {
environment.add_struct_child(*symbol, *binding, 0);
}
ErasedField::Callee | ErasedField::ValuePtr => {
// nothing to own
}
}
}
Reset { .. } | Expr::ResetRef { .. } => { /* do nothing */ }
FunctionPointer { .. }
| GetTagId { .. }
| Alloca { .. }
| EmptyArray
| NullPointer => { /* do nothing */ }
}
// now store the let binding for later
stack.push((*binding, expr.clone(), *layout));
// and "recurse" down the statement chain
stmt = continuation;
}
stack.into_iter().rev().fold(
specialize_drops_stmt(arena, layout_interner, ident_ids, environment, stmt),
|acc, (binding, expr, layout)| arena.alloc(Stmt::Let(binding, expr, layout, acc)),
)
}
Stmt::Switch {
cond_symbol,
cond_layout,
branches,
default_branch,
ret_layout,
} => {
macro_rules! insert_branch_info {
($branch_env:expr,$info:expr ) => {
match $info {
BranchInfo::Constructor {
scrutinee: symbol,
tag_id: tag,
..
} => {
$branch_env.symbol_tag.insert(*symbol, *tag);
}
BranchInfo::List {
scrutinee: symbol,
len,
} => {
$branch_env.list_length.insert(*symbol, *len);
}
_ => (),
}
};
}
let new_branches = branches
.iter()
.map(|(label, info, branch)| {
let mut branch_env = environment.clone();
insert_branch_info!(branch_env, info);
let new_branch = specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
&mut branch_env,
branch,
);
(*label, info.clone(), new_branch.clone(), branch_env)
})
.collect_in::<Vec<_>>(arena)
.into_bump_slice();
let new_default_branch = {
let (info, branch) = default_branch;
let mut branch_env = environment.clone();
insert_branch_info!(branch_env, info);
let new_branch = specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
&mut branch_env,
branch,
);
(info.clone(), new_branch, branch_env)
};
// Find consumed increments in each branch and make sure they are consumed in all branches.
// By incrementing them in each branch where they were not consumed.
{
let branch_envs = {
let mut branch_environments =
Vec::with_capacity_in(new_branches.len() + 1, arena);
for (_, _, _, branch_env) in new_branches.iter() {
branch_environments.push(branch_env);
}
branch_environments.push(&new_default_branch.2);
branch_environments
};
// Find the lowest symbol count for each symbol in each branch, and update the environment to match.
for (symbol, count) in environment.incremented_symbols.map.iter_mut() {
let consumed = branch_envs
.iter()
.map(|branch_env| {
branch_env.incremented_symbols.map.get(symbol).unwrap_or(&0)
})
.min()
.unwrap();
// Update the existing env to match the lowest count.
*count = *consumed;
}
}
macro_rules! insert_incs {
($branch_env:expr, $branch:expr ) => {{
let symbol_differences =
environment
.incremented_symbols
.map
.iter()
.filter_map(|(symbol, count)| {
let branch_count = $branch_env
.incremented_symbols
.map
.get(symbol)
.unwrap_or(&0);
match branch_count - count {
0 => None,
difference => Some((symbol, difference)),
}
});
symbol_differences.fold($branch, |new_branch, (symbol, difference)| {
arena.alloc(Stmt::Refcounting(
ModifyRc::Inc(*symbol, difference),
new_branch,
))
})
}};
}
environment.jump_incremented_symbols =
new_default_branch.2.jump_incremented_symbols.clone();
let newer_branches = new_branches
.iter()
.map(|(label, info, branch, branch_env)| {
for (joinpoint, current_incremented_symbols) in
environment.jump_incremented_symbols.iter_mut()
{
let opt_symbols = branch_env.jump_incremented_symbols.get(joinpoint);
if let Some(branch_incremented_symbols) = opt_symbols {
current_incremented_symbols.map.retain(|key, join_count| {
let opt_count = branch_incremented_symbols.map.get(key);
if let Some(count) = opt_count {
*join_count = std::cmp::min(*join_count, *count);
}
// retain only the Some cases
opt_count.is_some()
});
}
}
let new_branch = insert_incs!(branch_env, branch);
(*label, info.clone(), new_branch.clone())
})
.collect_in::<Vec<_>>(arena)
.into_bump_slice();
let newer_default_branch = {
let (info, branch, branch_env) = new_default_branch;
let new_branch = insert_incs!(branch_env, branch);
(info.clone(), new_branch)
};
arena.alloc(Stmt::Switch {
cond_symbol: *cond_symbol,
cond_layout: *cond_layout,
branches: newer_branches,
default_branch: newer_default_branch,
ret_layout: *ret_layout,
})
}
Stmt::Ret(symbol) => arena.alloc(Stmt::Ret(*symbol)),
Stmt::Refcounting(rc, continuation) => match rc {
ModifyRc::Inc(symbol, count) => {
let inc_before = environment.incremented_symbols.contains(symbol);
// Add a symbol for every increment performed.
environment
.incremented_symbols
.insert_count(*symbol, *count);
let new_continuation = specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
environment,
continuation,
);
if inc_before {
// There were increments before this one, best to let the first one do the increments.
// Or there are no increments left, so we can just continue.
new_continuation
} else {
match environment
.incremented_symbols
.map
.remove(symbol)
.unwrap_or(0)
{
// This is the first increment, but all increments are consumed. So don't insert any.
0 => new_continuation,
// We still need to do some increments.
new_count => arena.alloc(Stmt::Refcounting(
ModifyRc::Inc(*symbol, new_count),
new_continuation,
)),
}
}
}
ModifyRc::Dec(symbol) => {
// We first check if there are any outstanding increments we can cross of with this decrement.
// Then we check the continuation, since it might have a decrement of a symbol that's a child of this one.
// Afterwards we perform drop specialization.
// In the following example, we don't want to inline `dec b`, we want to remove the `inc a` and `dec a` instead.
// let a = index b
// inc a
// dec a
// dec b
if environment.incremented_symbols.pop(symbol) {
// This decremented symbol was incremented before, so we can remove it.
specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
environment,
continuation,
)
} else {
// Collect all children (recursively) that were incremented and make sure that one increment remains in the environment afterwards.
// To prevent
// let a = index b; inc a; dec b; ...; dec a
// from being translated to
// let a = index b; dec b
// As a might get dropped as a result of the decrement of b.
let mut incremented_children = {
let mut todo_children = bumpalo::vec![in arena; *symbol];
let mut incremented_children = CountingMap::new();
while let Some(child) = todo_children.pop() {
if environment.incremented_symbols.pop(&child) {
incremented_children.insert(child);
} else {
todo_children.extend(environment.get_children(&child));
}
}
incremented_children
};
// This decremented symbol was not incremented before, perhaps the children were.
let in_layout = environment.get_symbol_layout(symbol);
let runtime_repr = layout_interner.runtime_representation(*in_layout);
let updated_stmt = match runtime_repr {
// Layout has children, try to inline them.
LayoutRepr::Struct(field_layouts) => specialize_struct(
arena,
layout_interner,
ident_ids,
environment,
symbol,
field_layouts,
&mut incremented_children,
continuation,
),
LayoutRepr::Union(union_layout) => specialize_union(
arena,
layout_interner,
ident_ids,
environment,
symbol,
union_layout,
&mut incremented_children,
continuation,
),
LayoutRepr::Builtin(Builtin::List(layout)) => specialize_list(
arena,
layout_interner,
ident_ids,
environment,
&mut incremented_children,
symbol,
layout,
continuation,
),
// TODO: lambda sets should not be reachable, yet they are.
_ => {
let new_continuation = specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
environment,
continuation,
);
// No children, keep decrementing the symbol.
arena.alloc(Stmt::Refcounting(ModifyRc::Dec(*symbol), new_continuation))
}
};
// Add back the increments for the children to the environment.
for (child_symbol, symbol_count) in incremented_children.map.into_iter() {
environment
.incremented_symbols
.insert_count(child_symbol, symbol_count)
}
updated_stmt
}
}
ModifyRc::DecRef(_) | ModifyRc::Free(_) => {
// These operations are not recursive (the children are not touched)
// so inlining is not useful
arena.alloc(Stmt::Refcounting(
*rc,
specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
environment,
continuation,
),
))
}
},
Stmt::Expect {
condition,
region,
lookups,
variables,
remainder,
} => arena.alloc(Stmt::Expect {
condition: *condition,
region: *region,
lookups,
variables,
remainder: specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
environment,
remainder,
),
}),
Stmt::Dbg {
source_location,
source,
symbol,
variable,
remainder,
} => arena.alloc(Stmt::Dbg {
source_location,
source,
symbol: *symbol,
variable: *variable,
remainder: specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
environment,
remainder,
),
}),
Stmt::Join {
id,
parameters,
body,
remainder,
} => {
// We cannot perform this optimization if the joinpoint is recursive.
// E.g. if the body of a recursive joinpoint contains an increment, we do not want to move that increment up to the remainder.
let mut remainder_environment = environment.clone();
let new_remainder = specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
&mut remainder_environment,
remainder,
);
let mut body_environment = environment.clone();
for param in parameters.iter() {
body_environment.add_symbol_layout(param.symbol, param.layout);
}
body_environment.incremented_symbols.clear();
let new_body = specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
&mut body_environment,
body,
);
let remainder_jump_info = remainder_environment.jump_incremented_symbols.get(id);
let body_jump_info = body_environment.jump_incremented_symbols.get(id);
let (newer_body, newer_remainder) = match (remainder_jump_info, body_jump_info) {
// We have info from the remainder, and the body is not recursive.
// Meaning we can pass the incremented_symbols from the remainder to the body.
(Some(jump_info), None) if !jump_info.is_empty() => {
// Update body with incremented symbols from remainder
let mut body_environment = environment.clone();
for param in parameters.iter() {
body_environment.add_symbol_layout(param.symbol, param.layout);
}
body_environment.incremented_symbols = jump_info.clone();
let newer_body = specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
&mut body_environment,
body,
);
// Update remainder
environment.join_incremented_symbols.insert(
*id,
JoinUsage {
join_consumes: jump_info.clone(),
join_returns: body_environment.incremented_symbols,
},
);
let newer_remainder = specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
environment,
remainder,
);
(newer_body, newer_remainder)
}
_ => {
// Keep the body and remainder as is.
// Update the environment with remainder environment.
*environment = remainder_environment;
(new_body, new_remainder)
}
};
arena.alloc(Stmt::Join {
id: *id,
parameters,
body: newer_body,
remainder: newer_remainder,
})
}
Stmt::Jump(joinpoint_id, arguments) => {
match environment.join_incremented_symbols.get(joinpoint_id) {
Some(JoinUsage {
join_consumes,
join_returns,
}) => {
// Consume all symbols that were consumed in the join.
for (symbol, count) in join_consumes.map.iter() {
for _ in 0..*count {
let popped = environment.incremented_symbols.pop(symbol);
debug_assert!(
popped,
"Every incremented symbol should be available from jumps"
);
}
}
for (symbol, count) in join_returns.map.iter() {
environment
.incremented_symbols
.insert_count(*symbol, *count);
}
}
None => {
// No join usage, let the join know the minimum amount of symbols that were incremented from each jump.
environment
.jump_incremented_symbols
.insert(*joinpoint_id, environment.incremented_symbols.clone());
}
}
arena.alloc(Stmt::Jump(*joinpoint_id, arguments))
}
Stmt::Crash(symbol, crash_tag) => arena.alloc(Stmt::Crash(*symbol, *crash_tag)),
}
}
fn specialize_struct<'a, 'i>(
arena: &'a Bump,
layout_interner: &'i mut STLayoutInterner<'a>,
ident_ids: &'i mut IdentIds,
environment: &mut DropSpecializationEnvironment<'a>,
symbol: &Symbol,
struct_layout: &'a [InLayout],
incremented_children: &mut CountingMap<Child>,
continuation: &'a Stmt<'a>,
) -> &'a Stmt<'a> {
match environment.struct_children.get(symbol) {
// TODO all these children might be non reference counting, inlining the dec without any benefit.
// Perhaps only insert children that are reference counted.
Some(children) => {
// TODO perhaps this allocation can be avoided.
let children_clone = children.clone();
// Map tracking which index of the struct is contained in which symbol.
// And whether the child no longer has to be decremented.
let mut index_symbols = MutMap::default();
for (index, _layout) in struct_layout.iter().enumerate() {
for (child, _i) in children_clone.iter().filter(|(_, i)| *i == index as u64) {
let removed = incremented_children.pop(child);
index_symbols.insert(index, (*child, removed));
if removed {
break;
}
}
}
let mut new_continuation =
specialize_drops_stmt(arena, layout_interner, ident_ids, environment, continuation);
// Make sure every field is decremented.
// Reversed to ensure that the generated code decrements the fields in the correct order.
for (i, field_layout) in struct_layout.iter().enumerate().rev() {
// Only insert decrements for fields that are/contain refcounted values.
if layout_interner.contains_refcounted(*field_layout) {
new_continuation = match index_symbols.get(&i) {
// This value has been indexed before, use that symbol.
Some((s, popped)) => {
if *popped {
// This symbol was popped, so we can skip the decrement.
new_continuation
} else {
// This symbol was indexed but not decremented, so we will decrement it.
arena.alloc(Stmt::Refcounting(ModifyRc::Dec(*s), new_continuation))
}
}
// This value has not been index before, create a new symbol.
None => {
let field_symbol =
environment.create_symbol(ident_ids, &format!("field_val_{i}"));
let field_val_expr = Expr::StructAtIndex {
index: i as u64,
field_layouts: struct_layout,
structure: *symbol,
};
arena.alloc(Stmt::Let(
field_symbol,
field_val_expr,
layout_interner.chase_recursive_in(*field_layout),
arena.alloc(Stmt::Refcounting(
ModifyRc::Dec(field_symbol),
new_continuation,
)),
))
}
};
}
}
new_continuation
}
None => {
// No known children, keep decrementing the symbol.
let new_continuation =
specialize_drops_stmt(arena, layout_interner, ident_ids, environment, continuation);
arena.alloc(Stmt::Refcounting(ModifyRc::Dec(*symbol), new_continuation))
}
}
}
fn specialize_union<'a, 'i>(
arena: &'a Bump,
layout_interner: &'i mut STLayoutInterner<'a>,
ident_ids: &'i mut IdentIds,
environment: &mut DropSpecializationEnvironment<'a>,
symbol: &Symbol,
union_layout: UnionLayout<'a>,
incremented_children: &mut CountingMap<Child>,
continuation: &'a Stmt<'a>,
) -> &'a Stmt<'a> {
let current_tag = environment.symbol_tag.get(symbol).copied();
macro_rules! keep_original_decrement {
() => {{
let new_continuation =
specialize_drops_stmt(arena, layout_interner, ident_ids, environment, continuation);
arena.alloc(Stmt::Refcounting(ModifyRc::Dec(*symbol), new_continuation))
}};
}
match get_union_tag_layout(union_layout, current_tag) {
// No known tag, decrement the symbol as usual.
UnionFieldLayouts::Unknown => {
keep_original_decrement!()
}
// The union is null, so we can skip the decrement.
UnionFieldLayouts::Null => {
specialize_drops_stmt(arena, layout_interner, ident_ids, environment, continuation)
}
// We know the tag, we can specialize the decrement for the tag.
UnionFieldLayouts::Found { field_layouts, tag } => {
match environment.union_children.get(&(*symbol, tag)) {
None => keep_original_decrement!(),
Some(children) => {
// TODO perhaps this allocation can be avoided.
let children_clone = children.clone();
// Map tracking which index of the struct is contained in which symbol.
// And whether the child no longer has to be decremented.
let mut index_symbols = MutMap::default();
for (index, _layout) in field_layouts.iter().enumerate() {
for (child, _i) in children_clone
.iter()
.rev()
.filter(|(_child, i)| *i == index as u64)
{
let removed = incremented_children.pop(child);
index_symbols.entry(index).or_insert((*child, removed));
if removed {
break;
}
}
}
let new_continuation = specialize_drops_stmt(
arena,
layout_interner,
ident_ids,
environment,
continuation,
);
type RCFun<'a> =
Option<fn(arena: &'a Bump, Symbol, &'a Stmt<'a>) -> &'a Stmt<'a>>;
let refcount_fields = |layout_interner: &mut STLayoutInterner<'a>,
ident_ids: &mut IdentIds,
rc_popped: RCFun<'a>,
rc_unpopped: RCFun<'a>,
continuation: &'a Stmt<'a>|
-> &'a Stmt<'a> {
let mut new_continuation = continuation;
// Reversed to ensure that the generated code decrements the fields in the correct order.
for (i, field_layout) in field_layouts.iter().enumerate().rev() {
// Only insert decrements for fields that are/contain refcounted values.
if layout_interner.contains_refcounted(*field_layout) {
new_continuation = match index_symbols.get(&i) {
// This value has been indexed before, use that symbol.
Some((s, popped)) => {
if *popped {
// This symbol was popped, so we can skip the decrement.
match rc_popped {
Some(rc) => rc(arena, *s, new_continuation),
None => new_continuation,
}
} else {
// This symbol was indexed but not decremented, so we will decrement it.
match rc_unpopped {
Some(rc) => rc(arena, *s, new_continuation),
None => new_continuation,
}
}
}
// This value has not been index before, create a new symbol.
None => match rc_unpopped {
Some(rc) => {
let field_symbol = environment.create_symbol(
ident_ids,
&format!("field_val_{i}"),
);
let field_val_expr = Expr::UnionAtIndex {
structure: *symbol,
tag_id: tag,
union_layout,
index: i as u64,
};
arena.alloc(Stmt::Let(
field_symbol,
field_val_expr,
layout_interner.chase_recursive_in(*field_layout),
rc(arena, field_symbol, new_continuation),
))
}
None => new_continuation,
},
};
}
}
new_continuation
};
match union_layout {
UnionLayout::NonRecursive(_) => refcount_fields(
layout_interner,
ident_ids,
// Do nothing for the children that were incremented before, as the decrement will cancel out.
None,
// Decrement the children that were not incremented before. And thus don't cancel out.
Some(|arena, symbol, continuation| {
arena.alloc(Stmt::Refcounting(ModifyRc::Dec(symbol), continuation))
}),
new_continuation,
),
UnionLayout::Recursive(_)
| UnionLayout::NonNullableUnwrapped(_)
| UnionLayout::NullableWrapped { .. }
| UnionLayout::NullableUnwrapped { .. } => {
branch_uniqueness(
arena,
ident_ids,
layout_interner,
environment,
*symbol,
// If the symbol is unique:
// - drop the children that were not incremented before
// - don't do anything for the children that were incremented before