Repository navigation
Expand file tree
/
Copy pathlooplowering.d
More file actions
6386 lines (6375 loc) · 246 KB
/
Copy pathlooplowering.d
File metadata and controls
6386 lines (6375 loc) · 246 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
// Written in the D programming language
// License: http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0
// Lowering of loops to recursive functions (`--remove-loops`):
// - `sliceLoop`: lowers a loop with loop-carried lifted state into a main loop and loops that recompute the lifted state
// (each lowered into a recursive function)
// - `splitLoop`: splits a loop into several loops, such that loop-carried lifted state can be lowered
// into `qfree` recursive functions (with logs communicating values between the loops; used where `sliceLoop` is not)
// - `lowerLoop`: lowers a single loop into a recursive function
// - early-return elimination: prepares functions whose loops contain `return` statements for `lowerLoop`
module ast.looplowering;
import astopt;
import std.array,std.algorithm,std.range,std.exception;
import std.format, std.conv, util.tuple:Q=Tuple,q=tuple;
import ast.lexer,ast.scope_,ast.expression,ast.type,ast.conversion;
import ast.declaration,ast.error,util;
import ast.semantic_;
import ast.substitute:updateLambdaDefinition,updateLambdaDefinitions;
// Conservative check that evaluating `e` cannot fail (e.g., an `assert` or out-of-bounds access) or diverge.
// Only such code may be removed, or executed where the original program would not execute it.
bool cannotFail(Expression e){
bool ok=true;
// calls in definition targets are reversed: e.g., `dup(a):=z` checks that `z` equals `a`, which may fail
SetX!CallExp targetCalls;
visitStm(e,(Expression x){
if(auto de=cast(DefineExp)x) visitStm(de.e1,(Expression y){ if(auto ce=cast(CallExp)y) targetCalls.insert(ce); });
});
visitStm(e,(Expression x){
if(!ok) return;
if(auto ce=cast(CallExp)x){
if(ce.isSquare) return;
Expression f=ce.e;
while(auto sq=cast(CallExp)f){
if(!sq.isSquare) break;
f=sq.e;
}
auto id=cast(Identifier)f;
auto fd=id?cast(FunctionDef)id.meaning:null;
if(!fd){ ok=false; return; }
if(ce in targetCalls){ // only reversed unitary primitives cannot fail
auto prim=isPrimitive(fd);
if(!prim||!util.among(prim,"H","X","Y","Z","rX","rY","rZ")) ok=false;
return;
}
if(auto prim=isPrimitive(fd)){
if(!util.among(prim,"dup","M","H","X","Y","Z","P","rX","rY","rZ")) ok=false;
}else{
// (the prelude's `dup` and `measure` are curried: the called function is the one returned by the outer
// definition, which the parser marks `artificial` without a value)
import ast.modules:isInPrelude;
if(!(isInPrelude(fd)&&fd.attributes.getPtr(Id.s!"artificial")&&util.among(fd.getName,"dup","measure","rotZ"))) ok=false;
}
}else if(cast(IndexExp)x||cast(SliceExp)x||cast(DivExp)x||cast(IDivExp)x||cast(ModExp)x||cast(PowExp)x
||cast(AssertExp)x||isLoopStatement(x)||cast(ReturnExp)x){
ok=false;
}else if(auto tae=cast(TypeAnnotationExp)x){
if(tae.annotationType==TypeAnnotationType.coercion) ok=false;
}else if(auto fe=cast(ForgetExp)x){
// an explicit value may be correct only on some basis states (e.g., where a guarding condition holds)
if(fe.val) ok=false;
}
});
return ok;
}
void visitStm(Expression e,scope void delegate(Expression) dg){
if(!e) return;
dg(e);
if(auto fd=cast(FunctionDef)e){
foreach(decl;fd.capturedDecls) foreach(id;fd.captures[decl]) visitStm(id,dg);
return;
}
if(auto fe=cast(ForExp)e){
if(auto r=fe.aggr.isRange){
visitStm(r.left,dg);
visitStm(r.step,dg);
visitStm(r.right,dg);
}else if(auto c=fe.aggr.isContainer) visitStm(c.e,dg);
visitStm(fe.bdy,dg);
return;
}
foreach(c;e.components) visitStm(c,dg);
}
private void visitStmSkip(Expression e,scope bool delegate(Expression) dg){
if(!e) return;
if(!dg(e)) return;
if(auto fd=cast(FunctionDef)e){
foreach(decl;fd.capturedDecls) foreach(id;fd.captures[decl]) visitStmSkip(id,dg);
return;
}
if(auto fe=cast(ForExp)e){
if(auto r=fe.aggr.isRange){
visitStmSkip(r.left,dg);
visitStmSkip(r.step,dg);
visitStmSkip(r.right,dg);
}else if(auto c=fe.aggr.isContainer) visitStmSkip(c.e,dg);
visitStmSkip(fe.bdy,dg);
return;
}
foreach(c;e.components) visitStmSkip(c,dg);
}
private void walkCond(Expression e,bool cond,scope void delegate(Expression,bool) dg){
if(!e) return;
dg(e,cond);
if(auto fd=cast(FunctionDef)e){
foreach(decl;fd.capturedDecls) foreach(id;fd.captures[decl]) walkCond(id,cond,dg);
return;
}
if(auto le=cast(LambdaExp)e){
foreach(decl;le.fd.capturedDecls) foreach(id;le.fd.captures[decl]) walkCond(id,cond,dg);
return;
}
if(auto ite=cast(IteExp)e){
walkCond(ite.cond,cond,dg);
walkCond(ite.then,true,dg);
walkCond(ite.othw,true,dg);
return;
}
if(auto fe=cast(ForExp)e){
if(auto r=fe.aggr.isRange){
walkCond(r.left,cond,dg);
walkCond(r.step,cond,dg);
walkCond(r.right,cond,dg);
}else if(auto c=fe.aggr.isContainer) walkCond(c.e,cond,dg);
walkCond(fe.bdy,true,dg);
return;
}
if(isLoopStatement(e)){ // (`for` loops are handled above)
foreach(c;e.components) walkCond(c,true,dg);
return;
}
if(auto le=cast(ALogicExp)e){
walkCond(le.e1,cond,dg);
walkCond(le.e2,true,dg);
return;
}
foreach(c;e.components) walkCond(c,cond,dg);
}
private void walkShallow(Expression e,scope void delegate(Expression) dg){
if(!e) return;
dg(e);
if(cast(FunctionDef)e||cast(LambdaExp)e) return;
if(auto tae=cast(TypeAnnotationExp)e){
walkShallow(tae.e,dg);
return;
}
if(auto ce=cast(CallExp)e) if(ce.isSquare){
walkShallow(ce.e,dg);
return;
}
if(auto fe=cast(ForExp)e){
if(auto r=fe.aggr.isRange){
walkShallow(r.left,dg);
walkShallow(r.step,dg);
walkShallow(r.right,dg);
}else if(auto c=fe.aggr.isContainer) walkShallow(c.e,dg);
walkShallow(fe.bdy,dg);
return;
}
foreach(c;e.components) walkShallow(c,dg);
}
private Id varName(Identifier id){
return id.meaning&&id.meaning.name?id.meaning.name.id:id.id;
}
private bool sameDeps(ref Dependency a,ref Dependency b){
if(a.dependencies.length!=b.dependencies.length) return false;
foreach(x;a.dependencies) if(x !in b.dependencies) return false;
return true;
}
// Whether a lifted copy of the loop-carried variable `decl` with dependencies `dep` could not be forgotten after the loop,
// as its (transitive) dependencies are changed by the loop
private bool dependsTransitivelyOnLoopState(ref FixedPointIterState state,Scope sc,bool[Declaration] loopState,Declaration decl,Dependency dep){
bool[Declaration] visited;
Declaration[] todo;
foreach(d;dep.dependencies) todo~=d;
while(todo.length){
auto d=todo[$-1];
todo=todo[0..$-1];
if(d in visited) continue;
visited[d]=true;
if(d !is decl&&d in loopState) return true;
auto dd=state.prevStateSnapshot.dependencyOf(d);
if(dd.isTop){
// a dependency that was recomputable at the loop entry but is not after an iteration (as the loop consumes
// one of its dependencies) could no longer be forgotten after the loop
if(!state.origStateSnapshot.dependencyOf(d).isTop) return true;
// a variable that could still be forgotten at its last use (before it became non-recomputable) may be
// forgotten there, before the loop: it is not available after the loop unless it is consumed later
if(auto lu=sc.lastUses.get(d,false)){
for(;;){ // (the last use itself, not a split into a nested scope)
while(lu.forwardTo) lu=lu.forwardTo;
if(lu.kind!=imported!"ast.lastuse".LastUse.Kind.lazySplit) break;
lu=lu.getSplitFrom();
}
if(lu.isConsumption()||!lu.dep.isTop) return true;
}
continue; // (not recomputable anyway, but available: the traversal ends here)
}
foreach(e;dd.dependencies) todo~=e;
}
return false;
}
// (for diagnostics, the variables after a lowered loop are linked to those of the analysis of the loop itself)
private void linkLoweredVariables(Scope sc,ref SymbolTable before){
foreach(id,d;sc.rnsymtab)
if(auto vd=cast(VarDecl)d) if(auto od=cast(VarDecl)before.get(id,null))
if(od !is vd&&!vd.loweredFrom&&!vd.typeSource&&!od.isSemError()) vd.loweredFrom=od;
foreach(id,d;before)
if(auto dd=cast(DeadDecl)d) if(id !in sc.rnsymtab) sc.symtabInsert(dd); // (explains uses of a variable that the loop does not produce)
}
// whether a `return` can end an iteration of a `while` loop in `e` for all basis states, i.e., it is not in a quantum
// conditional of the body of the loop that does not definitely return (the code after one is reachable for the other basis states)
private bool whileStopsAtReturn(Expression e){
bool r=false;
visitStm(e,(Expression x){
auto we=cast(WhileExp)x;
if(r||!we) return;
visitStmSkip(we.bdy,(Expression y){
if(r) return false;
if(auto ite=cast(IteExp)y) if(ite.cond.type&&!ite.cond.type.isClassical()&&!definitelyReturns(ite)) return false;
if(cast(ReturnExp)y) r=true;
return !r;
});
});
return r;
}
Expression splitLoop(T)(T loop,ref FixedPointIterState state,Scope sc,ref StmFlags flags){
static if(is(T==ForExp)){
auto range=loop.aggr.isRange;
if(!range||!loop.loopVar) return null;
}
if(loop.noSplit||whileStopsAtReturn(loop)) return null; // (the copies of a `while` loop evaluate its condition: they would run its iterations after the return, e.g., forever for `while true { …; return x; }` under quantum control from outside of the loop)
static if(language==silq) if(containsDoWhile(loop.bdy)) return null;
enum NONE=-3,LSH=-2,SHARED=-1;
auto carried=state.prevStateSnapshot.loopParams(loop.bdy.blscope_,null,false,null);
if(!carried[0].length) return null;
bool[Declaration] loopState;
foreach(q;carried[0]~carried[1]) loopState[q[1]]=true;
// Versions of quantum variables: within a block, a variable that is defined several times at the top level
// of the block gets fresh names for its intermediate values; its last definition in the loop body restores the name
// (definitions in nested blocks are handled recursively: a conditional all of whose branches define the variable is a
// definition, and other nested definitions update the current name in place). The partitioning below is by name: this allows values of
// different classes to pass through the same variable within an iteration (e.g., with swaps). (No renaming is needed
// to keep intermediate values alive: a quantum variable cannot be redefined before it is consumed.)
Id[const(void)*] versionOf;
Id vname(Identifier id){
if(auto v=cast(const(void)*)id in versionOf) return *v;
return varName(id);
}
{
// (loop-carried and loop-local variables)
Id[] candidates;
SetX!Id seen;
void candidate(Id n){
if(n in seen) return;
seen.insert(n);
candidates~=n;
}
foreach(p;carried[0]~carried[1]){
auto ty=typeForDecl(p[1]);
if(ty&&!ty.isClassical()) candidate(p[1].name.id);
}
visitStm(loop.bdy,(Expression y){
if(auto de=cast(DefineExp)y) visitStm(de.e1,(Expression z){
if(auto id=cast(Identifier)z) if(!id.constLookup&&id.type&&!id.type.isClassical()) candidate(varName(id));
});
});
foreach(x;candidates){
Id[const(void)*] vers;
bool isX(Expression e){
auto id=cast(Identifier)e;
return id&&varName(id)==x;
}
Identifier simpleDef(Expression s){ // `x` defined by a component of the left-hand side of a definition
auto de=cast(DefineExp)s;
if(!de||de.isSwap) return null;
Identifier r=null;
size_t count=0;
visitStm(de.e1,(Expression y){ if(isX(y)) count++; });
if(count!=1) return null;
if(isX(de.e1)) r=cast(Identifier)de.e1;
else if(auto tpl=cast(TupleExp)de.e1) foreach(c;tpl.e) if(isX(c)) r=cast(Identifier)c;
return r&&!r.constLookup?r:null;
}
Expression[] flatten(CompoundExp b){ // (as in `addStm`)
Expression[] r;
void add(Expression s){
if(auto ce=cast(CompoundExp)s) if(!ce.blscope_){
foreach(t;ce.s) add(t);
return;
}
r~=s;
}
foreach(s;b.s) add(s);
return r;
}
// a definition of `x`, or a conditional all of whose branches define it (the branches then end with the same
// new version)
bool isDef(Expression s){
if(simpleDef(s)) return true;
auto ite=cast(IteExp)s;
return ite&&ite.othw&&flatten(ite.then).any!(t=>isDef(t))&&flatten(ite.othw).any!(t=>isDef(t));
}
// `entry`/`exit`: names of `x` at the start and end of the block
void renameBlock(CompoundExp b,Id entry,Id exit){
void renameAll(Expression e,Id name){
visitStmSkip(e,(Expression y){
if(auto ce=cast(CompoundExp)y){
renameBlock(ce,name,name);
return false;
}
if(isX(y)&&name!=x) vers[cast(const(void)*)y]=name;
return true;
});
}
auto flat=flatten(b);
auto numDefs=flat.count!(s=>isDef(s));
assert(numDefs||entry==exit);
Id name=entry;
size_t j=0;
foreach(s;flat){
if(!isDef(s)){
renameAll(s,name);
continue;
}
auto next=++j==numDefs?exit:freshName();
if(auto lhs=simpleDef(s)){
renameAll((cast(DefineExp)s).e2,name);
if(next!=x) vers[cast(const(void)*)lhs]=next;
}else{
auto ite=cast(IteExp)s;
renameAll(ite.cond,name);
renameBlock(ite.then,name,next);
renameBlock(ite.othw,name,next);
}
name=next;
}
assert(name==exit);
}
renameBlock(loop.bdy,x,x);
foreach(k,v;vers) versionOf[k]=v;
}
}
bool versionCopyFailed=false;
// copy of `e` with the versions of variables applied
Expression vcopy(Expression e){
auto c=e.copy();
if(!versionOf.length) return c;
Expression[] on,cn;
walkShallow(e,(Expression x){ on~=x; });
walkShallow(c,(Expression x){ cn~=x; });
if(on.length!=cn.length){
if(on.any!(x=>cast(const(void)*)x in versionOf)) versionCopyFailed=true; // (checked before the split is used)
return c;
}
foreach(k,x;on) if(auto v=cast(const(void)*)x in versionOf) (cast(Identifier)cn[k]).id=*v;
return c;
}
Dependency[] classDeps;
int[] classOf;
typeof(carried[0]) lifted;
foreach(p;carried[0]){
auto dep=state.prevStateSnapshot.dependencyOf(p[1]);
// the lifted copies of `p` are forgotten after the loop, which requires its dependencies, and eventually theirs:
// the transitive dependencies must not be modified by the loop (e.g., consumed by an early return within it)
if(dep.isTop||dependsTransitivelyOnLoopState(state,sc,loopState,p[1],dep)){ // (then `p` is not lifted)
carried[1]~=p;
continue;
}
lifted~=p;
int c=-1;
foreach(j,ref d;classDeps) if(sameDeps(d,dep)){ c=cast(int)j; break; }
if(c==-1){
c=cast(int)classDeps.length;
classDeps~=dep;
}
classOf~=c;
}
carried[0]=lifted;
if(!carried[0].length) return null;
auto late=new bool[](classDeps.length);
auto rank=new int[](classDeps.length);
int P;
void setupRanks(){
auto order=iota(cast(int)classDeps.length).array;
order.sort!((a,b)=>late[a]<late[b]||late[a]==late[b]&&classDeps[a].dependencies.length<classDeps[b].dependencies.length,SwapStrategy.stable);
P=cast(int)late.count!(x=>!x);
foreach(r,c;order) rank[c]=cast(int)(late[c]?r+1:r);
}
setupRanks();
MapX!(Id,int) color;
SetX!Id isCarried;
MapX!(Id,Expression) carriedType;
SetX!Id classical;
foreach(p;carried[0]~carried[1]){
auto ty=typeForDecl(p[1]);
isCarried.insert(p[1].name.id);
carriedType[p[1].name.id]=ty;
if(ty.isClassical()) classical.insert(p[1].name.id);
}
struct StmInfo{
SetX!Id defs,uses,nonConst,consumed,strong,fresh; // (`fresh`: defined by `:=`)
MapX!(Id,Expression) types;
bool nonQfree=false,isForget=false,effects=false;
}
Id[const(void)*] extracted;
bool[const(void)*] reanalyze,isExtractAtom;
bool hasQuantumReturn=false;
StmInfo analyzeStm(Expression s,out bool bad){
StmInfo info;
info.isForget=!!cast(ForgetExp)s;
SetX!Identifier targets;
void strongDef(Id n){
info.defs.insert(n);
info.strong.insert(n);
}
void addDefs(Expression lhs,bool fresh){
visitStm(lhs,(Expression x){
if(auto ie=cast(IndexExp)x){
Expression r=ie;
while(cast(IndexExp)r) r=(cast(IndexExp)r).e;
if(auto id=cast(Identifier)r) strongDef(vname(id));
}else if(auto id=cast(Identifier)x) if(!id.constLookup){
strongDef(vname(id));
if(fresh) info.fresh.insert(vname(id));
targets.insert(id);
if(id.type) info.types[vname(id)]=id.type;
}
});
}
visitStmSkip(s,(Expression x){
if(auto f=cast(const(void)*)x in extracted){
info.uses.insert(*f);
if(x.type) info.types[*f]=x.type;
return false;
}
if(auto ret=cast(ReturnExp)x){
// Loops with classically controlled early returns are not split: a separate loop computing lifted state
// would also run the iterations after the return, which may fail or diverge where the original program does
// not. (Such loops are rewritten without early returns first, see `erpExplicitExits`.) The code after
// quantum-controlled returns is reachable in the original program anyway.
auto ri=erpKey(ret) in erpReturns;
if(!ri||!ri.quantum){
bad=true;
return false;
}
info.effects=true; // (stays in the main loop)
hasQuantumReturn=true;
}
if(auto fd=cast(FunctionDef)x) if(fd.name) strongDef(fd.name.id);
if(cast(AssertExp)x) info.effects=true;
if(auto de=cast(DefineExp)x) addDefs(de.e1,true);
else if(auto we=cast(WithExp)x){
visitStm(we.trans,(Expression y){
if(auto id=cast(Identifier)y)
if(id.type&&!id.type.isClassical())
strongDef(vname(id));
});
if(we.itrans) visitStm(we.itrans,(Expression y){ if(auto de=cast(DefineExp)y) addDefs(de.e1,false); }); // (the inverse writes back what the transformation borrows, also classical variables, e.g., `k` for `with { c:=k; } do { c:=X(c); }`)
if(we.isIndices) foreach(st;we.trans.s) if(auto de=cast(DefineExp)st){ // (the write-back of an index assignment also updates a classical aggregate, e.g., `arr` for `arr[0]=5`)
Expression r=de.e2;
while(auto ie=cast(IndexExp)r) r=ie.e;
if(auto id=cast(Identifier)r) if(id.type&&id.type.isClassical()) strongDef(vname(id));
}
}else if(auto ae=cast(AAssignExp)x){
Expression lhs=ae.e1;
while(cast(IndexExp)lhs) lhs=(cast(IndexExp)lhs).e;
if(auto id=cast(Identifier)lhs) strongDef(vname(id));
else addDefs(ae.e1,false);
}else if(auto ce=cast(CallExp)x){
if(auto ft=cast(FunTy)ce.e.type)
if(!ft.isSquare&&ft.annotation<Annotation.qfree) info.nonQfree=true;
}else if(auto id=cast(Identifier)x){
if(id in targets||cast(DatDecl)id.meaning) return true;
auto n=vname(id);
info.uses.insert(n);
if(id.type) info.types[n]=id.type;
if(!id.constLookup&&!id.implicitDup){
info.nonConst.insert(n);
if(id.type&&!id.type.isClassical()){
info.consumed.insert(n);
info.defs.insert(n);
}
}
}
return true;
});
foreach(n;info.uses) info.fresh.remove(n); // (a definition that reads the previous value consumes it, e.g., `x:=H(x)`)
return info;
}
Expression[] stms;
StmInfo[] infos;
bool bad=false;
void addStm(Expression s){
if(auto ce=cast(CompoundExp)s) if(!ce.blscope_){
foreach(x;ce.s) addStm(x);
return;
}
bool b=false;
auto info=analyzeStm(s,b);
bad|=b;
stms~=s;
infos~=info;
}
foreach(s;loop.bdy.s) addStm(s);
if(bad) return null;
MapX!(Id,size_t) occurrences(Expression[] ss){
MapX!(Id,size_t) r;
foreach(s;ss) walkCond(s,false,(Expression x,bool c){
if(auto id=cast(Identifier)x) r[vname(id)]=r.get(vname(id),0)+1;
});
return r;
}
auto totalOcc=occurrences(stms);
Expression[const(void)*] replacedBy;
StmInfo[const(void)*] synthInfo;
bool dceRemoved=false; // (whether the loop has dead code)
void dce(ref Expression[] stms,ref StmInfo[] infos,scope bool delegate(Id) liveAtEnd){
struct Ver{ Id var; int stm; }
Ver[] vers;
MapX!(Id,int) cur;
int[][] usedBy;
MapX!(Id,int)[] useVer, defVer;
int getCur(Id n){
if(n !in cur){
cur[n]=cast(int)vers.length;
vers~=Ver(n,-1);
usedBy~=null;
}
return cur[n];
}
foreach(i,ref info;infos){
MapX!(Id,int) uv,dv;
foreach(u;info.uses){
auto v=getCur(u);
uv[u]=v;
usedBy[v]~=cast(int)i;
}
foreach(d;info.defs){
cur[d]=cast(int)vers.length;
dv[d]=cast(int)vers.length;
vers~=Ver(d,cast(int)i);
usedBy~=null;
}
useVer~=uv;
defVer~=dv;
}
auto liveOut=new bool[](vers.length);
foreach(n,v;cur) if(liveAtEnd(n)) liveOut[v]=true;
auto dead=new bool[](infos.length);
foreach(i,ref info;infos) dead[i]=!info.isForget&&!info.nonQfree&&!info.effects&&info.defs.length&&cannotFail(stms[i]);
bool defDead(int v){ return vers[v].stm>=0&&dead[vers[v].stm]; }
for(bool changed=true;changed;){
changed=false;
foreach(i,ref info;infos){
if(!dead[i]) continue;
bool ok=true;
foreach(d,v;defVer[i]){
if(liveOut[v]){ ok=false; break; }
foreach(j;usedBy[v]){
if(infos[j].isForget){
foreach(u,w;useVer[j]) if(!defDead(w)) ok=false;
if(!cannotFail(stms[j])) ok=false; // (a forget that may fail stays, with the definition, e.g., `forget(c=0:𝔹)` after `c:=1:𝔹`)
}else if(!dead[j]) ok=false;
}
}
if(!ok){
dead[i]=false;
changed=true;
}
}
}
if(dead.any){
dceRemoved=true;
Expression[] nstms;
StmInfo[] ninfos;
foreach(i,s;stms){
if(infos[i].isForget){
if(useVer[i].byValue.any!(w=>defDead(w))) continue;
}else if(dead[i]){
foreach(u;infos[i].consumed){
auto w=useVer[i][u];
if(defDead(w)||vers[w].stm<0&&!liveAtEnd(u)) continue;
auto fid=new Identifier(u);
fid.loc=s.loc;
auto fe=new ForgetExp(fid,null);
fe.loc=s.loc;
StmInfo fi;
fi.isForget=true;
fi.defs.insert(u);
fi.uses.insert(u);
fi.nonConst.insert(u);
fi.consumed.insert(u);
if(auto t=infos[i].types.get(u,null)) fi.types[u]=t;
nstms~=fe;
ninfos~=fi;
replacedBy[cast(const(void)*)fe]=s;
synthInfo[cast(const(void)*)fe]=fi;
}
continue;
}
nstms~=s;
ninfos~=infos[i];
}
stms=nstms;
infos=ninfos;
}
}
dce(stms,infos,(Id n)=>!!(n in isCarried));
Expression[] blockStms(Expression[] ss,bool isLoopBody){
Expression[] list;
StmInfo[] linfos;
void add(Expression s){
if(auto ce=cast(CompoundExp)s) if(!ce.blscope_){
foreach(x;ce.s) add(x);
return;
}
bool b=false;
linfos~=analyzeStm(s,b);
bad|=b;
list~=s;
}
foreach(s;ss) add(s);
auto occ=occurrences(list);
SetX!Id early;
if(isLoopBody){
SetX!Id defined;
foreach(ref inf;linfos){
foreach(u;inf.uses) if(u !in defined) early.insert(u);
foreach(d;inf.defs) defined.insert(d);
}
}
dce(list,linfos,(Id n)=>n in isCarried||n in early||totalOcc.get(n,0)>occ.get(n,0));
return list;
}
// A path of the loop body that ends in a diverging statement (e.g., a quantum-controlled `return` or a failing `assert`)
// does not reach the next iteration of the original loop, but it does in the split loops without that statement.
struct Div{
bool on; // (the path diverges before the end of the iteration)
SetX!Id redefs; // (variables defined on the path before it diverges)
}
Div including(Div dv,Expression s){ // (`s` runs before the path continues as described by `dv`)
bool b=false;
auto defs=analyzeStm(s,b).strong;
if(definitelyReturns(s)) return Div(true,defs);
if(!dv.on) return dv;
auto redefs=dv.redefs.dup;
foreach(d;defs) redefs.insert(d);
return Div(true,redefs);
}
Div[] divsOf(Expression[] list,Div after){ // (after each statement of a block)
auto r=new Div[](list.length);
foreach_reverse(j,s;list){
r[j]=after;
after=including(after,s);
}
return r;
}
struct Atom{
Expression e;
size_t stm;
size_t[] ites;
bool[] inElse;
Expression[] parts;
Div div;
}
struct Ite{
Expression e;
size_t stm;
StmInfo info;
size_t[] ctx;
size_t first;
bool isLoop;
Expression[] heads;
bool isWith;
size_t pseudo;
}
Atom[] atoms;
Ite[] ites;
bool splitTuple(DefineExp de){
auto lhs=cast(TupleExp)de.e1, rhs=cast(TupleExp)de.e2;
if(de.isSwap||!lhs||!rhs||lhs.e.length!=rhs.e.length||lhs.e.length<2) return false;
Id[] roots;
foreach(l;lhs.e){
Expression r=l;
while(cast(IndexExp)r) r=(cast(IndexExp)r).e;
auto id=cast(Identifier)r;
if(!id) return false;
auto n=vname(id);
if(roots.canFind(n)) return false;
roots~=n;
}
foreach(k;0..lhs.e.length){
bool ok=true;
void check(Expression e){
visitStm(e,(Expression x){
if(auto id=cast(Identifier)x){
auto n=vname(id);
foreach(j,r;roots) if(j!=k&&r==n) ok=false;
}
});
}
check(lhs.e[k]);
check(rhs.e[k]);
if(!ok) return false;
}
return true;
}
void extractFrom(Expression root,size_t i,size_t[] ctx,bool[] inElse,Div dv){
bool rb=false;
auto rootInfo=analyzeStm(root,rb);
// within a single simple statement, subexpressions are evaluated before any variable is updated
bool simple=true;
walkShallow(root,(Expression x){
if(cast(CompoundExp)x||cast(IteExp)x||isLoopStatement(x)||cast(WithExp)x) simple=false;
});
SetX!Expression covered;
walkShallow(root,(Expression x){
if(x in covered) return;
auto ce=cast(CallExp)x;
if(!ce||!ce.type||!ce.type.isClassical()) return;
auto ft=cast(FunTy)ce.e.type;
if(!ft||ft.isSquare||ft.annotation>=Annotation.qfree) return;
bool ok=true;
walkShallow(ce,(Expression y){
covered.insert(y);
if(auto id=cast(Identifier)y) if(id.type&&!id.type.isClassical()&&!cast(FunctionDef)id.meaning){
if(!simple&&(id.constLookup||id.implicitDup)&&vname(id) in rootInfo.defs) ok=false;
}
if(cast(LambdaExp)y||cast(FunctionDef)y) ok=false;
});
if(!ok) return;
auto fresh=freshName();
auto fid=new Identifier(fresh);
fid.loc=ce.loc;
fid.constLookup=false;
auto w=new DefineExp(fid,ce);
w.loc=ce.loc;
bool b2=false;
auto wi=analyzeStm(w,b2);
wi.types[fresh]=ce.type;
synthInfo[cast(const(void)*)w]=wi;
extracted[cast(const(void)*)ce]=fresh;
reanalyze[cast(const(void)*)root]=true;
isExtractAtom[cast(const(void)*)w]=true;
atoms~=Atom(w,i,ctx,inElse,[ce],dv);
});
}
bool[size_t] isPseudo;
Id[size_t] condVars;
SetX!Id isCondVar;
Id condVar(size_t k){
if(auto r=k in condVars) return *r;
auto n=freshName();
condVars[k]=n;
isCondVar.insert(n);
return n;
}
void flatten(Expression e,size_t i,size_t[] ctx,bool[] inElse,Div dv){ // (`dv`: the path after `e`)
if(auto fe=cast(ForgetExp)e) if(!fe.val&&fe.var.type&&fe.var.type.isClassical()) return; // (the split loops forget classical variables where needed)
if(auto ite=cast(IteExp)e){
bool b=false;
auto info=analyzeStm(ite.cond,b);
bad|=b;
if(info.nonQfree&&ite.cond.type&&ite.cond.type.isClassical()){
extractFrom(ite.cond,i,ctx,inElse,including(dv,e));
info=analyzeStm(ite.cond,b);
}
if(!info.strong.length){
foreach(u;info.consumed){
info.defs.remove(u);
info.nonConst.remove(u);
}
info.consumed=typeof(info.consumed).init;
}
if(!info.defs.length){
auto k=ites.length;
ites~=Ite(ite,i,info,ctx,atoms.length,false,[ite.cond]);
auto before=atoms.length;
void branch(CompoundExp b,bool isElse){
auto list=blockStms(b.s,false);
foreach(j,dj;divsOf(list,dv)) flatten(list[j],i,ctx~k,inElse~isElse,dj);
}
branch(ite.then,false);
if(ite.othw) branch(ite.othw,true);
if(atoms.length!=before) return;
ites=ites[0..k];
}
}
if(auto we=cast(WithExp)e) if(!we.isIndices){
auto k=ites.length;
auto p=atoms.length;
atoms~=Atom(we.trans,i,ctx,inElse,[we.trans],including(dv,e));
auto it=Ite(we,i,StmInfo.init,ctx,p,false,[]);
it.isWith=true;
it.pseudo=p;
ites~=it;
auto list=blockStms(we.bdy.s,false);
foreach(j,dj;divsOf(list,including(dv,e))) flatten(list[j],i,ctx~k,inElse~false,dj);
if(atoms.length!=p+1){
isPseudo[p]=true;
return;
}
ites=ites[0..k];
atoms=atoms[0..p];
}
Expression[] heads;
CompoundExp lbdy;
if(auto fe=cast(ForExp)e){
if(auto r=fe.aggr.isRange) if(fe.loopVar){
heads=[r.left]~(r.step?[r.step]:[])~[r.right];
lbdy=fe.bdy;
}
}else if(auto re=cast(RepeatExp)e){
heads=[re.num];
lbdy=re.bdy;
}else if(auto we=cast(WhileExp)e){
heads=[we.cond];
lbdy=we.bdy;
}
if(lbdy){
StmInfo info;
if(!cast(WhileExp)e) foreach(h;heads){
bool b=false;
auto hi=analyzeStm(h,b);
if(hi.nonQfree&&h.type&&h.type.isClassical()) extractFrom(h,i,ctx,inElse,including(dv,e));
}
foreach(h;heads){
bool b=false;
auto hi=analyzeStm(h,b);
bad|=b;
foreach(u;hi.uses) info.uses.insert(u);
foreach(u;hi.defs) info.defs.insert(u);
foreach(u;hi.nonConst) info.nonConst.insert(u);
foreach(u,t;hi.types) info.types[u]=t;
info.nonQfree|=hi.nonQfree;
info.effects|=hi.effects;
}
if(!info.defs.length){
auto k=ites.length;
ites~=Ite(e,i,info,ctx,atoms.length,true,heads);
auto before=atoms.length;
auto list=blockStms(lbdy.s,true);
foreach(j,dj;divsOf(list,Div.init)) flatten(list[j],i,ctx~k,inElse~false,dj); // (a nested loop continues with its next iteration)
if(atoms.length!=before) return;
ites=ites[0..k];
}
}
if(auto ce=cast(CompoundExp)e) if(!ce.blscope_){
foreach(j,dj;divsOf(ce.s,dv)) flatten(ce.s[j],i,ctx,inElse,dj);
return;
}
if(auto de=cast(DefineExp)e) if(splitTuple(de)){
auto lhs=cast(TupleExp)de.e1, rhs=cast(TupleExp)de.e2;
foreach(k;0..lhs.e.length){
auto w=new DefineExp(lhs.e[k],rhs.e[k]);
w.loc=de.loc;
atoms~=Atom(w,i,ctx,inElse,[lhs.e[k],rhs.e[k]],including(dv,e));
}
return;
}
{
bool b=false;
auto inf=analyzeStm(e,b);
bool qdef=false;
foreach(d;inf.defs){
if(d in isCarried&&d !in classical) qdef=true;
if(auto t=inf.types.get(d,null)) if(!t.isClassical()) qdef=true;
}
if(inf.nonQfree&&qdef){
extractFrom(e,i,ctx,inElse,including(dv,e));
}
}
atoms~=Atom(e,i,ctx,inElse,[e],including(dv,e));
}
foreach(i,dv;divsOf(stms,Div.init)) flatten(stms[i],i,[],[],dv);
if(bad) return null;
StmInfo[] ainfos;
foreach(ref a;atoms){
bool b=false;
auto info=a.e is stms[a.stm]&&cast(const(void)*)a.e !in reanalyze?infos[a.stm]:cast(const(void)*)a.e in synthInfo?synthInfo[cast(const(void)*)a.e]:analyzeStm(a.e,b);
if(b) return null;
foreach(k;a.ites){
auto ci=&ites[k].info;
foreach(u;ci.uses) info.uses.insert(u);
foreach(u;ci.nonConst) info.nonConst.insert(u);
foreach(u,t;ci.types) info.types[u]=t;
if(ci.nonQfree) info.uses.insert(condVar(k));
info.effects|=ci.effects;
}
ainfos~=info;
}
MapX!(Id,Expression)[] prevTypes; // (the types of the versions that fresh definitions replace, see the forgets of classical variables below)
foreach(a,ref info;ainfos){
bool exclusive(size_t b){ // (in another branch of an enclosing `if`)
foreach(j;0..min(atoms[a].ites.length,atoms[b].ites.length)){
if(atoms[a].ites[j]!=atoms[b].ites[j]) return false;
if(atoms[a].inElse[j]!=atoms[b].inElse[j]) return true;
}
return false;
}
MapX!(Id,Expression) pt;
foreach(d;info.fresh){
Expression t=null;
foreach_reverse(b;0..a) if(d in ainfos[b].defs&&!exclusive(b)) if((t=ainfos[b].types.get(d,null))!is null) break;
if(!t) t=carriedType.get(d,null);
if(t) pt[d]=t;
}
prevTypes~=pt;
}
// (the split loops forget a classical variable right before its fresh definition, see below: not if a statement before
// changes a variable that its type mentions, e.g., `m` in `forget(x); m+=1; x:=vector(1,0:!𝔹);` with `x:!𝔹^m`)
foreach(a,ref info;ainfos) foreach(d;info.fresh){
Expression[] types;
if(auto t=prevTypes[a].get(d,null)) types~=t;
if(d in isCarried) if(auto t=state.origStateSnapshot.typeOfName(d)) types~=t;
SetX!Id mentioned;
foreach(t;types) if(t.isClassical()) foreach(id;t.freeIdentifiers) mentioned.insert(varName(id));
if(!mentioned.length) continue;
foreach_reverse(b;0..a){
if(d in ainfos[b].uses||d in ainfos[b].defs) break;
foreach(m;ainfos[b].defs) if(m in mentioned) return null;
}
}
bool quantumIte(size_t j){
if(ites[j].isLoop||ites[j].isWith) return false;
auto c=ites[j].heads[0];
return !(c.type&&c.type.isClassical());
}
void refreshCtl(){
foreach(k,ref it;ites){
size_t f=size_t.max;
size_t[] ctx;
foreach(ai,ref at;atoms){
auto x=at.ites.countUntil(k);
if(x<0) continue;
if(f==size_t.max){
f=ai;
ctx=at.ites[0..x];
}else ctx=ctx[0..commonPrefix(ctx,at.ites[0..x]).length]; // (the controls moved into loops differ between atoms)
}
if(f==size_t.max) continue;
if(!it.isWith) it.first=f;
it.ctx=ctx;
}
}
// whether an atom within the quantum conditional `k` changes a variable that its condition reads (e.g., lifted state
// that the branch updates): then `k` cannot be split into several conditionals, as they would evaluate the condition again
bool conditionChanged(size_t k){
foreach(ai,ref at;atoms) if(at.ites.canFind(k)) foreach(u;ites[k].info.uses) if(u in ainfos[ai].defs) return true;
return false;
}
size_t[size_t] hoistedFrom; // (the outermost quantum conditional that `hoistLocal` moved an atom out of)
bool hoistLocal(size_t q,Id t){
if(t in isCarried) return false;
size_t occ=0;
walkCond(ites[q].e,false,(Expression x,bool c){
if(auto id=cast(Identifier)x) if(vname(id)==t) occ++;
});
if(occ!=totalOcc.get(t,0)) return false;
size_t[] defs;
foreach(ai,ref at;atoms) if(at.ites.canFind(q)&&t in ainfos[ai].defs) defs~=ai;
if(!defs.length) return false;
foreach(ai;defs){
auto inf=&ainfos[ai];
if(inf.nonQfree||inf.effects||ai in isPseudo) return false;
if(!cannotFail(atoms[ai].e)) return false; // (executed also where the original skips the branch)
foreach(d;inf.defs) if(d!=t) return false;
foreach(u;inf.uses){
if(u==t||u in isCarried) continue;
foreach(bj,ref b;atoms) if(b.ites.canFind(q)&&u in ainfos[bj].defs) return false;
}
auto c=atoms[ai].ites;
if(c[c.countUntil(q)..$].any!(k=>ites[k].isLoop)) return false; // (a definition within a loop of the conditional moves only with the loop)
// (moving the definition out of the middle of a conditional would split it into several conditionals)
foreach(k;c[c.countUntil(q)..$]){
if(!quantumIte(k)) continue;
bool before=false,after=false;
foreach(bj,ref b;atoms){
if(defs.canFind(bj)||!b.ites.canFind(k)) continue;
if(bj<ai) before=true;
else after=true;
}
if(before&&after) return false;
}
}
foreach(ai;defs){
auto c=atoms[ai].ites;
auto x=c.countUntil(q);
size_t[] nc;
bool[] ne;
foreach(y,k;c){
if(y>=x&&quantumIte(k)) continue;
nc~=k;
ne~=atoms[ai].inElse[y];
}
atoms[ai].ites=nc;