/
CommonSubExpression.mo
2450 lines (2198 loc) · 95.9 KB
/
CommonSubExpression.mo
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 file is part of OpenModelica.
*
* Copyright (c) 1998-2014, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
encapsulated package CommonSubExpression
" file: CommonSubExpression.mo
package: CommonSubExpression
description: This package contains functions for the optimization modules
wrapFunctionCalls, commonSubExpressionReplacement and cseBinary."
public
import BackendDAE;
import DAE;
protected
import Array;
import AvlSetInt;
import BackendDAEUtil;
import BackendDump;
import BackendEquation;
import BackendVarTransform;
import BackendVariable;
import BaseHashTable;
import ComponentReference;
import DAEUtil;
import ExpandableArray;
import Expression;
import ExpressionDump;
import ExpressionSolve;
import ExpressionSimplify;
import GC;
import Global;
import HashSet;
import HashTableExpToExp;
import HashTableExpToIndex;
import HpcOmTaskGraph;
import List;
import ResolveLoops;
import Types;
uniontype CSE_Equation
record CSE_EQUATION
DAE.Exp cse "lhs";
DAE.Exp call "rhs";
list<Integer> dependencies;
end CSE_EQUATION;
end CSE_Equation;
constant CSE_Equation dummy_equation = CSE_EQUATION(DAE.RCONST(0.0), DAE.RCONST(0.0), {});
constant Boolean debug = false;
constant String BORDER = "###############################################################";
constant String UNDERLINE = "========================================";
protected function printCSEEquation
input CSE_Equation cseEquation;
output String str;
protected
Boolean first = true;
algorithm
str := ExpressionDump.printExpStr(cseEquation.cse) + " - " + ExpressionDump.printExpStr(cseEquation.call) + " - {";
for i in cseEquation.dependencies loop
if first then
str := str + intString(i);
first := false;
else
str := str + ", " + intString(i);
end if;
end for;
str := str + "}";
end printCSEEquation;
public function wrapFunctionCalls "
This function traverses the equation systems and looks for function calls to store in $cse variables.
This avoids unnecessary function evaluations.
Main function: is called by postOpt and SymbolicJacobian
authors: Jan Hagemann, Lennart Ochel and Patrick Täuber (FH Bielefeld, Germany)"
input BackendDAE.BackendDAE inDAE;
output BackendDAE.BackendDAE outDAE;
protected
Integer size;
HashTableExpToIndex.HashTable HT "call -> index";
ExpandableArray<CSE_Equation> exarray "id -> (cse, call, dependencies)";
Integer cseIndex = System.tmpTickIndex(Global.backendDAE_cseIndex);
Integer index;
BackendDAE.Shared shared;
DAE.FunctionTree functionTree;
BackendDAE.EquationArray orderedEqs, orderedEqs_new;
BackendDAE.Variables orderedVars, globalKnownVars;
list<BackendDAE.EqSystem> eqSystems = {};
list<BackendDAE.Var> varList;
String daeTypeStr = BackendDump.printBackendDAEType2String(inDAE.shared.backendDAEType);
Boolean isSimulationDAE = stringEq(daeTypeStr, "simulation");
HashSet.HashSet globalKnownVarHT;
DAE.Exp cse, call;
list<Integer> dependencies;
algorithm
size := BackendDAEUtil.maxSizeOfEqSystems(inDAE.eqs) + 42; //create data structures independent from the size of the EqSystem
exarray := ExpandableArray.new(size, dummy_equation);
size := Util.nextPrime(realInt(2.4*size));
HT := HashTableExpToIndex.emptyHashTableSized(size);
shared := inDAE.shared;
BackendDAE.SHARED(globalKnownVars=globalKnownVars,functionTree=functionTree) := shared;
// Create Hashtable and store globally known variables in it
globalKnownVarHT := HashSet.emptyHashSetSized(Util.nextPrime(realInt(2.4*(globalKnownVars.numberOfVars + 42))));
if isSimulationDAE then
globalKnownVarHT := BackendVariable.traverseBackendDAEVars(globalKnownVars, VarToGlobalKnownVarHT, globalKnownVarHT);
end if;
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
print("Start optimization module wrapFunctionCalls for " + daeTypeStr + " DAE\n" + BORDER + BORDER + "\n\n\n");
print("Phase 0: Set up data structure\n" + BORDER + "\n");
BackendDump.dumpVariables(globalKnownVars, "globalKnownVars before WFC");
print("globalKnownVarHT before algorithm\n" + UNDERLINE + "\n");
BaseHashSet.dumpHashSet(globalKnownVarHT);
end if;
// Start the WFC algorithm for all equation systems
for syst in inDAE.eqs loop
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
print("\n\nHandle system (belongs to " + daeTypeStr + " DAE):\n" + BORDER + "\n");
BackendDump.dumpVariables(syst.orderedVars, "Variables");
BackendDump.dumpEquationArray(syst.orderedEqs, "Equations");
print("\nPhase 1: Analysis\n" + BORDER + "\n");
end if;
HT := BaseHashTable.clear(HT);
exarray := ExpandableArray.clear(exarray);
index := 0;
orderedEqs := syst.orderedEqs;
orderedVars := syst.orderedVars;
// Phase 1: Analysis
(HT, exarray, cseIndex, index, _) := BackendEquation.traverseEquationArray(orderedEqs, wrapFunctionCalls_analysis, (HT, exarray, cseIndex, index, functionTree));
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
print("Hastable after analysis\n" + UNDERLINE + "\n");
BaseHashTable.dumpHashTable(HT);
ExpandableArray.dump(exarray, "\nExpandable Array after analysis", printCSEEquation);
end if;
if index > 0 then
// Phase 2: Dependencies
exarray := determineDependencies(exarray, HT);
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
print("\n\nPhase 2: Dependencies\n" + BORDER + "\n\n");
print("Hashtable after dependencies\n" + UNDERLINE + "\n");
BaseHashTable.dumpHashTable(HT);
ExpandableArray.dump(exarray, "\nExpandable Array after dependencies", printCSEEquation);
print("\n\nPhase3: Substitution\n" + BORDER + "\n");
end if;
// Phase 3: Substitution
orderedEqs_new := BackendEquation.emptyEqnsSized(ExpandableArray.getNumberOfElements(orderedEqs) + ExpandableArray.getNumberOfElements(exarray));
(HT, exarray, orderedEqs_new) := BackendEquation.traverseEquationArray(orderedEqs, wrapFunctionCalls_substitution, (HT, exarray, orderedEqs_new));
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
print("Hashtable after substitution\n" + UNDERLINE + "\n");
BaseHashTable.dumpHashTable(HT);
ExpandableArray.dump(exarray, "\nExpandable Array after substitution", printCSEEquation);
print("\n\nPhase 4: Create CSE-Equations\n" + BORDER + "\n\n");
end if;
// Phase 4: Create CSE equations
(orderedEqs_new, orderedVars, globalKnownVars) := createCseEquations(exarray, orderedEqs_new, orderedVars, globalKnownVars, globalKnownVarHT);
syst.orderedEqs := orderedEqs_new;
syst.orderedVars := orderedVars;
// Check for unbalanced system
if not intEq(BackendEquation.equationArraySize(orderedEqs_new), orderedVars.numberOfVars) then
Error.addCompilerWarning("After manipulating the system with postOptModule wrapFunctionCalls the system is unbalanced. This indicates that the original system is singular. You can use -d=dumpCSE and -d=dumpCSE_verbose for more information.");
end if;
// Reset Matching
syst.m := NONE();
syst.mT := NONE();
syst.matching := BackendDAE.NO_MATCHING();
if Flags.isSet(Flags.DUMP_CSE) or Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
print("\n\n\n" + BORDER + "\nFinal Results\n" + BORDER + "\n");
BackendDump.dumpVariables(syst.orderedVars, "########### Updated Variable List (" + BackendDump.printBackendDAEType2String(shared.backendDAEType) + ")");
BackendDump.dumpEquationArray(syst.orderedEqs, "########### Updated Equation List (" + BackendDump.printBackendDAEType2String(shared.backendDAEType) + ")");
BackendDump.dumpVariables(globalKnownVars, "########### Updated globalKnownVars (" + BackendDump.printBackendDAEType2String(shared.backendDAEType) + ")");
ExpandableArray.dump(exarray, "\n########### CSE Replacements", printCSEEquation);
end if;
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
print("\n\n" + BORDER);
BackendDump.dumpEqSystem(syst, "Final EqSystem");
end if;
else
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
print("\n" + BORDER + "\nNo function calls found. Exiting the algorithm...\n\n\n");
end if;
end if;
eqSystems := syst::eqSystems;
end for;
shared.globalKnownVars := globalKnownVars;
System.tmpTickSetIndex(cseIndex, Global.backendDAE_cseIndex);
eqSystems := MetaModelica.Dangerous.listReverseInPlace(eqSystems);
outDAE := BackendDAE.DAE(eqSystems, shared);
end wrapFunctionCalls;
protected function VarToGlobalKnownVarHT
" Adds all globalKnownVars with bindExp to globalKnownVarHT except inputs and nonfixed parameters"
input BackendDAE.Var inVar;
input HashSet.HashSet inGlobalKnownVarHT;
output BackendDAE.Var outVar = inVar;
output HashSet.HashSet outGlobalKnownVarHT = inGlobalKnownVarHT;
algorithm
// To-Do: Move inputs to localKnownVars
if not BackendVariable.isInput(inVar) and not (BackendVariable.isParam(inVar) and not BackendVariable.varFixed(inVar)) and isSome(inVar.bindExp) then
outGlobalKnownVarHT := BaseHashSet.add(BackendVariable.varCref(inVar), inGlobalKnownVarHT);
end if;
end VarToGlobalKnownVarHT;
protected function findCallsInGlobalKnownVars
"This function traverses the globalKnownVars and looks for function calls. The calls are stored in the HT/expArray"
input BackendDAE.Var inVar;
input tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, Integer, Integer, DAE.FunctionTree> inTuple;
output BackendDAE.Var outVar = inVar;
output tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, Integer, Integer, DAE.FunctionTree> outTuple = inTuple;
protected
DAE.Exp exp;
BackendDAE.Equation eq;
algorithm
// To-Do: Move inputs to localKnownVars
if not BackendVariable.isInput(inVar) and not (BackendVariable.isParam(inVar) and not BackendVariable.varFixed(inVar)) and isSome(inVar.bindExp) then
SOME(exp):= inVar.bindExp;
if isCall(exp) then
eq := BackendEquation.generateEquation(DAE.CREF(inVar.varName, inVar.varType), exp);
(_, outTuple) := wrapFunctionCalls_analysis(eq, inTuple);
end if;
end if;
end findCallsInGlobalKnownVars;
protected function wrapFunctionCalls_substitution
"Third phase of the WFC algorithm: The found function calls in the equation system which are stored in the HT are replaced by its cse-variables."
input BackendDAE.Equation inEq;
input tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, BackendDAE.EquationArray> inTuple;
output BackendDAE.Equation outEq = inEq;
output tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, BackendDAE.EquationArray> outTuple;
protected
HashTableExpToIndex.HashTable HT;
ExpandableArray<CSE_Equation> exarray;
BackendDAE.EquationArray orderedEqs_new;
BackendDAE.Equation eq;
algorithm
(HT, exarray, orderedEqs_new) := inTuple;
_ := match(inEq)
case BackendDAE.COMPLEX_EQUATION() equation
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
BackendDump.dumpEquationList({inEq}, "wrapFunctionCalls_substitution (COMPLEX_EQUATION)");
end if;
(eq, (HT, exarray, orderedEqs_new)) = BackendEquation.traverseExpsOfEquation(inEq, wrapFunctionCalls_substitution2, (HT, exarray, orderedEqs_new));
if not isEquationRedundant(eq) then
orderedEqs_new = BackendEquation.add(eq, orderedEqs_new);
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
BackendDump.dumpEquationList({eq}, "isEquationRedundant? no");
end if;
else
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
BackendDump.dumpEquationList({eq}, "isEquationRedundant? yes");
end if;
end if;
then ();
case BackendDAE.EQUATION() equation
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
BackendDump.dumpEquationList({inEq}, "wrapFunctionCalls_substitution (EQUATION)");
end if;
(eq, (HT, exarray, orderedEqs_new)) = BackendEquation.traverseExpsOfEquation(inEq, wrapFunctionCalls_substitution2, (HT, exarray, orderedEqs_new));
if not isEquationRedundant(eq) then
orderedEqs_new = BackendEquation.add(eq, orderedEqs_new);
end if;
then ();
// all other cases are not handled (e.g. algorithms)
else equation
orderedEqs_new = BackendEquation.add(inEq, orderedEqs_new);
then ();
end match;
outTuple := (HT, exarray, orderedEqs_new);
end wrapFunctionCalls_substitution;
protected function wrapFunctionCalls_substitution2
input DAE.Exp inExp;
input tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, BackendDAE.EquationArray> inTuple;
output DAE.Exp outExp;
output tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, BackendDAE.EquationArray> outTuple;
algorithm
(outExp, outTuple) := Expression.traverseExpBottomUp(inExp, wrapFunctionCalls_substitution3, inTuple);
end wrapFunctionCalls_substitution2;
protected function wrapFunctionCalls_substitution3
input DAE.Exp inExp;
input tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, BackendDAE.EquationArray> inTuple;
output DAE.Exp outExp;
output tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, BackendDAE.EquationArray> outTuple;
protected
HashTableExpToIndex.HashTable HT;
ExpandableArray<CSE_Equation> exarray;
BackendDAE.EquationArray orderedEqs_new;
Integer id, ix;
DAE.Exp cse, call, tmp;
list<DAE.Exp> PR;
list<Integer> dependencies;
algorithm
(HT, exarray, orderedEqs_new) := inTuple;
if Expression.isCall(inExp) and BaseHashTable.hasKey(inExp, HT) then
id := BaseHashTable.get(inExp, HT);
CSE_EQUATION(cse=cse, call=call, dependencies=dependencies) := ExpandableArray.get(id, exarray);
(HT, exarray) := substituteDependencies(dependencies, HT, exarray, call, cse);
ExpandableArray.update(id, CSE_EQUATION(cse, call, {}), exarray);
outExp := cse;
elseif Expression.isTSUB(inExp) then
DAE.TSUB(exp=tmp, ix=ix) := inExp;
if Expression.isTuple(tmp) then
DAE.TUPLE(PR) := tmp;
outExp := listGet(PR, ix);
else
outExp := inExp;
end if;
else
outExp := inExp;
end if;
outTuple := (HT, exarray, orderedEqs_new);
end wrapFunctionCalls_substitution3;
protected function substituteDependencies
input list<Integer> inDependencies;
input output HashTableExpToIndex.HashTable ht;
input output ExpandableArray<CSE_Equation> exarray;
input DAE.Exp inCall;
input DAE.Exp inCSE;
protected
DAE.Exp cse, call;
list<Integer> dependencies;
DAE.Exp cse2, call2;
list<Integer> dependencies2;
Integer id2;
algorithm
for id in inDependencies loop
CSE_EQUATION(cse=cse, call=call, dependencies=dependencies) := ExpandableArray.get(id, exarray);
call := substituteExp(call, inCall, inCSE);
//ExpandableArray.dump(exarray, "substituteDependencies", printCSEEquation);
//print("Exp: " + ExpressionDump.printExpStr(call) + "\n");
if not BaseHashTable.hasKey(call, ht) then
ht := BaseHashTable.add((call, id), ht);
ExpandableArray.update(id, CSE_EQUATION(cse, call, dependencies), exarray);
else
id2 := BaseHashTable.get(call, ht);
CSE_EQUATION(cse=cse2, call=call2, dependencies=dependencies2) := ExpandableArray.get(id2, exarray);
cse2 := mergeCSETuples(cse, cse2);
ExpandableArray.update(id2, CSE_EQUATION(cse2, call, List.unique(listAppend(dependencies,dependencies2))), exarray);
ExpandableArray.update(id, CSE_EQUATION(cse, cse2, {}), exarray);
//print("substituteDependencies: not handled yet\n");
//print("id: " + intString(id) + "\n");
//print("inCall: " + ExpressionDump.printExpStr(inCall) + "\n");
//print("inCSE: " + ExpressionDump.printExpStr(inCSE) + "\n");
//BaseHashTable.dumpHashTable(ht);
//ExpandableArray.dump(exarray, "substituteDependencies", printCSEEquation);
end if;
end for;
end substituteDependencies;
protected function substituteExp
input DAE.Exp inExp;
input DAE.Exp inKey;
input DAE.Exp inValue;
output DAE.Exp outExp;
algorithm
outExp := Expression.traverseExpTopDown(inExp, substituteExp2, (inKey, inValue));
end substituteExp;
protected function substituteExp2
input DAE.Exp inExp;
input tuple<DAE.Exp, DAE.Exp> inTuple;
output DAE.Exp outExp;
output Boolean cont;
output tuple<DAE.Exp, DAE.Exp> outTuple = inTuple;
protected
DAE.Exp key, value, tmp;
list<DAE.Exp> expList;
Integer ix;
algorithm
(key, value) := inTuple;
if Expression.expEqual(inExp, key) then
outExp := value;
cont := false;
elseif Expression.isTSUB(inExp) then
DAE.TSUB(exp=tmp, ix=ix) := inExp;
if Expression.expEqual(tmp, key) then
DAE.TUPLE(expList) := value;
outExp := listGet(expList, ix);
cont := false;
else
outExp := inExp;
cont := true;
end if;
else
outExp := inExp;
cont := true;
end if;
end substituteExp2;
protected function createCseEquations
" Fourth phase of the WFC algorithm:
Creates CSE equations from the expandable array and stores them in the correct data structure:
1) cse var (i.e. function call) with $cse-prefix is dependending on variables
-> store eqn in orderedEqs and var in orderedVars
2) cse var (i.e. function call) without $cse-prefix is dependending on variables
-> store eqn in orderedEqs
3) cse var (i.e. function call) with $cse-prefix is only dependending on globally known variables
-> store var in globalKnownVars (bindExp=call)
4) cse var (i.e. function call) without $cse-prefix is only dependending on globally known variables
-> store var in globalKnownVars (bindExp=call) and delete var from orderedVars
author: ptaeuber"
input ExpandableArray<CSE_Equation> exarray "id -> (cse, call, dependencies)";
input output BackendDAE.EquationArray orderedEqs "equations of the system";
input output BackendDAE.Variables orderedVars;
input output BackendDAE.Variables globalKnownVars;
input output HashSet.HashSet globalKnownVarHT;
protected
DAE.Exp cse, call;
list<DAE.Exp> callArg;
BackendDAE.Equation eq;
list<DAE.ComponentRef> crefList;
DAE.ComponentRef cr;
BackendDAE.Var var;
list<BackendDAE.Var> varList, delVars;
Boolean isGlobalKnown, eqRedundant, add;
list<Integer> var_indexes;
algorithm
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
print("globalKnownVars:\n" + UNDERLINE + "\n");
BaseHashSet.dumpHashSet(globalKnownVarHT);
print("\nTraverse expandable array\n" + UNDERLINE + "\n");
end if;
for i in ExpandableArray.getNumberOfElements(exarray):-1:1 loop
add := true;
CSE_EQUATION(cse=cse, call=call) := ExpandableArray.get(i, exarray);
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
print("\n--> cse-equation: " + ExpressionDump.printExpStr(cse) + " = " + ExpressionDump.printExpStr(call) + "\n");
end if;
eq := BackendEquation.generateEquation(cse, call);
(globalKnownVarHT, globalKnownVars, orderedVars, eqRedundant, isGlobalKnown) := isEquationRedundant_flatten(eq, globalKnownVarHT, globalKnownVars, orderedVars);
if debug then print("\ndebug 1 - eq redundant?\n"); end if;
if not eqRedundant then
if debug then print("\ndebug 2 - no, not redundant. let's loop\n"); end if;
varList := createVarsForExp(cse);
// If cse is a constant number add the equation
if listEmpty(varList) then
orderedEqs := BackendEquation.add(eq, orderedEqs);
else
for var in varList loop
if debug then print("\ndebug 3 - handle var: " + BackendDump.varString(var) + " Is it a globalKnownVar?\n"); end if;
cr := BackendVariable.varCref(var);
// Variable is not in globalKnownVars HT
if not isGlobalKnown then
if debug then print("\ndebug 4 - The variable is not a globalKnownVar. Should an equation be added?\n"); end if;
if add then
if debug then print("\ndebug 5 - yes, definitely!\n"); end if;
orderedEqs := BackendEquation.add(eq, orderedEqs);
add := false;
end if;
if debug then print("\ndebug 6 - Is this cref a CSE cref?: " + ExpressionDump.printExpStr(Expression.crefExp(cr)) + "\n"); end if;
if isCSECref(cr) then
if debug then print("\ndebug 7 - yes it is a CSE cref. Add to orderedVars!\n"); end if;
orderedVars := BackendVariable.addVar(var, orderedVars);
end if;
if debug then print("\ndebug 8\n"); end if;
// Variable is in globalKnownVars HT: Add it to globalKnownVars and not to ordered vars and do not create a cse-equation
else
if debug then print("\ndebug 9 - The variable is a globalKnownVar.\n"); end if;
if not isCSECref(cr) then
if debug then print("\ndebug 10 - The globalKnownVar is no CSE cref, so copy attributes and delete it from orderedVars if it is in that list.\n"); end if;
(delVars, orderedVars) := BackendVariable.deleteVarIfExistsAndReturn(cr, orderedVars);
if listEmpty(delVars) then
(delVars, _) := BackendVariable.getVar(cr, globalKnownVars);
end if;
var := listGet(delVars, 1);
end if;
// Save the rhs (call) as bind expression and set fixed=true
var := BackendVariable.setBindExp(var, SOME(call));
var := BackendVariable.setVarFixed(var, true);
// If it is a tuple or a record (or record within tuple)
if intGt(listLength(varList), 1) or Expression.isTuple(cse) then
if debug then print("\ndebug 11 - It is a tuple! Add it to tplExp\n"); end if;
var.tplExp := SOME(cse);
end if;
if debug then print("\ndebug 12 - Add the variable to globalKnownVars\n"); end if;
// Add var to globalKnownVars
globalKnownVars := BackendVariable.addVar(var, globalKnownVars);
end if;
end for;
end if;
end if;
end for;
if debug then print("\ndebug 13\n"); end if;
end createCseEquations;
protected function determineDependencies
"Second phase of the WFC algorithm: Finds the dependencies between nested function calls and stores them in the expandable array."
input output ExpandableArray<CSE_Equation> exarray "id -> (cse, call, dependencies)";
input HashTableExpToIndex.HashTable HT "call -> index";
protected
list<DAE.Exp> callArguments;
algorithm
for i in 1:ExpandableArray.getNumberOfElements(exarray) loop
CSE_EQUATION(call=DAE.CALL(expLst=callArguments)) := ExpandableArray.get(i, exarray);
(_, (_, exarray, _)) := Expression.traverseExpList(callArguments, determineDependencies2, (HT, exarray, i));
end for;
end determineDependencies;
protected function determineDependencies2
input DAE.Exp inExp;
input tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, Integer> inTuple;
output DAE.Exp outExp = inExp;
output tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, Integer> outTuple;
protected
Integer id, index;
list<Integer> dependencies;
HashTableExpToIndex.HashTable HT;
ExpandableArray<CSE_Equation> exarray;
DAE.Exp cse, call;
algorithm
if Expression.isCall(inExp) then
(HT, exarray, index) := inTuple;
if BaseHashTable.hasKey(inExp, HT) then
id := BaseHashTable.get(inExp, HT);
CSE_EQUATION(cse=cse, call=call, dependencies=dependencies) := ExpandableArray.get(id, exarray);
if not listMember(index, dependencies) then
dependencies := index::dependencies;
ExpandableArray.update(id, CSE_EQUATION(cse, call, dependencies), exarray);
end if;
end if;
outTuple := (HT, exarray, index);
else
outTuple := inTuple;
end if;
end determineDependencies2;
protected function allArgsInGlobalKnownVars
"Returns true if all call arguments are globally known"
input list<DAE.Exp> callArgs;
input HashSet.HashSet globalKnownVarHT;
output Boolean allCrefsAreGlobal = true;
protected
list<DAE.ComponentRef> crefList;
algorithm
(_,crefList) := Expression.traverseExpList(callArgs, Expression.traversingComponentRefFinder, {});
for cr in crefList loop
if allCrefsAreGlobal then
allCrefsAreGlobal := BaseHashSet.has(cr, globalKnownVarHT);
else
return;
end if;
end for;
end allArgsInGlobalKnownVars;
protected function addConstantCseVarsToGlobalKnownVarHT
"Adds the cse variable to the globalKnownVarHT. For tuples the crefs are stored separately.
author: ptaeuber"
input DAE.Exp cse_crExp;
input output HashSet.HashSet globalKnownVarHT;
algorithm
_ := match(cse_crExp)
local
list<DAE.Exp> expLst;
DAE.ComponentRef cr;
list<DAE.ComponentRef> crefs;
case(DAE.TUPLE(PR = expLst))
algorithm
for exp in expLst loop
if Expression.isNotWild(exp) then
globalKnownVarHT := addConstantCseVarsToGlobalKnownVarHT(exp, globalKnownVarHT);
end if;
end for;
then ();
case DAE.CREF(componentRef=cr, ty = DAE.T_COMPLEX(complexClassType=ClassInf.RECORD(_)))
algorithm
globalKnownVarHT := BaseHashSet.add(cr, globalKnownVarHT);
crefs := ComponentReference.expandCref(cr, true /*the way it is now we won't get records here. but if we do somehow expand them*/);
for cr_ in crefs loop
globalKnownVarHT := BaseHashSet.add(cr_, globalKnownVarHT);
end for;
then ();
case DAE.CREF(componentRef=cr) guard(Expression.isArrayType(Expression.typeof(cse_crExp)))
algorithm
globalKnownVarHT := BaseHashSet.add(cr, globalKnownVarHT);
crefs := ComponentReference.expandCref(cr, true);
for cr_ in crefs loop
globalKnownVarHT := BaseHashSet.add(cr_, globalKnownVarHT);
end for;
then ();
case(DAE.CREF(componentRef=cr))
algorithm
globalKnownVarHT := BaseHashSet.add(cr, globalKnownVarHT);
then ();
end match;
end addConstantCseVarsToGlobalKnownVarHT;
protected function wrapFunctionCalls_analysis
"First phase of the WFC algorithm: The equation system is traversed and all occuring function calls are stored in the HT and the expandable array."
input BackendDAE.Equation inEq;
input tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, Integer, Integer, DAE.FunctionTree> inTuple;
output BackendDAE.Equation outEq = inEq;
output tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, Integer, Integer, DAE.FunctionTree> outTuple;
protected
DAE.FunctionTree functionTree;
HashTableExpToIndex.HashTable HT;
ExpandableArray<CSE_Equation> exarray;
Integer cseIndex, exIndex, index, ix;
DAE.Exp lhs, rhs;
DAE.Exp cref, call;
DAE.Exp exp;
list<DAE.Exp> expLst;
DAE.Type ty;
list<DAE.Type> types;
CSE_Equation cseEquation;
Boolean allCrefsAreGlobal = true;
list<DAE.ComponentRef> crefList;
list<BackendDAE.Var> varList;
algorithm
(HT, exarray, cseIndex, index, functionTree) := inTuple;
_ := match(inEq)
case BackendDAE.COMPLEX_EQUATION(left=lhs, right=rhs) algorithm
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
BackendDump.dumpEquationList({inEq}, "wrapFunctionCalls_analysis (COMPLEX_EQUATION)");
end if;
// TUPLE = CALL
// ************
if isCallAndTuple(lhs, rhs) then
(cref, call) := getTheRightPattern(lhs, rhs);
// Tuple is already in HT
if BaseHashTable.hasKey(call, HT) then
exIndex := BaseHashTable.get(call, HT);
cseEquation := ExpandableArray.get(exIndex, exarray);
cseEquation.cse := mergeCSETuples(cseEquation.cse, cref);
exarray := ExpandableArray.update(exIndex, cseEquation, exarray);
// Tuple is not already in HT
elseif not isSkipCase(call, functionTree) then
index := index + 1;
HT := BaseHashTable.add((call, index), HT);
exarray := ExpandableArray.set(index, CSE_EQUATION(cref, call, {}), exarray);
end if;
// RECORD = CALL
// *************
elseif isCallAndRecord(lhs, rhs) then
(cref, call) := getTheRightPattern(lhs, rhs);
if BaseHashTable.hasKey(call, HT) then
exIndex := BaseHashTable.get(call, HT);
cseEquation := ExpandableArray.get(exIndex, exarray);
cseEquation.cse := cref;
exarray := ExpandableArray.update(exIndex, cseEquation, exarray);
elseif not isSkipCase(call, functionTree) then
index := index + 1;
HT := BaseHashTable.add((call, index), HT);
exarray := ExpandableArray.set(index, CSE_EQUATION(cref, call, {}), exarray);
end if;
end if;
(_, (HT, exarray, cseIndex, index, functionTree)) := BackendEquation.traverseExpsOfEquation(inEq, wrapFunctionCalls_analysis2, (HT, exarray, cseIndex, index, functionTree));
then ();
case BackendDAE.EQUATION(exp=lhs, scalar=rhs) algorithm
if Flags.isSet(Flags.DUMP_CSE_VERBOSE) then
BackendDump.dumpEquationList({inEq}, "wrapFunctionCalls_analysis (EQUATION)");
end if;
// CREF = CALL or CONST = CALL
// ***************************
if isCallAndCref(lhs, rhs) or isConstAndCall(lhs, rhs) then
(cref, call) := getTheRightPattern(lhs, rhs);
if BaseHashTable.hasKey(call, HT) then
exIndex := BaseHashTable.get(call, HT);
cseEquation := ExpandableArray.get(exIndex, exarray);
cseEquation.cse := cref;
exarray := ExpandableArray.update(exIndex, cseEquation, exarray);
elseif not isSkipCase(call, functionTree) then
index := index + 1;
HT := BaseHashTable.add((call, index), HT);
exarray := ExpandableArray.set(index, CSE_EQUATION(cref, call, {}), exarray);
end if;
// CREF = TSUB
// ***********
elseif isTsubAndCref(lhs, rhs) then
(cref, DAE.TSUB(call as DAE.CALL(attr=DAE.CALL_ATTR(ty=DAE.T_TUPLE(types=types))),ix,_)) := getTheRightPattern(lhs, rhs);
if BaseHashTable.hasKey(call, HT) then
exIndex := BaseHashTable.get(call, HT);
cseEquation := ExpandableArray.get(exIndex, exarray);
cref := createCrefForTsub(listLength(types), ix, cref);
cseEquation.cse := mergeCSETuples(cseEquation.cse, cref);
exarray := ExpandableArray.update(exIndex, cseEquation, exarray);
elseif not isSkipCase(call, functionTree) then
index := index + 1;
HT := BaseHashTable.add((call, index), HT);
cref := createCrefForTsub(listLength(types), ix, cref);
exarray := ExpandableArray.set(index, CSE_EQUATION(cref, call, {}), exarray);
end if;
end if;
(_, (HT, exarray, cseIndex, index, functionTree)) := BackendEquation.traverseExpsOfEquation(inEq, wrapFunctionCalls_analysis2, (HT, exarray, cseIndex, index, functionTree));
then ();
// all other cases are not handled (e.g. algorithms)
else ();
end match;
outTuple := (HT, exarray, cseIndex, index, functionTree);
end wrapFunctionCalls_analysis;
protected function createCrefForTsub "(4, 2, x) -> TUPLE(_,x,_,_)"
input Integer length;
input Integer ix;
input DAE.Exp cref;
output DAE.Exp outCref;
protected
list<DAE.Exp> expList = {};
algorithm
for i in 1:ix-1 loop
expList := DAE.CREF(DAE.WILD(),DAE.T_UNKNOWN_DEFAULT)::expList;
end for;
expList := cref::expList;
for i in ix+1:length loop
expList := DAE.CREF(DAE.WILD(),DAE.T_UNKNOWN_DEFAULT)::expList;
end for;
outCref := DAE.TUPLE(listReverse(expList));
end createCrefForTsub;
protected function wrapFunctionCalls_analysis2
input DAE.Exp inExp;
input tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, Integer, Integer, DAE.FunctionTree> inTuple;
output DAE.Exp outExp = inExp;
output tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, Integer, Integer, DAE.FunctionTree> outTuple;
algorithm
(_, outTuple) := Expression.traverseExpTopDown(inExp, wrapFunctionCalls_analysis3, inTuple);
end wrapFunctionCalls_analysis2;
protected function wrapFunctionCalls_analysis3
input DAE.Exp inExp;
input tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, Integer, Integer, DAE.FunctionTree> inTuple;
output DAE.Exp outExp = inExp;
output Boolean cont;
output tuple<HashTableExpToIndex.HashTable, ExpandableArray<CSE_Equation>, Integer, Integer, DAE.FunctionTree> outTuple;
protected
DAE.FunctionTree functionTree;
HashTableExpToIndex.HashTable HT;
ExpandableArray<CSE_Equation> exarray;
Integer cseIndex, index;
list<DAE.ComponentRef> crefList;
DAE.Exp tsub;
algorithm
(HT, exarray, cseIndex, index, functionTree) := inTuple;
cont := match(inExp)
local
DAE.Exp cse_var, cse_var2, call, e;
DAE.Type ty;
list<DAE.Type> types;
Integer length, ix, id;
list<DAE.Exp> expList={}, expLst;
CSE_Equation cseEquation;
Boolean allCrefsAreGlobal = true;
DAE.ComponentRef cr;
case DAE.IFEXP()
then false;
// TODO: split up skip cases
case _
guard isSkipCase(inExp, functionTree)
then false;
case tsub as DAE.TSUB(exp=call as DAE.CALL(attr=DAE.CALL_ATTR(ty=DAE.T_TUPLE(types=types))), ix=ix, ty=ty) algorithm
if not BaseHashTable.hasKey(call, HT) then
index := index + 1;
HT := BaseHashTable.add((call, index), HT);
(cse_var, cseIndex) := createReturnExp(ty, cseIndex, inComplex=false);
cse_var2 := createCrefForTsub(listLength(types), ix, cse_var);
exarray := ExpandableArray.set(index, CSE_EQUATION(cse_var2, call, {}), exarray);
else
id := BaseHashTable.get(call, HT);
cseEquation := ExpandableArray.get(id, exarray);
if Expression.isTuple(cseEquation.cse) then
DAE.TUPLE(expList) := cseEquation.cse;
e := listGet(expList, ix);
if isWildCref(e) then
(cse_var, cseIndex) := createReturnExp(ty, cseIndex, inComplex=false);
expList := List.set(expList, ix, cse_var);
cseEquation.cse := DAE.TUPLE(expList);
exarray := ExpandableArray.update(id, cseEquation, exarray);
end if;
else
print("This should never appear\n");
end if;
end if;
then true;
case DAE.CALL(attr=DAE.CALL_ATTR(ty=ty)) algorithm
if not BaseHashTable.hasKey(inExp, HT) then
index := index + 1;
HT := BaseHashTable.add((inExp, index), HT);
(cse_var, cseIndex) := createReturnExp(ty, cseIndex, inComplex=false);
exarray := ExpandableArray.set(index, CSE_EQUATION(cse_var, inExp, {}), exarray);
end if;
then true;
else true;
end match;
outTuple := (HT, exarray, cseIndex, index, functionTree);
end wrapFunctionCalls_analysis3;
protected function getTheRightPattern
input DAE.Exp inExp1;
input DAE.Exp inExp2;
output DAE.Exp outExp1;
output DAE.Exp outExp2;
algorithm
(outExp1, outExp2) := match(inExp1, inExp2)
case (DAE.RCONST(), DAE.CALL()) then (inExp1, inExp2);
case (DAE.CALL(), DAE.RCONST()) then (inExp2, inExp1);
case (DAE.TUPLE(), DAE.CALL()) then (inExp1, inExp2);
case (DAE.CALL(), DAE.TUPLE()) then (inExp2, inExp1);
case (DAE.CREF(), DAE.CALL()) then (inExp1, inExp2);
case (DAE.CALL(), DAE.CREF()) then (inExp2, inExp1);
case (DAE.CREF(), DAE.TSUB()) then (inExp1, inExp2);
case (DAE.TSUB(), DAE.CREF()) then (inExp2, inExp1);
else fail();
end match;
end getTheRightPattern;
protected function isEquationRedundant
input BackendDAE.Equation inEq;
output Boolean outB "true if 'x=x', else false";
algorithm
outB := match(inEq)
local
DAE.Exp exp1, exp2;
list<DAE.Exp> lhs, rhs;
case BackendDAE.EQUATION(exp=exp1, scalar=exp2)
then Expression.expEqual(exp1, exp2);
case BackendDAE.EQUATION(exp=DAE.TUPLE(lhs), scalar=DAE.TUPLE(rhs)) guard (listLength(lhs) == listLength(rhs)) equation
print("This should never appear\n");
then isEquationRedundant2(lhs, rhs);
case BackendDAE.COMPLEX_EQUATION(left=DAE.TUPLE(lhs), right=DAE.TUPLE(rhs)) guard (listLength(lhs) == listLength(rhs))
then isEquationRedundant2(lhs, rhs);
case BackendDAE.COMPLEX_EQUATION(left = exp1 as DAE.CREF(ty = DAE.T_COMPLEX(complexClassType=ClassInf.RECORD(_))), right = exp2 as DAE.CREF(ty = DAE.T_COMPLEX(complexClassType=ClassInf.RECORD(_))))
then Expression.expEqual(exp1, exp2);
else false;
end match;
end isEquationRedundant;
protected function isEquationRedundant2
input list<DAE.Exp> lhs;
input list<DAE.Exp> rhs;
output Boolean result = true;
protected
DAE.Exp l, r;
list<DAE.Exp> ll, rr;
algorithm
if listEmpty(lhs) then
return;
end if;
l::ll := lhs;
r::rr := rhs;
if not isWildCref(l) and not isWildCref(r) then
//print(ExpressionDump.printExpStr(l) + " ?= " + ExpressionDump.printExpStr(r) + "\n");
if not Expression.expEqual(l, r) then
result := false;
return;
end if;
end if;
result := isEquationRedundant2(ll, rr);
end isEquationRedundant2;
protected function isEquationRedundant_flatten
"Same as isEquationRedundant but flattens equations of form 'tuple = tuple'
(e.g. (a,_,b) = (_,c,d) => b=d), if left tuple elements are in globalKnownVarHT and adds them to globalKnownVars"
input BackendDAE.Equation inEq;
input output HashSet.HashSet globalKnownVarHT;
input output BackendDAE.Variables globalKnownVars;
input output BackendDAE.Variables orderedVars;
output Boolean outB "true if 'x=x', else false";
output Boolean isGlobalKnown = false;
algorithm
outB := match(inEq)
local
DAE.Exp exp1, exp2;
list<DAE.Exp> lhs, rhs;
Boolean isRedundant;
case BackendDAE.EQUATION(exp=exp1, scalar=exp2)
algorithm
isRedundant := Expression.expEqual(exp1, exp2);
if not isRedundant then
isGlobalKnown := allArgsInGlobalKnownVars({exp2}, globalKnownVarHT);
if isGlobalKnown then
globalKnownVarHT := addConstantCseVarsToGlobalKnownVarHT(exp1, globalKnownVarHT);
end if;
end if;
then isRedundant;