/
SimCodeUtil.mo
13918 lines (12805 loc) · 593 KB
/
SimCodeUtil.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 SimCodeUtil
" file: SimCodeUtil.mo
package: SimCodeUtil
description: Code generation using Susan templates
The entry points to this module are the functions createSimCode and
createFunctions.
RCS: $Id$"
// public imports
import Absyn;
import BackendDAE;
import Ceval;
import DAE;
import FCore;
import FGraph;
import HashTableExpToIndex;
import HashTableStringToPath;
import SCode;
import Tpl;
import Types;
import Values;
import SimCode;
import SimCodeVar;
// protected imports
protected
import Array;
import BackendDAEOptimize;
import BackendDAETransform;
import BackendDAEUtil;
import BackendDump;
import BackendEquation;
import BackendVariable;
import BackendVarTransform;
import BaseHashTable;
import BaseHashSet;
import Builtin;
import ClockIndexes;
import CevalScript;
import CheckModel;
import ClassInf;
import ComponentReference;
import Config;
import DAEDump;
import DAEUtil;
import Debug;
import Differentiate;
import Error;
import Expression;
import ExpressionDump;
import ExpressionSimplify;
import ExpressionSolve;
import FindZeroCrossings;
import Flags;
import GC;
import Graph;
import HashSet;
import HpcOmSimCode;
import Initialization;
import Inline;
import List;
import Mod;
import PriorityQueue;
import Settings;
import SimCodeDump;
import SymbolicJacobian;
import System;
import Util;
import ValuesUtil;
// =============================================================================
// section for public function for SimCodeTV
//
// =============================================================================
public function elementVars
"Used by templates to get a list of variables from a valueblock."
input list<DAE.Element> ild;
output list<SimCode.Variable> vars;
protected
list<DAE.Element> ld;
algorithm
ld := List.filter(ild, isVarQ);
vars := List.map(ld, daeInOutSimVar);
end elementVars;
public function crefSubIsScalar
"Used by templates to determine if a component reference's subscripts are
scalar."
input DAE.ComponentRef cref;
output Boolean isScalar;
protected
list<DAE.Subscript> subs;
algorithm
subs := ComponentReference.crefSubs(cref);
isScalar := subsToScalar(subs);
end crefSubIsScalar;
public function crefNoSub
"Used by templates to determine if a component reference has no subscripts."
input DAE.ComponentRef cref;
output Boolean noSub;
algorithm
noSub := boolNot(ComponentReference.crefHaveSubs(cref));
end crefNoSub;
public function crefIsScalar
"Whether a component reference is a scalar depends on what context we are in.
If we are generating code for a function, then only crefs without subscripts
are scalar. If we are generating code for simulation though, then crefs with
only constant subscripts are also scalars, since a variable is generated for
each element of an array in the model."
input DAE.ComponentRef cref;
input SimCode.Context context;
output Boolean isScalar;
algorithm
isScalar := matchcontinue(cref, context)
local
Boolean res;
case (_, SimCode.FUNCTION_CONTEXT())
equation
res = crefNoSub(cref);
then
res;
case (_, SimCode.PARALLEL_FUNCTION_CONTEXT())
equation
res = crefNoSub(cref);
then
res;
case (_, _)
equation
res = ComponentReference.crefHasScalarSubscripts(cref);
then
res;
end matchcontinue;
end crefIsScalar;
public function buildCrefExpFromAsub
"Used by templates to convert an ASUB expression to a component reference
with subscripts."
input DAE.Exp cref;
input list<DAE.Exp> subs;
output DAE.Exp cRefOut;
algorithm
cRefOut := matchcontinue(cref, subs)
local
DAE.Exp crefExp;
DAE.Type ty;
DAE.ComponentRef crNew;
list<DAE.Subscript> indexes;
case (_, {}) then cref;
case (DAE.CREF(componentRef=crNew, ty=ty), _)
equation
indexes = List.map(subs, Expression.makeIndexSubscript);
crNew = ComponentReference.subscriptCref(crNew, indexes);
crefExp = Expression.makeCrefExp(crNew, ty);
then
crefExp;
end matchcontinue;
end buildCrefExpFromAsub;
public function incrementInt
"Used by templates to create new integers that are increments of another."
input Integer inInt;
input Integer increment;
output Integer outInt;
algorithm
outInt := inInt + increment;
end incrementInt;
public function decrementInt
"Used by templates to create new integers that are increments of another."
input Integer inInt;
input Integer decrement;
output Integer outInt;
algorithm
outInt := inInt - decrement;
end decrementInt;
public function protectedVars
input list<SimCodeVar.SimVar> InSimVars;
output list<SimCodeVar.SimVar> OutSimVars;
algorithm
OutSimVars:= List.filterOnTrue(InSimVars,isNotProtected);
end protectedVars;
protected function isNotProtected
input SimCodeVar.SimVar simVar;
output Boolean isProtected;
algorithm
SimCodeVar.SIMVAR(isProtected=isProtected) := simVar;
isProtected := not isProtected;
end isNotProtected;
public function makeCrefRecordExp
"Helper function to generate records."
input DAE.ComponentRef inCRefRecord;
input DAE.Var inVar;
output DAE.Exp outExp;
algorithm
outExp := match (inCRefRecord, inVar)
local
DAE.ComponentRef cr, cr1;
String name;
DAE.Type tp;
case (cr, DAE.TYPES_VAR(name=name, ty=tp))
equation
cr1 = ComponentReference.crefPrependIdent(cr, name, {}, tp);
outExp = Expression.makeCrefExp(cr1, tp);
then
outExp;
end match;
end makeCrefRecordExp;
public function cref2simvar
"Used by templates to find SIMVAR for given cref (to gain representaion index info mainly)."
input DAE.ComponentRef inCref;
input SimCode.SimCode simCode;
output SimCodeVar.SimVar outSimVar;
algorithm
outSimVar := matchcontinue(inCref, simCode)
local
DAE.ComponentRef cref, badcref;
SimCodeVar.SimVar sv;
SimCode.HashTableCrefToSimVar crefToSimVarHT;
String errstr;
case (cref, SimCode.SIMCODE(crefToSimVarHT = crefToSimVarHT) )
equation
sv = get(cref, crefToSimVarHT);
then sv;
case (cref, _)
equation
badcref = ComponentReference.makeCrefIdent("ERROR_cref2simvar_failed", DAE.T_REAL_DEFAULT, {});
/* Todo: This also generates an error for example itearation variables, so i commented out
"Template did not find the simulation variable for "+ ComponentReference.printComponentRefStr(cref) + ". ";
Error.addMessage(Error.INTERNAL_ERROR, {errstr});*/
then
SimCodeVar.SIMVAR(badcref, BackendDAE.VARIABLE(), "", "", "", -2, NONE(), NONE(), NONE(), NONE(), false, DAE.T_REAL_DEFAULT, false, NONE(), SimCodeVar.NOALIAS(), DAE.emptyElementSource, SimCodeVar.INTERNAL(), NONE(), {}, false, true);
end matchcontinue;
end cref2simvar;
public function isModelTooBigForCSharpInOneFile
"Used by C# template to determine if the generated code should be split into several files
to make Visual Studio responsive when the file is opened (C# compiler is OK,
but VS does not scale well for big C# files)."
input SimCode.SimCode simCode;
output Boolean outIsTooBig;
algorithm
outIsTooBig := match(simCode)
local
Integer numAlgVars;
case (SimCode.SIMCODE(modelInfo = SimCode.MODELINFO(varInfo = SimCode.VARINFO(numAlgVars = numAlgVars))))
equation
outIsTooBig = numAlgVars > 1000;
then outIsTooBig;
end match;
end isModelTooBigForCSharpInOneFile;
public function derComponentRef
"Used by templates to derrive a cref in a der(cref) expression.
Particularly, this function is called for the C# code generator,
while for C/C++, it is solved by prefixing the cref with '$P$DER' in daeExpCall() template.
The prefixing technique is not usable for C#, because there is no macroprocessor in C#.
TODO: all der(cref) expressions should be eliminated before the expressions enter templates
to pull this logic (and this function) out of templates."
input DAE.ComponentRef inCref;
output DAE.ComponentRef derCref;
algorithm
derCref := ComponentReference.crefPrefixDer(inCref);
end derComponentRef;
public function hackArrayReverseToCref
"This is a hack transformation of an expanded array back to its cref.
It is used in daeExpArray() (for C# yet) to optimize the generated code.
TODO: This function should not exist!
Rather the array should not be let expanded when SimCode is entering templates.
"
input DAE.Exp inExp;
input SimCode.Context context;
output DAE.Exp outExp;
algorithm
outExp := matchcontinue (inExp, context)
local
list<DAE.Exp> aRest;
DAE.ComponentRef cr;
DAE.Type aty;
DAE.Exp crefExp;
case(DAE.ARRAY(ty=aty, scalar=true, array =(DAE.CREF(componentRef=cr) ::aRest)), _)
equation
failure(SimCode.FUNCTION_CONTEXT()=context); // only in the function context
failure(SimCode.PARALLEL_FUNCTION_CONTEXT()=context); // only in the function context
{ DAE.INDEX(DAE.ICONST(1)) } = ComponentReference.crefLastSubs(cr);
cr = ComponentReference.crefStripLastSubs(cr);
true = isArrayExpansion(aRest, cr, 2);
crefExp = Expression.makeCrefExp(cr, aty);
then
crefExp;
case (_, _) then inExp;
end matchcontinue;
end hackArrayReverseToCref;
protected function isArrayExpansion
"Helper funtion to hackArrayReverseToCref."
input list<DAE.Exp> inArrayElems;
input DAE.ComponentRef inCref;
input Integer index;
output Boolean isExpanded;
algorithm
isExpanded := matchcontinue(inArrayElems, inCref, index)
local
list<DAE.Exp> aRest;
Integer i;
DAE.ComponentRef cr;
case({}, _, _) then true;
case (DAE.CREF(componentRef=cr) :: aRest, _, _)
equation
{ DAE.INDEX(DAE.ICONST(i)) } = ComponentReference.crefLastSubs(cr);
true = (i == index);
cr = ComponentReference.crefStripLastSubs(cr);
true = ComponentReference.crefEqualNoStringCompare(inCref, cr);
then isArrayExpansion(aRest, inCref, index+1);
case (_, _, _) then false;
end matchcontinue;
end isArrayExpansion;
public function hackMatrixReverseToCref
"This is a hack transformation of an expanded matrix back to its cref.
It is used in daeExpMatrix() (for C# yet) to optimize the generated code.
TODO: This function should not exist!
Rather the matrix should not be let expanded when SimCode is entering templates
"
input DAE.Exp inExp;
input SimCode.Context context;
output DAE.Exp outExp;
algorithm
outExp := matchcontinue (inExp, context)
local
DAE.ComponentRef cr;
DAE.Type aty;
list<list<DAE.Exp>> rows;
DAE.Exp crefExp;
case(DAE.MATRIX(ty=aty, matrix = rows as (((DAE.CREF(componentRef=cr))::_)::_) ), _)
equation
failure(SimCode.FUNCTION_CONTEXT()=context);
failure(SimCode.PARALLEL_FUNCTION_CONTEXT()=context); // only in the function context
{ DAE.INDEX(DAE.ICONST(1)), DAE.INDEX(DAE.ICONST(1)) } = ComponentReference.crefLastSubs(cr);
cr = ComponentReference.crefStripLastSubs(cr);
true = isMatrixExpansion(rows, cr, 1, 1);
crefExp = Expression.makeCrefExp(cr, aty);
then
crefExp;
case (_, _) then inExp;
end matchcontinue;
end hackMatrixReverseToCref;
protected function isMatrixExpansion
"Helper funtion to hackMatrixReverseToCref."
input list<list<DAE.Exp>> rows;
input DAE.ComponentRef inCref;
input Integer rowIndex;
input Integer colIndex;
output Boolean isExpanded;
algorithm
isExpanded := matchcontinue(rows, inCref, rowIndex, colIndex)
local
list<list<DAE.Exp>> restRows;
list<DAE.Exp> restElems;
Integer r, c;
DAE.ComponentRef cr;
case({}, _, _, _) then true;
case({} :: restRows, _, _, _) then isMatrixExpansion(restRows, inCref, rowIndex+1, 1);
case ( (DAE.CREF(componentRef=cr) :: restElems) :: restRows, _, _, _)
equation
{ DAE.INDEX(DAE.ICONST(r)), DAE.INDEX(DAE.ICONST(c)) } = ComponentReference.crefLastSubs(cr);
true = (r == rowIndex) and (c == colIndex);
cr = ComponentReference.crefStripLastSubs(cr);
true = ComponentReference.crefEqualNoStringCompare(inCref, cr);
then isMatrixExpansion(restElems :: restRows, inCref, rowIndex, colIndex+1);
else false;
end matchcontinue;
end isMatrixExpansion;
public function hackGetFirstExternalFunctionLib
"This is a hack to get the original library name given to an external function.
TODO: redesign OMC and Modelica specification so they are not so C/C++ centric."
input list<String> libs;
output String outFirstLib;
algorithm
outFirstLib := matchcontinue (libs)
local
String lib;
case _
equation
lib = List.last(libs);
lib = System.stringReplace(lib, "-l", "");
then
lib;
case(_) then "NO_LIB";
end matchcontinue;
end hackGetFirstExternalFunctionLib;
public function createAssertforSqrt
input DAE.Exp inExp;
output DAE.Exp outExp;
algorithm
outExp :=
match (inExp)
case(_)
equation
// Simplify things like abs(exp) >= 0 to exp
(outExp, _) = ExpressionSimplify.simplify(DAE.RELATION(inExp, DAE.GREATEREQ(DAE.T_REAL_DEFAULT), DAE.RCONST(0.0), -1, NONE()));
then outExp;
end match;
end createAssertforSqrt;
public function createDAEString
input String inString;
output DAE.Exp outExp;
annotation(__OpenModelica_EarlyInline = true);
algorithm
outExp := DAE.SCONST(inString);
end createDAEString;
public function appendLists
input list<SimCode.SimEqSystem> inEqn1;
input list<SimCode.SimEqSystem> inEqn2;
output list<SimCode.SimEqSystem> outEqn;
algorithm
outEqn := listAppend(inEqn1, inEqn2);
end appendLists;
protected function compareEqSystems
input SimCode.SimEqSystem eq1;
input SimCode.SimEqSystem eq2;
output Boolean b;
algorithm
b := eqIndex(eq1) > eqIndex(eq2);
end compareEqSystems;
public function sortEqSystems
input list<SimCode.SimEqSystem> eqs;
output list<SimCode.SimEqSystem> outEqs;
algorithm
outEqs := List.sort(eqs,compareEqSystems);
end sortEqSystems;
/** end of TypeView published functions **/
// =============================================================================
// section to generate SimCode from functions
//
// Finds the called functions in BackendDAE and transforms them to a list of
// libraries and a list of SimCode.Function uniontypes.
// =============================================================================
public function createFunctions
input Absyn.Program inProgram;
input DAE.DAElist inDAElist;
input BackendDAE.BackendDAE inBackendDAE;
input Absyn.Path inPath;
output list<String> libs;
output list<String> libPaths;
output list<String> includes;
output list<String> includeDirs;
output list<SimCode.RecordDeclaration> recordDecls;
output list<SimCode.Function> functions;
output BackendDAE.BackendDAE outBackendDAE;
output DAE.DAElist outDAE;
output tuple<Integer, HashTableExpToIndex.HashTable, list<DAE.Exp>> literals;
algorithm
(libs,libPaths, includes, includeDirs, recordDecls, functions, outBackendDAE, outDAE, literals) :=
matchcontinue (inProgram, inDAElist, inBackendDAE, inPath)
local
list<String> libs2,libpaths2, includes2, includeDirs2;
list<DAE.Function> funcelems, part_func_elems, recFuncs;
DAE.DAElist dae;
BackendDAE.BackendDAE dlow;
DAE.FunctionTree functionTree;
Absyn.Path path;
list<SimCode.Function> fns;
list<DAE.Exp> lits;
case (_, dae, dlow as BackendDAE.DAE(shared=BackendDAE.SHARED(functionTree=functionTree)), _)
equation
// get all the used functions from the function tree
funcelems = DAEUtil.getFunctionList(functionTree);
funcelems = setRecordVariability(funcelems,inBackendDAE);
funcelems = Inline.inlineCallsInFunctions(funcelems, (NONE(), {DAE.NORM_INLINE(), DAE.AFTER_INDEX_RED_INLINE()}), {});
(funcelems, literals as (_, _, lits)) = simulationFindLiterals(dlow, funcelems);
(fns, recordDecls, includes2, includeDirs2, libs2,libpaths2) = elaborateFunctions(inProgram, funcelems, {}, lits, {}); // Do we need metarecords here as well?
then
(libs2, libpaths2,includes2, includeDirs2, recordDecls, fns, dlow, dae, literals);
else
equation
Error.addMessage(Error.INTERNAL_ERROR, {"Creation of Modelica functions failed. "});
then
fail();
end matchcontinue;
end createFunctions;
protected function orderRecordDecls
input SimCode.RecordDeclaration decl1;
input SimCode.RecordDeclaration decl2;
output Boolean b;
algorithm
b := match (decl1,decl2)
local
Absyn.Path path1,path2;
case (SimCode.RECORD_DECL_DEF(path=path1),SimCode.RECORD_DECL_DEF(path=path2)) then Absyn.pathGe(path1,path2);
else true;
end match;
end orderRecordDecls;
public function elaborateFunctions
input Absyn.Program program;
input list<DAE.Function> daeElements;
input list<DAE.Type> metarecordTypes;
input list<DAE.Exp> literals;
input list<String> includes;
output list<SimCode.Function> functions;
output list<SimCode.RecordDeclaration> extraRecordDecls;
output list<String> outIncludes;
output list<String> includeDirs;
output list<String> libs;
output list<String> libpaths;
protected
list<SimCode.Function> fns;
list<String> outRecordTypes;
HashTableStringToPath.HashTable ht;
list<tuple<SimCode.RecordDeclaration,list<SimCode.RecordDeclaration>>> g;
algorithm
(extraRecordDecls, outRecordTypes) := elaborateRecordDeclarationsForMetarecords(literals, {}, {});
(functions, outRecordTypes, extraRecordDecls, outIncludes, includeDirs, libs,libpaths) := elaborateFunctions2(program, daeElements, {}, outRecordTypes, extraRecordDecls, includes, {}, {},{});
extraRecordDecls := List.unique(extraRecordDecls);
(extraRecordDecls, _) := elaborateRecordDeclarationsFromTypes(metarecordTypes, extraRecordDecls, outRecordTypes);
extraRecordDecls := List.sort(extraRecordDecls, orderRecordDecls);
ht := HashTableStringToPath.emptyHashTableSized(BaseHashTable.lowBucketSize);
(extraRecordDecls,_) := List.mapFold(extraRecordDecls, aliasRecordDeclarations, ht);
// Topological sort since we have no guarantees in the order of generated records
g := Graph.buildGraph(extraRecordDecls, getRecordDependencies, extraRecordDecls);
(extraRecordDecls, {}) := Graph.topologicalSort(g, isRecordDeclEqual);
end elaborateFunctions;
protected function getRecordDependencies
input SimCode.RecordDeclaration decl;
input list<SimCode.RecordDeclaration> allDecls;
output list<SimCode.RecordDeclaration> dependencies;
algorithm
dependencies := match (decl,allDecls)
local
String name;
list<SimCode.Variable> vars;
list<DAE.Type> tys;
list<list<DAE.Type>> tyss;
case (SimCode.RECORD_DECL_FULL(aliasName=SOME(name)),_)
then List.select1(allDecls, isRecordDecl, name);
case (SimCode.RECORD_DECL_FULL(variables=vars),_)
equation
tys = List.map(vars, getVarType);
tyss = List.map1(tys, Types.getAllInnerTypesOfType, Util.anyReturnTrue);
tys = List.flatten(tyss);
dependencies = List.filterMap1(tys, getRecordDependenciesFromType, allDecls);
then List.unique(dependencies);
else {};
end match;
end getRecordDependencies;
protected function getVarType
input SimCode.Variable var;
output DAE.Type ty;
algorithm
ty := match var
case SimCode.VARIABLE(ty=ty) then ty;
else DAE.T_ANYTYPE_DEFAULT;
end match;
end getVarType;
protected function getRecordDependenciesFromType
input DAE.Type ty;
input list<SimCode.RecordDeclaration> allDecls;
output SimCode.RecordDeclaration decl;
protected
Absyn.Path path;
String name;
algorithm
DAE.T_COMPLEX(complexClassType = ClassInf.RECORD(path)) := ty;
name := Absyn.pathStringUnquoteReplaceDot(path, "_");
decl := List.selectFirst1(allDecls, isRecordDecl, name);
end getRecordDependenciesFromType;
protected function isRecordDecl
input SimCode.RecordDeclaration decl;
input String name;
output Boolean b;
algorithm
b := match (decl,name)
local
String name1;
case (SimCode.RECORD_DECL_FULL(name=name1),_) then stringEq(name,name1);
else false;
end match;
end isRecordDecl;
protected function isRecordDeclEqual
input SimCode.RecordDeclaration decl1;
input SimCode.RecordDeclaration decl2;
output Boolean b;
algorithm
b := match (decl1,decl2)
local
String name1,name2;
Absyn.Path path1,path2;
case (SimCode.RECORD_DECL_FULL(name=name1),SimCode.RECORD_DECL_FULL(name=name2)) then stringEq(name1,name2);
case (SimCode.RECORD_DECL_DEF(path=path1),SimCode.RECORD_DECL_DEF(path=path2)) then Absyn.pathEqual(path1,path2);
else false;
end match;
end isRecordDeclEqual;
protected function elaborateFunctions2
input Absyn.Program program;
input list<DAE.Function> daeElements;
input list<SimCode.Function> inFunctions;
input list<String> inRecordTypes;
input list<SimCode.RecordDeclaration> inDecls;
input list<String> inIncludes;
input list<String> inIncludeDirs;
input list<String> inLibs;
input list<String> inPaths;
output list<SimCode.Function> outFunctions;
output list<String> outRecordTypes;
output list<SimCode.RecordDeclaration> outDecls;
output list<String> outIncludes;
output list<String> outIncludeDirs;
output list<String> outLibs;
output list<String> outLibsPaths;
algorithm
(outFunctions, outRecordTypes, outDecls, outIncludes, outIncludeDirs, outLibs,outLibsPaths) :=
match (program, daeElements, inFunctions, inRecordTypes, inDecls, inIncludes, inIncludeDirs, inLibs,inPaths)
local
Boolean b;
list<SimCode.Function> accfns, fns;
SimCode.Function fn;
list<String> rt, rt_1, rt_2, includes, libs,libPaths;
DAE.Function fel;
list<DAE.Function> rest;
list<SimCode.RecordDeclaration> decls;
String name;
list<String> includeDirs;
Absyn.Path path;
case (_, {}, accfns, rt, decls, includes, includeDirs, libs,libPaths)
then (listReverse(accfns), rt, decls, includes, includeDirs, libs,libPaths);
case (_, (DAE.FUNCTION( type_ = DAE.T_FUNCTION(functionAttributes=DAE.FUNCTION_ATTRIBUTES(isBuiltin=DAE.FUNCTION_BUILTIN_PTR()))) :: rest), accfns, rt, decls, includes, includeDirs, libs,libPaths)
equation
// skip over builtin functions
(fns, rt_2, decls, includes, includeDirs, libs,libPaths) = elaborateFunctions2(program, rest, accfns, rt, decls, includes, includeDirs, libs,libPaths);
then
(fns, rt_2, decls, includes, includeDirs, libs,libPaths);
case (_, (DAE.FUNCTION(partialPrefix = true) :: rest), accfns, rt, decls, includes, includeDirs, libs,libPaths)
equation
// skip over partial functions
(fns, rt_2, decls, includes, includeDirs, libs,libPaths) = elaborateFunctions2(program, rest, accfns, rt, decls, includes, includeDirs, libs,libPaths);
then
(fns, rt_2, decls, includes, includeDirs, libs,libPaths);
case (_, DAE.FUNCTION(functions = DAE.FUNCTION_EXT(externalDecl = DAE.EXTERNALDECL(language="builtin"))::_)::rest, accfns, rt, decls, includes, includeDirs, libs,libPaths)
equation
// skip over builtin functions
(fns, rt_2, decls, includes, includeDirs, libs,libPaths) = elaborateFunctions2(program, rest, accfns, rt, decls, includes, includeDirs, libs,libPaths);
then
(fns, rt_2, decls, includes, includeDirs, libs,libPaths);
case (_, (fel as DAE.FUNCTION(functions = DAE.FUNCTION_EXT(externalDecl = DAE.EXTERNALDECL(name=name, language="C"))::_))::rest, accfns, rt, decls, includes, includeDirs, libs,libPaths)
equation
// skip over builtin functions
b = listMember(name, SCode.knownExternalCFunctions);
(fn,_, decls, includes, includeDirs, libs,libPaths) = elaborateFunction(program, fel, rt, decls, includes, includeDirs, libs,libPaths);
(fns, rt_2, decls, includes, includeDirs, libs,libPaths) = elaborateFunctions2(program, rest, List.consOnTrue(not b, fn, accfns), rt, decls, includes, includeDirs, libs,libPaths);
then
(fns, rt_2, decls, includes, includeDirs, libs,libPaths);
case (_, (fel :: rest), accfns, rt, decls, includes, includeDirs, libs,libPaths)
equation
(fn, rt_1, decls, includes, includeDirs, libs,libPaths) = elaborateFunction(program, fel, rt, decls, includes, includeDirs, libs,libPaths);
(fns, rt_2, decls, includes, includeDirs, libs,libPaths) = elaborateFunctions2(program, rest, (fn :: accfns), rt_1, decls, includes, includeDirs, libs,libPaths);
then
(fns, rt_2, decls, includes, includeDirs, libs,libPaths);
end match;
end elaborateFunctions2;
/* Does the actual work of transforming a DAE.FUNCTION to a SimCode.Function. */
protected function elaborateFunction
input Absyn.Program program;
input DAE.Function inElement;
input list<String> inRecordTypes;
input list<SimCode.RecordDeclaration> inRecordDecls;
input list<String> inIncludes;
input list<String> inIncludeDirs;
input list<String> inLibs;
input list<String> inLibPaths;
output SimCode.Function outFunction;
output list<String> outRecordTypes;
output list<SimCode.RecordDeclaration> outRecordDecls;
output list<String> outIncludes;
output list<String> outIncludeDirs;
output list<String> outLibs;
output list<String> outLibPaths;
algorithm
(outFunction, outRecordTypes, outRecordDecls, outIncludes, outIncludeDirs, outLibs,outLibPaths):=
matchcontinue (program, inElement, inRecordTypes, inRecordDecls, inIncludes, inIncludeDirs, inLibs,inLibPaths)
local
DAE.Function fn;
String extfnname, lang, str;
list<DAE.Element> algs, vars; // , bivars, invars, outvars;
list<String> includes, libs, libPaths, fn_libs,fn_paths, fn_includes, fn_includeDirs, rt, rt_1;
Absyn.Path fpath;
list<DAE.FuncArg> args;
DAE.Type restype, tp;
list<DAE.ExtArg> extargs;
list<SimCode.SimExtArg> simextargs;
SimCode.SimExtArg extReturn;
DAE.ExtArg extretarg;
Option<SCode.Annotation> ann;
DAE.ExternalDecl extdecl;
list<SimCode.Variable> outVars, inVars, biVars, funArgs, varDecls;
list<SimCode.RecordDeclaration> recordDecls;
list<SimCode.Statement> bodyStmts;
list<DAE.Element> daeElts;
Absyn.Path name;
DAE.ElementSource source;
SourceInfo info;
Boolean dynamicLoad, hasIncludeAnnotation, hasLibraryAnnotation;
list<String> includeDirs;
DAE.FunctionAttributes funAttrs;
list<DAE.Var> varlst;
DAE.VarKind kind;
SCode.Visibility visibility;
// Modelica functions.
case (_, DAE.FUNCTION(path = fpath, source = source, visibility = visibility,
functions = DAE.FUNCTION_DEF(body = daeElts)::_, // might be followed by derivative maps
type_ = DAE.T_FUNCTION(funcArg=args, functionAttributes=funAttrs),
partialPrefix=false), rt, recordDecls, includes, includeDirs, libs,libPaths)
equation
DAE.FUNCTION_ATTRIBUTES(functionParallelism=DAE.FP_NON_PARALLEL()) = funAttrs;
outVars = List.map(DAEUtil.getOutputVars(daeElts), daeInOutSimVar);
funArgs = List.map1(args, typesSimFunctionArg, NONE());
(recordDecls, rt_1) = elaborateRecordDeclarations(daeElts, recordDecls, rt);
vars = List.filter(daeElts, isVarQ);
varDecls = List.map(vars, daeInOutSimVar);
algs = List.filterOnTrue(daeElts, DAEUtil.isAlgorithm);
bodyStmts = List.map(algs, elaborateStatement);
info = DAEUtil.getElementSourceFileInfo(source);
then
(SimCode.FUNCTION(fpath, outVars, funArgs, varDecls, bodyStmts, visibility, info), rt_1, recordDecls, includes, includeDirs, libs,libPaths);
case (_, DAE.FUNCTION(path = fpath, source = source,
functions = DAE.FUNCTION_DEF(body = daeElts)::_, // might be followed by derivative maps
type_ = DAE.T_FUNCTION(funcArg=args, functionAttributes=funAttrs),
partialPrefix=false), rt, recordDecls, includes, includeDirs, libs,libPaths)
equation
DAE.FUNCTION_ATTRIBUTES(functionParallelism=DAE.FP_KERNEL_FUNCTION()) = funAttrs;
outVars = List.map(DAEUtil.getOutputVars(daeElts), daeInOutSimVar);
funArgs = List.map1(args, typesSimFunctionArg, NONE());
(recordDecls, rt_1) = elaborateRecordDeclarations(daeElts, recordDecls, rt);
vars = List.filter(daeElts, isVarNotInputNotOutput);
varDecls = List.map(vars, daeInOutSimVar);
algs = List.filterOnTrue(daeElts, DAEUtil.isAlgorithm);
bodyStmts = List.map(algs, elaborateStatement);
info = DAEUtil.getElementSourceFileInfo(source);
then
(SimCode.KERNEL_FUNCTION(fpath, outVars, funArgs, varDecls, bodyStmts, info), rt_1, recordDecls, includes, includeDirs, libs,libPaths);
case (_, DAE.FUNCTION(path = fpath, source = source,
functions = DAE.FUNCTION_DEF(body = daeElts)::_, // might be followed by derivative maps
type_ = DAE.T_FUNCTION(funcArg=args, functionAttributes = funAttrs),
partialPrefix=false), rt, recordDecls, includes, includeDirs, libs,libPaths)
equation
DAE.FUNCTION_ATTRIBUTES(functionParallelism=DAE.FP_PARALLEL_FUNCTION()) = funAttrs;
outVars = List.map(DAEUtil.getOutputVars(daeElts), daeInOutSimVar);
funArgs = List.map1(args, typesSimFunctionArg, NONE());
(recordDecls, rt_1) = elaborateRecordDeclarations(daeElts, recordDecls, rt);
vars = List.filter(daeElts, isVarQ);
varDecls = List.map(vars, daeInOutSimVar);
algs = List.filterOnTrue(daeElts, DAEUtil.isAlgorithm);
bodyStmts = List.map(algs, elaborateStatement);
info = DAEUtil.getElementSourceFileInfo(source);
then
(SimCode.PARALLEL_FUNCTION(fpath, outVars, funArgs, varDecls, bodyStmts, info), rt_1, recordDecls, includes, includeDirs, libs,libPaths);
// External functions.
case (_, DAE.FUNCTION(path = fpath, source = source, visibility = visibility,
functions = DAE.FUNCTION_EXT(body = daeElts, externalDecl = extdecl)::_, // might be followed by derivative maps
type_ = (DAE.T_FUNCTION(funcArg = args))), rt, recordDecls, includes, includeDirs, libs,libPaths)
equation
DAE.EXTERNALDECL(name=extfnname, args=extargs,
returnArg=extretarg, language=lang, ann=ann) = extdecl;
// outvars = DAEUtil.getOutputVars(daeElts);
// invars = DAEUtil.getInputVars(daeElts);
// bivars = DAEUtil.getBidirVars(daeElts);
funArgs = List.map1(args, typesSimFunctionArg, NONE());
outVars = List.map(DAEUtil.getOutputVars(daeElts), daeInOutSimVar);
inVars = List.map(DAEUtil.getInputVars(daeElts), daeInOutSimVar);
biVars = List.map(DAEUtil.getBidirVars(daeElts), daeInOutSimVar);
(recordDecls, rt_1) = elaborateRecordDeclarations(daeElts, recordDecls, rt);
(fn_includes, fn_includeDirs, fn_libs, fn_paths,dynamicLoad) = generateExtFunctionIncludes(program, fpath, ann);
includes = List.union(fn_includes, includes);
includeDirs = List.union(fn_includeDirs, includeDirs);
libs = List.union(fn_libs, libs);
libPaths = List.union(fn_paths, libPaths);
simextargs = List.map(extargs, extArgsToSimExtArgs);
extReturn = extArgsToSimExtArgs(extretarg);
(simextargs, extReturn) = fixOutputIndex(outVars, simextargs, extReturn);
info = DAEUtil.getElementSourceFileInfo(source);
// make lang to-upper as we have FORTRAN 77 and Fortran 77 in the Modelica Library!
lang = System.toupper(lang);
then
(SimCode.EXTERNAL_FUNCTION(fpath, extfnname, funArgs, simextargs, extReturn,
inVars, outVars, biVars, fn_includes, fn_libs, lang, visibility, info, dynamicLoad),
rt_1, recordDecls, includes, includeDirs, libs,libPaths);
// Record constructor.
case (_, DAE.RECORD_CONSTRUCTOR(source = source, type_ = DAE.T_FUNCTION(funcArg = args, funcResultType = restype as DAE.T_COMPLEX(complexClassType = ClassInf.RECORD(name))),kind=kind), rt, recordDecls, includes, includeDirs, libs,libPaths)
equation
funArgs = List.map1(args, typesSimFunctionArg, NONE());
(recordDecls, rt_1) = elaborateRecordDeclarationsForRecord(restype, recordDecls, rt);
DAE.T_COMPLEX(varLst = varlst) = restype;
varlst = List.filterOnTrue(varlst, Types.isProtectedVar);
varDecls = List.map(varlst, typesVar);
info = DAEUtil.getElementSourceFileInfo(source);
then
(SimCode.RECORD_CONSTRUCTOR(name, funArgs, varDecls, SCode.PUBLIC(), info, kind), rt_1, recordDecls, includes, includeDirs, libs,libPaths);
// failure
case (_, fn, _, _, _, _, _,_)
equation
str = "./Compiler/BackEnd/SimCodeUtil.mo: function elaborateFunction failed for function: \n" + DAEDump.dumpFunctionStr(fn);
Error.addMessage(Error.INTERNAL_ERROR, {str});
then
fail();
end matchcontinue;
end elaborateFunction;
protected function typesSimFunctionArg
"Generates code from a function argument."
input DAE.FuncArg inFuncArg;
input Option<DAE.Exp> binding;
output SimCode.Variable outVar;
algorithm
outVar := matchcontinue (inFuncArg, binding)
local
DAE.Type tty;
String name;
DAE.ComponentRef cref_;
DAE.Const const;
list<DAE.FuncArg> args;
DAE.Type res_ty;
list<SimCode.Variable> var_args;
list<DAE.Type> tys;
DAE.VarKind kind;
DAE.VarParallelism prl;
case (DAE.FUNCARG(name=name, ty=DAE.T_FUNCTION(funcArg = args, funcResultType = DAE.T_TUPLE(types = tys))), _)
equation
var_args = List.map1(args, typesSimFunctionArg, NONE());
tys = List.map(tys, Types.simplifyType);
then
SimCode.FUNCTION_PTR(name, tys, var_args, binding);
case (DAE.FUNCARG(name=name, ty=DAE.T_FUNCTION(funcArg = args, funcResultType = DAE.T_NORETCALL())), _)
equation
var_args = List.map1(args, typesSimFunctionArg, NONE());
then
SimCode.FUNCTION_PTR(name, {}, var_args, binding);
case (DAE.FUNCARG(name=name, ty=DAE.T_FUNCTION(funcArg = args, funcResultType = res_ty)), _)
equation
res_ty = Types.simplifyType(res_ty);
var_args = List.map1(args, typesSimFunctionArg, NONE());
then
SimCode.FUNCTION_PTR(name, {res_ty}, var_args, binding);
case (DAE.FUNCARG(name=name, ty=tty, par=prl, const=const), _)
equation
tty = Types.simplifyType(tty);
cref_ = ComponentReference.makeCrefIdent(name, tty, {});
kind = DAEUtil.const2VarKind(const);
then
SimCode.VARIABLE(cref_, tty, binding, {}, prl, kind);
end matchcontinue;
end typesSimFunctionArg;
protected function daeInOutSimVar
input DAE.Element inElement;
output SimCode.Variable outVar;
algorithm
outVar := matchcontinue(inElement)
local
String name;
DAE.Type daeType;
DAE.ComponentRef id;
DAE.VarKind kind;
DAE.VarParallelism prl;
list<DAE.Dimension> inst_dims;
list<DAE.Exp> inst_dims_exp;
Option<DAE.Exp> binding;
SimCode.Variable var;
case (DAE.VAR(componentRef = DAE.CREF_IDENT(ident=name), ty = daeType as DAE.T_FUNCTION(), parallelism = prl, binding = binding))
equation
var = typesSimFunctionArg(DAE.FUNCARG(name, daeType, DAE.C_VAR(), prl, NONE()), binding);
then var;
case (DAE.VAR(componentRef = id,
parallelism = prl,
ty = daeType,
binding = binding,
dims = inst_dims,
kind = kind
))
equation
daeType = Types.simplifyType(daeType);
inst_dims_exp = List.map(inst_dims, Expression.dimensionSizeExpHandleUnkown);
then SimCode.VARIABLE(id, daeType, binding, inst_dims_exp, prl, kind);
case (_)
equation
// TODO: ArrayEqn fails here
Error.addMessage(Error.INTERNAL_ERROR, {"./Compiler/BackEnd/SimCodeUtil.mo: function daeInOutSimVar failed\n"});
then
fail();
end matchcontinue;
end daeInOutSimVar;
protected function extArgsToSimExtArgs
input DAE.ExtArg extArg;
output SimCode.SimExtArg simExtArg;
algorithm
simExtArg :=
match (extArg)
local
DAE.ComponentRef componentRef;
DAE.Attributes attributes;
DAE.Type type_;
Boolean isInput;
Boolean isOutput;