﻿id	summary	reporter	owner	description	type	status	priority	milestone	component	version	resolution	keywords	cc
5036	Better code generation for constant arrays	Per Östlund	Lennart Ochel	"There are two issues in the code generation that together creates problems for the new frontend.

The first issue is that constants in the DAE are not handled by the code generation. They are added to the SimCode structure, but then it seems they're mostly ignored by the code generation. This can be seen by changing:
{{{#!mo
if replaceConstants and node_var <= Variability.STRUCTURAL_PARAMETER then
}}}
to:
{{{#!mo
if replaceConstants and variability <= Variability.STRUCTURAL_PARAMETER then
}}}
in NFTyping.typeCrefExp, which will revert the NF to the old behaviour of only evaluating constants if their subscripts are also constant. Running this script will then return garbage results for `y`:
{{{#!mo
loadString(""
model M
  constant Real x[3] = {1, 2, 3};
  parameter Integer i = 2;
  Real y = x[i];
end M;
"");

simulate(M);
readSimulationResult(""M_res.mat"", y);
}}}
The code generated in `M.c` is:
{{{#!c
data->localData[0]->realVars[0] /* y variable */ =
  (&data->localData[0]->realVars[0] /* x[1] CONST */)[calc_base_index_dims_subs(1, 3, (modelica_integer)data->simulationInfo->integerParameter[0])];
}}}
Note how `data->localData[0]->realVars[0]` is used for both `y` and `x`. There doesn't seem to be any code generated for `x` at all.

The second issue is that the code generation for ASUB sometimes decides that the result of the ASUB must be a scalar. This can currently be seen in e.g. [https://libraries.openmodelica.org/branches/newInst/ModelicaTest_trunk/files/ModelicaTest_trunk_ModelicaTest.Blocks.Continuous.err ModelicaTest.Blocks.Continuous]. The old frontend seems to be aware of that and doesn't evaluate constants that would cause that issue, but then you run into the issue above that constants aren't initialized. The old frontend also evaluates much more in general, including things it shouldn't, so it doesn't run into as much problems with this.

These issues combined means that the NF needs to evaluate all constants, but can't do so since it then has to generate ASUBs which sometimes aren't accepted by the code generation. The exception are local constants in functions, for which literal expressions are generated in the C code.

Treating constant arrays (scalars can always be evaluated) declared in the DAE as literals in the same way we do for constants in functions would be one solution, and probably the most efficient. Improving the code generation for ASUB would also be a solution, but probably less straightforward."	defect	new	blocker	2.0.0	Code Generation	v1.13.0-dev-nightly			Martin Sjölund Adrian Pop
