%%============================================================================
%%
%%Abstract:
%%Thissystemfilecontainshelperfunctionstocreatean
%%S-Functionwrapperforanytarget.
%%
%%Copyright1994-2019TheMathWorks,Inc.
%%
 
%include "ertmdlreftiming.tlc"
%include "sfcnlib.tlc"
%include "ertfcnprotocontrol.tlc"
%include "servicelib.tlc"
 
 
%%FunctionMdlRefHasConstantOutput=========================================
%%Abstract:
%%Returntrueifthereareanyoutputportswithaconstantsampletime
%%
%function MdlRefHasConstantOutput()
   
  %return (::CompiledModel.HasConstantOutput == "yes")
%endfunction %%MdlRefHasConstantOutput
 
%%FunctionMdlRefHasParameterRateOutput=========================================
%%Abstract:
%%Returntrueifthereareanyoutputportswithaparametersampletime
%%
%function MdlRefHasParameterRateOutput()
   
  %return (::CompiledModel.HasParameterRateOutput == "yes")
%endfunction %%MdlRefHasParameterRateOutput
 
%%FunctionMdlRefHasInternalParameterRate======================================
%%Abstract:
%%Returntrueifthereisanyinternalusageofaparametersampletime
%%
%function MdlRefHasInternalParameterRate()
  %return (::CompiledModel.HasInternalParameterRate == "yes")
%endfunction
 
 
%%FunctionMdlRefHasParameterRate===========================================
%%Abstract:
%%Returntrueifthereisanyusageofaparametersampletime
%%
%function MdlRefHasParameterRate()
  %return MdlRefHasInternalParameterRate() || MdlRefHasParameterRateOutput()
%endfunction
 
 
%%FunctionMdlRefIsConstSampleBlock=========================================
%%Abstract:
%%Returntrueifallblocksampletimesareconstant.
%function MdlRefIsConstSampleBlock()
   
  %return (::CompiledModel.IsModelConstant == "yes")
%endfunction %%MdlRefIsConstSampleBlock
 
%%Function===================================================================
%function MdlRefIsFcnCallBlock()
  %return (::CompiledModel.HasRootTriggerPort == "yes") && ...
    (::CompiledModel.RootTriggerType == "function-call")
%endfunction
 
%%Function===================================================================
%function MdlRefIsTriggerBlock()
  %return (::CompiledModel.HasRootTriggerPort == "yes") && ...
    (::CompiledModel.RootTriggerType != "function-call")
%endfunction
 
%%Function===================================================================
%function MdlRefIsAPERTriggeredBlock()
  %return (::CompiledModel.IsAPERRootTriggeredSystem == "yes")
%endfunction
 
%%Function===================================================================
%function MdlRefDisallowSampleTimeInheritance()
  %return (::CompiledModel.ModelRefTsInheritance == ...
    "DISALLOW_SAMPLE_TIME_INHERITANCE")
%endfunction
 
%function HasRootEnablePort()
  %return (::CompiledModel.HasRootEnablePort == "yes")
%endfunction
 
%%=============================================================================
%%
%function MdlRefIsVarStepMultiRate() void
  %return ( IsModelReferenceForASimstructBasedTarget() && ...
            SolverType == "VariableStep" && ...
        LibIsContinuous(0) && NumSampleTimes > 1)
%endfunction
 
%%Function:DumpTimeConditioningCode=========================================
%%Abstract:
%%
%function DumpTimeConditioningCode() Output
  %if !SLibSingleTasking()
    {
      int_T localTid = 0;
      %foreach idx = NumRuntimeExportedRates
    if (ssIsSampleHit(S, %<idx>, %<::CompiledModel.GlobalScope.tTID> )) {
      %if Tid01Eq && ISEQUAL(idx,1)
        localTid = 0;
      %else
        localTid = %<idx>;
      %endif
    }
      %endforeach
      %<::CompiledModel.GlobalScope.tTID> = localTid;
    }
  %endif
%endfunction %% DumpTimeConditioningCode
 
 
%%Function:GenerateSFunctionOutputSignalDefinition==========================
%%Abstract:
%%ThisfunctiongeneratestheS-Functionoutputsignaldefinitionforthe
%%mdlOutputsfunction.
%%
%%Syntax:
%%GenerateSFunctionOutputSignalDefinition(prefix)
%%
%%Arguments:
%%prefix-signalnameprefix
%%
%%Returns:
%%real_T*_0=ssGetOutputPortSignal(S,0);
%%
%function GenerateSFunctionOutputSignalDefinition(prefix) Output
  %foreach idx = ExternalOutputs.NumExternalOutputs
    %assign extOut = ExternalOutputs.ExternalOutput[idx]
    %assign sysIdx = extOut.Block[0]
    %assign blkIdx = extOut.Block[1]
    %assign outportBlock = System[sysIdx].Block[blkIdx]
    %with System[sysIdx]
    %with outportBlock
      %assign dataType = LibBlockInputSignalDataTypeName(0, "")
      %<dataType> *%<prefix>%<idx> = ssGetOutputPortSignal(S, %<idx>);
    %endwith %% outportBlock
    %endwith %% System[sysIdx]
  %endforeach
%endfunction %% GenerateSFunctionOutputSignalDefinition
 
 
%%Function:GetConstBIOExternBuf============================================
%%Abstract:
%%TopTester:test/toolbox/simulink/variants/string/tStringSupport.m
%%
%function GetConstBIOExternBuf()
  %openfile extCBIOExtern
  %if !LibConstBlockIOInstanceIsEmpty()
    %assign qualifiers = SLibGetConstBlockIOQualifiers()
    %assign typePrefix = SLibGetModelTypesNamespacePrefix()
    /* Invariant block signals (%<::AutoOrDefaultStorageClass> storage) */
    %openfile extCBIODecl
    %<qualifiers> %<typePrefix>%<FcnSysVarGroupType(System[NumSystems-2],"ConstBlockIO")> %<::tConstBlockIOStruct>;
    %closefile extCBIODecl
    %<SLibApplyMemSecToDataDecl(extCBIODecl, "MemSecDataConstants", "%<::tConstBlockIOStruct>")>
  %endif
  %closefile extCBIOExtern
  %return extCBIOExtern
%endfunction %% GetConstBIOExternBuf
 
 
%%Function:GetConstPrmExternBuf============================================
%%Abstract:
%%
%function GetConstPrmExternBuf()
  %openfile extCPrmExtern
  %if !SLibPrmBufferIsEmpty("Const", "Typedef")
    %assign qualifiers = SLibGetConstParamQualifiers()
    %assign typePrefix = SLibGetModelTypesNamespacePrefix()
    /* Constant parameters (%<::AutoOrDefaultStorageClass> storage) */
    %openfile extCPrmExternDecl
    %<qualifiers> %<typePrefix>%<::tConstParamType> %<::tConstParamStruct>;
    %closefile extCPrmExternDecl
    %<SLibApplyMemSecToDataDecl(extCPrmExternDecl, "MemSecDataConstants", "%<::tConstParamStruct>")>
  %endif
  %closefile extCPrmExtern
  %return extCPrmExtern
%endfunction %% GetConstPrmExternBuf
 
 
%%Function:GetConstPrmWithInitExternBuf=====================================
%%Abstract:
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function GetConstPrmWithInitExternBuf()
  %openfile extCPrmExtern
  %if !SLibPrmBufferIsEmpty("ConstWithInit", "Typedef")
    %assign qualifiers = SLibGetConstParamWithInitQualifiers()
    %assign typePrefix = SLibGetModelTypesNamespacePrefix()
    /* Constant parameters with dynamic initialization (%<::AutoOrDefaultStorageClass> storage) */
    %openfile extCPrmExternDecl
    %<qualifiers> %<typePrefix>%<::tConstParamWithInitType> %<::tConstParamWithInitStruct>;
    %closefile extCPrmExternDecl
    %<SLibApplyMemSecToDataDecl(extCPrmExternDecl, "MemSecDataConstants", "%<::tConstParamWithInitStruct>")>
  %endif
  %closefile extCPrmExtern
  %return extCPrmExtern
%endfunction %% GetConstPrmWithInitExternBuf
 
 
%%Function:SLibWriteModelrefSFunctionMethods=================================
%%Abstract:
%%WriteoutthemodelreferenceS-Functionmethodstoafile.
%%TODO:Migratethecontentofthisfunctionthencleanitup.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibWriteModelrefSFunctionMethods() void
  %assign sFunctionName = GetModelrefSFunctionName(Name)
  %assign opFile = SLibAddModelFile("SystemBody","Simulink", sFunctionName)
  %<SLibSetModelFileAttribute(opFile, "Group", "interface")>
   
  %assign cBIOExtBuf = GetConstBIOExternBuf()
  %<SLibCacheCodeToFile("mdlsfcn_extern_data_defn", cBIOExtBuf)>
 
  %% Generate code for each of the sfcn methods
  %openfile fcnsBuf
  %<WriteModelrefSFunctionVarDimsSetDimsMethods("SetDims")>
  %<WriteModelrefSFunctionVarDimsSetDimsMethods("FinalizeDims")>
  %closefile fcnsBuf
   
  %<SLibCacheCodeToFile("mdlsfcn_fcn_defn", fcnsBuf)>
%endfunction
 
%%Function:ModelrefBlockNeedsDwork===========================================
%%Abstract:
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/modelref/tModelRefVariants.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tVariantSimulinkFunctionAutoInherit.m
%%
%function ModelrefBlockNeedsDwork() void
  %if IsModelRefScalableBuild()
    %return TLC_FALSE
  %else
    %assign baseSystem = ::CompiledModel.System[GetBaseSystemIdx()]
    %if (baseSystem.HasBlockIOArg || baseSystem.HasDWorkArg ...
      || !EmptyRealTimeObject || baseSystem.HasZCEventArg)
      %return TLC_TRUE
    %else
      %return TLC_FALSE
    %endif
  %endif
%endfunction %%ModelrefBlockNeedsDwork
 
%%Function:ModelRefBlockHasPrivateDWork======================================
%%Abstract:
%%ThisisaddedforrapidacceleratorsimulationofModelblockwith
%%initializeport.ThetopmodelneedstosaveandrestoresomeoftheDWork
%%content.Formulti-instance,thisisstraightforwardsincethetopmodel
%%caneasilyaccessthe"InstanceData"DWorkoftheModelblock.Forsingle
%%instance,theDWorkstructishidden.Weusethisfunctiontoquerysuch
%%case.
%function ModelRefBlockHasPrivateDWork() void
  %return IsModelRefScalableBuild() && !GenerateClassInterface && !LibDWorkStructIsEmpty()
%endfunction %%ModelRefBlockHasPrivateDWork
 
%%Function:SLibDeclareModelReferenceVars=====================================
%%Abstract:
%%Forthegivensystem,declaretheglobalvariablesthatareused.
%%Thefunctionmaybepassedastringtoprependthedeclaration(suchas
%%"extern")
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function SLibDeclareModelReferenceVars(system, genMdlRefDWork, isModelRefScalableBuild, extern) void
  %openfile tmpbuf
  %if !genMdlRefDWork && isModelRefScalableBuild
    %if system.HasBlockIOArg
      /* Block signals (%<::AutoOrDefaultStorageClass> storage) */
      %<SLibDeclareStandaloneVarType(system, [], "BlockIO", extern)>
    %endif
    %if system.HasDWorkArg
      /* Block states (%<::AutoOrDefaultStorageClass> storage) */
      %<SLibDeclareStandaloneVarType(system, [], "DWork", extern)>
    %endif
    %if system.HasZCEventArg
      /* Previous zero-crossings (trigger) states */
      %<SLibDeclareStandaloneVarType(system, [], "ZCEvent", extern)>
    %endif
  %endif
  %% Emit declarations/definitions for all exported coder data groups, except
  %% InSelf and InParent for multi-instance mdlref
  %createrecord groupFilter { /
      Static TLC_TRUE /
      Dynamic TLC_TRUE /
      AccessStandalone TLC_TRUE /
      AccessThroughSelf (!genMdlRefDWork && isModelRefScalableBuild) /
      Exported TLC_TRUE /
      Imported TLC_FALSE /
      ModelData TLC_FALSE /
  }
  %<SLibDeclareCoderDataGroupInstances(system,extern,groupFilter)>
  %closefile tmpbuf
  %return tmpbuf
%endfunction %% SLibDeclareStandaloneVars
 
%%Function:SLibGenerateSFcnDWork=============================================
%%Abstract:
%%Generatedworkstructureforthereferencemodel
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibModelReferenceGenerateDWork() void
  %assert IsModelReferenceTarget()
  %assign baseSystem = ::CompiledModel.System[GetBaseSystemIdx()]
  %assign genMdlRefDWork = ...
    ( !IsModelRefScalableBuild() || ::CompiledModel.GenSingleInstanceMdlRefDWork ) && ...
    !::CompiledModel.ModelRefSimpInterface
 
  %openfile dwBuf
  %assign dwHasNonRTMField = TLC_FALSE
  %if genMdlRefDWork && baseSystem.HasBlockIOArg && !SLibIsSelfInPluggableInterface()
    %<FcnSysVarGroupType(baseSystem,"BlockIO")> rtb;
    %assign dwHasNonRTMField = TLC_TRUE
  %endif
  %if genMdlRefDWork && baseSystem.HasDWorkArg && !SLibIsSelfInPluggableInterface()
    %<FcnSysVarGroupType(baseSystem,"DWork")> rtdw;
    %assign dwHasNonRTMField = TLC_TRUE
  %endif
  %if !EmptyRealTimeObject && !CompiledModel.ModelRefSimpInterface
    %<::tSimStructType> rtm;
  %endif
  %if genMdlRefDWork && baseSystem.HasZCEventArg && !SLibIsSelfInPluggableInterface()
    %<FcnSysVarGroupType(baseSystem,"ZCEvent")> rtzce;
    %assign dwHasNonRTMField = TLC_TRUE
  %endif
  %closefile dwBuf
   
  %if !EmptyRealTimeObject && CompiledModel.ModelRefSimpInterface && !CompiledModel.OkToMultiInstanceModelref
    %%% If using simplfied interface, and in Modelref single-instance case, we still need to define the singleton RTM variable.
    %assign allocatedVarName = SLibGetSimStructAllocatedVarName()
    %assign refVarName = SLibGetSimStructReferenceVarName()
    %assign def = "%<::tSimStructType> %<allocatedVarName>;/n"
    %assign rtmDef = SLibGetQualifiedRTMType() + " *const %<refVarName> = &%<allocatedVarName>;"
    %assign def = def + rtmDef
    %openfile dWorkDefn
      %<SLibApplyMemSecToDataDefn(def, "MemSecDataInternal", "")>/
    %closefile dWorkDefn
    %<SLibCacheCodeToFile("data_DWork_defn", dWorkDefn)>
    %undef dWorkDefn
  %endif
 
  %if !WHITE_SPACE(dwBuf)
    %assign skipMdlRefDWorkTypedef = SLibIsSelfInPluggableInterface() && !IsModelReferenceSimTarget()
    %assign needDWorkExported = SLibModelHasServicePortDWork()
    %if !skipMdlRefDWorkTypedef
      %if SLibSimTargetUsesModelSelf() && dwHasNonRTMField
        %<LibReportFatalError("Internal error: Unexpected field in MdlrefDW")>
      %endif
      %openfile dworkBuf
      %if !needDWorkExported
        %<GetHideChildDefineSymbol("ifndef")>/
      %endif
      typedef struct {
        %<dwBuf>/
 
      } %<FcnGetSFcnDWorkType(baseSystem)>;
      %if !needDWorkExported
        %<GetHideChildDefineSymbol("endif")>/
      %endif
      %closefile dworkBuf
      %<SLibCacheCodeToFile("data_DWork_typedef", dworkBuf)>
    %endif
 
    %if IsModelRefScalableBuild()
      %assign declaration = "%<FcnGetSFcnDWorkType(baseSystem)> %<FcnGetSFcnDWorkIdentifier(baseSystem)>;"
      %openfile dWorkDecl
      %if !needDWorkExported
        %<GetHideChildDefineSymbol("ifndef")>/
      %endif
      %<SLibApplyMemSecToDataDecl(declaration, "MemSecDataInternal", "%<FcnGetSFcnDWorkIdentifier(baseSystem)>")>/
      %if !needDWorkExported
        %<GetHideChildDefineSymbol("endif")>/
      %endif
      %closefile dWorkDecl
      %<SLibCacheCodeToFile("data_DWork_decl", dWorkDecl)>
       
      %assert !GenerateClassInterface
       
      %assign def = "%<FcnGetSFcnDWorkType(baseSystem)> %<FcnGetSFcnDWorkIdentifier(baseSystem)>;"
      %openfile dWorkDefn
      %<SLibApplyMemSecToDataDefn(def, "MemSecDataInternal", "%<FcnGetSFcnDWorkIdentifier(baseSystem)>")>/
      %closefile dWorkDefn
      %<SLibCacheCodeToFile("data_DWork_defn", dWorkDefn)>
    %endif
  %endif
  %assign mdlRefVars = ...
     SLibDeclareModelReferenceVars(baseSystem, genMdlRefDWork, IsModelRefScalableBuild(), "extern")
  %if !WHITE_SPACE(mdlRefVars)
    %openfile dWorkDecl
    %assign needToExportDWork = SLibModelHasServicePortDWork()
    %if !needToExportDWork
      %<GetHideChildDefineSymbol("ifndef")>/
    %endif
    %<mdlRefVars>
    %if !needToExportDWork
      %<GetHideChildDefineSymbol("endif")>/
    %endif
    %closefile dWorkDecl
    %<SLibCacheCodeToFile("data_DWork_decl", dWorkDecl)>
  %endif
  %<SLibCacheCodeToFile("data_DWork_defn", ...
    SLibDeclareModelReferenceVars(baseSystem, genMdlRefDWork, IsModelRefScalableBuild(), ""))>
%endfunction
 
%function FcnGetSFcnDWorkIdentifier(system) void
  %if !IsModelReferenceSimTarget() && SLibIsSelfInPluggableInterface() && system.SystemIdx == GetBaseSystemIdx()
    %return "%<::CompiledModel.GlobalScope.tRTM>"
  %else
    %return "%<system.Interface.tsysMdlrefDWork>"
  %endif
%endfunction
 
%function FcnGetSFcnDWorkType(system) void
  %if !IsModelReferenceSimTarget() && SLibIsSelfInPluggableInterface() && system.SystemIdx == GetBaseSystemIdx()
    %return "%<tSimStructType>"
  %else
    %return "%<system.Interface.tsysMdlrefDWorkType>"
  %endif
%endfunction
 
%function FcnGetSFcnDWorkRTM() void
  %assert IsModelReferenceSimTarget() && SLibGetUseRTMcgType()
  %assign modelDW = FcnGetSFcnDWorkIdentifier(::CompiledModel.System[baseSystemIdx])
  %return modelDW + ".rtm"
%endfunction
 
%%Function:LibGetFcnInfo====================================================
%%Abstract:
%%ReturnfcnInforecordofthesystem.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/tTypesToPrivate.m
%%
%function LibGetFcnInfo(system, fcnType, tid) void
  %% Output may have been combined with update
  %if fcnType == "Output" && !ISFIELD(system,"OutputFcn") && ...
      !(ISFIELD(system,"OutputCalledInUpdate") && ...
      system.OutputCalledInUpdate == "yes")
    %assign fcnType = "OutputUpdate"
  %endif
  %if LibIsSingleRateSystem(system) && ...
    LibSystemIsReusedFcn(system) && ...
    !SLibNonInlinedModelWideEventTID(tid)
    %assign tid = FcnGetSubsystemCodeBufTID(system)
  %endif
  %if (SLibSystemFcnPeriodicRateGrouping(system, fcnType) || ...
    (LibAsynchronousTriggeredTID(tid) && ...
    (fcnType == "Output" || fcnType == "Update" || ...
    fcnType == "OutputUpdate")))
      %assign tidStr = "TID%<tid>"
  %else
    %assign tidStr = ""
  %endif
  %if !ISEMPTY(tidStr) && SLibPartitionGroupingSystem(system)
    %if IsModelReferenceTarget()
        %assign pid = "PID%<system.CurrentPID>"
    %else
        %% For top model code interface, system.CurrentPID is set to -1
        %assign pidVec = SLibGetPidFromTid(tid)
        %if ISEMPTY(pidVec)
            %assign pid = ""
        %else
            %assign pid = "PID%"
        %endif
    %endif
  %else
    %assign pid = ""
  %endif
  %assign fieldname = fcnType + "%<tidStr>%<pid>FcnInfo"
  %if LibIsSystemField(system, fieldname)
    %assign fcnInfo = LibGetSystemField(system, fieldname)
  %else
    %assign fcnInfo = ""
  %endif
  %return fcnInfo
%endfunction
 
%%Function:CreateModelrefSFunctionForTopSystem=================================
%%Abstract:
%%CreateModelrefSFunctionrecordforthehiddensubsystem
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function CreateModelrefSFunctionForTopSystem() void
 
  %assert IsModelReferenceTarget()
  %% If we are generating an S-function, add cached variables for
  %% all the s-fcn entry points to the record ModelrefSFunction
  %assert ::CompiledModel.NumSystems > 1
 
  %addtorecord ::CompiledModel.System[NumSystems-2] ModelrefSFunction { ...
    CachedFcnCallInputBuffers ""; ...
    CachedInitializeSizesDeclarations ""; ...
    CachedInitializeSizesBody ""; ...
    CachedInitializeSampleTimesDeclarations ""; ...
    CachedInitializeSampleTimesBody ""; ...
    CachedInitializeConditionsDeclarations ""; ...
    CachedInitializeConditionsBody ""; ...
    CachedSystemInitializeDeclarations ""; ...
    CachedSystemInitializeBody ""; ...
    CachedSystemResetDeclarations ""; ...
    CachedSystemResetBody ""; ...
    CachedSetWorkWidthsDeclarations ""; ...
    CachedSetWorkWidthsBody ""; ...
    CachedProcessParametersDeclarations ""; ...
    CachedProcessParametersBody ""; ...
    CachedStartDeclarations ""; ...
    CachedStartBody ""; ...
    CachedEnableDeclarations ""; ...
    CachedEnableBody ""; ...
    CachedDisableDeclarations ""; ...
    CachedDisableBody ""; ...
    CachedOutputsDeclarations ""; ...
    CachedOutputsBody ""; ...
    CachedUpdateDeclarations ""; ...
    CachedUpdateBody ""; ...
    CachedZeroCrossingsDeclarations ""; ...
    CachedZeroCrossingsBody ""; ...
    CachedDerivativesDeclarations ""; ...
    CachedDerivativesBody ""; ...
    CachedProjectionDeclarations ""; ...
    CachedProjectionBody ""; ...
    CachedForcingFunctionDeclarations ""; ...
    CachedForcingFunctionBody ""; ...
    CachedMassMatrixDeclarations ""; ...
    CachedMassMatrixBody ""; ...
    CachedTerminateDeclarations ""; ...
    CachedTerminateBody ""...
  }
%endfunction
 
 
%%Function:AppendZeroToString===============================================
%%Abstract:
%%AppendtheinStrwithzero
%function AppendZeroToString(inStr, comma, num) void
  %foreach i = num
    %assign inStr = "%<inStr>%<comma>0"
    %assign comma = ", "
  %endforeach
  %return inStr
%endfunction
 
%%FunctionFcnAppendToBlockInterface=========================================
%%Abstract:
%%HelperfunctionforFcnAppendToBlockInterface.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/variants/tMdlrefToVSS.m
%%
%function SLibGetModelRefFcnNames(thisSystem, blockFcn, fcnCallTaskName, ...
  currentTID, isPeriodicRateGrouping)
   
  %if ISEMPTY(fcnCallTaskName)
    %assign tlcFcn = ""
    %assign tlcFcnName = ""
    %assign sysFcnName = ""
    %assign CGIRName = ""
    %if blockFcn == "Registration"
      %assert ISEMPTY(fcnCallTaskName)
      %assign sysFcnName = "%<blockFcn>Fcn"
      %if ::GenerateClassInterface
        %assign fcnName = "%<::CPPClassName>::initialize"
      %else
        %assign fcnName = GetModelRefRegistrationFcnName()
      %endif
      %assign tlcFcnName = []
    %else
      %assign fcnRecord = LibGetFcnInfo(thisSystem, blockFcn, currentTID)
      %assert (TYPE(fcnRecord) == "Scope")
      %assign fcnName = fcnRecord.Name
      %if ISFIELD(fcnRecord, "CGIRName")
        %assign CGIRName = fcnRecord.CGIRName
      %endif
  
      %switch (blockFcn)
        %case "Output"
        %case "OutputUpdate"
          %assign tlcFcn = "Outputs"
          %break
        %case "SetupRuntimeResources"
          %assign tlcFcn = "SetupRuntimeResources"
          %break
        %case "Initialize"
          %assign tlcFcn = "InitializeConditions"
          %break
        %case "SystemInitialize"
          %assign tlcFcn = "SystemInitialize"
          %break
        %case "SystemReset"
          %assign tlcFcn = "SystemReset"
          %break
        %case "Derivative"
          %assign tlcFcn = "Derivatives"
          %break
        %case "ZeroCrossing"
          %assign tlcFcn = "ZeroCrossings"
          %break
        %case "CleanupRuntimeResources"
          %assign tlcFcn = "CleanupRuntimeResources"
          %break
        %default
          %assign tlcFcn = blockFcn
          %break
      %endswitch
               
      %if !isPeriodicRateGrouping && ...
        !(SLibIsExportFcnDiagram() && SLibSystemFcnIsRateGroupType(blockFcn) && !ISEQUAL(currentTID,"")) && ...
        !LibSystemFcnIsEmpty(thisSystem, blockFcn)
        %assign sysFcnName = blockFcn + "Fcn"
        %assign tlcFcnName = tlcFcn + "_Function"
      %elseif !LibSystemFcnIsEmptyForTID(thisSystem, blockFcn)
        %assign sysFcnName = blockFcn + "TID%<thisSystem.CurrentTID>Fcn"
        %assign tlcFcnName = tlcFcn + "_FunctionTID%<thisSystem.CurrentTID>"
      %endif
    %endif
  %else
    %% For Fcn-call inputs, override the sysFcnName with the entry point
    %% task name.
    %assign sysFcnName = fcnCallTaskName
    %assign fcnName = fcnCallTaskName
    %assign tlcFcnName = []
    %assign CGIRName = []
  %endif
   
  %assign retRec = ["%<sysFcnName>", "%<tlcFcnName>", "%<fcnName>", "%<CGIRName>"]
  %return retRec
%endfunction
 
%%Function:SLibGetModelRefRootInputIdx=======================================
%%Abstract:
%%Returnstherootinputportforacanonicalinputindex
%%
%function SLibGetModelRefRootInputIdx(sysIdx, canInputIdx)
  %assign thisSystem = ::CompiledModel.System[sysIdx]
  %assign ci = thisSystem.Interface.CanonicalInputArgDef[canInputIdx].SignalSrc
  %assign idNum = IDNUM(ci[0])
  %assert (idNum[0] == "U" || idNum[0] == "M")
  %assign rootInputPortIdx = idNum[1]
  %return rootInputPortIdx
%endfunction %% SLibGetModelRefRootInputIdx
 
%%Function:SLibGetModelRefRootOutputIdx======================================
%%Abstract:
%%Returnstherootinputportforacanonicalinputindex
%%
%function SLibGetModelRefRootOutputIdx(sysIdx, canOutputIdx)
  %assign thisSystem = ::CompiledModel.System[sysIdx]
  %return thisSystem.Interface.CanonicalOutputArgDef[canOutputIdx].RootOutputIdx
%endfunction %% SLibGetModelRefRootOutputIdx
 
%%Function:CreateModelReferenceFcnRec========================================
%%Abstract:
%%HelperfunctionforFcnAppendToBlockInterface
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/tCSCDefine.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/variants/tMdlrefToVSS.m
%%
%function CreateModelReferenceFcnRec(sysIdx, blockFcn, sysFcnName, tid, blkInterface, useSysFcnName) void
  %assign thisSystem = ::CompiledModel.System[sysIdx]
  %assign modIdx = thisSystem.CGIRModuleIdx
  %assign thisModule = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
  %assign hasSimplifiedInterface = thisModule.SimplifiedInterface
  %assign thisSystem.CurrentTID = tid
  %assign currentTID = tid
   
  %assign isPeriodicRateGrouping = SLibSystemFcnPeriodicRateGrouping(thisSystem, blockFcn) || ...
    (SLibSystemFcnIsRateGroupType(blockFcn) && SLibIsModelRefAsyncTID(tid))
   
  %assign isWritable = !ISEMPTY(blkInterface)
   
  %if isWritable && !ISFIELD(blkInterface, "NumBlockFcns")
    %addtorecord blkInterface NumBlockFcns 0
  %endif
   
  %if(useSysFcnName)
    %assign keyFcnName = sysFcnName
  %else
    %assign keyFcnName = blockFcn
  %endif
 
   
  %% LibSystemFcnIsEmpty has side affect. (When output is passed,
  %% it may check for OutputUpdate!)
  %assign isRateGroupedAsync = RateGroupedAsyncFcns && FcnSysModuleIsRateGrouping(thisSystem,blockFcn)
  %if blockFcn != "Registration" && ...
    (!SLibIsModelRefAsyncTID(tid) || SLibNonInlinedModelWideEventTID(tid)) && ...
    !useSysFcnName && ...
    (!ISFIELD(thisSystem,"%<keyFcnName>Fcn") || ...
    ((SLibIsExportFcnDiagram() || isRateGroupedAsync) && LibSystemFcnIsEmptyForTID(thisSystem, keyFcnName)) || ...
    LibSystemFcnIsEmpty(thisSystem, keyFcnName))
    %createrecord retRec { /
    SysFcnName ""; /
    FcnRec ""/
    }
    %return retRec
  %endif
   
  %assign fcnNames = SLibGetModelRefFcnNames(thisSystem, blockFcn, ...
    sysFcnName, currentTID, isPeriodicRateGrouping)
 
  %assign sysFcnName = fcnNames[0]
  %assign tlcFcnName = fcnNames[1]
  %assign fcnName = fcnNames[2]
  %assign cgirName = fcnNames[3]
 
  %% For Async code gen, we always track argument based on func names, keyFcnName.
  %% For all other rates, we track argument based on func type, which is blockFcn.
  %% The 2nd option is the rate grouping code path.
  %if SLibExplicitTaskingTID(tid) && ...
    (!SLibIsModelRefAsyncTID(tid) || SLibIsExportFcnDiagram() || RateGroupedAsyncFcns)
      %assign ::BlockFcn = blockFcn
  %else
    %assign ::BlockFcn = keyFcnName
  %endif
 
  %with thisSystem.Interface
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Canonical input argument
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %assign comma = ""
    %assign inStr = ""
    %assign inCounter = 0
    %assign numInputs = ExternalInputs.NumExternalInputs
    %foreach argIdx = NumCanonicalInputArgDefs
      %assign idx = SLibGetModelRefRootInputIdx(sysIdx, argIdx)
       
      %% fill 0 for unused inputs
      %assign numZeroToAdd = idx - inCounter
      %if numZeroToAdd > 0
    %assign inStr = AppendZeroToString(inStr, comma, numZeroToAdd)
    %assign comma = ", "
      %endif
      %assign inCounter = idx
       
      %if FcnArgNeeded(CanonicalInputArgDef[argIdx],currentTID,isPeriodicRateGrouping)
    %if CanonicalInputArgDef[argIdx].DeclareAsPointer == "yes"
      %assign inStr = "%<inStr>%<comma>2"
    %else
      %assign inStr = "%<inStr>%<comma>1"
    %endif
      %else
    %assign inStr = "%<inStr>%<comma>0"
      %endif
      %assign comma = ", "
      %assign inCounter = inCounter + 1
    %endforeach
 
    %assign numZeroToAdd = numInputs - inCounter
    %if numZeroToAdd > 0
      %assign inStr = AppendZeroToString(inStr, comma, numZeroToAdd)
      %assign comma = ", "
    %endif
    %assign inCounter = numInputs
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Canonical dimsize dwork argument for input
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %assign inDWStr = GetBlockInputCanDimSizeDWInterface(sysIdx, blockFcn, tid)
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Canonical output argument
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %assign comma = ""
    %assign outStr = ""
    %assign outCounter = 0
    %assign numOutputs = ExternalOutputs.NumExternalOutputs
    %foreach argIdx = NumCanonicalOutputArgDefs
      %assign idx = SLibGetModelRefRootOutputIdx(sysIdx, argIdx)
 
      %% fill 0 for unused outputs
      %assign numZeroToAdd = idx - outCounter
      %if numZeroToAdd > 0
    %assign outStr = AppendZeroToString(outStr, comma, numZeroToAdd)
    %assign comma = ", "
      %endif
      %assign outCounter = idx
 
      %if FcnArgNeeded(CanonicalOutputArgDef[argIdx],currentTID,isPeriodicRateGrouping)
    %assign outStr = "%<outStr>%<comma>1"
      %else
    %assign outStr = "%<outStr>%<comma>0"
      %endif
      %assign comma = ", "
      %assign outCounter = outCounter + 1
    %endforeach
 
    %assign numZeroToAdd = numOutputs - outCounter
    %if numZeroToAdd > 0
      %assign outStr = AppendZeroToString(outStr, comma, numZeroToAdd)
      %assign comma = ", "
    %endif
    %assign outCounter = numOutputs
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Canonical dimsize dwork argument for output
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %assign outDWStr = GetBlockOutputCanDimSizeDWInterface(sysIdx, blockFcn, tid)
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Other flags
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Args: [oIdx, rIdx, TID, rtModel, BlockIo, DWork, CState, CStateDeriv, CStateDis, CStateAbsTol, ZC, ZCEvent]
 
    %% Note the following order is used in blocks/modelref.tlc.
    %% If you update this order, you must update the order in SLibCallModelBlockFunction in this file and
    %% FcnAddMdlRefFcnInterface in codeinfomdlreflib.tlc
    %% [oIdx, rIdx, TID, rtModel, BlockIo, DWork, CState, CStateDeriv, CStateDis, CStateAbsTol, ZC, ZCEvent]
    %assign args = ""
    %assign comma = ""
 
    %% oIdx and rIdx
    %if blockFcn == "SetDims"
      %assign val = 1
      %assign args = "%<args>%<comma>%<val>"
      %assign args = "%<args>%<comma>%<val>"
    %endif
     
    %% TID
    %if (SLibIsModelRefAsyncTID(tid))
      %% Because we know async is single instance, always return
      %% false for needs TID. (LibSystemFcnNeedsTID returns needs
      %% TID for the model, which does need TID, but the async doesn't,
      %% which causes code that won't compile)
      %assign val = TLC_FALSE
    %else
      %assign val = LibSystemFcnNeedsTID(thisSystem, blockFcn)
    %endif
    %assign args = "%<args>%<comma>%<val>"
    %assign comma = ", "
    %%rtModel
    %assign val = FcnArgNeeded(RTMArgDef,currentTID,isPeriodicRateGrouping) || hasSimplifiedInterface
    %if val && (IsModelRefScalableBuild() || GenerateClassInterface)
      %assign val = 0
    %endif
    %assign args = "%<args>%<comma>%<val>"
    %assign comma = ", "
    %% BlockIo argument
    %assign val = FcnArgNeeded(BlockIOArgDef,currentTID,isPeriodicRateGrouping)
    %if val && (IsModelRefScalableBuild() || GenerateClassInterface || hasSimplifiedInterface)
      %assign val = 0
    %endif
    %assign args = "%<args>%<comma>%<val>"
    %% DWork argument
    %assign val = FcnArgNeeded(DWorkArgDef,currentTID,isPeriodicRateGrouping)
    %if val && (IsModelRefScalableBuild() || GenerateClassInterface || hasSimplifiedInterface)
      %assign val = 0
    %endif
    %assign args = "%<args>%<comma>%<val>"
    %% Continuous States argument
    %assign val = FcnArgNeeded(ContStatesArgDef,currentTID,isPeriodicRateGrouping)
    %assert !(val && GenerateClassInterface)
    %assign args = "%<args>%<comma>%<val>"
    %% Continuous States Derivative argument
    %assign val = FcnArgNeeded(ContStatesDerivativeArgDef,currentTID,isPeriodicRateGrouping)
    %assert !(val && GenerateClassInterface && IsModelReferenceTarget())
    %assign args = "%<args>%<comma>%<val>"
    %% Continuous States Disabled argument
    %assign val = FcnArgNeeded(ContStatesDisabledArgDef,currentTID,isPeriodicRateGrouping)
    %assert !(val && GenerateClassInterface)
    %assign args = "%<args>%<comma>%<val>"
    %% Continuous States Absolute Tolerance argument
    %assign val = FcnArgNeeded(ContStatesAbsoluteToleranceArgDef,currentTID,isPeriodicRateGrouping)
    %assert !(val && GenerateClassInterface)
    %assign args = "%<args>%<comma>%<val>"
     
    %% Continuous States Perturb Min argument
    %assign val = FcnArgNeeded(ContStatesPerturbMinArgDef,currentTID,isPeriodicRateGrouping)
    %assert !(val && GenerateClassInterface)
    %assign args = "%<args>%<comma>%<val>"
     
    %% Continuous States Perturb Max argument
    %assign val = FcnArgNeeded(ContStatesPerturbMaxArgDef,currentTID,isPeriodicRateGrouping)
    %assert !(val && GenerateClassInterface)
    %assign args = "%<args>%<comma>%<val>"
     
     
    %% Non Sampled Zero Crossing argument
    %assign val = FcnArgNeeded(ZCSVArgDef,currentTID,isPeriodicRateGrouping)
    %assert !(val && GenerateClassInterface)
    %assign args = "%<args>%<comma>%<val>"
    %% ZCEvent H-Valuct argument
    %assign val = FcnArgNeeded(ZCEventArgDef,currentTID,isPeriodicRateGrouping)
    %if val && (IsModelRefScalableBuild() || GenerateClassInterface || hasSimplifiedInterface)
      %assign val = 0
    %endif
    %assign args = "%<args>%<comma>%<val>"
    %%
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Canonical parameter argument
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %assign comma = ""
    %assign prmStr = ""
    %assign prmType = []
    %assign prmIsPtr = []
    %foreach argIdx = NumCanonicalPrmArgDefs
      %assign argDef = CanonicalPrmArgDef[argIdx]
      %if (argDef.OriginalDataTypeIdx != -1)
        %if FcnArgNeeded(argDef,currentTID,isPeriodicRateGrouping)
          %assign prmWidth = LibBlockParameterWidth(argDef)
          %assign prmStr = "%<prmStr>%<comma>%<prmWidth>"
        %else
          %% Not needed, so arbitrary "0" as a placeholder suffices.
          %assign prmStr = "%<prmStr>%<comma>0"
        %endif
        %assign dtName = ...
          LibGetDataTypeNameFromId(LibGetRecordContainerDataTypeId(argDef))
        %assign prmType = prmType + dtName
        %assign comma = ", "
        %assign prmIsPtr = prmIsPtr + (argDef.DeclareAsPointer == "yes")
      %else
        %assert argDef.IsUsed == "no"
      %endif
    %endforeach
     
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Canonical dwork argument
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %assign comma = ""
    %assign canDWStr = ""
    %foreach argIdx = NumCanonicalDWorkArgDefs
      %assign argDef = CanonicalDWorkArgDef[argIdx]
      %if FcnArgNeeded(argDef,currentTID,isPeriodicRateGrouping)
        %assign dwIdx = argDef.FirstSignalSrc
        %assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
        %assign dwWidth = SLibDWorkWidth(dwRec)
        %assign canDWStr = "%<canDWStr>%<comma>%<dwWidth>"
      %else
    %assign canDWStr = "%<canDWStr>%<comma>0"
      %endif
      %assign comma = ", "
    %endforeach
     
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Computed stack size
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %assign stackSize = 0
    %if blockFcn != "Registration" && ...
      (!SLibIsModelRefAsyncTID(tid) && !SLibExplicitTaskingTID(tid) || ...
      SLibNonInlinedModelWideEventTID(tid))
      %if !ISEMPTY(tlcFcnName) && ISFIELD(RTWCGModules.RTWCGModule[thisSystem.CGIRModuleIdx], "RTWFcnConst")
        %assign rtwFcnConst = ...
          RTWCGModules.RTWCGModule[thisSystem.CGIRModuleIdx].RTWFcnConst
        %if ISFIELD(rtwFcnConst, tlcFcnName)
          %assign stackSize = rtwFcnConst.%<tlcFcnName>.StackSize
        %endif
      %endif
      %assign localTaskID = isPeriodicRateGrouping ? currentTID : -1
      %createrecord blockFcnRec { /
        BlockFcnType "%<blockFcn>"; /
        RateGrouping %<isPeriodicRateGrouping>; /
        TaskID %<localTaskID>; /
        StackSize %<stackSize> /
      }
      %if isWritable
        %assign blkInterface.NumBlockFcns = blkInterface.NumBlockFcns + 1
        %addtorecord blkInterface BlockFcns %<blockFcnRec>
      %endif
    %endif
     
    %assign numArgs = 0
    %assign argSourceVec = []
    %assign associationVec = []
     
    %if ISFIELD(thisModule, "SystemFunctions") && ...
      (ISFIELD(thisModule.SystemFunctions, fcnName) || ISFIELD(thisModule.SystemFunctions, cgirName))
      %% G1719775 During C++ Class Generation, the fcnName is not used in CGIR phase
      %% Using cgirName to get the correct function prototype
      %if ISFIELD(thisModule.SystemFunctions, fcnName)
         %assign fcnIndex = GETFIELD(thisModule.SystemFunctions, fcnName)
      %else
         %assign fcnIndex = GETFIELD(thisModule.SystemFunctions, cgirName)
      %endif
       
      %assign thisFcn = thisModule.Function[fcnIndex]
      %if thisFcn.IsRateGroupedSLFcn
        %createrecord retRec { /
          SysFcnName ""; /
          FcnRec ""/
        }
        %return retRec
      %endif
 
      %assert SIZE(thisFcn.ArgAccessed, 1) == thisFcn.NumArgs
      %assert SIZE(thisFcn.ArgSource, 1) == thisFcn.NumArgs
      %foreach argIdx = thisFcn.NumArgs
        %if thisFcn.ArgAccessed[argIdx] > 0
          %if ISFIELD(thisFcn, "Association")
            %assign association = thisFcn.Association[argIdx]
          %else
            %assign association = ""
          %endif
          %assign argSource = thisFcn.ArgSource[argIdx]
          %assign idNum = SLibSafeIDNUM(thisFcn.ArgSource, argIdx)
          %assign argSrc = idNum[0]
          %assign argSrcIdx = idNum[1]
          %switch argSrc
            %case "I" %% canonical input
              %assign idx = SLibGetModelRefRootInputIdx(sysIdx, argSrcIdx)
              %assign argSource = "I%<idx>"
              %break
            %case "O" %% canonical output
              %assign idx = SLibGetModelRefRootOutputIdx(sysIdx, argSrcIdx)
              %assign argSource = "O%<idx>"
              %break
            %case "Y" %% root outport not being canonical output, occur in FPC only
              %assign argSource = "O%<argSrcIdx>"
              %break
            %case "D" %% canonical dwork
              %if ISFIELD(thisFcn, "Association")
                %assign dimsIdNum = SLibSafeIDNUM(thisFcn.Association, argIdx)
                %assign dimsSrc = dimsIdNum[0]
                %assign dimsSrcIdx = dimsIdNum[1]
                %if "I" == dimsSrc
                  %assign idx = SLibGetModelRefRootInputIdx(sysIdx, dimsSrcIdx)
                  %assign association = "I%<idx>"
                %else
                  %assert "O" == dimsSrc
                  %assign idx = SLibGetModelRefRootOutputIdx(sysIdx, dimsSrcIdx)
                  %assign association = "O%<idx>"
                %endif
              %endif
              %break
            %case "P" %% canonical parameter
              %assert ISFIELD(thisFcn, "Association")
              %assert SIZE(thisFcn.Association, 1) == thisFcn.NumArgs
              %assert !ISEMPTY("%<association>")
              %assign argSource = association
              %break
            %case "RTM"
            %case "LB" %% block IO
            %case "LC" %% constat block IO
            %case "LW" %% dwork
            %case "LP" %% parameter
            %case "LCP" %% constant parameter
            %case "LPI" %% const parameter with init
            %case "LX" %% continues states
            %case "LDX" %% derivatives
            %case "LXDI" %% continues state disabled
            %case "LXAT" %% continues state absolute tolerance
            %case "LXPTMIN" %% continues state perturb min
            %case "LXPTMAX" %% continues state perturb max
            %case "LZ" %% non-sampled zero crossings
            %case "LZE" %% zero crossing events
            %case "X" %% unknown argument
            %case "LCDG"
        %case "U" %% external input
              %break
            %default
              %%START_ASSERT
              %assign errTxt = "Unhandled argument type '%<argSrc>'."
              %<LibBlockReportError([],errTxt)>
              %break
              %%END_ASSERT
          %endswitch
          %assign argSourceVec = argSourceVec + argSource
          %if ISFIELD(thisFcn, "Association")
            %assign associationVec = associationVec + association
          %endif
          %assign numArgs = numArgs + 1
        %endif
      %endforeach
    %endif
     
    %createrecord BlkFcnRec { /
      FcnName fcnName; /
      ArgInfo [%<args>]; /
      Outputs [%<outStr>]; /
      OutDimSizeDW [%<outDWStr>]; /
      Inputs [%<inStr>]; /
      InDimSizeDW [%<inDWStr>]; /
      PrmArgs [%<prmStr>]; /
      PrmTypes prmType; /
      PrmIsPointer prmIsPtr; /
      DWArgs [%<canDWStr>]; /
      NumArgs numArgs; /
      ArgSource argSourceVec; /
      Association associationVec; /
      CGIRName cgirName /
    }
 
    %assign ::BlockFcn = "Unknown"
  %endwith %% thisSystem.Interface
 
  %createrecord retRec { /
  SysFcnName "%<sysFcnName>"; /
  FcnRec %<BlkFcnRec>/
  }
  %return retRec
%endfunction
 
 
%%FunctionFcnAppendToBlockInterface=========================================
%%Abstract:
%%ThefollowingorderisusedinFcnGetAdditionalArgsand
%%FcnAddNeededParameter.Wemustusethesameorder:
%%Tid
%%oIdx,
%%rIdx,
%%CanonicalInput
%%CanonicalDWorkforCanonicalInput
%%CanonicalOutput
%%CanonicalDWorkforCanonicalOutput
%%RTModel
%%BlockIO
%%ConstBlockIO(notneeded.Thisisglobalforallinstances)
%%DWork
%%Prm(?)
%%ContStates
%%ContStatesDerivative
%%ContStatesDisabled
%%ContStatesAbsoluteTolerance
%%ContStatesPerturbMin
%%ContStatesPerturbMax
%%NonsampledZC
%%ZCEvent
%%NumCanonicalPrm
%%CanDWork(?)
%%
%function FcnAppendToBlockInterface(sysIdx, accessSysIdx, blockFcn, tid, blkInterface) void
   
  %assign fcnRec = CreateModelReferenceFcnRec(sysIdx, blockFcn, "", tid, blkInterface, TLC_FALSE)
   
  %assign fcnName = fcnRec.SysFcnName
  %assign BlkFcnRec = fcnRec.FcnRec
   
  %if fcnName != ""
    %addtorecord blkInterface %<fcnName> %<BlkFcnRec>
  %endif
 
%endfunction %%FcnAppendToBlockInterface
 
%%Function:FcnCacheMRRegFcnLocalVars======================================
%%Abstract:
%%Thisfunctionaddstheneededlocalvariablestotheregistrationfunction
%%bodye.g."localB,localDW,localX..."
%%Theadditionallocalvariablesareneededifwearedoingamodelref
%%scalablebuild.e.g.
%%
%%voidmr_ModelName_intialize(constint32_T*rtu_0,int32_T*rty_0)
%%{
%%rtB_mr_myecdemo*localB=&(mr_myecdemo_DW.rtb);
%%rtDW_mr_myecdemo*localDW=&(mr_myecdemo_DW.rtdw);
%%....
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function FcnCacheMRRegFcnLocalVars(thisSystem) void
   
  %assign thisSystem.CurrentTID = ""
  %assign currentTID = ""
  %assign isPeriodicRateGrouping = SLibSystemFcnPeriodicRateGrouping(thisSystem, "Registration")
 
  %assign ::BlockFcn = "Registration"
   
  %with thisSystem.Interface
    %% Args: [TID, rtModel, BlockIo, DWork, CState, CStateDriv, CStateDis, ZC, ZCEvent]
    %%rtModel
    %assign val = FcnArgNeeded(RTMArgDef,currentTID,isPeriodicRateGrouping)
    %if val && IsModelRefScalableBuild() && !SLibIsSelfInPluggableInterface()
      %openfile localRTMVar
      %assign rtmAccess = ".rtm"
      %<SLibGetQualifiedRTMType()> *const %<::tSimStruct> = &(%<FcnGetSFcnDWorkIdentifier(thisSystem)>%<rtmAccess>);
      %closefile localRTMVar
      %<FcnCacheModelRefLocalVars(thisSystem, "Registration", "", localRTMVar)>
    %endif
     
    %% CoderDataGroups
    %if !CompiledModel.SuppressSelf
      %openfile coderDataGroupVar
      %foreach gIdx = ::CompiledModel.NumCoderDataGroups
        %assign group = ::CompiledModel.CoderDataGroup[gIdx]
        %if SLibIsGroupSelfCoderGroup(group)
          %continue
        %endif
        %assign groupToken = "CoderDataGroup" + group.Name
        %assign argDef = %
        %if FcnArgNeeded(argDef,currentTID,isPeriodicRateGrouping)
          %assign varGroupIdx = FcnSysVarGroupIndex(thisSystem, groupToken, 0)
          %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
          %assign varGroupType = FcnSysVarGroupType(thisSystem, groupToken)
          %assign varName = varGroup.LocalName
          %assign typeQualifier = SLibTypeQualifierForGroup(group)
          %% Based on the SuprressSelf logic, we can get here when either the model is multi-instance
          %% or self has a coder datagroup.
          %% In multi-instance case, self is structured or there is no self (RTM would be used).
          %% In single-instance case (self vargroup is AsStructureNone) we access group instance.
          %if SLibAccessGroupThroughSelf(group) && ...
            (::CompiledModel.SelfCoderDataGroupIndex == -1 || SLibIsSelfStructured())
            %<typeQualifier> %<varGroupType> *%<varName> = %<SLibGetCoderDataGroupPointerFromRTM(group, 1)>;
          %else
            %<typeQualifier> %<varGroupType> *%<varName> = &%<SLibCoderDataGroupInstance(group)>;
          %endif
        %endif
      %endforeach
      %closefile coderDataGroupVar
      %if !ISEMPTY(coderDataGroupVar)
        %<FcnCacheModelRefLocalVars(thisSystem, "Registration", "", coderDataGroupVar)>
      %endif
    %endif
     
    %% Service port initialization
    %if SLibCacheAndRestoreServiceDWorkNeeded()
      %openfile servicePortVars
      %<SLibCacheServicePortDWork()>
      %closefile servicePortVars
      %if !ISEMPTY(servicePortVars)
        %<FcnCacheModelRefLocalVars(thisSystem, "Registration", "", servicePortVars)>
      %endif
    %endif
     
    %% Continuous States argument
    %assign val = FcnArgNeeded(ContStatesArgDef,currentTID,isPeriodicRateGrouping)
    %if (val && IsModelRefScalableBuild()) && !::CompiledModel.ModelRefSimpInterface
      %openfile localCStateVar
      %assign varGroupType = FcnSysVarGroupType(thisSystem,"ContStates")
      %<varGroupType> *localX = (%<varGroupType> *) localX_;
      %closefile localCStateVar
      %<FcnCacheModelRefLocalVars(thisSystem, "Registration", "", localCStateVar)>
    %endif
    %% Continuous States Derivative argument
    %assign val = FcnArgNeeded(ContStatesDerivativeArgDef,currentTID,isPeriodicRateGrouping)
    %if (val && IsModelRefScalableBuild()) && !::CompiledModel.ModelRefSimpInterface
      %openfile localCStateVar
      %assign varGroupType = FcnSysVarGroupType(thisSystem,"ContStatesDerivative")
      %<varGroupType> *localXdot = (%<varGroupType> *) localXdot_;
      %closefile localCStateVar
      %<FcnCacheModelRefLocalVars(thisSystem, "Registration", "", localCStateVar)>
    %endif
    %% Continuous States Disabled argument
    %assign val = FcnArgNeeded(ContStatesDisabledArgDef,currentTID,isPeriodicRateGrouping)
    %if (val && IsModelRefScalableBuild()) && !::CompiledModel.ModelRefSimpInterface
      %openfile localCStateVar
      %assign varGroupType = FcnSysVarGroupType(thisSystem,"ContStatesDisabled")
      %<varGroupType> *localXdis = (%<varGroupType> *) localXdis_;
      %closefile localCStateVar
      %<FcnCacheModelRefLocalVars(thisSystem, "Registration", "", localCStateVar)>
    %endif
    %% Continuous States Absolute Rolerance argument
    %assign val = FcnArgNeeded(ContStatesAbsoluteToleranceArgDef,currentTID,isPeriodicRateGrouping)
    %if (val && IsModelRefScalableBuild()) && !::CompiledModel.ModelRefSimpInterface
      %openfile localCStateVar
      %assign varGroupType = FcnSysVarGroupType(thisSystem,"ContStatesAbsoluteTolerance")
      %<varGroupType> *localXAbsTol = (%<varGroupType> *) localXAbsTol_;
      %closefile localCStateVar
      %<FcnCacheModelRefLocalVars(thisSystem, "Registration", "", localCStateVar)>
    %endif
     
    %% Continuous States Perturb Min argument
    %assign val = FcnArgNeeded(ContStatesPerturbMinArgDef,currentTID,isPeriodicRateGrouping)
    %if (val && IsModelRefScalableBuild()) && !::CompiledModel.ModelRefSimpInterface
      %openfile localCStateVar
      %assign varGroupType = FcnSysVarGroupType(thisSystem,"ContStatesPerturbMin")
      %<varGroupType> *localXPerturbMin = (%<varGroupType> *) localXPerturbMin_;
      %closefile localCStateVar
      %<FcnCacheModelRefLocalVars(thisSystem, "Registration", "", localCStateVar)>
    %endif
     
    %% Continuous States Perturb Max argument
    %assign val = FcnArgNeeded(ContStatesPerturbMaxArgDef,currentTID,isPeriodicRateGrouping)
    %if (val && IsModelRefScalableBuild()) && !::CompiledModel.ModelRefSimpInterface
      %openfile localCStateVar
      %assign varGroupType = FcnSysVarGroupType(thisSystem,"ContStatesPerturbMax")
      %<varGroupType> *localXPerturbMax = (%<varGroupType> *) localXPerturbMax_;
      %closefile localCStateVar
      %<FcnCacheModelRefLocalVars(thisSystem, "Registration", "", localCStateVar)>
    %endif
     
    %% Non Sampled Zero Crossing argument
    %assign val = FcnArgNeeded(ZCSVArgDef,currentTID,isPeriodicRateGrouping)
    %if (val && IsModelRefScalableBuild()) && !::CompiledModel.ModelRefSimpInterface
      %openfile localCStateVar
      %assign varGroupType = FcnSysVarGroupType(thisSystem,"ZCSV")
      %<varGroupType> *localZCSV = (%<varGroupType> *) localZCSV_;
      %closefile localCStateVar
      %<FcnCacheModelRefLocalVars(thisSystem, "Registration", "", localCStateVar)>
    %endif
    %assign ::BlockFcn = "Unknown"
  %endwith %% System[sysIdx].Interface
 
%endfunction %%FcnCacheMRRegFcnLocalVars
 
%%Function:FcnCacheModelRefFcnLocalVars======================================
%%Abstract:
%%Thisfunctionaddstheneededlocalvariablestothefunctionbody.
%%e.g."localB,localDW,localX..."
%%Theadditionallocalvariablesareneededifwearedoingamodelref
%%scalablebuild.e.g.
%%
%%voidmr_ModelName(constint32_T*rtu_0,int32_T*rty_0)
%%{
%%rtB_mr_myecdemo*localB=&(mr_myecdemo_DW.rtb);
%%rtDW_mr_myecdemo*localDW=&(mr_myecdemo_DW.rtdw);
%%....
%%
%function FcnCacheModelRefLocalVars(system, function, tid, localVars) void
  %assign cacheName = "MR" + function + "%<tid>" + "LocalVars"
  %if !LibIsSystemField(system, cacheName)
    %<LibAddToSystem(system, cacheName, localVars)>
  %else
    %<LibAddToSystemField(system, cacheName, localVars)>
  %endif
%endfunction
 
%%Function:SLibResetModelRefFcnLocalVars====================================
%%Abstract:
%%Thisfunctionresetsthelistofneededlocalvariablesforthefunctionbody.
%function SLibResetModelRefLocalVars(system, function, tid) void
  %assign cacheName = "MR" + function + "%<tid>" + "LocalVars"
  %if LibIsSystemField(system, cacheName)
    %<LibSetSystemField(system, cacheName, "")>
  %endif
%endfunction
 
%%Function:FcnDumpModelRefFcnLocalVars======================================
%%Abstract:
%%Thisfunctionaddstheneededlocalvariablestothefunctionbody.
%%e.g."localB,localDW,localX..."
%%Theadditionallocalvariablesareneededifwearedoingamodelref
%%scalablebuild.e.g.
%%
%%voidmr_ModelName(constint32_T*rtu_0,int32_T*rty_0)
%%{
%%rtB_mr_myecdemo*localB=&(mr_myecdemo_DW.rtb);
%%rtDW_mr_myecdemo*localDW=&(mr_myecdemo_DW.rtdw);
%%....
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function FcnDumpMRLocalVars(system, function, tid) void
 
  %if !IsModelReferenceBaseSys(system)
    %return ""
  %endif
   
  %if ::GenerateClassInterface
    %return ""
  %endif
   
  %% For functions that don't use rate-grouping, make sure we clear out the TID
  %if !SLibSystemFcnIsRateGroupType(function)
    %assign tid = ""
  %endif
 
  %assign cacheName = "MR" + function + "%<tid>" + "LocalVars"
  %if LibIsSystemField(system, cacheName)
    %assign cacheVal = LibGetSystemField(system, cacheName)
    %if !WHITE_SPACE(cacheVal)
      %return cacheVal
    %endif
  %endif
  %return ""
%endfunction
 
 
%%Function:SLibModelReferenceAppendInputsOutputs============================
%%Abstract:
%%UsedforthemodelreferenceSIMtargettodefinetheargumentsto
%%afunction,orcallthatfunctionfromtheS-Function.
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%TopTester:test/toolbox/simulink/variants/variantBus/tVariantBusGecks.m
%%
%function SLibModelReferenceAppendInputsOutputs(blockFcn, ...
  fcnName, isPeriodicRateGrouping, currentTID, recArgs) void
  %assign origBlockFcn = ::BlockFcn
  %assign ::BlockFcn = blockFcn
  %assign baseSystem = ::CompiledModel.System[GetBaseSystemIdx()]
  %assign modIdx = baseSystem.CGIRModuleIdx
  %assign thisModule = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
   
  %with baseSystem.Interface
    %%
    %% The following TLC code is used to prune the CGIR function call
    %% arguments and transfer the CGIR argument tracking
    %% information to the legacy TLC tracking infrastructure.
    %%
    %assign skipCanInput = ...
      Vector(%<NumCanonicalInputArgDefs>) [0@%<NumCanonicalInputArgDefs>]
    %assign skipInputDims = ...
      Vector(%<NumCanonicalInputArgDefs>) [0@%<NumCanonicalInputArgDefs>]
    %assign skipCanOutput = ...
      Vector(%<NumCanonicalOutputArgDefs>) [0@%<NumCanonicalOutputArgDefs>]
    %assign skipOutputDims = ...
      Vector(%<NumCanonicalOutputArgDefs>) [0@%<NumCanonicalOutputArgDefs>]
    %assign skipCanDWork = ...
      Vector(%<NumCanonicalDWorkArgDefs>) [0@%<NumCanonicalDWorkArgDefs>]
    %assign skipCanParam = ...
      Vector(%<NumCanonicalPrmArgDefs>) [0@%<NumCanonicalPrmArgDefs>]
       
    %if !ISEMPTY(fcnName) && ISFIELD(thisModule, "SystemFunctions") && ...
      ISFIELD(thisModule.SystemFunctions, fcnName)
      %assign fcnIndex = GETFIELD(thisModule.SystemFunctions, fcnName)
      %assign thisFcn = thisModule.Function[fcnIndex]
      %assign irParams = FEVAL("regexprep", thisFcn.ProtoType, ...
        "^[^/(]*/(", "")
      %if !ISEMPTY(cgirParams) && !WHITE_SPACE(cgirParams)
        %assign recArgs = recArgs + irParams
      %endif
      %foreach argIdx=thisFcn.NumArgs
        %if thisFcn.ArgAccessed[argIdx] > 0
          %assign idNum = SLibSafeIDNUM(thisFcn.ArgSource, argIdx)
          %assign argSrc = idNum[0]
          %assign argSrcIdx = idNum[1]
          %switch argSrc
            %case "I"
              %assign skipCanInput[argSrcIdx] = 1
              %break
            %case "O"
              %assign skipCanOutput[argSrcIdx] = 1
              %break
            %case "D"
              %assert ISFIELD(thisFcn, "Association")
              %assert SIZE(thisFcn.Association, 1) == thisFcn.NumArgs
              %assign dimsIdNum = SLibSafeIDNUM(thisFcn.Association, argIdx)
              %assign dimsSrc = dimsIdNum[0]
              %assign dimsSrcIdx = dimsIdNum[1]
              %assert "I" == dimsSrc || "O" == dimsSrc
              %if "I" == dimsSrc
                %assign skipInputDims[dimsSrcIdx] = 1
              %else
                %assign skipOutputDims[dimsSrcIdx] = 1
              %endif
              %assign skipCanDWork[argSrcIdx] = 1
              %break
            %case "P"
              %assign skipCanParam[argSrcIdx] = 1
              %break
            %case "RTM"
            %case "X"
              %break
            %default
              %%START_ASSERT
              %assign errTxt = "Unhandled argument type '%<argSrc>'."
              %<LibBlockReportError([],errTxt)>
              %break
              %%END_ASSERT
          %endswitch
        %endif
      %endforeach
    %endif
         
    %foreach argIdx = NumCanonicalInputArgDefs
      %if !skipCanInput[argIdx] && ...
        FcnArgNeeded(CanonicalInputArgDef[argIdx], currentTID,isPeriodicRateGrouping)
        %assign ci = CanonicalInputArgDef[argIdx]
        %assign identi = LibGetRecordIdentifier(ci)
        %assign dataType = SLibGetRecordDataTypeName(ci, "")
        %assign optWidth = LibOptionalVectorWidth(LibGetRecordWidth(ci))
        %assign optStar = (LibGetRecordWidth(ci) == 1 && ...
          !(IsModelReferenceRTWTarget() && !FcnPassCanonicalInputByPtr(ci))) ? " *" : " "
        %assign dataType = "const %<dataType> "
        %if SLibGetCanIOIsVarDims(ci)
          %assign argDef = dataType + identi + "[]"
        %else
          %assign argDef = dataType + optStar + identi + optWidth
        %endif
        %assign recArgs = recArgs + argDef
      %endif
      %if !skipInputDims[argIdx]
        %assign recArgs = ...
          AppendModelReferenceRegFcnInputCanDimSizeDWArgs(argIdx, ...
          currentTID, isPeriodicRateGrouping, recArgs)
      %endif
    %endforeach
 
    %foreach argIdx = NumCanonicalOutputArgDefs
      %if !skipCanOutput[argIdx] && ...
        FcnArgNeeded(CanonicalOutputArgDef[argIdx], currentTID,isPeriodicRateGrouping)
        %assign co = CanonicalOutputArgDef[argIdx]
        %assign identi = LibGetRecordIdentifier(co)
        %assign dataType = SLibGetRecordDataTypeName(co, "")
        %assign optStar = LibGetRecordWidth(co) == 1 ? " *" : " "
        %assign optWidth = LibOptionalVectorWidth(LibGetRecordWidth(co))
        %if SLibGetCanIOIsVarDims(co)
          %assign argDef = dataType + " " + identi + "[]"
        %else
          %assign argDef = dataType + optStar + identi + optWidth
        %endif
        %assign recArgs = recArgs + argDef
      %endif
      %if !skipOutputDims[argIdx]
        %assign recArgs = ...
          AppendModelReferenceRegFcnOutputCanDimSizeDWArgs(argIdx, ...
          currentTID, isPeriodicRateGrouping, recArgs)
      %endif
    %endforeach
 
     
    %foreach argIdx = NumCanonicalPrmArgDefs
      %if !skipCanParam[argIdx] && ...
        FcnArgNeeded(CanonicalPrmArgDef[argIdx], currentTID,isPeriodicRateGrouping)
        %assign prm = CanonicalPrmArgDef[argIdx]
        %assign identi = LibGetRecordIdentifier(prm)
        %assign dataType = SLibGetRecordDataTypeName(prm, "")
        %assign width = LibBlockParameterWidth(prm)
        %assign optWidth = LibOptionalVectorWidth(width)
        %assign declAsPtr = prm.DeclareAsPointer == "yes"
        %assign optConst = ((width > 1) || declAsPtr) ? "const " : ""
        %assign dataType = "%<optConst>%<dataType> "
        %assign optStar = declAsPtr ? " *" : " "
        %assign argDef = dataType + optStar + identi + optWidth
        %assign recArgs = recArgs + argDef
      %endif
    %endforeach
 
  %endwith
 
  %assign ::BlockFcn = origBlockFcn
  %return recArgs
   
%endfunction
   
   
 
%%Function:SLibModelReferenceRegFcnArgs===================================
%%Abstract:
%%Generatemodelfcnarglist.
%%
%%Thefollowingordershouldbemaintianiedforrefargs.SeeGetFunctionStr()
%%TID
%%CanonicalInput
%%CanonicalDWorkforCanonicalInput
%%CanonicalOutput
%%CanonicalDWorkforCanonicalOutput
%%SimStruct
%%rtModel
%%BlockIO
%%ConstBlockIO(?)
%%DWork
%%Prm(?)
%%ContStates
%%ContStatesDerivative
%%ContStatesDisabled
%%NonsampledZC
%%ZCEvent
%%MassMatrix
%%NumCanonicalPrm
%%CanDWork(?)
%%C-APIrequiredarguments(optional)
%%osysRan(mdlrefsimtargetrequired)
%%osysTID(mdlrefsimtargetrequired)
%%oMMI(mdlrefsimrequired,rtwtargetifRTWCAPI==true)
%%oblockPath(mdlrefsimrequired,rtwtargetifRTWCAPI==true)
%%ochildIdx(mdlrefsimrequired,rtwtargetifRTWCAPI==true)
%%oContStateIdx(mdlrefsimrequired,rtwtargetifRTWCAPI==true)
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%TopTester:test/toolbox/simulink/variants/tVariantGecks.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortReset3.m
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibModelReferenceRegFcnArgs() void
  %assign recArgs = []
  %assign rootSystem = System[NumSystems-1]
  %assign baseSystem = System[NumSystems-2]
  %assign isPeriodicRateGrouping = SLibIsMultiRateAndPeriodicRateGrouping(rootSystem)
 
  %assert IsModelReferenceTarget()
   
  %assign ::BlockFcn = "Registration"
 
  %if !IsModelReferenceForASimstructBasedTarget()
    %% ModelInitializeIsEmpty is computed in ertreg.tlc
    %% Why do we need this? Who calls it with 0?
    %if SLibGetNeedFirstTime()
      %assign recArgs = recArgs + "boolean_T %<SLibFirstTime()>"
    %endif
 
    %if !SuppressErrorStatus
      %assign recArgs = recArgs + "const char_T **rt_errorStatus"
    %endif
 
    %if RTMStopReqAccessed() || ::CompiledModel.ModelBlocksUseStopReq
      %assign recArgs = recArgs + "boolean_T *rt_stopRequested"
    %endif
 
    %if LibIsContinuous(0) || SLibModelHierarchyContainsNoninlinedSfcn()
      %assign recArgs = recArgs + "RTWSolverInfo *rt_solverInfo"
    %endif
     
    %if SLibModelHierarchyContainsNoninlinedSfcn()
      %assign recArgs = recArgs + "RTWSfcnInfo *rt_sfcnInfo"
    %endif
   
  %endif
   
  %% Add the canonical inputs/outputs to the interface
  %assign recArgs = SLibModelReferenceAppendInputsOutputs(...
    "Registration", "", isPeriodicRateGrouping, rootSystem.CurrentTID, recArgs)
   
  %if IsModelReferenceForASimstructBasedTarget()
    %assign recArgs = recArgs + "%<tMdlRefSfcnSType> %<tMdlRefSfcnS>"
     
    %if RTMIsVarStepSolver() && HasNonContSigFeedingOutport()
      %assign recArgs = recArgs + "ssNonContDerivSigFeedingOutports **mr_nonContOutputArray"
    %endif
  %endif %% !IsModelReferenceForASimstructBasedTarget()
   
  %% Add information to generate the correct model block's
  %% initialize function signature
  %if ISFIELD(::CompiledModel, "NumDataTransfers") && ::CompiledModel.NumDataTransfers > 0
    %assign recArgs = recArgs + "const uint32_T *gblDataTransferIds"
  %endif
   
  %% Pass the timing info to the registration function, we only
  %% do this for non simstruct based targets.
  %if !IsModelReferenceForASimstructBasedTarget() && ...
    ::tMdlRefTimingBridgeAccessed
    %assert SLibIsERTCodeFormat()
    %assign recArgs = recArgs + "const rtTimingBridge *timingBridge"
  %endif
 
  %if !IsModelReferenceForASimstructBasedTarget() && ...
    SLibModelHasControllableRate()
    %assert SLibIsERTCodeFormat()
    %assign recArgs = recArgs + "rtCtrlRateMdlRefTiming *CtrlRateMdlRefTimingPtr"
  %endif
   
  %% Only loop over the sample times if the model reference
  %% block will not become constant/triggered.
  %if ::tMdlRefNeedTIDArgs
    %if !MdlRefIsConstSampleBlock() || MdlRefHasParameterRate()
      %foreach idx = SLibGetNumTIDsForGlobalTIDMap()
        %% skip service task tid which is
        %% used for service infrastructure only
        %if SLibIsServiceTaskTID(idx)
          %continue
        %endif
        %assign recArgs = recArgs + "int_T mdlref_TID%<idx>"
      %endforeach
    %else
      %assign recArgs = recArgs + "int_T mdlref_TID0"
    %endif
   
    %if SLibModelNeedsTriggerTIDArg()
      %assign recArgs = recArgs + "int_T mdlref_TriggerTID"
    %endif
  %endif
  %assign selfAccess = ::CompiledModel.ModelRefSimpInterface || SLibGetDoesSelfExist()
  %with baseSystem.Interface
    %if !IsModelRefScalableBuild()
      %if FcnArgNeeded(RTMArgDef,rootSystem.CurrentTID,isPeriodicRateGrouping) || selfAccess
        %assign rtmArg = SLibGetQualifiedRTMType() + " *const %<::tSimStruct>"
        %assign recArgs = recArgs + rtmArg
      %endif
      %if FcnArgNeeded(BlockIOArgDef,rootSystem.CurrentTID,isPeriodicRateGrouping) && !selfAccess
        %assign blockIOCallee = "localB"
        %assign blockIOType = FcnSysVarGroupType(System[NumSystems-2],"BlockIO")
        %assign recArgs = recArgs + "%<blockIOType> *%<blockIOCallee>"
      %endif
      %if FcnArgNeeded(DWorkArgDef,rootSystem.CurrentTID,isPeriodicRateGrouping) && !selfAccess
        %assign dworkCallee = "localDW"
        %assign dworkType = FcnSysVarGroupType(System[NumSystems-2],"DWork")
        %assign recArgs = recArgs + "%<dworkType> *%<dworkCallee>"
      %endif
    %endif %% scalable
    %if FcnArgNeeded(ContStatesArgDef,rootSystem.CurrentTID,isPeriodicRateGrouping)
      %assign contState = IsModelRefScalableBuild() ? ...
        "localX_" : "localX"
      %assign contStateType = IsModelRefScalableBuild() ? ...
        "real_T" : FcnSysVarGroupType(System[NumSystems-2],"ContStates")
      %assign recArgs = recArgs + "%<contStateType> *%<contState>"
    %endif
    %if FcnArgNeeded(ContStatesDerivativeArgDef, ...
      rootSystem.CurrentTID,isPeriodicRateGrouping)
      %assign contDerivState = IsModelRefScalableBuild() ? ...
        "localdX_" :"localdX"
      %assign contDerivStateType = IsModelRefScalableBuild() ? ...
        "real_T" : FcnSysVarGroupType(System[NumSystems-2],"ContStatesDerivative")
      %assign recArgs = recArgs + "%<contDerivStateType> *%<contDerivState>"
    %endif
    %if !IsModelRefScalableBuild()
      %if FcnArgNeeded(ZCEventArgDef,rootSystem.CurrentTID,isPeriodicRateGrouping)
        %assign prevZCCallee = "localZCE"
        %assign prevZCEvType = FcnSysVarGroupType(System[NumSystems-2],"ZCEvent")
        %assign recArgs = recArgs + "%<prevZCEvType> *%<prevZCCallee>"
      %endif
    %endif
     
    %if (::CompiledModel.ModelIsLinearlyImplicit == "yes")
      %assign prevMMCallee = "localMM"
      %assign prevMMType = "real_T"
      %assign recArgs = recArgs + "%<prevMMType> *%<prevMMCallee>"
    %endif
       
  %endwith
   
  %%
  %% Pass in the initial context system and tid
  %%
  %if IsModelReferenceSimTarget()
    %assign recArgs = recArgs + "void *sysRanPtr"
    %assign recArgs = recArgs + "int contextTid"
  %endif
   
  %%
  %if (RTWCAPI == 1) && !GenerateClassInterface
    %assign recArgs = recArgs + "rtwCAPI_ModelMappingInfo *rt_ParentMMI"
    %assign recArgs = recArgs + "const char_T *rt_ChildPath"
    %assign recArgs = recArgs + "int_T rt_ChildMMIIdx"
    %assign recArgs = recArgs + "int_T rt_CSTATEIdx"
  %endif
   
  %assign ::BlockFcn = "Unknown"
 
  %if ISEMPTY(recArgs)
    %return "void"
  %endif
   
  %return SLibSerializeFcnArgs(recArgs)
%endfunction %%SLibModelReferenceRegFcnArgs
 
 
%%Function:FcnGetNoncontMangledName==========================================
%%Abstract:
%%Getthemanglednameforthearrayofnoncontinuoussignals.
%function FcnGetNoncontMangledName(name, systemIdx, blockIdx, instIdx) void
  %assign instance = instIdx < 0 ? 0 : instIdx
  %return "%<name>_%<systemIdx>_%<blockIdx>_%<instance>"
%endfunction
 
%%Function:FcnCheckForConstConsistency======================================
%%Abstract:
%%Checkwhetherthemodelbeingcalledpassesthesignalasanon-const
%%pointer,yetthissignalisaconstargtothismodel'sstepfunction.
%%block,argIdx,portIdx,andFPCallpertaintothesubmodelbeingcalled.
%%TopTester:test/toolbox/simulink/variants/normalMATLABVariableSupport/tNormalMatlabVariable2.m
%%
%function FcnCheckForConstConsistency(sysIdx, block, argIdx, portIdx, FPC) void
  %% See if the signal is passed to the child model by pointer or reference,
  %% without a const qualifier; if not, exit.
  %if FPC.ArgSpecData[argIdx].Category != "Pointer" && ...
      FPC.ArgSpecData[argIdx].Category != "Reference"
    %return TLC_TRUE
  %endif
  %assign hasConstQualifier = TLC_FALSE
  %switch FPC.ArgSpecData[argIdx].Qualifier
    %case "none"
      %break
    %case "const"
    %case "const *"
    %case "const * const"
    %case "const &"
      %assign hasConstQualifier = TLC_TRUE
      %break
    %default
      %assign errTxt = "Unhandled qualifier"
      %<LibReportFatalError(errTxt)>
      %break
  %endswitch
  %if hasConstQualifier
    %return TLC_TRUE
  %endif
     
  %% If we get to this point, the child model passes the input by pointer or ref
  %% without a const qualifier. Now see if the parent model or reusable
  %% subsystem declares the input with a const qualifier
   
  %assign portObj = FcnGetInputPortRecord(portIdx)
  %% We only have to check element 0 because if the input to the mdlref block
  %% is discontiguous, we insert a hidden buffer, and then the signal can't be
  %% const. We only can get const if the input arg is specified as const by FPC
  %% and passed directly into the mdlref block.
  %assign sigRecAndMapInfo = ...
    SLibGetSourceRecordAndMapInfo(portObj, 0, TLC_TRUE, TLC_TRUE)
   
  %% See if the signal is coming from the root inport in the parent model; if not,
  %% no worry: it is not const.
  %if sigRecAndMapInfo.mapSrc == "U"
    %if SLibFcnProtoCtrlActive() || ...
        GenerateClassInterface
     %assign sigRec = sigRecAndMapInfo.sigRec
     
     %% Trouble if the root input is passed as const
     %if FcnPassExternalInputAsConst(sigRec)
       %return TLC_FALSE
     %else
       %return TLC_TRUE
     %endif
 
    %% Just a "vanilla" root input; no problem.
    %else
      %return TLC_TRUE
    %endif
 
  %% If a canonical input
  %elseif sigRecAndMapInfo.mapSrc == "u"
    %assign sigRec = sigRecAndMapInfo.sigRec
     
    %% Default interface model reference build interface has const from IR
    %if GenerateClassInterface && IsModelReferenceTarget() && ...
      (::CompiledModel.RTWFcnCPPClass.Object.Class == "ModelCPPDefaultClass")
      %return TLC_FALSE
    %endif
 
    %% Trouble if the canonical input is passed as const
    %if FcnPassCanonicalInputAsConst(sysIdx, sigRec)
      %return TLC_FALSE
    %else
      %return TLC_TRUE
    %endif
  %elseif sigRecAndMapInfo.mapSrc == "C"
    %%%% The source is a constant
    %return TLC_FALSE
  %else
    %return TLC_TRUE
 
  %endif
 
%endfunction
 
%function SLibAttachIRTEventArgs(block, args)
  %foreach tid = NumSampleTimes
    %if SLibInitResetTermEventTID(tid)
      %assign childTid = MapParentTID2ChildTID(block, tid)
      %if childTid != -1
        %assign args = args + STRING(tid)
      %endif
    %endif
  %endforeach
  %return args
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/normalMATLABVariableSupport/tNormalMatlabVariable2.m
%%
%function SLibAttachTimingArgsForCPPEncap(block, blockInterface, inArgs)
  %assert SLibIsCPPEncapMdlRefBuild() || ...
          (GenerateClassInterface && block.MdlRefIsCPPClassGenMode)
  %assign args = inArgs
  %if !IsModelReferenceForASimstructBasedTarget()
    %if blockInterface.NeedsGlobalTimingEngine
      %if IsModelReferenceTarget()
        %assign args = args + "%<SLibGetGlobalTimingBridge()>"
      %else
        %assign args = args + "&%<SLibGetGlobalTimingBridge()>"
      %endif
    %endif
  %endif
   
  %% If the block is completely constant, then just
  %% pass 0 as the TID. If it is inherited, pass the
  %% TID that this instance is running at. This will
  %% help with data logging.
  %if blockInterface.NeedsTIDArgs
    %assign ::tMdlRefNeedTIDArgs = TLC_TRUE
    %assign blockTid = block.TID
    %if TYPE(blockTid) == "Vector"
      %assign nonModelWideEventTids = []
      %assign numTids = SIZE(blockTid)[1]
      %foreach idx = numTids
        %if !SLibModelWideEventTID(blockTid[idx])
          %assign nonModelWideEventTids = nonModelWideEventTids + blockTid[idx]
        %endif
      %endforeach
      %if SIZE(nonModelWideEventTids)[1] == 1
        %assign blockTid = nonModelWideEventTids[0]
      %endif
    %endif
    %if TYPE(blockTid) != "Identifier"
      %if LibAsynchronousTriggeredTID(blockTid)
        %% if it is in async fcn-call subsystem,
        %% pass -1
        %assign args = args + "-1"
      %else
        %% constant is handled in the loop
        %foreach idx = NumRuntimeExportedRates
          %assign childTID = MapParentTID2ChildTID(block, idx)
          %if childTID != -1
            %if IsModelReferenceTarget()
              %assign args = args + "%<FcnGetMdlRefGlobalTIDMap("")>[%<idx>]"
            %else
              %assign args = args + "%<idx>"
            %endif
          %endif
        %endforeach
        %% Add parameter rate if used by model block, since that rate is not
        %% represented in the ChildTidToParentTidMap
        %if blockInterface.HasInternalParameterRate || ...
            blockInterface.HasParameterRateOutput
          %assign args = args + STRING(SLibTidOfParameterChangeEvent())
        %endif
         
        %% Add irt event rate if used by model block
        %assign args = SLibAttachIRTEventArgs(block, args)
      %endif
    %else
      %% There is only one TID in the model and it
      %% is constant/triggered, pass 0 if it is constant
      %% and pass -1 if it is triggered.
      %if ISEQUAL(blockTid, "triggered")
        %assign args = args + "-1"
      %else
        %assign args = args + "0"
      %endif
    %endif
     
    %if GetModelRefFcnCallTriggerTIDIsReq(block)
      %if SLibModelNeedsTriggerTIDArg()
        %assign args = args + "%<FcnGetMdlRefTriggerTIDMap("")>"
      %else
        %assert ISEQUAL(blockTid, "triggered") || ...
          LibAsynchronousTriggeredTID(blockTid)
        %if LibAsynchronousTriggeredTID(blockTid)
          %assign args = args + "%<blockTid>"
        %else
          %assign trigTid = block.TriggerTID[0]
          %if IsModelReferenceTarget()
            %assign args = args + "%<FcnGetMdlRefGlobalTIDMap("")>[%<trigTid>]"
          %else
            %assign args = args + "%<trigTid>"
          %endif
        %endif
      %endif
    %endif
  %endif
  %return args
%endfunction %%SLibAttachTimingArgsForCPPEncap
 
%%Function:SLibGetModelBlockInput============================================
%%Abstract:
%%Returntheinputforamodelreferenceblockandportindex
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants3.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortReset3.m
%%
%function SLibGetModelBlockInput(sysIdx, block, sysFcnName, mdlRefIdx, portIdx, ...
  canInputInfo, FPC, argIdx) void
  %assign arg = []
  %if sysFcnName == "RegistrationFcn"
    %assign baseSystem = ::CompiledModel.System[GetBaseSystemIdx()]
    %assign thisModelBlock = ::CompiledModel.ModelBlock[mdlRefIdx]
    %assign dataPort = thisModelBlock.DataInputPort[portIdx]
    %assign id = IDNUM(dataPort.SignalSrc[0])
    %switch id[0]
      %case "y"
        %assign canOut = baseSystem.Interface.CanonicalOutputArgDef[id[1]]
        %assign arg = LibGetRecordIdentifier(canOut)
        %<SLibAccessArgHelper(canOut,"","")>
        %if ISFIELD(dataPort, "BusSelElIdx")
          %assign arg = "(*%<arg>)%"
          %if dataPort.SignalOffset[0] == 0
            %assign arg = "&%<arg>"
          %endif
        %endif
        %if dataPort.SignalOffset[0] != 0
          %assign arg = "&(%<arg>[%])"
        %endif
        %break
      %case "u"
        %assign canIn = baseSystem.Interface.CanonicalInputArgDef[id[1]]
        %assign arg = LibGetRecordIdentifier(canIn)
        %<SLibAccessArgHelper(canIn,"","")>
        %if ISFIELD(dataPort, "BusSelElIdx")
          %assign arg = "(*%<arg>)%"
          %if dataPort.SignalOffset[0] == 0
            %assign arg = "&%<arg>"
          %endif
        %endif
        %if dataPort.SignalOffset[0] != 0
          %assign arg = "&(%<arg>[%])"
        %endif
        %break
      %default
        %with thisModelBlock
          %assign arg = LibBlockInputSignalAddr(portIdx, "", "", 0)
          %break
        %endwith
    %endswitch
  %else
    %assign isMatrix = LibBlockInputSignalIsMatrix(portIdx)
    %if isMatrix || (canInputInfo[portIdx] == 2) || ...
      (!IsFPCIgnored(FPC) && ...
      (FPC.ArgSpecData[argIdx].Category == "Pointer" || ...
      FPC.ArgSpecData[argIdx].Category == "Reference"))
      %assign calleePassByRef = !IsFPCIgnored(FPC) && FPC.ArgSpecData[argIdx].Category == "Reference"
      %if calleePassByRef
        %% To avoid code like *(&arr[0]). arr[0] is more desirable
        %assign arg = LibBlockInputSignal(portIdx, "", "", 0)
      %else
        %assign arg = LibBlockInputSignalAddr(portIdx, "", "", 0)
      %endif
       
      %assign dtypeName = LibBlockInputSignalDataTypeName(portIdx, "")
 
      %if calleePassByRef
        %% pass by reference (C++) case
        %if isMatrix
          %assign symbWidth = LibBlockInputSignalSymbolicWidth(portIdx)
          %assign arg = "(" + dtypeName + "(&)" + "[" + symbWidth + "])" + arg
        %endif
      %endif
       
      %if !IsFPCIgnored(FPC) && ...
        !FcnCheckForConstConsistency(sysIdx, block, argIdx, portIdx, FPC)
        %assign refModelName = block.ParamSettings.ReferencedModelName
 
        %assign argName = FPC.ArgSpecData[argIdx].ArgName
        %assign msgArgs = ["%<refModelName>", "%<block.Name>", "%<argName>", "%<argName>"]
 
        %if ::GenerateClassInterface && IsModelReferenceTarget() && ...
          (::CompiledModel.RTWFcnCPPClass.Object.Class == "ModelCPPDefaultClass")
          %<SLibReportErrorWithIdAndArgs(...
            "Simulink:modelReference:DefaultInterfaceConstInconsistency", ...
            msgArgs)>
        %endif
 
        %if ::GenCPP
          %if !IsFPCIgnored(FPC) && FPC.ArgSpecData[argIdx].Category == "Reference"
            %if !isMatrix
              %%%% scalar signal
              %assign arg = "const_cast<" + dtypeName + "&>(" + arg + ")"
            %endif
          %else
            %assign arg = "const_cast<" + dtypeName + "*>(" + arg + ")"
          %endif
        %else
          %assign arg = "(" + dtypeName + "*)" + arg
        %endif
         
        %if !block.MdlRefIsCPPClassGenMode
          %<SLibReportWarningWithIdAndArgs(...
            "Simulink:modelReference:WarnAboutConstCastPrototypeFeature", ...
            msgArgs)>
        %else
          %<SLibReportWarningWithIdAndArgs(...
            "Simulink:modelReference:WarnAboutConstCastIOArgFeature", ...
            msgArgs)>
        %endif
      %endif
      %<SLibInvokeTLCInterface(block, "Input", ...
        portIdx, 0, TLC_FALSE, "", "", 0, "")>
    %else
      %assign arg = LibBlockInputSignal(portIdx, "", "", 0)
    %endif
  %endif
  %return arg
%endfunction %% SLibGetModelBlockInput
 
%%Function:SLibGetModelBlockOutput===========================================
%%Abstract:
%%Returntheoutputforamodelreferenceblockandportindex
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibGetModelBlockOutput(sysFcnName, mdlRefIdx, portIdx, FPC, argIdx) void
  %assign passByPtr = ...
    IsFPCIgnored(FPC) || FPC.ArgSpecData[argIdx].Category == "Pointer"
  %assign passByRef = ...
    !IsFPCIgnored(FPC) && FPC.ArgSpecData[argIdx].Category == "Reference"
  %assign arg = []
  %if sysFcnName == "RegistrationFcn"
    %assign baseSystemIdx = GetBaseSystemIdx()
    %assign baseSystem = ::CompiledModel.System[baseSystemIdx]
    %assign thisModelBlock = ::CompiledModel.ModelBlock[mdlRefIdx]
    %assign dataPort = thisModelBlock.DataOutputPort[portIdx]
    %assign id = IDNUM(dataPort.SignalSrc[0])
    %switch (id[0])
      %case "y"
        %assign canOut = baseSystem.Interface.CanonicalOutputArgDef[id[1]]
        %assign arg = LibGetRecordIdentifier(canOut)
        %<SLibAccessArgHelper(canOut,"","")>
        %assert !ISFIELD(dataPort, "BusSelElIdx")
        %if dataPort.SignalOffset[0] != 0
          %% must be passed as pointer arg to parent
          %assert canOut.PassByReturn == "no"
          %% if child takes as pointer
          %if passByPtr
            %assign arg = "&%<arg>[%]"
            %% if child passes as return
          %else
            %assign arg = "%<arg>[%]"
          %endif
        %endif
        %% if passed by return from parent
        %if canOut.PassByReturn == "yes"
          %% if child takes as pointer
          %if passByPtr
            %assign arg = "&(%<arg>)"
            %% if child passes as retur
          %else
            %% do nothing
          %endif
          %% else passed to parent as arg
        %else
          %% if child takes as pointer
          %if passByPtr
            %% do nothing
            %% if child passes as return
          %else
            %assign arg = "*%<arg>"
          %endif
        %endif
        %break
      %case "b"
        %assign bo = ::CompiledModel.BlockOutputs.GlobalBlockOutput[id[1]]
        %%
        %assign cross = System[bo.SigSrc[0]].CrossNoArgFcnBound
        %assign name = SLibCG_GetVarGroupElementPath(bo.VarGroupIdx, ...
          baseSystemIdx, cross)
        %assign opW = SLibGet1DArrayIndexer(LibGetRecordSymbolicWidth(bo), "", "", dataPort.SignalOffset[0])
        %assign arg = "%<name>%<opW>"
        %if passByPtr
          %assign arg = "&(%<arg>)"
        %endif
        %break
      %case "E"
        %if passByPtr
          %assign arg = LibBlockOutputSignalAddr(portIdx, "", "", 0)
        %else
          %assign arg = LibBlockOutputSignal(portIdx, "", "", 0)
        %endif
        %break
    %endswitch
  %else
    %if passByPtr
      %assign arg = LibBlockOutputSignalAddr(portIdx, "", "", 0)
    %elseif passByRef
      %% C++ pass by reference
      %assign arg = LibBlockOutputSignal(portIdx, "", "", 0)
      %if LibBlockOutputSignalIsMatrix(portIdx)
        %assign dtypeName = LibBlockOutputSignalDataTypeName(portIdx, "")
        %assign symbWidth = LibBlockOutputSignalSymbolicWidth(portIdx)
        %assign arg = "(" + dtypeName + "(&)" + "[" + symbWidth + "])" + arg
      %endif
    %endif
  %endif
  %assert !ISEMPTY(arg) || (!passByPtr && !passByRef)
  %return arg
%endfunction %% SLibGetModelBlockOutput
 
%%Function:LibBlockParamNonVolatilePtrCast======================================
%%Abstract:
%%Getthecastthatdiscardsthevolatilityofablockparameterpointer.
%%TopTester:test/toolbox/simulink/variants/normalMATLABVariableSupport/tNormalMatlabVariable2.m
%%
%function LibBlockParamNonVolatilePtrCast(param)
  %assign record = FcnBlockParameterIdxMemberStr(param)
  %assign paramIdx = record.param
  %assign cast = ""
   
  %% Only care volatile custom storage
  %if (paramIdx[0] != -1) && (!paramIdx[1])
    %assign mdlParam = ::CompiledModel.ModelParameters.Parameter[paramIdx[0]]
    %assign storageClass = mdlParam.StorageClass
    %if storageClass == "Custom"
      %assign msDefn = SLibGetMemorySectionDefForData(mdlParam)
      %assign dtypeId = LibGetRecordDataTypeId(mdlParam)
      %assign cmplx = LibGetRecordIsComplex(mdlParam)
      %assign cast = LibGetNonVolatileCmplxPointerCast(msDefn, dtypeId, cmplx, "")
    %endif
  %endif
  %return cast
%endfunction %%LibBlockParamNonVolatilePtrCast
 
%%Function:LibBlockParameterAddrForModelBlock================================
%%Abstract:
%%GetBlockParameterAddresssforModelBlock
%%TopTester:test/toolbox/simulink/variants/normalMATLABVariableSupport/tNormalMatlabVariable2.m
%%
%function LibBlockParameterAddrForModelBlock(param, blkPrmIdx)
  %assign prmSize = SLibGetSizeOfValueFromParamRec(param)
  %assign nRows = prmSize[0]
  %assign nCols = prmSize[1]
  %assign memberStr = ""
 
  %if nRows > 1
    %assign errTxt = "Number of rows greater than 1. Must " ...
      "access parameter %<param.Name> using LibBlockMatrixParameterAddr."
    %<LibBlockReportError([], errTxt)>
  %endif
   
  %assign paramRef = SLibInvokeTLCInterface(SLibGetCurrentBlock(), ...
    "BlkParam", 0, blkPrmIdx, TLC_TRUE, "", "", 0, "")
 
  %assign cast = LibBlockParamNonVolatilePtrCast(param)
   
  %assign parsingEnabled = !ISEMPTY(paramRef)
  %if !parsingEnabled
    %return LibBlockParameterAddr(param, "", "", 0)
  %endif
 
  %return cast + paramRef
%endfunction
 
%%Function:LibBlockParameterForModelBlock
%%Abstract:
%%Getblockparameterforamodelblockwithparameterindex
%%Note:thisfunctionisadaptedfromLibBlockParameter
%%
%function LibBlockParameterForModelBlock(param, blkPrmIdx)
  %% Determine the parameter's true size
  %assign prmSize = SLibGetSizeOfValueFromParamRec(param)
  %assign nRows = prmSize[0]
  %assign nCols = prmSize[1]
  %assign width = nRows * nCols
 
  %if SLibGetTypeOfValueFromParamRec(param) == "Matrix"
    %% exit if the parameter is a true matrix,
    %% i.e., has more than one row or columns.
    %if nRows > 1
      %assign errTxt = "Must access parameter %<param.Name> using "...
        "LibBlockMatrixParameter."
      %<LibBlockReportError([], errTxt)>
    %endif
  %endif
  %with ::CompiledModel
    %assign accSysIdx = BlockIdx[0]
    %assign parentSys = System[accSysIdx]
    %if LibSystemIsRoot(parentSys)
      %assign callSite = [%<accSysIdx>, 0, %<accSysIdx>, %]
    %else
      %assign callSite = parentSys.CallSites[0]
    %endif
  %endwith
   
  %assign str = SLibInvokeTLCInterface(SLibGetCurrentBlock(), ...
      "BlkParam", 0, blkPrmIdx, TLC_FALSE, "", "", "", "")
 
  %assign tlcIFv2Enabled = !ISEMPTY(str)
      
  %if tlcIFv2Enabled
    %return SLibProcessSafeExpression(Name, ...
      (NEEDS_PAREN(str) ? "(%<str>)" : str), 0)
  %else
    %return LibBlockParameter(param, "", "", 0)
  %endif
%endfunction
 
%%Function:SLibGetBaseTypeNameIfVariableSizeLUTParam=========================
%%Abstract:
%%ReturnthebasenameofavariablesizeLUTobjecttypebystripping'$'and
%%followingchecksumstring.Returntheoriginaltypenameifthetypeisnota
%%variablesizeLUTobjecttype
%%
%function SLibGetBaseTypeNameIfVariableSizeLUTParam(aParamType)
    %assign p = CGMODEL_ACCESS("String.find", aParamType, "$")
    %if p >= 0
        %return CGMODEL_ACCESS("String.substr", aParamType, 0, p)
    %else
        %return aParamType
    %endif
%endfunction
 
%%Function:LibBlockParameterForMdlRef========================================
%%Abstract:
%%Returntheparameterforamodelreferenceblockandparameterindex
%%TopTester:test/toolbox/simulink/variants/normalMATLABVariableSupport/tNormalMatlabVariable2.m
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%
%function SLibGetModelBlockParameter(aBlock, aPrmIdx, aArgInfo, ...
  argType, isPointer) void
  %assign blkParam = aBlock.Parameter[aPrmIdx]
  %if isPointer
    %assign cast = ""
    %assign blkParamType = ...
      LibGetDataTypeNameFromId(LibGetRecordContainerDataTypeId(blkParam))
 
    %assign argType = SLibGetBaseTypeNameIfVariableSizeLUTParam(argType)
    %assign blkParamType = SLibGetBaseTypeNameIfVariableSizeLUTParam(blkParamType)
    %if argType != blkParamType
      %assign cast = "(" + argType + "*)"
    %endif
    %return cast + LibBlockParameterAddrForModelBlock(blkParam, aPrmIdx)
  %elseif aArgInfo == 1
    %return LibBlockParameterForModelBlock(blkParam, aPrmIdx)
  %else
    %return LibBlockParameterAddrForModelBlock(blkParam, aPrmIdx)
  %endif
%endfunction
 
%%Function:SLibGetModelBlockVarGroupPath=====================================
%%Abstract:
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibGetModelBlockVarGroupPath(aBaseSystemIdx, aBlock, aInstanceIdx) void
  %assign thisSystem = ::CompiledModel.System[aBlock.BlockIdx[0]]
  %assign category = FcnGetModelBlockDWorkCategory(aBlock)
  %if category == "Self"
    %assign thisSystem = ::CompiledModel.System[baseSystemIdx]
    %assign varGroupIdx = thisSystem.SelfVarGroupIndex
  %else
    %assign varGroupIdx = FcnSysVarGroupIndex(thisSystem, category, aInstanceIdx)
  %endif
 
  %assign cross = thisSystem.CrossNoArgFcnBound
  %assign varGroupPath = SLibCGIRVarGroupPath(varGroupIdx, aBaseSystemIdx, cross)
  %return varGroupPath
%endfunction %% SLibGetModelBlockVarGroupPath
   
%%Function:SLibGetModelBlockVarGroupRoot(=====================================
%%Abstract:
%%
%function SLibGetModelBlockVarGroupRoot(aBlock) void
  %assign thisSystem = ::CompiledModel.System[GetBaseSystemIdx()]
  %assign category = FcnGetModelBlockDWorkCategory(aBlock)
  %if category == "Self"
    %assign thisSystem = ::CompiledModel.System[baseSystemIdx]
    %assign varGroupIdx = thisSystem.SelfVarGroupIndex
  %else
    %assign varGroupIdx = FcnSysVarGroupIndex(thisSystem, category, 0)
  %endif
 
  %assign cross = thisSystem.CrossNoArgFcnBound
  %assign varGroupPath = SLibCGIRVarGroupPath(varGroupIdx, GetBaseSystemIdx(), cross)
  %return varGroupPath
%endfunction %% SLibGetModelBlockVarGroupPath
  
 
%function SLibGetSelfVarGroupIndexForModelBlock(aBlock, aInstanceIndex) void
  %assign thisSystem = ::CompiledModel.System[aBlock.BlockIdx[0]]
  %assign selfVarGroupIdx = FcnSysVarGroupIndex(thisSystem, "CoderDataGroup_self", aInstanceIndex)
  %if selfVarGroupIdx < 0
    %assign selfVarGroupIdx = aBlock.ModelInstVarGroupIndex + aInstanceIndex
  %endif
  %assert selfVarGroupIdx > -1
  %return selfVarGroupIdx
%endfunction
 
%%Function:SLibGetModelBlockStructDWorkArg===================================
%%Abstract:
%%Returnsthedworkelementofamodelreferenceblock,thatcontains
%%itsstructuredelements.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibGetModelBlockStructDWorkArg (...
  aDWorkEl, aBaseSystemIdx, aBlock, aSysFcnType, aInstanceIdx) void
  %if !ISEMPTY(aDWorkEl)
    %return aDWorkEl
  %endif
  %assign blockInterface = GetModelrefInterface(aBlock)
  %assign isInstSpecific = (ISFIELD(aBlock, "ModelInstVarIndex") && aBlock.ModelInstVarIndex > -1)
  %assign rtmContainedInSelf = isInstSpecific || ...
    (blockInterface.rtmAllocateInParent)
  %assign baseSys = ::CompiledModel.System[GetBaseSystemIdx()]
  %if (::CompiledModel.RTWCGModules.RTWCGModule[baseSys.CGIRModuleIdx].SimplifiedInterface && ...
    blockInterface.usesSimplifiedInterface) || (GenerateClassInterface && SLibGetUseRTMcgType())
    %assign globalAccess = (aSysFcnType == "RegistrationFcn")
    %assign rtmField = SLibGetModelInstVariableAddressForSimplifiedInterface(aBlock,aInstanceIdx,globalAccess)
    %if !WHITE_SPACE(rtmField)
      %return "(*" + rtmField + ")"
    %endif
  %endif
  %if rtmContainedInSelf && SLibGetSelfVarGroupIndex() > -1 && isInstSpecific
    %if aInstanceIdx > 1
      %assign selfVarGroupIdx = SLibGetSelfVarGroupIndexForModelBlock(aBlock, aInstanceIdx)
    %else
      %assign selfVarGroupIdx = SLibGetSelfVarGroupIndex()
    %endif
    %assign selfCGTypeIdx = ::CompiledModel.VarGroups.VarGroup[selfVarGroupIdx].CGTypeIdx
    %if selfCGTypeIdx < 0
      %assign group = ::CompiledModel.CoderDataGroup[SLibGetSelfCoderDataGroupIndex()]
      %return SLibCoderDataGroupElementInstance(group, aBlock.ModelInstVarIndex)
    %endif
    %if LibCGTypeIsMatrix(selfCGTypeIdx)
      %assign selfCGTypeIdx = LibCGTypeBaseIndex(selfCGTypeIdx)
    %endif
    %assign fldName = LibCGTypeMemberName(selfCGTypeIdx, aBlock.ModelInstVarIndex)
    %if selfVarGroupIdx != SLibGetSelfVarGroupIndex()
      %% here we are not at the root level
      %return ::CompiledModel.VarGroups.VarGroup[selfVarGroupIdx].LocalName + "->" + fldName
    %elseif IsModelReferenceTarget() && IsModelRefScalableBuild()
      %% here we are in a single instance model that contains multi instance child models
      %assign modelDW = FcnGetSFcnDWorkIdentifier(::CompiledModel.System[baseSystemIdx])
      %assign slfAccess = IsModelReferenceSimTarget() ? ".rtm." : "."
      %return modelDW + slfAccess + fldName
    %else
      %if SLibIsSelfStructured()
        %<SLibCG_AccessRTM()>
      %endif
      %assign modelRTM = ::tSimStruct
      %return modelRTM + "->" + fldName
    %endif
  %elseif blockInterface.rtmAllocateInParent && !SLibIsSelfInSimTarget()
    %return aBlock.Identifier
  %endif
  %assign dworkIdx = SLibGetStructDWorkIdxForModelRefBlk(aBlock)
   
  %if "RegistrationFcn" == aSysFcnType
    %assign varGroupPath = ...
      SLibGetModelBlockVarGroupPath(aBaseSystemIdx, aBlock, aInstanceIdx)
    %assign dwRec = ...
      ::CompiledModel.DWorks.DWork[aBlock.DWork[dworkIdx].FirstRootIdx]
    %return varGroupPath + LibGetRecordIdentifier(dwRec)
  %endif
   
  %return LibBlockDWork(aBlock.DWork[dworkIdx], "","","0")
%endfunction
 
%%FunctionSLibModelBlockContinuousStateAddr====================================
%%Abstract:
%%Returnthebaseaddressofthecontinuesstatesargumentofamodelblock.
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%
%function SLibModelBlockContinuousStateAddr(aBaseSystemIdx, aModelSystemIdx, ...
  aBlock, aSysFcnType, aInstanceIdx) void
  %assign cs = ::CompiledModel.ContStates.ContState[aBlock.ContStates[1]]
   
  %if "RegistrationFcn" == aSysFcnType
    %assign thisSystem = ::CompiledModel.System[aBlock.BlockIdx[0]]
    %assign varGroupIdx = FcnSysVarGroupIndex(thisSystem, "ContStates", ...
      aInstanceIdx)
    %assign cross = thisSystem.CrossNoArgFcnBound
    %assign sysIdx = LibIsDeploymentDiagram() ? aModelSystemIdx : aBaseSystemIdx
    %assign varGroupPath = SLibCGIRVarGroupPath(varGroupIdx, sysIdx, cross)
    %assign intrf = GetModelrefInterface(aBlock)
    %assign optWidth = (intrf.xOptWidth > 1) ? "[0]" : ""
    %return "&(" + varGroupPath + cs.Identifier + optWidth + ")"
  %endif
   
  %return SLibContinuousStateAddr(cs, aModelSystemIdx)
%endfunction %% SLibModelBlockContinuousStateAddr
   
%%Function:SLibGetMdlRefArgumentForTID
%%Abstract:
%%ForthegivenTID,gettheargumenttobepassedintothecallto
%%areferencedmodelfunction
%%TopTester:test/toolbox/simulink/variants/string/tStringSupport.m
%%
%function SLibGetMdlRefArgumentForTID(idx)
  %if IsModelReferenceTarget()
    %% if the idx is constant tid, return it. see g1339414
    %if idx == -2
      %assign arg = "%<idx>"
    %else
      %assign arg = "mdlref_TID%<idx>"
    %endif
  %elseif IsSimstructBasedTarget() && LibAsynchronousTriggeredTID(idx)
    %assign arg = "0"
  %else
    %assign arg ="%<idx>"
  %endif
 
  %return arg
%endfunction
 
%%Function:SLibGetPathToSimplifiedInterfaceModelBlock
%%Abstract:
%%Whenusingsimplifiedinterface,getthepathtomodelblock
%%e.g.RTM->subsysSelf->
%%
%function SLibGetPathToSimplifiedInterfaceModelBlock(mdlBlk, instIdx)
  %assert mdlBlk.Type == "ModelReference" && SLibGetSelfVarGroupIndex() >= 0
  %assign selfVarGroupIdx = SLibGetSelfVarGroupIndexForModelBlock(mdlBlk, instIdx)
  %assign selfPath = SLibCGIRVarGroupPath(selfVarGroupIdx, GetBaseSystemIdx(), TLC_FALSE)
  %return selfPath
%endfunction
 
%%Function:SLibGetPathToModelBlockSelf
%%Abstract:
%%Whenusingpluggableinterface,getthepathtomodelblockrtm
%%
%function SLibGetPathToModelBlockSelf(mdlBlk)
  %assert mdlBlk.Type == "ModelReference" && SLibGetSelfVarGroupIndex() >= 0
  %assign selfVarGroupIdx = SLibGetSelfVarGroupIndexForModelBlock(mdlBlk, 0) %% Ok to use the first instance of model block
  %assign selfCGTypeIdx = ::CompiledModel.VarGroups.VarGroup[selfVarGroupIdx].CGTypeIdx
  %assign rtmRecIdx = mdlBlk.ModelInstVarIndex
  %assign fldName = LibCGTypeMemberName(selfCGTypeIdx, rtmRecIdx)
  %return fldName
%endfunction
 
%%Function:SLibGetModelInstVariableAddressForSimplifiedInterface
%%Abstract:
%%ForModelReferencesimplifiedinterface,givenaModelblock
%%returnthepointertothecorrespondingmodelvariableaccesspath
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibGetModelInstVariableAddressForSimplifiedInterface(mBlock,aInstanceIdx,globalAccess) void
  %assert mBlock.Type == "ModelReference"
  %assign containedInVargroup = ISFIELD(mBlock, "ModelInstVarGroupIndex") && mBlock.ModelInstVarGroupIndex > -1 && ...
    !(GenerateClassInterface && mBlock.ModelInstVarGroupIndex == SLibGetSelfVarGroupIndex())
 
  %% Look for global self instance first
  %if SLibPassGlobalInstanceForBlocksSelf(mBlock) && !containedInVargroup
    %return SLibGetGlobalInstanceNameForBlocksSelf(mBlock)
  %endif
 
  %assign path = ""
 
  %% See if we can find a path via pointer in Self
  %if SLibIsBlockInstanceAccessedViaPointerInSelf(mBlock)
    %% An example of path here is "self->anotherGroup->inst1"
    %assign path = "(&" + SLibGetPathToInstanceFromSelf(mBlock) + ")"
  %endif
 
  %if !ISEMPTY(path)
    %return path
  %elseif ISFIELD(mBlock, "ModelInstVarIndex")
    %assign isClassField = (GenerateClassInterface && mBlock.ModelInstVarGroupIndex == SLibGetSelfVarGroupIndex())
    %assign rtmRecIndex = mBlock.ModelInstVarIndex
    %if isClassField && rtmRecIndex > -1
      %return "&" + mBlock.Identifier
    %elseif rtmRecIndex > -1
      %if mBlock.ModelInstVarGroupIndex == SLibGetSelfVarGroupIndex()
        %<SLibCG_AccessRTM()>
        %assign selfPath = getRTMFieldPointerFromCGType("STANDALONE",rtmRecIndex)
        %return "(" + selfPath + ")"
      %else
        %assign selfVarGroupIdx = SLibGetSelfVarGroupIndexForModelBlock(mBlock, aInstanceIdx)
        %assign selfCGTypeIdx = ::CompiledModel.VarGroups.VarGroup[selfVarGroupIdx].CGTypeIdx
        %if LibCGTypeIsMatrix(selfCGTypeIdx)
          %assign selfCGTypeIdx = LibCGTypeBaseIndex(selfCGTypeIdx)
        %endif
        %assign fldName = LibCGTypeMemberName(selfCGTypeIdx, mBlock.ModelInstVarIndex)
        %assign blkSystem = ::CompiledModel.System[mBlock.BlockIdx[0]]
        %with blkSystem
          %assign graphParentSysIdx = CallSites[0][2]
          %assign graphParentSys = ::CompiledModel.System[graphParentSysIdx]
          %assign parentIsForEach = SLibGetSubsystemIsForEachSS(graphParentSys)
        %endwith
        %if globalAccess
          %% we are accessing model instance via the topmost node of self
          %assign vgPath = SLibCGIRVarGroupPath(selfVarGroupIdx,GetBaseSystemIdx(),TLC_TRUE)
        %elseif parentIsForEach
          %assign forEachModuleIdx = graphParentSys.CGIRModuleIdx
          %assign forEachModule = ::CompiledModel.RTWCGModules.RTWCGModule[forEachModuleIdx]
          %assign isSameSys = (forEachModule.CGSystemIdx == graphParentSysIdx)
          %assign isSimpInterf = isSameSys && forEachModule.SimplifiedInterface
          %if isSimpInterf
            %assign vgPath = SLibCGIRVarGroupPath(selfVarGroupIdx, graphParentSysIdx, graphParentSys.CrossNoArgFcnBound)
          %else
            %assign vgPath = SLibCGIRVarGroupPath(selfVarGroupIdx,GetBaseSystemIdx(),TLC_TRUE)
          %endif
        %else
          %assign vgPath = ::CompiledModel.VarGroups.VarGroup[selfVarGroupIdx].LocalName + "->"
        %endif
        %assign selfPath = "&" + vgPath + fldName
        %return "(" + selfPath + ")"
      %endif
    %endif
  %endif
   
  %return ""
%endfunction
 
%function SLibGetMdlRefInstCPPVar(block, instIdx, mdlRefSysIdx)
  %assert GenerateClassInterface && block.MdlRefIsCPPClassGenMode
  %assign mdlRefInstCPPVar = ...
    SLibGetCPPMdlRefObjName(System[BlockIdx[0]].SystemIdx, BlockIdx[2])
  %assert(ISFIELD(block, "ParamSettings"))
  %assign subsysRegFcnForCPPClassModelRefBlock = block.MdlRefIsCPPClassGenMode && ...
    (!IsSystemReusableParentBaseSys(BlockIdx[0]) || block.ParamSettings.InsideForEachSS) &&...
    (!IsModelRefScalableBuild() || GenerateClassInterface)
 
  %assign regFcn4MdlRefBlkCPPFromSubSys = subsysRegFcnForCPPClassModelRefBlock && ...
    ISFIELD(block,"CPPObjDWorkIdxInSubsys")
 
  %if regFcn4MdlRefBlkCPPFromSubSys
    %assign mdlRefInstCPPVar = ...
      SLibGetModelBlockVarGroupPath(baseSystemIdx, block, instIdx) ...
      + mdlRefInstCPPVar
  %elseif subsysRegFcnForCPPClassModelRefBlock && ...
    ISFIELD(block,"ModelInstVarGroupIndex") && ...
    block.ModelInstVarGroupIndex > -1
    %assign mdlRefInstCPPVar = ...
      SLibCGIRVarGroupPath(block.ModelInstVarGroupIndex,GetBaseSystemIdx(),TLC_FALSE) ...
      + mdlRefInstCPPVar
  %endif
  %return mdlRefInstCPPVar
%endfunction
 
%function SLibGetMdlRefCppEncapRTMInitCall(block, blockInterface, instIdx, mdlRefSysIdx)
  %assert GenerateClassInterface && IsModelReferenceRTWTarget() && ...
          block.MdlRefIsCPPClassGenMode && blockInterface.RTMAccessed
         
  %with block
    %assign mdlRefInstCPPVar = SLibGetMdlRefInstCPPVar(block, instIdx, mdlRefSysIdx)
    %assign dotOrArrow = SLibCPPDotOrArrowAccessOperator(block,blockInterface)
    %assign fcnArgs = SLibGetInitializeRTMFunctionArgs(block, blockInterface, instIdx, mdlRefSysIdx)
  %endwith
     
  %openfile modelRTMInitCallBuff
  %<mdlRefInstCPPVar>%<dotOrArrow>initializeRTM(%<fcnArgs>);
  %closefile modelRTMInitCallBuff
   
  %return modelRTMInitCallBuff
%endfunction
 
%function SLibGetModelBlockRegistrationFunctionForCppClassGen(block,blkPath,blockInterface,instIdx,childIdx,mdlRefSysIdx)
  %assert GenerateClassInterface && block.MdlRefIsCPPClassGenMode
  %assign mdlRefInstCPPVar = SLibGetMdlRefInstCPPVar(block, instIdx, mdlRefSysIdx)
  %assign subsysRegFcnForCPPClassModelRefBlock = block.MdlRefIsCPPClassGenMode && ...
    !IsSystemReusableParentBaseSys(BlockIdx[0]) &&...
    (!IsModelRefScalableBuild() || GenerateClassInterface)
 
  %assign regFcn4MdlRefBlkCPPFromSubSys = subsysRegFcnForCPPClassModelRefBlock && ...
    ISFIELD(block,"CPPObjDWorkIdxInSubsys")
 
  %assign dotOrArrow = SLibCPPDotOrArrowAccessOperator(block,blockInterface)
  %openfile tmp_file
  %%%% re-establish pointers for mdlref blocks in subsystems, if needed
  %if regFcn4MdlRefBlkCPPFromSubSys && ...
    CPPEncapNeedsLocalVars(TLC_FALSE) && ...
    !blockInterface.IsScalableBuild
    %assign restoreCode = SLibGetCPPEncapInitCopyCode(TLC_FALSE, TLC_FALSE)
    %<restoreCode>
  %endif
 
  %%%% this must be called early on
  %if blockInterface.RTMAccessed && ...
      (ISFIELD(blockInterface, "NeedsCPPInitRTM") && blockInterface.NeedsCPPInitRTM)
    %assign fcnArgs = SLibGetInitializeRTMFunctionArgs(block, blockInterface, instIdx, mdlRefSysIdx)
    %if !IsModelReferenceTarget()
      %openfile modelRTMInitCallBuff
      %assign fcnArgs = SLibGetInitializeRTMFunctionArgs(block, blockInterface, instIdx, mdlRefSysIdx)
      %<mdlRefInstCPPVar>%<dotOrArrow>initializeRTM(%<fcnArgs>);
      %closefile modelRTMInitCallBuff
      %<modelRTMInitCallBuff>
    %endif
  %endif
  %if blockInterface.NeedsErrorStatus
    /* Set error status pointer for %<Type> Block: '%<Name>' */
    %<mdlRefInstCPPVar>%<dotOrArrow>setErrorStatusPointer(%<RTMsGet(System[GetBaseSystemIdx()],"ErrorStatusPointer")>);
  %endif
  %% Setup the stop requested flag
  %if blockInterface.StopReqAccessed
    /* initialize stop requested flag */
    %<mdlRefInstCPPVar>%<dotOrArrow>setStopRequestPointer(%<RTMsGet(System[GetBaseSystemIdx()],"StopRequestedPtr")>);
  %endif
   
  %if ISFIELD(blockInterface, "RegistrationFcn") && GenerateClassInterface
    %% Invoke C++ initialize before setting fields to non-zero values
    %<mdlRefInstCPPVar>%<dotOrArrow>initialize();
  %endif
 
  %assert block.ContStates[0] <= 0
 
  %if ISFIELD(blockInterface, "RegFcnNeedsCAPIArgs") && ...
    blockInterface.RegFcnNeedsCAPIArgs
 
    %if RTWCAPI == 1 && !block.ParamSettings.InsideForEachSS
      %assign arg1 = "&(%<RTMGet("DataMapInfo")>.mmi)"
      %assign fcnArgs = "%<arg1>," + "/"%<blkPath>/"," + ...
        "%<childIdx>," + "-1"
    %else
      %assign capiArgs = []
      %assign capiArgs = capiArgs + SLibGetNullDefinitionFromTfl()
      %assign capiArgs = capiArgs + SLibGetNullDefinitionFromTfl()
      %assign capiArgs = capiArgs + "0"
      %assign capiArgs = capiArgs + "-1"
 
      %foreach idx = SIZE(capiArgs,1)
        %if idx == 0
          %assign fcnArgs = capiArgs[idx]
        %else
          %assign fcnArgs = fcnArgs + ", %"
        %endif
      %endforeach
    %endif %% RTWCAPI == 1
 
    %<mdlRefInstCPPVar>%<dotOrArrow>setupCAPIInfo(%<fcnArgs>);
  %endif %%RegFcnNeedsCAPIArgs
  %if ISFIELD(blockInterface, "RegistrationFcn") && !GenerateClassInterface
    %<mdlRefInstCPPVar>%<dotOrArrow>initialize();
  %endif
  %closefile tmp_file
 
  %return tmp_file
%endfunction
 
%%Function:SLibAddMdlRefTIDArgs========================================
%%Abstract:
%%ThiscodeappendsthereleventTIDs(thatshouldbeavailabeatacallsite)tothea
%%modelref'sinitializearglist.
%%Iftheblockiscompletelyconstant,thenjustpass0astheTID.Ifitisinherited,
%%passtheTIDthatthisinstanceisrunningat.Thiswillhelpwithdatalogging.
%%
%%Thismaybeusedforcallingamodelrefinitializefunction,orinthecaseofC++Class
%%packagingintheinitializeRTMfunction.
%%
%function SLibAddMdlRefTIDArgs(blockInterface, block, args)
  %if blockInterface.NeedsTIDArgs
      %assign ::tMdlRefNeedTIDArgs = TLC_TRUE
      %assign blockTid = block.TID
      %if TYPE(blockTid) == "Vector"
        %assign nonModelWideEventTids = []
        %assign numTids = SIZE(blockTid)[1]
        %foreach idx = numTids
          %if !SLibParameterChangeEventTID(blockTid[idx])
            %assign nonModelWideEventTids = nonModelWideEventTids + blockTid[idx]
          %endif
        %endforeach
        %if SIZE(nonModelWideEventTids)[1] == 1
          %assign blockTid = nonModelWideEventTids[0]
        %endif
      %endif
      %if TYPE(blockTid) != "Identifier" || blockInterface.IsExportFcnDiagram
        %assign numTids = SIZE(blockTid)[1]
        %if ISFIELD(block.ParamSettings, "ChildTidToParentTidMap")
          %% Loop through TID map to find parent TID for each child TID.
          %assign childTidToParentMap = block.ParamSettings.ChildTidToParentTidMap
          %assign numTids = SIZE(childTidToParentMap,1)/2
          %foreach tidIdx = numTids
            %assign parentTid = SLibGetMdlRefArgumentForTID(childTidToParentMap[numTids + tidIdx])
            %assign args = args + parentTid
          %endforeach
        %elseif (numTids == 1) && LibAsynchronousTriggeredTID(blockTid) && ...
          !ModelBlockHasAsyncInput(blockTid, block)
          %% if it is in async fcn-call subsystem, all blocks will access the base rate
          %assign args = args + "0"
          %% Add parameter rate if used by model block
          %if blockInterface.HasInternalParameterRate || ...
            blockInterface.HasParameterRateOutput
            %assign args = args + STRING(SLibTidOfParameterChangeEvent())
          %endif
          %% Add irt event rate if used by model block
          %assign args = SLibAttachIRTEventArgs(block, args)
         
        %else
          %% constant is handled in the loop
          %foreach idx = SLibGetNumTIDsForGlobalTIDMap()
            %assign parentTID = idx
            %assign childTID = MapParentTID2ChildTID(block, parentTID)
            %if childTID != -1
              %assign args = args + SLibGetMdlRefArgumentForTID(idx)
            %endif
          %endforeach
        %endif
      %else
        %% There is only one TID in the model and it
        %% is constant/triggered, pass 0 if it is constant.
        %if ISEQUAL(blockTid, "triggered")
          %if IsModelReferenceSimTarget()
            %% Because of model-wide events, it is possible for the TriggerTID to be an array,
            %% but the first TID is always the container TS.
            %assign args = args + "mdlref_TID%"
          %else
            %assign args = args + "-1"
          %endif
          %if blockInterface.HasInternalParameterRate || blockInterface.HasParameterRateOutput
            %assign args = args + STRING(SLibTidOfParameterChangeEvent())
          %endif
          %% Add irt event rate if used by model block
          %assign args = SLibAttachIRTEventArgs(block, args)
        %else
          %assign args = args + "0"
        %endif
      %endif
 
      %if GetModelRefFcnCallTriggerTIDIsReq(block)
        %if SLibModelNeedsTriggerTIDArg()
          %assign args = args + "mdlref_TriggerTID"
        %else
          %assert ISEQUAL(blockTid, "triggered") || ...
            LibAsynchronousTriggeredTID(blockTid[0])
          %if !ISEQUAL(blockTid, "triggered") && LibAsynchronousTriggeredTID(blockTid[0])
            %assign args = args + "%"
          %else
            %assign trigTid = block.TriggerTID[0]
            %if IsModelReferenceTarget()
              %assign args = args + "mdlref_TID%<trigTid>"
            %else
              %assign args = args + "%<trigTid>"
            %endif
          %endif
        %endif
      %endif
  %endif
%return args
%endfunction
 
%%Function:SLibGetSolverInfoVariableName========================================
%%Abstract:
%%ReturnsthevariablenameofthesolverInfoobject.Ittheresponsibilityof
%%theparenttomakesurethatasolverInfoobjectisgoingtobe
%%presentintheRTMstructure.
%%Thismaybeusedforcallingamodelrefinitializefunction,orinthecaseofC++Class
%%packagingintheinitializeRTMfunction.
%%
%function SLibGetSolverInfoVariableName(blkidx)
  %if LibIsDeploymentDiagram()
    %% find task idx to whom is mapped TID0 of system mSysIdx
    %assign rtmIdx = SLibDeploymentGetTaskIndexForBlock(blkidx, 0)
  %endif
  %if IsModelReferenceTarget()
    %assign arg = "rt_solverInfo"
  %elseif SLibIsERTCodeFormat()
    %if LibIsDeploymentDiagram()
      %if !ISEQUAL(rtmIdx, -1)
        %assign rtmName = SLibDeploymentGetTasksRTMVarName(rtmIdx)
        %assign arg = "&(%<SLibDeploymentRTMGet("RTWSolverInfo", rtmName)>)"
      %else
        %assign arg = "&(%<RTMGet("RTWSolverInfo")>)"
      %endif
    %else
      %if UsingMalloc
        %assign arg = "%<RTMGet("RTWSolverInfo")>"
      %else
        %assign arg = "&(%<RTMGet("RTWSolverInfo")>)"
      %endif
    %endif
  %elseif LibIsDeploymentDiagram()
    %if !ISEQUAL(rtmIdx, -1)
      %assign rtmName = SLibDeploymentGetTasksRTMVarName(rtmIdx)
      %assign arg = "%<SLibDeploymentRTMGet("RTWSolverInfo", rtmName)>"
    %else
      %assign arg = "%<RTMGet("RTWSolverInfo")>"
    %endif
  %else
    %assign arg = "%<RTMGet("RTWSolverInfo")>"
  %endif
  %return arg
%endfunction
 
%function SLibGetInitializeRTMFunctionArgs(block, blockInterface, instIdx, mdlRefSysIdx)
    %assert GenerateClassInterface && block.MdlRefIsCPPClassGenMode
    /* initialize real-time model for %<Type> Block: '%<Name>' */
    %assign args = []
 
    %%arg for initializing global timing engine
    %if !IsModelReferenceForASimstructBasedTarget()
      %if blockInterface.NeedsGlobalTimingEngine
        %if IsModelReferenceTarget()
          %assign args = args + "%<SLibGetGlobalTimingBridge()>"
        %elseif LibIsDeploymentDiagram()
          %assign timingBridgeIdx = 0
          %% Figure out the ModelReferenceBlock index for current block
          %% Update timingBridgeIdx if blkInterface.NeedsGlobalTimingEngine is true for previous mdlRefBlks
          %foreach rowIdx = SIZE(::CompiledModel.ModelReferenceBlocks, 0)
            %assign mdlRefBlk = ::CompiledModel.ModelReferenceBlocks[rowIdx]
            %if ((BlockIdx[0] == mdlRefBlk[0]) && (BlockIdx[2] == mdlRefBlk[1]) && ...
              ((instIdx == mdlRefBlk[2]) || ...
              (LibIsDeploymentDiagram() && !SLibDeploymentDiagramIsMapped(mdlRefBlk[0]))))
              %break
            %elseif SLibIsMappedSystemInDeploymentDiagram(mdlRefBlk[0])
              %assign prvBlk = System[mdlRefBlk[0]].Block[mdlRefBlk[1]]
              %assign prvBlkInterface = GetModelrefInterface(prvBlk)
              %if prvBlkInterface.NeedsGlobalTimingEngine
                %assign timingBridgeIdx = timingBridgeIdx + 1
              %endif
            %endif
          %endforeach
          %assign args = args + "&%<SLibDeploymentGetTimingBridgeName()>[%<timingBridgeIdx>]"
        %else
          %assign args = args + "&%<SLibGetGlobalTimingBridge()>"
        %endif
      %endif
    %endif
 
    %if TYPE(TID) == "Vector"
      %assign tid0 = TID[0]
    %else
      %assign tid0 = TID
    %endif
    %if (TYPE(tid0) == "Number" && LibIsContinuous(tid0)) || blockInterface.HasNonInlinedSfcn
      %assign arg = "%<SLibGetSolverInfoVariableName(BlockIdx[2])>"
      %assign args = args + "%<arg>"
    %endif
    %if blockInterface.HasNonInlinedSfcn
      %if IsModelReferenceTarget()
        %assign arg = "rt_sfcnInfo"
      %elseif SLibIsMappedSystemInDeploymentDiagram(mdlRefSysIdx)
        %assign sfcnInfoIdx = 0
        %foreach rowIdx = SIZE(::CompiledModel.ModelReferenceBlocks, 0)
          %assign mdlRefBlk = ::CompiledModel.ModelReferenceBlocks[rowIdx]
          %if ((BlockIdx[0] == mdlRefBlk[0]) && (BlockIdx[2] == mdlRefBlk[1]) && ...
               ((instIdx == mdlRefBlk[2]) ...
               || (LibIsDeploymentDiagram() && ...
               !SLibDeploymentDiagramIsMapped(mdlRefBlk[0]))))
            %break
          %elseif SLibIsMappedSystemInDeploymentDiagram(mdlRefBlk[0]) && blkInterface.HasNonInlinedSfcn
            %assign sfcnInfoIdx = sfcnInfoIdx + 1
          %endif
        %endforeach
        %assign arg = "(RTWSfcnInfo *)(%<SLibDeploymentGetTasksSfcnInfoVarName()>[%<sFcnInfoIdx>])"
      %else
        %assign arg = "(RTWSfcnInfo *)(%<RTMGet("RTWSfcnInfo")>)"
      %endif
      %assign args = args + "%<arg>"
    %endif
    %assign args = SLibAddMdlRefTIDArgs(blockInterface, block, args)
    %assign fcnArgs = SLibSerializeFcnArgs(args)
    %return fcnArgs
%endfunction
 
%function SLibModelBlockRTMAllocateInParent(block, blockInterface)
  %return (SLibGetStructDWorkIdxForModelRefBlk(block) < 0 || blockInterface.rtmAllocateInParent) && !SLibIsSelfInSimTarget()
%endfunction
   
%%Function:SLibCallModelBlockFunction========================================
%%Abstract:
%%Contructastringwhichisacalltosomefunctioninareferencedmodel.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants4.m
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/variants/normalMATLABVariableSupport/tNormalMatlabVariable2.m
%%TopTester:test/toolbox/simulink/variants/string/tStringSupport.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/localsGuarding/tmLG_forIterator.m
%%TopTester:test/toolbox/simulink/variants/tMdlrefToVSS.m
%%
%function SLibCallModelBlockFunction(outAndRuleIdx, block, sysFcnName, ...
  blockInterface, fcnInfo, instIdx, tid, childIdx, blkPath)
  %% Initially assume there is no outport returned by value (set retArgPortIdx to -1)
  %assign retArgPortIdx = -1
  %assign fcnName = fcnInfo.FcnName
  %if block.MdlRefIsCPPClassGenMode
    %assign fcnName = FEVAL("regexprep", fcnName,"^[a-zA-Z0-9_]*::", "")
  %endif
  %assign args = []
  %assign canInputInfo = fcnInfo.Inputs
  %assign canOutputInfo = fcnInfo.Outputs
  %assign canPrmArgInfo = fcnInfo.PrmArgs
  %assign baseSystemIdx = GetBaseSystemIdx()
  %assign blkSimpInterface = blockInterface.usesSimplifiedInterface
  %if TYPE(fcnInfo.PrmTypes) == "Vector"
    %assign prmTypes = fcnInfo.PrmTypes
  %else
    %assign prmTypes = []
    %assign prmTypes = prmTypes + fcnInfo.PrmTypes
  %endif
     
  %if TYPE(fcnInfo.PrmIsPointer) == "Vector"
    %assign prmIsPointer = fcnInfo.PrmIsPointer
  %else
    %assign prmIsPointer = []
    %assign prmIsPointer = prmIsPointer + fcnInfo.PrmIsPointer
  %endif
       
  %% If we aren't generating the registration function, then
  %% instanceIdx must be 0 since we don't use it.
  %assert (sysFcnName == "RegistrationFcn") || (instIdx == 0)
 
  %assign TIDIdx = 0
  %assign RTModelIdx = 1
  %assign BlockIOIdx = 2
  %assign DWorkIdx = 3
  %assign ContStatesIdx = 4
  %assign ContStatesDerivativeIdx = 5
  %assign ContStatesDisabledIdx = 6
  %assign ContStatesAbsoluteToleranceIdx = 7
  %assign ContStatesPerturbMinIdx = 8
  %assign ContStatesPerturbMaxIdx = 9
   
  %assign NonsampledZCIdx = 10
  %assign ZCEventIdx = 11
   
  %% Variables for the sfcnInfo and timing bridge index of the components
  %% in a deployment diagram
  %assign sfcnInfoIdx = 0
  %assign timingBridgeIdx = 0
   
  %% figure out which model block we're looking at
  %assign mdlRefIdx = -1
  %assign mSysIdx = 0
  %foreach rowIdx = SIZE(::CompiledModel.ModelReferenceBlocks, 0)
    %assign mdlRefBlk = ::CompiledModel.ModelReferenceBlocks[rowIdx]
    %if ((BlockIdx[0] == mdlRefBlk[0]) && (BlockIdx[2] == mdlRefBlk[1]) && ...
         ((instIdx == mdlRefBlk[2]) ...
         || (LibIsDeploymentDiagram() && ...
         !SLibDeploymentDiagramIsMapped(mdlRefBlk[0]))))
      %assign mdlRefIdx = rowIdx
      %assign mdlRefInfo = ::CompiledModel.ModelReferenceBlocks[mdlRefIdx]
      %assign mSysIdx = mdlRefInfo[0]
      %break
    %elseif SLibIsMappedSystemInDeploymentDiagram(mdlRefBlk[0])
      %assign blk = System[mdlRefBlk[0]].Block[mdlRefBlk[1]]
      %assign blkInterface = GetModelrefInterface(blk)
      %if blkInterface.NeedsGlobalTimingEngine
        %assign timingBridgeIdx = timingBridgeIdx + 1
      %endif
      %if blkInterface.HasNonInlinedSfcn
        %assign sfcnInfoIdx = sfcnInfoIdx + 1
      %endif
    %endif
  %endforeach
 
  %if LibIsDeploymentDiagram()
      %assign timingBridgeName = "%<SLibDeploymentGetTimingBridgeName()>[%<timingBridgeIdx>]"
  %endif
   
  %if (sysFcnName == "RegistrationFcn" && !IsSimstructBasedTarget())
    %if blockInterface.NeedsFirstTime
      %assign arg = "1"
      %assign args = args + "%<arg>"
    %endif
     
    %if blockInterface.NeedsErrorStatus
      %assign arg = "%<RTMGet("ErrorStatusPointer")>"
      %assign args = args + "%<arg>"
    %endif
     
    %if blockInterface.StopReqAccessed
      %if IsModelReferenceTarget()
        %assign arg = "rt_stopRequested"
      %else
        %assign arg = "%<RTMGet("StopRequestedPtr")>"
      %endif
      %assign args = args + "%<arg>"
    %endif
     
    %if TYPE(TID) == "Vector"
      %assign tid0 = TID[0]
    %else
      %assign tid0 = TID
    %endif
    %% For continuous time referenced models, pass the
    %% solverInfo to the submodel. In the case of
    %% non-ERT top models, the solverInfo is a pointer
    %% in the rtModel, but for ERT it's not a pointer.
    %if (TYPE(tid0) == "Number" && LibIsContinuous(tid0)) || blockInterface.HasNonInlinedSfcn
      %assign arg = "%<SLibGetSolverInfoVariableName(BlockIdx[2])>"
      %assign args = args + "%<arg>"
    %endif
     
    %if blockInterface.HasNonInlinedSfcn
      %if IsModelReferenceTarget()
        %assign arg = "rt_sfcnInfo"
      %elseif SLibIsMappedSystemInDeploymentDiagram(mSysIdx)
        %assign arg = "(RTWSfcnInfo *)(%<SLibDeploymentGetTasksSfcnInfoVarName()>[%<sfcnInfoIdx>])"
      %else
        %assign arg = "(RTWSfcnInfo *)(%<RTMGet("RTWSfcnInfo")>)"
      %endif
      %assign args = args + "%<arg>"
    %endif
  %endif
  %%
  %%
  %% TID
  %if fcnInfo.ArgInfo[TIDIdx] == 1
    %assert sysFcnName != "RegistrationFcn"
    %if ISEQUAL(tid,"")
      %assign arg = LibTID()
    %else
      %assign arg = %<tid>
    %endif
    %assign args = args + "%<arg>"
  %endif
 
  %if sysFcnName == "SetDimsFcn"
    %assign args = args + outAndRuleIdx[0]
    %assign args = args + outAndRuleIdx[1]
  %endif
 
  %assign FPC = []
   
  %% We do not honor the Function Prototype Control for a
  %% referenced model when generating code for:
  %% * Model Reference SIM Target
  %% * Top-level rapid-accelerator
  %if (sysFcnName == "OutputUpdateFcn") && ...
    !IsModelReferenceSimTarget() && ...
    !isRAccel
    %assign FPC = blockInterface.FPC
  %endif
  %if !ISEMPTY(FPC)
    %assign fcnName = FPC.FunctionName
  %endif
 
  %if GenerateClassInterface && block.MdlRefIsCPPClassGenMode
    %if sysFcnName == "RegistrationFcn"
      %assign fcnName = "initialize"
    %elseif sysFcnName == "InitializeFcn"
      %assign fcnName = "init"
    %elseif sysFcnName == "SystemInitializeFcn"
      %assign fcnName = "init"
    %elseif sysFcnName == "SystemResetFcn"
      %assign fcnName = "reset"
    %elseif sysFcnName == "StartFcn"
      %assign fcnName = "start"
    %elseif sysFcnName == "TerminateFcn"
      %assign fcnName = "terminate"
    %elseif sysFcnName == "DisableFcn"
      %assign fcnName = "disable"
    %elseif sysFcnName == "EnableFcn"
      %assign fcnName = "enable"
    %endif
     
    %assign mdlRefInstCPPVar = ...
      SLibGetCPPMdlRefObjName(System[BlockIdx[0]].SystemIdx,BlockIdx[2])
     
  %endif %% GenerateClassInterface && block.MdlRefIsCPPClassGenMode
   
  %assign NumInputs = CAST("Number", blockInterface.NumInputs)
  %assign NumOutputs = CAST("Number", blockInterface.NumOutputs)
     
  %if IsFPCIgnored(FPC)
    %assign NumArgs = NumInputs + NumOutputs
  %else
    %assign NumArgs = SIZE(FPC.ArgSpecData,1)
  %endif
   
  %assign mdlBlkDWork = ""
   
  %%
  %% The following TLC code is used to prune the CGIR function call
  %% arguments and transfer the CGIR argument tracking
  %% information to the legacy TLC trackig infrastructure.
  %%
  %assign numCanDWorks = SIZE(fcnInfo.DWArgs, 1)
  %assign numPrmArgs = SIZE(canPrmArgInfo,1)
  %assign skipCanInput = Vector(%<NumInputs>) [0@%<NumInputs>]
  %assign skipInputDims = Vector(%<NumInputs>) [0@%<NumInputs>]
  %assign skipCanOutput = Vector(%<NumOutputs>) [0@%<NumOutputs>]
  %assign skipOutputDims = Vector(%<NumOutputs>) [0@%<NumOutputs>]
  %assign skipCanDWork = Vector(%<numCanDWorks>) [0@%<numCanDWorks>]
  %assign skipCanParam = Vector(%<numPrmArgs>) [0@%<numPrmArgs>]
  %assign rtmContainedInSelf = (ISFIELD(block, "ModelInstVarIndex") && block.ModelInstVarIndex > -1) || ...
    (blockInterface.rtmAllocateInParent && ::isRAccel)
  %assign skipRTM = 0
  %assign skipLocalB = blockInterface.usesSimplifiedInterface || (blockInterface.rtmAllocateInParent)
  %assign skipLocalDW = blockInterface.usesSimplifiedInterface || (blockInterface.rtmAllocateInParent)
  %assign skipLocalX = 0
  %assign skipLocalXdot = 0
  %assign skipLocalXdis = 0
  %assign skipLocalXabstol = 0
  %assign skipLocalXperturbmin = 0
  %assign skipLocalXperturbmax = 0
  %assign skipLocalZCSV = 0
  %assign skipLocalZCE = 0
 
  %if IsFPCIgnored(FPC)
    %assign numFcnInfoArgs = CAST("Number", fcnInfo.NumArgs)
    %foreach argIdx = numFcnInfoArgs
      %assign idNum = SLibSafeIDNUM(fcnInfo.ArgSource, argIdx)
      %assign argSrc = idNum[0]
      %assign argSrcIdx = idNum[1]
      %switch argSrc
        %case "I" %% canonical input
          %assign arg = SLibGetModelBlockInput(mSysIdx, block, sysFcnName, ...
            mdlRefIdx, argSrcIdx, canInputInfo, FPC, argIdx)
          %assert !ISEMPTY(arg)
          %assign args = args + "%<arg>"
          %assign skipCanInput[argSrcIdx] = 1
          %break
        %case "O" %% canonical output
          %assign arg = SLibGetModelBlockOutput(sysFcnName, mdlRefIdx, ...
            argSrcIdx, FPC, argIdx)
          %assert !ISEMPTY(arg)
          %assign args = args + "%<arg>"
          %assign skipCanOutput[argSrcIdx] = 1
          %break
        %case "D" %% canonical dwork
          %assign dimsIdNum = SLibSafeIDNUM(fcnInfo.Association, argIdx)
          %assign dimsSrc = dimsIdNum[0]
          %assign dimsSrcIdx = dimsIdNum[1]
          %assert "I" == dimsSrc || "O" == dimsSrc
          %if "I" == dimsSrc
            %assign arg = SLibGetInputCanDimSizeDWForFunctionStr(block, ...
              dimsSrcIdx, fcnInfo, sysFcnName)
            %assert !ISEMPTY(arg)
            %assign args = args + "%<arg>"
            %assign skipInputDims[dimsSrcIdx] = 1
          %else
            %assign arg = SLibGetOutputCanDimSizeDWForFunctionStr(block, ...
              dimsSrcIdx, fcnInfo, sysFcnName)
            %assert !ISEMPTY(arg)
            %assign args = args + "%<arg>"
            %assign skipOutputDims[dimsSrcIdx] = 1
          %endif
          %assign skipCanDWork[argSrcIdx] = 1
          %break
        %case "P" %% canonical parameter
          %if blkSimpInterface
            %break
          %endif
          %assign argInfo = canPrmArgInfo[argSrcIdx]
          %assign prmType = prmTypes[argSrcIdx]
          %assign isPointer = (1 == prmIsPointer[argSrcIdx])
          %assert argInfo >= 1
          %assign numBlockParamArgs = block.ParamSettings.NumBlockParamArgs
          %assign arg = SLibGetModelBlockParameter(block, argSrcIdx+numBlockParamArgs, argInfo, ...
            prmType, isPointer)
          %assert !ISEMPTY(arg)
          %assign args = args + "%<arg>"
          %assign skipCanParam[argSrcIdx] = 1
          %break
        %case "RTM"
          %if blkSimpInterface || (blockInterface.rtmAllocateInParent && rtmContainedInSelf)
            %assign rtmAccess = SLibGetModelInstVariableAddressForSimplifiedInterface(block,instIdx,TLC_FALSE)
          %elseif SLibModelBlockRTMAllocateInParent(block, blockInterface)
            %assign rtmAccess = "&" + block.Identifier
          %else
            %assign mdlBlkDWork = SLibGetModelBlockStructDWorkArg(mdlBlkDWork, ...
              baseSystemIdx, block, sysFcnName, instIdx)
            %assign rtmField = rtmContainedInSelf ? "" : ".rtm"
            %assign rtmAccess = "&(%<mdlBlkDWork>%<rtmField>)"
          %endif
          %assign args = args + rtmAccess
          %assign skipRTM = 1
          %break
        %case "LB" %% block IO
          %if blkSimpInterface
            %assign skipLocalB = 1
            %break
          %endif
          %assign mdlBlkDWork = SLibGetModelBlockStructDWorkArg(mdlBlkDWork, ...
            baseSystemIdx, block, sysFcnName, instIdx)
          %assign rtmField = rtmContainedInSelf ? ".blockIO" : ".rtb"
          %assign args = args + "&(%<mdlBlkDWork>%<rtmField>)"
          %assign skipLocalB = 1
          %break
        %case "LW" %% dwork
          %if blkSimpInterface
            %assign skipLocalDW = 1
            %break
          %endif
          %assign mdlBlkDWork = SLibGetModelBlockStructDWorkArg(mdlBlkDWork, ...
            baseSystemIdx, block, sysFcnName, instIdx)
          %assign rtmField = rtmContainedInSelf ? ".dwork" : ".rtdw"
          %assign args = args + "&(%<mdlBlkDWork>%<rtmField>)"
          %assign skipLocalDW = 1
          %break
        %case "LX" %% continues states
          %assign arg = SLibModelBlockContinuousStateAddr(baseSystemIdx, ...
            mSysIdx, block, sysFcnName, instIdx)
          %assign args = args + "%<arg>"
          %assign skipLocalX = 1
          %break
        %case "LDX" %% derivatives
          %assert (sysFcnName != "RegistrationFcn")
          %assign arg = SLibContinuousStateDerivativeAddr(mSysIdx)
          %assign args = args + "%<arg>"
          %assign skipLocalXdot = 1
          %break
        %case "LXDI" %% continues state disabled
          %assert (sysFcnName != "RegistrationFcn")
          %assign arg = SLibContStateDisabledAddr(mSysIdx)
          %assign args = args + "%<arg>"
          %assign skipLocalXdis = 1
          %break
        %case "LXAT" %% continues state absolute tolerance
          %assert (sysFcnName != "RegistrationFcn")
          %assign arg = SLibContStateAbsoluteToleranceAddr(mSysIdx)
          %assign args = args + "%<arg>"
          %assign skipLocalXabstol = 1
          %break
         
        %case "LXPTMIN" %% continues state perturb min
          %assert (sysFcnName != "RegistrationFcn")
          %assign arg = SLibContStatePerturbMinAddr(mSysIdx)
          %assign args = args + "%<arg>"
          %assign skipLocalXperturbmin = 1
          %break
         
        %case "LXPTMAX" %% continues state perturb max
          %assert (sysFcnName != "RegistrationFcn")
          %assign arg = SLibContStatePerturbMaxAddr(mSysIdx)
          %assign args = args + "%<arg>"
          %assign skipLocalXperturbmax = 1
          %break
         
        %case "LZ" %% non-sampled zero crossings
          %assert (sysFcnName != "RegistrationFcn")
          %assign arg = SLibNonsampledZCAddr()
          %assign args = args + "%<arg>"
          %assign skipLocalZCSV = 1
          %break
        %case "LZE" %% zero crossing events
          %assign mdlBlkDWork = SLibGetModelBlockStructDWorkArg(mdlBlkDWork, ...
            baseSystemIdx, block, sysFcnName, instIdx)
          %assign args = args + "&(%<mdlBlkDWork>.rtzce)"
          %assign skipLocalZCE = 1
          %break
        %case "LCDG"
        %case "X" %% unknown agument type
          %break
        %case "LC" %% constat block IO
        %case "LP" %% parameter
        %case "LCP" %% constant parameter
        %case "LPI" %% const parameter with init
        %default
          %%START_ASSERT
          %assign errTxt = "Unhandled argument type '%<argSrc>'."
          %<LibBlockReportError([],errTxt)>
          %break
          %%END_ASSERT
      %endswitch
    %endforeach
  %endif
 
  %foreach argIdx = NumArgs
    %if IsFPCIgnored(FPC)
      %if argIdx < NumInputs
        %assign portIdx = argIdx
        %assign SLObjectType = "Inport"
      %else
        %assign portIdx = argIdx - NumInputs
        %assign SLObjectType = "Outport"
      %endif
    %else
      %assign portIdx = CAST("Number", FPC.ArgSpecData[argIdx].PortNum)
      %assign SLObjectType = FPC.ArgSpecData[argIdx].SLObjectType
    %endif
     
    %if SLObjectType == "Inport"
      %% Consider adding the argument if it is not reusable.
      %if GetTheOtherReusableArgInFPC(FPC, argIdx) < 0
        %if !IsFPCIgnored(FPC) || ...
          (!skipCanInput[portIdx] && canInputInfo[portIdx] > 0)
          %assign arg = SLibGetModelBlockInput(mSysIdx, block, sysFcnName, mdlRefIdx, ...
            portIdx, canInputInfo, FPC, argIdx)
          %assert !ISEMPTY(arg)
          %assign args = args + "%<arg>"
        %endif
      %endif
      %if !skipInputDims[portIdx]
        %assign arg = SLibGetInputCanDimSizeDWForFunctionStr(block, portIdx, ...
          fcnInfo, sysFcnName)
        %if !ISEMPTY(arg)
          %assign args = args + "%<arg>"
        %endif
      %endif
    %else
      %if !IsFPCIgnored(FPC) || ...
        (!skipCanOutput[portIdx] && canOutputInfo[portIdx] == 1)
        %assign arg = SLibGetModelBlockOutput(sysFcnName, mdlRefIdx, ...
          portIdx, FPC, argIdx)
        %if ISEMPTY(arg)
          %%
          %% If an output is not passed by pointer or ref, it is a return
          %% argument, passed by value;
          %% save the portIdx; assert that it is unassigned to this point
          %%
          %assert retArgPortIdx == -1
          %assign retArgPortIdx = portIdx
        %else
          %assign args = args + "%<arg>"
        %endif
      %endif
      %if !skipOutputDims[portIdx]
        %assign arg = SLibGetOutputCanDimSizeDWForFunctionStr(block, ...
          portIdx, fcnInfo, sysFcnName)
        %if !ISEMPTY(arg)
          %assign args = args + "%<arg>"
        %endif
      %endif
    %endif
  %endforeach
  %%
  %% SimStruct and noncontinuous output array
  %if sysFcnName == "RegistrationFcn" && IsSimstructBasedTarget()
    %assign args = args + "%<tMdlRefSfcnS>"
    %if RTMIsVarStepSolver() && blockInterface.HasNonContOutput
      %assign name = block.ParamSettings.ReferencedModelName
      %assign mangleName = FcnGetNoncontMangledName(name, BlockIdx[0], ...
        BlockIdx[2], instIdx)
      %assign args = args + "mr_%<mangleName>nonContOutputArray"
    %endif
  %endif
 
  %% calling the model intialize with right arguments from
  %% parent model initialize
  %if mdlRefIdx >= 0 && ISFIELD(::CompiledModel.ModelBlock[mdlRefIdx], "DataTransferIndexCount") && ::CompiledModel.ModelBlock[mdlRefIdx].DataTransferIndexCount > 0
    %assign startIdx = ...
      ::CompiledModel.ModelBlock[mdlRefIdx].DataTransferIndexStart
    %assign args = args + "&gblDataTransferIds[%<startIdx>]"
  %endif
     
  %% Pass the timing info to the registration function
  %% Note that we do not need to pass the timing bridge
  %% for any simstruct based targets. In this case the rtm
  %% macros will automatically go through the parent
  %% simstruct to get the timing bridge. Note that this is
  %% called for both model reference targets, and models
  %% that contain model blocks.
  %if sysFcnName == "RegistrationFcn" && ...
    !SLibIsCPPEncapMdlRefBuild()
    %if !IsModelReferenceForASimstructBasedTarget() && ...
      SLibIsERTCodeFormat()
      %if blockInterface.NeedsGlobalTimingEngine
        %if IsModelReferenceTarget()
          %assign args = args + "timingBridge"
        %elseif LibIsDeploymentDiagram()
          %assign args = args + "&%<timingBridgeName>"
        %else
          %assign args = args + "&%<SLibGetGlobalTimingBridge()>"
        %endif
      %endif
      %if blockInterface.NeedCtrlRateMdlRefTiming
        %if IsModelReferenceTarget()
          %assign args = args + "CtrlRateMdlRefTimingPtr"
        %else
          %assign ctrlRateTiming = RTMGet("CtrlRateMdlRefTiming")
          %assign args = args + "&(%<ctrlRateTiming>)"
        %endif
      %endif
    %endif
    %assign args = SLibAddMdlRefTIDArgs(blockInterface, block, args)
  %elseif sysFcnName == "RegistrationFcn" && SLibIsCPPEncapMdlRefBuild() && ...
                        !block.MdlRefIsCPPClassGenMode
    %% This case is the parent model is CPP Encap.
    %% class, while the referenced
    %% model is CPP (Non-encap), and it is ModelReferenceRTWTarget.
    %% We need to directly pass the
    %% local global timing
    %% engine variable, which is already a pointer, to the
    %% submodel_initialize function. The case of both parent/child
    %% models being C++ encap. will be handled later by
    %% setupGlobalTimingEngine
     
    %assert IsModelReferenceRTWTarget()
    %assign args = SLibAttachTimingArgsForCPPEncap(block,blockInterface,args)
   
  %endif %% sysFcnName == "RegistrationFcn" && !SLibIsCPPEncapMdlRefBuild()
 
  %assign rtmContainedInSelf = ISFIELD(block, "ModelInstVarIndex") && block.ModelInstVarIndex > -1 || ...
    (blockInterface.rtmAllocateInParent && ::isRAccel)
  %%
  %% RTModel
  %if !skipRTM && fcnInfo.ArgInfo[RTModelIdx] == 1
    %if blkSimpInterface || (blockInterface.rtmAllocateInParent && !SLibIsSelfInSimTarget() && !isRAccel)
      %assign isRegFcn = sysFcnName == "RegistrationFcn"
      %assign rtmField = SLibGetModelInstVariableAddressForSimplifiedInterface(block,instIdx,isRegFcn)
      %if SIZE(args,1) > 0 && !isRegFcn
        %assign tmpArgs = []
        %assign tmpArgs = tmpArgs+rtmField
        %foreach idx = SIZE(args,1)
          %assign tmpArgs = tmpArgs + args[idx]
        %endforeach
        %assign args = tmpArgs
      %else
        %assign args = args + rtmField
      %endif
    %elseif SLibModelBlockRTMAllocateInParent(block, blockInterface)
      %assign rtmArg = "&" + block.Identifier
      %assign args = args + rtmArg
    %else
      %assign mdlBlkDWork = SLibGetModelBlockStructDWorkArg(mdlBlkDWork, ...
          baseSystemIdx, block, sysFcnName, instIdx)
      %assign rtmField = rtmContainedInSelf ? "" : ".rtm"
      %assign args = args + "&(%<mdlBlkDWork>%<rtmField>)"
    %endif
  %endif
  %%
  %% BlockIO
  %if !skipLocalB && fcnInfo.ArgInfo[BlockIOIdx] == 1
    %assign mdlBlkDWork = SLibGetModelBlockStructDWorkArg(mdlBlkDWork, ...
      baseSystemIdx, block, sysFcnName, instIdx)
    %assign rtmField = rtmContainedInSelf ? ".blockIO" : ".rtb"
    %assign args = args + "&(%<mdlBlkDWork>%<rtmField>)"
  %endif
  %assign subsysRegFcnForCPPClassModelRefBlock = block.MdlRefIsCPPClassGenMode && ...
    !IsSystemReusableParentBaseSys(BlockIdx[0]) &&...
    (!IsModelRefScalableBuild() || GenerateClassInterface)
 
  %assign regFcn4MdlRefBlkCPPFromSubSys = subsysRegFcnForCPPClassModelRefBlock && ...
    sysFcnName == "RegistrationFcn" && ...
    ISFIELD(block,"CPPObjDWorkIdxInSubsys")
 
  %if regFcn4MdlRefBlkCPPFromSubSys
    %assert "RegistrationFcn" == sysFcnName
    %assign mdlRefInstCPPVar = ...
      SLibGetModelBlockVarGroupPath(baseSystemIdx, block, instIdx) ...
      + mdlRefInstCPPVar
  %elseif subsysRegFcnForCPPClassModelRefBlock && ...
    ISFIELD(block,"ModelInstVarGroupIndex") && ...
    block.ModelInstVarGroupIndex > -1
    %assign mdlRefInstCPPVar = ...
      SLibCGIRVarGroupPath(block.ModelInstVarGroupIndex,System[BlockIdx[0]].SystemIdx,sysFcnName != "RegistrationFcn") ...
      + mdlRefInstCPPVar
  %endif
 
  %%
  %% DWork
  %if !skipLocalDW && ...
    (fcnInfo.ArgInfo[DWorkIdx] == 1 || regFcn4MdlRefBlkCPPFromSubSys)
    %assign mdlBlkDWork = SLibGetModelBlockStructDWorkArg(mdlBlkDWork, ...
      baseSystemIdx, block, sysFcnName, instIdx)
    %assign rtmField = rtmContainedInSelf ? ".dwork" : ".rtdw"
    %assign args = args + "&(%<mdlBlkDWork>%<rtmField>)"
  %endif
     
  %if (sysFcnName == "RegistrationFcn") && ...
    GenerateClassInterface && block.MdlRefIsCPPClassGenMode
      %return SLibGetModelBlockRegistrationFunctionForCppClassGen(block,blkPath,blockInterface,instIdx,childIdx,mSysIdx)
  %endif %% (sysFcnName == "RegistrationFcn") && GenerateClassInterface &&
         %% block.MdlRefIsCPPClassGenMode
 
 
  %% All the rest will be supported when ERT supports continuous states/time, we
  %% must test them when that is online.
  %%
  %% ContStates
  %if !skipLocalX && fcnInfo.ArgInfo[ContStatesIdx] == 1
    %assign arg = SLibModelBlockContinuousStateAddr(baseSystemIdx, mSysIdx, ...
      block, sysFcnName, instIdx)
    %assign args = args + "%<arg>"
  %endif
  %%
  %% ContStatesDerivative
  %if !skipLocalXdot && fcnInfo.ArgInfo[ContStatesDerivativeIdx] == 1
    %assert (sysFcnName != "RegistrationFcn")
    %assign arg = SLibContinuousStateDerivativeAddr(mSysIdx)
    %assign args = args + "%<arg>"
  %endif
  %%
  %% ContStatesDisabled
  %if !skipLocalXdis && fcnInfo.ArgInfo[ContStatesDisabledIdx] == 1
    %assert (sysFcnName != "RegistrationFcn")
    %assign arg = SLibContStateDisabledAddr(mSysIdx)
    %assign args = args + "%<arg>"
  %endif
  %%
  %% Continuous States Absolute Tolerance
  %if !skipLocalXabstol && fcnInfo.ArgInfo[ContStatesAbsoluteToleranceIdx] == 1
    %assert (sysFcnName != "RegistrationFcn")
    %assign arg = SLibContStateAbsoluteToleranceAddr(mSysIdx)
    %assign args = args + "%<arg>"
  %endif
  %%
   
  %% Continuous States Perturb Min
  %if !skipLocalXperturbmin && fcnInfo.ArgInfo[ContStatesPerturbMinIdx] == 1
    %assert (sysFcnName != "RegistrationFcn")
    %assign arg = SLibContStatePerturbMinAddr(mSysIdx)
    %assign args = args + "%<arg>"
  %endif
  %%
   
  %% Continuous States Perturb Max
  %if !skipLocalXperturbmax && fcnInfo.ArgInfo[ContStatesPerturbMaxIdx] == 1
    %assert (sysFcnName != "RegistrationFcn")
    %assign arg = SLibContStatePerturbMaxAddr(mSysIdx)
    %assign args = args + "%<arg>"
  %endif
  %%
  
   
  %% NonsampledZC
  %if !skipLocalZCSV && fcnInfo.ArgInfo[NonsampledZCIdx] == 1
    %assert (sysFcnName != "RegistrationFcn")
    %assign arg = SLibNonsampledZCAddr()
    %assign args = args + "%<arg>"
  %endif
  %%
  %% ZCEvent
  %if !skipLocalZCE && fcnInfo.ArgInfo[ZCEventIdx] == 1
    %assign mdlBlkDWork = SLibGetModelBlockStructDWorkArg(mdlBlkDWork, ...
      baseSystemIdx, block, sysFcnName, instIdx)
    %assign args = args + "&(%<mdlBlkDWork>.rtzce)"
  %endif
  %%
  %% MassMatrix
  %if blockInterface.ModelIsLinearlyImplicit
    %assert (::CompiledModel.ModelIsLinearlyImplicit == "yes")
    %if (sysFcnName == "RegistrationFcn")
      %assign mmOffset = SLibBlockMassMatrixPrOffset("","",0)
      %if SLibIsMappedSystemInDeploymentDiagram(mSysIdx)
        %assign tIdx = SLibDeploymentGetTaskIndexForComponent(SLibGetPIDFromBlock(block, 0), 0)
        %assign args = args + ...
          "&(%<SLibDeploymentGetTasksMassMatricesVarName(tIdx)>.pr[%<mmOffset>])"
      %else
        %assign args = args + "&(%<LibGetMassMatrixGlobalPr()>[%<mmOffset>])"
      %endif
    %endif
  %endif
  %%
  %% Parameter Arguments
  %foreach argIdx=numPrmArgs
    %assign argInfo = canPrmArgInfo[argIdx]
    %if !skipCanParam[argIdx] && argInfo >= 1
      %assign prmType = prmTypes[argIdx]
      %assign isPointer = (1 == prmIsPointer[argIdx])
      %assign numBlockParamArgs = block.ParamSettings.NumBlockParamArgs
      %assign args = args + ...
        SLibGetModelBlockParameter(block, argIdx+numBlockParamArgs, argInfo, prmType, isPointer)
    %endif
  %endforeach
 
  %%
  %% In the ModelReference initialization code we need to pass in the systemRan
  %% dwork pointer and the corresponding tid. All this is already hanging off
  %% the DataMapInfo, so simply index in to the correct array(s).
  %%
  %if (sysFcnName == "RegistrationFcn")
    %if IsModelReferenceSimTarget()
      %assign descIdx = ::CompiledModel.System[BlockIdx[0]].DescSysIdx[instIdx]
      %assign contIdx = ::CompiledModel.SubsystemRanBC.ContextSysIdx[descIdx]
      %assign arg1 = "%<RTMGet("DataMapInfo")>.systemRan[%<contIdx>]"
      %assign arg2 = "%<RTMGet("DataMapInfo")>.systemTid[%<contIdx>]"
      %assign args = args + "%<arg1>" + "%<arg2>"
    %elseif ::isRAccel
      %assign args = args + "NULL" + "0"
    %endif
  %endif
   
  %% For every child model, when C-API is selected we need to pass the parent
  %% MMI structure to the child initialize function. The child MMI is cached
  %% inside the parent MMI. Also, the child model instance is assigned the
  %% corresponding block path in the parent model. Need to pass the block path
  %% and continous state start index (if states are logged).
  %if (sysFcnName == "RegistrationFcn")
    %assign blockInterface = GetModelrefInterface(block)
    %if ISFIELD(blockInterface, "RegFcnNeedsCAPIArgs") && ...
      blockInterface.RegFcnNeedsCAPIArgs
      %% Protected model blocks, and blocks inside foreach do not
      %% have any C-API information because they don't log.
      %if (RTWCAPI == 1) && !block.ParamSettings.InsideForEachSS && ...
        !block.ParamSettings.ProtectedModelBlock
        %% The top model has C-API turned on, i.e. it defines a MMI structure.
        %% Need to pass a pointer of the parent MMI to the child model
        %if GenRTModel
          %assign arg1 = "&(%<RTMGet("DataMapInfo")>.mmi)"
        %else
          %%RSim does not use rtModel with the C-API
          %assign arg1 = "&(%<RSimRTWCAPIVarPtr>->mmi)"
        %endif
         
        %% For protected SIM targets, we don't want to use actual blockpaths
        %assign blockPath = blkPath
        %if SLibIsGeneratingSimTargetForProtectedModel()
          %assign blockPath = SLibGetProtectedBlockPath()
        %endif
         
        %assign args = args + "%<arg1>" + "/"%<blockPath>/"" + "%<childIdx>"
        %if (block.ContStates[0] > 0)
          %% Search through all the global ContinuousStates to find the one that is associated
          %% with the Model block and instance to handle code reuse.
          %assign modelBlockSigSrc = [%, %<instIdx>, %]
          %with ::CompiledModel.ContStates
            %foreach csIdx = NumContStates
              %if ContState[csIdx].SigSrc == modelBlockSigSrc
                %assign csvIdx = ContState[csIdx].StartIndex
                %break
              %endif
            %endforeach
          %endwith
        %else
          %assign csvIdx = -1
        %endif
        %assign args = args + "%<csvIdx>"
      %else
        %% The top model has not defined a MMI pointer. Pass NULL pointers
        %% to the child model, if the child-model has a MMI structure
        %assign args = args + SLibGetNullDefinitionFromTfl">SLibGetNullDefinitionFromTfl() + SLibGetNullDefinitionFromTfl">SLibGetNullDefinitionFromTfl() + "0" + "-1"
      %endif %% RTWCAPI == 1
    %endif %% blockInterface.RegFcnNeedsCAPIArgs
  %endif %% Registration Functions
   
  %% Fill the return string fcnName(args, ...)
  %assign retStr = ""
   
  %if ISEMPTY(args)
    %% no input argument
    %if !GenerateClassInterface || !block.MdlRefIsCPPClassGenMode
      %assign retStr = "%<retStr>%<fcnName>" + "()"
    %else
      %assign dotOrArrow = SLibCPPDotOrArrowAccessOperator(block,blockInterface)
      %if (!IsSystemReusableParentBaseSys(BlockIdx[0]) || ...
        !(sysFcnName == "RegistrationFcn") || ...
        !IsModelRefScalableBuild()) && ...
        ISFIELD(block,"CPPObjDWorkIdxInSubsys")
        %assign subSysDWRec = SLibGetSubsysDWorkForCPPMdlRefBlk(block)
        %assign theObjArg = LibBlockDWork(subSysDWRec, "","","0")
        %assign retStr = "%<retStr>" + "(" + theObjArg +")%<dotOrArrow>%<fcnName>" + "()"
      %else
        %assign retStr = "%<retStr>" + mdlRefInstCPPVar +"%<dotOrArrow>%<fcnName>" + "()"
      %endif
    %endif
  %else
    %if !GenerateClassInterface || !block.MdlRefIsCPPClassGenMode
      %assign retStr = "%<retStr>%<fcnName>" + "("
    %else
      %assign dotOrArrow = SLibCPPDotOrArrowAccessOperator(block,blockInterface)
 
      %if (!IsSystemReusableParentBaseSys(BlockIdx[0])||...
          !(sysFcnName == "RegistrationFcn") ||...
          !IsModelRefScalableBuild()) && ...
          ISFIELD(block,"CPPObjDWorkIdxInSubsys")
        %assign subSysDWRec = SLibGetSubsysDWorkForCPPMdlRefBlk(block)
        %assign theObjArg = LibBlockDWork(subSysDWRec, "","","0")
        %assign retStr = "%<retStr>" + "(" + theObjArg +")%<dotOrArrow>%<fcnName>" + "("
      %else
        %assign retStr = "%<retStr>" + mdlRefInstCPPVar +"%<dotOrArrow>%<fcnName>" + "("
      %endif
    %endif
     
    %foreach idx = SIZE(args,1)
      %if idx == 0
        %% one input argument (no comma is needed)
        %assign retStr = retStr + args[idx]
      %else
        %assign retStr = retStr + ", " + args[idx]
      %endif
    %endforeach
    %assign retStr = retStr + ")"
  %endif
   
  %if retArgPortIdx >= 0
    %assign retStr = LibBlockAssignOutputSignal(retArgPortIdx, "", "", 0, retStr)
  %elseif !WHITE_SPACE(retStr)
    %assign retStr = retStr + ";"
  %endif
 
  %% Insert assignments between reusable inports and outports
  %if !ReuseMdlRefIO
    %assign retStr = GetReusableInoutAssignmentsFromFPC(...
      FPC, mSysIdx, block, sysFcnName, mdlRefIdx, canInputInfo) + retStr
  %endif
   
  %return retStr
%endfunction
 
 
%%Function:GetFunctionStr==================================================
%%Abstract:
%%ThefollowingorderisusedinFcnGetAdditionalArgsand
%%FcnAddParametersAndReturn.Wemustusethesameorder:
%%TID
%%outputIdx(VarDimsonly)
%%ruleIdx(VarDimsonly)
%%CanonicalInput
%%CanonicalDWorkforCanonicalInput
%%CanonicalOutput
%%CanonicalDWorkforCanonicalOutput
%%SimStruct
%%rtModel
%%BlockIO
%%ConstBlockIO(?)
%%DWork
%%Prm(?)
%%ContStates
%%ContStatesDerivative
%%ContStatesDisabled
%%ContStatesAbsoluteTolerance
%%ContStatesPerturbMin
%%ContStatesPerturbMax
%%NonsampledZC
%%ZCEvent
%%MassMatrix
%%NumCanonicalPrm
%%CanDWork(?)
%%C-APIrequiredarguments(optional)
%%osysRan(mdlrefsimtargetrequired)
%%osysTID(mdlrefsimtargetrequired)
%%oMMI(mdlrefsimrequired,rtwtargetifRTWCAPI==true)
%%oblockPath(mdlrefsimrequired,rtwtargetifRTWCAPI==true)
%%ochildIdx(mdlrefsimrequired,rtwtargetifRTWCAPI==true)
%%oContStateIdx(mdlrefsimrequired,rtwtargetifRTWCAPIStates)
%%
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function GetFunctionStr(block, sysFcn, instIdx, tid, childIdx, blkPath)
  %assign sysFcnName = ISEQUAL(tid,"") ? ...
    "%<sysFcn>Fcn" : "%<sysFcn>TID%<tid>Fcn"
  %assign blockInterface = GetModelrefInterface(block)
  %assign fcnInfo = blockInterface.%<sysFcnName>
  %return SLibCallModelBlockFunction([], block, sysFcnName, blockInterface, ...
    fcnInfo, instIdx, tid, childIdx, blkPath)
%endfunction %%GetFunctionStr
 
%function GetSetDimsFunctionStr(outAndRuleIdx, block, sysFcn, instIdx, tid, childIdx, blkPath)
  %assign sysFcnName = ISEQUAL(tid,"") ? ...
    "%<sysFcn>Fcn" : "%<sysFcn>TID%<tid>Fcn"
  %assign blockInterface = GetModelrefInterface(block)
  %assign fcnInfo = blockInterface.%<sysFcnName>
 
  %return SLibCallModelBlockFunction(outAndRuleIdx, block, sysFcnName, blockInterface, ...
    fcnInfo, instIdx, tid, childIdx, blkPath)
%endfunction %%GetFunctionStr
 
%function GetModelRefFcnCallTriggerTIDIsReq(block) void
  %assign blockInterface = GetModelrefInterface(block)
  %return blockInterface.FcnCallMdlRefTriggerTIDIsReq
%endfunction
 
%%Function:GetModelRefFcnNeedsTID===========================================
%%Abstract:
%%ReturnswhetherthisfunctionusesTIDintheargumentlist,weonly
%%needtocheckthisfortheupdateandoutputfunctions.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function GetModelRefFcnNeedsTID(block, sysFcn)
  %assert (sysFcn == "UpdateFcn") || (sysFcn == "OutputFcn") || ...
    (sysFcn == "OutputUpdateFcn")
  %% Note that the TIDidx must match the index in GetFunctionStr above.
  %assign TIDIdx = 0
  %assign needsTID = 0
 
  %with block
    %assign blockInterface = GetModelrefInterface(block)
    %if ISFIELD(blockInterface, "%<sysFcn>")
      %assign needsTID = blockInterface.%<sysFcn>.ArgInfo[TIDIdx]
    %endif
  %endwith
  %return needsTID
%endfunction
 
%function FcnEmitInitializerRegion(parent) void
  %openfile buffer
  {
  %assign numElements = SIZE(parent.Elements, 1)
  %foreach eIdx = numElements
    %assign comma = (eIdx < (numElements - 1)) ? "," : ""
    %assign element = parent.Elements[eIdx].Element
    %if TYPE(element) == "String"
      %assign idNum = IDNUM(element)
      %switch idNum[0]
        %% Reference to coder data group from this model
        %case "RCDG"
            %assign group = ::CompiledModel.CoderGroup[idNum[1]]
            &(%<SLibCoderDataGroupInstance(group)>)%<comma>
          %break
        %% Reference to propagated coder data group from descendent model
        %case "RPCDG"
          %assign group = ::CompiledModel.CoderDataGroups.CoderDataGroup[idNum[1]]
          &(%<group.GroupPath>)%<comma>
          %break
        %case "RVG"
          %assign vargroup = ::CompiledModel.VarGroups.VarGroup[idNum[1]]
          %break
        %case "PD"
          %foreach pads = idNum[1]
            %assign comma2 = (pads < (idNum[1] - 1)) ? "," : ""
            'a'%<comma2>/
          %endforeach
          %<comma>
          %break
        %default
          %<element>%<comma>
          %break
      %endswitch
    %else
      %<FcnEmitInitializerRegion(element)>%<comma>
    %endif
  %endforeach
  }/
  %closefile buffer
  %return buffer
%endfunction
 
%function FcnEmitInitializer(groupInitializer) void
  %if ISEMPTY(groupInitializer) || WHITE_SPACE(groupInitializer)
    %return ""
  %elseif TYPE(groupInitializer) == "String"
    %return groupInitializer
  %else
    %return FcnEmitInitializerRegion(groupInitializer)
  %endif
%endfunction
 
%%Function:FcnAdjustInitializer==============================================================================
%%Abstract:
%%reformulatethestaticinitializerofapropagatedgrouptothecontextofthisparentmodel
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnAdjustInitializer(originalInitializer, mdlRefIdx) void
  %if ISEMPTY(originalInitializer) || (TYPE(originalInitializer) == "String")
    %return originalInitializer
  %endif
  %createrecord adjustedInitializer {}
  %assign numElements = SIZE(originalInitializer.Elements, 1)
  %foreach eIdx = numElements
    %assign element = originalInitializer.Elements[eIdx].Element
    %if TYPE(element) == "String"
      %% In case element is a dataref, need to truly make a string to get element[0]
      %assign element0 = STRING(element)[0]
      %assign idNum = IDNUM(element)
      %switch idNum[0]
          %% Non-testpointed model parameter: just replace with the fornatted value
        %case "P"
          %assign blktpIdx = idNum[1]
          %assign mdlrefBlock = ::CompiledModel.ModelBlock[mdlRefIdx]
          %% The usage of the first instance block is OK here since all
          %% corresponding instances must have the same value or else
          %% reuse would not have been possible
          %assign prmIdx = mdlrefBlock.ParameterModelParameterIndices[blktpIdx]
          %assert prmIdx >= 0
          %assign mdlprm = ::CompiledModel.ModelParameters.Parameter[prmIdx]
          %assign mdltpIdx = mdlprm.TestpointIndex
          %assert mdltpIdx < 0
          %addtorecord adjustedInitializer Elements { Element "%<SLibGetFormattedPrmValue(mdlprm, "")>" }
          %break
          %% Testpointed parameter: adjust to this parent model, unless this parent model
          %% is a top model in which case replace with the formatted value
        %case "TP"
          %assign blktpIdx = idNum[1]
          %assign mdlrefBlock = ::CompiledModel.ModelBlock[mdlRefIdx]
          %% The usage of the first instance block is OK here since all
          %% corresponding instances must have the same value or else
          %% reuse would not have been possible
          %assign prmIdx = mdlrefBlock.ParameterModelParameterIndices[blktpIdx]
          %assert prmIdx >= 0
          %assign mdlprm = ::CompiledModel.ModelParameters.Parameter[prmIdx]
          %assign mdltpIdx = mdlprm.TestpointIndex
          %% We don't support testpointed parameters for top model
          %if mdltpIdx < 0 || !IsModelReferenceTarget()
            %if mdlprm.StorageClass == "Custom"
              %assign genType = SLibGetGenerateTypeForData(mdlprm)
              %assign init = GENERATE_TYPE(mdlprm,"DataAccess",genType,"contents","","")
              %addtorecord adjustedInitializer Elements { Element "%<init>" }
            %else
              %addtorecord adjustedInitializer Elements { Element "%<SLibGetFormattedPrmValue(mdlprm, "")>" }
            %endif
          %else
            %addtorecord adjustedInitializer Elements { Element "TP%<mdltpIdx>" }
          %endif
          %break
          %% Padding: preserve as-is
        %case "PD"
          %addtorecord adjustedInitializer Elements { Element element }
          %break
          %% reference to coder data group: convert to reference to propagated group with the index adjusted
          %% to this parent model
        %case "RCDG"
          %assign mapKey = "Group" + STRING(idNum[1])
          %assign mapValue = FcnCoderGroupIndexMapValue(mdlRefIdx, mapKey)
          %assign groupIndex = mapValue.CoderDataGroupIndex
          %assign adjustedElement = "RPCDG" + STRING(groupIndex)
          %addtorecord adjustedInitializer Elements { Element adjustedElement }
          %break
          %% Reference to propagated coder data group from descendent model
        %case "RPCDG"
          %assign mapKey = "ChildGroup" + STRING(idNum[1])
          %assign mapValue = FcnCoderGroupIndexMapValue(mdlRefIdx, mapKey)
          %assign groupIndex = mapValue.CoderDataGroupIndex
          %assign adjustedElement = idNum[0] + STRING(groupIndex)
          %addtorecord adjustedInitializer Elements { Element adjustedElement }
          %break
          %% Embedded Propagated coder data group from descendent model: preserve as-is
        %case "PCDG"
          %addtorecord adjustedInitializer Elements { Element element }
          %break
          %% Reference to (non-codergroup) vargroup: preserve as-is
        %case "RVG"
          %addtorecord adjustedInitializer Elements { Element %<element> }
          %break
          %% Default for string: preserve as-is
        %default
          %addtorecord adjustedInitializer Elements { Element element }
          %break
      %endswitch
    %elseif TYPE(element) == "Scope"
      %% Recurse for scopes
      %% Initialize to dummy value since addrecord can't handle newlines thus we
      %% will directly set the value of the new element after adding the dummy value.
      %addtorecord adjustedInitializer Elements { Element 0 }
      %assign init = FcnAdjustInitializer(element, mdlRefIdx)
      %assign numElements = SIZE(adjustedInitializer.Elements, 1)
      %assign adjustedInitializer.Elements[numElements - 1].Element = init
    %else
      %assign errTxt = "Unhandled argument"
      %<LibReportError(errTxt)>
    %endif
  %endforeach
  %return adjustedInitializer
%endfunction
 
%%Function:FcnAdjustDynamicInitializer======================================================================
%%Abstract:
%%reformulatethedynamicinitializerofapropagatedgrouptothecontextofthisparentmodel
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnAdjustDynamicInitializer(childGroup, mdlRefIdx, blockInterface, dynamicInitPath, childGroupPath, childGroupSID) void
  %assign originalInitializer = childGroup.DynamicInitializer
  %if ISEMPTY(originalInitializer)
    %return originalInitializer
  %endif
  %createrecord adjustedInitializer {}
  %assign fieldNames = FIELDNAMES(originalInitializer)
  %assign numElements = SIZE(fieldNames, 1)
  %foreach eIdx = numElements
    %assign fieldName = fieldNames[eIdx]
    %assign originalPath = originalInitializer.%<fieldName>
    %assign idNum = IDNUM(fieldName)
    %if idNum[0] == "TP"
      %assign blktpIdx = idNum[1]
      %assign mdlrefBlock = ::CompiledModel.ModelBlock[mdlRefIdx]
      %% The usage of the first instance block is OK here since all
      %% corresponding instances must have the same value or else
      %% reuse would not have been possible
      %assign prmIdx = mdlrefBlock.ParameterModelParameterIndices[blktpIdx]
      %assert prmIdx >= 0
      %assign mdlprm = ::CompiledModel.ModelParameters.Parameter[prmIdx]
      %assign mdltpIdx = mdlprm.TestpointIndex
      %if blockInterface.OkToMultiInstance
        %assign adjustedPath = dynamicInitPath + "." + originalPath
      %else
        %assign adjustedPath = originalPath
      %endif
      %if mdltpIdx >= 0 && !::isRAccel && !Accelerator
        %addtorecord adjustedInitializer TP%<mdltpIdx> adjustedPath
      %else
        %addtorecord adjustedInitializer P%<prmIdx> adjustedPath
      %endif
      %if IsModelReferenceSimTarget()
        %addtorecord mdlprm ChildGroupPath adjustedPath
      %endif
      %addtorecord mdlprm ChildGroupSID childGroupSID
    %elseif idNum[0] == "P"
      %% Do nothing; swallow it up
    %else
      %assign errTxt = "Unhandled argument type '%'."
      %<LibReportError(errTxt)>
    %endif
  %endforeach
  %return adjustedInitializer
%endfunction
 
%%Function:CallModelrefBlockRegFcns=========================================
%%Abstract:
%%Callallchildmodelreferenceblockregistrationfunctions.Note
%%thattheinputmdlRefBlkscanbeempty.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants_crossfeature.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants4.m
%%TopTester:test/toolbox/simulink/variants/tvss_sim_code_match_g984892.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1317695_VC1.m-tmg1331407_VC1.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tVariantSource4.m
%%
%function CallModelrefBlockRegFcns(mdlRefBlks)
  %assign baseSysIdx = GetBaseSystemIdx()
  %openfile modelrefBuffer
  %if !ISEMPTY(mdlRefBlks)
    %assign needsTimingBridgeForDeploymentDiagram = TLC_FALSE
    %% First determine if any of the model blocks in this
    %% model need the global timing engine.
    %foreach rowIdx = SIZE(mdlRefBlks,0)
      %assign mdlRefInfo = mdlRefBlks[rowIdx]
      %assign mSysIdx = mdlRefInfo[0]
      %assign bIdx = mdlRefInfo[1]
      %assign instIdx = mdlRefInfo[2]
      %with ::CompiledModel.System[mSysIdx].Block[bIdx]
        %assign blk = ::CompiledModel.System[mSysIdx].Block[bIdx]
        %% The usage of the first instance modelBlock is OK here because
        %% all corresponding instances across parent reusable subsystems
        %% must have a consistent state
        %assert 0 == blk.DeletedInIR
        %assign blockInterface = GetModelrefInterface(blk)
        %if blockInterface.NeedsGlobalTimingEngine
          %assign ::tMdlRefTimingBridgeAccessed = TLC_TRUE
          %if LibIsDeploymentDiagram() && ...
            !SLibIsMappedSystemInDeploymentDiagram(mSysIdx)
            %assign needsTimingBridgeForDeploymentDiagram = TLC_TRUE
          %endif
          %break
        %endif
      %endwith
    %endforeach
     
    %if !LibIsDeploymentDiagram() || needsTimingBridgeForDeploymentDiagram
    %% We only need to declare a local timing bridge
    %% for ERT based targets. If the target is simstruct based
    %% (like RSIM), then the simstruct will already have a timing bridge.
 
 
    %if !IsModelReferenceTarget() && SLibIsERTCodeFormat() && ...
      ::tMdlRefTimingBridgeAccessed
      %if !MultiInstanceERTCode
        %assign timingVar = "rtTimingBridge %<SLibGetGlobalTimingBridge()>;"
        %<SLibCacheCodeToFile("mdl_data_defn", timingVar)>
        %<SLibCacheCodeToFile("mdl_priv_extern_data_decl", "extern " + timingVar)>
      %endif
      {
        %% Determine if any clockticks are needed. Note that if a long clock
        %% tick is needed, then the normal clock tick is also needed since they
        %% come in pairs.
        %assign needClockTicks = TLC_FALSE
        %assign needLongClockTicks = TLC_FALSE
        %foreach idx = NumRuntimeExportedRates
          %if ClockTickForTIDIsReqFcn(idx)
            %assign needClockTicks = TLC_TRUE
            %if LongClockTickForTIDIsReqFcn(idx)
              %assign needLongClockTicks = TLC_TRUE
              %break
            %endif
          %endif
        %endforeach
         
        %if needClockTicks
          static uint32_T *clockTickPtrs[%<NumSampleTimes>];
          %if needLongClockTicks
            static uint32_T *clockTickHPtrs[%<NumSampleTimes>];
          %endif
        %endif
        %if RTMTimePtrIsReqFcn() || RTMTaskTimeIsReqFcnForTID(0)
          static real_T *taskTimePtrs[%<NumSampleTimes>];
        %endif
        %if ::CompiledModel.SingleRate != "yes"
          %if RTMTaskCountersIsReqFcn()
            static uint32_T *taskCounterPtrs;
          %endif
          %if ERTPerTaskSampleHitsIsReqFcn()
            %assign rateTransitionSize = ...
              "(%<NumSampleTimes> * %<NumSampleTimes>)"
            static boolean_T *rateTransitionPtrs[%<rateTransitionSize>];
          %endif
        %endif
         
        %<SLibGetGlobalTimingBridge()>.nTasks = %<NumSampleTimes>;
         
        %if needClockTicks
          %foreach idx = NumSampleTimes
            %if ClockTickForTIDIsReqFcn(idx)
              clockTickPtrs[%<idx>] = &(%<RTMGet("ClockTick%<idx>")>);
            %else
              clockTickPtrs[%<idx>] = %<SLibGetNullDefinitionFromTfl()>;
            %endif
            %if needLongClockTicks
              %if LongClockTickForTIDIsReqFcn(idx)
                clockTickHPtrs[%<idx>] = &(%<RTMGet("ClockTickH%<idx>")>);
              %else
                clockTickHPtrs[%<idx>] = %<SLibGetNullDefinitionFromTfl()>;
              %endif
            %endif
          %endforeach
          %<SLibGetGlobalTimingBridge()>.clockTick = clockTickPtrs;
          %if needLongClockTicks
            %<SLibGetGlobalTimingBridge()>.clockTickH = clockTickHPtrs;
          %else
            %<SLibGetGlobalTimingBridge()>.clockTickH = %<SLibGetNullDefinitionFromTfl()>;
          %endif
        %else
          %<SLibGetGlobalTimingBridge()>.clockTick = %<SLibGetNullDefinitionFromTfl()>;
          %<SLibGetGlobalTimingBridge()>.clockTickH = %<SLibGetNullDefinitionFromTfl()>;
        %endif
         
        %if ::CompiledModel.SingleRate != "yes"
          %if RTMTaskCountersIsReqFcn()
            %assign cTick = RTMGet("TaskCounters")
            taskCounterPtrs = ...
              &(%<cTick>.%<SLibERTMultiRateCounterField(0)>);
            %<SLibGetGlobalTimingBridge()>.taskCounter = taskCounterPtrs;
          %endif
          %if ERTPerTaskSampleHitsIsReqFcn()
            %assign shMat = RTMGet("PerTaskSampleHits")
            %foreach i = NumRuntimeExportedRates
              %foreach j = NumRuntimeExportedRates
                %if SLibGetNeedRateInteraction(i,j)
                  %if SuppressMultiTaskScheduler || (UseTargetTaskScheduler() && !SLibSingleTasking())
                    %assign val = "%<RTMGet("PerTaskSampleHits")>."...
                      "b_%<SLibERTMultiRateTimingField(j,i)>"
                  %else
                    %assign val = "%<RTMGet("PerTaskSampleHits")>."...
                      "%<SLibERTMultiRateTimingField(j,i)>"
                  %endif
                  rateTransitionPtrs[%<i>*%<NumSampleTimes> + %<j>] /
                  = &(%<val>);
                %endif
              %endforeach
            %endforeach
            %<SLibGetGlobalTimingBridge()>.rateTransition = rateTransitionPtrs;
          %endif
        %endif
         
        %if RTMTimePtrIsReqFcn() || RTMTaskTimeIsReqFcnForTID(0)
          %foreach idx = NumSampleTimes
            %if SampleTime[idx].NeedFloatTime == "yes"
              taskTimePtrs[%<idx>] = &(%<LibGetTaskTime(idx)>);
            %else
              taskTimePtrs[%<idx>] = %<SLibGetNullDefinitionFromTfl()>;
            %endif
          %endforeach
          %<SLibGetGlobalTimingBridge()>.taskTime = taskTimePtrs;
        %endif
         
        %if RTMFirstInitCondFlagIsReqFcn()
          %<SLibGetGlobalTimingBridge()>.firstInitCond = &%<RTMIs("FirstInitCond")>;
        %endif
      }
    %endif %% !IsModelReferenceTarget() && SLibIsERTCodeFormat() && ...
    %endif %% !LibIsDeploymentDiagram() || needsTimingBridgeForDeploymentDiagram
     
    %% Add information to generate the top model's initialize to generate the
    %% data need to pass into the child model's initalize
    %if !IsModelReferenceTarget() && ISFIELD(::CompiledModel, "NumDataTransfers") && ::CompiledModel.NumDataTransfers > 0
      %assign rteBlkDWorkIndex = ::CompiledModel.RteBlockDWorkIndex
      %with System[NumSystems-1]
        const uint32_T *gblDataTransferIds = &%<LibBlockDWork(::CompiledModel.DWorks.DWork[rteBlkDWorkIndex],"", "", 0)>;
      %endwith
    %endif
  %endif %% !ISEMPTY(mdlRefBlks)
   
  %if LibIsDeploymentDiagram()
    %assign buf = SLibDeploymentCallModelrefBlockRegFcns(mdlRefBlks)
    %if !WHITE_SPACE(buf)
      %<buf>
    %endif
  %endif
 
  %with ::CompiledModel.System[baseSysIdx]
    %assign mdlBlkIdx = 0
    %foreach rowIdx = SIZE(mdlRefBlks,0)
       %assign mdlRefInfo = mdlRefBlks[rowIdx]
       %assign mSysIdx = mdlRefInfo[0]
       %assign bIdx = mdlRefInfo[1]
       %assign instIdx = mdlRefInfo[2]
       %assign thisSystem = ::CompiledModel.System[mSysIdx]
       %assign thisBlock = thisSystem.Block[bIdx]
       %with thisBlock
        %% The usage of the first instance modelBlock is OK here because
        %% all corresponding instances across parent reusable subsystems
        %% must have a consistent state and interface
         %assert 0 == thisBlock.DeletedInIR
         %assign blockInterface = GetModelrefInterface(thisBlock)
         %assign doSSInitCacheClose = TLC_FALSE
         %if instIdx != -1
           %assign standaloneSysIdx = thisSystem.StandaloneParentSysIdx[instIdx]
           %if standaloneSysIdx != -1
             %% cache registration fcn to parent standalone initialize fcn
             %openfile stdSSBuffer
             %assign doSSInitCacheClose = TLC_TRUE
           %endif
         %endif
 
         %assign tmpVec = [%, %]
         %assign bpath = STRING(SLibMangledGrBlockPath(tmpVec))
         %if EXISTS(slrt)
         %%SPECIAL CASE FOR SLRT
             %assign bpath = STRING(SLibMangledGrBlockPath(tmpVec))
             %assign bpath = FEVAL("xpcgate","htmlencode",bpath)
         %endif
 
         %if MdlRefIsCPPClassGenMode
           %assign needsAuxilaryRegFcns = ...
             blockInterface.RTMAccessed || ...
             blockInterface.NeedsErrorStatus || ...
             blockInterface.StopReqAccessed || ...
             blockInterface.NeedsGlobalTimingEngine || ...
             (ISFIELD(blockInterface, "RegFcnNeedsCAPIArgs") && ...
             blockInterface.RegFcnNeedsCAPIArgs)
         %else
           %assign needsAuxilaryRegFcns = TLC_FALSE
         %endif
         %if ISFIELD(blockInterface, "RegistrationFcn")
           /* Model Initialize function for %<Type> Block: %<SLibGrBlockCommentName(thisBlock.GrSrc)> */
           %% TopTester : test/toolbox/simulink/variants/inlineVariants/modelref/tmdlref_basic.m -testspec:g1300511
           %assign sysIdxForMdlBlk = thisBlock.BlockIdx[0]
           %assign blockSystem = ::CompiledModel.System[sysIdxForMdlBlk]
           %assign vcRecord = SLibMdlRefNetInlineVariantPreprocessorCondition(mSysIdx, instIdx, bIdx)
           %assign parentIfCond = vcRecord.ifCond
           %assign parentIfEndCond = vcRecord.endIfCond
           %<parentIfCond>
           %assign mdlBlk = ::CompiledModel.ModelBlock[rowIdx]
           %if ISFIELD(mdlBlk, "ForEachSSLoopBnds")
             %assign ::NeedForEachLoopInReg = TLC_TRUE
             %assign ::NumForEachLoopHierarchyLevel = SIZE(mdlBlk.ForEachSSLoopBnds,1)
             %% Calculate the total number of for-loop iterations
             %assign numForLoops = 1
             %foreach levelIdx = ::NumForEachLoopHierarchyLevel
               %assign numForLoops = numForLoops * mdlBlk.ForEachSSLoopBnds[levelIdx]
             %endforeach
             %assign ::NeedLoopUnrolling = ((FEVAL("slsvTestingHook", "ForEachCodeGenLoopUnrolling") > 0) && (numForLoops < RollThreshold))
             {
             %if (::NeedLoopUnrolling)
               %% Initialize counter vector for loop unrolling
               %assign ::Counter4LoopUnrolling = []
               %foreach levelIdx = ::NumForEachLoopHierarchyLevel
                 %assign ::Counter4LoopUnrolling = ::Counter4LoopUnrolling + 0
               %endforeach
               %% Generate the unrolled loop
               %foreach loopIdx = numForLoops
                 %assign ::ForEachLoopHierarchyLevel = 1
                 %<GetFunctionStr(thisBlock, "Registration", instIdx, "", mdlBlkIdx, bpath)>
                 %% Update counter vector by adding 1 to the first level (the inner most ForEach)
                 %foreach levelIdx = ::NumForEachLoopHierarchyLevel
                   %assign ::Counter4LoopUnrolling[levelIdx] = ::Counter4LoopUnrolling[levelIdx] + 1
                   %if (::Counter4LoopUnrolling[levelIdx] < mdlBlk.ForEachSSLoopBnds[levelIdx])
                     %break
                   %else
                     %assign ::Counter4LoopUnrolling[levelIdx] = 0
                   %endif
                 %endforeach
               %endforeach
             %else
               %assign ::ForEachLoopHierarchyLevel = ::NumForEachLoopHierarchyLevel
               %foreach ssIdx = SIZE(mdlBlk.ForEachSSLoopBnds,1)
                 %assign iterVar = "i_%<ForEachLoopHierarchyLevel>"
                 %assign ::ForEachLoopHierarchyLevel = ::ForEachLoopHierarchyLevel - 1
                   int32_T %<iterVar>;
                   for (%<iterVar> = 0; %<iterVar> < %; %<iterVar>++) {
               %endforeach
               %assign ::ForEachLoopHierarchyLevel = 1
 
               %% Initialize child coder data groups when a model block is inside a ForEach SS
               %assign mdlrefKey = FcnCoderGroupIndexMapKey(rowIdx)
               %if ISFIELD(::CompiledModel.ChildGroupInitInForEachMap, mdlrefKey)
                 %assign childGroupInits = GETFIELD(::CompiledModel.ChildGroupInitInForEachMap, mdlrefKey)
                 %<childGroupInits>
               %endif
 
               %<GetFunctionStr(thisBlock, ...
                 "Registration", instIdx, "", mdlBlkIdx, bpath)>
               %foreach ssIdx = SIZE(mdlBlk.ForEachSSLoopBnds,1)
                 }
               %endforeach
             %endif
             }
             %assign ::NeedForEachLoopInReg = TLC_FALSE
           %else
             %<GetFunctionStr(thisBlock, ...
               "Registration", instIdx, "", mdlBlkIdx, bpath)>
           %endif
 
            %<parentIfEndCond>
         %elseif needsAuxilaryRegFcns
           /* Model Initialize function for %<Type> Block: '%<Name>' */
           %assign sysIdxForMdlBlk = thisBlock.BlockIdx[0]
           %% The usage of the first instance modelBlock is OK here because
           %% all corresponding instances across parent reusable subsystems
           %% must have consistent conditions
           %assign blockSystem = ::CompiledModel.System[sysIdxForMdlBlk]
           %assign vcRecord = SLibMdlRefNetInlineVariantPreprocessorCondition(mSysIdx, instIdx, bIdx)
           %assign parentIfCond = vcRecord.ifCond
           %assign parentIfEndCond = vcRecord.endIfCond
           %<parentIfCond>
           %<SLibGetModelBlockRegistrationFunctionForCppClassGen(thisBlock,bpath,blockInterface,instIdx,mdlBlkIdx,mSysIdx)>
           %<parentIfEndCond>
         %endif
         %if (::CompiledModel.RTWStatesLogging || (isRAccel&&(RTWCAPISignals==1)) ) && ...
           !IsModelReferenceTarget() && !thisBlock.ParamSettings.InsideForEachSS && ...
           !thisBlock.ParamSettings.ProtectedModelBlock
           %if GenRTModel
             %assign rtm_mmi = "&(%<RTMGet("DataMapInfo")>.mmi)"
           %else
             %assign rtm_mmi = "&(%<RSimRTWCAPIVarPtr>->mmi)"
           %endif
           %assign childMMI = "rtwCAPI_GetChildMMI(%<rtm_mmi>,%<mdlBlkIdx>)"
           {
             /* MAT-file logging: Update full-paths stored in the MMI */
             %assign bpath_unmangled = STRING(SLibGrBlockPath(tmpVec))
             char_T *tempStr = rtwCAPI_EncodePath("%<bpath_unmangled>");
             rtwCAPI_UpdateFullPaths((%<childMMI>), tempStr, 1);
             utFree(tempStr);
           }
         %endif
          
         %if doSSInitCacheClose
           %closefile stdSSBuffer
           %<LibAddToSystemField(System[standaloneSysIdx],"CachedInitializeDataBody",...
             "/n" + stdSSBuffer+ "/n")>
         %endif
          
         %<SLibDumpServiceInitForChildModel(thisBlock)>
 
       %endwith
        
       %% ChildMMI's are only created for unprotected models
       %if !thisBlock.ParamSettings.ProtectedModelBlock
         %assign mdlBlkIdx = mdlBlkIdx + 1
       %endif
     %endforeach
     %% We need to dump again ground declarations for model reference.
     %% This case happens when a scalar Ground signal is feeding a Reusable
     %% subsystem and the reusable subsystem contains a Model Reference
     %% Block
     %% -------------------
     %% | ---------- |
     %% Grnd sig | | | |
     %% -------->|--->| | |
     %% | | | |
     %% | | | |
     %% ---->|--->| | |
     %% Grnd Sig | | | |
     %% | ---------- |
     %% | Model Block |
     %% -------------------
     %% Reusable Subsystem
      
     %<SLibCacheCodeToFile("mdl_data_defn", LibDumpGroundDeclarations(0))>
 
   %endwith
    
   %if ((RTWCAPI == 1) && IsModelReferenceTarget()) && !GenerateClassInterface
     %assign mmiStr = "%<RTMGetModelSS()>->DataMapInfo.mmi"
     /* Initialize Parent model MMI */
     if ((rt_ParentMMI != %<SLibGetNullDefinitionFromTfl">SLibGetNullDefinitionFromTfl()>) && (rt_ChildPath != %<SLibGetNullDefinitionFromTfl">SLibGetNullDefinitionFromTfl()>))
     {
       rtwCAPI_SetChildMMI(*rt_ParentMMI, rt_ChildMMIIdx, &(%<mmiStr>));
       rtwCAPI_SetPath(%<mmiStr>, rt_ChildPath);
       rtwCAPI_MMISetContStateStartIndex(%<mmiStr>, rt_CSTATEIdx);
     }
   %endif
    
   %if IsModelReferenceForASimstructBasedTarget()
     %if EXISTS(SolverResetInfo) && SolverResetInfo.NumNonContDerivSignals > 0
      %assign numNoncontDerivSigs = SIZE(SolverResetInfo.NonContDerivSignal,1)
      %assign arrayIdx = 0
      %foreach idx = numNoncontDerivSigs
        %assign dU = SolverResetInfo.NonContDerivSignal[idx]
        %if ISFIELD(dU,"MdlRefInfo")
          %assign mdlRefInfo = dU.MdlRefInfo
          %assign mSysIdx = mdlRefInfo[0][0]
          %assign bIdx = mdlRefInfo[0][1]
          %assign instIdx = mdlRefInfo[0][2]
          %assign port = mdlRefInfo[0][3]
          %assign blk = System[mSysIdx].Block[bIdx]
          %assign name = blk.ParamSettings.ReferencedModelName
          %assign mangleName = FcnGetNoncontMangledName(name, mSysIdx, ...
            bIdx, instIdx)
          %foreach subIdx = dU.NumMdlRefNonContSigs
            %<RTMSetNonContDerivSignal(arrayIdx,...
              "mr_%<mangleName>nonContOutputArray[%<port>][%<subIdx>].sizeInBytes", ...
              "mr_%<mangleName>nonContOutputArray[%<port>][%<subIdx>].currVal")>;
            %assign arrayIdx = arrayIdx + 1
          %endforeach
        %else
          %if dU.ComplexSignal
            %assign dtype = LibGetDataTypeComplexNameFromId(dU.DataTypeIdx)
          %else
            %assign dtype = LibGetDataTypeNameFromId(dU.DataTypeIdx)
          %endif
          %% For NonContDerivSignal inside For Each subsystem, we need to
          %% index each For Each vargroup level by right index
          %if ISFIELD(dU, "ForEachSSIterIndices")
            %assign ::UseConstantForVarGroupIdx = TLC_TRUE
            %assign ::VarGroupIndexVector = dU.ForEachSSIterIndices
            %assign ::VarGroupIndexVectorSize = SIZE(::VarGroupIndexVector, 1)
            %assign ::VarGroupIndexVectorIdx = ::VarGroupIndexVectorSize - 1
          %endif
          %<RTMSetNonContDerivSignal(arrayIdx,...
            "%<dU.RegionLen>*sizeof(%<dtype>)", ...
            "%<GetNonContAddress(dU, System[baseSysIdx])>")>;
          %if ISFIELD(dU, "ForEachSSIterIndices")
            %assign ::UseConstantForVarGroupIdx = TLC_FALSE
            %assign ::VarGroupIndexVectorIdx = ::VarGroupIndexVectorSize - 1
          %endif
          %assign arrayIdx = arrayIdx + 1
        %endif
      %endforeach
    %endif
    %if EXISTS(SolverResetInfo) && ISFIELD(SolverResetInfo,"NonContOutputSignals")
      %foreach idx = ExternalOutputs.NumExternalOutputs
        %assign nonContOut = ...
          SolverResetInfo.NonContOutputSignals.NonContOutput[idx]
        %assign numNonContSigs = ISFIELD(nonContOut,"NonContOutputSignal") ? ...
          SIZE(nonContOut.NonContOutputSignal,1) : 0
        %assign arrayIdx = -1
        %foreach cIdx = numNonContSigs
          %assign nonContElem = nonContOut.NonContOutputSignal[cIdx]
          %assign regLen = nonContElem.RegionLen
          %if nonContElem.ComplexSignal
            %assign dType = LibGetDataTypeComplexNameFromId(nonContElem.DataTypeIdx)
          %else
            %assign dType = LibGetDataTypeNameFromId(nonContElem.DataTypeIdx)
          %endif
          %% If this signal is coming from a submodel, then we
          %% can't initialize it here. We will initialize the
          %% information after we call the submodels registration function
          if (mr_nonContOutputArray[%<idx>] != %<SLibGetNullDefinitionFromTfl()>) {
            %if ISFIELD(nonContElem,"MdlRefInfo")
              %assign mdlRefInfo = nonContElem.MdlRefInfo
              %assign mSysIdx = mdlRefInfo[0][0]
              %assign bIdx = mdlRefInfo[0][1]
              %assign instIdx = mdlRefInfo[0][2]
              %assign port = mdlRefInfo[0][3]
              %assign blk = System[mSysIdx].Block[bIdx]
              %assign name = blk.ParamSettings.ReferencedModelName
              %assign mangleName = FcnGetNoncontMangledName(name, mSysIdx, ...
                bIdx, instIdx)
              %foreach mIdx = nonContElem.NumMdlRefNonContSigs
                %assign arrayIdx = arrayIdx + 1
                mr_nonContOutputArray[%<idx>][%<arrayIdx>].sizeInBytes = ...
                  mr_%<mangleName>nonContOutputArray[%<port>][%<mIdx>].sizeInBytes;
                mr_nonContOutputArray[%<idx>][%<arrayIdx>].currVal = ...
                  mr_%<mangleName>nonContOutputArray[%<port>][%<mIdx>].currVal;
                %% If this is the last array, set the next pointer to NULL
                %if cIdx == numNonContSigs - 1 && ...
                  mIdx == nonContElem.NumMdlRefNonContSigs -1
                  mr_nonContOutputArray[%<idx>][%<arrayIdx>].next = %<SLibGetNullDefinitionFromTfl()>;
                %else
                  %assign nextIdx = arrayIdx + 1
                  mr_nonContOutputArray[%<idx>][%<arrayIdx>].next = ...
                    &(mr_nonContOutputArray[%<idx>][%<nextIdx>]);
                %endif
              %endforeach
            %else
              %% For NonContDerivSignal inside For Each subsystem, we need to
              %% index each For Each vargroup level by right index
              %if ISFIELD(nonContElem, "ForEachSSIterIndices")
                %assign ::UseConstantForVarGroupIdx = TLC_TRUE
                %assign ::VarGroupIndexVector = nonContElem.ForEachSSIterIndices
                %assign ::VarGroupIndexVectorSize = SIZE(::VarGroupIndexVector, 1)
                %assign ::VarGroupIndexVectorIdx = ::VarGroupIndexVectorSize - 1
              %endif
              %assign address = GetNonContAddress(nonContElem, ...
                ::CompiledModel.System[GetBaseSystemIdx()])
              %if ISFIELD(nonContElem, "ForEachSSIterIndices")
                %assign ::UseConstantForVarGroupIdx = TLC_FALSE
                %assign ::VarGroupIndexVectorIdx = ::VarGroupIndexVectorSize - 1
              %endif
              %assign arrayIdx = arrayIdx + 1
              mr_nonContOutputArray[%<idx>][%<arrayIdx>].sizeInBytes = ...
                %<regLen>*sizeof(%<dType>);
              mr_nonContOutputArray[%<idx>][%<arrayIdx>].currVal = (char_T *)%<address>;
              %if cIdx == numNonContSigs - 1
                mr_nonContOutputArray[%<idx>][%<arrayIdx>].next = %<SLibGetNullDefinitionFromTfl()>;
              %else
                %assign nextIdx = arrayIdx + 1
                mr_nonContOutputArray[%<idx>][%<arrayIdx>].next = ...
                  &(mr_nonContOutputArray[%<idx>][%<nextIdx>]);
              %endif
            %endif
          }
        %endforeach
      %endforeach
    %endif
  %endif
 
  %with ::CompiledModel.System[baseSysIdx]
  %<SLibDumpServicePortProvidersInit()>
  %endwith
   
  %closefile modelrefBuffer
  %return modelrefBuffer
%endfunction %%CallModelrefBlockRegFcns
 
%%Function:FcnGetChildCoderGroupDWorkPathFromSys
%%
%function FcnGetChildCoderGroupDWorkPathFromSys(modelBlock, blockInterface, instIdx, accSysIdx)
  %if !blockInterface.OkToMultiInstance
    %assign dworkPath = ""
  %elseif blockInterface.rtmAllocateInParent && ISFIELD(modelBlock, "ModelInstVarIndex") && modelBlock.ModelInstVarIndex > -1
    %assign selfVarGroupIdx = SLibGetSelfVarGroupIndexForModelBlock(modelBlock, instIdx)
    %assert selfVarGroupIdx > -1
    %assign selfCGTypeIdx = ::CompiledModel.VarGroups.VarGroup[selfVarGroupIdx].CGTypeIdx
    %if LibCGTypeIsMatrix(selfCGTypeIdx)
      %assign selfCGTypeIdx = LibCGTypeBaseIndex(selfCGTypeIdx)
    %endif
    %assign fldName = LibCGTypeMemberName(selfCGTypeIdx, modelBlock.ModelInstVarIndex)
    %assign vgPath = SLibCGIRVarGroupPath(selfVarGroupIdx, accSysIdx, TLC_FALSE)
    %assign dworkPath = vgPath + fldName
  %else
    %assign dworkCategory = FcnGetModelBlockDWorkCategory(modelBlock)
    %assign accSys = ::CompiledModel.System[accSysIdx]
    %assign varGroupIdx = FcnSysVarGroupIndex(accSys, dworkCategory, instIdx)
    %assert varGroupIdx > -1
    %assign varGroupPath = SLibCGIRVarGroupPath(varGroupIdx, accSysIdx, accSys.CrossNoArgFcnBound)
    %assign dworkIdx = SLibGetStructDWorkIdxForModelRefBlk(modelBlock)
    %assign dwRec = ::CompiledModel.DWorks.DWork[modelBlock.DWork[dworkIdx].FirstRootIdx]
    %assign dworkPath = varGroupPath + LibGetRecordIdentifier(dwRec)
  %endif
  %return dworkPath
%endfunction
 
%%Function:FcnGetChildCoderGroupDWorkPath======================================
%%Abstract:
%%Getdworkpathtousewithchildcodergroup
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function FcnGetChildCoderGroupDWorkPath(modelBlock, blockInterface, instIdx, isMdlblkInForEach) void
  %if !blockInterface.OkToMultiInstance
    %assign dworkPath = ""
  %elseif blockInterface.rtmAllocateInParent
    %if isMdlblkInForEach && ...
      ISFIELD(modelBlock, "ModelInstVarIndex") && (modelBlock.ModelInstVarIndex > -1)
      %assign selfVarGroupIdx = SLibGetSelfVarGroupIndexForModelBlock(modelBlock, instIdx)
      %assert selfVarGroupIdx > -1
      %assign selfCGTypeIdx = ::CompiledModel.VarGroups.VarGroup[selfVarGroupIdx].CGTypeIdx
      %if LibCGTypeIsMatrix(selfCGTypeIdx)
        %assign selfCGTypeIdx = LibCGTypeBaseIndex(selfCGTypeIdx)
      %endif
      %assign fldName = LibCGTypeMemberName(selfCGTypeIdx, modelBlock.ModelInstVarIndex)
      %assign vgPath = SLibCGIRVarGroupPath(selfVarGroupIdx, NumSystems-1, TLC_FALSE)
      %assign dworkPath = vgPath + fldName
    %elseif IsModelReferenceTarget() && ::CompiledModel.OkToMultiInstanceModelref
      %% The usage of the first instance modelBlock is OK here because
      %% all corresponding instances across parent reusable subsystems
      %% must have the same identifier
      %assign dworkPath = modelBlock.Identifier
    %else
      %assign dworkPath = SLibGetModelBlockStructDWorkArg( ...
        "", NumSystems-1, modelBlock, "RegistrationFcn", instIdx)
    %endif
  %else
    %assign dworkPath = SLibGetModelBlockStructDWorkArg( ...
      "", NumSystems-1, modelBlock, "RegistrationFcn", instIdx)
  %endif
  %return dworkPath
%endfunction
 
%%Function:FcnCoderGroupIndexMapKey=======================================
%%Abstract:
%%computethekeytothecodergroupindexmap
%function FcnCoderGroupIndexMapKey(mdlRefIdx) void
  %assign mdlRefBlks = ::CompiledModel.ModelReferenceBlocks
  %assign mdlRefInfo = mdlRefBlks[mdlRefIdx]
  %assign sysIdx = mdlRefInfo[0]
  %assign blkIdx = mdlRefInfo[1]
  %assign instIdx = mdlRefInfo[2]
  %if instIdx < 0
    %assign instIdx = 0
  %endif
  %return "B%<sysIdx>_%<blkIdx>_%<instIdx>"
%endfunction
   
%%Function:FcnAddToCoderGroupIndexMap=====================================
%%Abstract:
%%addanentrytotheCoderDataGroupIndexMapforamodelblock
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnAddToCoderGroupIndexMap(mdlRefIdx, childGroup, childGroupIndex, mappedCoderDataGroupIndex) void
  %assign mapKey1 = FcnCoderGroupIndexMapKey(mdlRefIdx)
  %if !ISFIELD(::CompiledModel.CoderDataGroupIndexMap, mapKey1)
    %addtorecord ::CompiledModel.CoderDataGroupIndexMap %<mapKey1> {}
  %endif
  %assign indexMapEntry = ::CompiledModel.CoderDataGroupIndexMap.%<mapKey1>
  %% If a group originating in this child model, the secondary key is Group#.
  %% Otherwise, it is ChildGroup#
  %if childGroup.Depth == 0
    %assign mapKey2 = "Group" + childGroupIndex
  %else
    %assign mapKey2 = "ChildGroup" + childGroupIndex
  %endif
  %createrecord mapValue {}
  %addtorecord mapValue CoderDataGroupIndex mappedCoderDataGroupIndex
  %addtorecord indexMapEntry %<mapKey2> %<mapValue>
  %undef mapValue
%endfunction
 
%%Function:FcnCoderGroupIndexMapValue=======================================
%%Abstract:
%%returnavaluefromthecodergroupindexmap
%function FcnCoderGroupIndexMapValue(mdlRefIdx, key) void
  %assign key1 = FcnCoderGroupIndexMapKey(mdlRefIdx)
  %assign value1 = ::CompiledModel.CoderDataGroupIndexMap.%<key1>
  %return value1.%<key>
%endfunction
   
 
%%Function:FcnGetCoderGroupSelfPath=================================
%%Abstract:
%%Computethepointerpathforachildcodergroup
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function FcnGetCoderGroupSelfPath(childGroup, blockInterface, dworkPath) void
  %if !blockInterface.OkToMultiInstance
    %assign pointerPath = childGroup.SelfPath
  %else
    %if blockInterface.rtmAllocateInParent
      %% self group has empty pointer path
      %if ISEMPTY(childGroup.SelfPath)
        %assign pointerPath = dworkPath
      %else
        %assign pointerPath = dworkPath + "." + childGroup.SelfPath
      %endif
    %else
      %if childGroup.Depth == 0
        %assign pointerPath = dworkPath + "." + childGroup.SelfPath
      %else
        %if ::isRAccel || ::isRSim
          %assign pointerPath = dworkPath + "." + childGroup.SelfPath
        %else
          %assign pointerPath = dworkPath + ".rtdw." + childGroup.SelfPath
        %endif
      %endif
    %endif
  %endif
  %return pointerPath
%endfunction
 
%%Function:FcnGetCoderGroupDynamicInitPath=============================
%%Abstract:
%%Computethedynamicinitpathforachildcodergroup
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function FcnGetCoderGroupDynamicInitPath(childGroup, modelBlock, blockInterface, dworkPath) void
  %if !blockInterface.OkToMultiInstance
    %assign dynamicInitPath = childGroup.SelfPath
  %else
    %if blockInterface.rtmAllocateInParent
      %% The usage of the first instance modelBlock is OK here because
      %% all corresponding instances across parent reusable subsystems
      %% must have the same identifier
      %assign dynamicInitPath = modelBlock.Identifier
    %else
      %if ::isRAccel || ::isRSim
        %assign dynamicInitPath = dworkPath
      %else
        %if SLibMultiInstance()
          %assign dynamicInitPath = "rtdw." + dworkPath
        %else
          %assign dynamicInitPath = dworkPath
        %endif
      %endif
    %endif
  %endif
  %return dynamicInitPath
%endfunction
 
%%FunctionFcnGetNameOfVarGroupElementForPCGD=============================
%%Abstract:
%%Computethenameofanelementinavargroupforasubmodel
%%
%function FcnGetNameOfVarGroupElementForPCGD(varGroupIdx, modelBlockIndex) void
  %assign numElement = SLibVarGroupNumElements(varGroupIdx)
  %foreach elemIdx = numElement
    %assign idnum = ...
      IDNUM(SLibVarGroupElementSource(varGroupIdx, elemIdx))
    %assign recType = idnum[0]
    %assign recIdx = idnum[1]
    %if recType == "PCDG" && ...
      (modelBlockIndex == recIdx)
      %return SLibVarGroupElementName(varGroupIdx, elemIdx)
    %endif
  %endforeach
  %% We can get here for self for encapsulated C++, which doesn't nest hierarchically
  %return ""
%endfunction
   
%%FunctionFcnGetCoderGroupPath===========================================
%%Abstract:
%%ComputetheGroupPathforachildcodergroup
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnGetCoderGroupPath(childGroup, modelBlock, modelBlockIndex, mdlblkInstIdx, isMdlBlkInForEach) void
 
  %% Multi-instance, InParent child group adds element name as determined
  %% by this model, who is its parent
  %if !childGroup.SingleInstancePropagator
    %if childGroup.AsStructure == "InParent"
      %assign isModelSingleInstance = !SLibMultiInstance()
      %assign actualGroup = childGroup
      %if isModelSingleInstance && ...
        childGroup.IsPolymorphic && ...
        childGroup.ImplementationType == "MultiInstance"
        %assign singleGroupIdx = SLibGetSingleInstanceGroupIdx(childGroup)
        %assign actualGroup = ::CompiledModel.CoderDataGroup[singleGroupIdx]
      %endif
      %if !isMdlBlkInForEach
        %assign varGroupIdx = SLibGetRootVarGroupIdxForCoderGroup(actualGroup)
      %else
        %assign blkSystem = ::CompiledModel.System[modelBlock.BlockIdx[0]]
        %assign varGroupIdx = FcnSysVarGroupIndex(blkSystem, "CoderDataGroup" + actualGroup.Name, mdlblkInstIdx)
        %assert varGroupIdx > -1
      %endif
       
      %% self can fail to be present in this model even though in child model
      %% in which case varGroupIdx = -1
      %if varGroupIdx < 0
        %% The usage of the first instance modelBlock is OK here because
        %% all corresponding instances across parent reusable subsystems
        %% must have the same identifier
        %assign groupPath = modelBlock.Identifier
        %if !ISEMPTY(childGroup.GroupPath)
          %assign groupPath = groupPath + "_" + childGroup.GroupPath
        %endif
 
        %% Otherwise we have a parent vargroup in this model at the root level
      %else
        %assign groupPath = FcnGetNameOfVarGroupElementForPCGD(varGroupIdx, modelBlockIndex)
        %if !ISEMPTY(childGroup.GroupPath)
          %assign groupPath = groupPath + "." + childGroup.GroupPath
        %endif
        %% If the current model is single instance, and the child group is
        %% propagated from a multi-instance model so that we are now
        %% transitioning from a multi-instance portion of a model hierarchy
        %% to single instance, add the varGroups's root instance because its
        %% a lot easier to find it here than from the context of a parent model
        %% Exception: skip if InParent is implemented as unstructured in top model.
        %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
        %if isModelSingleInstance && varGroup.PackageAsStruct && !isMdlBlkInForEach
          %assign structInstance = ISFIELD(varGroup, "StructureInstanceName") ? ...
            varGroup.StructureInstanceName : varGroup.SelfStructureInstanceName
          %assign groupPath = structInstance + "." + groupPath
        %endif
      %endif
       
    %else
     
      %% The usage of the first instance modelBlock is OK here because
      %% all corresponding instances across parent reusable subsystems
      %% must have the same identifier
      %if childGroup.IsSelf
        %assign groupPath = modelBlock.Identifier
        %% Now, multi-instance Standalone or InSelf
      %else
        %assign groupPath = modelBlock.Identifier + "_" + childGroup.GroupPath
      %endif
    %endif
     
  %% Single-instance propagator - remains unchanged
  %else
    %assign groupPath = childGroup.GroupPath
  %endif
   
  %return groupPath
%endfunction
 
%function FcnAdjustChildGroupPathForForEach(childGroupPath, parentGroup, mdlBlk, mdlblkInstIdx)
  %assign blkSys = ::CompiledModel.System[mdlBlk.BlockIdx[0]]
  %assign groupVGName = "CoderDataGroup" + parentGroup.Name
  %assign parentVGIdx = FcnSysVarGroupIndex(blkSys, groupVGName, mdlblkInstIdx)
  %if parentVGIdx > -1
    %assign childGroupPath = ...
      SLibCGIRVarGroupPath(parentVGIdx, GetBaseSystemIdx(), blkSys.CrossNoArgFcnBound) + childGroupPath
  %endif
  %return childGroupPath
%endfunction
 
%function FcnAdjustChildGroupPathForMultiInst(childGroupPath, parentGroup, mdlBlk)
  %assign childGroupPath = ...
    SLibGetCoderDataGroupPointerFromRTM(parentGroup, 0) + "->" + childGroupPath
  %return childGroupPath
%endfunction
 
%%FunctionFcnGenerateGroupInstance============================================
%%Abstract:
%%Dowegenerateaninstanceforthegroup?
%function FcnGenerateGroupInstance(childGroup) void
  %assign generateGroupInstance = TLC_FALSE
 
  %if !childGroup.IsImportedFromFile
    %if childGroup.AsStructure == "InParent"
      %assign isSelfGroup = SLibGetSelfCoderDataGroupIndex() > -1 && ...
        childGroup.Name == ::CompiledModel.CoderDataGroup[SLibGetSelfCoderDataGroupIndex()].Name
      %if childGroup.ContainsInstanceSpecificParameter
        %assign generateGroupInstance = !IsModelReferenceTarget()
      %elseif !isSelfGroup
        %assign generateGroupInstance = childGroup.Depth == 0
      %endif
    %elseif childGroup.AsStructure == "InSelf"
      %% InstP in order to provide initialization from the top
      %if childGroup.ContainsInstanceSpecificParameter
        %if Accelerator
          %assign generateGroupInstance = (childGroup.Depth == 0)
        %elseif ::isRAccel || ::isRSim
          %assign generateGroupInstance = childGroup.SingleInstanceDefiner
        %else
          %assign generateGroupInstance = TLC_TRUE
        %endif
      %endif
    %else
      %assign generateGroupInstance = TLC_TRUE
    %endif
  %endif
  %return generateGroupInstance
%endfunction
 
%%Function:FcnCopyInstPForSimTargets=========================================
%%Abstract:
%%Copyinstance-specificparametervaluesforsimtargets
%function FcnCopyInstPForSimTargets(dynamicInitializer) void
  %assign fieldNames = FIELDNAMES(dynamicInitializer)
  %assign numElements = SIZE(fieldNames, 1)
  %foreach eIdx = numElements
    %assign fieldName = fieldNames[eIdx]
    %assign idNum = IDNUM(fieldName)
    %if idNum[0] == "P"
      %assign dst = dynamicInitializer.%<fieldName>
      %assign mdlParam = ::CompiledModel.ModelParameters.Parameter[idNum[1]]
      %assign src = LibModelParameterAddr(mdlParam, "", "", 0)
      %assign sizeof = "sizeof(" + dst + ")"
      %assign memcpy = "(void) " + ...
        LibGenMemFcnCall("memcpy", "&(" + dst + ")", src, sizeof) + ";/n"
      %if ::isRAccel || Accelerator
        %assign ::CompiledModel.ChildCoderDataGroupAssignmentForRegistration = ...
          ::CompiledModel.ChildCoderDataGroupAssignmentForRegistration + memcpy
        %if !mdlParam.HasDescendantParamWrite
          %assign ::CompiledModel.ChildCoderDataGroupAssignmentForParamTs = ...
            ::CompiledModel.ChildCoderDataGroupAssignmentForParamTs + memcpy
        %endif
      %else
        %assert ::isRSim
        %<LibMdlStartCustomCode(memcpy, "execution")>
      %endif
    %endif
  %endforeach
%endfunction
 
%%Function:FcnAssignCoderGroupsInNonAllocators==================================
%%Abstract:
%%AssignselfpointersforcodergroupsinmiddlemodelswithAsStructure=InParent
%function FcnAssignCoderGroupsInNonAllocators(childGroup, modelBlock, instIdx, blockInterface, isMdlblkInForEach, groupPath, selfPath) void
  %assign localStructAccess = ""
  %if IsModelReferenceTarget()
    %if !::CompiledModel.OkToMultiInstanceModelref
      %assign localStructAccess = ""
    %elseif blockInterface.rtmAllocateInParent
      %if isMdlblkInForEach
        %% In this case, selfPath starts from root, so local access starts with ::tSimStruct
        %assign localStructAccess = ::tSimStruct + "->"
      %else
        %% When using self vargroup (rtmAllocateInParent), model block may be nested to subsystem self,
        %% whereas selfPath only contains the model block's path.
        %% In this case, local access needs to build up the path from root to model block.
        %assign localStructAccess = SLibGetPathToSimplifiedInterfaceModelBlock(modelBlock, instIdx)
      %endif
    %else
      %% The usage of the first instance modelBlock is OK here because
      %% all corresponding instances across parent reusable subsystems
      %% must have the same root
      %assign localStructAccess = SLibGetModelBlockVarGroupRoot(modelBlock)
    %endif
  %endif
  %% The usage of the first instance modelBlock is OK here because
  %% all corresponding instances across parent reusable subsystems
  %% must have the same name and condition
  %assign comment = "/* Assign pointer for %<childGroup.Identification>, Block: '%<modelBlock.Name>' *//n"
  %assign condition = SLibMdlRefSystemPreprocessorCondition(modelBlock)
  %assign ppIf = ""
  %assign ppEndif = ""
  %if !ISEMPTY(condition)
    %assign ppIf = "#if " + condition + "/n"
    %assign ppEndif = "#endif/n"
  %endif
  %assign guardedInitStmt = ppIf + comment + ...
      "%<localStructAccess>%<selfPath> = &%<groupPath>;/n" + ppEndif
  %assign ::CompiledModel.ChildCoderDataGroupAssignmentForParamTs = ...
      ::CompiledModel.ChildCoderDataGroupAssignmentForParamTs + guardedInitStmt
  %if !isMdlblkInForEach
    %assign ::CompiledModel.ChildCoderDataGroupAssignmentForRegistration = ...
      ::CompiledModel.ChildCoderDataGroupAssignmentForRegistration + guardedInitStmt
  %else
    %assign ::childGroupInitsInForEach = ::childGroupInitsInForEach + guardedInitStmt
  %endif
%endfunction
 
%%Function:FcnDeclareChildCoderGroups===============================================
%%Abstract:
%%declareanddefinechildcodergroups
%function FcnDeclareChildCoderGroups(childGroup, blockInterface, groupPath, initializer) void
  %if !WHITE_SPACE(initializer)
    %assign initializer = " = " + initializer
  %endif
  %if !ISEMPTY(childGroup.Type) && !ISEMPTY(groupPath)
    %assign comment = "/* Define buffer for %<childGroup.Identification>, Block: '%<Name>' *//n"
    %assign definition = "%<childGroup.Type> %<groupPath>%<initializer>;/n"
    %assign definition = comment + ...
      SLibApplyMemSecToDataDefnForGroup(definition, childGroup, groupPath, ::CompiledModel.ConfigSet, TLC_TRUE)
    %if ISEMPTY(childGroup.SingleInstanceDefinitionFileRule)
      %<SLibCacheCodeToFile("mdldata_data_defn", definition)>
    %else
      %assign defnFileNameRule = SLibGetFileNameWithoutExtension(childGroup.SingleInstanceDefinitionFileRule)
      %assign defnFileName = FEVAL("slInternal", "getCodePreviewUsingNamingService", ::CompiledModel.Name, defnFileNameRule, ::CompiledModel.Name, childGroup.UserProvidedName, ::CompiledModel.ConfigSet.CustomUserTokenString)
      %assign defnFile = SLibAddModelFile("SystemBody", "Simulink", defnFileName)
      %<SLibSetModelFileAttribute(defnFile, "Group", "data")>
      %assign declHdr = childGroup.SingleInstanceHeaderFile
      %if !ISEMPTY(declHdr)
        %<SLibSetModelFileAttribute(defnFile, "RequiredIncludes", declHdr + ".h")>
      %endif
      %<SLibSetModelFileAttribute(defnFile, "Definitions", definition)>
    %endif
    %assign comment = "/* Declare buffer for %<childGroup.Identification>, Block: '%<Name>' *//n"
    %assign declaration = "%<childGroup.Type> %<groupPath>;/n"
    %assign declaration = comment + ...
      SLibApplyMemSecToDataDeclForGroup(declaration, childGroup, groupPath, ::CompiledModel.ConfigSet, TLC_TRUE)
    %<SLibCacheCodeToFile("mdl_priv_data_define", declaration)>
  %endif
%endfunction
 
%%Function:FcnAssignCoderGroupsInAllocators==================================
%%Abstract:
%%AssignselfpointersforcodergroupsinallocatingmodelswithAsStructure=InParent
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnAssignCoderGroupsInAllocators(childGroup, modelBlock, isMdlblkInForEach, groupPath, selfPath) void
  %% The usage of the first instance modelBlock is OK here because
  %% all corresponding instances across parent reusable subsystems
  %% must have the same name and condition
  %assign comment = "/* Assign pointer for %<childGroup.Identification>, Block: '%<modelBlock.Name>' *//n"
  %assign condition = SLibMdlRefSystemPreprocessorCondition(modelBlock)
  %assign ppIf = ""
  %assign ppEndif = ""
  %if !ISEMPTY(condition)
    %assign ppIf = "#if " + condition + "/n"
    %assign ppEndif = "#endif/n"
  %endif
  %if childGroup.AsStructure == "InSelf"
    %assign sizeof = "sizeof(" + childGroup.Type + ")"
    %assign memcpy = "(void) " + ...
      LibGenMemFcnCall("memcpy", "&(" + selfPath + ")", "&(" + groupPath + ")", sizeof) + ";/n"
    %assign ::CompiledModel.ChildCoderDataGroupMemcpy = ...
      ::CompiledModel.ChildCoderDataGroupMemcpy + ppIf + comment + memcpy + ppEndif
    %% Self is directly embededed instead of via reference
  %elseif ((childGroup.Depth == 0) && (childGroup.AsStructure == "InParent")) || ...
    (childGroup.AsStructure == "Standalone")
    %assign guardedInitStmt = ppIf + comment + ...
      "%<selfPath> = &%<groupPath>;/n" + ppEndif
    %assign ::CompiledModel.ChildCoderDataGroupAssignmentForParamTs = ...
      ::CompiledModel.ChildCoderDataGroupAssignmentForParamTs + guardedInitStmt
    %if !isMdlblkInForEach
      %assign ::CompiledModel.ChildCoderDataGroupAssignmentForRegistration = ...
        ::CompiledModel.ChildCoderDataGroupAssignmentForRegistration + guardedInitStmt
    %else
      %assign ::childGroupInitsInForEach = ::childGroupInitsInForEach + guardedInitStmt
    %endif
  %endif
%endfunction
 
%%Function:FcnAssignHSAutosarCoderGroupsInAllocators==================================
%%Abstract:
%%AssignselfpointersforcodergroupsforAutosarPerInstanceMemoryandPerInstanceParameterinallocation
%function FcnAssignHSAutosarCoderGroupsInAllocators(childGroup, modelBlock, groupPath, selfPath) void
  %% The usage of the first instance modelBlock is OK here because
  %% all corresponding instances across parent reusable subsystems
  %% must have the same name
  %assign comment = "/* Assign pointer for %<childGroup.Identification>, Block: '%<modelBlock.Name>' *//n"
  %assign arg = ""
  %if MultiInstanceERTCode
    %assign arg = FcnGetMultiInstanceRunnableArgs(TLC_TRUE)
  %endif
  %assign rteCall = "Rte_"
  %if SLibIsAutosarPIMCoderGroup(childGroup)
    %assign rteCall = "Rte_Pim_"
  %elseif SLibIsAutosarInstPCoderGroup(childGroup)
    %assign rteCall = "Rte_CData_"
  %endif
  %assign ::CompiledModel.ChildCoderDataGroupAssignmentForRegistration = ...
    ::CompiledModel.ChildCoderDataGroupAssignmentForRegistration + comment + ...
    "%<selfPath> = %<rteCall>%<groupPath>(%<arg>);/n"
  %assign ::CompiledModel.ChildCoderDataGroupAssignmentForParamTs = ...
    ::CompiledModel.ChildCoderDataGroupAssignmentForParamTs + comment + ...
    "%<selfPath> = %<rteCall>%<groupPath>(%<arg>);/n"
%endfunction
 
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall3.m
%%
%function FcnGetCoderGroupSelfPointerInit(group)
  %% Promote to static if inparent or inself and self is static
  %if SLibAccessGroupThroughSelf(group)
    %if SLibHasSelfWithStaticInit()
      %return "Static"
    %else
      %return "Dynamic"
    %endif
  %else
    %return group.DataInit
  %endif
%endfunction
 
%%Doweneedtodynamicallyassignthiscodergrouppointerintheself?
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnAssignCoderGroup(childGroup) void
  %return !::isRAccel && !Accelerator && ...
    !GenerateClassInterface && ...
    !childGroup.SingleInstanceDefiner && ...
    (!SLibIsSelfImported() ||...
    SLibIsAutosarInstPCoderGroup(childGroup))&& ...
    (childGroup.AsStructure != "None") && ...
    (childGroup.SelfPointerInit == "Dynamic") && ...
    !childGroup.IsSelf
%endfunction
 
%function FcnGetSingleInstanceType(childGroup, singleInstancePropagator) void
  %if singleInstancePropagator && !childGroup.SingleInstancePropagator
    %assign groupIndex = SLibCoderDataGroupIndex(childGroup.Name)
    %% groupIndex can be negative if child group is _self and this model
    %% has no _self
    %if groupIndex >= 0
      %return SLibCoderDataGroupType(::CompiledModel.CoderDataGroup[groupIndex])
    %else
      %return ""
    %endif
  %else
    %return childGroup.SingleInstanceType
  %endif
%endfunction
   
%%Getindexofparentgroupinthismodel
%function FcnGetParentGroupIndex(childGroup) void
  %assign switchToSingleInstGroup = ...
    !SLibMultiInstance() && ...
    childGroup.IsPolymorphic && ...
    childGroup.ImplementationType == "MultiInstance"
  %if switchToSingleInstGroup
    %return SLibGetSingleInstanceGroupIdx(childGroup)
  %else
    %return SLibCoderDataGroupIndex(childGroup.Name)
  %endif
%endfunction
 
%function SetupForEachLoopVariablesForChildGroupInit(mdlBlk) void
  %assert ISFIELD(mdlBlk, "ForEachSSLoopBnds")
  %<CacheForEachLoopVariablesForChildGroupInit()>
  %assign ::NeedForEachLoopInReg = TLC_TRUE
  %assign ::NumForEachLoopHierarchyLevel = SIZE(mdlBlk.ForEachSSLoopBnds, 1)
  %assign ::ForEachLoopHierarchyLevel = 1 %% Init code is always inside the innermost loop
  %assign ::childGroupInitsInForEach = ""
 
  %openfile ::loopStartBuf
  %assign iterVar = "i_%<ForEachLoopHierarchyLevel>"
  int32_T %<iterVar>;
  for (%<iterVar> = 0; %<iterVar> < %; %<iterVar>++) {
  %closefile ::loopStartBuf
  %openfile ::loopEndBuf
  }
  %closefile ::loopEndBuf
%endfunction
 
%function CacheForEachLoopVariablesForChildGroupInit() void
  %assert !EXISTS(::NeedForEachLoopInReg)
  %assert !EXISTS(::NumForEachLoopHierarchyLevel)
  %assert !EXISTS(::ForEachLoopHierarchyLevel)
  %% %assign ::NeedForEachLoopInRegPrev = ::NeedForEachLoopInReg
  %% %assign ::NumForEachLoopHierarchyLevelPrev = ::NumForEachLoopHierarchyLevel
  %% %assign ::ForEachLoopHierarchyLevelPrev = ::ForEachLoopHierarchyLevel
%endfunction
 
%function RestoreForEachLoopVariablesForChildGroupInit() void
  %undef ::NeedForEachLoopInReg
  %undef ::NumForEachLoopHierarchyLevel
  %undef ::ForEachLoopHierarchyLevel
  %undef ::childGroupInitsInForEach
  %undef ::loopStartBuf
  %undef ::loopEndBuf
  %% %assign ::NeedForEachLoopInReg = ::NeedForEachLoopInRegPrev
  %% %assign ::NumForEachLoopHierarchyLevel = ::NumForEachLoopHierarchyLevelPrev
  %% %assign ::ForEachLoopHierarchyLevel = ::ForEachLoopHierarchyLevelPrev
%endfunction
 
%%Function:FcnProcessChildCoderGroups=========================================
%%Abstract:
%%Processchildcodergroups
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnProcessChildCoderGroups() void
  %assign mdlRefBlks = ISFIELD(::CompiledModel,"ModelReferenceBlocks") ? ...
    ::CompiledModel.ModelReferenceBlocks : []
  %if ISEMPTY(mdlRefBlks)
    %return
  %endif
  %assign baseSysIdx = GetBaseSystemIdx()
 
  %assign childCoderDataGroupIndex = 0
  %assign ::CompiledModel.ChildCoderDataGroupAssignmentForRegistration = ""
  %assign ::CompiledModel.ChildCoderDataGroupAssignmentForParamTs = ""
  %assign ::CompiledModel.ChildCoderDataGroupMemcpy = ""
  %assign ancestorAllocatesCoderDataGroups = ::CompiledModel.AncestorAllocatesCoderDataGroups
  %addtorecord ::CompiledModel CoderDataGroupIndexMap {}
  %with System[baseSysIdx]
    %assign mdlBlkIdx = 0
 
    %% Loop over all the model blocks ...
    %foreach rowIdx = SIZE(mdlRefBlks,0)
      %assign mSysIdx = mdlRefBlks[rowIdx][0]
      %assign bIdx = mdlRefBlks[rowIdx][1]
      %assign instIdx = mdlRefBlks[rowIdx][2]
      %with ::CompiledModel.System[mSysIdx].Block[bIdx]
        %assign blk = ::CompiledModel.System[mSysIdx].Block[bIdx]
         
        %% If the model block is in SIL mode, we don't propagate its
        %% coder groups up for accelerator or model ref sim target
        %if ParamSettings.XILCodeInterface != "None" && ...
          (Accelerator || isRAccel || IsModelReferenceSimTarget())
          %continue
        %endif
         
        %% The usage of the first instance modelBlock is OK here because
        %% all corresponding instances across parent reusable subsystems
        %% must have a consistent state
        %assert 0 == blk.DeletedInIR
        %% The usage of the first instance modelBlock is OK here because
        %% all corresponding instances across parent reusable subsystems
        %% must have a consistent interface
        %assign blockInterface = GetModelrefInterface(blk)
 
        %% If the model block propagates child code groups ...
        %if ISFIELD(blockInterface, "CoderDataGroups") && ...
          !ISEMPTY(blockInterface.CoderDataGroups)
          %assign childGroups = blockInterface.CoderDataGroups.CoderDataGroup
          %assign numChildGroups = SIZE(childGroups, 1)
 
          %assign mdlBlkRec = ::CompiledModel.ModelBlock[rowIdx]
          %assign isMdlblkInForEach = ISFIELD(mdlBlkRec, "ForEachSSLoopBnds")
          %if isMdlblkInForEach
            %<SetupForEachLoopVariablesForChildGroupInit(mdlBlkRec)>
          %endif
 
          %% The usage of the first instance modelBlock is OK here because
          %% we pass in the parent subsystem instance index
          %assign dworkPath = FcnGetChildCoderGroupDWorkPath(blk, blockInterface, instIdx, isMdlblkInForEach)
 
          %% Establish codergroup mapping from index in child model to index in this model
          %assign mappedCoderDataGroupIndex = childCoderDataGroupIndex
 
 
          %% Loop over each child group
          %foreach gIdx = numChildGroups
            %assign childGroup = blockInterface.CoderDataGroups.CoderDataGroup[gIdx]
            %assign previousChildGroupIndex = STRING(CAST("Number", childGroup.CoderDataGroupIndex))
            %<FcnAddToCoderGroupIndexMap(rowIdx, childGroup, previousChildGroupIndex, mappedCoderDataGroupIndex)>
 
            %% Keep track of whether an ancestor allocates coder groups for this model,
            %% since that breaks incremental build.
            %if !SLibAllocatesCoderDataGroup(childGroup)
              %assign ::CompiledModel.AncestorAllocatesCoderDataGroups = TLC_TRUE
            %endif
 
            %% Assign paths since we'll need them in the second loop below where we
            %% adjust initializers
            %assign selfPath = ...
              FcnGetCoderGroupSelfPath(childGroup, blockInterface, dworkPath)
            %% The usage of the first instance modelBlock is OK here because
            %% we pass in the rowIdx which is instance-specific
            %assign childGroupPath = FcnGetCoderGroupPath(childGroup, blk, rowIdx, instIdx, isMdlblkInForEach)
            %assign selfPointerInit = FcnGetCoderGroupSelfPointerInit(childGroup)
            %assign grBlkIndex = [ %, % ]
            %assign graphicalPath = ISEMPTY(childGroup.GraphicalPath) ? ...
              SLibGrBlockCommentName(grBlkIndex) : ...
              SLibGrBlockCommentName(grBlkIndex) + "/" + childGroup.GraphicalPath
            %assign singleInstancePropagator = !SLibMultiInstance()
            %assign singleInstanceType = FcnGetSingleInstanceType(childGroup, singleInstancePropagator)
            %assign sid = STRING(rowIdx) + "_" + STRING(gIdx) + "_" + childGroup.SID
            %assign vcOnMdlBlk = SLibMdlRefSystemPreprocessorCondition(blk)
            %% Create the child data group records
            %addtorecord ::CompiledModel.CoderDataGroups CoderDataGroup { /
            Name childGroup.Name /
            UserProvidedName childGroup.UserProvidedName /
            Description childGroup.Description /
            Identification childGroup.Identification /
            Type childGroup.Type /
            Depth childGroup.Depth+1 /
            SelfPath selfPath /
            GroupPath childGroupPath /
            GraphicalPath graphicalPath /
            SID sid /
            DataInit childGroup.DataInit /
            SelfPointerInit selfPointerInit /
            SingleInstanceDefiner childGroup.SingleInstanceDefiner /
            SingleInstancePropagator singleInstancePropagator /
            SingleInstanceType singleInstanceType /
            IsInstanceSpecific childGroup.IsInstanceSpecific /
            IsSelf childGroup.IsSelf /
            IsSynthesized childGroup.IsSynthesized /
            SynthesizedNamePrefix childGroup.SynthesizedNamePrefix /
            SingleInstanceHeaderFile childGroup.SingleInstanceHeaderFile /
            SingleInstanceDefinitionFileRule childGroup.SingleInstanceDefinitionFileRule /
            IsOpaque childGroup.IsOpaque /
            IsPolymorphic childGroup.IsPolymorphic /
            ImplementationType childGroup.ImplementationType /
            IsMemorySectionConst childGroup.IsMemorySectionConst /
            IsMemorySectionVolatile childGroup.IsMemorySectionVolatile /
            MemorySectionQualifier childGroup.MemorySectionQualifier /
            MemorySection childGroup.MemorySection /
            MemorySectionIsLegacy childGroup.MemorySectionIsLegacy /
            IsImportedFromFile childGroup.IsImportedFromFile /
            AsStructure childGroup.AsStructure /
            CompiledModelBlockIndex rowIdx /
            IndexInBlockInterface gIdx /
            NetVariantCondition vcOnMdlBlk /
            CoderDataGroupIndex mappedCoderDataGroupIndex /
            ContainsInstanceSpecificParameter childGroup.ContainsInstanceSpecificParameter /
            HasAccessMethod childGroup.HasAccessMethod /
            IsDataTransferGroup childGroup.IsDataTransferGroup /
            GroupContains childGroup.GroupContains /
            }
 
            %if isMdlblkInForEach
              %addtorecord ::CompiledModel.CoderGroupInitLoop CoderDataGroupInitLoop { /
                LoopStart ::loopStartBuf /
                LoopEnd ::loopEndBuf /
              }
            %else
              %addtorecord ::CompiledModel.CoderGroupInitLoop CoderDataGroupInitLoop { /
                LoopStart "" /
                LoopEnd "" /
              }
            %endif
 
            %% Add to the child group map
            %assign key = "CG" + sid
            %if ISFIELD(::CompiledModel.ChildGroupMap, key)
              %<LibReportFatalError("duplicate map entries")>
            %endif
            %addtorecord ::CompiledModel.ChildGroupMap %<key> ::CompiledModel.CoderDataGroups.CoderDataGroup[mappedCoderDataGroupIndex]
            %assign mappedCoderDataGroupIndex = mappedCoderDataGroupIndex + 1
          %endforeach
 
          %% Now set up all static and dynamic initializers, which can cross reference
          %% other groups - that's why we had to do this in two separate loops
          %assign mappedCoderDataGroupIndex = childCoderDataGroupIndex
 
          %% Loop over each group
          %foreach gIdx = numChildGroups
 
            %assign childGroup = blockInterface.CoderDataGroups.CoderDataGroup[gIdx]
            %assign childGroupPath = ::CompiledModel.CoderDataGroups.CoderDataGroup[mappedCoderDataGroupIndex].GroupPath
            %assign childSelfPath = ::CompiledModel.CoderDataGroups.CoderDataGroup[mappedCoderDataGroupIndex].SelfPath
            %assign sid = ::CompiledModel.CoderDataGroups.CoderDataGroup[mappedCoderDataGroupIndex].SID
            %% The usage of the first instance modelBlock is OK here because
            %% we pass in the dworkPath which is instance-specific
            %assign dynamicInitPath = ...
              FcnGetCoderGroupDynamicInitPath(childGroup, blk, blockInterface, dworkPath)
            %% If we're allocating the group, or if a top-model multi-instance build,
            %% create group allocation and definition buffers
            %if SLibAllocatesCoderDataGroup(childGroup) || ...
              (!IsModelReferenceTarget() && MultiInstanceERTCode)
               
              %% Adjust the initializers to the context of this parent model
              %assign adjustedInitializer = FcnAdjustInitializer(childGroup.Initializer, rowIdx)
              %assign dynamicInitializer = FcnAdjustDynamicInitializer(childGroup, rowIdx, blockInterface, dynamicInitPath, childGroupPath, sid)
              %% Emit the initializer since we're allocating groups
              %assign initializer = FcnEmitInitializer(adjustedInitializer)
               
              %% Declare child groups that are in-self, or single instance
              %if childGroup.AsStructure != "InParent" || childGroup.SingleInstanceDefiner
                %% We only allocate and declare data in some cases
                %if FcnGenerateGroupInstance(childGroup)
                  %<FcnDeclareChildCoderGroups(childGroup, blockInterface, childGroupPath, initializer)>
                %endif
                %% Otherwise, put finishing touches on childGroupPath
              %else
                %% Parent group may not be present if child creates _self but
                %% parent does not. In that case, leave childGroupPath alone.
                %assign parentGroupIndex = FcnGetParentGroupIndex(childGroup)
                %if parentGroupIndex >= 0
                  %assign parentGroup = ::CompiledModel.CoderDataGroup[parentGroupIndex]
                  %if SLibCoderGroupPackageAsStruct(parentGroup)
                    %if isMdlblkInForEach
                      %assign childGroupPath = ...
                        FcnAdjustChildGroupPathForForEach(childGroupPath, parentGroup, blk, instIdx)
                    %elseif MultiInstanceERTCode
                      %assign childGroupPath = ...
                        FcnAdjustChildGroupPathForMultiInst(childGroupPath, parentGroup, blk)
                    %endif
                  %endif
                %endif
              %endif
 
              %% Create coder group assignment buffers
              %if FcnAssignCoderGroup(childGroup)
                %if (SLibIsAutosarPIMCoderGroup(childGroup) || SLibIsAutosarInstPCoderGroup(childGroup))
                  %% The usage of the first instance modelBlock is OK here
                  %% because the routine doesn't need instance-specific info
                  %<FcnAssignHSAutosarCoderGroupsInAllocators(childGroup, blk, childGroupPath, childSelfPath)>
                %else
                  %% The usage of the first instance modelBlock is OK here
                  %% because the routine doesn't need instance-specific info
                  %<FcnAssignCoderGroupsInAllocators(childGroup, blk, isMdlblkInForEach, childGroupPath, childSelfPath)>
                %endif
              %endif
 
              %% Copy instance-specific parameter values for sim targets
              %if ::isRAccel || Accelerator || ::isRSim
                %<FcnCopyInstPForSimTargets(dynamicInitializer)>
              %endif
 
            %% if we don't allocate or declare the childGroup, we still need to
            %% adjust the initializer to the context of this parent model
            %% as well as initialize pointers for submodel's InParent groups
            %else
              %assign initializer = FcnAdjustInitializer(childGroup.Initializer, rowIdx)
              %assign dynamicInitializer = FcnAdjustDynamicInitializer(childGroup, rowIdx, blockInterface, dynamicInitPath, childGroupPath, sid)
              %% Create coder group assignment buffers
              %if FcnAssignCoderGroup(childGroup) && ...
                (childGroup.AsStructure == "InParent") && ...
                (childGroup.Depth == 0)
                %assign parentGroupIndex = FcnGetParentGroupIndex(childGroup)
                %assign parentGroup = ::CompiledModel.CoderDataGroup[parentGroupIndex]
                %if isMdlblkInForEach
                  %assign childGroupPath = ...
                    FcnAdjustChildGroupPathForForEach(childGroupPath, parentGroup, blk, instIdx)
                %elseif SLibMultiInstance()
                  %assign childGroupPath = ...
                    FcnAdjustChildGroupPathForMultiInst(childGroupPath, parentGroup, blk)
                %endif
                %<FcnAssignCoderGroupsInNonAllocators(childGroup, blk, instIdx, blockInterface, isMdlblkInForEach, childGroupPath, childSelfPath)>
              %endif
            %endif
             
            %% Add the static and dynamic initializers to the child coder group record.
            %addtorecord ::CompiledModel.CoderDataGroups.CoderDataGroup[mappedCoderDataGroupIndex] Initializer initializer
            %addtorecord ::CompiledModel.CoderDataGroups.CoderDataGroup[mappedCoderDataGroupIndex] DynamicInitializer dynamicInitializer
                
            %assign mappedCoderDataGroupIndex = mappedCoderDataGroupIndex + 1
          %endforeach
          %assign childCoderDataGroupIndex = childCoderDataGroupIndex + numChildGroups
          %if isMdlblkInForEach
            %if !ISEMPTY(::childGroupInitsInForEach)
              %assign mdlrefKey = FcnCoderGroupIndexMapKey(rowIdx)
              %addtorecord ::CompiledModel.ChildGroupInitInForEachMap %<mdlrefKey> ::childGroupInitsInForEach
            %endif
            %<RestoreForEachLoopVariablesForChildGroupInit()>
          %endif
        %endif
      %endwith
    %endforeach
  %endwith
 
%endfunction %%FcnProcessChildCoderGroups
 
%%Function:GetNonContAddress================================================
%%Abstract:
%%Returnstheaddressofthesignalwhichisusedtotrackanoncontinuous
%%signalfeedinganintegrator.
%function GetNonContAddress(du, ss)
  %assign sigSrc = du.SigSrc
  %assign startEl = du.StartEl
  %assign regLen = du.RegionLen
  %assign idNum = IDNUM(sigSrc)
  %%
  %switch idNum[0]
      %% Note: no need for "u" because the top model will
      %% check for the reset in this case.
    %case "y"
      %assign opIdx = idNum[1]
      %assign interface = ss.Interface
      %assign canOutputArg = interface.CanonicalOutputArgDef[opIdx]
      %assign name = LibGetRecordIdentifier(canOutputArg)
      %assign addr = "&%<name>[%<startEl>]"
      %<SLibAccessArgHelper(canOutputArg,"",ss.CurrentTID)>
      %break
    %default
      %assign bo = BlockOutputs.GlobalBlockOutput[idNum[1]]
      %assert (bo.Invariant == "no")
      %assert (LibGetRecordWidth(bo) >= regLen + startEl)
      %assign cross = System[bo.SigSrc[0]].CrossNoArgFcnBound
      %assign name = SLibCG_GetVarGroupElementPath(bo.VarGroupIdx, ...
        ss.SystemIdx, cross)
      %assign opW = (LibGetRecordWidth(bo) == 1) ? "" : "[%<startEl>]"
      %assign addr = "&%<name>%<opW>"
      %break
  %endswitch
  %return addr
%endfunction
 
 
%%Function:CallModelrefBlockFreeFullPaths===================================
%%Abstract:
%%CallrtwCAPI_SetFreeFullPaths
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function CallModelrefBlockFreeFullPaths(mdlRefBlks)
  %openfile modelrefBuffer
  %if ::CompiledModel.RTWStatesLogging && !IsModelReferenceTarget() && ...
    HasModelReferenceBlocks()
    %assign baseSysIdx = GetBaseSystemIdx()
    %with System[baseSysIdx]
      %if ::NumModelBlocksWithCAPI > 0
        %assign mdlBlkIdx = 0
        %foreach rowIdx = SIZE(mdlRefBlks,0)
          %% This does a deep dive so we only want to do it
          %% for the top (note: the engine takes care of this in sim)
          %assign mdlRefInfo = mdlRefBlks[rowIdx]
          %assign mSysIdx = mdlRefInfo[0]
          %assign bIdx = mdlRefInfo[1]
          %assign instIdx = mdlRefInfo[2]
          %assign blk = ::CompiledModel.System[mSysIdx].Block[bIdx]
          %% The usage of the first instance modelBlock is OK here because
          %% all corresponding instances across parent reusable subsystems
          %% must have a consistent state
          %assert 0 == blk.DeletedInIR
          %if !blk.ParamSettings.SupportsCAPI
            %continue
          %endif
           
          %if GenRTModel
            %assign rtm_mmi = "&(%<RTMGet("DataMapInfo")>.mmi)"
          %else
            %assign rtm_mmi = "&(%<RSimRTWCAPIVarPtr>->mmi)"
          %endif
          %assign childMMI = "rtwCAPI_GetChildMMI(%<rtm_mmi>,%<mdlBlkIdx>)"
          rtwCAPI_FreeFullPaths((%<childMMI>));
          %assign mdlBlkIdx = mdlBlkIdx + 1
        %endforeach
      %endif
    %endwith
  %endif
  %closefile modelrefBuffer
  %return modelrefBuffer
%endfunction %%CallModelrefBlockFreePath
 
 
%%=============================================================================
%%
%function ModelrefCacheVarStepSolverResetCode(ss) void
  %openfile tmpbuf
  %if SolverType == "VariableStep"
    %assign nDU = SolverResetInfo.NumNonContDerivSignals
    %if nDU > 0
      if (%<RTMIs("MajorTimeStep")>) {
    %foreach idx = nDU
      %assign dulocal = RTMGetIdxed("NonContDerivSignal", %<idx>)
      if (%<LibGenMemFcnCall("memcmp", "%<dulocal>.pCurrVal", ...
        "%<dulocal>.pPrevVal", "%<dulocal>.sizeInBytes")> != 0) {
        (void) %<LibGenMemFcnCall("memcpy", "%<dulocal>.pPrevVal", ...
          "%<dulocal>.pCurrVal", "%<dulocal>.sizeInBytes")>;
        %<RTMSetSolverNeedsReset()>;
      }
    %endforeach
      }
    %endif
  %endif %% SolverType == "VariableStep"
  %closefile tmpbuf
  %return tmpbuf
%endfunction
 
 
%%Thefollowingfunctionshavesimilarformatsforexportedidentifiers.
%%SLibWriteMdlRefExportedMdlInfoisusedinmodelreferencesimtargetand
%%CacheMdlRefExportedMdlInfoInBinfoisusedinModelReferenceRTWTarget.
%%Ifyouchangetheexportedsignalformatinonefunction,youshouldmodifyanotherone.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants6.m
%%
%function CacheMdlRefExportedMdlInfoInBinfo() void
  %with ::CompiledModel
    %createrecord mdlInfoRecords {}
     
    %foreach idIdx = ExportedMdlInfo.NumExportedMdlInfo
      %assign id = ExportedMdlInfo.ExportedMdlInfo[idIdx]
      %assign path = ""
      %if !ISEMPTY(id.BPath) && !WHITE_SPACE(id.BPath)
        %assign path = id.BPath
      %endif
       
      %addtorecord mdlInfoRecords mdlInfo { /
        Id id.Id; /
        Class id.Class; /
        Alias id.Alias; /
        Port id.Port; /
        Path path /
      }
    %endforeach
    %<CacheModelrefInterfaceInMatInfoFile(::CompiledModel.Name, ...
      "addMdlInfos", mdlInfoRecords)>
  %endwith
%endfunction
 
%%Thefollowingfunctionshavesimilarformatsforexportedidentifiers.
%%SLibWriteMdlRefExportedMdlInfoisusedinmodelreferencesimtargetand
%%CacheMdlRefExportedMdlInfoInBinfoisusedinModelReferenceRTWTarget.
%%Ifyouchangetheexportedsignalformatinonefunction,youshouldmodifyanotherone.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants6.m
%%
%function SLibWriteMdlRefExportedMdlInfo() void
  %with ::CompiledModel
    %openfile tmpBuffer
    static RegMdlInfo rtMdlInfo_%<Name>[%<ExportedMdlInfo.NumExportedMdlInfo>] = {
    %foreach idIdx = ExportedMdlInfo.NumExportedMdlInfo
      %assign id = ExportedMdlInfo.ExportedMdlInfo[idIdx]
      %if ISEMPTY(id.BPath) || WHITE_SPACE(id.BPath)
    {"%<id.Id>", %<id.Class>, %<id.Alias>, %<id.Port>, %<SLibGetNullDefinitionFromTfl()>}/
      %else
    {"%<id.Id>", %<id.Class>, %<id.Alias>, %<id.Port>, (void *) "%<STRING(id.BPath)>"}/
      %endif
      %if idIdx < (ExportedMdlInfo.NumExportedMdlInfo-1)
    ,
      %endif
    %endforeach
    };
    %assign numSharedDSM = ::CompiledModel.NumDataStoresPushedToTopModel
    %if numSharedDSM > 0
       
      void *%<::CompiledModel.Name>_DSM[%<numSharedDSM>];
      int %<::CompiledModel.Name>_DSMIdx[%<numSharedDSM>];
    %endif
    %closefile tmpBuffer
    %<SLibCacheCodeToFile("mdl_data_defn", tmpBuffer)>
     
    %openfile tmpBuffer
    %if numSharedDSM > 0
      extern void *%<::CompiledModel.Name>_DSM[%<numSharedDSM>];
      extern int %<::CompiledModel.Name>_DSMIdx[%<numSharedDSM>];
    %endif
    %closefile tmpBuffer
    %<SLibCacheCodeToFile("mdl_fcn_decl", tmpBuffer)>
 
    %<SLibWriteMdlRefMdlInfoRegFcn()>
 
    %% These might be better off in the SIM target boilerplate?
    %<SLibWriteMdlRefCacheDataAsMxArrayFcn()>
    %<SLibWriteMdlRefRestoreDataFromMxArrayFcn()>
    %<SLibWriteMdlRefCacheBitFieldToMxArrayFcn()>
    %<SLibWriteMdlRefExtractBitFieldFromMxArrayFcn()>
     
    %<SLibWriteMdlRefCacheDataToMxArrayWithOffsetFcn()>
    %<SLibWriteMdlRefRestoreDataFromMxArrayWithOffsetFcn()>
    %<SLibWriteMdlRefCacheBitFieldToCellArrayWithOffsetFcn()>
    %<SLibWriteMdlRefExtractBitFieldFromCellArrayWithOffsetFcn()>
     
    %<SLibWriteMdlRefGetSetDWorkFcns()>
    %<SLibWriteRegisterSimStateChecksumFcn()>
    %<SLibWriteGetSimStateDisallowedBlocksFcn()>
    %<SLibWriteReusedSubSystemBlockPathFcn()>
 
    %<SLibWriteMdlRefInitRestoreDataFcns()>
  %endwith
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteMdlRefMdlInfoRegFcn
%%Abstract:Writesmodel_MdlInfoRegFcninmodel.c.
%%ExtractedfromSLibWriteMdlRefExportedMdlInfo.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants4.m
%%
%function SLibWriteMdlRefMdlInfoRegFcn() void
    %assign regFcnName = SLibCreateMdlInfoRegFcnName()
    %createrecord ReferencedModelHash {}
    %openfile mdlInfoRegFcnBuffer
    void %<regFcnName>(SimStruct* mdlRefSfcnS, char_T *modelName, int_T *retVal)
    {
      *retVal = 0;
      %if ISFIELD(::CompiledModel, "NumModelReferenceBlocks")
        {
          boolean_T regSubmodelsMdlinfo = %;
          ssGetRegSubmodelsMdlinfo(mdlRefSfcnS, &regSubmodelsMdlinfo);
          if (regSubmodelsMdlinfo) {
            %foreach idIdx = NumModelReferenceBlocks
              %assign blkIdx = ModelReferenceBlocks[idIdx]
              %assign mdlBlock = System[blkIdx[0]].Block[blkIdx[1]]
              %assign modelName = mdlBlock.ParamSettings.ReferencedModelName
              %if !ISFIELD(ReferencedModelHash, modelName)
                mr_%<modelName>_MdlInfoRegFcn(mdlRefSfcnS, "%<modelName>", retVal);
                if (*retVal == 0) return;
                *retVal = 0;
                %addtorecord ReferencedModelHash %<modelName> 1
              %endif
            %endforeach
          }
        }
      %endif
       
     %<RegisterMdlRefSFcnToWksDataTypes()>
 
      %assign modelName = Name
      *retVal = 0;
      ssRegModelRefMdlInfo(...
        mdlRefSfcnS, modelName, rtMdlInfo_%<modelName>, ...
        %<ExportedMdlInfo.NumExportedMdlInfo>);
       
      *retVal = 1;
    }
     
    %closefile mdlInfoRegFcnBuffer
    %<SLibCacheCodeToFile("mdl_fcn_defn", mdlInfoRegFcnBuffer)>
     
    %openfile mdlInfoRegFcnBuffer
    %<LibExternInFcnDecls()>void %<regFcnName>(SimStruct* mdlRefSfcnS, char_T *modelName, int_T *retVal);
    %closefile mdlInfoRegFcnBuffer
    %<SLibCacheCodeToFile("mdl_fcn_prototype", mdlInfoRegFcnBuffer)>
%endfunction
 
%%===========================================================================|
%%BEGINModelRefAccelModeSimStatesupport
%%===========================================================================|
 
%%===========================================================================|
%%Function:SLibWriteGetSimStateDisallowedBlocksFcn
%%Abstract:Recursivelypackagestheinformationaboutblocksthatprevent
%%theSimStatefrombeingsafelystored,andreturnsitinan
%%mxArray.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants4.m
%%
%function SLibWriteGetSimStateDisallowedBlocksFcn() void
  %assign currentSystem = System[GetBaseSystemIdx()]
  %with currentSystem.Interface
    %assign fcnSig = SLibCreateGetSimStateDisallowedBlocksFcnSigForModel(Name)
 
    %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
    %% Code generation for header prototype.
    %%
    %openfile fcnBuffer
    %<LibExternInFcnDecls()>%<fcnSig>;
    %closefile fcnBuffer
    %<SLibCacheCodeToFile("mdl_fcn_prototype", fcnBuffer)>
 
    %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
    %% Code generation for function implementation.
    %%
    %openfile fcnBuffer
 
    %selectfile fcnBuffer
    %<fcnSig>
    {
    %with SimStateDisallowedBlocks
 
      %assign modelNames = LibGetReferencedModelNames()
      %assign numChildren = modelNames.NumReferencedModels
 
      %if (0 == NumSimStateDisallowedBlocks) && (0 == numChildren)
        %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
        %% This model is a leaf node with no disallowed block data.
        %%
        return NULL;
 
      %elseif (0 == NumSimStateDisallowedBlocks) && (1 == numChildren)
        %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
        %% This is an internal node with no disallowed block data of its own.
        %% Just return the singleton child's result to the caller.
        %%
        return %<SLibCreateGetSimStateDisallowedBlocksFcnNameForModel(...
          modelNames.ReferencedModel[0].Name)>();
 
      %elseif (0 == NumSimStateDisallowedBlocks)
        %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
        %% This is a multi-child internal node with no disallowed block data of
        %% its own. We must fetch data from each unique child in turn.
        %% If only one child returns non-NULL, simply return its data.
        %% Otherwise, concatenate the results into a new cell matrix, destroy
        %% the individual arrays, and return the consolidated data instead.
        %%
        mxArray * data = NULL;
        size_t numChildrenWithDisallowedBlocks = 0;
        size_t numBlocks = 0;
 
        %<SLibWriteFetchChildSimStateDisallowedBlockData(modelNames, fcnBuffer)>
 
        if (numChildrenWithDisallowedBlocks > 1) {
          mwIndex subs[2], offset;
 
          data = mxCreateCellMatrix(numBlocks, 3);
 
          subs[0] = 0;
 
          %<SLibWriteCacheChildSimStateDisallowedBlockData(...
            modelNames, fcnBuffer)>
        }
 
        return data;
 
      %elseif (0 == numChildren)
        %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
        %% This is a leaf node with disallowed block data. Pack the data into
        %% a new cell matrix and return it.
        %%
        mxArray * data = mxCreateCellMatrix(%<NumSimStateDisallowedBlocks>, 3);
        mwIndex subs[2], offset;
 
        %<SLibWriteCacheLocalSimStateDisallowedBlockData(numChildren, fcnBuffer)>
 
        return data;
 
      %else
        %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
        %% This is the general case of an internal node with disallowed block
        %% data of its own. Generate an array of mxArrays along with a running
        %% total of non-null results and a total block count, then concatenate
        %% the contents
        %%
        mxArray * data = NULL;
        mwIndex subs[2], offset;
        size_t numChildrenWithDisallowedBlocks = 0;
        size_t numBlocks = 0;
 
          %<SLibWriteFetchChildSimStateDisallowedBlockData(...
            modelNames, fcnBuffer)>
 
          %assign allocM = "numBlocks + %<NumSimStateDisallowedBlocks>"
 
          data = mxCreateCellMatrix(%<allocM>, 3);
 
          %<SLibWriteCacheLocalSimStateDisallowedBlockData(...
            numChildren, fcnBuffer)>
 
          %<SLibWriteCacheChildSimStateDisallowedBlockData(...
            modelNames, fcnBuffer)>
 
        return data;
 
      %endif
 
    %endwith
 
    }
 
    %closefile fcnBuffer
    %<SLibCacheCodeToFile("mdl_fcn_defn", fcnBuffer)>
 
  %endwith
 
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteCacheChildSimStateDisallowedBlockData
%%Abstract:Emitcodetocachethedisallowedblocklistsreturnedby
%%recursivecallsintochildmodels.
%%
%function SLibWriteCacheChildSimStateDisallowedBlockData(...
  modelNames, fcnBuffer) void
 
  %selectfile fcnBuffer
 
  {
    size_t i;
    for (i = 0; i < %<modelNames.NumReferencedModels>; ++i) {
      mxArray * data_i = disallowedBlocksInChild[i];
 
      if (NULL != data_i) {
        mwIndex subs_i[2], offset_i;
        const mwIndex numRows_i = (mwIndex) mxGetM(data_i);
 
        for (subs_i[0] = 0; subs_i[0] < numRows_i; ++(subs_i[0])) {
          mwIndex j;
          for (j = 0; j < 3; ++j) {
            mxArray* data_ij;
 
            subs_i[1] = j;
 
            offset_i = mxCalcSingleSubscript(data_i, 2, subs_i);
             
            data_ij = mxGetCell(data_i, offset_i);
            data_ij = mxDuplicateArray(data_ij);
 
            subs[1] = j;
            offset = mxCalcSingleSubscript(data, 2, subs );
 
            mxSetCell(data, offset, data_ij);
          }
 
          ++(subs[0]);
        }
 
        mxDestroyArray(data_i);
      }
    }
  }
   
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteFetchChildSimStateDisallowedBlockData
%%Abstract:EmitcodetoaskeachchildmodelforanmxArrayofdisallowed
%%blocks,thenperformsomebookkeepingtoensurethatallofthe
%%blockdatagetspassedupcorrectly.
%%
%function SLibWriteFetchChildSimStateDisallowedBlockData(...
  modelNames, fcnBuffer) void
 
  %selectfile fcnBuffer
 
  %with modelNames
 
    mxArray * disallowedBlocksInChild[%<NumReferencedModels>];
 
    %foreach idx = NumReferencedModels
 
      disallowedBlocksInChild[%<idx>] =
        %<SLibCreateGetSimStateDisallowedBlocksFcnNameForModel(...
          ReferencedModel[idx].Name)>();
 
    %endforeach
    {
      size_t i;
      for (i = 0; i < %<NumReferencedModels>; ++i) {
        mxArray * data_i = disallowedBlocksInChild[i];
        if (NULL != data_i) {
          if (0 == numChildrenWithDisallowedBlocks++) {
            data = data_i;
          }
          numBlocks += mxGetM(data_i);
        }
      }
    }
  %endwith
 
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteCacheLocalSimStateDisallowedBlockData
%%Abstract:Emitcodetocachethedisallowedblockdatacontainedinthe
%%model.rtwfilebeingprocessed.
%%
%function SLibWriteCacheLocalSimStateDisallowedBlockData(...
  numChildren, fcnBuffer) void
 
  %selectfile fcnBuffer
 
  %with SimStateDisallowedBlocks
 
  {
    static const char * blockType[%<NumSimStateDisallowedBlocks>] = {
      %foreach idx = NumSimStateDisallowedBlocks
        "%",
      %endforeach
    };
 
    static const char * blockPath[%<NumSimStateDisallowedBlocks>] = {
      %foreach idx = NumSimStateDisallowedBlocks
        "%",
      %endforeach
    };
 
    static const int reason[%<NumSimStateDisallowedBlocks>] = {
      %foreach idx = NumSimStateDisallowedBlocks
        %,
      %endforeach
    };
 
    %% There is a bit of a hack-fu that uses the side effect of incrementing
    %% subs[0] to the correct value prior to the start of appending child data.
    for (subs[0] = 0; subs[0] < %<NumSimStateDisallowedBlocks>; ++(subs[0])) {
      subs[1] = 0;
      offset = mxCalcSingleSubscript(data, 2, subs);
 
      mxSetCell(data, offset, mxCreateString(blockType[subs[0]]));
 
      subs[1] = 1;
      offset = mxCalcSingleSubscript(data, 2, subs);
 
      mxSetCell(data, offset, mxCreateString(blockPath[subs[0]]));
 
      subs[1] = 2;
      offset = mxCalcSingleSubscript(data, 2, subs);
 
      mxSetCell(data, offset, mxCreateDoubleScalar((double)reason[subs[0]]));
    }
  }
 
  %endwith
 
%endfunction
 
%%===========================================================================|
%%FunctionSLibLogStatesAfterStateWrite
%%Abstract:callintosimulinktologstatesafterstateWriterblock'soutput
%%
%function SLibLogStatesAfterStateWrite(stateWriteBlockSID) void
  %return "slmrLogStatesAfterStateWrite(%<RTMGet("MdlRefSfcnS")>, /"%<stateWriteBlockSID>/")"
%endfunction
 
%%===========================================================================|
%%FunctionSLibIsRapidAccelSimulating
%%Abstract:returnifitisRapidAcceleratorsimulation
%%
%function SLibIsRapidAccelSimulating() void
  %return "slIsRapidAcceleratorSimulating()"
%endfunction
 
 
%%===========================================================================|
%%Function:SLibWriteRegisterSimStateChecksumFcn
%%Abstract:Constructthemodel_RegisterSimStateChecksumfunction.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants4.m
%%
%function SLibWriteRegisterSimStateChecksumFcn() void
  %assign currentSystem = System[GetBaseSystemIdx()]
  %with currentSystem.Interface
    %assign fcnSig = SLibCreateRegisterSimStateChecksumFcnSigForModel(Name)
 
    %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
    %% Code generation for function definition.
    %%
    %openfile fcnBuffer
    %<fcnSig>
    {
      %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
      %% Initialize with value computed during the build procedure
      %%
      const uint32_T chksum[4] = {
      %foreach idx = 4
        %,
      %endforeach
      };
 
      slmrModelRefRegisterSimStateChecksum(S, "%<Name>", &chksum[0]);
 
      %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
      %% Ask all child models to register their checksums.
      %%
      %assign modelNames = LibGetReferencedModelNames() %% from mdlrefutil.tlc
 
      %with modelNames
        %foreach idx = NumReferencedModels
            %              (ReferencedModel[idx].Name)>(S);
        %endforeach
      %endwith
    }
    %closefile fcnBuffer
    %<SLibCacheCodeToFile("mdl_fcn_defn", fcnBuffer)>
 
    %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
    %% Code generation for header prototype.
    %%
    %openfile fcnBuffer
    %<LibExternInFcnDecls()>%<fcnSig>;
    %closefile fcnBuffer
    %<SLibCacheCodeToFile("mdl_fcn_prototype", fcnBuffer)>
  %endwith
%endfunction
 
%%===========================================================================|
%%Function:SLibCreateRegisterSimStateChecksumFcnSigForModel
%%Abstract:Constructthemodel_RegisterSimStateChecksumfunctionsignature.
%%
%function SLibCreateRegisterSimStateChecksumFcnSigForModel(thisModelName)
  %assign regFcnName = SLibCreateRegisterSimStateChecksumFcnNameForModel(Name)
  %return "void %<regFcnName>(SimStruct* S)"
%endfunction
 
%%===========================================================================|
%%Function:SLibCreateRegisterSimStateChecksumFcnNameForModel
%%Abstract:Createsthemodel_RegisterSimStateChecksumfunctionname.
%%
%function SLibCreateRegisterSimStateChecksumFcnNameForModel(thisModelName)
  %return "mr_%<thisModelName>_RegisterSimStateChecksum"
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteMdlRefGetSetDWorkFcns
%%Abstract:Writeagetterandsetterforamodel'sDWorkitems.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibWriteMdlRefGetSetDWorkFcns() void
  %assign currentSystem = System[GetBaseSystemIdx()]
  %with currentSystem.Interface
    %assign getterFcnSig = SLibCreateGetDWorkFcnSigForModel(Name)
    %assign setterFcnSig = SLibCreateSetDWorkFcnSigForModel(Name)
 
    %assign isSingleInstance = !::CompiledModel.OkToMultiInstanceModelref
    %assign dwMembers ...
      = SLibGetDWorkMemberNamesForSystem(currentSystem, isSingleInstance)
 
    %with dwMembers %% rtbName->"mdlrefDW->rtb", hasRTB etc
 
      %assign needsToCacheDWorkState ...
        = hasRTB ...
        || hasRTDW ...
        || hasRTZCE ...
        || HasModelReferenceBlocks()
 
      %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
      %% Code generation for function bodies begins here.
      %%
      %openfile getDWorkBuffer
      %<getterFcnSig> {
 
      %openfile setDWorkBuffer
      %<setterFcnSig> {
 
      %assign ssMxName = "ssDW"
 
      %if needsToCacheDWorkState
 
        (void) %<ssMxName>;
        %if !isSingleInstance
        (void) %<SLibGetMdlrefDWPtrName()>;
        %endif
     
        %<SLibWriteGetDWorkPreamble(...
          rtbMxName, rtdwMxName, rtzceMxName, ssMxName, getDWorkBuffer)>
 
        %if hasRTB
          %<SLibWriteCacheRestoreVariableToFromMxArray(...
            rtbName, ssMxName, 0, getDWorkBuffer, setDWorkBuffer)>
        %endif
 
        %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
        %% Traverse the RTDW tree and list of referenced models, make lists
        %% of variables to stash, emit code to stash them if necessary.
        %%
 
        %assign rtdwTree = SLibCreateEmptyRTDWTreeObject(rtdwName)
 
        %if hasRTDW
          %% This picks up state for this model, s-functions in models
          %% referenced from this model, and MdlrefDW structs for multi-instance
          %% models referenced from this model.
          %%
          %assign varGroupIdx = FcnSysVarGroupIndex(currentSystem, "DWork", 0)
          %<SLibGetDWorkStateItemsForVarGroup(rtdwTree, varGroupIdx)>
        %endif
         
        %if SLibSimTargetUsesModelSelf()
          %% When using RTM as model self, dwork is contained by RTM, so child model's dwork
          %% is contained in child model's RTM, which is then contained by the parent model.
          %% Therefore, to get child model dwork hierarchically, the RTM needs to be passed down.
          %assign varGroupIdx = FcnSysVarGroupIndex(currentSystem, "CoderDataGroup_self", 0)
          %<SLibGetDWorkStateItemsForVarGroup(rtdwTree, varGroupIdx)>
        %endif
 
        %if HasModelReferenceBlocks() && isSingleInstance
          %% Iterate over the list, picking out the single-instance models
          %% and noting their name. These need to be stashed even if no
          %% RTDW struct exists.
          %%
          %<SLibGetDWorkPairsForSingleInstanceModelBlocks(rtdwTree)>
        %endif
 
        %if SLibRTDWTreeContainsPersistentState(rtdwTree)
          %% If this model or its children own persistent state, emit code
          %% to cache it.
          %%
          %<SLibWriteGetSetRTDWContents(...
            rtdwTree, ssMxName, 1, getDWorkBuffer, setDWorkBuffer)>
        %endif
 
        %if hasRTZCE
          %<SLibWriteCacheRestoreVariableToFromMxArray(...
            rtzceName, ssMxName, 2, getDWorkBuffer, setDWorkBuffer)>
        %endif
 
        %selectfile getDWorkBuffer
      %if !isSingleInstance
          (void) %<SLibGetMdlrefDWPtrName()>;
          %endif
          return %<ssMxName>;
      %else %% doesn't need to cache DWork state
        %selectfile getDWorkBuffer
        %if !isSingleInstance
          (void) %<SLibGetMdlrefDWPtrName()>;
        %endif
        return NULL;
 
        %selectfile setDWorkBuffer
        (void) %<ssMxName>;
        %if !isSingleInstance
          (void) %<SLibGetMdlrefDWPtrName()>;
        %endif
      %endif
 
      %selectfile getDWorkBuffer
      }
      %selectfile setDWorkBuffer
      }
 
      %closefile getDWorkBuffer
      %closefile setDWorkBuffer
 
      %<SLibCacheCodeToFile("mdl_fcn_defn", getDWorkBuffer)>
      %<SLibCacheCodeToFile("mdl_fcn_defn", setDWorkBuffer)>
 
      %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
      %% Code generation for header declarations.
      %%
      %openfile getDWorkBuffer
      %<LibExternInFcnDecls()>%<getterFcnSig>;
      %closefile getDWorkBuffer
 
      %openfile setDWorkBuffer
      %<LibExternInFcnDecls()>%<setterFcnSig>;
      %closefile setDWorkBuffer
 
      %<SLibCacheCodeToFile("mdl_fcn_prototype", getDWorkBuffer)>
      %<SLibCacheCodeToFile("mdl_fcn_prototype", setDWorkBuffer)>
    %endwith %% dwMembers
  %endwith %% currentSystem.Interface
%endfunction
 
%%===========================================================================|
%%Function:SLibCreateEmptyRTDWTreeObject
%%Abstract:Createaninitializedemptyinstanceoftherecordusedtocache
%%theresultsoftraversingtheRTDWtree.
%%
%%Membersofthereturnedstruct:
%%
%%prefixName:NameofthisnodeinpathtoDWORKitems.
%%
%%numStateItems:ThenumberofPODitemstostoreatthislevel.
%%
%%numModelBlocks:ThenumberofModelblocksatthislevel.
%%
%%numberOfIterations:Thenumberoftimesthislevelisiterated.
%%(>0==ForEachSS)
%%
%%numForEachSSs:ThenumberofForEachSubsystemsatthislevel.
%%
%function SLibCreateEmptyRTDWTreeObject(newPrefixName)
  %createrecord rtdwTree { ...
    prefixName newPrefixName; ...
    numStateItems 0; ...
    numModelBlocks 0; ...
    numberOfIterations 0; ...
    numForEachSSs 0 ...
  }
 
  %return rtdwTree
%endfunction
 
%%===========================================================================|
%%Function:SLibRTDWTreeContainsPersistentState
%%Abstract:Returnstrueifthereissomethingthatneedstobecached.
%%
%function SLibRTDWTreeContainsPersistentState(rtdwTree)
  %return ...
    rtdwTree.numStateItems > 0 || ...
    rtdwTree.numModelBlocks > 0 || ...
    rtdwTree.numForEachSSs > 0
%endfunction
 
%%===========================================================================|
%%Function:SLibEnumerateAndIndexRTDWTree
%%Abstract:MakeaflatlistofDWORKpathstobeusedinvariousplaces,and
%%insertthecorrespondingindicestotheflatlistintoeachleaf
%%node.Forsingle-instanceModelblocks,themodelnameisused
%%asaplaceholdersincethepathsareusedasthefieldnamesfor
%%thecontainerstruct.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants4.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibEnumerateAndIndexRTDWTree(...
  rtdwTree, prefix, rtdwList, loopDepth) void
 
  %foreach modelIdx = rtdwTree.numModelBlocks
 
    %assign thisBlock = rtdwTree.modelBlock[modelIdx]
 
    %addtorecord thisBlock index rtdwList.numItems
 
    %if WHITE_SPACE(thisBlock.dwName)
      %addtorecord rtdwList item { value thisBlock.modelName }
    %else
      %if ISFIELD(thisBlock, "modelBlockPrefix")
        %assign prefixToBlock = thisBlock.modelBlockPrefix
      %else
        %assign prefixToBlock = prefix
      %endif
      %addtorecord rtdwList item { value prefixToBlock + "." + thisBlock.dwName }
    %endif
 
    %assign rtdwList.numItems = rtdwList.numItems + 1
  %endforeach
 
  %foreach stateIdx = rtdwTree.numStateItems
    %assign thisState = rtdwTree.stateItem[stateIdx]
 
    %addtorecord thisState index rtdwList.numItems
 
    %addtorecord rtdwList item { value prefix + "." + thisState.name }
 
    %assign rtdwList.numItems = rtdwList.numItems + 1
  %endforeach
 
  %if rtdwTree.numForEachSSs > 0
    %assign maxLoopDepth = %<loopDepth> + 1
 
    %foreach ssIdx = rtdwTree.numForEachSSs
      %assign thisSS = rtdwTree.forEachSS[ssIdx]
      %assign subPrefix = prefix + "." + thisSS.prefixName + "[0]"
      %assign subLoopDepth = ...
        %<SLibEnumerateAndIndexRTDWTree(thisSS, subPrefix, rtdwList, loopDepth+1)>
      %if subLoopDepth > maxLoopDepth
        %assign maxLoopDepth = subLoopDepth
      %endif
    %endforeach
 
    %assign loopDepth = maxLoopDepth
  %endif
 
  %return loopDepth
%endfunction
 
%%===========================================================================|
%%Function:SLibGetDWorkMemberNamesForSystem
%%Abstract:Constructthefully-qualifiedvariablenamesforthemembers
%%oftheMdlrefDW_model_checksum_Tstructandreturnthemas
%%arecord.
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibGetDWorkMemberNamesForSystem(currentSystem, isSingleInstance)
  %assign hasRTB = currentSystem.HasBlockIOArg
  %assign hasRTDW = currentSystem.HasDWorkArg
  %assign hasRTZCE = currentSystem.HasZCEventArg
 
  %if isSingleInstance
    %assign rtbName = FcnSysVarGroupNonreusedName(currentSystem, "BlockIO")
    %assign rtdwName = FcnSysVarGroupNonreusedName(currentSystem, "DWork" )
    %assign rtzceName = FcnSysVarGroupNonreusedName(currentSystem, "ZCEvent")
 
    %assign rtbMxName = hasRTB ? rtbName : "NULL_B"
    %assign rtdwMxName = hasRTDW ? rtdwName : "NULL_DW"
    %assign rtzceMxName = hasRTZCE ? rtzceName : "NULL_PrevZCX"
  %else
    %assign rtbName = !SLibGetUseRTMcgType() ? "rtb" : "rtm.blockIO"
    %assign dwName = !SLibGetUseRTMcgType() ? "rtdw" : "rtm.dwork"
    %assign zceName = !SLibGetUseRTMcgType() ? "rtzce" : "rtm.prevZCSigState"
    %assign rtbMxName = hasRTB ? "%<rtbName>" : "NULL->rtb"
    %assign rtdwMxName = hasRTDW ? "%<dwName>" : "NULL->rtdw"
    %assign rtzceMxName = hasRTZCE ? "%<zceName>" : "NULL->rtzce"
 
    %assign mdlrefDWPtrName = SLibGetMdlrefDWPtrName()
 
    %assign rtbName = hasRTB ? "%<mdlrefDWPtrName>->%<rtbMxName>" : ""
    %assign rtdwName = hasRTDW ? "%<mdlrefDWPtrName>->%<rtdwMxName>" : ""
    %assign rtzceName = hasRTZCE ? "%<mdlrefDWPtrName>->%<rtzceMxName>" : ""
 
    %if SLibSimTargetUsesModelSelf()
      %if !hasRTDW && IsBaseSystem(currentSystem)
        %% At the root level, rtm acts like dwork. So use rtm to populate names.
        %assign rtdwMxName = "rtm"
        %assign rtdwName = "%<mdlrefDWPtrName>->%<rtdwMxName>"
      %endif
    %endif
  %endif
 
  %createrecord dwMembers { ...
    rtbName "%<rtbName>" ; rtbMxName "%<rtbMxName>" ; ...
    rtdwName "%<rtdwName>" ; rtdwMxName "%<rtdwMxName>" ; ...
    rtzceName "%<rtzceName>" ; rtzceMxName "%<rtzceMxName>" ; ...
    hasRTB %<hasRTB> ; hasRTDW %<hasRTDW> ; hasRTZCE %<hasRTZCE> ...
  }
 
  %return dwMembers
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteGetDWorkPreamble
%%Abstract:Writethevariabledeclarationsneededatthebeginningofthe
%%top-levelscopeofmr_model_{Get,Set}DWork.
%%
%function SLibWriteGetDWorkPreamble(...
    rtbMxName, rtdwMxName, rtzceMxName, ssMxName, getDWorkBuffer) void
  %selectfile getDWorkBuffer
  static const char * %<ssMxName>FieldNames[3] = {
    "%<rtbMxName>",
    "%<rtdwMxName>",
    "%<rtzceMxName>",
  };
  mxArray * %<ssMxName> = mxCreateStructMatrix(1, 1, 3, %<ssMxName>FieldNames);
%endfunction
 
%%===========================================================================|
%%Function:SLibGetCreateInitRestoreDataFcnNameForModel
%%Abstract:Createsthemr_model_CreateInitRestoreDatafunctionname.
%%
%function SLibGetCreateInitRestoreDataFcnNameForModel(modelName)
  %return "mr_%<modelName>_CreateInitRestoreData"
%endfunction
 
%%===========================================================================|
%%Function:SLibGetCopyFromInitRestoreDataFcnNameForModel
%%Abstract:Createsthemr_model_CopyFromInitRestoreDatafunctionname.
%%
%function SLibGetCopyFromInitRestoreDataFcnNameForModel(modelName)
  %return "mr_%<modelName>_CopyFromInitRestoreData"
%endfunction
 
%%===========================================================================|
%%Function:SLibGetDestroyInitRestoreDataFcnNameForModel
%%Abstract:Createsthemr_model_DestroyInitRestoreDatafunctionname.
%%
%function SLibGetDestroyInitRestoreDataFcnNameForModel(modelName)
  %return "mr_%<modelName>_DestroyInitRestoreData"
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteMdlRefInitRestoreDataFcns
%%Abstract:Writethefunctionstohandlesavingandrestoringdatainthe
%%DWorkstructureofthereferencedmodelafterinitialization.
%%Thesefunctionsare
%%mr_model_CreateInitRestoreData()
%%mr_model_CopyFromInitRestoreData()
%%mr_model_DestroyInitRestoreData()
%%
%function SLibWriteMdlRefInitRestoreDataFcns() void
  %if ModelRefBlockHasPrivateDWork()
    %assign modelName = ::CompiledModel.Name
    %assign initRestoreData = "%<modelName>_InitRestoreDataPtr"
    %assign createDataFcnSignature = ...
      "void %<SLibGetCreateInitRestoreDataFcnNameForModel(modelName)>()"
    %assign copyDataFcnSignature = ...
      "void %<SLibGetCopyFromInitRestoreDataFcnNameForModel(modelName)>()"
    %assign destroyDataFcnSignature = ...
      "void %<SLibGetDestroyInitRestoreDataFcnNameForModel(modelName)>()"
    %openfile tmpBuffer
    static void *%<initRestoreData> = NULL;
 
    %<createDataFcnSignature>
    {
      %<initRestoreData> = utMalloc(sizeof(%<LibGetDWorkStruct()>));
      memcpy(%<initRestoreData>, (void *) &(%<LibGetDWorkStruct">LibGetDWorkStruct()>), sizeof(%<LibGetDWorkStruct">LibGetDWorkStruct()>));
    }
 
    %<copyDataFcnSignature>
    {
      memcpy((void *) &(%<LibGetDWorkStruct">LibGetDWorkStruct()>), %<initRestoreData>, sizeof(%<LibGetDWorkStruct">LibGetDWorkStruct()>));
    }
       
    %<destroyDataFcnSignature>
    {
      utFree(%<initRestoreData>);
    }
    %closefile tmpBuffer
    %<SLibCacheCodeToFile("mdl_fcn_defn", tmpBuffer)>
 
    %openfile tmpBuffer
    %<createDataFcnSignature>;
    %<copyDataFcnSignature>;
    %<destroyDataFcnSignature>;
    %closefile tmpBuffer
    %<SLibCacheCodeToFile("mdl_fcn_decl", tmpBuffer)>
  %endif
%endfunction
 
%%===========================================================================|
%%Function:SLibDWorkIsPWork
%%Abstract:ReturnstrueiftheargumentDWORKisdeclaredtobeaPWORKor
%%pointertype.
%%
%function SLibDWorkIsPWork(thisDWork)
  %if thisDWork.Origin == "PWORK"
    %return TLC_TRUE
  %endif
 
  %if LibCGTypeIsPointer(thisDWork.CGTypeIdx)
    %return TLC_TRUE
  %endif
 
  %if LibCGTypeIsMatrix(thisDWork.CGTypeIdx) && ...
    LibCGTypeIsPointer(LibCGTypeBaseIndex(thisDWork.CGTypeIdx))
    %return TLC_TRUE
  %endif
 
  %return TLC_FALSE
%endfunction
 
%%===========================================================================|
%%Function:SLibGetDWorkStateItemsForVarGroup
%%Abstract:RecursivelymakeaflatlistofmembersoftheDWtocachefor
%%thecurrentmodel.IncludesMdlrefDWstructsformulti-instance
%%models.
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref2.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants4.m
%%
%function SLibGetDWorkStateItemsForVarGroup(rtdwTree, varGroupIdx) void
 
  %if varGroupIdx >= 0
 
    %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
    %assign isSelfVarGroup = varGroup.IsModelSelfCoderGroupVarGroup
    %assign cgTypeIdx = varGroup.CGTypeIdx
 
    %if LibCGTypeIsMatrix(cgTypeIdx) %% this is a ForEach SS
 
      %% grab the number of iterations of this SS
      %assign rtdwTree.numberOfIterations = LibCGTypeWidth(varGroup.CGTypeIdx)
 
      %% proceed using the base type of the SS
      %assign cgTypeIdx = LibCGTypeBaseIndex(varGroup.CGTypeIdx)
 
    %endif
 
    %foreach mIdx = LibCGTypeNumMembers(cgTypeIdx)
 
      %assign memberName = LibCGTypeMemberName(cgTypeIdx, mIdx)
 
      %assign idnum = IDNUM(varGroup.VarGroupElements[mIdx])
 
      %assign recType = idnum[0]
      %assign recIdx = idnum[1]
 
      %switch recType
        %case "W"
        %case "LDW" %% local scratch dwork converted to global
          %if isSelfVarGroup
            %continue
          %endif
          %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
          %% Most DWORKs fall under this case.
          %%
          %assign dataRec = SLibGetDataRecForVarGroupMember(recType, recIdx)
          %assign sysIdx = dataRec.SigSrc[0]
          %assign blkIdx = dataRec.SigSrc[2]
           
          %if !(sysIdx >= 0 && blkIdx >= 0) %% is virtual
            %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
            %% If we ever encounter this combination, abort the compilation.
            %%
            %<SLibReportErrorWithIdAndArgs(...
              "Simulink:modelReference:InternalCodeGenerationError", ...
              Name + ": Virtual DWORK")>
            %exit
          %endif
           
          %assign ownerBlk = ::CompiledModel.System[sysIdx].Block[blkIdx]
           
          %if "ModelReference" == ownerBlk.Type && "DWORK" == dataRec.Origin
            %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
            %% Multi-instance Model blocks will have an entry in the DWORK
            %% tree. The MdlrefDW items for single-instance Models are picked
            %% up in SLibGetDWorkPairsForSingleInstanceModelBlocks.
            %%
            %if GetModelrefInterface(ownerBlk).IsScalableBuild
              %% This is an S-Function DWork owned by a single-instance model
              %% referenced from ownerBlk. Add it to the list of states
              %%
              %if !SLibDWorkIsPWork(dataRec)
                %<SLibAppendStateItem(...
                  varGroup, mIdx, rtdwTree, memberName, dataRec)>
              %endif
            %else
              %% This is a MdlrefDW struct that belongs to the model
              %% referenced by this block.
              %%
              %addtorecord rtdwTree ...
                modelBlock { ...
                modelName ownerBlk.ParamSettings.ReferencedModelName; ...
                dwName memberName ...
              }
              %assign rtdwTree.numModelBlocks = rtdwTree.numModelBlocks + 1
            %endif
          %elseif !SLibDWorkIsPWork(dataRec) %% all non-ModelReference blocks
            %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
            %% Most POD DWORKs will be picked up here.
            %%
            %<SLibAppendStateItem(...
              varGroup, mIdx, rtdwTree, memberName, dataRec)>
          %endif
           
          %break %% case "W" "LDW"
           
        %case "VG"
          %if isSelfVarGroup
            %continue
          %endif
          %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
          %% Recursively descend into non-virtual subsystems.
          %%
          %assign newRtdwTree = SLibCreateEmptyRTDWTreeObject(memberName)
           
          %<SLibGetDWorkStateItemsForVarGroup(newRtdwTree, recIdx)>
           
          %if newRtdwTree.numberOfIterations > 0
            %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
            %% If we parsed a ForEach SS DWORK structure, we need to add an
            %% entry for each instance with the proper index appended the
            %% member name prefix prior to the dot operator.
            %%
            %addtorecord rtdwTree forEachSS %<newRtdwTree>
            %assign rtdwTree.numForEachSSs = rtdwTree.numForEachSSs + 1
          %else
            %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
            %% This is a normal sub-structure in the DWORK, all we need is
            %% the dot operator. Fold the new sub-tree into the existing tree.
            %%
            %<SLibAppendNewRtdwTree(rtdwTree, newRtdwTree)>
          %endif
           
          %break %% case "VG"
           
        %case "S"
          %if isSelfVarGroup
            %continue
          %endif
          %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
          %%
          %addtorecord rtdwTree ...
            stateItem { name memberName; bitFieldWidth 0 }
           
          %assign rtdwTree.numStateItems = rtdwTree.numStateItems + 1
           
          %break %% case "S"
           
        %case "PCDG"
          %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
          %% When child model's DWork is contained in RTM (child model's
          %% self coder data group vargroup)
          %%
          %assign prefixName = "%<SLibGetMdlrefDWPtrName()>->rtm"
          %assign group = FcnGetCoderGroupForVarGroup(varGroup)
          %assign childDataGroup = FcnGetChildDataGroup(group, recIdx)
          %assert childDataGroup.AsStructure == "InParent"
          %assign mdlrefBlock = ::CompiledModel.ModelReferenceBlocks[childDataGroup.CompiledModelBlockIndex]
          %assign ownerBlk = ::CompiledModel.System[mdlrefBlock[0]].Block[mdlrefBlock[1]]
 
          %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
          %% Multi-instance Model blocks will have an entry in the DWORK
          %% tree. The MdlrefDW items for single-instance Models are picked
          %% up in SLibGetDWorkPairsForSingleInstanceModelBlocks.
          %%
          %assign mdlrefInterface = GetModelrefInterface(ownerBlk)
          %if mdlrefInterface.IsScalableBuild
            %% This is an S-Function DWork owned by a single-instance model
            %% referenced from ownerBlk. Add it to the list of states
            %%
            %if !SLibDWorkIsPWork(dataRec)
              %<SLibAppendStateItem(...
                varGroup, mIdx, rtdwTree, memberName, dataRec)>
            %endif
          %else
            %% This is a DWork struct that belongs to the model
            %% referenced by this block.
            %%
            %addtorecord rtdwTree ...
              modelBlock { ...
              modelName ownerBlk.ParamSettings.ReferencedModelName; ...
              modelBlockPrefix prefixName ...
              mdlrefDWorkType "%<mdlrefInterface.DWorkType>" ...
              dwName memberName ...
            }
            %assign rtdwTree.numModelBlocks = rtdwTree.numModelBlocks + 1
          %endif
 
          %break %% case "PCDG"
           
        %default
          %if SLibSimTargetUsesModelSelf()
            %% In this case, RTM is passed in to build up the rtdwTree. RTM
            %% can contain other types of vargroups. DWork vargroup and child
            %% RTMs are handled above, and other vargroups will be skipped.
            %break %% skip unhandled vargroups
          %endif
          %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
          %% If there other states that we haven't handled, abort compilation.
          %%
          %<SLibReportErrorWithIdAndArgs(...
            "Simulink:modelReference:InternalCodeGenerationError", ...
            Name + ": Unexpected recType")>
          %exit
      %endswitch
    %endforeach
  %endif
 
%endfunction
 
%%===========================================================================|
%%Function:SLibAppendStateItem
%%Abstract:Appendthecurrentstructdatamembertothelistofnewstate
%%itemsforthesystemofinterest.
%%
%function SLibAppendStateItem(...
  varGroup, mIdx, rtdwTree, memberName, dataRec) void
 
  %assign subStructIdx = varGroup.NumSubStructs > 0 ? ...
    varGroup.SubStructIndex[mIdx] : -1
 
  %assign subStructPath = -1 != subStructIdx ? ...
    varGroup.SubStuctNames[subStructIdx] + "." : ""
 
  %addtorecord rtdwTree ...
    stateItem { ...
      name subStructPath + memberName; ...
      bitFieldWidth dataRec.BitFieldWidth ...
    }
 
  %assign rtdwTree.numStateItems = rtdwTree.numStateItems + 1
 
%endfunction
 
%%===========================================================================|
%%Function:SLibAppendNewRtdwTree
%%Abstract:AppendthegiventreeofDWORKitemstothecurrenttree,
%%prependingthenewtree'sprefixpath.
%%TopTester:test/toolbox/simulink/variants/exportFcns/tExportFcnsWithInlineVariants.m
%function SLibAppendNewRtdwTree(rtdwTree, newRtdwTree) void
 
  %assign prefix = newRtdwTree.prefixName + "."
 
  %foreach stateIdx = newRtdwTree.numStateItems
 
    %addtorecord rtdwTree ...
      stateItem { ...
        name prefix + newRtdwTree.stateItem[stateIdx].name; ...
        bitFieldWidth newRtdwTree.stateItem[stateIdx].bitFieldWidth ...
      }
 
  %endforeach
 
  %assign rtdwTree.numStateItems = ...
    rtdwTree.numStateItems + newRtdwTree.numStateItems
 
  %foreach blockIdx = newRtdwTree.numModelBlocks
 
    %assign thisDwName = newRtdwTree.modelBlock[blockIdx].dwName
 
    %addtorecord rtdwTree ...
      modelBlock { ...
        modelName newRtdwTree.modelBlock[blockIdx].modelName; ...
        dwName "" == thisDwName ? "" : prefix + thisDwName ...
      }
 
  %endforeach
 
  %assign rtdwTree.numModelBlocks = ...
    rtdwTree.numModelBlocks + newRtdwTree.numModelBlocks
 
  %foreach ssIdx = newRtdwTree.numForEachSSs
 
    %assign thisForEachSS = newRtdwTree.forEachSS[ssIdx]
    %assign thisForEachSS.prefixName = prefix + thisForEachSS.prefixName
    %addtorecord rtdwTree forEachSS %<thisForEachSS>
 
  %endforeach
 
  %assign rtdwTree.numForEachSSs = ...
    rtdwTree.numForEachSSs + newRtdwTree.numForEachSSs
 
%endfunction
 
%%===========================================================================|
%%Function:SLibGetDWorkPairsForSingleInstanceModelBlocks
%%Abstract:Appendsentriesforthesingle-instancereferencedmodelsto
%%theprovidedlistof{model;path.to.model_DWORK1}pairs.
%%
%%>Single-instancereferencedmodelsowntheirstate,soanempty
%%stringisreturnedforthepath.Thissignifiesthatthe
%%getter/setterdoesnotrequireapointertobepassedfromthe
%%parentmodel.
%%
%%>Multi-instancereferencedmodelsplacetheirstateintheRTDW
%%heirarchy,sothedataneededtogeneratecallstotheir
%%respectivemr_model_{get,set}DWorkfunctionsispickedupin
%%SLibGetDWorkStateItemsForVarGroup.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibGetDWorkPairsForSingleInstanceModelBlocks(rtdwTree) void
 
  %foreach idIdx = NumModelReferenceBlocks
 
    %assign blkIdx = ModelReferenceBlocks[idIdx]
    %assign mdlBlk = System[blkIdx[0]].Block[blkIdx[1]]
    %assign blkIntf = GetModelrefInterface(mdlBlk)
 
    %if blkIntf.IsScalableBuild %% single-instance mode
 
      %addtorecord rtdwTree ...
        modelBlock { ...
          modelName mdlBlk.ParamSettings.ReferencedModelName; ...
          dwName "" ...
        }
 
      %assign rtdwTree.numModelBlocks = rtdwTree.numModelBlocks + 1
 
    %endif
  %endforeach
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteGetSetRTDWContents
%%Abstract:Writescodetocache/restorethecontentsofdw->rtdw/model_DW.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibWriteGetSetRTDWContents(...
    rtdwTree, ...
    ssMxName, ssMxIndex, ...
    getDWorkBuffer, setDWorkBuffer) void
 
  %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
  %% Prepare to generate code.
  %%
  %createrecord rtdwList { numItems 0 }
  %assign maxLoopDepth = ...
    SLibEnumerateAndIndexRTDWTree(rtdwTree, rtdwTree.prefixName, rtdwList, 0)
 
  %% for variable and constant declarations at the beginning of the rtdw scope
  %openfile getDWorkDeclarationsBuffer
  %openfile setDWorkDeclarationsBuffer
 
  %% for memory allocation statements and other things that must happen between
  %% the definition statements and the main body
  %openfile getDWorkPreambleBuffer
  %openfile setDWorkPreambleBuffer
 
  %% for the actual load/save operation statements
  %openfile getDWorkBodyBuffer
  %openfile setDWorkBodyBuffer
 
  %% for anything that must be done after all of the state load/save operations
  %% are complete
  %openfile getDWorkEpilogueBuffer
  %openfile setDWorkEpilogueBuffer
 
  %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
  %% Generate code.
  %%
  %assign rtdwMxName = "rtdwData"
 
  %<SLibWriteGetSetRTDWDeclarations(...
    rtdwList, rtdwMxName, ...
    ssMxName, ssMxIndex, ...
    getDWorkDeclarationsBuffer, setDWorkDeclarationsBuffer)>
 
  %<SLibWriteGetSetRTDWItems(...
    rtdwTree, rtdwList, maxLoopDepth, ...
    rtdwMxName, ...
    getDWorkDeclarationsBuffer, setDWorkDeclarationsBuffer, ...
    getDWorkPreambleBuffer, setDWorkPreambleBuffer, ...
    getDWorkBodyBuffer, setDWorkBodyBuffer)>
 
  %<SLibWriteGetSetRTDWEpilogue(...
    rtdwMxName, ssMxName, ssMxIndex, ...
    getDWorkEpilogueBuffer, setDWorkEpilogueBuffer)>
 
  %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
  %% Consolidate generated code.
  %%
  %closefile getDWorkDeclarationsBuffer
  %closefile setDWorkDeclarationsBuffer
 
  %closefile getDWorkPreambleBuffer
  %closefile setDWorkPreambleBuffer
 
  %closefile getDWorkBodyBuffer
  %closefile setDWorkBodyBuffer
 
  %closefile getDWorkEpilogueBuffer
  %closefile setDWorkEpilogueBuffer
 
  %selectfile getDWorkBuffer
 
  %<getDWorkDeclarationsBuffer>
  %<getDWorkPreambleBuffer>
  %<getDWorkBodyBuffer>
  %<getDWorkEpilogueBuffer>
 
  %selectfile setDWorkBuffer
 
  %<setDWorkDeclarationsBuffer>
  %<setDWorkPreambleBuffer>
  %<setDWorkBodyBuffer>
  %<setDWorkEpilogueBuffer>
 
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteGetSetRTDWDeclarations
%%Abstract:Openanewscopeanddeclarelocalvariablesneededtocachethe
%%contentsofdw->rtdw/model_DW.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibWriteGetSetRTDWDeclarations(...
    rtdwList, ...
    rtdwMxName, ssMxName, ssMxIndex, ...
    getDWorkDeclarationsBuffer, setDWorkDeclarationsBuffer) void
 
  %selectfile getDWorkDeclarationsBuffer
 
  {
    %if rtdwList.numItems > 0
    static const char * %<rtdwMxName>FieldNames[%<rtdwList.numItems>] = {
      %foreach itemIdx = rtdwList.numItems
        "%",
      %endforeach
    };
    %else
    static const char * %<rtdwMxName>FieldNames = NULL;
    %endif
    mxArray * %<rtdwMxName> =
      mxCreateStructMatrix(1, 1, %<rtdwList.numItems>, %<rtdwMxName>FieldNames);
 
  %selectfile setDWorkDeclarationsBuffer
 
  {
    const mxArray * %<rtdwMxName> =
      mxGetFieldByNumber(%<ssMxName>, 0, %<ssMxIndex>);
 
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteGetSetRTDWEpilogue
%%Abstract:Terminatetheblockscopethatcaches/restoresthertdwstruct.
%%
%function SLibWriteGetSetRTDWEpilogue(...
    rtdwMxName, ssMxName, ssMxIndex, ...
    getDWorkBodyBuffer, setDWorkBodyBuffer) void
   
  %selectfile getDWorkBodyBuffer
 
    mxSetFieldByNumber(%<ssMxName>, 0, %<ssMxIndex>, %<rtdwMxName>);
  }
   
  %selectfile setDWorkBodyBuffer
 
  }
 
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteGetSetRTDWItems
%%Abstract:Writesthecodethatcaches/restorestheMdlrefDWcontents.
%%
%%Thiscreatesarecordofcommonly-useditemssuchasloopvariablenames,
%%alongwiththeworkspaceusedtocomputeoffsetswhenmarshallingDWORKS
%%containedwithinaForEachSS.Afterthisrecordiscreated,recursethe
%%treeandpopulatetheloopbodies.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibWriteGetSetRTDWItems(...
    rtdwTree, rtdwList, maxLoopDepth, rtdwMxName, ...
    getDWorkDeclarationsBuffer, setDWorkDeclarationsBuffer, ...
    getDWorkPreambleBuffer, setDWorkPreambleBuffer, ...
    getDWorkBodyBuffer, setDWorkBodyBuffer) void
 
  %createrecord forEachDims { numDims 0; maxDims %<maxLoopDepth> }
 
  %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
  %% If we are generating loop bodies, pre-generate the variable names and
  %% emit code declaring the loop counter variables. Since we may have multiple
  %% loop scopes, we emit the offsetN variable at the start of each loop body
  %% instead of declaring them with the loop counter. Loop counts are written
  %% as numeric literals.
  %%
  %foreach loopIdx = maxLoopDepth
 
    %addtorecord forEachDims dim { size 0 }
 
    %assign loopVarName = "k" + "%<loopIdx>"
 
    %addtorecord forEachDims loopVar { name loopVarName }
    %addtorecord forEachDims offsetVar { name "offset%<loopIdx>" }
 
    %selectfile getDWorkDeclarationsBuffer
 
    int %<loopVarName>;
 
    %selectfile setDWorkDeclarationsBuffer
 
    int %<loopVarName>;
 
  %endforeach
 
  %<SLibTraverseAndGenerateGetSetRTDWItems(...
    rtdwTree, rtdwList, forEachDims, "", rtdwMxName, ...
    getDWorkPreambleBuffer, setDWorkPreambleBuffer, ...
    getDWorkBodyBuffer, setDWorkBodyBuffer)>
 
%endfunction
 
%%===========================================================================|
%%Function:SLibTraverseAndGenerateGetSetRTDWItems
%%Abstract:RecursivelydescendtheintermediatetreeofDWORKitems.
%%
%%DWORKscontainedinsideatomicSSswithinaForEachSSarefoldedintotheir
%%enclosingForEachSS.Onentry,wewriteoutallDWORKitemsthatarenot
%%containedwithinaForEachSS,thentraversethetreeofeachForEachSS.
%%Ateachlevel,weopenanewloopbodyonentryandcloseitonexit.
%%
%%Withinagivenloopbody,thennumberofcopiesofallDWORKSatthatlevel
%%ofthetreearefixed.Thisnumberisstoredinthevariable"offset{0,...}"
%%andusedwhereappropriate.
%%
%%MemoryallocationforeachDWORKhappensinthepreamble.ForMdlrefDWand
%%bitfieldtypes,acellmatrixiscreated.Allotheritemsaremarshalled
%%intoanappropriately-sizeduint8_Tarray.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/modelVariants/tInactiveVariants.m
%%
%function SLibTraverseAndGenerateGetSetRTDWItems(...
  rtdwTree, rtdwList, forEachDims, prefixName, rtdwMxName, ...
  getDWorkPreambleBuffer, setDWorkPreambleBuffer, ...
  getDWorkBodyBuffer, setDWorkBodyBuffer) void
 
  %assert 0 == rtdwTree.numberOfIterations
  %assert WHITE_SPACE(prefixName)
 
  %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
  %% Emit code for Model blocks
  %%
  %foreach modelIdx = rtdwTree.numModelBlocks
    %assign thisBlock = rtdwTree.modelBlock[modelIdx]
    %assign modelName = thisBlock.modelName
    %assign dwIndex = thisBlock.index
    %assign dwName = rtdwList.item[dwIndex].value
    %assign dwCast = ISFIELD(thisBlock, "mdlrefDWorkType") ? ...
      "(%<thisBlock.mdlrefDWorkType>*)" : ""
    %assign isSingleInstanceModelBlock = WHITE_SPACE(thisBlock.dwName)
 
    %selectfile getDWorkBodyBuffer
    {
      
    %if isSingleInstanceModelBlock
      mxArray* varData = %<SLibCreateGetDWorkFcnNameForModel(modelName)>();
    %else
      mxArray* varData = %<SLibCreateGetDWorkFcnNameForModel(modelName)>(/
        %<dwCast> &(%<dwName>));
    %endif
      mxSetFieldByNumber(%<rtdwMxName>, 0, %<dwIndex>, varData);
    }
 
    %selectfile setDWorkBodyBuffer
     
    %if isSingleInstanceModelBlock
      %<SLibCreateSetDWorkFcnNameForModel(modelName)>(/
      mxGetFieldByNumber(%<rtdwMxName>, 0, %<dwIndex>));
    %else
      %<SLibCreateSetDWorkFcnNameForModel(modelName)>(
        %<dwCast> &(%<dwName>),
        mxGetFieldByNumber(%<rtdwMxName>, 0, %<dwIndex>));
    %endif
 
  %endforeach
 
  %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
  %% Emit code for this model's DWORKs
  %%
  %foreach stateIdx = rtdwTree.numStateItems
    %assign thisState = rtdwTree.stateItem[stateIdx]
    %assign numBits = thisState.bitFieldWidth
 
    %assign dwIndex = thisState.index
    %assign dwName = rtdwList.item[dwIndex].value
 
    %if 0 != numBits
      %<SLibWriteCacheRestoreBitFieldToFromMxArray(...
        dwName, rtdwMxName, dwIndex, ...
        numBits, getDWorkBodyBuffer, setDWorkBodyBuffer)>
    %else
      %<SLibWriteCacheRestoreVariableToFromMxArray(...
        dwName, rtdwMxName, dwIndex, ...
        getDWorkBodyBuffer, setDWorkBodyBuffer)>
    %endif
 
  %endforeach
 
  %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
  %% Recursively emit code for For Each SS blocks
  %%
  %foreach ssIdx = rtdwTree.numForEachSSs
 
    %<SLibGenerateForEachGetSetRTDWItems(...
      rtdwTree.forEachSS[ssIdx], rtdwList, forEachDims, ...
      rtdwTree.prefixName, rtdwMxName, ...
      getDWorkPreambleBuffer, setDWorkPreambleBuffer, ...
      getDWorkBodyBuffer, setDWorkBodyBuffer)>
 
  %endforeach
 
%endfunction
 
%%===========================================================================|
%%Function:SLibGenerateForEachGetSetRTDWItems
%%Abstract:Emitcodetocache/restoreDWORKitemsthatareinsidea
%%ForEachSShierarchy.
%%
%%RecursesoneveryForEachSSitcontains.
%%
%function SLibGenerateForEachGetSetRTDWItems(...
  rtdwTree, rtdwList, forEachDims, prefixName, rtdwMxName, ...
  getDWorkPreambleBuffer, setDWorkPreambleBuffer, ...
  getDWorkBodyBuffer, setDWorkBodyBuffer) void
 
  %assert 0 < rtdwTree.numberOfIterations
  %assert !WHITE_SPACE(prefixName)
 
  %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
  %% Setup up dimensions and loop variables
  %%
  %assign loopVarName = forEachDims.loopVar[forEachDims.numDims].name
  %assign fullPrefix = "%<prefixName>.%<rtdwTree.prefixName>[%<loopVarName>]"
 
  %assign forLoopStatement = ...
    "for(" + loopVarName + " = 0; " ...
      + loopVarName + " < " + "%<rtdwTree.numberOfIterations>" + "; " ...
      + "++" + loopVarName + ")"
 
  %assign forEachDims.dim[forEachDims.numDims].size = rtdwTree.numberOfIterations
  %assign offsetVarName = forEachDims.offsetVar[forEachDims.numDims].name
  %assign forEachDims.numDims = forEachDims.numDims + 1
  %assign loopOffsetStatement = SLibGetOffsetDefinitionForLoop(forEachDims)
  %assign matrixSize = SLibGetMatrixSizeForLoop(forEachDims)
 
  %selectfile getDWorkBodyBuffer
 
  %<forLoopStatement>
  {
    %<loopOffsetStatement>
 
  %selectfile setDWorkBodyBuffer
 
  %<forLoopStatement>
  {
    %<loopOffsetStatement>
 
  %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
  %% Emit code for Model blocks
  %%
  %foreach modelIdx = rtdwTree.numModelBlocks
    %assign thisBlock = rtdwTree.modelBlock[modelIdx]
    %assign modelName = thisBlock.modelName
    %assign dwIndex = thisBlock.index
    %assign dwName = fullPrefix + "." + thisBlock.dwName
 
    %if WHITE_SPACE(thisBlock.dwName)
      %<SLibReportErrorWithIdAndArgs(...
        "Simulink:modelReference:InternalCodeGenerationError", ...
        Name + ": Single-instance Model block within For Each Subsystem")>
    %endif
 
    %selectfile getDWorkPreambleBuffer
 
    mxSetFieldByNumber(%<rtdwMxName>, 0, %<dwIndex>, /
      mxCreateCellMatrix(1, %<matrixSize>));
 
    %selectfile getDWorkBodyBuffer
    {
      
      mxArray* varData = %<SLibCreateGetDWorkFcnNameForModel(modelName)>( /
        &(%<dwName>));
 
      mxSetCell(mxGetFieldByNumber(%<rtdwMxName>, 0, %<dwIndex>), /
        %<offsetVarName>, varData);
    }
 
    %selectfile setDWorkBodyBuffer
 
    %<SLibCreateSetDWorkFcnNameForModel(modelName)>(/
      &(%<dwName>), /
      mxGetCell(mxGetFieldByNumber(%<rtdwMxName>,0, %<dwIndex>), /
      %<offsetVarName>));
 
  %endforeach
 
  %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
  %% Emit code for DWORK items at this level
  %%
  %foreach stateIdx = rtdwTree.numStateItems
    %assign thisState = rtdwTree.stateItem[stateIdx]
    %assign numBits = thisState.bitFieldWidth
 
    %assign dwIndex = thisState.index
    %assign dwName = fullPrefix + "." + thisState.name
 
    %if 0 != numBits
 
      %selectfile getDWorkPreambleBuffer
 
      mxSetFieldByNumber(%<rtdwMxName>, 0, %<dwIndex>, /
        mxCreateCellMatrix(1, %<matrixSize>));
 
      %selectfile getDWorkBodyBuffer
 
      %<SLibGetCacheBitFieldToCellArrayWithOffsetFcnName()>(/
        %<rtdwMxName>, 0, %<dwIndex>, %<offsetVarName>, %<dwName>);
 
      %selectfile setDWorkBodyBuffer
 
      %<dwName> = %<SLibGetExtractBitFieldFromCellArrayWithOffsetFcnName()>(/
        %<rtdwMxName>, 0, %<dwIndex>, %<offsetVarName>, %<numBits>);
 
    %else
 
      %selectfile getDWorkPreambleBuffer
 
      mxSetFieldByNumber(%<rtdwMxName>, 0, %<dwIndex>, /
        mxCreateUninitNumericMatrix( /
          1, /
          %<matrixSize>*sizeof(%), /
          mxUINT8_CLASS, mxREAL));
 
      %selectfile getDWorkBodyBuffer
 
      %<SLibGetCacheDataToMxArrayWithOffsetFcnName()>( /
        %<rtdwMxName>, 0, %<dwIndex>, %<offsetVarName>, /
        &(%<dwName>), sizeof(%));
 
      %selectfile setDWorkBodyBuffer
 
      %<SLibGetRestoreDataFromMxArrayWithOffsetFcnName()>( /
        &(%<dwName>), /
        %<rtdwMxName>, 0, %<dwIndex>, %<offsetVarName>, /
        sizeof(%));
 
    %endif
 
  %endforeach
 
  %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
  %% Recursively emit code for For Each SSs at this level
  %%
  %foreach ssIdx = rtdwTree.numForEachSSs
 
    %<SLibGenerateForEachGetSetRTDWItems(...
      rtdwTree.forEachSS[ssIdx], rtdwList, forEachDims, ...
      fullPrefix, rtdwMxName, ...
      getDWorkPreambleBuffer, setDWorkPreambleBuffer, ...
      getDWorkBodyBuffer, setDWorkBodyBuffer)>
 
  %endforeach
 
  %% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
  %% Close this loop body and decrement the dimensions vector counter
  %%
  %selectfile getDWorkBodyBuffer
  }
 
  %selectfile setDWorkBodyBuffer
  }
 
  %assign forEachDims.numDims = forEachDims.numDims - 1
 
%endfunction
 
%%===========================================================================|
%%Function:SLibGetOffsetDefinitionForLoop
%%Abstract:ComputeanddefinetheoffsetNvariablefortheinnermostloopbody
%%withthespecifieddimensions.Returnsthevariabledefinition
%%statement.
%%
%%ThisistheoffsetintothearrayusedtostoretheinstancesofaDWORK
%%containedwithinaForEachSS.Thevalueis
%%
%%offset_(N_d-1)=Sum_(i=0)_(N_d-1){k_i*Prod_(j=i+1)_(j=N_d-1){l_j}}
%%
%%,where
%%
%%N_d=depthoftheloopnest
%%k_i=loopvariableofthei'thdimension
%%l_j=numberofloopsoverthej'thdimension
%%
%%(WeusetheconventionthatProd_n_n{}=1)
%%
%function SLibGetOffsetDefinitionForLoop(forEachDims)
  %assign offsetVal = ""
 
  %foreach i = forEachDims.numDims
 
    %if i > 0
      %assign offsetVal = offsetVal + " + "
    %endif
 
    %assign offsetVal = offsetVal + forEachDims.loopVar[i].name
 
    %foreach j = forEachDims.numDims
      %if j > i
        %assign offsetVal = offsetVal + "*%"
      %endif
    %endforeach
 
  %endforeach
 
  %return "const mwIndex %" ...
    + " = %<offsetVal>;"
 
%endfunction
 
%%===========================================================================|
%%Function:SLibGetMatrixSizeForLoop
%%Abstract:Foragivenloopnestinglevel,computethenumberoftimesits
%%bodywillbeexecutedandreturnit.
%%
%function SLibGetMatrixSizeForLoop(forEachDims)
  %assign matrixSize = 1
  %foreach i = forEachDims.numDims
    %assign matrixSize = matrixSize * forEachDims.dim[i].size
  %endforeach
  %return matrixSize
%endfunction
 
%%===========================================================================|
%%Function:SLibCreateGetDWorkFcnSigForModel
%%Abstract:Constructthemodel_GetDWorkfunctionsignature.
%%
%function SLibCreateGetDWorkFcnSigForModel(thisModelName)
  %assign getFcnName = SLibCreateGetDWorkFcnNameForModel(Name)
  %assign getFcnArgs = SLibCreateGetDWorkFcnArgs()
  %return "mxArray * %<getFcnName>%<getFcnArgs>"
%endfunction
 
%%===========================================================================|
%%Function:SLibCreateSetDWorkFcnSigForModel
%%Abstract:Constructthemodel_SetDWorkfunctionsignature.
%%
%function SLibCreateSetDWorkFcnSigForModel(thisModelName)
  %assign setFcnName = SLibCreateSetDWorkFcnNameForModel(Name)
  %assign setFcnArgs = SLibCreateSetDWorkFcnArgs()
  %return "void %<setFcnName>%<setFcnArgs>"
%endfunction
 
%%===========================================================================|
%%Function:SLibCreateGetDWorkFcnNameForModel
%%Abstract:Createsthemodel_GetDWorkfunctionname.
%%
%function SLibCreateGetDWorkFcnNameForModel(thisModelName)
  %return "mr_%<thisModelName>_GetDWork"
%endfunction
 
%%===========================================================================|
%%Function:SLibGetMdlrefDWPtrName
%%Abstract:SinglepointofdefinitionforthepointertotheMdlrefDWstruct.
%%
%function SLibGetMdlrefDWPtrName()
  %return "mdlrefDW"
%endfunction
 
%%===========================================================================|
%%Function:SLibCreateGetDWorkFcnArgs
%%Abstract:Gettheargumentsignatureforthemr_model_GetDWorkfunction.
%%Ifthemodelissingle-instance,thenitownsitsDWorkand
%%takesnoarguments.
%%
%function SLibCreateGetDWorkFcnArgs()
  %if ::CompiledModel.OkToMultiInstanceModelref
    %return "(const %<tsysMdlrefDWorkType> * %<SLibGetMdlrefDWPtrName()>)"
  %endif
  %return "()"
%endfunction
 
%%===========================================================================|
%%Function:SLibCreateSetDWorkFcnNameForModel
%%Abstract:Createsthemodel_SetDWorkfunctionname.
%%
%function SLibCreateSetDWorkFcnNameForModel(thisModelName)
  %return "mr_%<thisModelName>_SetDWork"
%endfunction
 
%%===========================================================================|
%%Function:SLibCreateSetDWorkFcnArgs
%%Abstract:Gettheargumentsignatureforthemodel_SetDWorkfunction.
%%Ifthemodelissingle-instance,thenitownsitsDWorkand
%%onlyneedsapointertothedataitcachedinthegetter.
%%
%function SLibCreateSetDWorkFcnArgs()
  %if ::CompiledModel.OkToMultiInstanceModelref
    %assign mdlrefDW = SLibGetMdlrefDWPtrName()
    %return "(%<tsysMdlrefDWorkType> * %<mdlrefDW>, const mxArray* ssDW)"
  %endif
  %return "(const mxArray* ssDW)"
%endfunction
 
%%===========================================================================|
%%Function:SLibCreateGetSimStateDisallowedBlocksFcnSigForModel
%%Abstract:Createthefunctionsignatureforthefunction
%%mr_model_GetSimStateDisallowedBlocks.
%%
%function SLibCreateGetSimStateDisallowedBlocksFcnSigForModel(thisModelName)
  %assign fcnName = ...
    SLibCreateGetSimStateDisallowedBlocksFcnNameForModel(thisModelName)
 
  %assign fcnArgs = SLibCreateGetSimStateDisallowedBlocksFcnArgs()
 
  %return "mxArray * %<fcnName>%<fcnArgs>"
%endfunction
 
%%===========================================================================|
%%Function:SLibCreateGetSimStateDisallowedBlocksFcnArgs
%%Abstract:Gettheargumentsignatureforthefunction
%%mr_model_GetSimStateDisallowedBlocks.
%%
%function SLibCreateGetSimStateDisallowedBlocksFcnArgs()
  %return "()"
%endfunction
 
%%===========================================================================|
%%Function:SLibCreateGetSimStateDisallowedBlocksFcnNameForModel
%%Abstract:Createthemr_model__GetSimStateDisallowedBlocksfunctionname.
%%
%function SLibCreateGetSimStateDisallowedBlocksFcnNameForModel(thisModelName)
  %return "mr_%<thisModelName>_GetSimStateDisallowedBlocks"
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteCacheRestoreBitFieldToFromMxArray
%%Abstract:Addcodetocache/restorethespecifiedvariable
%%totheappropriatebuffers.
%%
%function SLibWriteCacheRestoreBitFieldToFromMxArray(...
    varName, mxName, mxIndex, numBits, getBuffer, setBuffer) void
   
  %selectfile getBuffer
  %<SLibGetCacheBitFieldToMxArrayFcnName()>(
    %<mxName>, 0, %<mxIndex>, (uint_T) %<varName>);
 
  %selectfile setBuffer
  %<varName> = %<SLibGetExtractBitFieldFromMxArrayFcnName()>(
    %<mxName>, 0, %<mxIndex>, %<numBits>);
 
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteCacheRestoreVariableToFromMxArray
%%Abstract:Addcodetocache/restorethespecifiedvariable
%%totheappropriatebuffers.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibWriteCacheRestoreVariableToFromMxArray(...
    varName, mxName, mxIndex, getBuffer, setBuffer) void
  %selectfile getBuffer
  %<SLibGetCacheDataAsMxArrayFcnName()>(
    %<mxName>, 0, %<mxIndex>, &(%<varName>), sizeof(%<varName>));
  
  %selectfile setBuffer
  %<SLibGetRestoreDataFromMxArrayFcnName()>(
    &(%<varName>), %<mxName>, 0, %<mxIndex>, sizeof(%<varName>));
 
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteMdlRefCacheBitFieldToMxArrayFcn
%%Abstract:Constructthemr_cacheBitFieldToMxArrayfunction.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibWriteMdlRefCacheBitFieldToMxArrayFcn() void
  %assign fcnArgs = "(mxArray * destArray, mwIndex i, int j, uint_T bitVal)"
  %assign fcnSig = ...
    "static void %<SLibGetCacheBitFieldToMxArrayFcnName()>%<fcnArgs>"
 
  %openfile fcnBuffer
  %<fcnSig>;
  %<fcnSig>
  {
    %% This seems brittle to me: What if someone creates a 64-bit wide field?
    %% A double can only encode 51 bits. Hopefully a compiler warning will
    %% tip the user off.
    %%
    mxSetFieldByNumber(destArray, i, j, mxCreateDoubleScalar((double) bitVal));
  }
  %closefile fcnBuffer
 
  %<SLibCacheCodeToFile("mdl_fcn_defn", fcnBuffer)>
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteMdlRefExtractBitFieldFromMxArrayFcn
%%Abstract:Constructthemr_extractBitFieldFromMxArrayfunction.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibWriteMdlRefExtractBitFieldFromMxArrayFcn() void
  %assign fcnArgs = ...
    "(const mxArray * srcArray, mwIndex i, int j, uint_T numBits)"
  %assign fcnSig = ...
    "static uint_T %<SLibGetExtractBitFieldFromMxArrayFcnName()>%<fcnArgs>"
 
  %openfile fcnBuffer
  %<fcnSig>;
  %<fcnSig>
  {
    const uint_T varVal = (uint_T) mxGetScalar(mxGetFieldByNumber(srcArray, i, j));
    return varVal & ((1u<  }
  %closefile fcnBuffer
 
  %<SLibCacheCodeToFile("mdl_fcn_defn", fcnBuffer)>
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteMdlRefCacheDataAsMxArrayFcn
%%Abstract:Constructthemr_cacheDataAsMxArrayfunction.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibWriteMdlRefCacheDataAsMxArrayFcn() void
  %assign fcnArgs = ...
    "(mxArray * destArray, mwIndex i, int j, const void * srcData, size_t numBytes)"
  %assign fcnSig = ...
    "static void %<SLibGetCacheDataAsMxArrayFcnName()>%<fcnArgs>"
 
  %openfile fcnBuffer
  %<fcnSig>;
  %<fcnSig>
  {
    mxArray * newArray =
      mxCreateUninitNumericMatrix((size_t) 1, numBytes, mxUINT8_CLASS, mxREAL);
    memcpy((uint8_T *) mxGetData(newArray), (const uint8_T *) srcData, numBytes);
    mxSetFieldByNumber(destArray, i, j, newArray);
  }
  %closefile fcnBuffer
 
  %<SLibCacheCodeToFile("mdl_fcn_defn", fcnBuffer)>
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteMdlRefRestoreDataFromMxArrayFcn
%%Abstract:Constructthemr_restoreDataFromMxArrayfunction.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibWriteMdlRefRestoreDataFromMxArrayFcn() void
  %assign fcnArgs = ...
    "(void * destData, const mxArray * srcArray, mwIndex i, int j, size_t numBytes)"
  %assign fcnSig = ...
    "static void %<SLibGetRestoreDataFromMxArrayFcnName()>%<fcnArgs>"
 
  %openfile fcnBuffer
  %<fcnSig>;
  %<fcnSig>
  {
    memcpy((uint8_T *) destData,
           (const uint8_T *) mxGetData(mxGetFieldByNumber(srcArray, i, j)),
           numBytes);
  }
  %closefile fcnBuffer
 
  %<SLibCacheCodeToFile("mdl_fcn_defn", fcnBuffer)>
%endfunction
 
%%===========================================================================|
%%Function:SLibGetCacheBitFieldToMxArrayFcnName
%%Abstract:Canonicalgetterforthenameofthisstaticutilityfunction.
%%
%function SLibGetCacheBitFieldToMxArrayFcnName()
  %return "mr_%<::CompiledModel.Name>_cacheBitFieldToMxArray"
%endfunction
 
%%===========================================================================|
%%Function:SLibGetExtractBitFieldFromMxArrayFcnName
%%Abstract:Canonicalgetterforthenameofthisstaticutilityfunction.
%%
%function SLibGetExtractBitFieldFromMxArrayFcnName()
  %return "mr_%<::CompiledModel.Name>_extractBitFieldFromMxArray"
%endfunction
 
%%===========================================================================|
%%Function:SLibGetCacheDataAsMxArrayFcnName
%%Abstract:Canonicalgetterforthenameofthisstaticutilityfunction.
%%
%function SLibGetCacheDataAsMxArrayFcnName()
  %return "mr_%<::CompiledModel.Name>_cacheDataAsMxArray"
%endfunction
 
%%===========================================================================|
%%Function:SLibGetRestoreDataFromMxArrayFcnName
%%Abstract:Canonicalgetterforthenameofthisstaticutilityfunction.
%%
%function SLibGetRestoreDataFromMxArrayFcnName()
  %return "mr_%<::CompiledModel.Name>_restoreDataFromMxArray"
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteMdlRefCacheDataToMxArrayWithOffsetFcn
%%Abstract:Constructthemr_cacheDataToMxArrayWithOffsetfunction.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibWriteMdlRefCacheDataToMxArrayWithOffsetFcn() void
  %assign fcnArgs = ...
    "(mxArray * destArray, mwIndex i, int j, mwIndex offset, const void * srcData, size_t numBytes)"
  %assign fcnSig = "static void %<SLibGetCacheDataToMxArrayWithOffsetFcnName()>%<fcnArgs>"
 
  %openfile fcnBuffer
  %<fcnSig>;
  %<fcnSig>
  {
    uint8_T * varData = /
      (uint8_T *) mxGetData(mxGetFieldByNumber(destArray, i, j));
 
    memcpy( /
      (uint8_T *) &varData[offset*numBytes], /
      (const uint8_T *) srcData, /
      numBytes);
  }
  %closefile fcnBuffer
 
  %<SLibCacheCodeToFile("mdl_fcn_defn", fcnBuffer)>
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteMdlRefRestoreDataFromMxArrayWithOffsetFcn
%%Abstract:Constructthemr_restoreDataFromMxArrayWithOffsetfunction.
%%
%function SLibWriteMdlRefRestoreDataFromMxArrayWithOffsetFcn() void
  %assign fcnArgs = ...
    "(void * destData, const mxArray * srcArray, mwIndex i, int j, mwIndex offset, size_t numBytes)"
  %assign fcnSig = ...
    "static void %<SLibGetRestoreDataFromMxArrayWithOffsetFcnName()>%<fcnArgs>"
 
  %openfile fcnBuffer
  %<fcnSig>;
  %<fcnSig>
  {
    const uint8_T * varData = /
      (const uint8_T *) mxGetData(mxGetFieldByNumber(srcArray, i, j));
 
    memcpy( /
      (uint8_T *) destData, /
      (const uint8_T *) &varData[offset*numBytes], /
      numBytes);
  }
  %closefile fcnBuffer
 
  %<SLibCacheCodeToFile("mdl_fcn_defn", fcnBuffer)>
%endfunction
 
%%===========================================================================|
%%Function:SLibGetCacheDataToMxArrayWithOffsetFcnName
%%Abstract:Canonicalgetterforthenameofthisstaticutilityfunction.
%%
%function SLibGetCacheDataToMxArrayWithOffsetFcnName()
  %return "mr_%<::CompiledModel.Name>_cacheDataToMxArrayWithOffset"
%endfunction
 
%%===========================================================================|
%%Function:SLibGetRestoreDataFromMxArrayWithOffsetFcnName
%%Abstract:Canonicalgetterforthenameofthisstaticutilityfunction.
%%
%function SLibGetRestoreDataFromMxArrayWithOffsetFcnName()
  %return "mr_%<::CompiledModel.Name>_restoreDataFromMxArrayWithOffset"
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteMdlRefCacheBitFieldToCellArrayWithOffsetFcn
%%Abstract:Constructthemr_cacheBitFieldToCellArrayWithOffsetfunction.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibWriteMdlRefCacheBitFieldToCellArrayWithOffsetFcn() void
  %assign fcnArgs = ...
    "(mxArray * destArray, mwIndex i, int j, mwIndex offset, uint_T fieldVal)"
  %assign fcnSig = ...
    "static void %<SLibGetCacheBitFieldToCellArrayWithOffsetFcnName()>%<fcnArgs>"
 
  %openfile fcnBuffer
  %<fcnSig>;
  %<fcnSig>
  {
    mxSetCell(mxGetFieldByNumber(destArray, i, j), offset, /
      mxCreateDoubleScalar((double) fieldVal));
  }
  %closefile fcnBuffer
 
  %<SLibCacheCodeToFile("mdl_fcn_defn", fcnBuffer)>
%endfunction
 
%%===========================================================================|
%%Function:SLibWriteMdlRefExtractBitFieldFromCellArrayWithOffsetFcn
%%Abstract:Constructthemr_extractBitFieldFromCellArrayWithOffsetfunction.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibWriteMdlRefExtractBitFieldFromCellArrayWithOffsetFcn() void
  %assign fcnArgs = ...
    "(const mxArray * srcArray, mwIndex i, int j, mwIndex offset, uint_T numBits)"
  %assign fcnSig = ...
    "static uint_T %<SLibGetExtractBitFieldFromCellArrayWithOffsetFcnName()>%<fcnArgs>"
 
  %openfile fcnBuffer
  %<fcnSig>;
  %<fcnSig>
  {
    const uint_T fieldVal = /
      (uint_T) mxGetScalar(mxGetCell(mxGetFieldByNumber(srcArray, i, j), offset));
 
    return fieldVal & ((1u << numBits) - 1u);
  }
  %closefile fcnBuffer
 
  %<SLibCacheCodeToFile("mdl_fcn_defn", fcnBuffer)>
%endfunction
 
%%===========================================================================|
%%Function:SLibGetCacheBitFieldToCellArrayWithOffsetFcnName
%%Abstract:Canonicalgetterforthenameofthisstaticutilityfunction.
%%
%function SLibGetCacheBitFieldToCellArrayWithOffsetFcnName()
  %return "mr_%<::CompiledModel.Name>_cacheBitFieldToCellArrayWithOffset"
%endfunction
 
%%===========================================================================|
%%Function:SLibGetExtractBitfieldFromCellArrayWithOffsetFcnName
%%Abstract:Canonicalgetterforthenameofthisstaticutilityfunction.
%%
%function SLibGetExtractBitFieldFromCellArrayWithOffsetFcnName()
  %return "mr_%<::CompiledModel.Name>_extractBitFieldFromCellArrayWithOffset"
%endfunction
 
%%===========================================================================|
%%ENDModelRefAccelModeSimStatesupport
%%===========================================================================|
 
%%Writeexportedmodelinformationtothemodel_msf.c.
%function SLibWriteMdlRefExportedMdlInfoForModelRef() void
  %with ::CompiledModel
    %openfile tmpBuffer
    int_T retVal = 1;
    %assign regFcnName = SLibCreateMdlInfoRegFcnName()
    %<regFcnName>(S, "%<Name>", &retVal);
    if (!retVal) return;
    %closefile tmpBuffer
  %endwith
  %return tmpBuffer
%endfunction
 
%function SLibCreateMdlInfoRegFcnName() void
  %return "mr_%<Name>_MdlInfoRegFcn"
%endfunction
 
%%Function:FcnInitializeModelRefGlobalTimingEngine===========================
%%Abstract:
%%Declarealltheglobalvariablesnecessaryfortheglobaltimingengine
%%andinitializethesevariablesintheregistrationfunction
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/tVariantGecks.m
%%TopTester:test/toolbox/simulink/variants/tVariantGecks6.m
%%
%function FcnInitializeModelRefGlobalTimingEngine() Output
  %assert IsModelReferenceTarget()
 
  %% Write out the declaration of the global TID map. Note that for inherited
  %% submodels, we will put the map into the rtModel. This is because each
  %% instance the submodel could get a different TID and we need the TID
  %% for logging.
  %assign numTIDs = SLibGetNumTIDsForGlobalTIDMap()
 
  %openfile cbuffer
  %if ::tMdlRefGlobalTIDMapAccessed
    %if MdlRefIsConstSampleBlock() && !MdlRefHasParameterRate()
      int_T %<::tMdlRefGlobalTID>[1];
    %elseif !RTMMdlRefGlobalTIDIsInstanceBased()
      int_T %<::tMdlRefGlobalTID>[%<numTIDs>];
    %endif
  %endif
  %if !IsModelReferenceForASimstructBasedTarget() && ...
    ::tMdlRefTimingBridgeAccessed && !RTMTimingBridgeIsReqFcn()
    %assert SLibIsERTCodeFormat()
    const rtTimingBridge *%<SLibGetGlobalTimingBridge()>;
  %endif
  %closefile cbuffer
  %<SLibCacheCodeToFile("mdl_data_defn", cbuffer)>
   
  %openfile hpbuffer
  %if ::tMdlRefGlobalTIDMapAccessed
    %if MdlRefIsConstSampleBlock() && !MdlRefHasParameterRate()
      extern int_T %<::tMdlRefGlobalTID>[1];
    %elseif !RTMMdlRefGlobalTIDIsInstanceBased()
      extern int_T %<::tMdlRefGlobalTID>[%<numTIDs>];
    %endif
  %endif
  %if !IsModelReferenceForASimstructBasedTarget() && ...
    ::tMdlRefTimingBridgeAccessed && !RTMTimingBridgeIsReqFcn()
    %assert SLibIsERTCodeFormat()
    extern const rtTimingBridge *%<SLibGetGlobalTimingBridge()>;
  %endif
  %closefile hpbuffer
  %<SLibCacheCodeToFile("mdl_priv_extern_data_decl", hpbuffer)>
 
  %if !GenerateClassInterface
    %if ::tMdlRefGlobalTIDMapAccessed
      /* setup the global timing engine */
      %if !MdlRefIsConstSampleBlock() || MdlRefHasParameterRate()
        %foreach idx = numTIDs
          %% skip service task tid which is
          %% used for service infrastructure only
          %if SLibIsServiceTaskTID(idx)
            %continue
          %endif
          %<FcnGetMdlRefGlobalTIDMap("")>[%<idx>] = mdlref_TID%<idx>;
        %endforeach
      %else
        %<::tMdlRefGlobalTID>[0] = mdlref_TID0;
      %endif
       
      %if RTMMdlRefTriggerTIDIsReqFcn()
        %<FcnGetMdlRefTriggerTIDMap("")> = mdlref_TriggerTID;
      %endif
    %endif
     
    %if !IsModelReferenceForASimstructBasedTarget() && ...
      ::tMdlRefTimingBridgeAccessed
      %assert SLibIsERTCodeFormat()
      %if RTMTimingBridgeIsReqFcn()
        %% Set timing bridge of rtm
        %<RTMSet("timingBridge", "timingBridge")>;
      %else
        %<SLibGetGlobalTimingBridge()> = timingBridge;
      %endif
    %endif
  %endif
%endfunction
 
%%Function:FcnInitializeNoncontSignals=======================================
%%Abstract:
%%Writeoutthedeclarationandinitializationofthedatastructuresfor
%%handlinginformationonnoncontinoussignalscomingfrommodelreference
%%blocks.WecreateanarrayoftypessNonContDerivSigforeachmodel
%%referenceblock,andinitializetheoutportsthatweneedinformationfor.
%%TopTester:test/toolbox/simulink/variants/modelVariants/tVariantsBasic_g724566.m
%%
%function FcnInitializeNoncontSignals() Output
  %if !HasModelReferenceBlocks()
    %return
  %endif
  %% Declare all the arrays
  %assign mdlRefBlks = ::CompiledModel.ModelReferenceBlocks
  %openfile declbuf
  %openfile codebuf
  %foreach rowIdx = SIZE(mdlRefBlks,0)
    %assign mdlRefInfo = mdlRefBlks[rowIdx]
    %assign mSysIdx = mdlRefInfo[0]
    %assign bIdx = mdlRefInfo[1]
    %assign instIdx = mdlRefInfo[2]
    %assign blk = ::CompiledModel.System[mSysIdx].Block[bIdx]
    %% The usage of the first instance modelBlock is OK here because
    %% all corresponding instances across parent reusable subsystems
    %% must have a consistent state
    %assert 0 == blk.DeletedInIR
    %assign name = blk.ParamSettings.ReferencedModelName
    %assign blockInterface = GetModelrefInterface(blk)
    %if blockInterface.HasNonContOutput
      %assign mangleName = FcnGetNoncontMangledName(name, mSysIdx, bIdx, instIdx)
      %selectfile declbuf
      %assign comma = ""
      %% This is an array of pointers of size nOutputPorts. If an
      %% output port has any noncontinuous signals, we'll create
      %% another array to hold all those signals below
      ssNonContDerivSigFeedingOutports *mr_%<mangleName>nonContOutputArray[%<LibBlockNumOutputPorts(blk)>] = {/
      %foreach nullIdx = LibBlockNumOutputPorts(blk)
        %<comma>%<SLibGetNullDefinitionFromTfl()>/
        %assign comma = ", "
      %endforeach
      };
      %assign nonContPorts = blockInterface.NonContOutports
      %foreach pIdx = SIZE(nonContPorts,1)
        %if nonContPorts[pIdx] > 0
          %assign intNumSigs = CAST("Number", nonContPorts[pIdx])
          %selectfile declbuf
          %% Create an array of noncont signals for this port
          ssNonContDerivSigFeedingOutports mr_%<mangleName>nonContDerivSig%<pIdx>[%<intNumSigs>];
          %selectfile codebuf
          mr_%<mangleName>nonContOutputArray[%<pIdx>] = mr_%<mangleName>nonContDerivSig%<pIdx>;
        %endif
      %endforeach
    %endif
  %endforeach
  %closefile declbuf
  %closefile codebuf
  %<declbuf>/
   
  %<codebuf>/
%endfunction
 
%%Function:SLibGenNoncontDerivSigStruct======================================
%%Abstract:
%%Writeoutthestructurewhichholdsthememoryneededwhenlooking
%%atnoncontinuoussignalsfeedingderivports.Thisisformodelref
%%only,andithelpsavoidusingmalloc.
%function SLibGenNoncontDerivSigStruct() void
  %openfile declBuf
   
  /*
   * The following structure contains memory needed to
   * track noncontinuous signals feeding derivative ports.
   */
   struct {
     %assign numNoncontDerivSigs = SIZE(SolverResetInfo.NonContDerivSignal,1)
     %assign arrayIdx = 0
     %foreach idx = numNoncontDerivSigs
       %assign dU = SolverResetInfo.NonContDerivSignal[idx]
       %if ISFIELD(dU,"MdlRefInfo")
         %foreach subIdx = dU.NumMdlRefNonContSigs
           %assign numBytes = dU.NonContSigSizeInBytes[subIdx]
           uint8_T mr_nonContSig%<arrayIdx>[%<numBytes>];
           %assign arrayIdx = arrayIdx + 1
         %endforeach
       %else
         %if dU.ComplexSignal
           %assign dtype = LibGetDataTypeComplexNameFromId(dU.DataTypeIdx)
         %else
           %assign dtype = LibGetDataTypeNameFromId(dU.DataTypeIdx)
         %endif
         %<dtype> mr_nonContSig%<arrayIdx>[%<dU.RegionLen>];
         %assign arrayIdx = arrayIdx + 1
       %endif
     %endforeach
   } /
   %closefile declBuf
   %return declBuf
%endfunction
 
 
%%Function:CPPEncapNeedsLocalVars======================================
%%Abstract:
%%DoesC++encapsulationinterfaceneedstointroducelocalvariablesto
%%modelregestrationfunction?
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function CPPEncapNeedsLocalVars(genERTSfcn) void
   %assign hasDWork = ! SLibModelDWorkStructIsEmpty()
   %assign dworkZeroed = TLC_FALSE
    
   %if hasDWork && (!(ForceBlockIOInitOptimize && IsModelReferenceTarget()))
      %assign dworkZeroed = SLibZeroMemory("DWork")
   %endif
    
   %if hasDWork && genERTSfcn
      %% SIL requires DWork (if existing) to be Zeroed regardless user setting.
      %% See the callsite to SLibDumpERTAndModelrefInitMemoryCode in ertsfcnbody.tlc
      %assign dworkZeroed = TLC_TRUE
   %endif
    
   %return GenerateClassInterface && ...
           CGMODEL_ACCESS("CGModel.getUseOperatorNewForModelRefRegistration") && ...
           dworkZeroed
%endfunction %% CPPEncapNeedsLocalVars
 
 
%%Function:SLibGetCPPEncapInitLocalVars================================
%%Abstract:
%%Determinewhatlocalvariableswillbeneededforcppencapsulation
%%inthemodelinitializationfunction;mustbeguardedby
%%CPPEncapNeedsLocalVars
 
%function SLibGetCPPEncapInitLocalVars(genERTSFcn) void
  %assert CPPEncapNeedsLocalVars(genERTSFcn)
   
  %assign localVars = ""
   
  %assign mdlRefBlks = ISFIELD(::CompiledModel,"ModelReferenceBlocks") ? ...
    ::CompiledModel.ModelReferenceBlocks : []
   
   
  %if !ISEMPTY(mdlRefBlks)
    %assign NO_PARENT = ""
    %assign NO_QUALIFIER = ""
    %assign ERT_MACRO_NONE = [0, 0, 0, 0]
     
    %foreach rowIdx = SIZE(mdlRefBlks,0)
      %assign mdlRefInfo = mdlRefBlks[rowIdx]
      %assign mSysIdx = mdlRefInfo[0]
      %assign bIdx = mdlRefInfo[1]
      %assign instIdx = mdlRefInfo[2]
      %% The usage of the first instance modelBlock is OK here because
      %% all corresponding instances across parent reusable subsystems
      %% must have a consistent state
      %assign blk = ::CompiledModel.System[mSysIdx].Block[bIdx]
      %assert 0 == blk.DeletedInIR
     
      %if !blk.MdlRefIsCPPClassGenMode
         %continue
      %endif
       
      %assign blkInterface = GetModelrefInterface(blk)
       
      %if blkInterface.IsScalableBuild || IsSystemReusableParentBaseSys(mSysIdx)
            %continue
      %endif
       
      %assign locVarName = "local_" + ::CompiledModel.ModelBlock[rowIdx].MdlRefInstanceVarName
      %assign mdlBlkCompiledModel = ::CompiledModel.ModelBlock[rowIdx]
      %assign optDim = ""
      %if ISFIELD(mdlBlkCompiledModel, "ForEachSSLoopBnds")
          %assign tmpLevel = SIZE(mdlBlkCompiledModel.ForEachSSLoopBnds,1)
          %foreach ssIdx = SIZE(mdlBlkCompiledModel.ForEachSSLoopBnds,1)
            %assign tmpLevel = tmpLevel - 1
            %assign optDim = optDim + "[%]"
          %endforeach
      %endif
                                             
      %openfile tmpBuf
         %assign namespaceStr = ""
         %if EXISTS(blkInterface.FPC.ClassNamespace) && (!ISEMPTY(blkInterface.FPC.ClassNamespace))
           %assign namespaceStr = "%<blkInterface.FPC.ClassNamespace>::"
         %endif
          
         %if ISEMPTY(optDim)
           %<namespaceStr>%<blkInterface.FPC.ModelClassName>_ptr %<locVarName>;
         %else
           %<namespaceStr>%<blkInterface.FPC.ModelClassName>_ptr %<locVarName>%<optDim>;
         %endif
      %closefile tmpBuf
       
      %assign localVars = localVars + tmpBuf
    %endforeach
  %endif
   
  %return localVars
   
%endfunction %% SLibGetCPPEncapInitLocalVars
 
 
%%Function:SLibGetCPPEncapInitCopyCode================================
%%Abstract:
%%Determinethecodeneededtocopythereferencedmodelobjectpointerssothat
%%laterwecanrestorethemaftertheDWorkhasbeenZeroed,inthemodelinitializationfunction;
%%ItmustbeguardedbyCPPEncapNeedsLocalVars.Theargumentisabooleanflagtoindicatethatit
%%isabackupoperationorarestoreoperation.
%function SLibGetCPPEncapInitCopyCode(isBackup, genERTSfcn) void
  %assert CPPEncapNeedsLocalVars(genERTSfcn)
   
  %assign copyCode = ""
   
  %assign mdlRefBlks = ISFIELD(::CompiledModel,"ModelReferenceBlocks") ? ...
    ::CompiledModel.ModelReferenceBlocks : []
   
   
  %if !ISEMPTY(mdlRefBlks)
    %assign NO_PARENT = ""
    %assign NO_QUALIFIER = ""
    %assign ERT_MACRO_NONE = [0, 0, 0, 0]
     
    %foreach rowIdx = SIZE(mdlRefBlks,0)
      %assign mdlRefInfo = mdlRefBlks[rowIdx]
      %assign mSysIdx = mdlRefInfo[0]
      %assign bIdx = mdlRefInfo[1]
      %assign instIdx = mdlRefInfo[2]
      %% The usage of the first instance modelBlock is OK here because
      %% all corresponding instances across parent reusable subsystems
      %% must have a consistent state
      %assign blk = ::CompiledModel.System[mSysIdx].Block[bIdx]
      %assert 0 == blk.DeletedInIR
       
      %if !blk.MdlRefIsCPPClassGenMode
         %continue
      %endif
       
      %assign blkInterface = GetModelrefInterface(blk)
      
      %if blkInterface.IsScalableBuild || IsSystemReusableParentBaseSys(mSysIdx)
            %continue
      %endif
       
      %assign locVarName = "local_" + ::CompiledModel.ModelBlock[rowIdx].MdlRefInstanceVarName
 
      %assign mdlBlkCompiledModel = ::CompiledModel.ModelBlock[rowIdx]
 
 
      %openfile tmpBuf
        %if !ISFIELD(mdlBlkCompiledModel, "ForEachSSLoopBnds")
          %assign cppVarPath = SLibCalcMdlRefObjSubsysAccessPath(mSysIdx,...
                                bIdx,instIdx,"Registration")
          %if isBackup
            %<locVarName> = %<cppVarPath>;
          %else
            %<cppVarPath> = %<locVarName>;
          %endif
        %else
          %assign ::NeedForEachLoopInReg = TLC_TRUE
          %assign ::NumForEachLoopHierarchyLevel = SIZE(mdlBlkCompiledModel.ForEachSSLoopBnds,1)
          %assign ::ForEachLoopHierarchyLevel = ::NumForEachLoopHierarchyLevel
          %assign copySrcVarForEachSS = locVarName
 
          {
            %foreach ssIdx = SIZE(mdlBlkCompiledModel.ForEachSSLoopBnds,1)
              %assign iterVar = "i_%<ForEachLoopHierarchyLevel>"
              %assign ::ForEachLoopHierarchyLevel = ::ForEachLoopHierarchyLevel - 1
              %assign copySrcVarForEachSS = copySrcVarForEachSS + "[%<iterVar>]"
              int32_T %<iterVar>;
              for (%<iterVar> = 0; %<iterVar> < %; %<iterVar>++) {
            %endforeach
            %assign ::ForEachLoopHierarchyLevel = 1
            %assign cppVarPath = SLibCalcMdlRefObjSubsysAccessPath(mSysIdx,...
                                bIdx,instIdx,"Registration")
            %if isBackup
              %<copySrcVarForEachSS> = %<cppVarPath>;
            %else
              %<cppVarPath> = %<copySrcVarForEachSS>;
            %endif
            %assign ::ForEachLoopHierarchyLevel = 1
             
            %foreach ssIdx = SIZE(mdlBlkCompiledModel.ForEachSSLoopBnds,1)
                   }
            %endforeach
            }
            %assign ::NeedForEachLoopInReg = TLC_FALSE
        %endif
      %closefile tmpBuf
 
      %assign copyCode = copyCode + tmpBuf
    %endforeach
  %endif
   
  %return copyCode
   
%endfunction %% SLibGetCPPEncapInitCopyCode
 
%%Function:SLibCPPDotOrArrowAccessOperator======================================
%%Abstract:
%%Whichaccessoperator,"."or"->",tousewhencallingmemberfunctionson
%%encapsulatedmodelreferenceC++objects.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibCPPDotOrArrowAccessOperator(blk, blkInterface) void
  %assert GenerateClassInterface
  %assert blk.MdlRefIsCPPClassGenMode
   
  %assign accOperator = ((!blkInterface.IsScalableBuild) && ...
                         CGMODEL_ACCESS("CGModel.getUseOperatorNewForModelRefRegistration")) ? ...
                            "->" : "."
                           
  %return accOperator
%endfunction %% SLibCPPDotOrArrowAccessOperator
 
 
%%FunctionRegisterMdlRefSFcnToWksDataTypes======================================
%%Abstract:
%%GeneratetheS-Functioncodetoregisterenumandfixedpointdatatypesused
%%byworkspacelogginginthemdlInitializeSizesfunction.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function RegisterMdlRefSFcnToWksDataTypes() Output
 
  %% ToWks logging in Dataset format is only supported currently for modelref sim
  %% targets.
  %if (!IsModelReferenceSimTarget())
    %return
  %endif
 
  %% See if there are any logged non-builtin types to register
  %if !EXISTS(::CompiledModel.DataTypes.NonBuiltinLoggingTypes) || ...
      SIZE(::CompiledModel.DataTypes.NonBuiltinLoggingTypes, 1) < 1
    %return
  %endif
 
  /* Workspace Logging Data Type Registration */
  %foreach idx = SIZE(::CompiledModel.DataTypes.NonBuiltinLoggingTypes, 1)
    {
      DTypeId dtId = INVALID_DTYPE_ID;
      %assign dID = ::CompiledModel.DataTypes.NonBuiltinLoggingTypes[idx]
       
      %% ENUM data types
      %if LibIsEnumDataType(dID)
        %assign dtName = LibGetDataTypeNameFromId(dID)
        ssRegisterTypeFromNamedObject(mdlRefSfcnS, "%<dtName>", &dtId);
      %% Half Precision type
      %elseif LibIsHalfDataType(dID)
        dtId = ssRegisterDataTypeHalfPrecision(mdlRefSfcnS, 0);
      %% FIXED POINT data types
      %elseif LibIsDataTypeFixpt(dID)
        %assign curDT = FixPt_GetDataTypeFromIndex(dID)
         
        %if FixPt_DataTypeIsFloat(curDT)
          dtId = ssRegisterDataTypeFxpScaledDouble( /
            mdlRefSfcnS, /
            %<curDT.IsSigned>, /
            %<curDT.RequiredBits>, /
            (double)%<curDT.FracSlope>, /
            %<curDT.FixedExp>, /
            (double)%<curDT.Bias>, /
            0);
          %else
            dtId = ssRegisterDataTypeFxpFSlopeFixExpBias( /
              mdlRefSfcnS, /
              %<curDT.IsSigned>, /
              %<curDT.RequiredBits>, /
              (double)%<curDT.FracSlope>, /
              %<curDT.FixedExp>, /
              (double)%<curDT.Bias>, /
              0);
          %endif
        
        %% BUS data types
        %elseif LibDataTypeIsBus(dID)
          %assign dtName = LibGetDataTypeNameFromId(dID)
          ssRegisterTypeFromNamedObject(mdlRefSfcnS, "%<dtName>", &dtId);
         
        %% UNKNOWN types
        %else
          %assign errTxt = ...
            "User-defined data types not supported for model reference simulation logging."
          %<LibReportFatalError(errTxt)>
        %endif
             
        if(dtId == INVALID_DTYPE_ID) {
          return;
        }
      }
    %endforeach
%endfunction %% RegisterMdlRefSFcnToWksDataTypes
 
 
%function SLibUsePortBasedSampleTime() void
  %return (::CompiledModel.UsePortBasedSampleTime == "yes")
%endfunction
 
%function SLibSimTargetUsesModelSelf() void
  %return SLibIsSelfInSimTarget() && SLibIsSelfStructured()
%endfunction
 
%%Function:SLibGetInstancePath===============================
%%
%%GetthefullpathtotopmodelfromDataMapInfo
%%
%function SLibGetInstancePath() void
  %if ::isRAccel
    %return "%<RSimRTWCAPIVar>.mmi.InstanceMap.fullPath"
  %else
    %return "%<RTMGet("DataMapInfo")>.mmi.InstanceMap.fullPath"
  %endif
%endfunction
 
%%Function:SLibWriteReusedSubSystemBlockPathFcn===============================
%%
%%WritereusedsubsystemsysId,blkId,andblkpatharraysandfunction
%%toreturnblkpath
%%
%function SLibWriteReusedSubSystemBlockPathFcn() void
 
  %if IsModelReferenceSimTarget() && ISFIELD(::CompiledModel, "ReusedSubSystemBlockData")
    %assign numBlks = SIZE(::CompiledModel.ReusedSubSystemBlockData.BlockPath,1)
    %openfile fcnBuffer
    %assign fcnSig = "void %<Name>_rt_ssGetBlockPath(SimStruct* S, int_T sysIdx, int_T blkIdx, char_T** blkPath)"
    %<fcnSig>
    {
      static int_T systemIdx[%<numBlks>] = { /
      %foreach idx = numBlks
        %<::CompiledModel.ReusedSubSystemBlockData.SystemIndex[idx]>,/
      %endforeach
      };
      static int_T blockIdx[%<numBlks>] = { /
      %foreach idx = numBlks
        %<::CompiledModel.ReusedSubSystemBlockData.BlockIndex[idx]>,/
      %endforeach
      };
      static char_T* blockPath[%<numBlks>] = { /
      %foreach idx = numBlks
        "%<::CompiledModel.ReusedSubSystemBlockData.BlockPath[idx]>",/
      %endforeach
      };
      uint32_T idx;
      *blkPath = NULL;
      for(idx = 0; idx < %<numBlks>; ++idx)
      {
        if(sysIdx == systemIdx[idx] && blkIdx == blockIdx[idx] )
        {
          *blkPath = blockPath[idx];
          return;
        }
      }
    }
 
%closefile fcnBuffer
%<SLibCacheCodeToFile("mdl_fcn_defn", fcnBuffer)>
 
%openfile fcnBuffer
%<LibExternInFcnDecls()>%<fcnSig>;
%closefile fcnBuffer
%<SLibCacheCodeToFile("mdl_fcn_prototype", fcnBuffer)>
%endif
%endfunction
 
 
%%EOFmodelrefsfcnlib.tlc