This repository was archived by the owner on Mar 25, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathcodegen_cpp_visitor.cpp
More file actions
1775 lines (1477 loc) · 62.6 KB
/
Copy pathcodegen_cpp_visitor.cpp
File metadata and controls
1775 lines (1477 loc) · 62.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2023 Blue Brain Project, EPFL.
* See the top-level LICENSE file for details.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "codegen/codegen_cpp_visitor.hpp"
#include <filesystem>
#include "config/config.h"
#include "ast/all.hpp"
#include "codegen/codegen_helper_visitor.hpp"
#include "codegen/codegen_utils.hpp"
#include "utils/string_utils.hpp"
#include "visitors/defuse_analyze_visitor.hpp"
#include "visitors/rename_visitor.hpp"
#include "visitors/symtab_visitor.hpp"
#include "visitors/visitor_utils.hpp"
namespace nmodl {
namespace codegen {
using namespace ast;
using visitor::DefUseAnalyzeVisitor;
using visitor::DUState;
using visitor::RenameVisitor;
using visitor::SymtabVisitor;
using symtab::syminfo::NmodlType;
/****************************************************************************************/
/* Common helper routines accross codegen functions */
/****************************************************************************************/
bool CodegenCppVisitor::ion_variable_struct_required() const {
return optimize_ion_variable_copies() && info.ion_has_write_variable();
}
std::string CodegenCppVisitor::get_arg_str(const ParamVector& params) {
std::vector<std::string> variables;
for (const auto& param: params) {
variables.push_back(std::get<3>(param));
}
return fmt::format("{}", fmt::join(variables, ", "));
}
std::string CodegenCppVisitor::get_parameter_str(const ParamVector& params) {
std::vector<std::string> variables;
for (const auto& param: params) {
variables.push_back(fmt::format("{}{} {}{}",
std::get<0>(param),
std::get<1>(param),
std::get<2>(param),
std::get<3>(param)));
}
return fmt::format("{}", fmt::join(variables, ", "));
}
template <typename T>
bool CodegenCppVisitor::has_parameter_of_name(const T& node, const std::string& name) {
auto parameters = node->get_parameters();
return std::any_of(parameters.begin(),
parameters.end(),
[&name](const decltype(*parameters.begin()) arg) {
return arg->get_node_name() == name;
});
}
std::string CodegenCppVisitor::table_update_function_name(const std::string& block_name) const {
return "update_table_" + method_name(block_name);
}
/**
* \details Certain statements like unit, comment, solve can/need to be skipped
* during code generation. Note that solve block is wrapped in expression
* statement and hence we have to check inner expression. It's also true
* for the initial block defined inside net receive block.
*/
bool CodegenCppVisitor::statement_to_skip(const Statement& node) {
// clang-format off
if (node.is_unit_state()
|| node.is_line_comment()
|| node.is_block_comment()
|| node.is_solve_block()
|| node.is_conductance_hint()
|| node.is_table_statement()) {
return true;
}
// clang-format on
if (node.is_expression_statement()) {
auto expression = dynamic_cast<const ExpressionStatement*>(&node)->get_expression();
if (expression->is_solve_block()) {
return true;
}
if (expression->is_initial_block()) {
return true;
}
}
return false;
}
bool CodegenCppVisitor::net_send_buffer_required() const noexcept {
if (net_receive_required() && !info.artificial_cell) {
if (info.net_event_used || info.net_send_used || info.is_watch_used()) {
return true;
}
}
return false;
}
bool CodegenCppVisitor::net_receive_buffering_required() const noexcept {
return info.point_process && !info.artificial_cell && info.net_receive_node != nullptr;
}
bool CodegenCppVisitor::nrn_state_required() const noexcept {
if (info.artificial_cell) {
return false;
}
return info.nrn_state_block != nullptr || breakpoint_exist();
}
bool CodegenCppVisitor::nrn_cur_required() const noexcept {
return info.breakpoint_node != nullptr && !info.currents.empty();
}
bool CodegenCppVisitor::net_receive_exist() const noexcept {
return info.net_receive_node != nullptr;
}
bool CodegenCppVisitor::breakpoint_exist() const noexcept {
return info.breakpoint_node != nullptr;
}
bool CodegenCppVisitor::net_receive_required() const noexcept {
return net_receive_exist();
}
/**
* \details When floating point data type is not default (i.e. double) then we
* have to copy old array to new type (for range variables).
*/
bool CodegenCppVisitor::range_variable_setup_required() const noexcept {
return codegen::naming::DEFAULT_FLOAT_TYPE != float_data_type();
}
// check if there is a function or procedure defined with given name
bool CodegenCppVisitor::defined_method(const std::string& name) const {
const auto& function = program_symtab->lookup(name);
auto properties = NmodlType::function_block | NmodlType::procedure_block;
return function && function->has_any_property(properties);
}
bool CodegenCppVisitor::is_function_table_call(const std::string& name) const {
auto it = std::find_if(info.function_tables.begin(),
info.function_tables.end(),
[name](const auto& node) { return node->get_node_name() == name; });
return it != info.function_tables.end();
}
int CodegenCppVisitor::float_variables_size() const {
int n_floats = 0;
for (const auto& var: codegen_float_variables) {
n_floats += var->get_length();
}
return n_floats;
}
int CodegenCppVisitor::int_variables_size() const {
const auto count_semantics = [](int sum, const IndexSemantics& sem) { return sum += sem.size; };
return std::accumulate(info.semantics.begin(), info.semantics.end(), 0, count_semantics);
}
/**
* \details We can directly print value but if user specify value as integer then
* then it gets printed as an integer. To avoid this, we use below wrapper.
* If user has provided integer then it gets printed as 1.0 (similar to mod2c
* and neuron where ".0" is appended). Otherwise we print double variables as
* they are represented in the mod file by user. If the value is in scientific
* representation (1e+20, 1E-15) then keep it as it is.
*/
std::string CodegenCppVisitor::format_double_string(const std::string& s_value) {
return utils::format_double_string(s_value);
}
std::string CodegenCppVisitor::format_float_string(const std::string& s_value) {
return utils::format_float_string(s_value);
}
/**
* \details Statements like if, else etc. don't need semicolon at the end.
* (Note that it's valid to have "extraneous" semicolon). Also, statement
* block can appear as statement using expression statement which need to
* be inspected.
*/
bool CodegenCppVisitor::need_semicolon(const Statement& node) {
// clang-format off
if (node.is_if_statement()
|| node.is_else_if_statement()
|| node.is_else_statement()
|| node.is_from_statement()
|| node.is_verbatim()
|| node.is_conductance_hint()
|| node.is_while_statement()
|| node.is_protect_statement()
|| node.is_mutex_lock()
|| node.is_mutex_unlock()) {
return false;
}
if (node.is_expression_statement()) {
auto expression = dynamic_cast<const ExpressionStatement&>(node).get_expression();
if (expression->is_statement_block()
|| expression->is_eigen_newton_solver_block()
|| expression->is_eigen_linear_solver_block()
|| expression->is_solution_expression()
|| expression->is_for_netcon()) {
return false;
}
}
// clang-format on
return true;
}
/**
* \details Depending upon the block type, we have to print read/write ion variables
* during code generation. Depending on block/procedure being printed, this
* method return statements as vector. As different code backends could have
* different variable names, we rely on backend-specific read_ion_variable_name
* and write_ion_variable_name method which will be overloaded.
*/
std::vector<std::string> CodegenCppVisitor::ion_read_statements(BlockType type) const {
if (optimize_ion_variable_copies()) {
return ion_read_statements_optimized(type);
}
std::vector<std::string> statements;
for (const auto& ion: info.ions) {
auto name = ion.name;
for (const auto& var: ion.reads) {
auto const iter = std::find(ion.implicit_reads.begin(), ion.implicit_reads.end(), var);
if (iter != ion.implicit_reads.end()) {
continue;
}
auto variable_names = read_ion_variable_name(var);
auto first = get_variable_name(variable_names.first);
auto second = get_variable_name(variable_names.second);
statements.push_back(fmt::format("{} = {};", first, second));
}
for (const auto& var: ion.writes) {
if (ion.is_ionic_conc(var)) {
auto variables = read_ion_variable_name(var);
auto first = get_variable_name(variables.first);
auto second = get_variable_name(variables.second);
statements.push_back(fmt::format("{} = {};", first, second));
}
}
}
return statements;
}
std::vector<std::string> CodegenCppVisitor::ion_read_statements_optimized(BlockType type) const {
std::vector<std::string> statements;
for (const auto& ion: info.ions) {
for (const auto& var: ion.writes) {
if (ion.is_ionic_conc(var)) {
auto variables = read_ion_variable_name(var);
auto first = "ionvar." + variables.first;
const auto& second = get_variable_name(variables.second);
statements.push_back(fmt::format("{} = {};", first, second));
}
}
}
return statements;
}
// NOLINTNEXTLINE(readability-function-cognitive-complexity)
std::vector<ShadowUseStatement> CodegenCppVisitor::ion_write_statements(BlockType type) {
std::vector<ShadowUseStatement> statements;
for (const auto& ion: info.ions) {
std::string concentration;
for (const auto& var: ion.writes) {
auto variable_names = write_ion_variable_name(var);
if (ion.is_ionic_current(var)) {
if (type == BlockType::Equation) {
auto current = breakpoint_current(var);
auto lhs = variable_names.first;
auto op = "+=";
auto rhs = get_variable_name(current);
if (info.point_process) {
auto area = get_variable_name(naming::NODE_AREA_VARIABLE);
rhs += fmt::format("*(1.e2/{})", area);
}
statements.push_back(ShadowUseStatement{lhs, op, rhs});
}
} else {
if (!ion.is_rev_potential(var)) {
concentration = var;
}
auto lhs = variable_names.first;
auto op = "=";
auto rhs = get_variable_name(variable_names.second);
statements.push_back(ShadowUseStatement{lhs, op, rhs});
}
}
if (type == BlockType::Initial && !concentration.empty()) {
append_conc_write_statements(statements, ion, concentration);
}
}
return statements;
}
/**
* If mechanisms dependency level execution is enabled then certain updates
* like ionic current contributions needs to be atomically updated. In this
* case we first update current mechanism's shadow vector and then add statement
* to queue that will be used in reduction queue.
*/
std::string CodegenCppVisitor::process_shadow_update_statement(const ShadowUseStatement& statement,
BlockType /* type */) {
// when there is no operator or rhs then that statement doesn't need shadow update
if (statement.op.empty() && statement.rhs.empty()) {
auto text = statement.lhs + ";";
return text;
}
// return regular statement
auto lhs = get_variable_name(statement.lhs);
auto text = fmt::format("{} {} {};", lhs, statement.op, statement.rhs);
return text;
}
/**
* \details Current variable used in breakpoint block could be local variable.
* In this case, neuron has already renamed the variable name by prepending
* "_l". In our implementation, the variable could have been renamed by
* one of the pass. And hence, we search all local variables and check if
* the variable is renamed. Note that we have to look into the symbol table
* of statement block and not breakpoint.
*/
std::string CodegenCppVisitor::breakpoint_current(std::string current) const {
auto breakpoint = info.breakpoint_node;
if (breakpoint == nullptr) {
return current;
}
auto symtab = breakpoint->get_statement_block()->get_symbol_table();
auto variables = symtab->get_variables_with_properties(NmodlType::local_var);
for (const auto& var: variables) {
auto renamed_name = var->get_name();
auto original_name = var->get_original_name();
if (current == original_name) {
current = renamed_name;
break;
}
}
return current;
}
/**
* \details Depending programming model and compiler, we print compiler hint
* for parallelization. For example:
*
* \code
* #pragma omp simd
* for(int id = 0; id < nodecount; id++) {
*
* #pragma acc parallel loop
* for(int id = 0; id < nodecount; id++) {
* \endcode
*/
void CodegenCppVisitor::print_parallel_iteration_hint(BlockType /* type */,
const ast::Block* block) {
// ivdep allows SIMD parallelisation of a block/loop but doesn't provide
// a standard mechanism for atomics. Also, even with openmp 5.0, openmp
// atomics do not enable vectorisation under "omp simd" (gives compiler
// error with gcc < 9 if atomic and simd pragmas are nested). So, emit
// ivdep/simd pragma when no MUTEXLOCK/MUTEXUNLOCK/PROTECT statements
// are used in the given block.
std::vector<std::shared_ptr<const ast::Ast>> nodes;
if (block) {
nodes = collect_nodes(*block,
{ast::AstNodeType::PROTECT_STATEMENT,
ast::AstNodeType::MUTEX_LOCK,
ast::AstNodeType::MUTEX_UNLOCK});
}
if (nodes.empty()) {
printer->add_line("#pragma omp simd");
printer->add_line("#pragma ivdep");
}
}
/****************************************************************************************/
/* Routines for returning variable name */
/****************************************************************************************/
std::string CodegenCppVisitor::update_if_ion_variable_name(const std::string& name) const {
std::string result(name);
if (ion_variable_struct_required()) {
if (info.is_ion_read_variable(name)) {
result = naming::ION_VARNAME_PREFIX + name;
}
if (info.is_ion_write_variable(name)) {
result = "ionvar." + name;
}
if (info.is_current(name)) {
result = "ionvar." + name;
}
}
return result;
}
std::pair<std::string, std::string> CodegenCppVisitor::read_ion_variable_name(
const std::string& name) {
return {name, naming::ION_VARNAME_PREFIX + name};
}
std::pair<std::string, std::string> CodegenCppVisitor::write_ion_variable_name(
const std::string& name) {
return {naming::ION_VARNAME_PREFIX + name, name};
}
int CodegenCppVisitor::get_int_variable_index(const std::string& var_name) {
return get_index_from_name(codegen_int_variables, var_name);
}
/****************************************************************************************/
/* Main printing routines for code generation */
/****************************************************************************************/
void CodegenCppVisitor::print_backend_info() {
time_t current_time{};
time(¤t_time);
std::string data_time_str{std::ctime(¤t_time)};
auto version = nmodl::Version::NMODL_VERSION + " [" + nmodl::Version::GIT_REVISION + "]";
printer->add_line("/*********************************************************");
printer->add_line("Model Name : ", info.mod_suffix);
printer->add_line("Filename : ", info.mod_file, ".mod");
printer->add_line("NMODL Version : ", nmodl_version());
printer->fmt_line("Vectorized : {}", info.vectorize);
printer->fmt_line("Threadsafe : {}", info.thread_safe);
printer->add_line("Created : ", stringutils::trim(data_time_str));
printer->add_line("Simulator : ", simulator_name());
printer->add_line("Backend : ", backend_name());
printer->add_line("NMODL Compiler : ", version);
printer->add_line("*********************************************************/");
}
void CodegenCppVisitor::print_global_struct_function_table_ptrs() {
for (const auto& f: info.function_tables) {
printer->fmt_line("void* _ptable_{}{{}};", f->get_node_name());
codegen_global_variables.push_back(make_symbol("_ptable_" + f->get_node_name()));
}
}
void CodegenCppVisitor::print_global_var_struct_assertions() const {
// Assert some things that we assume when copying instances of this struct
// to the GPU and so on.
printer->fmt_line("static_assert(std::is_trivially_copy_constructible_v<{}>);",
global_struct());
printer->fmt_line("static_assert(std::is_trivially_move_constructible_v<{}>);",
global_struct());
printer->fmt_line("static_assert(std::is_trivially_copy_assignable_v<{}>);", global_struct());
printer->fmt_line("static_assert(std::is_trivially_move_assignable_v<{}>);", global_struct());
printer->fmt_line("static_assert(std::is_trivially_destructible_v<{}>);", global_struct());
}
void CodegenCppVisitor::print_global_var_struct_decl() {
printer->fmt_line("static {} {};", global_struct(), global_struct_instance());
}
void CodegenCppVisitor::print_function_call(const FunctionCall& node) {
const auto& name = node.get_node_name();
// return C++ function name for RANDOM construct function
// e.g. nrnran123_negexp for random_negexp
auto get_renamed_random_function =
[&](const std::string& name) -> std::pair<std::string, bool> {
if (codegen::naming::RANDOM_FUNCTIONS_MAPPING.count(name)) {
return {codegen::naming::RANDOM_FUNCTIONS_MAPPING[name], true};
}
return {name, false};
};
auto [function_name, is_random_function] = get_renamed_random_function(name);
if (defined_method(name)) {
function_name = method_name(name);
}
if (is_nrn_pointing(name)) {
print_nrn_pointing(node);
return;
}
if (is_net_send(name)) {
print_net_send_call(node);
return;
}
if (is_net_move(name)) {
print_net_move_call(node);
return;
}
if (is_net_event(name)) {
print_net_event_call(node);
return;
}
if (is_function_table_call(name)) {
print_function_table_call(node);
return;
}
const auto& arguments = node.get_arguments();
printer->add_text(function_name, '(');
if (defined_method(name)) {
auto internal_args = internal_method_arguments();
printer->add_text(internal_args);
if (!arguments.empty() && !internal_args.empty()) {
printer->add_text(", ");
}
}
print_vector_elements(arguments, ", ");
printer->add_text(')');
}
void CodegenCppVisitor::print_nrn_pointing(const ast::FunctionCall& node) {
printer->add_text("nrn_pointing(&");
print_vector_elements(node.get_arguments(), ", ");
printer->add_text(")");
}
void CodegenCppVisitor::print_procedure(const ast::ProcedureBlock& node) {
print_function_procedure_helper(node);
}
void CodegenCppVisitor::print_function(const ast::FunctionBlock& node) {
auto name = node.get_node_name();
// name of return variable
std::string return_var;
if (info.function_uses_table(name)) {
return_var = "ret_f_" + name;
} else {
return_var = "ret_" + name;
}
// first rename return variable name
auto block = node.get_statement_block().get();
RenameVisitor v(name, return_var);
block->accept(v);
print_function_procedure_helper(node);
}
void CodegenCppVisitor::print_function_tables(const ast::FunctionTableBlock& node) {
auto name = node.get_node_name();
const auto& p = node.get_parameters();
auto [params, table_params] = function_table_parameters(node);
printer->fmt_push_block("double {}({})", method_name(name), get_parameter_str(params));
printer->fmt_line("double _arg[{}];", p.size());
for (size_t i = 0; i < p.size(); ++i) {
printer->fmt_line("_arg[{}] = {};", i, p[i]->get_node_name());
}
printer->fmt_line("return hoc_func_table({}, {}, _arg);",
get_variable_name(std::string("_ptable_" + name), true),
p.size());
printer->pop_block();
printer->fmt_push_block("double table_{}({})",
method_name(name),
get_parameter_str(table_params));
printer->fmt_line("hoc_spec_table(&{}, {});",
get_variable_name(std::string("_ptable_" + name)),
p.size());
printer->add_line("return 0.;");
printer->pop_block();
}
void CodegenCppVisitor::print_prcellstate_macros() const {
printer->add_line("#ifndef NRN_PRCELLSTATE");
printer->add_line("#define NRN_PRCELLSTATE 0");
printer->add_line("#endif");
}
void CodegenCppVisitor::print_mechanism_info() {
auto variable_printer = [&](const std::vector<SymbolType>& variables) {
for (const auto& v: variables) {
auto name = v->get_name();
if (!info.point_process) {
name += "_" + info.mod_suffix;
}
if (v->is_array()) {
name += fmt::format("[{}]", v->get_length());
}
printer->add_line(add_escape_quote(name), ",");
}
};
printer->add_newline(2);
printer->add_line("/** channel information */");
printer->fmt_line("static const char *{}[] = {{", get_channel_info_var_name());
printer->increase_indent();
printer->add_line(add_escape_quote(nmodl_version()), ",");
printer->add_line(add_escape_quote(info.mod_suffix), ",");
variable_printer(info.range_parameter_vars);
printer->add_line("0,");
variable_printer(info.range_assigned_vars);
printer->add_line("0,");
variable_printer(info.range_state_vars);
printer->add_line("0,");
variable_printer(info.pointer_variables);
printer->add_line("0");
printer->decrease_indent();
printer->add_line("};");
}
void CodegenCppVisitor::print_using_namespace() {
printer->fmt_line("using namespace {};", namespace_name());
}
void CodegenCppVisitor::print_namespace_start() {
printer->add_newline(2);
printer->fmt_push_block("namespace {}", namespace_name());
}
void CodegenCppVisitor::print_namespace_stop() {
printer->pop_block();
}
void CodegenCppVisitor::print_top_verbatim_blocks() {
if (info.top_verbatim_blocks.empty()) {
return;
}
print_namespace_stop();
printer->add_newline(2);
print_using_namespace();
printing_top_verbatim_blocks = true;
for (const auto& block: info.top_verbatim_blocks) {
printer->add_newline(2);
block->accept(*this);
}
printing_top_verbatim_blocks = false;
print_namespace_start();
}
/****************************************************************************************/
/* Printing routines for code generation */
/****************************************************************************************/
void CodegenCppVisitor::print_statement_block(const ast::StatementBlock& node,
bool open_brace,
bool close_brace) {
if (open_brace) {
printer->push_block();
}
const auto& statements = node.get_statements();
for (const auto& statement: statements) {
if (statement_to_skip(*statement)) {
continue;
}
/// not necessary to add indent for verbatim block (pretty-printing)
if (!statement->is_verbatim() && !statement->is_mutex_lock() &&
!statement->is_mutex_unlock() && !statement->is_protect_statement()) {
printer->add_indent();
}
statement->accept(*this);
if (need_semicolon(*statement)) {
printer->add_text(';');
}
if (!statement->is_mutex_lock() && !statement->is_mutex_unlock()) {
printer->add_newline();
}
}
if (close_brace) {
printer->pop_block_nl(0);
}
}
bool CodegenCppVisitor::is_functor_const(const ast::StatementBlock& variable_block,
const ast::StatementBlock& functor_block) {
// Create complete_block with both variable declarations (done in variable_block) and solver
// part (done in functor_block) to be able to run the SymtabVisitor and DefUseAnalyzeVisitor
// then and get the proper DUChains for the variables defined in the variable_block
ast::StatementBlock complete_block(functor_block);
// Typically variable_block has only one statement, a statement containing the declaration
// of the local variables
for (const auto& statement: variable_block.get_statements()) {
complete_block.insert_statement(complete_block.get_statements().begin(), statement);
}
// Create Symbol Table for complete_block
auto model_symbol_table = std::make_shared<symtab::ModelSymbolTable>();
SymtabVisitor(model_symbol_table.get()).visit_statement_block(complete_block);
// Initialize DefUseAnalyzeVisitor to generate the DUChains for the variables defined in the
// variable_block
DefUseAnalyzeVisitor v(*complete_block.get_symbol_table());
// Check the DUChains for all the variables in the variable_block
// If variable is defined in complete_block don't add const quilifier in operator()
auto is_functor_const = true;
const auto& variables = collect_nodes(variable_block, {ast::AstNodeType::LOCAL_VAR});
for (const auto& variable: variables) {
const auto& chain = v.analyze(complete_block, variable->get_node_name());
is_functor_const = !(chain.eval() == DUState::D || chain.eval() == DUState::LD ||
chain.eval() == DUState::CD);
if (!is_functor_const) {
break;
}
}
return is_functor_const;
}
void CodegenCppVisitor::print_functors_definitions() {
for (const auto& functor_name: info.functor_names) {
printer->add_newline(2);
print_functor_definition(*functor_name.first);
}
}
void CodegenCppVisitor::print_functor_definition(const ast::EigenNewtonSolverBlock& node) {
// functor that evaluates F(X) and J(X) for
// Newton solver
auto float_type = default_float_data_type();
int N = node.get_n_state_vars()->get_value();
const auto functor_name = info.functor_names[&node];
printer->fmt_push_block("struct {}", functor_name);
auto params = functor_params();
for (const auto& param: params) {
printer->fmt_line("{}{} {};", std::get<0>(param), std::get<1>(param), std::get<3>(param));
}
if (ion_variable_struct_required()) {
print_ion_variable();
}
print_statement_block(*node.get_variable_block(), false, false);
printer->add_newline();
printer->push_block("void initialize()");
print_statement_block(*node.get_initialize_block(), false, false);
printer->pop_block();
printer->add_newline();
printer->fmt_line("{}({})", functor_name, get_parameter_str(params));
printer->increase_indent();
auto initializers = std::vector<std::string>();
for (const auto& param: params) {
initializers.push_back(fmt::format("{0}({0})", std::get<3>(param)));
}
printer->add_multi_line(": " + fmt::format("{}", fmt::join(initializers, ", ")));
printer->decrease_indent();
printer->add_line("{}");
printer->add_indent();
const auto& variable_block = *node.get_variable_block();
const auto& functor_block = *node.get_functor_block();
printer->fmt_text(
"void operator()(const Eigen::Matrix<{0}, {1}, 1>& nmodl_eigen_xm, Eigen::Matrix<{0}, {1}, "
"1>& nmodl_eigen_dxm, Eigen::Matrix<{0}, {1}, "
"1>& nmodl_eigen_fm, "
"Eigen::Matrix<{0}, {1}, {1}>& nmodl_eigen_jm) {2}",
float_type,
N,
is_functor_const(variable_block, functor_block) ? "const " : "");
printer->push_block();
printer->fmt_line("const {}* nmodl_eigen_x = nmodl_eigen_xm.data();", float_type);
printer->fmt_line("{}* nmodl_eigen_dx = nmodl_eigen_dxm.data();", float_type);
printer->fmt_line("{}* nmodl_eigen_j = nmodl_eigen_jm.data();", float_type);
printer->fmt_line("{}* nmodl_eigen_f = nmodl_eigen_fm.data();", float_type);
for (size_t i = 0; i < N; ++i) {
printer->fmt_line(
"nmodl_eigen_dx[{0}] = std::max(1e-6, 0.02*std::fabs(nmodl_eigen_x[{0}]));", i);
}
print_statement_block(functor_block, false, false);
printer->pop_block();
printer->add_newline();
// assign newton solver results in matrix X to state vars
printer->push_block("void finalize()");
print_statement_block(*node.get_finalize_block(), false, false);
printer->pop_block();
printer->pop_block(";");
}
void CodegenCppVisitor::print_eigen_linear_solver(const std::string& float_type, int N) {
if (N <= 4) {
// Faster compared to LU, given the template specialization in Eigen.
printer->add_multi_line(R"CODE(
bool invertible;
nmodl_eigen_jm.computeInverseWithCheck(nmodl_eigen_jm_inv,invertible);
nmodl_eigen_xm = nmodl_eigen_jm_inv*nmodl_eigen_fm;
if (!invertible) assert(false && "Singular or ill-conditioned matrix (Eigen::inverse)!");
)CODE");
} else {
// In Eigen the default storage order is ColMajor.
// Crout's implementation requires matrices stored in RowMajor order (C++-style arrays).
// Therefore, the transposeInPlace is critical such that the data() method to give the rows
// instead of the columns.
printer->add_line("if (!nmodl_eigen_jm.IsRowMajor) nmodl_eigen_jm.transposeInPlace();");
// pivot vector
printer->fmt_line("Eigen::Matrix<int, {}, 1> pivot;", N);
printer->fmt_line("Eigen::Matrix<{0}, {1}, 1> rowmax;", float_type, N);
// In-place LU-Decomposition (Crout Algo) : Jm is replaced by its LU-decomposition
printer->fmt_line(
"if (nmodl::crout::Crout<{0}>({1}, nmodl_eigen_jm.data(), pivot.data(), rowmax.data()) "
"< 0) assert(false && \"Singular or ill-conditioned matrix (nmodl::crout)!\");",
float_type,
N);
// Solve the linear system : Forward/Backward substitution part
printer->fmt_line(
"nmodl::crout::solveCrout<{0}>({1}, nmodl_eigen_jm.data(), nmodl_eigen_fm.data(), "
"nmodl_eigen_xm.data(), pivot.data());",
float_type,
N);
}
}
/****************************************************************************************/
/* Main code printing entry points */
/****************************************************************************************/
/**
* NMODL constants from unit database
*
*/
void CodegenCppVisitor::print_nmodl_constants() {
if (!info.factor_definitions.empty()) {
printer->add_newline(2);
printer->add_line("/** constants used in nmodl from UNITS */");
for (const auto& it: info.factor_definitions) {
const std::string format_string = "static const double {} = {};";
printer->fmt_line(format_string, it->get_node_name(), it->get_value()->get_value());
}
}
}
/****************************************************************************************/
/* Overloaded visitor routines */
/****************************************************************************************/
extern const std::regex regex_special_chars{R"([-[\]{}()*+?.,\^$|#\s])"};
void CodegenCppVisitor::visit_string(const String& node) {
std::string name = node.eval();
if (enable_variable_name_lookup) {
name = get_variable_name(name);
}
printer->add_text(name);
}
void CodegenCppVisitor::visit_integer(const Integer& node) {
const auto& value = node.get_value();
printer->add_text(std::to_string(value));
}
void CodegenCppVisitor::visit_float(const Float& node) {
printer->add_text(format_float_string(node.get_value()));
}
void CodegenCppVisitor::visit_double(const Double& node) {
printer->add_text(format_double_string(node.get_value()));
}
void CodegenCppVisitor::visit_boolean(const Boolean& node) {
printer->add_text(std::to_string(static_cast<int>(node.eval())));
}
void CodegenCppVisitor::visit_name(const Name& node) {
node.visit_children(*this);
}
void CodegenCppVisitor::visit_unit(const ast::Unit& node) {
// do not print units
}
void CodegenCppVisitor::visit_prime_name(const PrimeName& /* node */) {
throw std::runtime_error("PRIME encountered during code generation, ODEs not solved?");
}
/**
* \todo : Validate how @ is being handled in neuron implementation
*/
void CodegenCppVisitor::visit_var_name(const VarName& node) {
const auto& name = node.get_name();
const auto& at_index = node.get_at();
const auto& index = node.get_index();
name->accept(*this);
if (at_index) {
printer->add_text("@");
at_index->accept(*this);
}
if (index) {
printer->add_text("[");
printer->add_text("static_cast<int>(");
index->accept(*this);
printer->add_text(")");
printer->add_text("]");
}
}
void CodegenCppVisitor::visit_indexed_name(const IndexedName& node) {
node.get_name()->accept(*this);
printer->add_text("[");
printer->add_text("static_cast<int>(");
node.get_length()->accept(*this);
printer->add_text(")");
printer->add_text("]");
}
void CodegenCppVisitor::visit_local_list_statement(const LocalListStatement& node) {
printer->add_text(local_var_type(), ' ');
print_vector_elements(node.get_variables(), ", ");
}
void CodegenCppVisitor::visit_if_statement(const IfStatement& node) {
printer->add_text("if (");
node.get_condition()->accept(*this);