-
Notifications
You must be signed in to change notification settings - Fork 297
/
CodegenCFunctions.tpl
7644 lines (6979 loc) · 320 KB
/
CodegenCFunctions.tpl
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 defines templates for transforming Modelica/MetaModelica code to C
// code. They are used in the code generator phase of the compiler to write
// target code.
//
// CodegenC.tpl has the root template translateModel while
// this template contains only translateFunctions.
// These templates do not return any
// result but instead write the result to files. All other templates return
// text and are used by the root templates (most of them indirectly).
package CodegenCFunctions
import interface SimCodeTV;
import CodegenUtil.*;
import ExpressionDumpTpl;
/* public */ template generateEntryPoint(Path entryPoint, String url) "used in Compiler/Script/CevalScript.mo"
::=
let name = ("omc_" + underscorePath(entryPoint))
<<
/* This is an automatically generated entry point to a MetaModelica function */
#if defined(__cplusplus)
extern "C" {
#endif
#if defined(OMC_ENTRYPOINT_STATIC)
#include <stdio.h>
#include <openmodelica.h>
DLLImport extern int __omc_main(int argc, char **argv);
int main(int argc, char **argv)
{
return __omc_main(argc, argv);
}
#else
#include <meta/meta_modelica.h>
#include <stdio.h>
extern void
#if defined(OMC_GENERATE_RELOCATABLE_CODE)
(*<%name%>)
#else
<%name%>
#endif
(threadData_t*,modelica_metatype);
void (*omc_assert)(threadData_t*,FILE_INFO info,const char *msg,...) __attribute__((noreturn)) = omc_assert_function;
void (*omc_assert_warning)(FILE_INFO info,const char *msg,...) = omc_assert_warning_function;
void (*omc_terminate)(FILE_INFO info,const char *msg,...) = omc_terminate_function;
void (*omc_throw)(threadData_t*) __attribute__ ((noreturn)) = omc_throw_function;
#ifdef _OPENMP
#include<omp.h>
/* Hack to make gcc-4.8 link in the OpenMP runtime if -fopenmp is given */
int (*force_link_omp)(void) = omp_get_num_threads;
#endif
static int rml_execution_failed()
{
fflush(NULL);
fprintf(stderr, "Execution failed!\n");
fflush(NULL);
return 1;
}
DLLExport int __omc_main(int argc, char **argv)
{
MMC_INIT(0);
{
void *lst = mmc_mk_nil();
int i = 0;
for (i=argc-1; i>0; i--) {
lst = mmc_mk_cons(mmc_mk_scon(argv[i]), lst);
}
<%mainTop('<%name%>(threadData, lst);',url)%>
}
<%if Flags.isSet(HPCOM) then "terminateHpcOmThreads();" %>
fflush(NULL);
EXIT(0);
return 0;
}
#endif
#if defined(__cplusplus)
} /* end extern "C" */
#endif
>>
end generateEntryPoint;
template mainTop(Text mainBody, String url)
::=
<<
{
MMC_TRY_TOP()
MMC_TRY_STACK()
<%mainBody%>
MMC_ELSE()
rml_execution_failed();
fprintf(stderr, "Stack overflow detected and was not caught.\nSend us a bug report at <%url%>\n Include the following trace:\n");
printStacktraceMessages();
fflush(NULL);
return 1;
MMC_CATCH_STACK()
MMC_CATCH_TOP(return rml_execution_failed());
}
>>
end mainTop;
/* public */ template translateFunctions(FunctionCode functionCode)
"Generates C code and Makefile for compiling and calling Modelica and
MetaModelica functions.
used in Compiler/SimCode/SimCodeMain.mo"
::=
match functionCode
case fc as FUNCTIONCODE(__) then
let()= System.tmpTickResetIndex(0,2) /* auxFunction index */
let()= System.tmpTickResetIndex(0,20) /*parfor index*/
let &staticPrototypes = buffer ""
let filePrefix = name
let _= (if mainFunction then textFile(functionsMakefile(functionCode), '<%filePrefix%>.makefile'))
let()= textFile(functionsHeaderFile(filePrefix, mainFunction, functions, extraRecordDecls, staticPrototypes), '<%filePrefix%>.h')
let()= textFileConvertLines(functionsFile(filePrefix, mainFunction, functions, literals, staticPrototypes), '<%filePrefix%>.c')
let()= textFile(externalFunctionIncludes(fc.externalFunctionIncludes), '<%filePrefix%>_includes.h')
let()= textFile(recordsFile(filePrefix, extraRecordDecls, false /*isSimulation*/), '<%filePrefix%>_records.c')
// If ParModelica generate the kernels file too.
if acceptParModelicaGrammar() then
let()= textFile(functionsParModelicaKernelsFile(filePrefix, mainFunction, functions), '<%filePrefix%>_kernels.cl')
"" // Return empty result since result written to files directly
end match
end translateFunctions;
template translateFunctionHeaderFiles(FunctionCode functionCode)
::=
match functionCode
case fc as FUNCTIONCODE(__) then
let()= System.tmpTickResetIndex(0,2) /* auxFunction index */
let()= System.tmpTickResetIndex(0,20) /*parfor index*/
let &staticPrototypes = buffer ""
let filePrefix = name
let _= (if mainFunction then textFile(functionsMakefile(functionCode), '<%filePrefix%>.makefile'))
let()= textFile(functionsHeaderFile(filePrefix, mainFunction, functions, extraRecordDecls, staticPrototypes), '<%filePrefix%>.h')
let()= textFile(externalFunctionIncludes(fc.externalFunctionIncludes), '<%filePrefix%>_includes.h')
let()= textFile(recordsFile(filePrefix, extraRecordDecls, false /*isSimulation*/), '<%filePrefix%>_records.c')
"" // Return empty result since result written to files directly
end match
end translateFunctionHeaderFiles;
template functionsFile(String filePrefix,
Option<Function> mainFunction,
list<Function> functions,
list<Exp> literals,
Text &staticPrototypes)
"Generates the contents of the main C file for the function case."
::=
<<
#include "omc_simulation_settings.h"
#include "<%filePrefix%>.h"
<% /* Note: The literals may not be part of the header due to separate compilation */
literals |> literal hasindex i0 fromindex 0 => literalExpConst(literal,i0) ; separator="\n";empty
%>
#include "util/modelica.h"
#include "<%filePrefix%>_includes.h"
<%if acceptParModelicaGrammar() then
<<
/* the OpenCL Kernels file name needed in libParModelicaExpl.a */
const char* omc_ocl_kernels_source = "<%filePrefix%>_kernels.cl";
/* the OpenCL program. Made global to avoid repeated builds */
extern cl_program omc_ocl_program;
/* The default OpenCL device. If not set (=0) show the selection option.*/
unsigned int default_ocl_device = <%getDefaultOpenCLDevice()%>;
>>
%>
<%if staticPrototypes then
<<
/* default, do not make protected functions static */
#if !defined(PROTECTED_FUNCTION_STATIC)
#define PROTECTED_FUNCTION_STATIC
#endif
<%staticPrototypes%>
>>
%>
<%match mainFunction case SOME(fn) then functionBody(fn,true,false)%>
<%functionBodies(functions,false)%>
<%\n%>
>>
end functionsFile;
template functionsHeaderFile(String filePrefix,
Option<Function> mainFunction,
list<Function> functions,
list<RecordDeclaration> extraRecordDecls,
Text &staticPrototypes)
"Generates the contents of the main C file for the function case."
::=
<<
#ifndef <%makeC89Identifier(filePrefix)%>__H
#define <%makeC89Identifier(filePrefix)%>__H
<%commonHeader(filePrefix)%>
#ifdef __cplusplus
extern "C" {
#endif
<%extraRecordDecls |> rd => recordDeclarationHeader(rd) ;separator="\n"%>
<%match mainFunction case SOME(fn) then functionHeader(fn,true,false,staticPrototypes)%>
<%functionHeaders(functions, false, staticPrototypes)%>
#ifdef __cplusplus
}
#endif
#endif<%\n%>
>>
/* adrpo: leave a newline at the end of file to get rid of the warning */
end functionsHeaderFile;
template functionsMakefile(FunctionCode fnCode)
"Generates the contents of the makefile for the function case."
::=
match fnCode
case FUNCTIONCODE(makefileParams=MAKEFILE_PARAMS(__)) then
let libsStr = (makefileParams.libs ;separator=" ")
let ParModelicaExpLibs = if acceptParModelicaGrammar() then '-lParModelicaExpl -lOpenCL' // else ""
let ExtraStack = if boolOr(stringEq(makefileParams.platform, "win32"),stringEq(makefileParams.platform, "win64")) then '--stack,16777216,'
let WinMingwExtraLibs = if boolAnd(acceptMetaModelicaGrammar(), boolOr(stringEq(makefileParams.platform, "win32"),stringEq(makefileParams.platform, "win64"))) then '-lOpenModelicaCompiler'
<<
# Makefile generated by OpenModelica
# Platform: <%makefileParams.platform%>
# Dynamic loading uses -O0 by default
SIM_OR_DYNLOAD_OPT_LEVEL=-O0
CC=<%if acceptParModelicaGrammar() then 'g++' else '<%makefileParams.ccompiler%>'%>
CXX=<%makefileParams.cxxcompiler%>
LINK=<%makefileParams.linker%>
EXEEXT=<%makefileParams.exeext%>
DLLEXT=<%makefileParams.dllext%>
DEBUG_FLAGS=<% if boolOr(acceptMetaModelicaGrammar(), Flags.isSet(Flags.GEN_DEBUG_SYMBOLS)) then " -g"%>
CFLAGS= $(DEBUG_FLAGS) <%makefileParams.cflags%>
CPPFLAGS= -I"<%makefileParams.omhome%>/include/omc/c" <%makefileParams.includes ; separator=" "%><%
if Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS) then " -DOMC_GENERATE_RELOCATABLE_CODE"
%>
LDFLAGS= -L"<%makefileParams.omhome%>/lib/<%Autoconf.triple%>/omc" -Wl,<%ExtraStack%>-rpath,'<%makefileParams.omhome%>/lib/<%Autoconf.triple%>/omc' <%ParModelicaExpLibs%> <%WinMingwExtraLibs%> <%makefileParams.ldflags%> <%makefileParams.runtimelibs%>
PERL=perl
MAINFILE=<%name%>.c
.PHONY: <%name%>
<%name%>: $(MAINFILE) <%name%>.h <%name%>_records.c
<%\t%> $(CC) $(CFLAGS) $(CPPFLAGS) -c -o <%name%>.o $(MAINFILE)
<%\t%> $(CC) $(CFLAGS) $(CPPFLAGS) -c -o <%name%>_records.o <%name%>_records.c
<%\t%> $(LINK) -o <%name%>$(DLLEXT) <%name%>.o <%name%>_records.o <%libsStr%> $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -lm
>>
end functionsMakefile;
template commonHeader(String filePrefix)
::=
<<
#include "meta/meta_modelica.h"
#include "util/modelica.h"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
<%if acceptParModelicaGrammar() then
<<
#include <ParModelica/explicit/openclrt/omc_ocl_interface.h>
>>
%>
>>
end commonHeader;
/* public */ template externalFunctionIncludes(list<String> includes)
"Generates external includes part in function files.
used in Compiler/Template/CodegenFMU.tpl"
::=
if includes then
<<
#ifdef __cplusplus
extern "C" {
#endif
<% (includes ;separator="\n") %>
#ifdef __cplusplus
}
#endif<%\n%>
>>
end externalFunctionIncludes;
template functionHeaders(list<Function> functions, Boolean isSimulation, Text &staticPrototypes)
"Generates function header part in function files."
::=
(functions |> fn => functionHeader(fn, false, isSimulation, staticPrototypes) ; separator="\n\n")
end functionHeaders;
template functionHeadersParModelica(String filePrefix, list<Function> functions)
"Generates the content of the C file for functions in the simulation case."
::=
<<
#ifndef <%makeC89Identifier(filePrefix)%>__H
#define <%makeC89Identifier(filePrefix)%>__H
//#include "helper.cl"
<%parallelFunctionHeadersImpl(functions)%>
#endif
<%\n%>
>>
/* adrpo: leave a newline at the end of file to get rid of the warning */
end functionHeadersParModelica;
template parallelFunctionHeadersImpl(list<Function> functions)
"Generates function header part in function files."
::=
(functions |> fn => parallelFunctionHeader(fn, false) ; separator="\n\n")
end parallelFunctionHeadersImpl;
template functionHeader(Function fn, Boolean inFunc, Boolean isSimulation, Text &staticPrototypes)
"Generates function header part in function files."
::=
match fn
case FUNCTION(__) then
<<
<%functionHeaderNormal(underscorePath(name), functionArguments, outVars, inFunc, visibility, false, isSimulation, staticPrototypes)%>
<%if not funcHasParallelInOutArrays(fn) then functionHeaderBoxed(underscorePath(name), functionArguments, outVars, inFunc, isBoxedFunction(fn), visibility, false, isSimulation, staticPrototypes)%>
>>
case KERNEL_FUNCTION(__) then
<<
<%functionHeaderKernelFunctionInterface(underscorePath(name), functionArguments, outVars)%>
>>
case EXTERNAL_FUNCTION(dynamicLoad=true) then
<<
<%functionHeaderNormal(underscorePath(name), funArgs, outVars, inFunc, visibility, true, isSimulation, staticPrototypes)%>
<%functionHeaderBoxed(underscorePath(name), funArgs, outVars, inFunc, isBoxedFunction(fn), visibility, true, isSimulation, staticPrototypes)%>
<%extFunDefDynamic(fn)%>
>>
case EXTERNAL_FUNCTION(__) then
<<
<%functionHeaderNormal(underscorePath(name), funArgs, outVars, inFunc, visibility, false, isSimulation, staticPrototypes)%>
<%functionHeaderBoxed(underscorePath(name), funArgs, outVars, inFunc, isBoxedFunction(fn), visibility, false, isSimulation, staticPrototypes)%>
<%extFunDef(fn)%>
>>
case RECORD_CONSTRUCTOR(__) then
let fname = underscorePath(name)
let funArgsStr = (funArgs |> var as VARIABLE(__) => ', <%varType(var)%> omc_<%crefStr(name)%>')
let vis = (match visibility case PUBLIC() then "DLLExport")
<<
<% if Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS)
then
<<
typedef <%fname%> (*omctd_<%fname%>)(threadData_t *threadData<%funArgsStr%>);
<%vis%>
omctd_<%fname%> omc_<%fname%>;
>>
else
<<
<%vis%>
<%fname%> omc_<%fname%> (threadData_t *threadData<%funArgsStr%>);
>>
%>
<%functionHeaderBoxed(fname, funArgs, boxedRecordOutVars, inFunc, false, visibility, false, isSimulation, staticPrototypes)%>
>>
end functionHeader;
template parallelFunctionHeader(Function fn, Boolean inFunc)
"Generates function header part in function files."
::=
match fn
case PARALLEL_FUNCTION(__) then
<<
<%functionHeaderParallelImpl(underscorePath(name), functionArguments, outVars, inFunc, false)%>;
>>
end parallelFunctionHeader;
template functionHeaderParallelImpl(String fname, list<Variable> fargs, list<Variable> outVars, Boolean inFunc, Boolean boxed)
"Generates parmodelica paralell function header part in kernels files."
::=
let fargsStr = (fargs |> var => funArgDefinitionKernelFunctionInterface(var) ;separator=", ")
// let &fargsStr += if outVars then ", " + (outVars |> var => tupleOutfunArgDefinitionKernelFunctionInterface(var) ;separator=", ")
// 'void omc_<%fname%>(<%fargsStr%>)'
match outVars
case {} then
'void omc_<%fname%>(<%fargsStr%>)'
case fvar::rest then
let rettype = varType(fvar)
let &fargsStr += if rest then ", " + (rest |> var => tupleOutfunArgDefinitionKernelFunctionInterface(var) ;separator=", ")
'<%rettype%> omc_<%fname%>(<%fargsStr%>)'
else
error(sourceInfo(), 'functionHeaderParallelImpl failed')
end functionHeaderParallelImpl;
template recordDeclaration(RecordDeclaration recDecl)
"Generates structs for a record declaration."
::=
match recDecl
case r as RECORD_DECL_FULL(__) then
<<
<%recordDefinition(dotPath(defPath),
underscorePath(defPath),
(variables |> VARIABLE(__) => '"<%crefStr(name)%>"' ;separator=","),
listLength(variables))%>
<%recordConstructorDef(r.name, r.name, r.variables)%>
<%recordCopyFromVarsDef(r.name, r.variables)%>
<%recordCopyDef(r.name, r.variables)%>
<%recordCopyToVarsDef(r.name, r.variables)%>
>>
case r as RECORD_DECL_ADD_CONSTRCTOR(__) then
<<
<%recordConstructorDef(r.ctor_name, r.name, r.variables)%>
>>
case r as RECORD_DECL_DEF(__) then
<<
<%recordDefinition(dotPath(r.path),
underscorePath(r.path),
(r.fieldNames |> fname => '"<%fname%>"' ;separator=","),
listLength(r.fieldNames))%>
>>
end recordDeclaration;
template recordDeclarationHeader(RecordDeclaration recDecl)
"Generates structs for a record declaration."
::=
match recDecl
case r as RECORD_DECL_FULL(__) then recordDeclarationFullHeader(r)
case r as RECORD_DECL_ADD_CONSTRCTOR(__) then recordDeclarationExtraCtor(r)
// TODO revise me
case r as RECORD_DECL_DEF(__) then 'extern struct record_description <%underscorePath(r.path)%>__desc;<%\n%>'
end recordDeclarationHeader;
template recordDeclarationExtraCtor(RecordDeclaration recDecl)
"Generates structs for a record declaration."
::=
match recDecl
case r as RECORD_DECL_ADD_CONSTRCTOR(__) then
let ctor_name = r.ctor_name
let rec_name = r.name
let ctor_macro_name = '<%ctor_name%>_construct'
let ctor_macro_additional_inputs = (r.variables |> var as VARIABLE(__) => if var.bind_from_outside
then (", " + "in_" + crefStr(var.name))
)
let ctor_func_name = '<%ctor_macro_name%>_p'
let ctor_additional_inputs = (r.variables |> var as VARIABLE(__) => if var.bind_from_outside
then (", " + varType(var) + " in_" + crefStr(var.name))
)
<<
void <%ctor_func_name%>(threadData_t *threadData, void* v_ths <%ctor_additional_inputs%>);
#define <%ctor_macro_name%>(td, ths <%ctor_macro_additional_inputs%>) <%ctor_func_name%>(td, &ths <%ctor_macro_additional_inputs%>)
#define alloc_<%ctor_name%>_array(dst,ndims,...) generic_array_create(NULL, dst, <%ctor_func_name%>, ndims, sizeof(<%rec_name%>), __VA_ARGS__)
>>
end recordDeclarationExtraCtor;
template recordDeclarationFullHeader(RecordDeclaration recDecl)
"Generates structs for a record declaration."
::=
match recDecl
case r as RECORD_DECL_FULL(__) then
let rec_name = r.name
let ctor_macro_name = '<%rec_name%>_construct'
let ctor_macro_additional_inputs = (r.variables |> var as VARIABLE(__) => if var.bind_from_outside
then (", " + "in_" + crefStr(var.name))
)
let ctor_func_name = '<%ctor_macro_name%>_p'
let ctor_additional_inputs = (r.variables |> var as VARIABLE(__) => if var.bind_from_outside
then (", " + varType(var) + " in_" + crefStr(var.name))
)
let cpy_macro_name = '<%rec_name%>_copy'
let cpy_func_name = '<%cpy_macro_name%>_p'
let copy_to_vars_name = '<%rec_name%>_copy_to_vars'
let copy_to_vars_name_p = '<%copy_to_vars_name%>_p'
let copy_to_vars_inputs = r.variables |> var as VARIABLE(__) => (", " + varType(var) + "* in_" + crefStr(var.name))
let modelica_ctor_name = 'omc_<%rec_name%>'
let modelica_ctor_inputs = r.variables |> var as VARIABLE(__) => (", " + varType(var) + " in_" + crefStr(var.name))
<<
<% match aliasName
case SOME(str) then 'typedef <%str%> <%rec_name%>;'
else <<
typedef struct {
<%r.variables |> var as VARIABLE(__) => '<%varType(var)%> _<%crefStr(var.name)%>;' ;separator="\n"%>
} <%rec_name%>;
>> %>
extern struct record_description <%underscorePath(r.defPath)%>__desc;
void <%ctor_func_name%>(threadData_t *threadData, void* v_ths <%ctor_additional_inputs%>);
#define <%ctor_macro_name%>(td, ths <%ctor_macro_additional_inputs%>) <%ctor_func_name%>(td, &ths <%ctor_macro_additional_inputs%>)
void <%cpy_func_name%>(void* v_src, void* v_dst);
#define <%cpy_macro_name%>(src,dst) <%cpy_func_name%>(&src, &dst)
// <%rec_name%> <%modelica_ctor_name%>(threadData_t *threadData <%modelica_ctor_inputs%>);
/* This function is used to copy a records members to simvars. Since simvars
have no structure yet we can not directly copy records. Insted we pass the
corresponding simvars to this function and then copy each element one by one.*/
void <%copy_to_vars_name_p%>(void* v_src <%copy_to_vars_inputs%>);
#define <%copy_to_vars_name%>(src,...) <%copy_to_vars_name_p%>(&src, __VA_ARGS__)
typedef base_array_t <%rec_name%>_array;
#define alloc_<%rec_name%>_array(dst,ndims,...) generic_array_create(NULL, dst, <%ctor_func_name%>, ndims, sizeof(<%rec_name%>), __VA_ARGS__)
#define <%rec_name%>_array_copy_data(src,dst) generic_array_copy_data(src, &dst, <%cpy_func_name%>, sizeof(<%rec_name%>))
// This is here unitl we remove all places where this function call is written out instead of the one above.
#define copy_<%rec_name%>_array_data(src,dst) generic_array_copy_data(src, &dst, <%cpy_func_name%>, sizeof(<%rec_name%>))
#define <%rec_name%>_array_alloc_copy(src,dst) generic_array_alloc_copy(src, &dst, <%cpy_func_name%>, sizeof(<%rec_name%>))
#define <%rec_name%>_array_get(src,ndims,...) (*(<%rec_name%>*)(generic_array_get(&src, sizeof(<%rec_name%>), __VA_ARGS__)))
#define <%rec_name%>_set(dst,val,...) generic_array_set(&dst, &val, <%cpy_func_name%>, sizeof(<%rec_name%>), __VA_ARGS__)
>>
end recordDeclarationFullHeader;
template recordCopyDef(String rec_name, list<Variable> variables)
"Generates structs for a record declaration."
::=
let &varCopies = buffer ""
let &auxFunction = buffer ""
let dst_pref = 'dst->'
let src_pref = 'src->'
let _ = (variables |> var => recordMemberCopy(var, src_pref, dst_pref, &varCopies, &auxFunction) ;separator="\n")
<<
void <%rec_name%>_copy_p(void* v_src, void* v_dst) {
<%rec_name%>* src = (<%rec_name%>*)(v_src);
<%rec_name%>* dst = (<%rec_name%>*)(v_dst);
<%varCopies%>
}
>>
end recordCopyDef;
template recordCopyFromVarsDef(String rec_name, list<Variable> variables)
"Generates structs for a record declaration."
::=
let &varCopies = buffer ""
let &auxFunction = buffer ""
let dst_pref = 'dst.'
let src_pref = ' in'
let _ = (variables |> var => recordMemberCopy(var, src_pref, dst_pref, &varCopies, &auxFunction) ;separator="\n")
let inputs = variables |> var as VARIABLE(__) => (", " + varType(var) + functionContextCref(var.name, contextFunction, src_pref, &auxFunction))
<<
/*
<%rec_name%> omc_<%rec_name%>(threadData_t *threadData <%inputs%>) {
<%rec_name%> dst;
// TODO Improve me. No need to initalize the record memebers with defaults in <%rec_name%>_construct
// We should just do the allocs here and then copy the input parameters as default values instead.
<%rec_name%>_construct(threadData, dst);
<%varCopies%>
return dst;
}
*/
>>
end recordCopyFromVarsDef;
template recordCopyToVarsDef(String rec_name, list<Variable> variables)
"Generates structs for a record declaration."
::=
let &varCopies = buffer ""
let &auxFunction = buffer ""
let dst_pref = ' *in'
let src_pref = 'src->'
let _ = (variables |> var => recordMemberCopy(var, src_pref, dst_pref, &varCopies, &auxFunction) ;separator="\n")
let inputs = variables |> var as VARIABLE(__) => (", " + varType(var) + functionContextCref(var.name, contextFunction, dst_pref, &auxFunction))
<<
void <%rec_name%>_copy_to_vars_p(void* v_src <%inputs%>) {
<%rec_name%>* src = (<%rec_name%>*)(v_src);
<%varCopies%>
}
>>
end recordCopyToVarsDef;
template recordMemberCopy(Variable var, String src_pref, String dst_pref, Text &varCopies, Text &auxFunction)
::=
match var
case var as VARIABLE(__) then
let dstName = functionContextCref(var.name, contextFunction, dst_pref, &auxFunction)
let srcName = functionContextCref(var.name, contextFunction, src_pref, &auxFunction)
match ty
case ty as T_ARRAY(__) then
let varType = expTypeShort(ty)
let &varCopies += '<%varType%>_array_copy_data(<%srcName%>, <%dstName%>);<%\n%>'
""
case ty as T_COMPLEX(complexClassType=RECORD(__)) then
let recType = expTypeShort(ty)
let &varCopies += '<%recType%>_copy(<%srcName%>, <%dstName%>);<%\n%>'
""
else
let &varCopies += '<%dstName%> = <%srcName%>;<%\n%>'
""
end match
end recordMemberCopy;
template recordConstructorDef(String ctor_name, String rec_name, list<Variable> variables)
"Generates structs for a record declaration."
::=
let &varDecls = buffer ""
let &auxFunction = buffer ""
let ctor_additional_inputs = (variables |> var as VARIABLE(__) => if var.bind_from_outside
then (", " + varType(var) + " in" + contextCref(var.name, contextFunction, &auxFunction))
)
let varInits = (variables |> var => recordMemberAllocInit(var, appendCurrentCrefPrefix(contextFunction, "ths->"), &varDecls, &auxFunction) /*;separator="\n"*/)
<<
void <%ctor_name%>_construct_p(threadData_t *threadData, void* v_ths <%ctor_additional_inputs%>) {
<%rec_name%>* ths = (<%rec_name%>*)(v_ths);
<%varDecls%>
<%varInits%>
}
>>
end recordConstructorDef;
template recordMemberAllocInit(Variable var, Context context, Text &varDecls, Text &auxFunction)
::=
match var
case var as VARIABLE(__) then
match var.ty
case ty as T_ARRAY(__) then arrayVarAllocInit(var.name, var.ty, ty.dims, var.value, var.bind_from_outside, context, &varDecls, &auxFunction)
case ty as T_COMPLEX(complexClassType=RECORD(__)) then recordVarAllocInit(var.value, var.name, var.bind_from_outside, var.ty, context, &varDecls, &auxFunction)
else simpleVarInit(var.value, var.name, var.bind_from_outside, context, &varDecls, &auxFunction)
end match
end recordMemberAllocInit;
template simpleVarInit(Option<Exp> value, ComponentRef var_cref, Boolean bind_outside, Context context, Text &varDecls, Text &auxFunction)
::=
let var_name = contextCref(var_cref, context, &auxFunction)
match value
case SOME(rhs_exp) then
let &preExp = buffer ""
let rhs = if bind_outside then "in" + contextCref(var_cref, contextFunction /*unprefixed context*/, &auxFunction)
else daeExp(rhs_exp, context, &preExp, &varDecls, &auxFunction)
<<
<%preExp%>
<%var_name%> = <%rhs%>;<%\n%>
>>
case NONE() then
'// <%var_name%> has no default value.<%\n%>'
end match
end simpleVarInit;
template recordVarAllocInit(Option<Exp> value, ComponentRef var_cref, Boolean bind_outside, Type var_type, Context context, Text &varDecls, Text &auxFunction)
::=
let &preExp = buffer ""
let &ctor_suffix = buffer ""
let type_name = expTypeShort(var_type)
let var_name = contextCref(var_cref, context, &auxFunction)
let ctor_additional_inputs = match var_type
case ty as DAE.T_COMPLEX() then
(ty.varLst |> sv hasindex i1 fromindex 1 =>
recordInitOutsideBindings(sv, i1, &ctor_suffix, context, &preExp, &varDecls, &auxFunction); empty /* increase the counter! */
)
end match
let allocation = '<%type_name%><%ctor_suffix%>_construct(threadData, <%var_name%><%ctor_additional_inputs%>);'
match value
case SOME(rhs_exp) then
let &preExp1 = buffer ""
let copy_stmt = if bind_outside then
let in_var_name = "in" + contextCref(var_cref, contextFunction /*unprefixed context*/, &auxFunction)
'<%type_name%>_copy(<%in_var_name%>, <%var_name%>);'
else
assignRhsExpToRecordCref(var_cref, rhs_exp, var_type, context, &preExp1, &varDecls, &auxFunction)
<<
<%preExp%>
<%allocation%>
<%preExp1%>
<%copy_stmt%>;
>>
case NONE() then
<<
<%preExp%>
<%allocation%> // <%var_name%> has no default value.<%\n%>
>>
end match
end recordVarAllocInit;
template recordInitOutsideBindings(Var subvar, Integer ix, Text& ctor_suffix, Context context, Text &preExp, Text &varDecls, Text &auxFunction)
::=
match subvar
case TYPES_VAR(binding=EQBOUND(exp=exp), bind_from_outside = true) then
let &ctor_suffix += "_" + ix
", " + daeExp(exp, context, &preExp, &varDecls, &auxFunction)
case TYPES_VAR(bind_from_outside = true) then
error(sourceInfo(), 'Record has binding from outside but found a non EQBOUND binding. Implement me.')
end match
end recordInitOutsideBindings;
template arrayVarAllocInit(ComponentRef var_cref, Type var_type, list<DAE.Dimension> var_dims, Option<DAE.Exp> value, Boolean bind_outside, Context context, Text &varDecls, Text &auxFunction)
::=
let type_name = expTypeShort(var_type)
let var_name = contextCref(var_cref, context, &auxFunction)
match value
case SOME(rhs_exp) then
let &preExpBind = buffer ""
let rhs = if bind_outside then "in" + contextCref(var_cref, contextFunction /*unprefixed context*/, &auxFunction)
else daeExp(rhs_exp, context, &preExpBind, &varDecls, &auxFunction)
if Expression.hasUnknownDims(var_dims) then
<<
<%preExpBind%>
<%type_name%>_array_alloc_copy(<%rhs%>, <%var_name%>);
>>
else
let &preExpAlloc = buffer ""
let dims_str = (var_dims |> dim => dimension(dim, context, &preExpAlloc, &varDecls, &auxFunction) ;separator=", ")
<<
<%preExpAlloc%>
alloc_<%type_name%>_array(&(<%var_name%>), <%listLength(var_dims)%>, <%dims_str%>);
<%preExpBind%>
<%type_name%>_array_copy_data(<%rhs%>, <%var_name%>);
>>
case NONE() then
if Expression.hasUnknownDims(var_dims) then
<<
generic_array_create_flexible(&<%var_name%>, <%listLength(var_dims)%>); // <%var_name%> has unknown size and no default value. It is flexible.<%\n%>
>>
else
let &preExpAlloc = buffer ""
let dims_str = (var_dims |> dim => dimension(dim, context, &preExpAlloc, &varDecls, &auxFunction) ;separator=", ")
<<
<%preExpAlloc%>
alloc_<%type_name%>_array(&(<%var_name%>), <%listLength(var_dims)%>, <%dims_str%>); // <%var_name%> has no default value.<%\n%>
>>
end match
end arrayVarAllocInit;
template recordDefinition(String origName, String encName, String fieldNames, Integer numFields)
"Generates the definition struct for a record declaration."
::=
match encName
case "SourceInfo_SOURCEINFO" then ''
else
/* adrpo: 2011-03-14 make MSVC happy, no arrays of 0 size! */
let fieldsDescription =
match numFields
case 0 then
'const char* <%encName%>__desc__fields[1] = {"no fields"};'
case _ then
'const char* <%encName%>__desc__fields[<%numFields%>] = {<%fieldNames%>};'
<<
#define <%encName%>__desc_added 1
<%fieldsDescription%>
struct record_description <%encName%>__desc = {
"<%encName%>", /* package_record__X */
"<%origName%>", /* package.record_X */
<%encName%>__desc__fields
};
>>
end recordDefinition;
template recordDefinitionHeader(String origName, String encName, Integer numFields)
"Generates the definition struct for a record declaration."
::=
<<
extern struct record_description <%encName%>__desc;
>>
end recordDefinitionHeader;
template functionHeaderNormal(String fname, list<Variable> fargs, list<Variable> outVars, Boolean inFunc, SCode.Visibility visibility, Boolean dynLoad, Boolean isSimulation, Text &staticPrototypes)
::=functionHeaderImpl(fname, fargs, outVars, inFunc, false, visibility, dynLoad, isSimulation, staticPrototypes)
end functionHeaderNormal;
template functionHeaderBoxed(String fname, list<Variable> fargs, list<Variable> outVars, Boolean inFunc, Boolean isBoxed, SCode.Visibility visibility, Boolean dynLoad, Boolean isSimulation, Text &staticPrototypes)
::=
let boxvar =
<<
static const MMC_DEFSTRUCTLIT(boxvar_lit_<%fname%>,2,0) {(void*) <%if Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS) then "&"%>boxptr_<%fname%>,0}};
#define boxvar_<%fname%> MMC_REFSTRUCTLIT(boxvar_lit_<%fname%>)<%\n%>
>>
<<
<%if isBoxed then '#define boxptr_<%fname%> omc_<%fname%><%\n%>' else functionHeaderImpl(fname, fargs, outVars, inFunc, true, visibility, dynLoad, isSimulation, staticPrototypes)%>
<% match visibility
case PROTECTED(__) then
let &staticPrototypes += (if boolOr(isSimulation, Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS)) then "" else boxvar)
if boolOr(isSimulation, Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS)) then '<%boxvar%> /* boxvar early */' else ""
else boxvar %>
>>
end functionHeaderBoxed;
template functionHeaderImpl(String fname, list<Variable> fargs, list<Variable> outVars, Boolean inFunc, Boolean boxed, SCode.Visibility visibility, Boolean dynamicLoad, Boolean isSimulation, Text &staticPrototypes)
"Generates function header for a Modelica/MetaModelica function. Generates a
boxed version of the header if boxed = true, otherwise a normal header"
::=
let &dummy = buffer ""
let prototype = functionPrototype(fname, fargs, outVars, boxed, visibility, isSimulation, true, dummy)
let inFnStr = if boolAnd(boxed,inFunc) then
<<
DLLExport
int in_<%fname%>(threadData_t *threadData, type_description * inArgs, type_description * outVar);
>>
match visibility
case PROTECTED(__) then
if boolOr(isSimulation, Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS)) then
if dynamicLoad then "" else '<%prototype%>;<%\n%>'
else
let &staticPrototypes += if dynamicLoad then "" else '<%prototype%>;<%\n%>'
inFnStr
else
<<
<%inFnStr%>
<%if dynamicLoad then '' else 'DLLExport<%\n%><%prototype%>;'%>
>>
end functionHeaderImpl;
template functionPrototype(String fname, list<Variable> fargs, list<Variable> outVars, Boolean boxed, SCode.Visibility visibility, Boolean isSimulation, Boolean isPrototype, Text &afterBody)
"Generates function header definition for a Modelica/MetaModelica function. Generates a boxed version of the header if boxed = true, otherwise a normal definition"
::=
let static = if isSimulation then "" else (match visibility case PROTECTED(__) then 'PROTECTED_FUNCTION_STATIC ')
let fargsStr = if boxed then
(fargs |> var => ", " + funArgBoxedDefinition(var) )
else
(fargs |> var => ", " + funArgDefinition(var) )
let outarg = (match outVars
case var::_ then (match var
case VARIABLE(__) then if boxed then varTypeBoxed(var) else varType(var)
case FUNCTION_PTR(__) then "modelica_fnptr")
else "void")
let boxPtrStr = if boxed then "boxptr" else "omc"
let fn_name = '<%boxPtrStr%>_<%fname%>'
let fn_name_impl = (if isPrototype then fn_name else '<%boxPtrStr%>impl_<%fname%>')
let fn_name_typedef = (if Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS) then '<%boxPtrStr%>td_<%fname%>' else fn_name)
let fn_name_ptr_typedef = (if Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS) then (if isPrototype then '(*<%fn_name_typedef%>)' else fn_name_impl) else fn_name)
let res = (if outVars then
let outargs = List.rest(outVars) |> var => ", " + (match var
case var as VARIABLE(__) then '<%if boxed then varTypeBoxed(var) else varType(var)%> *out<%funArgName(var)%>'
case FUNCTION_PTR(__) then 'modelica_fnptr *out<%funArgName(var)%>')
'<%outarg%> <%fn_name_ptr_typedef%>(threadData_t *threadData<%fargsStr%><%outargs%>)'
else
'void <%fn_name_ptr_typedef%>(threadData_t *threadData<%fargsStr%>)')
(if Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS) then
// No static functions for relocatable code...
(if isPrototype then
<<
typedef <%res%>;
<%fn_name_typedef%> <%fn_name%>
>>
else
let &afterBody += '<%fn_name_typedef%> <%fn_name%> = <%fn_name_impl%>;'
res)
else '<%static%><%res%>')
end functionPrototype;
template functionHeaderKernelFunctionInterface(String fname, list<Variable> fargs, list<Variable> outVars)
"Generates function header for a ParModelica Kernel function interface."
::=
'<%functionHeaderKernelFunctionInterfacePrototype(fname, fargs, outVars)%>;'
end functionHeaderKernelFunctionInterface;
template functionHeaderKernelFunctionInterfacePrototype(String fname, list<Variable> fargs, list<Variable> outVars)
"Generates function header for a ParModelica Kernel function interface."
::=
let fargsStr = 'threadData_t *threadData'
let &fargsStr += if fargs then ", " + (fargs |> var => funArgDefinitionKernelFunctionInterface(var) ;separator=", ")
// let &fargsStr += if outVars then ", " + (outVars |> var => tupleOutfunArgDefinitionKernelFunctionInterface(var) ;separator=", ")
// 'void omc_<%fname%>(<%fargsStr%>)'
match outVars
case {} then
'void omc_<%fname%>(<%fargsStr%>)'
case fvar::rest then
let rettype = varType(fvar)
let &fargsStr += if rest then ", " + (rest |> var => tupleOutfunArgDefinitionKernelFunctionInterface(var) ;separator=", ")
'<%rettype%> omc_<%fname%>(<%fargsStr%>)'
else
error(sourceInfo(), 'functionHeaderKernelFunctionInterfacePrototype failed')
end functionHeaderKernelFunctionInterfacePrototype;
template funArgName(Variable var)
::=
let &auxFunction = buffer ""
match var
case VARIABLE(__) then contextCref(name,contextFunction,&auxFunction)
case FUNCTION_PTR(__) then '_' + System.unquoteIdentifier(name)
end funArgName;
template funArgDefinition(Variable var)
::=
let &auxFunction = buffer ""
match var
case VARIABLE(__) then ('<%varType(var)%> <%contextCref(name,contextFunction,&auxFunction)%>' + (if var.instDims then " = {0}"))
case FUNCTION_PTR(__) then 'modelica_fnptr _<%System.unquoteIdentifier(name)%>'
end funArgDefinition;
template funArgDefinitionKernelFunctionInterface(Variable var)
::=
let &auxFunction = buffer ""
match var
case VARIABLE(__) then
'<%varType(var)%> <%funArgName(var)%>'
else error(sourceInfo(), 'funArgDefinitionKernelFunctionInterface : unsupported function argument type')
end funArgDefinitionKernelFunctionInterface;
template tupleOutfunArgDefinitionKernelFunctionInterface(Variable var)
::=
let &auxFunction = buffer ""
match var
case VARIABLE(__) then
'<%varType(var)%> *out<%funArgName(var)%>'
else error(sourceInfo(), 'tupleOutfunArgDefinitionKernelFunctionInterface : unsupported function argument type')
end tupleOutfunArgDefinitionKernelFunctionInterface;
template funArgDefinitionKernelFunctionBody(Variable var)
"Generates code to initialize variables.
Does not return anything: just appends declarations to buffers."
::=
let &auxFunction = buffer ""
match var
//function args will have nill instdims even if they are arrays. handled here
case var as VARIABLE(ty=T_ARRAY(__), parallelism = PARGLOBAL(__)) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
'__global modelica_<%expTypeShort(var.ty)%>* data_<%varName%>,<%\n%> __global modelica_integer* info_<%varName%>'
case var as VARIABLE(ty=T_ARRAY(__), parallelism = PARLOCAL(__)) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
'__local modelica_<%expTypeShort(var.ty)%>* data_<%varName%>,<%\n%> __local modelica_integer* info_<%varName%>'
case var as VARIABLE(__) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
if instDims then
(match parallelism
case PARGLOBAL(__) then
'__global modelica_<%expTypeShort(var.ty)%>* data_<%varName%>,<%\n%> __global modelica_integer* info_<%varName%>'
case PARLOCAL(__) then
'__local modelica_<%expTypeShort(var.ty)%>* data_<%varName%>,<%\n%> __local modelica_integer* info_<%varName%>'
)
else
'modelica_<%expTypeShort(var.ty)%> <%varName%>'
else '#error Unknown variable type in as function argument funArgDefinitionKernelFunctionBody<%\n%>'
end funArgDefinitionKernelFunctionBody;
template funArgDefinitionKernelFunctionBody2(Variable var, Text &parArgList /*BUFPA*/)
"Generates code to initialize variables.
Does not return anything: just appends declarations to buffers."
::=
let &auxFunction = buffer ""
match var
//function args will have nill instdims even if they are arrays. handled here
case var as VARIABLE(ty=T_ARRAY(__)) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
let &parArgList += ',<%\n%> __global modelica_<%expTypeShort(var.ty)%>* data_<%varName%>,'
let &parArgList += '<%\n%> __global modelica_integer* info_<%varName%>'
""
case var as VARIABLE(__) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
if instDims then
let &parArgList += ',<%\n%> __global modelica_<%expTypeShort(var.ty)%>* data_<%varName%>,'
let &parArgList += '<%\n%> __global modelica_integer* info_<%varName%>'
" "
else
let &parArgList += ',<%\n%> modelica_<%expTypeShort(var.ty)%> <%varName%>'
""
else let &parArgList += ' #error Unknown variable type in as function argument funArgDefinitionKernelFunctionBody2<%\n%>' ""
end funArgDefinitionKernelFunctionBody2;
template parFunArgDefinitionFromLooptupleVar(tuple<DAE.ComponentRef,builtin.SourceInfo> tupleVar)
::=
match tupleVar