%%
%%Copyright1994-2019TheMathWorks,Inc.
%%
%%Abstract:
%%ThisTLClibraryfilecontainsallthecodeforgeneratingsystemoutput
%%code.
%%
 
%include "sysarglib.tlc"
 
%if EXISTS("_SYSLIB_") == 0
%assign _SYSLIB_ = 1
 
%include "servicelib.tlc"
%include "systemslib.tlc"
 
%%---------------------------------------------------------------%
%%FunctionRecord-recordusedfordefiningfunctionprototypes%
%%---------------------------------------------------------------%
%%
%%Createarecordfordefiningfunctionprototypes.Theidentifiersof
%%FcnRecareusedasfollows
%%
%%Declaration:voidfoo(int_Ttid);
%%CallSyntax:foo(tid);
%%
%%Name="foo"
%%Returns="void"
%%Params="int_Ttid"
%%Args="tid"
 
%assign FunctionRecord = FcnRec/
  {/
    Name "";/
    Returns "";/
    Params "";/
    CommonPrms "";/
    CommonArgs ""/
  }
 
%%Function:FcnResetFunctionRecord================================================================
%%Abstract:
%%Aroutinetoresetthefunctionrecord.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnResetFunctionRecord() void
  %assign ::FcnRec.Name = ""
  %assign ::FcnRec.Returns = ""
  %assign ::FcnRec.Params = ""
  %assign ::FcnRec.CommonPrms = ""
  %assign ::FcnRec.CommonArgs = ""
%endfunction
 
%%Function:FcnAddArgument========================================================================
%%Abstract:
%%AddanargumenttotheparameterandargumentfieldsoftheFcnRec
%%record.
%%
%%Arguments:
%%type:thetypefortheargument
%%var:thevariablenamefortheargument
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function FcnAddArgument(type, var, arg) void
  %if !WHITE_SPACE(::FcnRec.Params)
    %assign comma = ", "
  %else
    %assign comma = ""
  %endif
  %assign dataDef = type + var
  %assign ::FcnRec.Params = ::FcnRec.Params + comma + dataDef
  %assign ::FcnRec.CommonArgs = ::FcnRec.CommonArgs + comma + arg
%endfunction
 
 
%%Function:FcnAddArgumentWithCompilerAbstraction=================================================
%%Abstract:
%%AddanargumenttotheparameterandargumentfieldsoftheFcnRec
%%recordwithAUTOSARcompilerabstractionmacros
%%
%%Arguments:
%%type:thetypefortheargument
%%var:thevariablenamefortheargument
%%
%function FcnAddArgumentWithCompilerAbstraction(isConst, datatype, isPtr, ptrIsConst, var, arg) void
  %if !WHITE_SPACE(::FcnRec.Params)
    %assign comma = ", "
  %else
    %assign comma = ""
  %endif
  %assign dataDef = SLibAutosarCompilerAbstractionForDataDecl(isConst, datatype, isPtr, ptrIsConst, var, "DataAutomatic")
  %assign ::FcnRec.Params = ::FcnRec.Params + comma + dataDef
  %assign ::FcnRec.CommonArgs = ::FcnRec.CommonArgs + comma + arg
%endfunction
 
%%Function:FcnAddParameter=======================================================================
%%Abstract:
%%AddanargumentdefinitiontotheparameterfieldoftheFcnRecrecord.
%%
%%Arguments:
%%type:thetypefortheargumentdefinition
%%var:thevariablenamefortheargumentdefinition
%%TopTester:test/toolbox/simulink/variants/outputWhenUnconnected/tOutWhenUnconnected.m
%%
%function FcnAddParameter(type, var) void
  %if !WHITE_SPACE(::FcnRec.Params)
    %assign comma = ", "
  %else
    %assign comma = ""
  %endif
  %assign dataDef = type + var
  %assign ::FcnRec.Params = ::FcnRec.Params + comma + dataDef
%endfunction
 
%%Toptetser:test/toolbox/simulink/variants/CondExecutedVSS/tMdlRefWithFcnOnDataAsVSSChoice.m
%%
%function FcnPrependParameter(type, var) void
  %if !WHITE_SPACE(::FcnRec.Params)
    %assign comma = ", "
  %else
    %assign comma = ""
  %endif
  %assign dataDef = type + var
  %assign ::FcnRec.Params = dataDef + comma + ::FcnRec.Params
%endfunction
 
%%Function:FcnAddParameterWithCompilerAbstraction================================================
%%Abstract:
%%AddanargumentdefinitiontotheparameterfieldoftheFcnRecrecord.
%%
%%Arguments:
%%type:thetypefortheargumentdefinition
%%var:thevariablenamefortheargumentdefinition
%%
%function FcnAddParameterWithCompilerAbstraction(isConst, datatype, isPtr, var) void
  %if !WHITE_SPACE(::FcnRec.Params)
    %assign comma = ", "
  %else
    %assign comma = ""
  %endif
  %assign dataDef = SLibAutosarCompilerAbstractionForDataDecl(isConst, datatype, isPtr, TLC_FALSE, var, "DataAutomatic")
  %assign ::FcnRec.Params = ::FcnRec.Params + comma + dataDef
%endfunction
 
%%Function:FcnPassCanonicalInputByPtr============================================================
%%Abstract:
%%Returnwhetheracanonicalinputshouldbepassedbypointer
%function FcnPassCanonicalInputByPtr(ci)
  %return ci.DeclareAsPointer == "yes"
%endfunction
 
%%Function:FcnPassCanonicalInputAsConst==========================================================
%%Abstract:
%%Returnwhetheracanonicalinputshouldbepassedusingconst
%%qualifier
%%TopTester:test/toolbox/rtw/targets/ert/model2model/pir2engine/tPir2EngineLutGecks04.m
%%
%function FcnPassCanonicalInputAsConst(sysIdx, ci)
  %if !IsBaseSystem(System[System[sysIdx].ReusedParentSystemIdx]) || (!SLibFcnProtoCtrlActive() && !GenerateClassInterface)
    %return FcnPassCanonicalInputByPtr(ci) || (LibGetRecordWidth(ci) > 1)
  %else
    %if ISFIELD(ci, "IsCustomConst")
      %return ci.IsCustomConst == "yes"
    %else
      %return TLC_FALSE
    %endif
  %endif
%endfunction
 
%function FcnPassExternalInputAsConst(ci)
  %if ISFIELD(ci, "IsCustomConst")
    %return ci.IsCustomConst == "yes"
  %else
    %return TLC_FALSE
  %endif
%endfunction
 
%%Function:FcnPassCanonicalOutputAsReference=====================================================
%%Abstract:
%%Returnwhetheracanonicaloutputispassedbyreference
%%qualifier
%function FcnPassCanonicalOutputAsReference(co)
  %return co.DeclareAsReference == "yes"
%endfunction
 
%function SLibAccessThisArgGlobally(aArgDef, aFcnName) void
  %<SLibAccessThisSysFcnArgHelper(aArgDef, aFcnName, "Global", "", TLC_FALSE)>
  %<SLibAccessThisSysFcnArgHelper(aArgDef, aFcnName, "", "", TLC_FALSE)>
%endfunction
 
%%Function:SLibAccessMdlRefCanParam==============================================================
%%Abstract:
%%MarkestheparameterargumentforaPrmIdxasaccessedinagivenmodel
%%referencebasesystemfunction(aFcnName).
%%
%function SLibAccessMdlRefCanParam(aPrmIdx, aFcnName) void
  %if IsModelRefScalableBuild()
    %assign baseSystem = ::CompiledModel.System[GetBaseSystemIdx()]
    %with baseSystem.Interface
      %assert aPrmIdx < NumCanonicalPrmArgDefs
      %assign canParamRecord = CanonicalPrmArgDef[aPrmIdx]
      %<SLibAccessThisArgGlobally(canParamRecord, aFcnName)>
    %endwith
  %endif
%endfunction
 
%%Function:SLibAccessMdlRefGlobals===============================================================
%%Abstract:
%%Thisfunctionmarksmodelreferenceglobalargumentdefinitionrecordsas
%%accessed,basedonthevirtualargumentlistcreatedinIR.
%%
%function SLibAccessMdlRefGlobals(aFcn) void
  %if !IsModelRefScalableBuild()
    %return
  %endif
  %assign baseSystem = ::CompiledModel.System[GetBaseSystemIdx()]
  %with baseSystem.Interface
    %assign fcnName = aFcn.Name
    %foreach argIdx=aFcn.NumArgs
      %if 2 == aFcn.ArgAccessed[argIdx]
        %assign idNum = SLibSafeIDNUM(aFcn.ArgSource, argIdx)
        %assign argSrc = idNum[0]
        %assign argSrcIdx = idNum[1]
        %switch argSrc
          %case "I" %% canonical input
            %assign canInputRecord = CanonicalInputArgDef[argSrcIdx]
            %<SLibAccessThisArgGlobally(canInputRecord, fcnName)>
            %break
          %case "O" %% canonical output
            %assign canOutputRecord = CanonicalOutputArgDef[argSrcIdx]
            %<SLibAccessThisArgGlobally(canOutputRecord, fcnName)>
            %break
          %case "Y" %% root outport not being canonical output, occur in FPC only
            %break
          %case "Y" %% root outport not being canonical output, occur in FPC only
            %break
          %case "D" %% canonical dwork
            %assign canDWorkRecord = CanonicalDWorkArgDef[argSrcIdx]
            %<SLibAccessThisArgGlobally(canDWorkRecord, fcnName)>
            %break
          %case "P" %% canonical parameters
            %assign canParamRecord = CanonicalPrmArgDef[argSrcIdx]
            %<SLibAccessThisArgGlobally(canParamRecord, fcnName)>
            %break
          %case "RTM"
            %<SLibAccessThisArgGlobally(RTMArgDef, fcnName)>
            %break
          %case "LB" %% block IO
            %<SLibAccessThisArgGlobally(BlockIOArgDef, fcnName)>
            %break
          %case "LC" %% constat block IO
            %<SLibAccessThisArgGlobally(ConstBlockIOArgDef, fcnName)>
            %break
          %case "LW" %% dwork
            %<SLibAccessThisArgGlobally(DWorkArgDef, fcnName)>
            %break
          %case "LP" %% parameter
          %case "LCP" %% constant parameter
          %case "LPI" %% const parameter with init
            %<SLibAccessThisArgGlobally(ParameterArgDef, fcnName)>
            %break
          %case "LX" %% continues states
            %<SLibAccessThisArgGlobally(ContStatesArgDef, fcnName)>
            %break
          %case "LDX" %% derivatives
            %<SLibAccessThisArgGlobally(ContStatesDerivativeArgDef, fcnName)>
            %break
          %case "LXDI" %% continues state disabled
            %<SLibAccessThisArgGlobally(ContStatesDisabledArgDef, fcnName)>
            %break
          %case "LXAT" %% continues state absolute tolerance
            %<SLibAccessThisArgGlobally(ContStatesAbsoluteToleranceArgDef, fcnName)>
            %break
           
          %case "LXPTMIN" %% continues state perturb min
            %<SLibAccessThisArgGlobally(ContStatesPerturbMinArgDef, fcnName)>
            %break
           
          %case "LXPTMAX" %% continues state perturb max
            %<SLibAccessThisArgGlobally(ContStatesPerturbMaxArgDef, fcnName)>
            %break
             
          %case "LZ" %% non-sampled zero crossings
            %<SLibAccessThisArgGlobally(ZCSVArgDef, fcnName)>
            %break
          %case "LZE" %% zero crossing events
            %<SLibAccessThisArgGlobally(ZCEventArgDef, fcnName)>
            %break
          %case "LCDG"
          %case "CPI"
          %case "TID"
          %case "X"
          %case "U"
          %case "Y"
            %break
          %default
            %%START_ASSERT
            %assign errTxt = "Unhandled argument type '%<argSrc>'."
            %<LibBlockReportError([],errTxt)>
            %break
            %%END_ASSERT
        %endswitch
      %endif
    %endforeach
  %endwith
%endfunction
 
%%Function:SLibAccessArgGlobally=================================================================
%%Abstract:
%%Thisfunctionmarksaargumentofthecurrentfunctionasaccessed
%%globally.
%%
%function SLibAccessArgGlobally(arg, fcnName, accessTid, periodicRateGrouping) void
  %if periodicRateGrouping || SLibNonInlinedModelWideEventTID(accessTid)
    %<SLibAccessThisSysFcnArgHelper(arg, fcnName, "", accessTid, TLC_FALSE)>
    %<SLibAccessThisSysFcnArgHelper(arg, fcnName, "Global", accessTid, TLC_FALSE)>
  %else
    %<SLibAccessThisSysFcnArgHelper(arg, fcnName, "", "", TLC_FALSE)>
    %<SLibAccessThisSysFcnArgHelper(arg, fcnName, "Global", "", TLC_FALSE)>
  %endif
%endfunction
 
%%Function:SLibAccessArg=========================================================================
%%Abstract:
%%Thisfunctionmarksaargumentofthecurrentfunctionasaccessed
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibAccessArg(arg, fcnName, accessTid, periodicRateGrouping) void
  %if periodicRateGrouping || SLibNonInlinedModelWideEventTID(accessTid)
    %<SLibAccessThisSysFcnArgHelper(arg, fcnName, "", accessTid, TLC_FALSE)>
  %else
    %<SLibAccessThisSysFcnArgHelper(arg, fcnName, "", "", TLC_FALSE)>
  %endif
%endfunction
 
%%Function:FcnGetGroupArgDef
%%Abstract:
%%Givenagroupindex,returnsthetoken"CoderDataGroupArgDef"where"x"
%%isthegroupname
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnGetGroupArgDef(groupIndex) void
  %assign group = ::CompiledModel.CoderDataGroup[groupIndex]
  %assign groupToken = "CoderDataGroup" + group.Name
  %assign argDef = %
  %return argDef
%endfunction
 
%%Function:FcnAddParametersAndReturn=============================================================
%%Abstract:
%%Thisfunctionaddstheneededparametersandreturntothefunction
%%prototype,e.g."u0,u1,localB,..."
%%refertoGetFunctionStrfortheorderofparameters.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tIVfcnCall_neg.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tMdlRefWithFcnOnDataAsVSSChoice.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmVariantsRSim.m-tmg1078041_VC1.m
%%
%function FcnAddParametersAndReturn(sysFcn, fcnName, sysIdx, isRGSLF) void
  %assign thisSystem = ::CompiledModel.System[sysIdx]
  %assign thisModule = ...
    ::CompiledModel.RTWCGModules.RTWCGModule[thisSystem.CGIRModuleIdx]
  %assign hasReusableInterface = thisModule.SimplifiedInterface || SLibGetUseRTMcgType()
  %assign cTID = thisSystem.CurrentTID
  %% For async rate grouping, want arg access tracked by TID, so set isRG to true
  %assign isRG = SLibSystemFcnPeriodicRateGrouping(thisSystem, sysFcn) || ...
    SLibIsExplicitTaskingExportFcnRateGrouping(sysFcn, cTID)
 
  %if (sysFcn == "OutputUpdate") && SLibFcnProtoCtrlActive() && ...
    IsModelReferenceBaseSys(thisSystem)
 
    %assign FPC = FcnGetFunctionPrototypeRecord()
  %else
    %assign FPC = []
  %endif
  %assign thisFcn = []
  %assign isCPPDefaultClassForMdlrefRGOutput = TLC_FALSE
  %if sysFcn == "OutputUpdate" && ...
      GenerateClassInterface && ...
      !LibAsynchronousTriggeredTID(cTID) && ...
      IsModelReferenceBaseSys(thisSystem) && ...
      !(LibAsynchronousTriggeredTID(cTID) || SLibExplicitPeriodicInExportFcnDiagram(cTID))
 
    %assign FPC = FcnGetRTWCPPStepPrototypeRecord()
    %assign isCPPDefaultClassForMdlrefRGOutput = !(SLibRTWCPPClassActive() && ::CompiledModel.RTWFcnCPPClass.Object.Class == "ModelCPPArgsClass")
  %endif
  %assign hasFPC = !ISEMPTY(FPC)
 
  %with thisSystem.Interface
    %%
    %% The following TLC code is used to create the agrument defintions for
    %% CGIR function arguments and transfer the CGIR argument tracking
    %% information to the legacy TLC tracking infrastructure.
    %%
    %%
    %% FPC uses a fixed argument set which doesn't need to be extended in TLC
    %% since the IR defenition is already complete. This is also true of
    %% rate grouped Simulink functions.
    %%
    %if (hasFPC && !isCPPDefaultClassForMdlrefRGOutput) || isRGSLF
      %assign skipCanInput = ...
        Vector(%<NumCanonicalInputArgDefs>) [1@%<NumCanonicalInputArgDefs>]
      %assign skipCanOutput = ...
        Vector(%<NumCanonicalOutputArgDefs>) [1@%<NumCanonicalOutputArgDefs>]
    %else
      %assign skipCanInput = ...
        Vector(%<NumCanonicalInputArgDefs>) [0@%<NumCanonicalInputArgDefs>]
      %assign skipCanOutput = ...
        Vector(%<NumCanonicalOutputArgDefs>) [0@%<NumCanonicalOutputArgDefs>]
    %endif
    %assign skipCanDWork = ...
      Vector(%<NumCanonicalDWorkArgDefs>) [0@%<NumCanonicalDWorkArgDefs>]
    %assign skipCanParam = ...
      Vector(%<NumCanonicalPrmArgDefs>) [0@%<NumCanonicalPrmArgDefs>]
    %assign skipRTM = SLibGenSubsysFcnAsClassMemFcn(thisSystem)
    %assign skipHStructArgs = LibSystemIsNonReusedFcn(thisSystem)
    %assign skipLocalB = skipHStructArgs || hasReusableInterface
    %assign skipLocalC = skipHStructArgs
    %assign skipLocalDW = skipHStructArgs || hasReusableInterface
    %assign skipLocalP = skipHStructArgs || hasReusableInterface
    %assign skipLocalX = skipHStructArgs
    %assign skipLocalXdot = skipHStructArgs
    %assign skipLocalXdis = skipHStructArgs
    %assign skipLocalXabstol = skipHStructArgs
    %assign skipLocalXperturbmin = skipHStructArgs
    %assign skipLocalXperturbmax = skipHStructArgs
    %assign skipLocalZCSV = skipHStructArgs
    %assign skipLocalZCE = skipHStructArgs || hasReusableInterface
 
    %assign skipLocalDataGroup = ...
      Vector(%<::CompiledModel.NumCoderDataGroups>) [%<skipHStructArgs>@%<::CompiledModel.NumCoderDataGroups>]
 
    %if ISFIELD(thisModule, "SystemFunctions") && ...
      ISFIELD(thisModule.SystemFunctions, fcnName)
      %assign fcnIndex = GETFIELD(thisModule.SystemFunctions, fcnName)
      %assign thisFcn = thisModule.Function[fcnIndex]
      %%
      %% Subfunction are fully defined in IR and do not use this infrastructure
      %%
      %if fcnIndex >= thisModule.NumSubFunctions
        %assign cgirParams = FEVAL("regexprep", thisFcn.ProtoType, "^[^/(]*/(", "")
        %if !ISEMPTY(cgirParams)
          %if !WHITE_SPACE(::FcnRec.Params)
            %assign ::FcnRec.Params = ::FcnRec.Params + "," + cgirParams
          %else
            %assign ::FcnRec.Params = ::FcnRec.Params + cgirParams
          %endif
          %if hasFPC && FPC.NumArgSpecData > 0 && ...
            FPC.ArgSpecData[0].SLObjectType == "Outport" && ...
            FPC.ArgSpecData[0].Category == "Value"
            %assign portIdx = FPC.ArgSpecData[0].PortNum
            %assign eo = ExternalOutputs.ExternalOutput[portIdx]
            %assign dataType = SLibGetRecordDataTypeName(eo, "")
            %assign ::FcnRec.Returns = dataType
          %endif
          %assign hasFPC = TLC_FALSE
          %assign FPC = []
        %endif
      %endif
      %assert SIZE(thisFcn.ArgAccessed, 1) == thisFcn.NumArgs
      %assert SIZE(thisFcn.ArgSource, 1) == thisFcn.NumArgs
      %%
      %% Transfer the access flags from exported graphical functions to entry
      %% function model arguments, based on a call graph pattern
      %% (MdlRefChildFcnNames) that has been pre computed in IR.
      %%
      %foreach childFcnIdx=SIZE(thisFcn.MdlRefChildFcnNames, 1)
        %assign childFcnName = thisFcn.MdlRefChildFcnNames[childFcnIdx]
        %foreach canInpIdx = NumCanonicalInputArgDefs
          %assign canInputRecord = CanonicalInputArgDef[canInpIdx]
          %if SysFcnArgNeeded(childFcnName, canInputRecord, cTID, isRG)
            %<SLibAccessArgGlobally(canInputRecord, sysFcn, cTID, isRG)>
          %endif
        %endforeach
        %foreach canOutpIdx = NumCanonicalOutputArgDefs
          %assign canOutputRecord = CanonicalOutputArgDef[canOutpIdx]
          %if SysFcnArgNeeded(childFcnName, canOutputRecord, cTID, isRG)
            %<SLibAccessArgGlobally(canOutputRecord, sysFcn, cTID, isRG)>
          %endif
        %endforeach
        %foreach canDwIdx = NumCanonicalDWorkArgDefs
          %assign canDWorkRecord = CanonicalDWorkArgDef[canDwIdx]
          %if SysFcnArgNeeded(childFcnName, canDWorkRecord, cTID, isRG)
            %<SLibAccessArgGlobally(canDWorkRecord, sysFcn, cTID, isRG)>
          %endif
        %endforeach
        %foreach canPrmIdx = NumCanonicalPrmArgDefs
          %assign canPrmRecord = CanonicalPrmArgDef[canPrmIdx]
          %if SysFcnArgNeeded(childFcnName, canPrmRecord, cTID, isRG)
            %<SLibAccessArgGlobally(canPrmRecord, sysFcn, cTID, isRG)>
          %endif
        %endforeach
        %if SysFcnArgNeeded(childFcnName, RTMArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(RTMArgDef, sysFcn, cTID, isRG)>
        %endif
        %%
        %if SysFcnArgNeeded(childFcnName, BlockIOArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(BlockIOArgDef, sysFcn, cTID, isRG)>
        %endif
        %if SysFcnArgNeeded(childFcnName, ConstBlockIOArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(ConstBlockIOArgDef, sysFcn, cTID, isRG)>
        %endif
        %if SysFcnArgNeeded(childFcnName, DWorkArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(DWorkArgDef, sysFcn, cTID, isRG)>
        %endif
        %if SysFcnArgNeeded(childFcnName, ParameterArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(ParameterArgDef, sysFcn, cTID, isRG)>
        %endif
        %if SysFcnArgNeeded(childFcnName, ContStatesArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(ContStatesArgDef, sysFcn, cTID, isRG)>
        %endif
        %if SysFcnArgNeeded(childFcnName, ContStatesDerivativeArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(ContStatesDerivativeArgDef, sysFcn, cTID, isRG)>
        %endif
        %if SysFcnArgNeeded(childFcnName, ContStatesDisabledArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(ContStatesDisabledArgDef, sysFcn, cTID, isRG)>
        %endif
        %if SysFcnArgNeeded(childFcnName, ContStatesAbsoluteToleranceArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(ContStatesAbsoluteToleranceArgDef, sysFcn, cTID, isRG)>
        %endif
         
        %if SysFcnArgNeeded(childFcnName, ContStatesPerturbMinArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(ContStatesPerturbMinArgDef, sysFcn, cTID, isRG)>
        %endif
         
        %if SysFcnArgNeeded(childFcnName, ContStatesPerturbMaxArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(ContStatesPerturbMaxArgDef, sysFcn, cTID, isRG)>
        %endif
         
        %if SysFcnArgNeeded(childFcnName, ZCSVArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(ZCSVArgDef, sysFcn, cTID, isRG)>
        %endif
        %if SysFcnArgNeeded(childFcnName, ZCEventArgDef, cTID, isRG)
          %<SLibAccessArgGlobally(ZCEventArgDef, sysFcn, cTID, isRG)>
        %endif
        %% Handling of data groups
        %foreach gIdx = ::CompiledModel.NumCoderDataGroups
          %assign argDef = FcnGetGroupArgDef(gIdx)
          %if SysFcnArgNeeded(sysFcn, argDef, cTID, isRG)
            %<SLibAccessArgGlobally(argDef, sysFcn, cTID, isRG)>
          %endif
        %endforeach
 
        %%
      %endforeach
      %%
      %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" %% canonical input
              %if 0 < NumCanonicalInputArgDefs && !isRGSLF %% CrossNoArgFcnBound
                %assign skipCanInput[argSrcIdx] = 1
                %assign canInputRecord = CanonicalInputArgDef[argSrcIdx]
                %<SLibAccessArg(canInputRecord, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "O" %% canonical output
              %if 0 < NumCanonicalOutputArgDefs && !isRGSLF %% CrossNoArgFcnBound
                %assign skipCanOutput[argSrcIdx] = 1
                %assign canOutputRecord = CanonicalOutputArgDef[argSrcIdx]
                %<SLibAccessArg(canOutputRecord, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "D" %% canonical dwork
              %if 0 < NumCanonicalDWorkArgDefs %% CrossNoArgFcnBound
                %assign skipCanDWork[argSrcIdx] = 1
                %assign canDWorkRecord = CanonicalDWorkArgDef[argSrcIdx]
                %<SLibAccessArg(canDWorkRecord, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "P" %% canonical parameters
              %if 0 < NumCanonicalPrmArgDefs && !isRGSLF %% CrossNoArgFcnBound
                %assign skipCanParam[argSrcIdx] = 1
                %assign canParamRecord = CanonicalPrmArgDef[argSrcIdx]
                %<SLibAccessArg(canParamRecord, sysFcn, cTID, isRG)>
              %elseif thisSystem.IsService || isRGSLF
                %%
                %% cache this parameter argument in model start
                %%
                %<SLibAccessMdlRefCanParam(argSrcIdx, "Start")>
              %endif
              %break
            %case "RTM"
              %assign skipRTM = 1
              %break
            %case "LCDG"
              %% Here, argSrcIdx refers to the index of the coder data group
              %if 0 == skipLocalDataGroup[argSrcIdx] %% CrossNoArgFcnBound
                %assign skipLocalDataGroup[argSrcIdx] = 1
                %assign argDef = FcnGetGroupArgDef(argSrcIdx)
                %<SLibAccessArg(argDef, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "LB" %% block IO
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %assign skipLocalB = 1
                %<SLibAccessArg(BlockIOArgDef, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "LC" %% constat block IO
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %assign skipLocalC = 1
                %<SLibAccessArg(ConstBlockIOArgDef, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "LW" %% dwork
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %assign skipLocalDW = 1
                %<SLibAccessArg(DWorkArgDef, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "LP" %% parameter
            %case "LCP" %% constant parameter
            %case "LPI" %% const parameter with init
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %assign skipLocalP = 1
                %<SLibAccessArg(ParameterArgDef, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "LX" %% continues states
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %assign skipLocalX = 1
                %<SLibAccessArg(ContStatesArgDef, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "LDX" %% derivatives
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %assign skipLocalXdot = 1
                %<SLibAccessArg(ContStatesDerivativeArgDef, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "LXDI" %% continues state disabled
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %assign skipLocalXdis = 1
                %<SLibAccessArg(ContStatesDisabledArgDef, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "LXAT" %% continues state absolute tolerance
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %assign skipLocalXabstol = 1
                %<SLibAccessArg(ContStatesAbsoluteToleranceArgDef, sysFcn, cTID, isRG)>
              %endif
              %break
               
            %case "LXPTMIN" %% continues state perturb min
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %assign skipLocalXperturbmin = 1
                %<SLibAccessArg(ContStatesPerturbMinArgDef, sysFcn, cTID, isRG)>
              %endif
              %break
               
            %case "LXPTMAX" %% continues state perturb max
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %assign skipLocalXperturbmax = 1
                %<SLibAccessArg(ContStatesPerturbMaxArgDef, sysFcn, cTID, isRG)>
              %endif
              %break
               
               
            %case "LZ" %% non-sampled zero crossings
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %assign skipLocalZCSV = 1
                %<SLibAccessArg(ZCSVArgDef, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "LZE" %% zero crossing events
              %if 0 == skipHStructArgs
                %assign skipLocalZCE = 1
                %<SLibAccessArg(ZCEventArgDef, sysFcn, cTID, isRG)>
              %endif
              %break
            %case "CPI"
            %case "TID"
            %case "X"
            %case "U"
            %case "Y" %% root outport not being canonical output, occur in FPC only
              %break
            %default
              %%START_ASSERT
              %assign errTxt = "Unhandled argument type '%<argSrc>'."
              %<LibBlockReportError([],errTxt)>
              %break
              %%END_ASSERT
          %endswitch
        %endif
      %endforeach
    %endif
 
    %if !(GenerateClassInterface && SLibModelWideEventTID(cTID)) && ...
      (LibSystemIsReusedFcn(thisSystem) || ...
      (LibSystemIsNonReusedFcn(thisSystem) && ...
      ISFIELD(thisSystem,"RTWSystemCodeOptIntf")) || ...
      thisSystem.IsService)
      %assign useFPC = hasFPC && ISFIELD(FPC,"FunctionName")
      %if !useFPC
        %assign numArgs = NumCanonicalInputArgDefs + NumCanonicalOutputArgDefs
      %else
        %assign numArgs = FPC.NumArgSpecData
      %endif
      %assign isISSReuseDiffNumIters = SLibGetIsForEachSSReuseWithDiffNumIters(thisSystem)
 
      %foreach argIdx = numArgs
        %if !useFPC
          %if argIdx < NumCanonicalInputArgDefs
            %assign portIdx = argIdx
            %assign SLObjectType = "Inport"
          %else
            %assign portIdx = argIdx - NumCanonicalInputArgDefs
            %assign SLObjectType = "Outport"
          %endif
        %else
          %assign portIdx = FPC.ArgSpecData[argIdx].PortNum
          %assign SLObjectType = FPC.ArgSpecData[argIdx].SLObjectType
        %endif
        %%
        %% Canonical input argument
        %%
        %if SLObjectType == "Inport"
          %if hasFPC || ...
            (!skipCanInput[portIdx] && ...
            SysFcnArgNeeded(sysFcn, CanonicalInputArgDef[portIdx], cTID, isRG))
            %assign skipThisArg = 0
            %if !hasFPC
              %assign ci = CanonicalInputArgDef[portIdx]
              %if ISFIELD(ci,"VarGroupIdx") && SLibGetDoesSelfExist() && SLibIsSelfStructured()
                %% accessed through rtm make sure instance specific rtm is added to definition
                %<SLibAccessArg(RTMArgDef,sysFcn, cTID, isRG)>
              %endif
              %if IDNUM(ci.SignalSrc[0])[0] == "F"
                %assign skipThisArg = 1
              %endif
              %assign dataType = SLibGetRecordDataTypeName(ci, "")
              %assign width = LibGetRecordWidth(ci)
              %assign optWidth = LibOptionalVectorWidth(width)
            %else
              %assign ei = ExternalInputs.ExternalInput[portIdx]
              %assign dataType = SLibGetRecordDataTypeName(ei, "")
              %assign width = LibGetRecordWidth(ei)
              %assign optWidth = LibOptionalVectorWidth(width)
            %endif
 
            %if skipThisArg==0
              %if !hasFPC
                %assign passByPtr = FcnPassCanonicalInputByPtr(ci)
                %assign passConst = FcnPassCanonicalInputAsConst(sysIdx, ci) || ...
                  (GenerateClassInterface && IsModelReferenceBaseSys(thisSystem) && passByPtr && sysFcn == "Start")
                %assign optConst = passConst ? "const " : ""
                %assign optStar = passByPtr ? "*" : ""
                %if SLibGetCanIOIsVarDims(ci) || isISSReuseDiffNumIters && !ISEMPTY(optWidth)
                  %% Always pass pointer for var-dims signal or Implicit Iterator
                  %% subsystem reused for different number of iterations.
                  %assign argDef = " %<LibGetRecordIdentifier(ci)>[]"
                %else
                  %assign argDef = "%<optStar>%<LibGetRecordIdentifier(ci)>%<optWidth>"
                %endif
              %else
                %assign passByPtr = FPC.ArgSpecData[argIdx].Category == "Pointer" && width == 1
                %assign isReference = (FPC.ArgSpecData[argIdx].Category == "Reference")
                %assign qualifier = FPC.ArgSpecData[argIdx].Qualifier
                %assign argDef = ""
                %switch qualifier
                  %case "none"
                    %assign optConst = ""
                    %if passByPtr
                      %assign argDef = "*"
                    %elseif isReference
                      %assign argDef = "&"
                    %endif
                    %break
                  %case "const"
                    %assign optConst = "const "
                    %assign argDef = ""
                    %break
                  %case "const *"
                    %assign optConst = "const "
                    %if LibGetRecordWidth(ei) == 1
                      %assign argDef = "*"
                    %endif
                    %break
                  %case "const * const"
                    %assign optConst = "const "
                    %if LibGetRecordWidth(ei) == 1
                      %assign argDef = "*const "
                    %endif
                    %break
                  %case "const &"
                    %assign optConst = "const "
                    %assign argDef = "&"
                    %break
                  %default
                    %assign errTxt = "Unhandled qualifier"
                    %<LibReportFatalError(errTxt)>
                    %break
                %endswitch
 
                %if !ISEMPTY(optWidth) && isReference
                  %assign argDef = ...
                    "(%<argDef>%)%<optWidth>"
                %else
                  %assign argDef = ...
                    "%<argDef>%%<optWidth>"
                %endif
              %endif
              %if SLibAutosarCompilerAbstractionRequired()
                %if SLibGetCanIOIsVarDims(ci) || isISSReuseDiffNumIters
                  %assign argDef = "%<LibGetRecordIdentifier(ci)>[]"
                %else
                  %assign argDef = "%<LibGetRecordIdentifier(ci)>%<optWidth>"
                %endif
                %<FcnAddParameterWithCompilerAbstraction(passConst, dataType, passByPtr, argDef)>
              %elseif dataType != "fcn_call"
                %assign dataType = "%<optConst>%<dataType> "
                %<FcnAddParameter(dataType, argDef)>
              %endif
            %endif
            %% Add vardims argument for the canonical input
            %<FcnAddNeededCanDimSizeDWForCanInp(sysFcn, sysIdx, portIdx, ...
              skipCanDWork)>
          %endif %% SysFcnArgNeeded
 
          %%
          %% Canonical output arguments
        %else
          %if hasFPC || ...
            (!skipCanOutput[portIdx] && ...
            SysFcnArgNeeded(sysFcn, CanonicalOutputArgDef[portIdx], cTID, isRG))
            %if !hasFPC
              %assign co = CanonicalOutputArgDef[portIdx]
              %if ISFIELD(co,"VarGroupIdx") && SLibGetDoesSelfExist() && SLibIsSelfStructured()
                %% accessed through rtm make sure instance specific rtm is added to definition
                %<SLibAccessArg(RTMArgDef,sysFcn, cTID, isRG)>
              %endif
              %assign dataType = SLibGetRecordDataTypeName(co, "")
              %assign identi = LibGetRecordIdentifier(co)
              %assign optStar = LibGetRecordWidth(co) == 1 ? " *" : " "
              %assign optWidth = LibOptionalVectorWidth(LibGetRecordWidth(co))
              %if SLibAutosarCompilerAbstractionRequired()
                %if SLibGetCanIOIsVarDims(co) || isISSReuseDiffNumIters
                  %% Always pass pointer for var-dims signal or Implicit Iterator
                  %% subsystem reused for different number of iterations.
                  %assign argDef = " " + identi + "[]"
                %else
                  %assign argDef = identi + optWidth
                %endif
                %<FcnAddParameterWithCompilerAbstraction(TLC_FALSE, dataType, (LibGetRecordWidth(co) == 1), argDef)>
              %else
                %if SLibGetCanIOIsVarDims(co) || isISSReuseDiffNumIters
                  %% Always pass pointer for var-dims signal or Implicit Iterator
                  %% subsystem reused for different number of iterations.
                  %assign argDef = " " + identi + "[]"
                %else
                  %assign argDef = optStar + identi + optWidth
                %endif
                %<FcnAddParameter(dataType, argDef)>
              %endif
            %else
              %assign eo = ExternalOutputs.ExternalOutput[portIdx]
              %assign dataType = SLibGetRecordDataTypeName(eo, "")
              %if FPC.ArgSpecData[argIdx].Category == "Value"
                %assign ::FcnRec.Returns = dataType
              %else
                %assign identi = FPC.ArgSpecData[argIdx].ArgName
                %assign isReference = (FPC.ArgSpecData[argIdx].Category == "Reference")
                %assign optStarOrRef = isReference ? " &" : ...
                  (LibGetRecordWidth(eo) == 1 ? " *" : " ")
                %assign optWidth = LibOptionalVectorWidth(LibGetRecordWidth(eo))
                %if !ISEMPTY(optWidth) && isReference
                  %assign argDef = "(" + optStarOrRef + identi +")" + optWidth
                %else
                  %assign argDef = optStarOrRef + identi + optWidth
                %endif
                %% SLibAutosarCompilerAbstractionRequired() not supported for FPC
                %<FcnAddParameter(dataType, argDef)>
              %endif
            %endif
            %% Add vardims argument for the canonical output
            %% Function FinalizeDims and SetDims only need canonical dim-size
            %% dwork. They don't need canonical output.
            %<FcnAddNeededCanDimSizeDWForCanOut(sysFcn, sysIdx, portIdx, ...
              skipCanDWork)>
          %endif
 
          %if !hasFPC
            %if ISFIELD(thisSystem, "RTWSystemWithReturnValue") && ...
              EXISTS(portIdx) && ...
              thisSystem.RTWSystemReturnArgIndex == portIdx && ...
              SLObjectType == "Outport" && ...
              (sysFcn == "OutputUpdate" || sysFcn == "Output")
              %assign dataType =SLibGetRecordDataTypeName(CanonicalOutputArgDef[portIdx],"")
              %assign ::FcnRec.Returns = dataType
            %endif
          %endif
 
        %endif
      %endforeach
 
      %%
      %% Is a model reference scalable build - some args are accessed as globals
      %% Skip these args.
      %%
      %assign isScalableMRSys = ...
        IsModelReferenceBaseSys(thisSystem) && IsModelRefScalableBuild()
 
      %% Is a model reference build and in C++ encapsulation mode
      %assign isCPPEncapMdlRef = GenerateClassInterface && ...
        IsModelReferenceBaseSys(thisSystem)
      %%
      %% rtModel argument
      %%
      %if ISFIELD(thisModule,"SystemFunctions") && ISFIELD(thisModule.SystemFunctions, fcnName)
        %assign fcnIdx = thisModule.SystemFunctions.%<fcnName>
        %assign fcn = thisModule.Function[fcnIdx]
        %assign isOutlinedBlockFcn = fcn.IsOutlinedBlockFcn
      %else
        %assign isOutlinedBlockFcn = TLC_FALSE
      %endif
      %assign isServiceFcn = TLC_FALSE
      %if !ISEMPTY(thisFcn) && thisFcn.IsServiceFcn
        %<FcnCacheServiceFcnLocalVars(thisSystem, sysFcn, cTID, isRG)>
        %assign isServiceFcn = TLC_TRUE
      %endif
      %assign isMatchGrInterface = (LibSystemIsNonReusedFcn(thisSystem) && ISFIELD(thisSystem,"RTWSystemMatchGrInterface"))
       %if !isCPPEncapMdlRef && !(thisSystem.IsService && thisModule.SimplifiedInterface) && (skipRTM || (SysFcnArgNeeded(sysFcn, RTMArgDef, cTID, isRG) && !isMatchGrInterface))
        %if isScalableMRSys && !::CompiledModel.ModelRefSimpInterface
          %if !isServiceFcn && (!SLibGetDoesSelfExist() || SLibIsSelfInSimTarget())
              %openfile localRTMVar
              %assign rtmField = ".rtm"
              %<::tSimStructType> *const %<::tSimStruct> = &(%<FcnGetSFcnDWorkIdentifier(thisSystem)>%<rtmField>);
              %closefile localRTMVar
              %<FcnCacheModelRefLocalVars(thisSystem, sysFcn, cTID, localRTMVar)>
          %endif
        %elseif thisSystem.IsService && !thisModule.SimplifiedInterface && SLibIsSelfInSimTarget()
          %openfile localRTMVar
          %<::tSimStructType> *const %<::tSimStruct> = &(%<FcnGetSFcnDWorkRTM()>);
          %closefile localRTMVar
          %<LibAddToSystemField(thisSystem, "Cached%<sysFcn>%<cTID>LocalBO", localRTMVar)>
        %elseif !skipRTM && !isOutlinedBlockFcn
          %if thisModule.SimplifiedInterface
            %<FcnPrependParameter(::tSimStructType, " *const %<SLibGetSimStruct()>")>
          %else
            %<FcnAddParameter(::tSimStructType, " *const %<SLibGetSimStruct()>")>
          %endif
        %endif
      %endif %% SysFcnArgNeeded
      %%
      %% Block IO argument
      %%
      %if !skipLocalB && !isCPPEncapMdlRef && SysFcnArgNeeded(sysFcn, BlockIOArgDef, cTID, isRG)
        %assign dataType = FcnSysVarGroupType(thisSystem,"BlockIO") + " "
        %if !isScalableMRSys
          %if SLibAutosarCompilerAbstractionRequired()
            %assign dataType = FcnSysVarGroupType(thisSystem,"BlockIO")
            %<FcnAddParameterWithCompilerAbstraction(TLC_FALSE, dataType, TLC_TRUE, "localB")>
          %else
            %<FcnAddParameter(dataType, "*localB")>
          %endif
        %endif
      %endif %% SysFcnArgNeeded
      %%
      %% DataGroup arguments - only do this for non-model reference base systems
      %%
      %if !IsModelReferenceBaseSys(thisSystem) && !thisModule.SimplifiedInterface
        %foreach gIdx = ::CompiledModel.NumCoderDataGroups
          %assign argDef = FcnGetGroupArgDef(gIdx)
          %if !(skipLocalDataGroup[gIdx]) && !isCPPEncapMdlRef && SysFcnArgNeeded(sysFcn, argDef, cTID, isRG)
            %assign group = ::CompiledModel.CoderDataGroup[gIdx]
            %assign groupToken = "CoderDataGroup" + group.Name
            %assign dataType = FcnSysVarGroupType(thisSystem, groupToken) + " "
            %assign varGroupIdx = FcnSysVarGroupIndex(thisSystem, groupToken, 0)
            %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
            %assign varName = varGroup.LocalName
 
            %if !isScalableMRSys
              %if SLibAutosarCompilerAbstractionRequired()
                %assign dataType = FcnSysVarGroupType(thisSystem, groupToken)
                %<FcnAddParameterWithCompilerAbstraction(TLC_FALSE, dataType, TLC_TRUE, varName)>
              %else
                %assign localString = "*" + varName
                %<FcnAddParameter(dataType, localString)>
              %endif
            %endif
          %endif
        %endforeach
      %endif
      %%
      %% Constant block IO argument
      %%
      %if !skipLocalC && !isCPPEncapMdlRef && SysFcnArgNeeded(sysFcn, ConstBlockIOArgDef, cTID, isRG)
        %assert !isScalableMRSys
        %if SLibAutosarCompilerAbstractionRequired()
          %assign dataType = FcnSysVarGroupType(thisSystem,"ConstBlockIO")
          %<FcnAddParameterWithCompilerAbstraction(TLC_FALSE, dataType, TLC_TRUE, "localC")>
        %else
          %assign dataType = FcnSysVarGroupType(thisSystem,"ConstBlockIO") + " "
          %<FcnAddParameter(dataType, "*localC")>
        %endif
      %endif %% SysFcnArgNeeded
      %%
      %% DWork argument
      %%
      %if !skipLocalDW && !isCPPEncapMdlRef && SysFcnArgNeeded(sysFcn, DWorkArgDef, cTID, isRG)
        %assign varGroupType = FcnSysVarGroupType(thisSystem,"DWork")
        %if !isScalableMRSys
          %if SLibAutosarCompilerAbstractionRequired()
            %assign dataType = varGroupType
            %<FcnAddParameterWithCompilerAbstraction(TLC_FALSE, dataType, TLC_TRUE, "localDW")>
          %else
            %assign dataType = varGroupType + " "
            %<FcnAddParameter(dataType, "*localDW")>
          %endif
        %endif
      %endif %% SysFcnArgNeeded
      %%
      %% Parameter H-Struct argument
      %%
      %assign isSysFcnArgNeeded = SysFcnArgNeeded(sysFcn, ParameterArgDef, cTID, isRG)
      %if !skipLocalP && isSysFcnArgNeeded
        %%
        %% Does a passthrough parameter structure argument exists ?
        %%
        %assert( !isScalableMRSys || IsModelReferenceInlineOffTarget())
        %if (InlineParameters != 0 && ParameterArgDef.PassthroughSystemIdx > -1)
          %assign prmSysIdx = ParameterArgDef.PassthroughSystemIdx
        %else
          %assign prmSysIdx = sysIdx
        %endif
        %assign numsys = GetNumSystemsForCodeGen()
        %if prmSysIdx < numsys-1 %% not the root system
          %if SLibAutosarCompilerAbstractionRequired()
            %assign dataType = FcnSysVarGroupType(System[prmSysIdx],"Parameter")
            %<FcnAddParameterWithCompilerAbstraction(TLC_FALSE, dataType, TLC_TRUE, "localP")>
          %else
            %assign dataType = FcnSysVarGroupType(System[prmSysIdx],"Parameter") + " "
            %<FcnAddParameter(dataType, "*localP")>
          %endif
        %else
          %%
          %% The child function has the root parameter structure as
          %% a passthrough argument
          %%
          %if SLibAutosarCompilerAbstractionRequired()
            %assign dataType = ::tParametersType
            %<FcnAddParameterWithCompilerAbstraction(TLC_FALSE, dataType, TLC_TRUE, LibGetParametersStruct())>
          %elseif !(GenerateClassInterface && IsModelReferenceBaseSys(thisSystem))
            %assign dataType = ::tParametersType + " "
            %<FcnAddParameter(dataType, "*%<LibGetParametersStruct()>")>
          %endif
 
        %endif
      %endif %% SysFcnArgNeeded
      %%
      %% Continuous States argument
      %%
      %if !skipLocalX && SysFcnArgNeeded(sysFcn, ContStatesArgDef, cTID, isRG)
        %assign dataType = isScalableMRSys ? "real_T " : ...
          "%<FcnSysVarGroupType(thisSystem,"ContStates")> "
        %assign paramName= isScalableMRSys ? "*localX_" : "*localX"
        %assert !isCPPEncapMdlRef
        %<FcnAddParameter(dataType, paramName)>
        %if isScalableMRSys
          %openfile localCStateVar
          %assign varGroupType = FcnSysVarGroupType(thisSystem,"ContStates")
          %<varGroupType> *localX = (%<varGroupType> *) localX_;
          %closefile localCStateVar
          %<FcnCacheModelRefLocalVars(thisSystem, sysFcn, cTID, localCStateVar)>
        %endif
      %endif
      %%
      %% Continuous States Derivative argument
      %%
      %if !skipLocalXdot && SysFcnArgNeeded(sysFcn, ContStatesDerivativeArgDef, cTID, isRG)
        %assign dataType = isScalableMRSys ? "real_T " : "%<FcnSysVarGroupType(thisSystem,"ContStatesDerivative")> "
        %assign paramName= isScalableMRSys ? "*localXdot_" : "*localXdot"
        %assert !isCPPEncapMdlRef
        %% SLibAutosarCompilerAbstraction not needed for continuous states
        %<FcnAddParameter(dataType, paramName)>
        %if isScalableMRSys
          %openfile localCStateVar
          %assign varGroupType = FcnSysVarGroupType(thisSystem,"ContStatesDerivative")
          %<varGroupType> *localXdot = (%<varGroupType> *) localXdot_;
          %closefile localCStateVar
          %<FcnCacheModelRefLocalVars(thisSystem, sysFcn, cTID, localCStateVar)>
        %endif
      %endif
      %%
      %% Continuous States Disabled argument
      %%
      %if !skipLocalXdis && SysFcnArgNeeded(sysFcn, ContStatesDisabledArgDef, cTID, isRG)
        %assign dataType = isScalableMRSys ? "boolean_T " : "%<FcnSysVarGroupType(thisSystem,"ContStatesDisabled")> "
        %assign paramName= isScalableMRSys ? "*localXdis_" : "*localXdis"
        %assert !isCPPEncapMdlRef
        %% SLibAutosarCompilerAbstraction not needed for continuous states
        %<FcnAddParameter(dataType, paramName)>
        %if isScalableMRSys
          %openfile localCStateVar
          %assign varGroupType = FcnSysVarGroupType(thisSystem,"ContStatesDisabled")
          %<varGroupType> *localXdis = (%<varGroupType> *) localXdis_;
          %closefile localCStateVar
          %<FcnCacheModelRefLocalVars(thisSystem, sysFcn, cTID, localCStateVar)>
        %endif
      %endif
      %%
      %% Continuous States Absolute Tolerance argument
      %%
      %if !skipLocalXabstol && SysFcnArgNeeded(sysFcn, ContStatesAbsoluteToleranceArgDef, cTID, isRG)
        %assign dataType = isScalableMRSys ? "real_T " : ...
          "%<FcnSysVarGroupType(thisSystem,"ContStatesAbsoluteTolerance")> "
        %assign paramName= isScalableMRSys ? "*localXAbsTol_" : "*localXAbsTol"
        %assert !isCPPEncapMdlRef
        %% SLibAutosarCompilerAbstraction not needed for continuous states
        %<FcnAddParameter(dataType, paramName)>
        %if isScalableMRSys
          %openfile localCStateVar
          %assign varGroupType = FcnSysVarGroupType(thisSystem,"ContStatesAbsoluteTolerance")
          %<varGroupType> *localXAbsTol = (%<varGroupType> *) localXAbsTol_;
          %closefile localCStateVar
          %<FcnCacheModelRefLocalVars(thisSystem, sysFcn, cTID, localCStateVar)>
        %endif
      %endif
      %%
       
      %% Continuous States Perturb Min argument
      %%
      %if !skipLocalXperturbmin && SysFcnArgNeeded(sysFcn, ContStatesPerturbMinArgDef, cTID, isRG)
        %assign dataType = isScalableMRSys ? "real_T " : ...
          "%<FcnSysVarGroupType(thisSystem,"ContStatesPerturbMin")> "
        %assign paramName= isScalableMRSys ? "*localXPerturbMin_" : "*localXPerturbMin"
        %assert !isCPPEncapMdlRef
        %% SLibAutosarCompilerAbstraction not needed for continuous states
        %<FcnAddParameter(dataType, paramName)>
        %if isScalableMRSys
          %openfile localCStateVar
          %assign varGroupType = FcnSysVarGroupType(thisSystem,"ContStatesPerturbMin")
          %<varGroupType> *localXPerturbMin = (%<varGroupType> *) localXPerturbMin_;
          %closefile localCStateVar
          %<FcnCacheModelRefLocalVars(thisSystem, sysFcn, cTID, localCStateVar)>
        %endif
      %endif
      
      %%
       %% Continuous States Perturb Max argument
      %%
      %if !skipLocalXperturbmax && SysFcnArgNeeded(sysFcn, ContStatesPerturbMaxArgDef, cTID, isRG)
        %assign dataType = isScalableMRSys ? "real_T " : ...
          "%<FcnSysVarGroupType(thisSystem,"ContStatesPerturbMax")> "
        %assign paramName= isScalableMRSys ? "*localXPerturbMax_" : "*localXPerturbMax"
        %assert !isCPPEncapMdlRef
        %% SLibAutosarCompilerAbstraction not needed for continuous states
        %<FcnAddParameter(dataType, paramName)>
        %if isScalableMRSys
          %openfile localCStateVar
          %assign varGroupType = FcnSysVarGroupType(thisSystem,"ContStatesPerturbMax")
          %<varGroupType> *localXPerturbMax = (%<varGroupType> *) localXPerturbMax_;
          %closefile localCStateVar
          %<FcnCacheModelRefLocalVars(thisSystem, sysFcn, cTID, localCStateVar)>
        %endif
      %endif
      %%
       
       
       
      %% ZcSignalValue argument
      %%
      %if !skipLocalZCSV && SysFcnArgNeeded(sysFcn,ZCSVArgDef, cTID, isRG)
        %if SLibAutosarCompilerAbstractionRequired()
          %assign dataType = isScalableMRSys ? "real_T" : "%<FcnSysVarGroupType(thisSystem,"ZCSV")>"
          %assign paramName= isScalableMRSys ? "localZCSV_" : "localZCSV"
          %assert !isCPPEncapMdlRef
          %<FcnAddParameterWithCompilerAbstraction(TLC_FALSE, dataType, TLC_TRUE, paramName)>
        %else
          %assign dataType = isScalableMRSys ? "real_T " : "%<FcnSysVarGroupType(thisSystem,"ZCSV")> "
          %assign paramName= isScalableMRSys ? "*localZCSV_" : "*localZCSV"
          %assert !isCPPEncapMdlRef
          %<FcnAddParameter(dataType, paramName)>
        %endif
        %if isScalableMRSys
          %openfile localCStateVar
          %assign varGroupType = FcnSysVarGroupType(thisSystem,"ZCSV")
          %<varGroupType> *localZCSV = (%<varGroupType> *) localZCSV_;
          %closefile localCStateVar
          %<FcnCacheModelRefLocalVars(thisSystem, sysFcn, cTID, localCStateVar)>
        %endif
      %endif
      %%
      %% ZCEvent H-Struct argument
      %if !skipLocalZCE && !isCPPEncapMdlRef && SysFcnArgNeeded(sysFcn, ZCEventArgDef, cTID, isRG)
        %if !isScalableMRSys
          %if SLibAutosarCompilerAbstractionRequired()
            %assign dataType = FcnSysVarGroupType(thisSystem,"ZCEvent")
            %<FcnAddParameterWithCompilerAbstraction(TLC_FALSE, dataType, TLC_TRUE, "localZCE")>
          %else
            %assign dataType = FcnSysVarGroupType(thisSystem,"ZCEvent") + " "
            %<FcnAddParameter(dataType, "*localZCE")>
          %endif
        %endif
      %endif %% SysFcnArgNeeded
      %%
      %% Coder Data Groups - add RTM to the interface
      %%
      %if IsModelReferenceBaseSys(thisSystem) && !SLibGetUseRTMcgType() && !isOutlinedBlockFcn
        %openfile coderDataGroupVar
        %foreach gIdx = ::CompiledModel.NumCoderDataGroups
          %assign group = ::CompiledModel.CoderDataGroup[gIdx]
            %if SLibAccessGroupThroughSelf(group)
              %assign groupToken = "CoderDataGroup" + group.Name
              %assign argDef = %
              %if SysFcnArgNeeded(sysFcn, argDef, cTID, isRG)
                %assign varGroupIdx = FcnSysVarGroupIndex(System[sysIdx], groupToken, 0)
                %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
                %assign varGroupType = FcnSysVarGroupType(::CompiledModel.System[sysIdx], groupToken)
                %assign varName = varGroup.LocalName
                %<SLibTypeQualifierForGroup(group)> %<SLibCoderDataGroupType(group)> *%<varName> = %<SLibGetCoderDataGroupPointerFromRTM(group, 0)>;
              %endif
            %endif
        %endforeach
        %closefile coderDataGroupVar
        %if !ISEMPTY(coderDataGroupVar)
          %<FcnCacheModelRefLocalVars(thisSystem, sysFcn, cTID, coderDataGroupVar)>
        %endif
      %endif
      %%
      %%
      %% Canonical Parameters
      %%
      %foreach argIdx=NumCanonicalPrmArgDefs
        %assign canPrmDef = CanonicalPrmArgDef[argIdx]
        %if !skipCanParam[argIdx] && SysFcnArgNeeded(sysFcn, canPrmDef, cTID, isRG)
          %assign identi = LibGetRecordIdentifier(canPrmDef)
          %assign dataType = SLibGetRecordDataTypeName(canPrmDef, "")
          %assign width = LibBlockParameterWidth(canPrmDef)
          %assign optWidth = LibOptionalVectorWidth(width)
          %assign declAsPtr = canPrmDef.DeclareAsPointer == "yes"
          %if SLibAutosarCompilerAbstractionRequired()
            %assign optConst = ((width > 1) || declAsPtr)
            %assign optStar = declAsPtr
            %assign argDef = "%<identi>%<optWidth>"
            %<FcnAddParameterWithCompilerAbstraction(optConst, dataType, optStar, argDef)>
          %else
            %assign optConst = ((width > 1) || declAsPtr) ? "const " : ""
            %assign dataType = "%<optConst>%<dataType> "
            %assign optStar = declAsPtr ? "*" : ""
            %assign argDef = "%<optStar>%<identi>%<optWidth>"
            %<FcnAddParameter(dataType, argDef)>
          %endif
        %endif %% SysFcnArgNeeded
      %endforeach %% argIdx=NumCanonicalPrmArgDefs
      %%
      %% CanonicalDWork
      %%
      %foreach argIdx = NumCanonicalDWorkArgDefs
        %% Canonical dimsize dwork has already beed added to the
        %% args following the corresponding canonical input/output
        %if !skipCanDWork[argIdx] && !SLibGetCanDWorkIsCanDimSizeDWork(argIdx)
          %assign canDWork = CanonicalDWorkArgDef[argIdx]
          %if SysFcnArgNeeded(sysFcn, canDWork, cTID, isRG)
            %assign dwIdx = canDWork.FirstSignalSrc %% global idx
            %assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
            %assign dwWidth = SLibDWorkWidth(dwRec)
            %assign dwId = LibGetRecordIdentifier(canDWork)
            %assign dataType = SLibGetRecordDataTypeName(dwRec, "")
            %%
            %% Example:
            %% Scalar signal: void foo(real_T *a)
            %% Wide signal: void foo(real_T b[7])
            %%
            %if SLibAutosarCompilerAbstractionRequired()
              %if dwWidth == 1
                %assign argDef = "%<dwId>"
              %else
                %assign argDef = "%<dwId>[%<dwWidth>]"
              %endif
              %<FcnAddParameterWithCompilerAbstraction(TLC_FALSE, dataType, (dwWidth == 1), argDef)>
            %else
              %if dwWidth == 1
                %assign argDef = " *%<dwId>"
              %else
                %assign argDef = " %<dwId>[%<dwWidth>]"
              %endif
              %<FcnAddParameter(dataType,argDef)>
            %endif
          %endif
        %endif %% if !SLibGetCanDWorkIsCanDimSizeDWork
      %endforeach
    %elseif SLibNeedHandleParallelForEachSS(thisSystem, sysFcn)
      %% Add argument (int32_T rtSS_iter) for parallel ForEach Subsystem
      %assign dw = DWorks.DWork[IDNUM(thisSystem.IndexingSigSrc)[1]]
      %if dw.IsLocalScratchDWork == 1
        %assign argDef = LibGetRecordIdentifier(dw)
        %assign dataType = SLibGetRecordDataTypeName(dw,"") + " "
        %<FcnAddParameter(dataType, argDef)>
      %endif
    %endif
  %endwith
%endfunction
 
%%Function:FcnGetSfcnFormDefine==================================================================
%%Abstract:
%%Returnthe#definethatisneededinfrontofrootmodelmethodsin
%%S-functionformat
%%
%function FcnGetSfcnFormDefine(sysFcn) void
  %assign retVal = ""
  %switch sysFcn
    %case "Start"
      %assign retVal = "MDL_START"
      %break
    %case "Initialize"
      %assign retVal = "MDL_INITIALIZE_CONDITIONS"
      %break
    %case "Enable"
      %assign retVal = "RTW_GENERATED_ENABLE"
      %break
    %case "Disable"
      %assign retVal = "RTW_GENERATED_DISABLE"
      %break
    %case "Update"
      %assign retVal = "MDL_UPDATE"
      %break
    %case "Derivative"
      %assign retVal = "MDL_DERIVATIVES"
      %break
    %case "ForcingFunction"
      %assign retVal = "MDL_FORCINGFUNCTION"
      %break
    %case "MassMatrix"
      %assign retVal = "MDL_MASSMATRIX"
      %break
    %case "Projection"
      %assign retVal = "MDL_PROJECTION"
      %break
    %case "ZeroCrossing"
      %assign retVal = "MDL_ZERO_CROSSINGS"
      %break
    %default
      %assign retVal = ""
      %break
  %endswitch
 
  %return retVal
%endfunction %% FcnGetSfcnFormDefine
 
%%Function:FcnReplaceCCastWithStaticCastForCPP===================================================
%%Abstract:FunctiontoreplaceC-stylecastingwithstatic_castforC++
%%codegeneration.
%%TopTester:test/toolbox/rtw/cpp/cppclassgen/tTypeCasting.m
%%
%function FcnReplaceCCastWithStaticCastForCPP(inputArg)
  %return CGMODEL_ACCESS("CGModel.replaceCCastWithStaticCast", inputArg)
%endfunction %%FcnReplaceCCastWithStaticCastForCPP
 
%%Function:FcnRewriteCast========================================================================
%%Abstract:ThisfunctionrewritesaC-stylecastforC++codegeneration,and
%%returntheoriginalexpressionforC.
%%
%function FcnRewriteCast(aCast)
  %if ::GenCPP && !::Accelerator
    %return FcnReplaceCCastWithStaticCastForCPP(aCast)
  %else
    %return aCast
  %endif
%endfunction %% FcnRewriteCast
 
%%Function:FcnUseStaticStorageSpecifier==========================================================
%%Abstract:Functiontodetermineifstatickeywordshouldbeprependedto
%%asubsystemprototype.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnUseStaticStorageSpecifier(system)
  %assign compactFileFormat = SLibIsCompactFileFormat()
  %assign isReusedLibraryFcn = LibSystemIsReusedLibraryFcn(system)
  %assign isExportedSlFcn = SLibIsModelScopedServer(system)
  %assign useStatic = compactFileFormat && ...
  (!LibSystemIsRoot(system) || !(IsModelReferenceBaseSys(system) && IsModelReferenceTarget())) && ...
  !IsModelReferenceTarget() && !LibIsGlobalServer(system) && ...
  !SLibGenSubsysFcnAsClassMemFcn(system) && !isReusedLibraryFcn && ...
  !::CompiledModel.ConfigSet.GenerateTestInterfaces && !isExportedSlFcn
  %return useStatic
%endfunction %% FcnUseStaticStorageSpecifier
 
%%Function:FcnUseExternStorageSpecifier==========================================================
%%Abstract:Functiontodetermineifexternkeywordshouldbeprependedto
%%asubsystemprototype.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnUseExternStorageSpecifier(system)
  %assign genClassMemFcn = SLibGenSubsysFcnAsClassMemFcn(system)
  %assign useExtern = LibPreserveExternInFcnDecls() && ...
    (UsingMalloc == 0) && !genClassMemFcn
  %return useExtern
%endfunction %% FcnUseExternStorageSpecifier
 
 
%<LibAddToCompiledModel("SubsystemPrototypesCache", "")>
%%Function:LibCacheSubsystemPrototype============================================================
%%Abstract:
%%Cacheafunctionprototype(incasethefilesplits)
%%
%%Arguments:
%%system:Referstothesystemwhoseprototypewearecaching
%%fcn:ReferencetoaFcnRec(seetopoffilefordefinitionofRecord)
%%
%%
%%Example:
%%fcn.Returns="real_T*"
%%fcn.Name="foo"
%%fcn.Params="int_Ti"
%%
%%caches:(in'system.SystemFcnPrototype')
%%C-
%%"externreal_T*foo(int_Ti);"
%%
%%Ada-
%%packagesystemis
%%proceduresystem_output
%%endsystem
%%
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall3.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%Toptetser:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tIVfcnCall_neg.m
%%
%function LibCacheSubsystemPrototype(system,fcn) void
  %% Cache extern only if the storage class is non-static
  %assign genClassMemFcn = SLibGenSubsysFcnAsClassMemFcn(system)
 
  %assign staticOrExternSpecifier = ""
  %if(CGMODEL_ACCESS("CGModel.AddStaticKeywordToFcn"))
    %if FcnUseStaticStorageSpecifier(system)
      %assign staticOrExternSpecifier = "static "
    %elseif FcnUseExternStorageSpecifier(system)
      %assign staticOrExternSpecifier = !genClassMemFcn ? "extern " : ""
    %endif
  %else
    %if FcnUseExternStorageSpecifier(system)
      %assign staticOrExternSpecifier = !genClassMemFcn ? "extern " : ""
    %endif
  %endif
 
  %if(CGMODEL_ACCESS("CGModel.AddInlineKeywordToFcns", system.SystemIdx))
    %assign staticOrExternSpecifier = staticOrExternSpecifier + "inline "
  %endif
 
  %assign sysFcnType = fcn.SysFcn
  %if (sysFcnType == "Initialize" || sysFcnType == "SystemInitialize" || sysFcnType == "SystemReset" ||sysFcnType == "Start" || sysFcnType == "Terminate")
    %assign msFcnType = "MemSecFuncInitTerm"
  %else
    %assign msFcnType = "MemSecFuncExecute"
  %endif
  %assign ppIf = SLibVariantConditionForTID(system.CurrentTID)
  %openfile ssp
  %if !ISEMPTY(ppIf)
    %<SLibIfVariantConditionForm(ppIf)>
  %endif
  %<SLibIfSystemVariantCondition(system)>
  %assign useIndividualMapping = TLC_FALSE
  %assign functionType = ""
  %assign functionId = "" %% Assume
  %if CGMODEL_ACCESS("CGModel.isIndividualFunctionMappingEnabled")
    %if IsModelReferenceTarget()
      %% Model Reference build
      %if (sysFcnType == "ModelInitialize") && TLC_FALSE
        %% Initialize function
        %% NOTE: Skip this (this is re-computed in formatmodelref.tlc)
        %assign functionType = "Initialize"
        %assign useIndividualMapping = TLC_TRUE
      %elseif (sysFcnType == "Terminate")
        %% Terminate function
        %assign functionType = "Terminate"
        %assign useIndividualMapping = TLC_TRUE
      %elseif (sysFcnType == "OutputUpdate") || (sysFcnType == "Output") || ...
        (sysFcnType == "Update")
        %if SLibExplicitTaskingTID(system.CurrentTID)
          %if SLibResetOrResetWithInitEventTID(system.CurrentTID)
            %% Reset function
            %assign functionType = "Reset"
            %assign functionId = SampleTime[system.CurrentTID].EventSourceName
            %assign useIndividualMapping = TLC_TRUE
          %elseif SLibIsRateGroupedSLFcn(system, sysFcnType, system.CurrentTID)
            %% Global or Public Simulink Function in export function model
            %assign functionType = "SimulinkFunction"
            %assign functionId = SLibGetRateGroupedSimulinkFunctionName(system, sysFcnType, system.CurrentTID)
            %assign useIndividualMapping = TLC_TRUE
          %elseif !LibIsServer(system) && ...
            SLibIsExplicitTaskingExportFcnRateGrouping(sysFcnType, system.CurrentTID)
            %% Export or Async function
            %% NOTE: SampleTime[tid].TaskName returns block name for export function,
            %% and full block path for async function
            %assign functionType = "FcnCallInport"
            %assign functionId = FEVAL("regexprep", ...
              SampleTime[system.CurrentTID].TaskName, ".*//", "")
            %assign useIndividualMapping = TLC_TRUE
          %elseif SLibIsExplicitPartitioningTID(system.CurrentTID)
            %% Partition via schedule editor
            %if (sysFcnType == "OutputUpdate")
              %assign functionType = "Step"
            %elseif (sysFcnType == "Output")
              %assign functionType = "Output"
            %elseif (sysFcnType == "Update")
              %assign functionType = "Update"
            %endif
            %assign functionId = system.CurrentTID
            %assign useIndividualMapping = TLC_TRUE
          %endif
        %else
          %if !SLibIsExportFcnDiagram()
            %if (LibIsGlobalServer(system) || SLibIsModelScopedServer(system))
              %% Global or Exported Global Scoped Function in a rate-based model
              %assign functionType = "SimulinkFunction"
              %assign functionId = SLibGetSimulinkFunctionNameInNonExportFcnModel(system)
              %assign useIndividualMapping = TLC_TRUE
            %else
              %% Implicit periodic functions
              %if (sysFcnType == "OutputUpdate")
                %assign functionType = "Step"
              %elseif (sysFcnType == "Output")
                %assign functionType = "Output"
              %elseif (sysFcnType == "Update")
                %assign functionType = "Update"
              %endif
              %assign functionId = system.CurrentTID
              %assign useIndividualMapping = TLC_TRUE
            %endif
          %endif
        %endif
      %endif
    %else
      %% Top Model build
      %if (LibIsGlobalServer(system) || SLibIsModelScopedServer(system))
        %% Global or Exported Global Scoped Function in a rate-based model
        %assign functionType = "SimulinkFunction"
        %assign functionId = SLibGetSimulinkFunctionNameInNonExportFcnModel(system)
        %assign useIndividualMapping = TLC_TRUE
      %endif
    %endif
  %endif
  %if !GenerateClassInterface
    %if useIndividualMapping
      %<SLibGetFcnMemSecPragmaForFunction(fcn.Name, functionType, functionId, "Pre")>/
    %else
      %<SLibGetFcnMemSecPragmaForSystemOnDecl(fcn.Name, msFcnType, "Pre", system)>/
    %endif
  %endif
  %<staticOrExternSpecifier>%<fcn.FcnPrototype>;
  %if !GenerateClassInterface
    %if useIndividualMapping
      %<SLibGetFcnMemSecPragmaForFunction(fcn.Name, functionType, functionId, "Post")>/
    %else
      %<SLibGetFcnMemSecPragmaForSystemOnDecl(fcn.Name, msFcnType, "Post", system)>/
    %endif
  %endif
  %<SLibEndIfSystemVariantCondition(system)>
  %if !ISEMPTY(ppIf)
    %<SLibEndIfVariantConditionForm(ppIf)>
  %endif
 
  %closefile ssp
  %% To avoid warnings, use a different name for the
  %% rtModel in the function declaration than in the
  %% function body.
  %if GenRTModel
    %assign rtm = " *%<::tSimStruct>"
    %assign lowerrtm = " *%<SLibGetSimStruct()>"
    %assign ssp = FEVAL("strrep",ssp, rtm, lowerrtm)
  %endif
  %assign fileOwnerSystem = ::CompiledModel.System[system.FileNameOwnerIdx]
  %if IsModelRefScalableBuild() && IsModelReferenceBaseSys(system)
    %assert (system.FileNameOwnerIdx == system.SystemIdx)
    %if !GenerateClassInterface
      %if !LibIsSystemField(system, "MRSystemFcnPrototype")
        %<LibAddToSystem(fileOwnerSystem, "MRSystemFcnPrototype", ssp)>
      %else
        %<LibAddToSystemField(fileOwnerSystem, "MRSystemFcnPrototype", ssp)>
      %endif
    %endif
  %else
    %if !SLibGenSubsysFcnAsClassMemFcn(system)
      %if LibIsServer(system)
        %if ((!LibIsGlobalServer(system)) || sysFcnType != "OutputUpdate") ...
          || SLibResetOrResetWithInitEventTID(system.CurrentTID)
          %% If it is a SL function but not a global SLFcn, or a global SLFcn, but fcnType != "OutputUpdate". Declarations need to
          %% be in model.h (if model scoped) or model_private.h (if subsystem scoped). We cannot put them into fileOwnerSystem, as
          %% it would mean the base system, and we cannot make SLFcn specific decisions.
           
          %% If it is a Reset/ResetWithInit output function, put it into fileOwnerSystem, even the
          %% simulink function is global. So the Reset/ResetWithInit function at the root level can
          %% see the definition of the Reset/ResetWithInit inside the simulink function. see
          %% g2066071.
          %<LibAddToSystemField(system, "SystemFcnPrototype", ssp)>
        %endif
      %else
         %<LibAddToSystemField(fileOwnerSystem, "SystemFcnPrototype", ssp)>
      %endif
    %else
      %% When in generating subsystem funcitons as C++ member function mode,
      %% system function prototoype cannot be put in the file owner subsystem, as they will
      %% need to be put into root_model.h
      %if (!LibIsServer(system)) || ...
        (FcnIsServerPublicAccess(system) && sysFcnType == "OutputUpdate" && ...
        SLibIsExportFcnDiagram() && ...
        !SLibModelWideEventTID(system.CurrentTID))
        %<LibAddToSystemField(system, "EncapSystemFcnPrototype", ssp)>
      %else
        %% SlFcn prototypes placed in System Member Prototypes will become private access methods
        %<LibAddToSystemField(system, "SystemMemberPrototype", ssp)>
      %endif
    %endif
  %endif
 
%endfunction %% LibCacheSubsystemPrototype
 
%%Function:LibDumpSystemPrototype================================================================
%%Abstract:
%%Placethesystemfunctionprototypesintheoutputstream.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function LibDumpSystemPrototype(system) Output
  %assign systemFcnPrototype = LibGetSystemField(system,"SystemFcnPrototype")
  %if !WHITE_SPACE(systemFcnPrototype)
    %<systemFcnPrototype>/
  %endif
%endfunction %% LibDumpSystemPrototype
 
%%Function:SLibGetNeedLocalTIDFieldName==========================================================
%%Abstract:
%%
%function SLibGetNeedLocalTIDFieldName(system, fcnType) void
  %return "NeedLocalTIDIn" + ...
    ((fcnType == "Outputs" || fcnType == "OutputUpdate") ? "Output" : fcnType)
%endfunction
 
%%Function:SLibSetNeedLocalTIDInSystem===========================================================
%%Abstract:
%%
%function SLibSetNeedLocalTIDInSystem(system, fcnType) void
  %assign fieldName = SLibGetNeedLocalTIDFieldName(system, fcnType)
  %if ISFIELD(system, fieldName)
    %<SETFIELD(system, fieldName, TLC_TRUE)>
  %else
    %addtorecord system %<fieldName> TLC_TRUE
  %endif
%endfunction
 
%%Function:SLibGetNeedLocalTIDInSystem===========================================================
%%Abstract:
%%
%function SLibGetNeedLocalTIDInSystem(system, fcnType)
  %assign fieldName = SLibGetNeedLocalTIDFieldName(system, fcnType)
  %if ISFIELD(system, fieldName)
    %return GETFIELD(system, fieldName)
  %else
    %return TLC_FALSE
  %endif
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibTIDInSystem=========================
%%Abstract:
%%Thisfunctionreturnsatidifitisinthescopeofasubsystemfunction
%%andcanbecalledbeforeorduringTLCgeneratingcode.
%%Itreturnsthetidargumentname,ifatidispassedasargumentinthe
%%systemfunctionscope.
%%
%%Iftidisnotpassedasargumentinthescope,thisfunctionreturns:
%%1.'0'ifmodelissingletasking,
%%2.thetidvalueofthesubsystemifthesubsystemissinglerate,
%%3.returnsalocaltidvariablename,ifthesubsystemismultirate.
%%Alocaltidvariablewillbeaddedtothesubsystemcode.
%%
%%Note:
%%Thisfunctionissueanerrormessage,ifitiscalledforareusable
%%subsystemwhoseinstancerunatdifferentrate.
%%
%%Example:
%%LibTIDInSystem(system,fcnType)
%%
%%system-isarecordwithintheglobal::CompiledModelrecord.
%%fcnType-canbeanyofthefollowing:'Output','Update','Outputupdate'
%%
%function LibTIDInSystem(system, fcnType) void
  %assert (fcnType == "Output" || ...
    fcnType == "Update" || fcnType == "OutputUpdate")
  %if ::CompiledModel.NumSampleTimes == 1 || ...
    SLibSingleTasking()
    %return "0"
  %elseif LibIsSingleRateSystem(system)
    %assign tmpTid = FcnGetSubsystemTID(system, TLC_TRUE)
    %if tmpTid == -1
      %<SLibReportErrorWithIdAndArgs("RTW:tlc:ReuseOfDifferentRate", "%<system.Name>")>
    %else
      %return FcnGetSubsystemTID(system, TLC_TRUE)
    %endif
  %else
    %if IsModelReferenceBaseSys(system)
      %<SLibReportErrorWithIdAndArgs("RTW:tlc:IncorrectLibTIDCall", "%<system.Name>")>
    %else
      %<SLibSetNeedLocalTIDInSystem(system, fcnType)>
      %return ::tTID
    %endif
  %endif
%endfunction %% LibTIDInSystem
 
%%Function:SLibDumpLocalTidInSystem==============================================================
%%Abstract:
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%
%function SLibDumpLocalTidInSystem(system, fcn)
  %% Do need dump local tid is a subsystem for an async rate
  %% if the subsystem is not async the async rate. In this case,
  %% async code for this subsystem is going to be grouped in
  %% the async task entry functions. The code doesn't belong to
  %% this subsystem eventually.
  %if LibAsynchronousTriggeredTID(system.CurrentTID) && ...
    !SLibModelWideEventTID(system.CurrentTID) && ...
    system.CurrentTID != LibGetSubsystemTID(system,TLC_TRUE)
    %return ""
  %endif
  %assign needLocalTid = SLibGetNeedLocalTIDInSystem(system,fcn)
  %if fcn == "OutputUpdate"
    %assign needLocalTid = needLocalTid || ...
      SLibGetNeedLocalTIDInSystem(system,"Output") || ...
      SLibGetNeedLocalTIDInSystem(system,"Update")
  %endif
  %openfile tmpBuf
  %if needLocalTid && !LibSystemFcnNeedsTID(system, fcn)
    %% System need local tid value, but does not pass in tid arg
    %if SLibSingleTasking()
      %assign tidValue = 0
    %else
      %% CurrentTID is set only if the system generate rate grouping
      %% code. Otherwise, we need get tid value from system record directly.
      %assign tidValue = !SLibSystemFcnPeriodicRateGrouping(system, fcn) ? ...
        FcnGetSubsystemTID(system,!LibIsSingleRateSystem(system)) : ...
        system.CurrentTID
    %endif
    %if ISEMPTY(tidValue)
      %<LibReportFatalError("TID value is empty")>
    %endif
    int_T %<::tTID> = %<tidValue>;
  %endif
  %closefile tmpBuf
 
  %return tmpBuf
%endfunction
 
%%Function:LibDumpFcnOpen========================================================================
%%Abstract:
%%Dumptheopening(start)ofthespecifiedfunction(e.g.Output).
%%
%function LibDumpFcnOpen(system,function) Output
  %assign fcnInfo = LibGetFcnInfo(system, function, system.CurrentTID)
  %if fcnInfo.SfcnFormDefine != ""
    #define %<fcnInfo.SfcnFormDefine>
  %endif
  %<fcnInfo.Open>/
  %<SLibDumpLocalTidInSystem(system, function)>
%endfunction %% LibDumpFcnOpen
 
%%Function:LibDumpFcnBegin=======================================================================
%%Abstract:
%%Dumpthebeginningofthefunction(e.g.Output)code.
%%
%function LibDumpFcnBegin(system,function) Output
  %assign fcnInfo = LibGetFcnInfo(system, function, system.CurrentTID)
  %<fcnInfo.Begin>/
%endfunction %%LibDumpFcnBegin
 
%%Function:LibDumpFcnClose=======================================================================
%%Abstract:
%%Dumptheclosingofthespecifiedfunction(e.g.Output).
%%
%function LibDumpFcnClose(system,function) Output
  %assign fcnInfo = LibGetFcnInfo(system, function, system.CurrentTID)
  %<fcnInfo.Close>/
%endfunction %% LibDumpFcnClose
 
%%Function:FcnSysFcnHasRTM=======================================================================
%%Abstract:
%%Returnswhetherasystemfcnneedstherealtimemodelasanarg
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnSysFcnHasRTM(system, sysFcn) void
  %assign cTID = system.CurrentTID
  %assign isRG = SLibSystemFcnPeriodicRateGrouping(system, sysFcn)
  %with system.Interface
    %assign hasRTM = SysFcnArgNeeded(sysFcn, RTMArgDef, cTID, isRG) && ...
      LibSystemIsReusedFcn(system) && !LibSystemIsRoot(system)
  %endwith
  %return hasRTM
%endfunction
 
%%Function:FcnSysNeedAddRTMArg===================================================================
%%Abstract:
%%Thisfunctionreturntruewhenthesubsystem
%%doesn'thavertmarg,butitmustbeaddedtoarglistdueto:
%%1.S-Functiontarget
%%2.Malloctarget(grtmalloc)orERTMulti-Instance,
%%andsystemcrossflagistrue
%%(Noreusablesysteminreusablesystem).
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnSysNeedAddRTMArg(system, sysFcn) void
  %if FcnSysFcnHasRTM(system, sysFcn)
    %return TLC_FALSE
  %else
    %return (CodeFormat == "S-Function") || ...
     (system.CrossNoArgFcnBound && (UsingMalloc || (MultiInstanceERTCode && !GenerateClassInterface))) ...
      && system.IsService == 0
  %endif
%endfunction
 
%%Function:SLibIsFcnSubFunction(system,sysFcn)void
%%Abstract:
%%ThisfunctionreturnstruewhensysFcnisasub-functioninsystem
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibIsFcnSubFunction(system, sysFcn)
  %assign module = ::CompiledModel.RTWCGModules.RTWCGModule[system.CGIRModuleIdx]
  %assign isSubFunction = TLC_FALSE
  %if ISFIELD(module, "SystemFunctions") && ISFIELD(module.SystemFunctions, sysFcn)
    %assign fcnIdx = GETFIELD(module.SystemFunctions, sysFcn)
    %if fcnIdx < module.NumSubFunctions
      %assign isSubFunction = TLC_TRUE
    %endif
  %endif
  %return isSubFunction
%endfunction
 
%%Function:SLibSystemHasExportedFunction=========================================================
%%Abstract:
%%Thisfunctiondeterminesif
%%1)Thesystemisafunctioncallsystem
%%2)Thesystemfunctionisexported
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibSystemHasExportedFunction(system) void
  %assign retVal = TLC_FALSE
  %if ExportFunctionsMode == 1
    %assign retVal = (system.Type == "function-call" && system.Exported == "yes" )
  %elseif ExportFunctionsMode == 2 && system.Type == "function-call" && ...
      system.DescSysNonTrigTID[0] >= NumRuntimeExportedRates
    %assign retVal = TLC_TRUE
  %endif
  %return retVal
%endfunction
 
 
%%Function:SLibSystemFcnInfoRecord===============================================================
%%Abstract:
%%ReturnsthefunctioninforecordforLibDefineSystemFcn.
%%SeeLibDefineSystemFcn
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall3.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/autoInherit/tmWithCombSpecAndInherit_VC1.m
%%TopTester:test/toolbox/simulink/variants/normalMATLABVariableSupport/tNormalMatlabVariable2.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/dimensionVariants/tDimensionVariants.m
%%TopTester:test/toolbox/simulink/variants/modelVariants/tVariantsBasic.m
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Gain/rtw/tdtgain4.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/inlineVariants/tInlineVariants10.m
%%
%function SLibSystemFcnInfoRecord(system, sysFcn) void
  %<FcnResetFunctionRecord()>
  %assign fcnname = sysFcn + "Fcn"
  %assign sysIdx = system.SystemIdx
  %assign isRoot = (system.Type == "root")
 
  %% In the exporting functions model 1 (exporting functions), we want to
  %% use the user specified function name to the wrapper. Thus the real
  %% function is rename to fcnname_core
  %assign functionExported = TLC_FALSE
  %if ExportFunctionsMode == 1 && system.Type == "function-call" && ...
    sysFcn == "OutputUpdate"
    %%
    %assign rootSystem = System[NumSystems-1]
    %foreach id = rootSystem.NumChildSystems
      %assign systemId = rootSystem.ChildSystems[id][0]
      %if systemId == sysIdx
        %assign functionExported = TLC_TRUE
        %break
      %endif
    %endforeach
  %endif
 
  %assign getFcnNameFromFPC = TLC_FALSE
  %% Try to get function name from FPC
  %if IsModelReferenceBaseSys(system)
    %if (sysFcn == "OutputUpdate") && ...
      SLibFcnProtoCtrlActive()
      %assign FPC = FcnGetFunctionPrototypeRecord()
      %assign ::FcnRec.Name = FPC.FunctionName
      %assign getFcnNameFromFPC = TLC_TRUE
    %elseif (sysFcn == "Initialize") && ...
      SLibFcnProtoCtrlActive()
      %assign FPC = FcnGetFunctionPrototypeRecord()
      %assign ::FcnRec.Name = FPC.InitFunctionName
      %assign getFcnNameFromFPC = TLC_TRUE
    %elseif GenerateClassInterface
      %assign getFcnNameFromFPC = TLC_TRUE
      %assign FPC = FcnGetRTWCPPStepPrototypeRecord()
      %if sysFcn == "OutputUpdate"
        %if ISFIELD(FPC,"FunctionName")
          %if (!ISEMPTY(system.CurrentTID) && ISFIELD(SampleTime[system.CurrentTID],"EventSourceName"))
            %if ISFIELD(SampleTime[system.CurrentTID],"EntryFcnName")
              %assign ::FcnRec.Name = FPC.ModelClassName + "::" + SampleTime[system.CurrentTID].EntryFcnName
            %endif
          %else
            %assign ::FcnRec.Name = FPC.ModelClassName + "::" + FPC.FunctionName
          %endif
        %elseif SLibIsExplicitTaskingExportFcnRateGrouping(sysFcn,system.CurrentTID) || ...
          (!ISEMPTY(system.CurrentTID) && ISFIELD(SampleTime[system.CurrentTID],"EventSourceName"))
          %if ISFIELD(SampleTime[system.CurrentTID],"EntryFcnName")
            %assign ::FcnRec.Name = FPC.ModelClassName + "::" + SampleTime[system.CurrentTID].EntryFcnName
          %endif
        %endif
      %elseif SLibIsExplicitTaskingExportFcnRateGrouping(sysFcn,system.CurrentTID)
        %assign ::FcnRec.Name = FPC.ModelClassName + "::" + SampleTime[system.CurrentTID].EntryFcnName
      %elseif sysFcn == "SystemInitialize"
        %assign ::FcnRec.Name = FPC.ModelClassName + "::" + "init"
      %elseif sysFcn == "SystemReset"
        %assign ::FcnRec.Name = FPC.ModelClassName + "::" + "reset"
      %elseif sysFcn == "Start"
        %assign ::FcnRec.Name = FPC.ModelClassName + "::" + "start"
      %elseif sysFcn == "Terminate"
        %assign ::FcnRec.Name = FPC.ModelClassName + "::" + "terminate"
      %elseif sysFcn == "Enable"
        %assign ::FcnRec.Name = FPC.ModelClassName + "::" + "enable"
      %elseif sysFcn == "Disable"
        %assign ::FcnRec.Name = FPC.ModelClassName + "::" + "disable"
      %elseif sysFcn == "SetupRuntimeResources"
        %assign ::FcnRec.Name = FPC.ModelClassName + "::" + "setupruntimeresources"
      %elseif sysFcn == "CleanupRuntimeResources"
        %assign ::FcnRec.Name = FPC.ModelClassName + "::" + "cleanupruntimeresources"
      %endif
    %endif
  %endif
  %% get fcn name from system record.
  %assert(ISFIELD(system,fcnname))
  %assign fcnName = GETFIELD(system, fcnname)
  %assign modIdx = system.CGIRModuleIdx
  %assign ownerModule = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
  %if ISFIELD(ownerModule ,"SystemFunctions") && ISFIELD(ownerModule.SystemFunctions, fcnName)
    %assign fcnIdx = ownerModule.SystemFunctions.%<fcnName>
    %assign fcn = ownerModule.Function[fcnIdx]
    %assign isOutlinedBlockFcn = fcn.IsOutlinedBlockFcn
  %else
    %assign isOutlinedBlockFcn = TLC_FALSE
  %endif
  %assign updateFcnRecName = TLC_TRUE
  %assign isRootOrMdlRefBaseSystem = isRoot || IsModelReferenceBaseSys(system)
  %assign exportFcnMode = TLC_FALSE
  %assign isExternFcn = TLC_FALSE
  %assign isAsyncTriggered = TLC_FALSE
  %if ((sysFcn == "OutputUpdate") || (sysFcn == "Output")) && ...
    TYPE(system.CurrentTID) == "Number" && system.CurrentTID > 0 && ...
    ISFIELD(SampleTime[system.CurrentTID],"EntryFcnName") && ...
    !ISEMPTY(SampleTime[system.CurrentTID].EntryFcnName) && ...
    !SLibNonInlinedIRTEventTID(system.CurrentTID) && ...
    isRootOrMdlRefBaseSystem
    %if LibAsynchronousTriggeredTID(system.CurrentTID) && isRootOrMdlRefBaseSystem
      %assign isAsyncTriggered = TLC_TRUE
    %endif
    %if !getFcnNameFromFPC
      %assign ::FcnRec.Name = SampleTime[system.CurrentTID].EntryFcnName
    %endif
    %if SLibIsExplicitTaskingExportFcnRateGrouping(sysFcn,system.CurrentTID) && GenerateClassInterface
      %assign FPC = FcnGetRTWCPPStepPrototypeRecord()
      %assign ::FcnRec.Name = FPC.ModelClassName + "::" + SampleTime[system.CurrentTID].EntryFcnName
    %endif
    %% Added below check for test/toolbox/simulink/sampletimes/tSTO_ExportFcn -lvlTwo_Export_Periodic_FcnCall
    %if !SLibIsExportFcnDiagram() || !LibAsynchronousTriggeredTID(system.CurrentTID) || IsModelReferenceBaseSys(system)
      %assign fcnName = SampleTime[system.CurrentTID].EntryFcnName
    %endif
    %assign updateFcnRecName = TLC_FALSE
    %assign appendTIDToFcnName = TLC_FALSE
    %assign exportFcnMode = TLC_TRUE
  %elseif SLibExplicitTaskingTID(system.CurrentTID)
    %if SLibNonInlinedIRTEventTID(system.CurrentTID) && ((sysFcn == "OutputUpdate") || (sysFcn == "Output"))
      %assign appendTIDToFcnName = TLC_FALSE
 
      %% If the subsystem is a single rate simulink function with only IRT
      %% rate, don't include reset id in the function name.
      %assign isSingleRateServer = LibIsServer(system) && LibIsSingleRateSystem(system)
      %if !isSingleRateServer
        %if isRootOrMdlRefBaseSystem
          %assign fcnName = "%<::CompiledModel.SampleTime[system.CurrentTID].EntryFcnName>"
        %else
          %assign fieldName = "ModelWideEventFcn" + "%<::CompiledModel.SampleTime[system.CurrentTID].EventSourceName>"
          %if ISFIELD(system, "%<fieldName>") && !ISEMPTY(GETFIELD(system, "%<fieldName>"))
            %assign fcnName = GETFIELD(system, "%<fieldName>")
          %endif
        %endif
        %if IsModelReferenceBaseSys(system) && SLibFcnProtoCtrlActive()
          %% For non-inlined irt (reset) don't use fpc, use the reset id instead.
          %assign ::FcnRec.Name = fcnName
        %endif
      %endif
 
    %elseif SLibNonInlinedModelWideEventTID(system.CurrentTID)
      %assign appendTIDToFcnName = FcnSysModuleIsRateGrouping(system, sysFcn)
    %elseif LibAsynchronousTriggeredTID(system.CurrentTID)
      %% Async fcn-call system is single rate,
      %% Never append tid to fcn name
      %% However, for accelerator simulation, an empty update function
      %% will be generated. The Update function must have a TID appended
      %% to avaoid name clashes with the other update fucntions
 
      %% the async is the only runtime rates, and the other are all IRTs, never
      %% append tid to fcn name
      %assign isSingleAsync = TLC_TRUE
      %assign ssTaskToFirstTid = FcnGetSubsystemTaskToFirstTID(system)
      %foreach idx = SIZE(ssTaskToFirstTid, 1)
        %if ssTaskToFirstTid[idx] != system.CurrentTID && ...
          !SLibInitResetTermEventTID(ssTaskToFirstTid[idx])
          isSingleAsync = TLC_FALSE
          %break
        %endif
      %endforeach
      %assign isSingleAsyncUpdateInAccelOrRAccel = (sysFcn == "Update") && ...
                                                   (Accelerator || isRAccel) && ...
                                                   isSingleAsync
 
      %if ((sysFcn == "OutputUpdate") || (sysFcn == "Output") || !Accelerator) || ...
        isSingleAsyncUpdateInAccelOrRAccel
        %assign appendTIDToFcnName = TLC_FALSE
      %else
        %assign appendTIDToFcnName = FcnSysModuleIsRateGrouping(system, sysFcn)
      %endif
    %else
      %% Append tid to fcn name if rate grouping
      %%
      %assign appendTIDToFcnName = SLibSystemFcnPeriodicRateGrouping(system, sysFcn)
      %if (Accelerator || isRAccel) && TYPE(system.CurrentTID) == "Number" && ...
        system.CurrentTID > 0 && system.CurrentTID < NumRuntimeExportedRates
        %assign isExternFcn = TLC_TRUE
      %endif
    %endif
  %elseif SLibIsPeriodicRateGrouping()
    %% Append tid to fcn name if rate grouping
    %if (Accelerator || isRAccel) && TYPE(system.CurrentTID) == "Number"
      %if system.Type == "root" && system.CurrentTID == 0
        %assign appendTIDToFcnName = TLC_FALSE
      %elseif system.CurrentTID < NumRuntimeExportedRates
        %assign appendTIDToFcnName = SLibSystemFcnPeriodicRateGrouping(system, sysFcn)
        %assign isExternFcn = TLC_TRUE
      %endif
    %else
      %assign appendTIDToFcnName = SLibSystemFcnPeriodicRateGrouping(system, sysFcn)
    %endif
 
    %if appendTIDToFcnName && ...
      ISEQUAL(SolverType, "FixedStep") && FixedStepOpts.TID01EQ
      %assign ssTid = LibGetSubsystemTID(system, TLC_FALSE)
      %if SIZE(ssTid, 1) == 1 && ssTid[0] == 0
        %assign appendTIDToFcnName = TLC_FALSE
      %endif
    %endif
 
    %% Continuous rate related fcn does not need tid in fcn name
    %if SLibContFcnPartitionGrouping(sysFcn) && ...
      SLibIsMappedInDeploymentDiagram(system)
      %assign appendTIDToFcnName = TLC_FALSE
    %endif
 
    %% For export function models, tid 0 functions should not be appended with TID
    %if appendTIDToFcnName && system.CurrentTID == 0 && SLibIsExportFcnDiagram()
        %assign appendTIDToFcnName = TLC_FALSE
    %endif
  %else
    %assign appendTIDToFcnName = TLC_FALSE
  %endif
  %if appendTIDToFcnName
    %assert !WHITE_SPACE(system.CurrentTID)
 
    %if SLibIsExplicitPartitioningTID(system.CurrentTID)
      %% For explicit tasking models (other than export fcn) we want to adjust
      %% the function names to incorporate the task names. Eventually this should
      %% not include the TID, but more codegen support is needed before that can
      %% be enabled.
      %assign fcnName = SLibExplicitPartitioningSystemFcnName(fcnName, system.CurrentTID)
      %assign isExternFcn = TLC_TRUE
    %else
      %% The TIDn is always concatentated, even for tasked functions.
      %assign fcnName = "%<fcnName>TID%<system.CurrentTID>"
    %endif
  %endif
 
  %if !getFcnNameFromFPC && updateFcnRecName
    %assign ::FcnRec.Name = fcnName
  %endif
 
  %% Append TID to output function for CPP class generation
  %if GenerateClassInterface && appendTIDToFcnName
    %assign ::FcnRec.Name = ::FcnRec.Name + "%<system.CurrentTID>"
  %endif
 
  %assign thisModule = ...
    ::CompiledModel.RTWCGModules.RTWCGModule[system.CGIRModuleIdx]
 
  %assign hasTIDArg = 0
  %assign hasCPIArg = 0
  %assign hasRTMArg = 0
  %assign isSysFcn = TLC_FALSE
  %if ISFIELD(thisModule, "SystemFunctions") && ...
    ISFIELD(thisModule.SystemFunctions, fcnName)
    %assign fcnIndex = GETFIELD(thisModule.SystemFunctions, fcnName)
    %assign thisFcn = thisModule.Function[fcnIndex]
    %assign hasTIDArg = thisFcn.TIDArgIndex > -1
    %assign hasCPIArg = thisFcn.CPIArgIndex > -1
    %assign hasRTMArg = thisFcn.SimStructArgIndex > -1
    %assign isSysFcn = TLC_TRUE
  %endif
 
  %% If the system is reusable and it already has rtModel as an
  %% argument, don't add it again.
  %assign ResetInRootAccelRAccel = SLibResetOrResetWithInitEventTID(system.CurrentTID) && ...
    LibSystemIsRoot(system) && (Accelerator || isRAccel)
 
  %if (!hasRTMArg || exportFcnMode || ResetInRootAccelRAccel) && ...
    FcnSysNeedAddRTMArg(system, sysFcn)
    %if !FcnSysFcnHasRTM(system, sysFcn)
      %assign locSS = RTMGetModelSS()
      %if LibSystemIsRoot(system) && (CodeFormat == "S-Function")
        %<FcnAddArgument(::tSimStructType + " *", locSS, locSS)>
      %else
        %<FcnAddArgument(::tSimStructType + " *const ", locSS, locSS)>
      %endif
    %endif
  %endif
 
  %if !hasCPIArg && LibSystemFcnNeedsCPI(system,sysFcn)
    %if SLibAutosarCompilerAbstractionRequired()
      %<FcnAddArgumentWithCompilerAbstraction(TLC_FALSE, "int_T", TLC_FALSE, TLC_FALSE, ::tControlPortIdx, ...
        ::tControlPortIdx)>
    %else
      %<FcnAddArgument("int_T ", ::tControlPortIdx, ...
        ::tControlPortIdx)>
    %endif
  %endif
 
  %if !hasTIDArg && !isAsyncTriggered && LibSystemFcnNeedsTID(system,sysFcn)
    %<SLibSetTIDAddedInTLC(system)>
    %if SLibAutosarCompilerAbstractionRequired()
      %<FcnAddArgumentWithCompilerAbstraction(TLC_FALSE, "int_T", TLC_FALSE, TLC_FALSE, ::tTID, tTID)>
    %else
      %<FcnAddArgument("int_T ",::tTID, tTID)>
    %endif
  %endif
 
  %assign ::FcnRec.CommonPrms = ::FcnRec.Params
 
  %assign fcnPrototype = ""
  %assign fcnReturns = ""
  %assign isRateGroupedSLF = SLibIsRateGroupedSLFcn(system, sysFcn, system.CurrentTID)
  %assign isServiceFcn = SLibIsServiceFcn(system, sysFcn, system.CurrentTID)
  %if (exportFcnMode && isRateGroupedSLF) || isServiceFcn
    %% A rate grouped Simulink function's prototype is fully defined
    %% in IR (with the exception of the C++ class name). So, use the
    %% IR defined prototype rather than discarding and recomputing it.
    %assign aFcnPrototype = SLibGetRateGroupedFcnPrototype(thisModule, system.CurrentTID)
    %assign fcnName = aFcnPrototype.Name
    %assign fcnPrototype = aFcnPrototype.Prototype
    %assign cgirParams = aFcnPrototype.Params
    %assign fcnReturns = aFcnPrototype.Return
    %if !ISEMPTY(fcnName) && SLibAutosarCompilerAbstractionRequired()
      %% return type will be added later in this function
      %assign fcnPrototype = fcnName + "(" + cgirParams
      %assign ::FcnRec.Returns = fcnReturns
    %else
      %assign ::FcnRec.Returns = ""
    %endif
    %if !ISEMPTY(fcnName) && GenerateClassInterface
      %assign fcnPrototype = fcnReturns + " " + ::FcnRec.Name + "(" + cgirParams
    %endif
    %if (!GenerateClassInterface)
      %assign fcnPrototype = FEVAL("regexprep", fcnPrototype, "//()", "(void)")
    %endif
    %if !isServiceFcn || !GenerateClassInterface || !IsModelReferenceBaseSys(system)
      %assign ::FcnRec.Params = cgirParams
    %endif
  %endif
 
  %% The rate grouped Simulink function's prototype is
  %% fully defined in IR. However, blockI/O and parameters are still
  %% using classic arg tracking. We still need to call FcnAddParametersAndReturn
  %% to handle those args. We can skip calling FcnAddParametersAndReturn
  %% if C++ is being generated since these are class members.
  %if !LibSystemIsInlined(system) && !isRoot && (!isRateGroupedSLF || !GenerateClassInterface)
    %<FcnAddParametersAndReturn(sysFcn, fcnName, sysIdx, isRateGroupedSLF)>
  %endif
 
  %if ISEMPTY(::FcnRec.Returns) && !isRateGroupedSLF && !isServiceFcn
    %assign ::FcnRec.Returns = "void"
  %endif
 
  %% non-inlined and non reused library subsystem functions can also be part of the
  %% model class; its prototype may or may not have a classname:: prefix
  %% depending on it is in the declaration position (in class) or definition
  %% position (in .cpp).
  %assign subsysFcnAsMemFcn = SLibGenSubsysFcnAsClassMemFcn(system)
  %assign optClassNamePrefix = ""
  %if subsysFcnAsMemFcn
    %assign FPC = FcnGetRTWCPPStepPrototypeRecord()
    %assign optClassNamePrefix = FPC.ModelClassName + "::"
  %endif
  %assign isSubFunction = SLibIsFcnSubFunction(system, sysFcn)
  %if (SLibIsMultiInstanceServer(system) || ...
    (thisModule.SimplifiedInterface && IsModelReferenceBaseSys(system) && !subsysFcnAsMemFcn)) ...
    && ISEMPTY(::FcnRec.Params) && !GenerateClassInterface && !isOutlinedBlockFcn && !isSubFunction
    %assign ::FcnRec.Params = "%<tSimStructType> * const %<tSimStruct>"
  %endif
 
  %assign statQual = ""
  %if isRoot && RootBodyMthsStatic && !subsysFcnAsMemFcn && !exportFcnMode && !isExternFcn
      %assign statQual = "static "
  %endif
 
   %if(CGMODEL_ACCESS("CGModel.AddStaticKeywordToFcn"))
    %if FcnUseStaticStorageSpecifier(system) && !SLibSystemHasExportedFunction(system)
      %assign statQual = "static "
    %endif
  %endif
 
  %% If generating C++ and the function isn't static (thus limiting visibility
  %% to a single file) then extern "C" it because it will be called from the
  %% static _main.c file.
  %assign cppStorageClass = ""
  %if GenCPP && isRoot && (statQual == "") && !subsysFcnAsMemFcn
      %assign cppStorageClass = ExternCPrefix + " "
  %endif
 
  %if (sysFcn == "Initialize" || sysFcn == "SystemInitialize" || sysFcn == "SystemReset" || sysFcn == "Start" || sysFcn == "Terminate")
    %assign msFcnType = "MemSecFuncInitTerm"
  %else
    %assign msFcnType = "MemSecFuncExecute"
  %endif
 
  %% Create function opening:
  %% pre-pragma + qualifiers + function prototype
  %% We need to add pre-processor conditionals into the record so that the callee knows
  %% about the pre-processor condition in prototype. Note that this record will go into
  %% "OutputUpdateFcnInfo"in system scope. The existsing 'SLibIfVariantConditionForm'
  %% doesn't return the pre-processor conditionals for export functions, so we have to
  %% use the root inport CGVCE (propagated variant condition) set for a particular TID.
  %% This information lives in CodeVariants and populated from root input function-call
  %% generator block.
  %assign ppIf = ""
  %if exportFcnMode == 1
    %assign ppIf = SLibVariantConditionForTID(system.CurrentTID)
  %endif
  %openfile open
  %if !ISEMPTY(ppIf)
    %<SLibIfVariantConditionForm(ppIf)>
  %endif
  %<SLibIfSystemVariantCondition(system)>
  %assign useIndividualMapping = TLC_FALSE
  %assign functionType = ""
  %assign functionId = "" %% Assume
  %assign isPartitionOrImplicitStepOutputOrUpdateFcn = TLC_FALSE
  %if CGMODEL_ACCESS("CGModel.isIndividualFunctionMappingEnabled")
    %if IsModelReferenceTarget()
      %% Model Reference build
      %if (sysFcn == "ModelInitialize") && TLC_FALSE
        %% Initialize function
        %% NOTE: Skip this (this is re-computed in ertreg.tlc)
        %assign functionType = "Initialize"
        %assign useIndividualMapping = TLC_TRUE
      %elseif (sysFcn == "Terminate")
        %% Terminate function
        %assign functionType = "Terminate"
        %assign useIndividualMapping = TLC_TRUE
      %elseif (sysFcn == "OutputUpdate") || (sysFcn == "Output") || ...
        (sysFcn == "Update")
        %if SLibExplicitTaskingTID(system.CurrentTID)
          %if SLibResetOrResetWithInitEventTID(system.CurrentTID)
            %% Reset function
            %assign functionType = "Reset"
            %assign functionId = SampleTime[system.CurrentTID].EventSourceName
            %assign useIndividualMapping = TLC_TRUE
          %elseif SLibIsRateGroupedSLFcn(system, sysFcn, system.CurrentTID)
            %% Global or Public Simulink Function in export function model
            %assign functionType = "SimulinkFunction"
            %assign functionId = SLibGetRateGroupedSimulinkFunctionName(system, sysFcn, system.CurrentTID)
            %assign useIndividualMapping = TLC_TRUE
          %elseif !LibIsServer(system) && ...
            SLibIsExplicitTaskingExportFcnRateGrouping(sysFcn, system.CurrentTID)
            %% Export or Async function
            %% NOTE: SampleTime[tid].TaskName returns block name for export function,
            %% and full block path for async function
            %assign functionType = "FcnCallInport"
            %assign functionId = FEVAL("regexprep", ...
              SampleTime[system.CurrentTID].TaskName, ".*//", "")
            %assign useIndividualMapping = TLC_TRUE
          %elseif SLibIsExplicitPartitioningTID(system.CurrentTID)
            %% Partition via schedule editor
            %if (sysFcn == "OutputUpdate")
              %assign functionType = "Step"
            %elseif (sysFcn == "Output")
              %assign functionType = "Output"
            %elseif (sysFcn == "Update")
              %assign functionType = "Update"
            %endif
            %assign functionId = system.CurrentTID
            %assign useIndividualMapping = TLC_TRUE
            %assign isPartitionOrImplicitStepOutputOrUpdateFcn = TLC_TRUE
          %endif
        %else
          %if !SLibIsExportFcnDiagram()
            %if (LibIsGlobalServer(system) || SLibIsModelScopedServer(system))
              %% Global or Exported Global Scoped Function in a rate-based model
              %assign functionType = "SimulinkFunction"
              %assign functionId = SLibGetSimulinkFunctionNameInNonExportFcnModel(system)
              %assign useIndividualMapping = TLC_TRUE
            %elseif !LibIsServer(system)
              %% Implicit periodic functions
              %if (sysFcn == "OutputUpdate")
                %assign functionType = "Step"
              %elseif (sysFcn == "Output")
                %assign functionType = "Output"
              %elseif (sysFcn == "Update")
                %assign functionType = "Update"
              %endif
              %assign functionId = system.CurrentTID
              %assign useIndividualMapping = TLC_TRUE
              %assign isPartitionOrImplicitStepOutputOrUpdateFcn = TLC_TRUE
            %endif
          %endif
        %endif
      %endif
    %else
      %% Top Model build
      %if (LibIsGlobalServer(system) || SLibIsModelScopedServer(system))
        %% Global or Exported Global Scoped Function in a rate-based model
        %assign functionType = "SimulinkFunction"
        %assign functionId = SLibGetSimulinkFunctionNameInNonExportFcnModel(system)
        %assign useIndividualMapping = TLC_TRUE
      %endif
    %endif
  %endif
 
  %assign memSecUUID = ""
  %if useIndividualMapping
    %if ISEMPTY(functionType)
      %<LibReportFatalError("Unknown functionType for individual function mapping")>
    %endif
    %assign memSecUUID = SLibGetFcnMemSecUUIDForFunction(functionType, functionId)
    %if isPartitionOrImplicitStepOutputOrUpdateFcn && !SLibFcnProtoCtrlActive() && ...
      IsModelReferenceRTWTarget() && IsModelReferenceBaseSys(system)
      %% Update function name using name stored in the mapping.
      %% Only needed for model reference output/update functions. Handling is
      %% done else where for other functions.
      %assign fcnNameInMapping = CGMODEL_ACCESS("CGModel.getModelEntryFunctionName", "%<functionType>", "%<functionId>")
      %if ISEMPTY(fcnNameInMapping) && (functionType == "Output")
        %% In some scenarios (e.g. continuous sample time or states logging),
        %% model reference codegen can decide to split the step function into
        %% separate output/update functions. In this case, there is only one
        %% step function mapping, and this is where the registered function
        %% name for the output function is stored. Hence fetch the name from the
        %% step function mapping.
        %% Note that for these scenarios, there is no update function mapping.
        %% Hence the default name will be used for the update function name.
        %assign fcnNameInMapping = CGMODEL_ACCESS("CGModel.getModelEntryFunctionName", "Step", "%<functionId>")
      %endif
      %if !ISEMPTY(fcnNameInMapping)
        %assign ::FcnRec.Name = fcnNameInMapping
      %endif
 
    %endif
    %<SLibGetFcnMemSecPragmaForFunction(::FcnRec.Name, functionType, functionId, "Pre")>/
  %else
    %<SLibGetFcnMemSecPragmaForSystem(::FcnRec.Name, msFcnType, "Pre", system)>/
  %endif
 
  %if ISEMPTY(fcnPrototype)
    %if ISEMPTY(::FcnRec.Params)
      %if !subsysFcnAsMemFcn
        %assign fcnPrototype = fcnPrototype + ::FcnRec.Name + "(void)"
      %else
        %% C++ conventions is not to use 'void' for empty param function prototype
        %assign fcnPrototype = fcnPrototype + ::FcnRec.Name + "()"
      %endif %% !subsysFcnAsMemFcn
    %else
      %assign fcnPrototype = ::FcnRec.Name + "(" + ::FcnRec.Params + ")"
    %endif %% ISEMPTY(::FcnRec.Params)
  %endif
 
  %if SLibAutosarCompilerAbstractionRequired()
    %if SLibAutosarIsMultiRunnableFcn(::FcnRec.Name)
      %assign memclass = "FuncCalledByRTE"
    %else
      %assign memclass = "FuncInternal"
    %endif
 
    %<cppStorageClass> %<statQual> %<SLibAutosarCompilerAbstractionForFcnDeclRtnType(::FcnRec.Returns, memclass, memSecUUID)> %<optClassNamePrefix>%<fcnPrototype>
  %else
    %<cppStorageClass> %<statQual> %<::FcnRec.Returns> %<optClassNamePrefix>%<fcnPrototype>
  %endif
  {
  %closefile open
 
  %% Create function closing
  %openfile close
  }
  %if useIndividualMapping
    %<SLibGetFcnMemSecPragmaForFunction(::FcnRec.Name, functionType, functionId, "Post")>/
  %else
    %<SLibGetFcnMemSecPragmaForSystem(::FcnRec.Name, msFcnType, "Post", system)>/
  %endif
  %<SLibEndIfSystemVariantCondition(system)>
  %if !ISEMPTY(ppIf)
    %<SLibEndIfVariantConditionForm(ppIf)>
  %endif
 
  %closefile close
 
  %assign begin = ""
 
  %%
  %% For root methods in S-function format, we may need a
  %% # define before the method. We cache that here
  %%
  %assign sfcnFormDefine = ""
  %if isRoot && (CodeFormat == "S-Function")
    %%
    %% For S-Function target (right click build), add
    %% '#define MDL_INITIALIZE_CONDITIONS' before root systemInitialize
    %% since S-Function block should have block initialize method
    %% instead of systemInitialize and systemReset.
    %%
    %if sysFcn == "SystemInitialize" && !Accelerator
      %assign sfcnFormDefine = FcnGetSfcnFormDefine("Initialize")
    %else
      %assign sfcnFormDefine = FcnGetSfcnFormDefine(sysFcn)
    %endif
  %endif
 
  %assign name = sysFcn + "FcnInfo"
  %if SLibAutosarCompilerAbstractionRequired()
    %if SLibAutosarIsMultiRunnableFcn(::FcnRec.Name)
      %assign memclass = "FuncCalledByRTE"
    %else
      %assign memclass = "FuncInternal"
    %endif
 
    %assign fcnPrototype = SLibAutosarCompilerAbstractionForFcnDeclRtnType(::FcnRec.Returns, memclass, memSecUUID) + " " + fcnPrototype
  %else
    %assign fcnPrototype = ::FcnRec.Returns + " " + fcnPrototype
  %endif
 
  %if ISEMPTY(::FcnRec.Returns)
    %if !ISEMPTY(fcnReturns)
      %assign ::FcnRec.Returns = fcnReturns
    %else
      %assign ::FcnRec.Returns = "void"
    %endif
  %endif
 
  %createrecord %<name> /
  { /
    SysFcn sysFcn; /
    Name ::FcnRec.Name; /
    CGIRName fcnName; /
    Returns ::FcnRec.Returns;/
    Params ::FcnRec.Params; /
    CommonPrms ::FcnRec.CommonPrms; /
    CommonArgs ::FcnRec.CommonArgs; /
    FcnPrototype fcnPrototype; /
    SfcnFormDefine sfcnFormDefine; /
    Open open; /
    Begin begin; /
    Close close /
  }
  %return %<name>
%endfunction
 
%function SLibSystemFcnIsExtern(system, tid, fcn) void
  %return SLibSystemIsModelEntryPoint(system, tid) && ...
    (fcn == "Output" || fcn == "OutputUpdate" || fcn == "UpdateContStates" || ...
    fcn == "Enable" || fcn == "Disable")
%endfunction
 
%%Function:SLibSystemFcnIsModelEntryPoint
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/inlineVariants/tInlineVariants10.m
%%
%function SLibSystemIsModelEntryPoint(system, tid) void
  %assign retVal = TLC_FALSE
  %if ExportFunctionsMode == 1
    %assign retVal = (system.Type == "function-call" && system.Exported == "yes" )
  %else
    %if ExportFunctionsMode == 2 && system.Type == "function-call" && ...
      system.DescSysNonTrigTID[0] >= NumRuntimeExportedRates
      %assign retVal = TLC_TRUE
    %endif
    %if LibSystemIsRoot(system) %%|| IsModelReferenceBaseSys(system)
      %if SLibFcnProtoCtrlActive() || SLibAutosarActive() || ...
        LibIsDeploymentDiagram() || SLibIsAsyncTaskOnlyModel()
         %assign retVal = TLC_FALSE
      %else
        %if SLibIsPeriodicRateGrouping() && SLibNeedExternRootSysRateGroupingFcn()
          %if TYPE(tid) == "Number" && !((tid == 1)&&Tid01Eq) && ...
            (!LibAsynchronousTriggeredTID(tid) || SLibNonInlinedModelWideEventTID(tid))
            %assign retVal = TLC_TRUE
          %endif
        %else
          %% solver always call rate grouped function if rate grouping is on
          %assign retVal = ISEQUAL(tid,"") || ...
            (SLibIsPeriodicRateGrouping() && ISEQUAL(tid,0) && NumContStates > 0)
        %endif
      %endif
    %endif
  %endif
  %return retVal
%endfunction
 
%%Function:SLibGetFcnInfoForFcnName==============================================================
%%Abstract:
%%ReturnfcnInforecordofthesystemandagivenfunctionname.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibGetFcnInfoForFcnName(aSystem, aFcnName) void
  %assign fieldName = "CGIR_" + aFcnName + "_FcnInfo"
  %if LibIsSystemField(aSystem, fieldName)
    %return LibGetSystemField(aSystem, fieldName)
  %endif
  %return ""
%endfunction
 
%%Function:LibDefineSystemFcnForTID==============================================================
%%Abstract:
%%Cachearecordinthesystemscopesothatthesubsystemblock
%%(whocallsthefunction)knowstheprototyped.
%%
%%Arguments:
%%system:Simulinksystem
%%sysFcn:Thesystemfunctiontodefine
%%oInitialize
%%oOutput
%%oUpdate
%%oOutputUpdate
%%oDerivative
%%oEnable
%%oDisable
%%fcnRec:ReferencetofcnRec(seetopoffilefordefinitionofrecord)
%%
%%
%%Example:
%%%assignfcnRec.Name="foo"
%%%assignfcnRec.Returns="void"
%%%assignfcnRec.Params="int_Ttid"
%%%assignfcnRec.Args="tid"
%%
%%%<LibDefineSystemFcnForTID(system,"OutputUpdate",tid)>
%%
%%Createsafunctioninformationrecordinthesystemscope:
%%
%%System{
%%:
%%OutputUpdateFcnInfo{
%%Name"foo"
%%Returns"void"
%%Params"int_Ttid"
%%Args"tid"
%%fcnCall"foo(tid)"
%%fcnPrototype"voidfoo(int_Ttid)"
%%}
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/variants/codevariants/-tcodevariants10.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tIVfcnCall_neg.m
%%
%function LibDefineSystemFcnForTID(system, sysFcn,tid) void
  %assign system.CurrentTID = tid
  %assign isRateGrouping = SLibSystemFcnPeriodicRateGrouping(system, sysFcn) || ...
    (LibAsynchronousTriggeredTID(system.CurrentTID) && ...
    (sysFcn == "Output" || sysFcn == "Update" || sysFcn == "OutputUpdate"))
  %assign fcnRecord = SLibSystemFcnInfoRecord(system, sysFcn)
 
  %assign fieldName = "CGIR_" + fcnRecord.CGIRName + "_FcnInfo"
  %if !LibIsSystemField(system, fieldName)
    %<LibAddToSystem(system, fieldName, fcnRecord)>
  %elseif (TYPE(tid) == "Number" && tid < NumRuntimeExportedRates)
    %% Call it, just to get error message
    %<LibAddToSystem(system, fieldName, fcnRecord)>
  %else
    %assign needToStop = IsModelReferenceBaseSys(system) && ISEMPTY(tid) && ...
      (sysFcn == "Output" || sysFcn == "Update" || sysFcn == "OutputUpdate")
    %if needToStop
      %return
    %endif
  %endif
 
  %if isRateGrouping && TYPE(system.CurrentTID) == "Number"
    %% Set up the global vars for this system and function, this
    %% is needed for nonreusable functions that live in reusable functions
    %assign globalVars = LibInitializeGlobalVars(system, sysFcn)
    %if SLibPartitionGroupingSystem(system)
      %assign pidVec = SLibGetPidFromTid(system.CurrentTID)
      %foreach i = SIZE(pidVec, 1)
        %<LibSetSystemField(system, ...
          "Cached%<sysFcn>%<system.CurrentTID>%GlobalVars", globalVars)>
        %<LibAddToSystem(system,...
          "%<sysFcn>TID%<system.CurrentTID>PID%FcnInfo", fcnRecord)>
      %endforeach
    %else
      %<LibSetSystemField(system, ...
        "Cached%<sysFcn>%<system.CurrentTID>GlobalVars", globalVars)>
      %<LibAddToSystem(system,...
        "%<sysFcn>TID%<system.CurrentTID>FcnInfo", fcnRecord)>
    %endif
  %else
    %% Set up the global vars for this system and function, this
    %% is needed for nonreusable functions that live in reusable functions
    %assign globalVars = LibInitializeGlobalVars(system, sysFcn)
    %if !ISEMPTY(globalVars) && !WHITE_SPACE(globalVars)
      %<LibSetSystemField(system, "Cached"+sysFcn+"GlobalVars", globalVars)>
    %endif
    %<LibAddToSystem(system, sysFcn + "FcnInfo", fcnRecord)>
  %endif
 
  %if LibSystemIsInlined(system)
    %% If inlining reassign Open and FcnCall
    %openfile declarebuf
    %<LibDumpSystemSSVars(system,sysFcn)>/
    %if isRateGrouping
      %<LibGetSystemLocalVars(system, sysFcn, system.CurrentTID)>
      %if sysFcn == "OutputUpdate"
        %<SLibGetFcnLocalVars(system, "Output", system.CurrentTID)>
        %assert ISEMPTY(SLibGetFcnLocalVars(system, "Update", system.CurrentTID))
      %else
        %<SLibGetFcnLocalVars(system, sysFcn, system.CurrentTID)>
      %endif
    %else
      %<LibGetSystemLocalVars(system, sysFcn, "")>
      %if sysFcn == "OutputUpdate"
        %<SLibGetFcnLocalVars(system, "Output", "")>
        %assert ISEMPTY(SLibGetFcnLocalVars(system, "Update", ""))
      %else
        %<SLibGetFcnLocalVars(system, sysFcn, "")>
      %endif
    %endif
    %closefile declarebuf
    %if LibSystemUserCodeIsEmpty(system,sysFcn,"Header") && ...
      WHITE_SPACE(declarebuf)
      %assign needOutputsBrace = 0
    %else
      %assign needOutputsBrace = 1
    %endif
    %if needOutputsBrace
      %assign fcnRecord.Open = "{/n"
      %assign fcnRecord.Begin = "/n"
      %assign fcnRecord.Close = "}/n"
    %else
      %assign fcnRecord.Open = ""
      %assign fcnRecord.Begin = ""
      %assign fcnRecord.Close = ""
    %endif
  %else
    %if (!LibSystemFcnIsEmptyHelper(system,sysFcn,tid)) || ...
      (system.Type == "function-call" && sysFcn == "OutputUpdate" && ...
      (ISEQUAL(tid,FcnGetSubsystemTID(system,TLC_TRUE)) || (GenerateClassInterface && !LibIsServer(system) && !SLibModelWideEventTID(tid) ))) || ...
      (SLibGenSubsysFcnAsClassMemFcn(system) && ...
       ISEQUAL(tid, "") && ((!FcnSysModuleIsRateGrouping(system, sysFcn) && RateGroupedAsyncFcns) || !SLibIsExportFcnDiagram()) && !LibSystemFcnIsEmpty(system, sysFcn))
      %% Only dump the prototype if the caller does not live
      %% in the same file or it is a Async sfcn.
      %assign isMdlRefBaseAndIsAsyncTID = ...
        IsModelReferenceBaseSys(system) && LibAsynchronousTriggeredTID(tid) && !SLibNonInlinedModelWideEventTID(tid)
      %% Need to delay the caching of the start fcn prototype until after output fcn
      %% has been processed. Output fcn can indicate the need for model params to be initialize
      %% in the start fcn. The prototype of the start fcn is formed by the need of those
      %% params. The prototype is later cached in commonbodlib.tlc
      %assign isMdlRefStart = IsModelReferenceBaseSys(system) && SLibIsExportFcnDiagram() && sysFcn == "Start"
      %assign simulinkFunctionPrototypeInModelHeader = SLibIsRateGroupedSLFcn(system, sysFcn, tid) && ...
        !SLibRateGroupedSimulinkFunctionNeedsDeclaration(system, sysFcn, tid)
 
      %if (system.Type != "root") && ...
        (!isMdlRefBaseAndIsAsyncTID || ...
          SLibIsExplicitTaskingExportFcnRateGrouping(sysFcn,tid) || ...
          simulinkFunctionPrototypeInModelHeader) && ...
        !SLibSystemFcnIsExtern(system, tid, sysFcn) && ...
        !isMdlRefStart
        %<LibCacheSubsystemPrototype(system,fcnRecord)>/
      %endif
    %endif
  %endif
  %assign system.CurrentTID = -1
%endfunction %% LibDefineSystemFcnForTID
 
%%Modelreferencebasesystemhasseparateentrypointsfor
%%tid0and1,eveniftid01eq.
%function FcnAddMdlRefTid1Interface(system, tid)
  %return ISEQUAL(tid,0) && ...
    ISEQUAL(::CompiledModel.SolverType, "FixedStep") && ...
    (LibGetTID01EQ() == 1) && ...
    IsModelReferenceBaseSys(system)
%endfunction
 
%%Function:LibDefineSystemFcn====================================================================
%%Description:
%%CallLibDefineSystemFcntoCacherecord(s)inthesystemscope
%%sothatthesubsystemblock(whocallsthefunction)knows
%%theprototyped.WhenSLibSystemFcnPeriodicRateGrouping(istrue,recordsare
%%cachedveryeachtidfunctioncall.Ifpartitiongroupingison,
%%recordsarecachedforeachpairpid>functioncall.
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/inlineVariants/tInlineVariants10.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tVariantSimulinkFunctionAutoInherit.m
%%
%function LibDefineSystemFcn(system, sysFcn) void
  %if sysFcn == "Output" || sysFcn == "Update" || ...
    sysFcn == "OutputUpdate" || ...
    (SLibContFcnPartitionGrouping(sysFcn) && ...
    SLibDeploymentDiagramIsMapped(system.SystemIdx))
    %assign ssTaskToFirstTid = FcnGetSubsystemTaskToFirstTID(system)
    %% Currently, we need to make sure that base system for mdlref gets
    %% tid 0 for argument tracking otherwise
    %% t/t/simulink/sltools/raccel/mg544769_raccell fails
    %if IsModelReferenceBaseSys(system) && ...
      (ISEMPTY(ssTaskToFirstTid) || ssTaskToFirstTid[0] != 0)
      %assign tid = FcnGetCodeCacheTid(system, sysFcn, 0)
      %<LibDefineSystemFcnForTID(system, sysFcn, tid)>
    %endif
    %foreach idx = SIZE(ssTaskToFirstTid, 1)
      %assign tid = FcnGetCodeCacheTid(system, sysFcn, ssTaskToFirstTid[idx])
      %% Reset, Terminate (in mdlrefsim), and reset with init event have no update functions.
      %% Do not cached continuous rate related fcn records if tid is not 0,
      %% we hit this because of the way we treat tid01eq in partition grouping.
      %if (SLibNonInlinedIRTEventTID(tid) && sysFcn == "Update") || ...
        (SLibContFcnPartitionGrouping(sysFcn) && tid != 0)
        %continue
      %endif
      %<LibDefineSystemFcnForTID(system, sysFcn,tid)>
      %if FcnAddMdlRefTid1Interface(system, tid)
        %<LibDefineSystemFcnForTID(system, sysFcn,1)>
      %endif
    %endforeach
  %else
    %<LibDefineSystemFcnForTID(system, sysFcn, "" )>
  %endif
%endfunction %% LibDefineSystemFcn
 
%%Function:LibGenSubsystemFcnCall================================================================
%%Abstract:
%%Generatesafunctioncalltoasystem.
%%
%%Arguments:
%%outAndRuleIdx-atwo-elementsvectorofstringforactualargumentsofoutputidx
%%andruleidx.use[]ifthefcnisnotSetDimsfcn.
%%canIO-avectorofstringsforactualargumentsofcanonicalI/O,
%%use[]normallyworks.
%%fcnInfo-containsthefunctionnameandthetypeofthecall
%%(e.g."Start,Output,Update,...")
%%parentSysIdx-locationofthesystemcall
%%(Wherethefunctioniscalled)
%%sysIdx-systemtobecalled
%%callSiteIdx-systeminstancetobeused
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/inlineVariants/tInlineVariants10.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function LibGenSubsystemFcnCall(canIO, fcnInfo, parentSysIdx, sysIdx, callSiteIdx) void
  %if ISEMPTY(fcnInfo)
    %return ""
  %endif
  %assign accessSysIdx = System[parentSysIdx].HStructDeclSystemIdx
  %assign genModelRef = ...
    IsModelReferenceTarget() && accessSysIdx == ::CompiledModel.NumSystems-1
 
  %assign addArgs = FcnGetAdditionalArgs(fcnInfo.CGIRName, canIO, ...
    fcnInfo.SysFcn, sysIdx, accessSysIdx, callSiteIdx, genModelRef, TLC_FALSE)
  %assign comArgs = fcnInfo.CommonArgs
  %assign cs = System[sysIdx].CallSites[callSiteIdx]
  %assign ssBlk = System[cs[2]].Block[cs[3]]
  %%
  %assign comma = (WHITE_SPACE(addArgs) || WHITE_SPACE(comArgs)) ? "" : ", "
  %%
  %% If one or more of arguments of a function that is passed by address
  %% is a expression, than the result of this expression has to be stored
  %% in a temporrary variable. The address of the temporary variable will
  %% than be passed as the argument of the function call.
  %%
  %if (fcnInfo.SysFcn == "OutputUpdate") && ...
    IsModelReferenceBaseSys(System[sysIdx]) && ...
    SLibFcnProtoCtrlActive()
    %assign FPC = FcnGetFunctionPrototypeRecord()
    %assign fcnName = FPC.FunctionName
  %else
    %assign fcnName = fcnInfo.Name
  %endif
  %if ISFIELD(ssBlk, "%<fcnInfo.SysFcn>FcnCallCode")
    %assign fcnCallCode = GETFIELD(ssBlk, "%<fcnInfo.SysFcn>FcnCallCode")
    %assign fcnCall = ""
    %openfile fcnCall
    {
      %<fcnCallCode.localPrmDecl>
      %<fcnCallCode.localExpr>
      %<fcnName>(%<comArgs>%<comma>%<addArgs>);
    }
    %closefile fcnCall
    %return fcnCall
  %else
    %if (fcnInfo.Returns == "void")
      %return "%<fcnName>(%<comArgs>%<comma>%<addArgs>);"
    %else
      %return "%<fcnName>(%<comArgs>%<comma>%<addArgs>)"
    %endif
  %endif
%endfunction
 
%%Function:FcnGetCanDWorkArg=====================================================================
%%Abstract:
%%Returnsacanonicaldworkargumentforagiveargumentindex,callsite,
%%accesssystemindexandcallsiteindex.
%%
%function FcnGetCanDWorkArg(sysFcn, cs, argIdx, sysIdx, accessSysIdx, callSiteIdx) void
  %%
  %assign parent = System[sysIdx]
  %%
  %% Get the reused function or root
  %%
  %assign callerHStSystem = SLibCallerHStuctDeclSystem(parent, callSiteIdx)
  %assign dwArg = ""
  %assign ssBlk = System[cs[2]].Block[cs[3]]
 
  %with parent
    %assign cTID = FcnGetCurrentAccessTid()
  %endwith
 
  %assign accessSystem = ::CompiledModel.System[accessSysIdx]
 
  %if sysIdx == accessSysIdx
    %% For code reuse of multi-mode enable/trigger subsystems,
    %% function FinalizeDims is not called by its parent
    %% subsystem. It is called by its output function.
    %% In the output function, local reference of the canonical
    %% dwork for current dimensions should be used to call the
    %% function FinalizeDims
    %%
    %% Also, output function may also call its enable function
    %% for the same type subsystems
    %%
    %assert (sysFcn == "FinalizeDims" || sysFcn == "Enable")
    %assert (parent.HStructDeclSystemIdx == sysIdx)
    %assert (callSiteIdx == 0)
    %%
    %% idNum[0] == "dp"
    %%
    %% we want to access a formal argument at the callsite
    %% of sysIdx being called by itself, dp0 tells that it
    %% is the 1st dwork argument of the parent reusable
    %% subsystem, and it is passed in as the argIdx'th
    %% argument of sysIdx.
    %%
    %% the same is true for "D" and "d".
    %%
    %assign canDWorkArgDef = ...
      parent.Interface.CanonicalDWorkArgDef[argIdx]
    %assign dwArg = LibGetRecordIdentifier(canDWorkArgDef)
    %<SLibAccessArgHelper(canDWorkArgDef, "",cTID)>
    %if parent.CrossNoArgFcnBound
      %<SLibAccessArgHelper(canDWorkArgDef, "Global",cTID)>
      %assign dwArg = canDWorkArgDef.GlobalIdentifier
    %endif
  %else
    %assign arg = ssBlk.CallSiteInfo.CanonicalDWorkArg[argIdx]
    %assign argSrc = arg.SignalSrc %% Di, di or dpi
    %assign idNum = IDNUM(argSrc)
    %%
    %assert (idNum[0] == "D" || idNum[0] == "d" || idNum[0] == "dp" || idNum[0] == "db")
    %%
    %%
    %assign callerSysIdx = cs[0]
    %assign cross = System[callerSysIdx].CrossNoArgFcnBound
    %if idNum[0] == "dp" %% uses relative idx
      %assert (callerHStSystem.Type != "Root")
      %%
      %if callerHStSystem.SystemIdx < accessSysIdx
        %assign parentNonReuseSysIdx = System[parent.CallSites[callSiteIdx][0]].ReusedParentSystemIdx
        %assign nonreuseCallerSysIdx = System[parentNonReuseSysIdx].CallSites[cs[1]]
        %assign dwArg = FcnGetCanDWorkArg(sysFcn, nonreuseCallerSysIdx, idNum[1], ...
          parentNonReuseSysIdx, accessSysIdx, cs[1])
      %else
        %%
        %% If the callerHStSystem is a hidden system for
        %% Implicit Iterator Subsystem, it might not have
        %% Interface.CanonicalDWorkArgDef field because it might be
        %% inlined.
        %%
        %assign localSystem = SLibCallerReusedParentSystem(parent, callSiteIdx)
        %assign callerDWork = ...
          localSystem.Interface.CanonicalDWorkArgDef[idNum[1]]
        %assign dwArg = LibGetRecordIdentifier(callerDWork)
        %<SLibAccessArgHelper(callerDWork, "",cTID)>
        %if cross
          %<SLibAccessArgHelper(callerDWork, "Global",cTID)>
          %assign dwArg = callerDWork.GlobalIdentifier
        %endif
      %endif
    %elseif idNum[0] == "db" %% access buried DWork
      %if callerHStSystem.SystemIdx != accessSysIdx
        %% For dwork in hidden system for Implicit Iterator Subsystem,
        %% callerHStSystem is not accessSys.
        %assign localSystem = SLibCallerReusedParentSystem(parent, callSiteIdx)
        %assert(localSystem.SystemIdx == accessSysIdx)
      %endif
      %assign dworkAndRec = FcnGetDworkAndRec(argSrc)
      %assign dwRec = dworkAndRec.DWorkRec
      %assign dwArg = ...
        "&" + ...
        FcnCGIRCGVarHelper(dwRec.VarGroupIdx[0], dwRec.VarGroupIdx[1], ...
        cross, accessSysIdx, SLibDWorkWidth(dwRec), "", -1, ...
        "", 0, TLC_FALSE)
    %elseif idNum[0] == "D" || idNum[0] == "d" %% global or local access
      %assign dworkAndRec = FcnGetDworkAndRec(argSrc)
      %assign dwRec = dworkAndRec.DWorkRec
      %% temporary work around for g494342
 
      %if idNum[0] == "D" || dwRec.StorageClass != "Auto"
        %% Example,
        %% Scalar: foo(&DWork.a)
        %% Wide: foo(&DWork.b[0])
        %%
        %% if dwork belongs to ExternalInputSize
        %% vargroup, it is actually not a DWork.
        %% this only happens for "D" case, not for
        %% "d", "dp" and "db".
        %assign dwRec = ::CompiledModel.DWorks.DWork[idNum[1]]
 
        %if !ISFIELD(dwRec, "VarGroupIdx")
          %assign isPointer = dwRec.StorageClass == "ImportedExternPointer" && LibGetRecordWidth(dwRec) == 1
          %assign dwArg = FcnCGIRSimpleCGVarHelper(dwRec.Identifier, ...
              isPointer, %<LibGetRecordWidth(dwRec)>, "", -1, "", 0, TLC_TRUE)
        %elseif LibGetVarGroupCategory(dwRec.VarGroupIdx[0]) == "ExternalInputSize"
          %if CodeFormat == "S-Function" && !Accelerator
            %assign memberIdx = dwRec.VarGroupIdx[1]
            %assign cgTypeIdx = SLibCGVarGroupMemberCGTypeIdx(...
              dwRec.VarGroupIdx[0], ...
              memberIdx)
            %assign dwArg = "&" + FcnCGIRSFcnSizeVarHelper("ssGetCurrentInputPortDimensions", ...
              TLC_FALSE, "const", ...
              cgTypeIdx, memberIdx, %<LibGetRecordWidth(dwRec)>, "", "", 0)
          %else
            %assign varGroup = ...
              ::CompiledModel.VarGroups.VarGroup[dwRec.VarGroupIdx[0]]
            %assign memberIdx = dwRec.VarGroupIdx[1]
            %assign portVarName = FcnSLibCGIRGetVarGroupMemberName(dwRec.VarGroupIdx[0], memberIdx)
            %assign identifier = varGroup.Name + "." + portVarName
            %assign dwArg = FcnCGIRSimpleCGVarHelper(identifier, ...
              TLC_FALSE, %<LibGetRecordWidth(dwRec)>, "", -1, "", 0, TLC_TRUE)
          %endif
        %else
          %assign dwArg = SLibGetGlobalDWorkAddr(idNum[1], cross)
        %endif
      %else %% "d", Auto storage class
        %assert idNum[0] == "d"
        %% Example,
        %% Scalar: foo(&localDW->a)
        %% Wide: foo(localDW->b)
        %%
        %% If the caller is crossing a function boundary, use
        %% the global variable instead of localDW.
        %assign dwRec = ::CompiledModel.DWorks.DWork[idNum[1]]
        %assign dwId = LibGetRecordIdentifier(dwRec)
        %assign dwWidth = SLibDWorkWidth(dwRec)
        %%
        %if cross || callerHStSystem.StandaloneSubsystem
          %if cross
            %assert !callerHStSystem.StandaloneSubsystem
            %<SLibAccessArgHelper(accessSystem.Interface.DWorkArgDef, "Global",...
              cTID)>
            %assign acc = "->"
          %else
            %assign acc = "."
          %endif
          %assign dWIdent = FcnSysVarGroupNonreusedName(accessSystem,"DWork")
          %if dwWidth == 1
            %assign dwArg = "&" + dWIdent + acc + dwId
          %else
            %assign dwArg = dWIdent + acc + dwId
          %endif
        %else
          %if !(GenerateClassInterface && IsModelReferenceBaseSys(callerHStSystem))
            %if dwWidth == 1
              %assign dwArg = "&localDW->" + dwId
            %else
              %assign dwArg = "localDW->" + dwId
            %endif
          %else
            %%%% must be C++ encap. MdlRef and calling the subsys fcn
            %%%% from the model reference hidden base subsystem
            %assert IsModelReferenceRTWTarget()
            %if dwWidth == 1
              %assign dwArg = "&(%<::tDWork>." + dwId + ")"
            %else
              %assign dwArg = "%<::tDWork>." + dwId
            %endif
          %endif %% !(GenerateClassInterface && IsModelReferenceBaseSys(parent))
        %endif
        %<SLibAccessArgHelper(callerHStSystem.Interface.DWorkArgDef,"",...
          cTID)>
      %endif
    %endif
  %endif
  %return dwArg
%endfunction
 
%%Function:FcnGetCanDWorkArgs====================================================================
%%Abstract:
%%
%%Arguments:
%%sysIdx-systemfunctiontocall
%%callSiteIdx-systeminstancetocall
%%accessSysIdx-locationofthesystemcall.Thiscanbeafunction
%%orreusablefunction.
%%Note:IfthesubsystemisusingoneofitsCanonicalDWork,
%%andthesubsystemisinareusablefunction,itmustmark
%%thecorrespondingreusablefunctionargasAccessed.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/exportFcns/tExportFcnsWithInlineVariants.m
%%
%function FcnGetCanDWorkArgs(sysFcn, sysIdx, accessSysIdx, callSiteIdx, ...
  currentTID, isPeriodicRateGrouping, skipCanDWork) void
  %assign thisSystem = ::CompiledModel.System[sysIdx]
  %assign cs = thisSystem.CallSites[callSiteIdx]
  %assign args = ""
  %assign comma = ""
  %assign errTxt = "Invalid SignalSrc for CanonicalDWork."
  %assign isTestInterface = ...
    ::CompiledModel.ConfigSet.GenerateTestInterfaces && ...
    ISFIELD(thisSystem, "GenerateReusableWrapper") && ...
    GETFIELD(thisSystem, "GenerateReusableWrapper")
 
  %with thisSystem.Interface
    %foreach argIdx = NumCanonicalDWorkArgDefs
      %%
      %% Canonical DWorks has already been added in IR
      %%
      %if skipCanDWork[argIdx]
        %continue
      %endif
      %%
      %% Canonical dimsize dwork has already been added to args when
      %% canonical input(s) and output(s) are processed
      %%
      %if SLibGetCanDWorkIsCanDimSizeDWork(argIdx)
        %continue
      %endif
 
      %assign canDWork = CanonicalDWorkArgDef[argIdx]
      %if SysFcnArgNeeded(sysFcn, canDWork, currentTID, isPeriodicRateGrouping)
        %if isTestInterface && ISFIELD(canDWork, "SSGraphicalAPIReference")
            %assign grDS = canDWork.SSGraphicalAPIReference
            %assign args = args + comma + grDS.Name
            %assign comma = ", "
        %else
          %assign args = args + comma + ...
            FcnGetCanDWorkArg(sysFcn, cs, argIdx, sysIdx, accessSysIdx, callSiteIdx)
          %assign comma = ", "
        %endif %% if ConfigSet.GenerateTestInterfaces
      %endif %% if SysFcnArgNeeded
    %endforeach %% argIdx
    %%
  %endwith %% thisSystem.Interface
  %return args
%endfunction %% FcnGetCanDWorkArgs
 
%%Function:SLibGetCallSitePrmArg=================================================================
%%Abstract:
%%Returnstheparameterargumentforagivencallsiteandparmeterindex.
%%tOPTESTER:test/toolbox/simulink/blocks/tconcat.m
%%
%function SLibGetCallSitePrmArg(cs, childPrmIdx) void
  %if System[cs[0]].NumChildPrmArgs == 0
    %return SLibGetCallSitePrmArg(System[cs[0]].CallSites[cs[1]], childPrmIdx)
  %else
    %return System[cs[0]].ChildPrmArg[childPrmIdx]
  %endif
%endfunction %% SLibGetCallSitePrmArg
 
%%FunctionGetChildPrmArgFromParent===========================================
%%Abstract:
%%Thisfunction,forasystem'scanonicalparameter,returnsthe
%%correspondingChildPrmArgoftheparentsystem.Iftheparentsystem
%%itselfisareusablefunctionandhastheparameterasacanonicalparam
%%thenthefunctionseeksthetrueparentofthesystem.Thetrueparent
%%systemdefinestheactualaddressorvalue(incaseofinlined)ofa
%%canonicalparameter.Thetrueparent'sChildPrmArgcontainstheactual
%%address/valueoftheparameter
%%Forgeneratingtestinterfaces,weneedtheactualvalue/addressofa
%%canonicalparameterinsteadofitscanonicalargumentstring.
%%
%%cs:CallSiteofthesystem
%%childPrmIdx:IndexoftheChildPrmArginthesystem
%%
%function FunctionGetChildPrmArgFromParent(cs, childPrmIdx) void
  %assign prm = SLibGetCallSitePrmArg(cs, childPrmIdx)
  %if prm.ASTNode.Op == "M_CANPRM_ID"
    %% Canonical param - Top-level Parent defines the memory/value
    %assign sysCS = System[cs[0]].CallSites[cs[1]]
    %assign ssBlk = System[sysCS[2]].Block[sysCS[3]]
    %assign argIdx = prm.ASTNode.CanonicalPrmArgDefIdx
    %if ssBlk.CallSiteInfo.NumCanonicalPrmArgs > 0
    %assign childPrmIdx = ...
          ssBlk.CallSiteInfo.CanonicalPrmArg[argIdx].ChildPrmArgIdx
    %endif
    %% Recurse to get to the top level parent (true parent)
    %assign prm = FunctionGetChildPrmArgFromParent(sysCS, childPrmIdx)
  %endif
  %return prm
%endfunction
 
%%Function:SLibGetHStructWithLocalScopeSystemIdx=================================================
%%Abstract:
%%Returnthereusableparentsystemindexforagivensystemindex.
%%
%function SLibGetHStructWithLocalScopeSystemIdx(sysIdx)
  %return ::CompiledModel.System[sysIdx].ReusedParentSystemIdx
%endfunction
 
%%Function:FcnGetCanonicalOutput=================================================================
%%Abstract:
%%Returnsthecanonicaloutputargument(string)foragivencanonical
%%outputindex.
%%
%function FcnGetCanonicalOutput(accessSysIdx, aCallSite, coIdx) void
  %assign systemIdx = aCallSite[0]
  %assign callsiteIdx = aCallSite[1]
  %assign returnVal = ""
  %with ::CompiledModel
    %assign ssBlk = System[aCallSite[2]].Block[aCallSite[3]]
    %assign system = System[systemIdx]
    %assign sysCurrentTid = system.CurrentTID
    %assign system.CurrentTID = CurrentTID %% set system current tid to context current tid
    %with system
      %assign cross = CrossNoArgFcnBound
      %assign hStrucIdx = SLibGetHStructWithLocalScopeSystemIdx(systemIdx)
      %with ssBlk %% subsystem block
        %assign co = CallSiteInfo.CanonicalOutputArg[coIdx]
        %assign idnum = IDNUM(co.SignalSrc[0])
        %assign oldBlockIdx1 = ssBlk.BlockIdx[1]
        %assign ssBlk.BlockIdx[1] = accessSysIdx
        %if hStrucIdx < accessSysIdx && idnum[0] == "y"
          %assign cs = System[systemIdx].CallSites[callsiteIdx]
          %assign returnVal = FcnGetCanonicalOutput(accessSysIdx, cs, idnum[1])
        %else
          %% canonical output, if is scalar, must pass by addr.
          %assign returnVal = FcnGetCanonicalArg(co, 0, cross, TLC_TRUE)
        %endif
        %assign ssBlk.BlockIdx[1] = oldBlockIdx1
      %endwith
    %endwith %% System[sysIdx]
    %assign system.CurrentTID = sysCurrentTid
  %endwith
  %return returnVal
%endfunction
 
%%Function:FcnGetCanonicalInput==================================================================
%%Abstract:
%%Returnsthecanonicalinputargument(string)foragivencanonical
%%inputindex.
%%
%function FcnGetCanonicalInput(accessSysIdx, aCallSite, ciIdx) void
  %assign systemIdx = aCallSite[0]
  %assign callsiteIdx = aCallSite[1]
  %assign returnVal = ""
  %with ::CompiledModel
    %assign ssBlk = System[aCallSite[2]].Block[aCallSite[3]]
    %assign system = System[systemIdx]
    %assign sysCurrentTid = system.CurrentTID
    %assign system.CurrentTID = CurrentTID %% set system current tid to context current tid
    %with system
      %assign cross = CrossNoArgFcnBound
      %assign hStrucIdx = SLibGetHStructWithLocalScopeSystemIdx(systemIdx)
      %with ssBlk %% subsystem block
        %assign ci = CallSiteInfo.CanonicalInputArg[ciIdx]
        %assign idnum = IDNUM(ci.SignalSrc[0])
        %assert idnum[0] != "F"
        %assign oldBlockIdx1 = ssBlk.BlockIdx[1]
        %assign ssBlk.BlockIdx[1] = accessSysIdx
        %if hStrucIdx < accessSysIdx && (idnum[0] == "u" || idnum[0] == "y")
          %assign cs = System[systemIdx].CallSites[callsiteIdx]
          %if idnum[0] == "u"
            %assign returnVal = ...
              FcnGetCanonicalInput(accessSysIdx, cs, idnum[1])
          %else
            %assign returnVal = ...
              FcnGetCanonicalOutput(accessSysIdx, cs, idnum[1])
          %endif
        %else
          %assign ssBlkSysIdx = LibBlockParamSetting("Subsystem", "SystemIdx")
          %if LibGetRecordWidth(ci) == 1 && SLibGetISSCanInputIter(ssBlkSysIdx, ciIdx)
            %% If the canonical input is for an Implicit Iterator subsystem and it is
            %% a scalar, the scalar signal needs to be returned as reference.
            %assign returnVal = FcnGetCanonicalArg(ci, 0, cross, TLC_TRUE)
          %else
            %assign useAddr = (ci.DeclareAsPointer == "yes")
            %assign returnVal = FcnGetCanonicalArg(ci, 0, cross, useAddr)
          %endif
        %endif
        %assign ssBlk.BlockIdx[1] = oldBlockIdx1
      %endwith
      %assign system.CurrentTID = sysCurrentTid
    %endwith %% System[sysIdx]
  %endwith
  %return returnVal
%endfunction
 
 
%%Function:FcnGetArgForType======================================================================
%%Abstract:
%%Thisfunctiongeneratestheargumentneededinforasystemfunction
%%callbasedonargumenttype,e.g.DWorkorBlockIO.Thisisusedby
%%functionFcnGetAdditionalArgs
%%
%%Arguments:
%%argType-Thetypeoftheargument,e.g."DWork","BlockIO"
%%mdlrefArg-Thestringusedformodelreference,e.g."&(dw->rtb)"
%%localArg-Thestringforargumentpassedthroughparentsystem
%%e.g."localB"
%%sysIdx-systemfunctiontocall
%%callSiteIdx-systeminstancetocall
%%accessSysIdx-locationofthesystemcall
%%cTID-currenttid
%%
%function FcnGetArgForType(argType, mdlrefArg, localArg, sysIdx, callSiteIdx, accessSysIdx)
  %%
  %% If a system function (e.g. "Start") calls a function of the
  %% same system (e.g. "Enable"), it has to pass the structured arguments
  %% without adding a substructure element
  %%
 
  %assign thisSystem = ::CompiledModel.System[sysIdx]
  %with thisSystem
    %assign cTID = FcnGetCurrentAccessTid()
  %endwith
 
  %assign genModelRef = IsModelReferenceTarget() && accessSysIdx == NumSystems-1
 
  %if genModelRef
    %assign arg = mdlrefArg
  %elseif LibIsPassThroughSubsystemCall(sysIdx, accessSysIdx)
    %assign arg = localArg
    %assign retAccessHelper = SLibAccessArgHelper(%<argType>ArgDef,"",cTID)
    %<retAccessHelper>
  %else
    %assign cs = thisSystem.CallSites[callSiteIdx]
    %assign cross = ::CompiledModel.System[cs[0]].CrossNoArgFcnBound
    %assign varGroupIdx = FcnSysVarGroupIndex(thisSystem, argType, callSiteIdx)
    %assign parentVarGroupIdx = SLibVarGroupParentIndex(varGroupIdx)
    %assign identiPath = SLibCGIRVarGroupPath(parentVarGroupIdx, accessSysIdx, cross)
    %assign indenti = SLibVarGroupName(varGroupIdx)
 
    %if SLibGetSubsystemIsForEachSS(System[cs[0]])
      %% Callsite is For Each Subsystem
      %assign arg = SLibGetIndexedArgForForEachSS(parentVarGroupIdx, identiPath, indenti, cs, accessSysIdx, sysIdx)
    %elseif SLibIsMatrixVarGroupForIIS(sysIdx, argType)
      %% This subsystem is code reuse For Each subsystem
      %assert SLibGetSubsystemIsForEachSS(thisSystem)
      %assign arg = "%<identiPath>%<indenti>"
    %else
      %assign arg = "&%<identiPath>%<indenti>"
    %endif
  %endif
 
  %return arg
 
%endfunction
 
%%Function:FcnGetModelRefInput===================================================================
%%Abstract:
%%Returnsthemodelreferences-functioninputargument.
%%
%function FcnGetModelRefInput(thisSystem, argIdx) void
  %assign ci = thisSystem.Interface.CanonicalInputArgDef[argIdx]
  %assign passByRef = LibGetRecordWidth(ci) > 1 || ci.DeclareAsPointer == "yes"
  %assign ptr = passByRef ? "" : "*"
  %return ptr + "InPort_%<argIdx>"
%endfunction %% FcnGetModelRefInput
 
%%Function:FcnGetModelRefOutput==================================================================
%%Abstract:
%%Returnsthemodelreferences-functionoutputargument.
%%
%function FcnGetModelRefOutput(argIdx) void
  %return "OutPort_%<argIdx>"
%endfunction %% FcnGetModelRefOutput
 
%%Function:FcnGetModelRefParameter===============================================================
%%Abstract:
%%Generateparameterargumentas"ParamArg_#"formodelreferences-function.
%%
%function FcnGetModelRefParameter(thisSystem, argIdx) void
  %assign expr = "ParamArg_%<argIdx>"
  %assign canPrmArgDef = thisSystem.Interface.CanonicalPrmArgDef[argIdx]
  %assign isStruct = SLibDeclareDataAsPointer(canPrmArgDef.OriginalDataTypeIdx)
  %if (1 == LibGetRecordWidth(canPrmArgDef)) && (isStruct==TLC_FALSE)
    %return expr + "[0]"
  %endif
  %return expr
%endfunction %% FcnGetModelRefParameter
 
%function FcnGetModelRefRtm(thisSystem) void
  %return "&(dw->rtm)"
%endfunction
 
%%Function:FcnGetModelRefBlockIOArg==============================================================
%%Abstract:
%%Returnsthemodelreferences-functionblockIOargument.
%%
%function FcnGetModelRefBlockIOArg() void
  %if !SLibGetUseRTMcgType()
    %return "&(dw->rtb)"
  %else
    %return "&(dw->rtm.blockIO)"
  %endif
%endfunction %% FcnGetModelRefBlockIOArg
 
%%Function:FcnGetModelRefConstBlockIOArg=========================================================
%%Abstract:
%%Returnsthemodelreferences-functionconstantblockIOargument.
%%
%function FcnGetModelRefConstBlockIOArg() void
  %return "rtc_" + ::CompiledModel.Name
%endfunction %% FcnGetModelRefConstBlockIOArg
 
%%Function:FcnGetModelRefDWorkArg================================================================
%%Abstract:
%%Returnsthemodelreferences-functiondworkargument.
%%
%function FcnGetModelRefDWorkArg() void
  %if !SLibGetUseRTMcgType()
    %return "&(dw->rtdw)"
  %else
    %return "&(dw->rtm.dwork)"
  %endif
%endfunction %% FcnGetModelRefDWorkArg
 
 
%%Function:FcnGetModelRefContStatesArg===========================================================
%%Abstract:
%%Returnsthemodelreferences-functioncontinuesstatesargument.
%%
%function FcnGetModelRefContStatesArg() void
  %return "rtx"
%endfunction %% FcnGetModelRefContStatesArg
 
%%Function:FcnGetModelRefDerivativesArg==========================================================
%%Abstract:
%%Returnsthemodelreferences-functionderivativesargument.
%%
%function FcnGetModelRefDerivativesArg() void
  %return "rtxdot"
%endfunction %% FcnGetModelRefDerivativesArg
 
%%Function:FcnGetModelRefContStatesDisabledArg===================================================
%%Abstract:
%%Returnsthemodelreferences-functioncontinuesstatesdisabledargument.
%%
%function FcnGetModelRefContStatesDisabledArg() void
  %return "rtxdis"
%endfunction %% FcnGetModelRefContStatesDisabledArg
 
%%Function:FcnGetModelRefContStatesAbsTolArg=====================================================
%%Abstract:
%%Returnsthemodelreferences-functioncontinuesstatesabsolutetolerance
%%argument.
%%
%function FcnGetModelRefContStatesAbsTolArg() void
  %return "rtxAbsTol"
%endfunction %% FcnGetModelRefContStatesAbsTolArg
 
 
%%Function:FcnGetModelRefContStatesPerturbMinArg=====================================================
%%Abstract:
%%Returnsthemodelreferences-functioncontinuesstatesperturbmin
%%argument.
%%
%function FcnGetModelRefContStatesPerturbMinArg() void
  %return "rtxPerturbMin"
%endfunction %% FcnGetModelRefContStatesPerturbMinArg
 
%%Function:FcnGetModelRefContStatesPerturbMaxArg=====================================================
%%Abstract:
%%Returnsthemodelreferences-functioncontinuesstatesperturbmax
%%argument.
%%
%function FcnGetModelRefContStatesPerturbMaxArg() void
  %return "rtxPerturbMax"
%endfunction %% FcnGetModelRefContStatesPerturbMaxArg
 
%%Function:FcnGetModelRefNSZCArg=================================================================
%%Abstract:
%%Returnsthemodelreferences-functionnon-sampledzerocrossingsargument.
%%
%function FcnGetModelRefNSZCArg() void
  %return "rtzcsv"
%endfunction %% FcnGetModelRefNSZCdArg
 
%%Function:FcnGetModelRefZCEArg==================================================================
%%Abstract:
%%Returnsthemodelreferences-functionzerocrossingeventsargument.
%%
%function FcnGetModelRefZCEArg() void
  %return "&(dw->rtzce)"
%endfunction %% FcnGetModelRefZCEdArg
 
 
%%Function:FcnGetAdditionalArgs==================================================================
%%Abstract:
%%Thisfunctiongeneratestheargumentsneededinforasystemfunction
%%call.RefertoGetFunctionStrfortheorderofparameters.
%%
%%Arguments:
%%outAndRuleIdx-atwo-elementsvectorofstringforactualarguments
%%ofoutputidxandruleidx.use[]ifthefcnisnot
%%SetDimsfcn.
%%argVec-avectorofstringsforactualarguments(defaultis[])
%%sysIdx-systemfunctiontocall
%%callSiteIdx-systeminstancetocall
%%accessSysIdx-locationofthesystemcall
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants3.m
%%TopTester:test/toolbox/simulink/variants/exportFcns/tExportFcnsWithInlineVariants.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortHighlight.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tVariantsAndSubmodels.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/dimensionVariants/tDimensionVariants2.m
%%
%function FcnGetAdditionalArgs(fcnName, argVec, sysFcn, sysIdx, accessSysIdx, callSiteIdx, genModelRef, rtmNeeded) void
  %%
  %% CallSite is misleading in this context. The callsite vector is
  %% defines the memory instances of the function and is
  %% equal to the number of reused instances of a system.
  %%
  %assign thisSystem = ::CompiledModel.System[sysIdx]
  %assign modIdx = thisSystem.CGIRModuleIdx
  %assign thisModule = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
  %assign hasSimplifiedInterface = thisModule.SimplifiedInterface
  %assign isRateGroupedSLF = thisSystem.IsRateGroupedSLFcn
  %assign cs = thisSystem.CallSites[callSiteIdx]
  %assign args = ""
 
  %with thisSystem
    %assign cTID = FcnGetCurrentAccessTid()
  %endwith
 
  %assign isRG = SLibSystemFcnPeriodicRateGrouping(thisSystem, sysFcn)
  %with thisSystem.Interface
    %assign comma = ""
    %assign ssBlk = System[cs[2]].Block[cs[3]]
 
    %% We need to reset this so we will use the correct
    %% Interface when accessing canonical inputs and outputs.
    %% See the function SLibGetSourceRecordAndMapInfo in blkiolib.tlc
    %% NOTE: we reset this back after canonical inputs/outputs below.
    %assign saveMe = ssBlk.BlockIdx[1]
    %assign ssBlk.BlockIdx[1] = accessSysIdx
 
    %%
    %% 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 skipCanOutput = ...
      Vector(%<NumCanonicalOutputArgDefs>) [0@%<NumCanonicalOutputArgDefs>]
    %assign skipCanDWork = ...
      Vector(%<NumCanonicalDWorkArgDefs>) [0@%<NumCanonicalDWorkArgDefs>]
    %assign skipCanParam = ...
      Vector(%<NumCanonicalPrmArgDefs>) [0@%<NumCanonicalPrmArgDefs>]
 
    %assign skipRTM = SLibGenSubsysFcnAsClassMemFcn(thisSystem)
    %assign skipHStructArgs = LibSystemIsNonReusedFcn(thisSystem)
    %assign skipLocalB = skipHStructArgs || hasSimplifiedInterface
    %assign skipLocalC = skipHStructArgs
    %assign skipLocalDW = skipHStructArgs || hasSimplifiedInterface
    %assign skipLocalP = skipHStructArgs || hasSimplifiedInterface
    %assign skipLocalX = skipHStructArgs
    %assign skipLocalXdot = skipHStructArgs
    %assign skipLocalXdis = skipHStructArgs
    %assign skipLocalXabstol = skipHStructArgs
    %assign skipLocalXperturbmin = skipHStructArgs
    %assign skipLocalXperturbmax = skipHStructArgs
    %assign skipLocalZCSV = skipHStructArgs
    %assign skipLocalZCE = skipHStructArgs || hasSimplifiedInterface
 
    %assign skipLocalDataGroup = ...
      Vector(%<::CompiledModel.NumCoderDataGroups>) [%<skipHStructArgs>@%<::CompiledModel.NumCoderDataGroups>]
 
    %if isRateGroupedSLF && Accelerator
      %% Rate grouped Simulink functions are defined in the root module. Need to get
      %% the Function record from root. FcnGetAdditionalArgs is only
      %% invoked during Accel code gen to create a call to the smiulink function.
      %% (A call to the SLF is not emitted for RTW code gen.)
      %assign rootSystem = ::CompiledModel.System[NumSystems-1]
      %assign rootModIdx = rootSystem.CGIRModuleIdx
      %assign rootModule = ::CompiledModel.RTWCGModules.RTWCGModule[rootModIdx]
      %assign fncExistsInSystem = ISFIELD(rootModule, "SystemFunctions") && ...
        ISFIELD(rootModule.SystemFunctions, fcnName)
      %if fncExistsInSystem
        %assign fcnIndex = GETFIELD(rootModule.SystemFunctions, fcnName)
        %assign thisFcn = rootModule.Function[fcnIndex]
      %endif
      %% Canonical I/O and RTM are handled in IR. Setting needArgs to false and
      %% skipRTM to true will prevent adding these args twice. The only args
      %% that do not get handled in IR are canonical parameters so we
      %% still need to execute the following loop through args.
      %assign needArgs = TLC_FALSE
      %assign skipRTM = 1
    %else
      %assign fncExistsInSystem = ISFIELD(thisModule, "SystemFunctions") && ...
        ISFIELD(thisModule.SystemFunctions, fcnName)
      %assign fcnIndex = GETFIELD(thisModule.SystemFunctions, fcnName)
      %assign thisFcn = thisModule.Function[fcnIndex]
      %if thisModule.AccessesArgsGlobally && !thisModule.NeedsSimStruct
        %assign skipRTM = 1
      %endif
      %assign needArgs = LibSystemIsReusedFcn(thisSystem) || ...
        (LibSystemIsNonReusedFcn(thisSystem) && ...
        ISFIELD(thisSystem,"RTWSystemCodeOptIntf")) || ...
        thisSystem.IsService
    %endif
 
    %if fncExistsInSystem
      %if genModelRef
        %foreach argIdx = SIZE(argVec, 1)
          %assign args = args + comma + argVec[argIdx]
          %assign comma = ", "
        %endforeach
      %endif
      %assert genModelRef || SIZE(argVec, 1) == thisFcn.NumArgs
      %assert SIZE(thisFcn.ArgAccessed, 1) == thisFcn.NumArgs
      %assert SIZE(thisFcn.ArgSource, 1) == thisFcn.NumArgs
      %foreach argIdx=thisFcn.NumArgs
        %assign idNum = SLibSafeIDNUM(thisFcn.ArgSource, argIdx)
        %assign argSrc = idNum[0]
        %assign argSrcIdx = idNum[1]
        %if thisFcn.ArgAccessed[argIdx] || (GenerateClassInterface && argSrc == "LCDG")
          %switch argSrc
            %case "I" %% canonical input
              %if 0 < NumCanonicalInputArgDefs %% CrossNoArgFcnBound
                %if needArgs
                  %if genModelRef
                    %assign args = args + comma + ...
                      FcnGetModelRefInput(thisSystem, argSrcIdx)
                  %else
                    %assign args = args + comma + argVec[argIdx]
                  %endif
                  %assign comma = ", "
                %endif
                %assign skipCanInput[argSrcIdx] = 1
              %endif
              %break
            %case "O" %% canonical output
              %if 0 < NumCanonicalOutputArgDefs %% CrossNoArgFcnBound
                %if needArgs
                  %if genModelRef
                    %assign args = args + comma + ...
                      FcnGetModelRefOutput(argSrcIdx)
                  %else
                    %assign args = args + comma + argVec[argIdx]
                  %endif
                  %assign comma = ", "
                %endif
                %assign skipCanOutput[argSrcIdx] = 1
              %endif
              %break
            %case "D" %% canonical dwork
              %if 0 < NumCanonicalDWorkArgDefs %% CrossNoArgFcnBound
                %if genModelRef
                  %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
                  %assign prefix = (("I" == dimsSrc) ? "In" : "Out")
                  %assign args = args + comma + ...
                    FcnGetModelRefDWork(prefix, dimsSrcIdx, argSrcIdx)
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipCanDWork[argSrcIdx] = 1
              %endif
              %break
            %case "P" %% canonical parameter
              %if 0 < NumCanonicalPrmArgDefs %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = args + comma + ...
                    FcnGetModelRefParameter(thisSystem, argSrcIdx)
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipCanParam[argSrcIdx] = 1
              %endif
              %break
            %case "RTM"
              %if 0 == skipRTM
                %if GenerateClassInterface
                  %if argVec[argIdx] != "getRTM()"
                    %assign args = args + comma + RTMGetModelSS()
                  %else
                    %assign args = args + comma + argVec[argIdx]
                  %endif
                %elseif genModelRef && !IsModelRefScalableBuild()
                  %assign args = args + comma + ...
                    FcnGetModelRefRtm(thisSystem)
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipRTM = 1
              %endif
              %break
            %case "LCDG"
              %% Here, argSrcIdx refers to the index of the coder data group
              %if 0 == skipLocalDataGroup[argSrcIdx] %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = args + comma + FcnGetModelRefBlockIOArg()
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipLocalDataGroup[argSrcIdx] = 1
              %endif
              %break
            %case "LB" %% block IO
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = args + comma + FcnGetModelRefBlockIOArg()
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipLocalB = 1
              %endif
              %break
            %case "LC" %% constat block IO
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = args + comma + FcnGetModelRefConstBlockIOArg()
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipLocalC = 1
              %endif
              %break
            %case "LW" %% dwork
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = args + comma + FcnGetModelRefDWorkArg()
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipLocalDW = 1
              %endif
              %break
            %case "LP" %% parameter
            %case "LCP" %% constant parameter
            %case "LPI" %% const parameter with init
              %assert !genModelRef
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %assign args = args + comma + argVec[argIdx]
                %assign comma = ", "
                %assign skipLocalP = 1
              %endif
              %break
            %case "LX" %% continues states
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = args + comma + FcnGetModelRefContStatesArg()
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipLocalX = 1
              %endif
              %break
            %case "LDX" %% derivatives
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = args + comma + FcnGetModelRefDerivativesArg()
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipLocalXdot = 1
              %endif
              %break
            %case "LXDI" %% continues state disabled
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = ...
                    args + comma + FcnGetModelRefContStatesDisabledArg()
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipLocalXdis = 1
              %endif
              %break
            %case "LXAT" %% continues state absolute tolerance
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = ...
                    args + comma + FcnGetModelRefContStatesAbsTolArg()
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipLocalXabstol = 1
              %endif
              %break
               
            %case "LXPTMIN" %% continues state perturb min
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = ...
                    args + comma + FcnGetModelRefContStatesPerturbMinArg()
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipLocalXperturbmin = 1
              %endif
              %break
               
            %case "LXPTMAX" %% continues state perturb max
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = ...
                    args + comma + FcnGetModelRefContStatesPerturbMaxArg()
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipLocalXperturbmax = 1
              %endif
              %break
                
               
            %case "LZ" %% non-sampled zero crossings
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = args + comma + FcnGetModelRefNSZCArg()
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipLocalZCSV = 1
              %endif
              %break
            %case "LZE" %% zero crossing events
              %if 0 == skipHStructArgs %% CrossNoArgFcnBound
                %if genModelRef
                  %assign args = args + comma + FcnGetModelRefZCEArg()
                %else
                  %assign args = args + comma + argVec[argIdx]
                %endif
                %assign comma = ", "
                %assign skipLocalZCE = 1
              %endif
              %break
            %case "CPI"
            %case "TID"
              %if !genModelRef
                %assign args = args + comma + argVec[argIdx]
                %assign comma = ", "
              %endif
              %break
            %case "X"
              %if !genModelRef
                %assign args = args + comma + argVec[argIdx]
                %assign comma = ", "
              %endif
              %break
            %case "U"
            %case "Y"
              %if !thisSystem.CrossNoArgFcnBound
                %assign args = args + comma + argVec[argIdx]
                %assign comma = ", "
              %endif
              %break
            %default
              %%START_ASSERT
              %assign errTxt = "Unhandled argument type '%<argSrc>'."
              %break
              %%END_ASSERT
          %endswitch
        %endif
      %endforeach
    %endif
 
    %%
    %% Only reused systems get arguments (except for elapased time)
    %%
    %if needArgs
      %assign isTestInterface = ...
        ::CompiledModel.ConfigSet.GenerateTestInterfaces && ...
        ISFIELD(thisSystem, "GenerateReusableWrapper") && ...
        GETFIELD(thisSystem, "GenerateReusableWrapper")
 
      %%
      %% Canonical input argument
      %%
      %foreach argIdx=thisSystem.Interface.NumCanonicalInputArgDefs
        %assign canIn = thisSystem.Interface.CanonicalInputArgDef[argIdx]
        %if !skipCanInput[argIdx] && ...
          SysFcnArgNeeded(sysFcn, canIn, cTID, isRG)
          %%
          %if isTestInterface && ISFIELD(canIn, "SSGraphicalAPIReference")
            %assign grIn = canIn.SSGraphicalAPIReference
            %assign args = "%<args>%<comma>%<grIn.SLName>"
            %assign comma = ", "
          %elseif LibIsPassThroughSubsystemCall(sysIdx, accessSysIdx)
            %assign args = "%<args>%<comma>%<LibGetRecordIdentifier(canIn)>"
            %assign comma = ", "
            %<SLibAccessArgHelper(canIn,"",cTID)>
          %else
            %with System[cs[0]]
              %assign cross = CrossNoArgFcnBound
              %with ssBlk %% subsystem block
                %assign skipThisArg = 0
                %if IDNUM(canIn.SignalSrc[0])[0] == "F"
                  %assign skipThisArg = 1
                %endif
                %if skipThisArg == 0
                  %if genModelRef
                    %assign args = args + comma + ...
                      FcnGetModelRefInput(thisSystem, argIdx)
                  %else
                    %assign args = args + comma + ...
                      FcnGetCanonicalInput(accessSysIdx, cs, argIdx)
                  %endif
                  %assign comma = ", "
                %endif
              %endwith %% subsystem block
            %endwith %% thisSystem
          %endif %%LibIsPassThroughSubsystemCall(sysIdx, accessSysIdx)
 
          %% Add vardims argument for the canonical input
          %assign res = FcnGetAdditionalCanDimSizeDWForCanInp(sysFcn, sysIdx, ...
            accessSysIdx, callSiteIdx, argIdx, comma, args, skipCanDWork)
          %assign comma = res[0]
          %assign args = res[1]
        %endif %% SysFcnArgNeeded
 
      %endforeach %% argIdx=NumCanonicalInputArgDefs
      %%
      %% Canonical output argument
      %%
      %foreach argIdx=thisSystem.Interface.NumCanonicalOutputArgDefs
        %assign canOut = thisSystem.Interface.CanonicalOutputArgDef[argIdx]
        %if !skipCanOutput[argIdx] && SysFcnArgNeeded(sysFcn, canOut, cTID, isRG)
          %%
          %if isTestInterface && ISFIELD(canOut, "SSGraphicalAPIReference")
            %assign grOut = canOut.SSGraphicalAPIReference
            %assign args = "%<args>%<comma>%<grOut.SLName>"
          %else
            %if LibIsPassThroughSubsystemCall(sysIdx, accessSysIdx)
              %assign isReference = FcnPassCanonicalOutputAsReference(canOut)
              %if IsModelReferenceBaseSys(thisSystem) && ...
                (SLibFcnProtoCtrlActive() || GenerateClassInterface) && ...
                canOut.DeclareAsPointer == "no" && ...
                (canOut.PassByReturn == "yes" || isReference) && ...
                  sysFcn != "Output" && sysFcn != "OutputUpdate"
                %%root output is return-by-value, needs to get its address
                %assign args = "%<args>%<comma>&%<LibGetRecordIdentifier(canOut)>"
              %else
                %assign args = "%<args>%<comma>%<LibGetRecordIdentifier(canOut)>"
              %endif
              %<SLibAccessArgHelper(canOut,"",cTID)>
            %elseif genModelRef
              %assign args = args + comma + FcnGetModelRefOutput(argIdx)
            %else
              %assign args = args + comma + ...
                FcnGetCanonicalOutput(accessSysIdx, cs, argIdx)
            %endif %%LibIsPassThroughSubsystemCall(sysIdx, accessSysIdx)
          %endif %% ConfigSet.GenerateTestInterfaces
          %assign comma = ", "
 
          %%
          %% Add vardims argument for the canonical output
          %assign res = FcnGetAdditionalCanDimSizeDWForCanOut(sysFcn, sysIdx, ...
            accessSysIdx, callSiteIdx, argIdx, comma, args, skipCanDWork)
          %assign comma = res[0]
          %assign args = res[1]
        %endif %% SysFcnArgNeeded
        %%
      %endforeach %% argIdx=NumCanonicalOutputArgDefs
      %%
      %% Reset the BlockIdx, see comment above.
      %assign ssBlk.BlockIdx[1] = saveMe
      %assign isScalableMRSys = IsModelReferenceBaseSys(thisSystem) && IsModelRefScalableBuild()
      %%
      %% rtModel argument
      %%
      %assign isMatchGrInterface = (LibSystemIsNonReusedFcn(thisSystem) && ...
        ISFIELD(thisSystem,"RTWSystemMatchGrInterface"))
      %if !skipRTM && ((SysFcnArgNeeded(sysFcn, RTMArgDef, cTID, isRG) && !isMatchGrInterface) || rtmNeeded) && !isScalableMRSys
        %if genModelRef
          %assign args = "%<args>%<comma>&(dw->rtm)"
        %else
          %assign accessSystem = ::CompiledModel.System[accessSysIdx]
          %assign rtmArg = FcnUpdateRTModelInterfaceArg(accessSystem, GetSimStructExpr(accessSystem, SLibGetSimStruct()))
          %if thisModule.SimplifiedInterface
            %assign args = "%<rtmArg>%<comma>%<args>"
          %else
            %assign args = "%<args>%<comma>%<rtmArg>"
          %endif
        %endif
        %assign comma = ", "
        %assign callerHStSystem = ...
          SLibCallerHStuctDeclSystem(thisSystem, callSiteIdx)
        %<SLibAccessArgHelper(callerHStSystem.Interface.RTMArgDef,"",cTID)>
      %endif
      %%
      %% Block IO argument
      %%
      %if !skipLocalB && !isScalableMRSys && SysFcnArgNeeded(sysFcn, BlockIOArgDef, cTID, isRG)
        %assign arg = FcnGetArgForType("BlockIO", ...
          FcnGetModelRefBlockIOArg(), "localB", sysIdx, callSiteIdx, accessSysIdx)
        %assign args = "%<args>%<comma>%<arg>"
        %assign comma = ", "
      %endif
      %%
      %% DataGroup arguments. For model reference, we're using localGroup
      %% to hold the pointer from RTM and pass that down into subfunctions. For
      %% access by the model reference root system, access will be through RTM.
      %foreach gIdx = ::CompiledModel.NumCoderDataGroups
        %assign argDef = FcnGetGroupArgDef(gIdx)
        %assign group = ::CompiledModel.CoderDataGroup[gIdx]
        %assign groupAccessedThroughRTM = ...
          IsModelReferenceBaseSys(System[accessSysIdx]) && ...
          SLibAccessGroupThroughSelf(group)
        %if !(skipLocalDataGroup[gIdx]) && ...
            !isScalableMRSys && ...
            !GenerateClassInterface && ...
            !groupAccessedThroughRTM && ...
            SysFcnArgNeeded(sysFcn, argDef, cTID, isRG) && ...
            !hasSimplifiedInterface
          %assign groupToken = "CoderDataGroup" + group.Name
          %assign varGroupIdx = FcnSysVarGroupIndex(thisSystem, groupToken, callSiteIdx)
          %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
          %assign varName = varGroup.LocalName
          %assign arg = FcnGetArgForType(groupToken, ...
            varName, varName, sysIdx, callSiteIdx, accessSysIdx)
          %assign args = "%<args>%<comma>%<arg>"
          %assign comma = ", "
        %endif
      %endforeach
      %%
      %% Constant block IO argument
      %%
      %if !skipLocalC && SysFcnArgNeeded(sysFcn, ConstBlockIOArgDef, cTID, isRG)
        %%
        %% If a system function (e.g. "Start") calls a function of the
        %% same system (e.g. "Enable"), it has to pass the structured arguments
        %% without adding a substructure element
        %%
        %assert !isScalableMRSys
        %if genModelRef
          %assign args = args + comma + FcnGetModelRefConstBlockIOArg()
        %elseif LibIsPassThroughSubsystemCall(sysIdx, accessSysIdx)
          %assign args = "%<args>%<comma>localC"
          %<SLibAccessArgHelper(ConstBlockIOArgDef,"",cTID)>
        %else
          %assign cross = ::CompiledModel.System[cs[0]].CrossNoArgFcnBound
          %assign varGroupIdx = ...
            FcnSysVarGroupIndex(thisSystem, "ConstBlockIO", callSiteIdx)
          %assign parentVarGroupIdx = SLibVarGroupParentIndex(varGroupIdx)
          %assign identiPath = SLibCGIRVarGroupPath(parentVarGroupIdx, ...
            accessSysIdx, cross)
          %assign indenti = SLibVarGroupName(varGroupIdx)
          %assign dataType = FcnSysVarGroupType(thisSystem,"ConstBlockIO")
          %assign cast = "(" + dataType + "*)"
          %assign argStr = cast + "&%<identiPath>%<indenti>"
          %assign argStr = FcnReplaceCCastWithStaticCastForCPP(argStr)
          %assign args = "%<args>%<comma>%<argStr>"
        %endif
        %assign comma = ", "
      %endif
      %%
      %% DWork IO argument
      %%
      %assign isCPPEncapMdlRef = GenerateClassInterface && IsModelReferenceBaseSys(thisSystem)
      %if !skipLocalDW && SysFcnArgNeeded(sysFcn, DWorkArgDef, cTID, isRG) && !isScalableMRSys && !isCPPEncapMdlRef
        %assign arg = FcnGetArgForType("DWork", FcnGetModelRefDWorkArg(), ...
          "localDW", sysIdx, callSiteIdx, accessSysIdx)
        %assign args = "%<args>%<comma>%<arg>"
        %assign comma = ", "
      %endif
      %%
      %% Parameter H-Struct argument
      %%
      %assign isSysFcnArgNeeded = SysFcnArgNeeded(sysFcn, ParameterArgDef, cTID, isRG)
      %if !skipLocalP && isSysFcnArgNeeded
        %assert !isScalableMRSys
        %if !genModelRef
          %%
          %% Does a passthrough parameter structure argument exists ?
          %%
          %if InlineParameters != 0 && ParameterArgDef.PassthroughSystemIdx > -1
            %%
            %% Get the parent callsite vector (pcs)
            %%
            %assign pcs = thisSystem.CallSites[0]
            %%
            %% Mark the parents parameter structure argument as accessed
            %%
            %assign csPrmArgDef = System[pcs[0]].Interface.ParameterArgDef
            %assign prmAccessSysIdx = ParameterArgDef.PassthroughSystemIdx
            %<SLibAccessArgHelper(System[pcs[0]].Interface.ParameterArgDef,"",cTID)>
            %<SLibAccessArgHelper(System[prmAccessSysIdx].Interface.ParameterArgDef,"",cTID)>
            %%
            %if prmAccessSysIdx == NumSystems-1
              %if !GenerateClassInterface
                %assign args = "%<args>%<comma>%<LibGetParametersStruct()>"
              %else
                %if accessSysIdx == NumSystems-1
                  %assign args = "%<args>%<comma>&%<LibGetParametersStruct()>"
                %else
                  %assign args = "%<args>%<comma> %<LibGetParametersStruct()>"
                %endif
              %endif
            %elseif LibIsPassThroughSubsystemCall(sysIdx, accessSysIdx) || ...
              csPrmArgDef.PassthroughSystemIdx == prmAccessSysIdx
              %%
              %% - not called by a parent system (e.g. enable in start)
              %% - parent has the same pass through system index
              %%
              %assign args = "%<args>%<comma>localP"
              %<SLibAccessArgHelper(ParameterArgDef,"",cTID)>
            %else
              %assign cast = "(" + FcnSysVarGroupType(thisSystem,"Parameter") + " *)"
              %assign varGroupIdx = ...
                FcnSysVarGroupIndex(thisSystem, "Parameter", callSiteIdx)
              %assign parentVarGroupIdx = SLibVarGroupParentIndex(varGroupIdx)
              %assign cross = ::CompiledModel.System[cs[0]].CrossNoArgFcnBound
              %assign identiPath = SLibCGIRVarGroupPath(parentVarGroupIdx, ...
                csPrmArgDef.PassthroughSystemIdx, cross)
              %assign indenti = SLibVarGroupName(varGroupIdx)
              %assign args = "%<args>%<comma>%<cast> &%<identiPath>%<indenti>"
            %endif
          %elseif LibIsPassThroughSubsystemCall(sysIdx, accessSysIdx)
            %assign args = "%<args>%<comma>localP"
            %<SLibAccessArgHelper(ParameterArgDef,"",cTID)>
          %else %% normal parameter structure argument
            %assign cast = "(" + FcnSysVarGroupType(thisSystem,"Parameter") + " *)"
            %assign varGroupIdx = ...
              FcnSysVarGroupIndex(thisSystem, "Parameter", callSiteIdx)
            %assign parentVarGroupIdx = SLibVarGroupParentIndex(varGroupIdx)
            %assign cross = ::CompiledModel.System[cs[0]].CrossNoArgFcnBound
            %assign identiPath = SLibCGIRVarGroupPath(parentVarGroupIdx, ...
              accessSysIdx, cross)
            %assign indenti = SLibVarGroupName(varGroupIdx)
            %assign args = "%<args>%<comma>%<cast> &%<identiPath>%<indenti>"
          %endif
        %endif
        %assign comma = ", "
      %endif
      %%
      %% CState argument
      %%
      %if !skipLocalX && SysFcnArgNeeded(sysFcn, ContStatesArgDef, cTID, isRG)
        %assign arg = FcnGetArgForType("ContStates", ...
          FcnGetModelRefContStatesArg(), "localX", sysIdx, ...
          callSiteIdx, accessSysIdx)
        %assign args = "%<args>%<comma>%<arg>"
        %assign comma = ", "
      %endif
      %%
      %% CState Derivative argument
      %%
      %if !skipLocalXdot && SysFcnArgNeeded(sysFcn, ContStatesDerivativeArgDef, cTID, isRG)
        %assign arg = FcnGetArgForType("ContStatesDerivative", ...
          FcnGetModelRefDerivativesArg(), "localXdot", sysIdx, ...
          callSiteIdx, accessSysIdx)
        %assign args = "%<args>%<comma>%<arg>"
        %assign comma = ", "
      %endif
      %%
      %% CState Disabled argument
      %%
      %if !skipLocalXdis && SysFcnArgNeeded(sysFcn, ContStatesDisabledArgDef, cTID, isRG)
        %assign arg = FcnGetArgForType("ContStatesDisabled", ...
          FcnGetModelRefContStatesDisabledArg(), "localXdis", sysIdx, ...
          callSiteIdx, accessSysIdx)
        %assign args = "%<args>%<comma>%<arg>"
        %assign comma = ", "
      %endif
      %%
      %% CState Absolute Tolerance argument
      %%
      %if !skipLocalXabstol && SysFcnArgNeeded(sysFcn, ContStatesAbsoluteToleranceArgDef, cTID, isRG)
        %assign arg = FcnGetArgForType("ContStatesAbsoluteTolerance", ...
          FcnGetModelRefContStatesAbsTolArg(), "localXAbsTol", sysIdx, ...
          callSiteIdx, accessSysIdx)
        %assign args = "%<args>%<comma>%<arg>"
        %assign comma = ", "
      %endif
      %%
       
      %% CState Perturb Min argument
      %%
      %if !skipLocalXperturbmin && SysFcnArgNeeded(sysFcn, ContStatesPerturbMinArgDef, cTID, isRG)
        %assign arg = FcnGetArgForType("ContStatesPerturbMin", ...
          FcnGetModelRefContStatesPerturbMinArg(), "localXPerturbMin", sysIdx, ...
          callSiteIdx, accessSysIdx)
        %assign args = "%<args>%<comma>%<arg>"
        %assign comma = ", "
      %endif
      %%
       
      %% CState Perturb Max argument
      %%
      %if !skipLocalXperturbmax && SysFcnArgNeeded(sysFcn, ContStatesPerturbMaxArgDef, cTID, isRG)
        %assign arg = FcnGetArgForType("ContStatesPerturbMax", ...
          FcnGetModelRefContStatesPerturbMaxArg(), "localXPerturbMax", sysIdx, ...
          callSiteIdx, accessSysIdx)
        %assign args = "%<args>%<comma>%<arg>"
        %assign comma = ", "
      %endif
      %%
       
      %% Non Sampled Zero Crossing argument
      %%
      %if !skipLocalZCSV && SysFcnArgNeeded(sysFcn, ZCSVArgDef, cTID, isRG)
        %assign arg = FcnGetArgForType("ZCSV", FcnGetModelRefNSZCArg(), ...
          "localZCSV", sysIdx, callSiteIdx, accessSysIdx)
        %assign args = "%<args>%<comma>%<arg>"
        %assign comma = ", "
      %endif
      %%
      %% ZCEvent argument
      %%
      %if !skipLocalZCE && !GenerateClassInterface && SysFcnArgNeeded(sysFcn, ZCEventArgDef, cTID, isRG) && !isScalableMRSys
        %assign arg = FcnGetArgForType("ZCEvent", FcnGetModelRefZCEArg(), ...
          "localZCE", sysIdx, callSiteIdx, accessSysIdx)
        %assign args = "%<args>%<comma>%<arg>"
        %assign comma = ", "
      %endif
      %%
      %% Canonical parameters
      %%
      %foreach argIdx=NumCanonicalPrmArgDefs
        %assign argDef = CanonicalPrmArgDef[argIdx]
        %if !skipCanParam[argIdx] && SysFcnArgNeeded(sysFcn, argDef, cTID, isRG)
          %assign prmWidth = LibGetRecordWidth(argDef)
 
          %if !genModelRef
            %assign childPrmIdx = ...
              ssBlk.CallSiteInfo.CanonicalPrmArg[argIdx].ChildPrmArgIdx
            %%
            %if isTestInterface
              %% Called by Test interface. Get information about parent Child Prm
              %assign prm = FunctionGetChildPrmArgFromParent(cs, childPrmIdx)
            %else
              %assign prm = SLibGetCallSitePrmArg(cs, childPrmIdx)
            %endif
            %%
          %endif
 
          %%
          %% If one or more of arguments of a function that is passed by address
          %% is a expression, than the result of this expression has to be stored
          %% in a temporrary variable. The address of the temporary variable will
          %% than be passed as the argument of the function call.
          %%
          %assign ref = ""
          %if genModelRef
            %% Generating S-Function for model-reference.
            %% Always generate parameter argument as "ParamArg_#"
            %assign expr = FcnGetModelRefParameter(thisSystem, argIdx)
          %elseif LibIsPassThroughSubsystemCall(sysIdx, accessSysIdx)
            %assign expr = LibGetRecordIdentifier(argDef)
            %<SLibAccessArgHelper(argDef,"",cTID)>
          %elseif prmWidth > 1
            %if LibBlockParameterIsExpression(prm)
              %assign ref = "&"
              %if !ISFIELD(ssBlk, "%<sysFcn>FcnCallCode")
                %addtorecord ssBlk %<sysFcn>FcnCallCode ...
                  { localPrmDecl ""; localExpr ""}
              %endif
              %assign dataType = SLibGetRecordDataTypeName(argDef, "")
              %assign fcnCode = ssBlk.%<sysFcn>FcnCallCode
              %assign iden = LibGetRecordIdentifier(argDef)
              %if !isTestInterface
                %% Add parameter declaration if not called by test interface
                %% The canonical parameter identifier is dangerous to reuse so massage it. See g612025.
                %assign iden_tmp = "%<iden>"
                %assign iden_tmp[2] = "e"
                %assign iden = iden_tmp
                %assign fcnCode.localPrmDecl = fcnCode.localPrmDecl + ...
                  "%<dataType> %<iden>[%<prmWidth>];/n"
              %endif %% ! isTestInterface
              %assign expr = "%<iden>[0]"
              %assign rolledExpr = ""
              %openfile rolledExpr
              %roll idx=[0:%],lcv=RollThreshold,ssBlk,"Roller",""
                %<iden>[%] = ...
                  %<FcnGenParamExprWithCast("", accessSysIdx, cs[0], cs, prm, lcv, "", idx)>;
              %endroll
 
              %closefile rolledExpr
              %if !isTestInterface
                %% Add localExpr if not called by interface
                %assign fcnCode.localExpr = fcnCode.localExpr + rolledExpr
              %endif
            %elseif prm.ASTNode.IsNonTerminal == 0 && ...
              prm.ASTNode.Op == "M_CANPRM_ID"
              %assign ref = "&"
              %assign expr = FcnGenParamExprWithCast("", accessSysIdx, cs[0], cs, prm, "", "", "")
            %else
              %assign prmSize = SLibGetSizeOfValueFromParamRec(prm)
              %assign nRows = prmSize[0]
              %if nRows == 1
                %assign expr = FcnBlockParameterAddr(prm, "", "", 0, 0, TLC_FALSE)
              %else
                %assign expr = ...
                  FcnBlockMatrixParameterAddr(prm, "", "", 0, "", "", 0, TLC_FALSE)
              %endif
            %endif
          %else
            %assign expr = FcnGenParamExprWithCast("", accessSysIdx, cs[0], cs, prm, "", "", "")
            %if argDef.DeclareAsPointer == "yes"
              %assign expr = "(%<expr>)"
              %assign ref = "&"
            %endif
          %endif
          %assign args = "%<args>%<comma>%<ref>%<expr>"
          %assign comma = ", "
        %endif %% SysFcnArgNeeded
      %endforeach %% argIdx=NumCanonicalPrmArgDefs
      %%
      %% Canonical DWork argument
      %%
      %assign canDWork = FcnGetCanDWorkArgs(sysFcn, sysIdx, ...
        accessSysIdx, callSiteIdx, cTID, isRG, skipCanDWork)
      %if canDWork != ""
        %assign args = "%<args>%<comma>%<canDWork>"
        %assign comma = ", "
      %endif
    %endif %% LibSystemIsReusedFcn(thisSystem)
  %endwith %% thisSystem.Interface
 
  %return args
%endfunction %% FcnGetAdditionalArgs
 
%%Function:LibIsPassThroughSubsystemCall=========================================================
%%Abstract:
%%Theparenthasthesamepassthroughsystemindexasthecaller.
%%
%function LibIsPassThroughSubsystemCall(sysIdx, accessSysIdx)
  %return ::CompiledModel.System[sysIdx].HStructDeclSystemIdx == accessSysIdx
%endfunction
 
%%Function:LibGetFcnCallISR======================================================================
%%Abstract:
%%ForusebyinlinedS-Functionswithfunctioncalloutputs.Returnsa
%%functioncallstringwithaISR(interuptserviceroutine)compatible
%%interface.
%%Thislibraryfunctionshouldbeusedtoaattachthegeneratedcode
%%ofaSimulinkfunctioncallsubsystemtoaISR.
%%
%function LibGetFcnCallISR(ssBlock, portEl, tidVal) void
  %return SLibGetFcnEventType(ssBlock, portEl, tidVal, "ISR", "OutputUpdate")
%endfunction
 
%%Function:LibGetFcnCallFNI======================================================================
%%Abstract:
%%ForusebyinlinedS-Functionswithfunctioncalloutputs.Returnsa
%%functioncallstringwithaFNI(forcednon-inlined)compatible
%%interface.
%%
%function LibGetFcnCallFNI(ssBlock, portEl, tidVal) void
  %return SLibGetFcnEventType(ssBlock, portEl, tidVal, "FNI", "OutputUpdate")
%endfunction
 
%%Function:LibGetFcnInitializeFNI================================================================
%%Abstract:
%%ForusebyinlinedS-Functionswithfunctioncalloutputs.Returnsa
%%functioncallstringwithaFNI(forcednon-inlined)compatible
%%interface.
%%
%function LibGetFcnInitializeFNI(ssBlock, portEl, tidVal) void
  %return SLibGetFcnEventType(ssBlock, portEl, tidVal, "FNI", "Initialize")
%endfunction
 
%%Function:LibGetFcnSystemResetFNI===============================================================
%%Abstract:
%%ForusebyinlinedS-Functionswithfunctioncalloutputs.Returnsa
%%functioncallstringwithaFNI(forcednon-inlined)compatible
%%interface.
%%
%function LibGetFcnSystemResetFNI(ssBlock, portEl, tidVal) void
  %return SLibGetFcnEventType(ssBlock, portEl, tidVal, "FNI", "SystemReset")
%endfunction
 
%%Function:LibGetFcnEnableFNI====================================================================
%%Abstract:
%%ForusebyinlinedS-Functionswithfunctioncalloutputs.Returnsa
%%functioncallstringwithaFNI(forcednon-inlined)compatible
%%interface.
%%
%function LibGetFcnEnableFNI(ssBlock, portEl, tidVal) void
  %return SLibGetFcnEventType(ssBlock, portEl, tidVal, "FNI", "Enable")
%endfunction
 
%%Function:LibGetFcnDisableFNI===================================================================
%%Abstract:
%%ForusebyinlinedS-Functionswithfunctioncalloutputs.Returnsa
%%functioncallstringwithaFNI(forcednon-inlined)compatible
%%interface.
%%
%function LibGetFcnDisableFNI(ssBlock, portEl, tidVal) void
  %return SLibGetFcnEventType(ssBlock, portEl, tidVal, "FNI", "Disable")
%endfunction
 
%%Function:SLibGenerateISRStubs==================================================================
%%Abstract:
%%ThisfunctioniscalledbySLibGetBodyOutputUpdateFcnCachein
%%commonbodlib.tlcinordertogeneratethefunctioncallstubswitha
%%ISR(interuptserviceroutine)compatibleinterface.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibGenerateISRStubs(fcnCallSys) void
  %assign tmpBuffer = ""
  %assign sysFcnPrototype = ""
 
  %if LibIsSystemField(fcnCallSys, "NumISROutputUpdateCallSites")
    %assign NumISRCallSites = ...
      LibGetSystemField(fcnCallSys, "NumISROutputUpdateCallSites")
    %assign ISRCallSite = ...
      LibGetSystemField(fcnCallSys, "ISROutputUpdateCallSite")
    %openfile tmpBuffer
    %foreach idx=NumISRCallSites
      %assign fcnName = ISRCallSite[idx][0]
      %assign sysIdx = ISRCallSite[idx][1]
      %assign csIdx = ISRCallSite[idx][2]
      %assign portEl = ISRCallSite[idx][3]
      %assign tidVal = ISRCallSite[idx][4]
      %assign callSite = ::CompiledModel.System[sysIdx].CallSites[csIdx]
      %assign ssBlock = ::CompiledModel.System[callSite[2]].Block[callSite[3]]
 
      /*
       * Interrupt service routine (ISR) function call stub
       * for '%<ssBlock.Name>'
       */
      void %<fcnName>(void) {
        %if FcnSubsystemIsAsycnTopSS(fcnCallSys)
          %<SLibDumpOutputUpdateCodeForAsyncTid(fcnCallSys.CurrentTID)>
        %elseif LibIsSystemField(fcnCallSys,"CallerBlkIdx")
          %assign callerBlkIdx = LibGetSystemField(fcnCallSys,"CallerBlkIdx")
          %if callerBlkIdx[0] > 0
            %assign sfcnBlk = System[callerBlkIdx[0]].Block[callerBlkIdx[2]]
            %<LibBlockExecuteFcnCall(sfcnBlock, portEl)>
          %else
            %<SLibCallFCSS(sysIdx,csIdx,NumSystems-1,portEl,tidVal,0,"OutputUpdate")>
          %endif
        %else
          %<SLibCallFCSS(sysIdx,csIdx,NumSystems-1,portEl,tidVal,0,"OutputUpdate")>
        %endif
      }
      %assign sysFcnPrototype = sysFcnPrototype + ...
        "%<LibExternInFcnDecls()>void %<fcnName>(void);/n"
    %endforeach
    %closefile tmpBuffer
    %if !SLibGenSubsysFcnAsClassMemFcn(::CompiledModel.System[sysIdx])
      %assign fileSysIdx = ::CompiledModel.System[sysIdx].FileNameOwnerIdx
      %assign fileOwner = ::CompiledModel.System[fileSysIdx]
      %<LibAddToSystemField(fileOwner, "SystemFcnPrototype", sysFcnPrototype)>
    %else
      %% When in generating subsystem funcitons as C++ member function mode,
      %% system function prototoype cannot be put in the file owner subsystem, as they will
      %% need to be put into root_model.h
      %<LibAddToSystemField(::CompiledModel.System[sysIdx], "EncapSystemFcnPrototype", sysFcnPrototype)>
    %endif
  %endif
 
  %return tmpBuffer
%endfunction %% SLibGenerateISRStubs
 
%%Function:FcnGenerateFNIStubsForFcn=============================================================
%%Abstract:
%%ThisfunctioniscalledbySLibGetBodyOutputUpdateFcnCachein
%%commonbodlib.tlcinordertogeneratethefunctioncallstubswitha
%%FNI(forcednon-inlined)compatibleinterface.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%
%function FcnGenerateFNIStubsForFcn(fcnCallSys, fcnType) void
  %assign tmpBuffer = ""
  %assign sysFcnPrototype = ""
 
  %if LibIsSystemField(fcnCallSys, "NumFNI%<fcnType>CallSites")
    %assign NumFNICallSites = ...
      LibGetSystemField(fcnCallSys, "NumFNI%<fcnType>CallSites")
    %assign FNICallSite = ...
      LibGetSystemField(fcnCallSys, "FNI%<fcnType>CallSite")
    %openfile tmpBuffer
    %foreach idx=NumFNICallSites
      %assign fcnName = FNICallSite[idx][0]
      %assign sysIdx = FNICallSite[idx][1]
      %assign csIdx = FNICallSite[idx][2]
      %assign portEl = FNICallSite[idx][3]
      %assign tidVal = FNICallSite[idx][4]
      %assign blkSysIdx = FNICallSite[idx][5]
      %assign blkIdx = FNICallSite[idx][6]
      %assign emitted = FNICallSite[idx][7]
      %assign isRateGroupedSLFInAccel = Accelerator ...
        && fcnCallSys.IsRateGroupedSLFcn == TLC_TRUE && fcnType == "OutputUpdate"
      %if isRateGroupedSLFInAccel
        %% Rate grouped Simulink functions exist in the root module. So need to
        %% get the FcnInfo from root.
        %assign rateGroupedSLFSystem = System[NumSystems-1]
        %assign fcnInfo = LibGetFcnInfo(rateGroupedSLFSystem, "Output", fcnCallSys.CurrentTID)
      %else
        %assign fcnInfo = ...
          LibGetFcnInfo(fcnCallSys, fcnType, fcnCallSys.CurrentTID)
      %endif
      %assign cgirName = fcnInfo.CGIRName
      %assign calleeSystem = ::CompiledModel.System[sysIdx]
      %assign callSite = calleeSystem.CallSites[csIdx]
      %assign ssBlock = ::CompiledModel.System[callSite[2]].Block[callSite[3]]
      %assign sfcnBlock = ::CompiledModel.System[blkSysIdx].Block[blkIdx]
      %assign modIdx = ::CompiledModel.RTWCGModules.NumRTWCGModules-1
      %assign fcnIdx = ::CompiledModel.RTWCGModules.TestInterfaceFcnIdx
      %assign argVec = []
 
      %if emitted == 1
        %continue
      %else
        %assign FNICallSite[idx][7] = 1
        %<LibSetSystemField(fcnCallSys, "FNI%<fcnType>CallSite", FNICallSite)>
      %endif
 
      %with sfcnBlock
        %if SLibTLCSystemFcnCallExists(fcnType, sysIdx, csIdx, modIdx, fcnIdx)
          %assign callInfo = ...
            SLibTLCSystemFcnCallInfo(fcnType, sysIdx, csIdx, modIdx, fcnIdx)
          %assign argVec = callInfo.Args
          %assign cgirName = callInfo.Name
        %endif
      %endwith
 
      %assign locSS = RTMGetModelSS()
      %assign argDefs = ::tSimStructType + " *const " + locSS
      %assign rtmUnused = 1
      %assign cpiUnused = 0
      %assign tidUnused = 0
      %if SLibAutosarCompilerAbstractionRequired()
        %assign dataDef = SLibAutosarCompilerAbstractionForDataDecl(...
          TLC_FALSE, "int_T", TLC_FALSE, TLC_FALSE, ::tControlPortIdx, ...
          "DataAutomatic")
        %assign argDefs = argDefs + ", " + dataDef
      %else
        %assign argDefs = argDefs + ", int_T " + ::tControlPortIdx
      %endif
      %if !LibSystemFcnNeedsCPI(fcnCallSys, fcnType)
        %assign cpiUnused = 1
      %endif
 
      %% If the system function doesn't have TID, then add it to the
      %% stub since the stub has an expected interface including the TID
      %if SLibAutosarCompilerAbstractionRequired()
        %assign dataDef = SLibAutosarCompilerAbstractionForDataDecl(...
          TLC_FALSE, "int_T", TLC_FALSE, TLC_FALSE, ::tTID, "DataAutomatic")
        %assign argDefs = argDefs + ", " + dataDef
      %else
        %assign argDefs = argDefs + ", int_T " + ::tTID
      %endif
      %if !LibSystemFcnNeedsTID(fcnCallSys, fcnType)
        %assign tidUnused = 1
      %endif
 
      %%
      %% To avoid warnings, use a different name for the
      %% rtModel in the function declaration than in the
      %% function body.
      %%
      %if GenRTModel
        %assign rtm = " *%<locSS>"
        %assign lowerrtm = " *rtm"
        %assign lowerArgDefs = FEVAL("strrep", argDefs, rtm, lowerrtm)
      %else
        %assign lowerArgDefs = argDefs
      %endif
 
      /*
       * Forced non-inlined (FNI) function call stub
       * for '%<ssBlock.Name>'
       */
      %% Model Reference must supply boolean return argument to satisfy
      %% fcnCallSys macro
      %assign retArg = "boolean_T"
      %<SLibIfSystemVariantCondition(fcnCallSys)>
      %<retArg> %<fcnName>(%<argDefs>) {
        %% Make the smarts for whether or not to call the initialize
        %% function based on state reset here, so the caller (e.g. Stateflow
        %% or rt_EnableSys can be blissfully and generically unaware of it
        %% (at runtime)
 
        %assign fcnCode = ""
        %openfile fcnCode
        %assign callerSfcnBlk = ""
        %if LibIsSystemField(fcnCallSys,"CallerBlkIdx")
          %assign callerBlkIdx = LibGetSystemField(fcnCallSys,"CallerBlkIdx")
          %if callerBlkIdx[0] > 0
            %assign callerSfcnBlk = System[callerBlkIdx[0]].Block[callerBlkIdx[2]]
            %assign callerSfcnBlkEl = LibGetSystemField(fcnCallSys,"CallerBlkPortEl")
          %endif
        %endif
 
        %if !ISEMPTY(callerSfcnBlk) && ...
          callerSfcnBlk.NumSFcnSysOutputCallDsts > 1
          %% If this callerSfcnBlk has multiple destination, checking the emptyness of
          %% this one destination system is not sufficient. In this case, be conservative,
          %% assume at least one destination subsystems is not empty.
          %assign systemFcnIsEmpty = TLC_FALSE
        %else
          %if fcnType == "OutputUpdate" || ...
            fcnType == "Output" || fcnType == "Update"
            %if isRateGroupedSLFInAccel
              %% Sometimes the CurrentTID for root is not set. We should
              %% set it to the passed in TID (tidVal) in order to ensure
              %% we are looking at the right Output function in root when
              %% we call LibSystemFcnIsEmptyForTID.
              %assign oldTidVal = rateGroupedSLFSystem.CurrentTID
              %assign rateGroupedSLFSystem.CurrentTID = tidVal
              %assign systemFcnIsEmpty = ...
              LibSystemFcnIsEmptyForTID(rateGroupedSLFSystem, fcnType)
              %assign rateGroupedSLFSystem.CurrentTID = oldTidVal
            %else
              %assign systemFcnIsEmpty = ...
                LibSystemFcnIsEmptyForTID(fcnCallSys, fcnType)
            %endif
          %else
            %assign systemFcnIsEmpty = ...
              LibSystemFcnIsEmpty(fcnCallSys, fcnType)
          %endif
        %endif
        %%
 
        %if IsModelReferenceSimTarget() && (fcnType == "Enable")
          %% The Enable Function must call the Initialize function because
          %% simulation doesn't cache away the Initialize function pointer
          %if !LibSystemFcnIsEmpty(fcnCallSys, "SystemReset")
            %if !ISEMPTY(callerSfcnBlk)
              %foreach fcIdx = callerSfcnBlk.NumSFcnSysOutputCallDsts
                %assign blockToCall = ...
                  sfcnBlock.SFcnSystemOutputCall[fcIdx].BlockToCall
                %assign calledBlock = ...
                  ::CompiledModel.System[blockToCall[0]].Block[blockToCall]
                %with sfcnBlock
                  %assign initFNI = LibGetFcnSystemResetFNI(calledBlock,0,tidVal)
                %endwith
                %assign rtmUnused = 0
                %<initFNI>(%<locSS>, %<::tTID>, %<::tControlPortIdx>);
              %endforeach
            %else
              %with sfcnBlock
                %assign initFNI = LibGetFcnSystemResetFNI(ssBlock,portEl,tidVal)
              %endwith
              %assign rtmUnused = 0
              %<initFNI>(%<locSS>, %<::tTID>, %<::tControlPortIdx>);
            %endif
          %endif
        %endif
        %assign initiateFcnCall = !systemFcnIsEmpty && ...
          (fcnType != "SystemReset" || fcnCallSys.TriggerBlkReset)
        %if initiateFcnCall
          %if isRateGroupedSLFInAccel
            %assign calleeModIdx = rateGroupedSLFSystem.CGIRModuleIdx
          %else
            %assign calleeModIdx = calleeSystem.CGIRModuleIdx
          %endif
          %assign calleeModule = ...
            ::CompiledModel.RTWCGModules.RTWCGModule[calleeModIdx]
          %if ISFIELD(calleeModule, "SystemFunctions") && ...
            ISFIELD(calleeModule.SystemFunctions, cgirName)
            %assign fcnIndex = GETFIELD(calleeModule.SystemFunctions, cgirName)
            %assign calleeFcn = calleeModule.Function[fcnIndex]
 
            %foreach argIdx=calleeFcn.NumArgs
              %if calleeFcn.ArgAccessed[argIdx] > 0
                %assign idNum = SLibSafeIDNUM(calleeFcn.ArgSource, argIdx)
                %assign argSrc = idNum[0]
                %switch argSrc
                  %case "RTM"
                    %%if GenRTModel
                    %%assign argVec[argIdx] = "rtm"
                    %%else
                    %assign argVec[argIdx] = locSS
                    %%endif
                    %if calleeSystem.CrossNoArgFcnBound == 0
                      %assign rtmUnused = 0
                    %endif
                    %break
                  %case "CPI"
                    %assign argVec[argIdx] = ::tControlPortIdx
                    %if calleeSystem.CrossNoArgFcnBound == 0
                      %assign cpiUnused = 0
                    %endif
                    %break
                  %case "TID"
                    %assign argVec[argIdx] = ::tTID
                    %if calleeSystem.CrossNoArgFcnBound == 0
                      %assign tidUnused = 0
                    %endif
                    %break
                  %default
                    %break
                %endswitch
              %endif %% !calleeFcn.ArgAccessed[argIdx]
            %endforeach %% argIdx=calleeFcn.NumArgs
          %endif %% ISFIELD(calleeModule, "SystemFunctions")
 
          %if FcnSubsystemIsAsycnTopSS(fcnCallSys) && fcnType == "OutputUpdate"
            %<SLibDumpOutputUpdateCodeForAsyncTid(fcnCallSys.CurrentTID)>
          %elseif !ISEMPTY(callerSfcnBlk)
            %<SLibBlockExecuteSysFcn(callerSfcnBlk, callerSfcnBlkEl, fcnType)>
          %else
            %assign addArgs = FcnGetAdditionalArgs(cgirName, argVec, ...
              fcnType, sysIdx, ::CompiledModel.NumSystems-1, csIdx, TLC_FALSE, TLC_FALSE)
            %if !WHITE_SPACE(fcnInfo.CommonArgs) && !WHITE_SPACE(addArgs)
              %assign addArgs = ", " + addArgs
            %endif
            %if !EXISTS(callInfo.OpeningTraceComment)
            %<fcnInfo.Name>(%<fcnInfo.CommonArgs>%<addArgs>);
            %else
              %% add traceability comment to the function call site
              %<callInfo.OpeningTraceComment>%<fcnInfo.Name>%<callInfo.ClosingTraceComment>(%<fcnInfo.CommonArgs>%<addArgs>);
 
          %endif
 
 
 
        %endif
        %endif
 
        %if 1 == rtmUnused
          %<SLibUnusedParameter(locSS)>
        %endif
        %if 1 == cpiUnused
          %<SLibUnusedParameter(::tControlPortIdx)>
        %endif
        %if 1 == tidUnused
          %<SLibUnusedParameter(::tTID)>
        %endif
        %closefile fcnCode
        %<fcnCode>
        return (1);
      }
      %<SLibEndIfSystemVariantCondition(fcnCallSys)>
      %assign sysFcnPrototype = sysFcnPrototype + ...
        "%<LibExternInFcnDecls()>%<retArg> %<fcnName>(%<lowerArgDefs>);/n"
    %endforeach
    %closefile tmpBuffer
 
    %if !SLibGenSubsysFcnAsClassMemFcn(::CompiledModel.System[sysIdx])
      %assign fileSysIdx = ::CompiledModel.System[sysIdx].FileNameOwnerIdx
      %assign fileOwner = ::CompiledModel.System[fileSysIdx]
      %<LibAddToSystemField(fileOwner, "SystemFcnPrototype", sysFcnPrototype)>
    %else
      %% When in generating subsystem funcitons as C++ member function mode,
      %% system function prototoype cannot be put in the file owner subsystem, as they will
      %% need to be put into root_model.h
      %<LibAddToSystemField(::CompiledModel.System[sysIdx], "EncapSystemFcnPrototype", sysFcnPrototype)>
    %endif
  %endif
 
  %return tmpBuffer
%endfunction %% end: FcnGenerateFNIStubsForFcn
 
%%Function:SLibGenerateFNIStubs==================================================================
%%Abstract:
%%ThisfunctioniscalledbySLibGetBodyOutputUpdateFcnCachein
%%commonbodlib.tlcinordertogeneratethefunctioncallstubswitha
%%FNI(forcednon-inlined)compatibleinterface.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibGenerateFNIStubs(fcnCallSys) void
  %openfile tmpBuf
  %<FcnGenerateFNIStubsForFcn(fcnCallSys, "OutputUpdate")>/
  %<FcnGenerateFNIStubsForFcn(fcnCallSys, "SystemReset")>/
  %<FcnGenerateFNIStubsForFcn(fcnCallSys, "Enable")>/
  %<FcnGenerateFNIStubsForFcn(fcnCallSys, "Disable")>/
  %closefile tmpBuf
  %return tmpBuf
%endfunction
 
%%Function:SLibGetFcnEventType===================================================================
%%Abstract:
%%ThisfunctioniscalledbyLibGetFcnCallISRandLibGetFcnCallFNI.It
%%attachesadditionalinformationtothesysteminstancerecodethatis
%%usedtogeneratetogeneratethefunctioncallstubs.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%
%function SLibGetFcnEventType(fcnCallDst, portEl, tidVal, fcnCallType, fcnType) void
  %if fcnCallDst.Type == "SubSystem"
    %with fcnCallDst
      %assign bType = (Type == "SubSystem") ? "Subsystem" : ""
      %assign sysIdx = LibBlockParamSetting(bType, "SystemIdx")
    %endwith
 
    %assign csIdx = fcnCallDst.CallSiteIdx
    %assign fcnCallSys = ::CompiledModel.System[sysIdx]
    %if ISFIELD(fcnCallSys, "%<fcnType>Fcn")
      %assign fcnName = fcnCallSys.%<fcnType>Fcn + fcnCallType
      %assign fieldName = fcnCallType + fcnType + "CallSite"
      %assign numFieldName = "Num" + fcnCallType + fcnType + "CallSites"
 
      %if csIdx > 0 || portEl > 0
        %assign fcnName = fcnName + "_%<csIdx>_%<portEl>"
      %endif
 
      %assign thisSytemIdx = BlockIdx[0]
      %assign thisBlockIdx = BlockIdx[2]
 
      %assign callSite = [%<fcnName>, %<sysIdx>, %<csIdx>, ...
        %<portEl>, %<tidVal>, %<thisSytemIdx>, %<thisBlockIdx>, 0]
      %if !LibIsSystemField(fcnCallSys, numFieldName)
        %assign callSite = Matrix (1,8) [[%<callSite>];]
        %<LibAddToSystem(fcnCallSys, numFieldName, 1)>
        %<LibAddToSystem(fcnCallSys, fieldName, callSite)>
      %else
        %assign fcnExists = 0
        %assign numFields = LibGetSystemField(fcnCallSys, numFieldName)
        %assign fieldValue = LibGetSystemField(fcnCallSys, fieldName)
        %foreach idx=numFields
          %if fieldValue[idx][0] == fcnName
            %assign fcnExists = 1
            %break
          %endif
        %endforeach
        %if !fcnExists
          %<LibAddToSystemField(fcnCallSys, numFieldName, 1)>
          %<LibAddToSystemField(fcnCallSys, fieldName, callSite)>
        %endif
      %endif
      %return fcnName
    %else
      %return ""
    %endif
  %else
    %assert fcnCallDst.Type == "ModelReference"
 
    %% Check that this is being called from the right scope so we can
    %% correctly get the right fcn-call input on the Model block.
    %if !EXISTS(FcnPortIdx)
      %if fcnType == "OutputUpdate"
        %assign tlcFcnName = "LibGetFcnCall%<fcnCallType>"
      %else
        %assign tlcFcnName = "LibGetFcn%<fcnType>%<fcnCallType>"
      %endif
      %<SLibReportErrorWithIdAndArgs("RTW:tlc:SFcnSystemOutputCallOutOfScope", tlcFcnName)>
    %endif
 
    %assign fcnName = ""
    %if FcnPortIdx >= fcnCallDst.NumDataInputPorts && fcnType == "OutputUpdate" && ...
      ISFIELD(fcnCallDst.ParamSettings, "ModelEventPortNames")
      %assign eventPortIdx = FcnPortIdx - fcnCallDst.NumDataInputPorts
      %assign eventPortName = fcnCallDst.ParamSettings.ModelEventPortNames[eventPortIdx]
      %assign fcnName = "%<fcnCallDst.ParamSettings.ReferencedModelName>_%<fcnCallDst.Identifier>_%<eventPortName>_w"
      %assign TID = SLibGetFcnCallDstTID(fcnCallDst, FcnPortIdx)
      %assign isAsync = TLC_TRUE
      %assign groupIndex = -1
    %else
      %assign fcnCallInfo = SLibGetModelBlockFcnCallInputInfo(fcnCallDst, FcnPortIdx, fcnType)
      %if !ISEMPTY(fcnCallInfo)
        %assign fcnName = "%<fcnCallInfo.TaskName>_w"
        %assign TID = SLibGetFcnCallDstTID(fcnCallDst, FcnPortIdx)
        %assign isAsync = fcnCallInfo.isAsync
        %assign groupIndex = fcnCallInfo.FcnCallPortGroupIndex
      %endif
    %endif
 
    %if !ISEMPTY(fcnName)
      %if !ISFIELD(fcnCallDst, "WrapperFcns")
        %addtorecord fcnCallDst WrapperFcns {}
      %endif
      %addtorecord fcnCallDst.WrapperFcns %<fcnType> ...
        {FcnName fcnName; ...
         FcnPortIdx FcnPortIdx; ...
         TID TID; ...
         isAsync isAsync; ...
         FcnCallPortGroupIndex groupIndex}
    %endif
 
    %return fcnName
  %endif
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tmMultiRateAsyncTask_VC1.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tMdlRefWithFcnOnDataAsVSSChoice.m
%%
%function SLibGetFcnCallDstTID(dstBlock, dstPort)
  %if dstBlock.Type == "SubSystem"
    %return LibGetSubsystemBlkTIDForTask(dstBlock, TLC_TRUE)
  %else
    %assert dstBlock.Type == "ModelReference"
    %with dstBlock
      %if EXISTS("InputPortTIDs")
        %assign tid = InputPortTIDs[dstPort]
      %else
        %assign tid = TID
      %endif
    %endwith
 
    %return tid
  %endif
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibBlockExecuteFcnCall=================
%%Abstract:
%%ForusebyinlinedS-Functionstocallfcn-callsystemoutputfunction.
%%Returnsastringtoeithercallfunction-callsubsystemoutputfunction
%%withtheappropriatenumberofargumentsorthegeneratethesubsystemoutput
%%coderightthere(inlined).
%%
%%Example:
%%%foreachcallIdx=NumSFcnSysOutputCallDsts
%%%ifLibIsEqual(SFcnSystemOutputCall[callIdx].BlockToCall,"unconnected")
%%%continue
%%%endif
%%%%callthedownstreamsystem
%%%<LibBlockExecuteFcnCall(block,callIdx)>/
%%%endforeach
%%
%%ConsiderusingthisfunctiontoreplaceLibBlockExecuteFcnCallandLibCallFCSS.
%%ThesetwofunctionarealsousedbyinlineS-Functionwithfunctioncalloutput
%%function.However,LibExecuteFcnCallandLibCallFCSSworksonlyiffcn-call
%%doesn'tbranch,can'thandlefcn-callbranches.LibBlockExecuteFcnCallworksfor
%%bothcases
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tMdlRefWithFcnOnDataAsVSSChoice.m
%%
%function LibBlockExecuteFcnCall(sfcnBlock, callIdx) void
  %% Get the starting index of corresponding SFcnSystemOutputCall record first
  %% e.g.
  %% 'sfcnBlock' outputs 3 elements
  %% The 1st element calls 2 function-call destinations: {'AAA', 'BBB'}
  %% The 2nd element is unconnected: {'unconnected'}
  %% The 3rd element calls 3 function-call destinations: {'CCC', 'DDD', 'EEE'}
  %%
  %% Then it has a flat list of 'SFcnSystemOutputCall' records:
  %% SFcnSystemOutputCall[0] --> 'AAA'
  %% SFcnSystemOutputCall[1] --> 'BBB'
  %% SFcnSystemOutputCall[2] --> 'unconnected'
  %% SFcnSystemOutputCall[3] --> 'CCC'
  %% SFcnSystemOutputCall[4] --> 'DDD'
  %% SFcnSystemOutputCall[5] --> 'EEE'
  %%
  %% The 'SFcnSystemOutputCallMappingInfo' has 3 records, each mapped to one
  %% output element of 'sfcnBlock':
  %% SFcnSystemOutputCallMappingInfo[0].StartingIdx = 0
  %% SFcnSystemOutputCallMappingInfo[0].NumOfCalledFC = 2
  %% SFcnSystemOutputCallMappingInfo[1].StartingIdx = 2
  %% SFcnSystemOutputCallMappingInfo[1].NumOfCalledFC = 1
  %% SFcnSystemOutputCallMappingInfo[2].StartingIdx = 3
  %% SFcnSystemOutputCallMappingInfo[2].NumOfCalledFC = 3
  %%
  %% When passing a 'callIdx' of 2, we should be able to get the starting
  %% index in the list of 'SFcnSystemOutputCall' records, which is 3.
  %assign recIdx = sfcnBlock.SFcnSystemOutputCallMappingInfo[callIdx].StartingIdx
 
  %% Using the example shown above, given the starting index of 3, we should
  %% be able to get the first function-call destination block, which is 'CCC'.
  %assign dstSSBlk = LibGetFcnCallBlock(sfcnBlock, recIdx)
 
  %if LibIsEqual(dstSSBlk, "")
    %return "" %% Do nothing if the function-call signal is not connected
  %endif
  %with sfcnBlock
    %assign tidVal = ParamSettings.SampleTimesToSet[0][1]
    %% Get called block's function-call input port element index
    %assign fcInpPortEl = SFcnSystemOutputCall[recIdx].FcnPortElement
    %% Get number of called blocks
    %assign nCalledFC = SFcnSystemOutputCallMappingInfo[callIdx].NumOfCalledFC
    %assign dstBlkTid = SLibGetFcnCallDstTID(dstSSBlk, ...
      SFcnSystemOutputCall[recIdx].FcnPortIdx)
  %endwith
 
  %if FcnBlkIsAsyncTopSfcn(sfcnBlock)
    %assert !IsModelReferenceTarget()
    %% Output element of the S-function block
    %assign sfcnOutputEl = sfcnBlock.SFcnSystemOutputCall[recIdx].OutputElement
    %assign tidFromSfcnBlk = FcnGetAsyncTidFromSfcnBlk(sfcnBlock, sfcnOutputEl)
 
    %assert LibAsynchronousTriggeredTID(tidFromSfcnBlk)
    %assert LibAsynchronousTriggeredTID(dstBlkTid)
 
    %openfile codeForAsyncTid
    %if !ISFIELD(sfcnBlock, "GenCodeForTopAsyncSS")
      %addtorecord sfcnBlock GenCodeForTopAsyncSS TLC_FALSE
    %endif
    %if sfcnBlock.GenCodeForTopAsyncSS
      %% Second time parse the async sfcn TLC file.
      %if tidFromSfcnBlk == dstBlkTid
         %% If the sfcn block is the top sfcn of the rate, the sfcn
         %% will be reponsible to generate task entry fcn. Get the
         %% code that is rate grouped with the async rate at root level
         %% so that code can be dumped in task entry fcn.
         {
           %if SLibIsMappedSystemInDeploymentDiagram(sfcnBlock.BlkSysIdx)
             %assign ssIdx = sfcnBlock.BlkSysIdx
             %<SLibDumpOutputUpdateCodeForAsyncTidInSS(ssIdx, dstBlkTid)>
           %else
             %<SLibDumpOutputUpdateCodeForAsyncTid(dstBlkTid)>
           %endif
         }
      %else
        %% If the sfcn block is not the tops sfcn of the rate,
        %% call task entry fcn for the rate. This sfcn block is
        %% no repsonsible to generate the function body.
        %%
        %<RTWCGBlockExecuteAsyncEntryFcn(fcInpPortEl, dstBlkTid)>
      %endif
    %else
      %% First time parse the async sfcn TLC file.
      %% Generate code body. The code will be rate grouped
      %% in parent system.
      %<SLibExecuteFcnCallGeneralHelper(sfcnBlock, recIdx, nCalledFC, tidVal)>
    %endif
    %closefile codeForAsyncTid
    %return codeForAsyncTid
  %else
    %openfile retBuf
    %if !ISEQUAL(sfcnBlock.TID, dstBlkTid) && LibAsynchronousTriggeredTID(dstBlkTid)
      %% Destination block has different sample time and it is a union sample time.
      %% Call the task entry fcn of the union sample time.
      %% %assert Sampletime[dstBlkTid].IsUnionTs == "yes"
      %<RTWCGBlockExecuteAsyncEntryFcn(fcInpPortEl, dstBlkTid)>
    %else
      %<SLibExecuteFcnCallGeneralHelper(sfcnBlock, recIdx, nCalledFC, tidVal)>
    %endif
    %closefile retBuf
    %return retBuf
  %endif
%endfunction %% end: LibBlockExecuteFcnCall
 
%%DocFunction{OtherUsefulFunctions}:LibBlockExecuteFcnEnable=================
%%Abstract:
%%ForusebyinlinedS-Functionstocallfcn-callsystemenablefunction.
%%Returnsastringtoeithercallfunction-callsubsystemenablefunction
%%withtheappropriatenumberofargumentsorthegeneratethesubsystemenable
%%coderightthere(inlined).
%%
%%Example:
%%%foreachcallIdx=NumSFcnSysOutputCallDsts
%%%ifLibIsEqual(SFcnSystemOutputCall[callIdx].BlockToCall,"unconnected")
%%%continue
%%%endif
%%%%callthedownstreamsystem
%%%<LibBlockExecuteFcnEnable(block,callIdx)>/
%%%endforeach
%%
%%ConsiderusingthisfunctiontoreplaceLibBlockExecuteFcnEnableandLibEnableFCSS.
%%ThesetwofunctionarealsousedbyinlineS-Functionwithfunctioncallenable
%%function.However,LibExecuteFcnEnableandLibEnableFCSSworksonlyiffcn-call
%%doesn'tbranch,can'thandlefcn-callbranches.LibBlockExecuteFcnEnableworksfor
%%bothcases
%%
%function LibBlockExecuteFcnEnable(sfcnBlock, callIdx)
  %return SLibBlockExecuteFcnEnableDisableHelper(sfcnBlock, callIdx, TLC_TRUE)
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibBlockExecuteFcnDisable=================
%%Abstract:
%%ForusebyinlinedS-Functionstocallfcn-callsystemdisablefunction.
%%Returnsastringtoeithercallfunction-callsubsystemdisablefunction
%%withtheappropriatenumberofargumentsorthegeneratethesubsystemdisable
%%coderightthere(inlined).
%%
%%Example:
%%%foreachcallIdx=NumSFcnSysOutputCallDsts
%%%ifLibIsEqual(SFcnSystemOutputCall[callIdx].BlockToCall,"unconnected")
%%%continue
%%%endif
%%%%callthedownstreamsystem
%%%<LibBlockExecuteFcnDisable(block,callIdx)>/
%%%endforeach
%%
%%ConsiderusingthisfunctiontoreplaceLibBlockExecuteFcnDisableandLibDisableFCSS.
%%ThesetwofunctionarealsousedbyinlineS-Functionwithfunctioncalldisable
%%function.However,LibExecuteFcnDisableandLibDisableFCSSworksonlyiffcn-call
%%doesn'tbranch,can'thandlefcn-callbranches.LibBlockExecuteFcnDisableworksfor
%%bothcases
%%
%function LibBlockExecuteFcnDisable(sfcnBlock, callIdx)
  %return SLibBlockExecuteFcnEnableDisableHelper(sfcnBlock, callIdx, TLC_FALSE)
%endfunction
 
%%SLibBlockExecuteFcnEnableDisableHelper======================================
%%Abstract:
%%HelperfunctionforLibBlockExecuteFcnEnable&LibBlockExecuteFcnDisable
%%WhenenableFcn==TLC_TRUE,generateenablefunction;otherwise,generate
%%disablefunction.
%function SLibBlockExecuteFcnEnableDisableHelper(sfcnBlock, callIdx, enableFcn)
  %openfile retBuf
  %assign recIdx = sfcnBlock.SFcnSystemOutputCallMappingInfo[callIdx].StartingIdx
  %assign nCalledFC = sfcnBlock.SFcnSystemOutputCallMappingInfo[callIdx].NumOfCalledFC
 
  %foreach fcIdx = nCalledFC
    %assign dstSSBlk = LibGetFcnCallBlock(sfcnBlock, recIdx)
 
    %if !LibIsEqual(dstSSBlk, "") %% Ignore unconnected function-call signal
      %with sfcnBlock
        %assign tidVal = ParamSettings.SampleTimesToSet[0][1]
        %assign fcInpPortEl = SFcnSystemOutputCall[recIdx].FcnPortElement
        %assign fcInpPortIdx = SFcnSystemOutputCall[recIdx].FcnPortIdx
      %endwith
 
      %if enableFcn == TLC_TRUE %% Generate enable function
        %<SLibExecuteFcnEnableHelper(dstSSBlk, fcInpPortEl, fcInpPortIdx, tidVal,TLC_FALSE)>
      %else %% Generate disable function
        %<SLibExecuteFcnDisableHelper(dstSSBlk, fcInpPortEl, fcInpPortIdx, tidVal,TLC_FALSE)>
      %endif
    %endif
 
    %assign recIdx = recIdx + 1 %% Update the record index
  %endforeach
  %closefile retBuf
 
  %return retBuf
%endfunction
 
%function SLibBlockExecuteFcnInit(sfcnBlock, callIdx)
  %with sfcnBlock
    %assign recIdx = SFcnSystemOutputCallMappingInfo[callIdx].StartingIdx
    %assign nCalledFC = SFcnSystemOutputCallMappingInfo[callIdx].NumOfCalledFC
    %assign tidVal = ParamSettings.SampleTimesToSet[0][1]
    %assign portEl = SFcnSystemOutputCall[recIdx].FcnPortElement
  %endwith
 
  %openfile retBuf
  %foreach fcIdx = nCalledFC
    %assign dstSSBlk = LibGetFcnCallBlock(sfcnBlock, recIdx)
 
    %if !LibIsEqual(dstSSBlk, "") %% Ignore unconnected function-call signal
      %<SLibExecuteFcnInitHelper(dstSSBlk, portEl, tidVal,TLC_FALSE)>
    %endif
 
    %assign recIdx = recIdx + 1 %% Update the record index
  %endforeach
  %closefile retBuf
 
  %return retBuf
%endfunction
 
%function SLibBlockExecuteSysFcn(sfcnBloc, callIdx, fcnType)
  %openfile retBuf
  %switch(fcnType)
    %case "OutputUpdate"
      %<LibBlockExecuteFcnCall(sfcnBloc, callIdx)>
      %break
    %case "Initialize"
      %<SLibBlockExecuteFcnInit(sfcnBloc, callIdx)>
      %break
    %case "Enable"
      %<LibBlockExecuteFcnEnable(sfcnBloc, callIdx)>
      %break
    %case "Disable"
      %<LibBlockExecuteFcnDisable(sfcnBloc, callIdx)>
      %break
    %default
      %<SLibReportErrorWithIdAndArgs("RTW:tlc:InvalidFcnType", fcnType)>
      %break
  %endswitch
  %closefile retBuf
 
  %return retBuf
%endfunction
 
 
%function SLibReportObsoleteFcnCallAPI(OldFcnName, NewFcnName, system)
  %<SLibReportErrorWithIdAndArgs("RTW:tlc:ObsoleteFcnCall", ...
    ["%<OldFcnName>", "%<system.Name>", "%<NewFcnName>"])>
%endfunction
 
%function GetInstanceIndexOfModelBlock(modelBlkId)
    %%if the current block is model reference Compiled model should have
    %%model reference field
    %assert ISFIELD(::CompiledModel,"ModelReferenceBlocks")
    %assign mdlRefBlks = ::CompiledModel.ModelReferenceBlocks
 
    %% get all model blocks instances and
    %% find current model block instance
    %foreach rowIdx = SIZE(mdlRefBlks,0)
       %assign mdlRefInfo = mdlRefBlks[rowIdx]
       %assign bIdx = mdlRefInfo[1]
       %if bIdx == modelBlkId
           %return mdlRefInfo[2]
       %endif
    %endforeach
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%
%function SLibExecuteFcnCallGeneralHelper(sFcnBlock, recStartingIdx, nCalledFC, tidVal) void
  %assign recIdx = recStartingIdx
  %openfile buffer
  %foreach fcIdx = nCalledFC
    %assign blockToCall = sFcnBlock.SFcnSystemOutputCall[recIdx].BlockToCall
    %assign sysIdx = blockToCall[0]
    %assign blkIdx = blockToCall[1]
    %assign calledBlock = ::CompiledModel.System[sysIdx].Block[blkIdx]
    %with sFcnBlock
      %% Get called block's function-call input port element index
      %assign fcInpPortEl = SFcnSystemOutputCall[recIdx].FcnPortElement
      %assign fcPortIdx = SFcnSystemOutputCall[recIdx].FcnPortIdx
      %assign subsysFcnCall = SLibExecuteFcnCallHelper(calledBlock, fcInpPortEl, ...
        fcPortIdx, tidVal, TLC_FALSE)
    %endwith
 
    %if (calledBlock.Type == "ModelReference")
        %% TopTester: test/toolbox/simulink/variants/tVariantGecks8.m -testspec:TestPoint_vssWithExpFcnMdl1
        %assign instIdx = GetInstanceIndexOfModelBlock(blkIdx)
        %assign vcRecord = SLibMdlRefNetInlineVariantPreprocessorCondition(sysIdx, instIdx, blkIdx)
        %assign ifCond = vcRecord.ifCond
        %assign endIfCond = vcRecord.endIfCond
        %<SLibWrapBody(ifCond, subsysFcnCall, endIfCond)>
    %else
        %<SLibWrapSystemVariantCondition(calledBlock, subsysFcnCall)>
    %endif
 
 
    %assign recIdx = recIdx + 1 %% Update the record index
  %endforeach
  %closefile buffer
  %return buffer
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tMdlRefWithFcnOnDataAsVSSChoice.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%
%function SLibExecuteFcnCallHelper(fcnCallDstBlock, portEl, portIdx, tidVal,checkUsage) void
  %assign isSubsystem = (fcnCallDstBlock.Type == "SubSystem")
 
  %if isSubsystem
    %with fcnCallDstBlock
      %assign bType = (Type == "SubSystem") ? "Subsystem" : ""
      %assign sysIdx = LibBlockParamSetting(bType, "SystemIdx")
    %endwith
 
    %if checkUsage && ISFIELD(System[sysIdx],"IsBranchedSys")
      %<SLibReportObsoleteFcnCallAPI("LibExecuteFcnCall","LibBlockExecuteFcnCall",System[sysIdx])>
    %endif
 
    %if checkUsage && FcnSubsystemIsAsycnTopSS(System[sysIdx])
      %assign ssBlkTid = LibGetSubsystemBlkTIDForTask(fcnCallDstBlock, TLC_TRUE)
      %assert LibAsynchronousTriggeredTID(ssBlkTid)
      %assign topAsyncSfcn = FcnGetTaskTopSfcnBlock(ssBlkTid)
      %if ISEMPTY(topAsyncSfcn)
        %% If the sfcn block is not the tops sfcn of the rate,
        %% call task entry fcn for the rate. This sfcn block is
        %% no repsonsible to generate the function body.
        %%
        %<RTWCGBlockExecuteAsyncEntryFcn(portEl,ssBlkTid)>
      %else
        %assign el = SampleTime[ssBlkTid].AsyncSfcnBlkElm
        %return LibBlockExecuteFcnCall(topAsyncSfcn,el)
      %endif
    %else
      %assign csIdx = fcnCallDstBlock.CallSiteIdx
      %assign cs = System[sysIdx].CallSites[csIdx]
      %assign accessSysIdx = System[cs[0]].HStructDeclSystemIdx
      %assign fciCont = SLibIsFcnCallerContinuous(tidVal)
      %return SLibCallFCSS(sysIdx, csIdx, accessSysIdx, ...
         portEl, tidVal, fciCont, "OutputUpdate")
    %endif
  %else
    %assert (fcnCallDstBlock.Type == "ModelReference")
    %if checkUsage && (portIdx == -1)
      %<SLibReportObsoleteFcnCallAPI("LibExecuteFcnCall", ...
        "LibBlockExecuteFcnCall", fcnCallDstBlock)>
    %endif
 
    %with System[fcnCallDstBlock.BlockIdx[0]]
      %with fcnCallDstBlock
        %return CallModelBlockAsyncFcnCallInput(fcnCallDstBlock, portIdx, tidVal, ...
          "OutputUpdate")
      %endwith
    %endwith
  %endif
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibExecuteFcnCall======================
%%Abstract:
%%ForusebyinlinedS-Functionswithfunctioncalloutputs.Returnsa
%%stringtoeithercallfunction-callsubsystemwiththeappropriatenumber
%%ofargumentsorthegeneratethesubsystem'scoderightthere(inlined).
%%
%%Example:
%%%foreachfcnCallIdx=NumSFcnSysOutputCallDsts
%%%%callthedownstreamsystem
%%%withSFcnSystemOutputCall[fcnCallIdx]
%%%%skipunconnectedfunctioncalloutputs
%%%ifISEQUAL(BlockToCall,"unconnected")
%%%continue
%%%endif
%%%assignsysIdx=BlockToCall[0]
%%%assignblkIdx=BlockToCall[1]
%%%assignssBlock=System[sysIdx].Block[blkIdx]
%%%<LibExecuteFcnCall(ssBlock,FcnPortElement,...
%%ParamSettings.SampleTimesToSet[0][1])>/
%%%endwith
%%%endforeach
%%
%%BlockToCallandFcnPortElementareelementsoftheSFcnSystemOutputCall
%%record.
%%
%function LibExecuteFcnCall(ssBlock, portEl, tidVal) void
  %return SLibExecuteFcnCallHelper(ssBlock, portEl, -1, tidVal,TLC_TRUE)
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%
%function SLibExecuteFcnEnableHelper(fcnCallBlock, portEl, fcnPort, tidVal,checkUsage)
  %assign isSubsystem = (fcnCallBlock.Type == "SubSystem")
 
  %if isSubsystem
    %with fcnCallBlock
      %assign bType = (Type == "SubSystem") ? "Subsystem" : ""
      %assign sysIdx = LibBlockParamSetting(bType, "SystemIdx")
    %endwith
 
    %if checkUsage && ISFIELD(System[sysIdx],"IsBranchedSys")
      %<SLibReportObsoleteFcnCallAPI("LibExecuteFcnEnable","LibBlockExecuteFcnEnable",System[sysIdx])>
    %endif
 
    %assign csIdx = fcnCallBlock.CallSiteIdx
    %assign cs = System[sysIdx].CallSites[csIdx]
    %assign accessSysIdx = System[cs[0]].HStructDeclSystemIdx
    %assign fciCont = SLibIsFcnCallerContinuous(tidVal)
    %openfile tmpBuf
    %with fcnCallBlock
      %assign bType = (Type == "SubSystem") ? "Subsystem" : ""
      %assign swe = LibBlockParamSetting(bType, "StatesWhenEnabling")
    %endwith
 
    %if swe == "reset"
      %openfile initBuffer
      %<SLibCallFCSS(sysIdx, csIdx, accessSysIdx, ...
         portEl, tidVal, fciCont, "SystemReset")>
      %closefile initBuffer
      %if !WHITE_SPACE(initBuffer)
        %if ProtectCallInitFcnTwice
          /* protect against calling initialize function twice at startup */
          if (!(%<LibIsFirstInitCond()>)) {
            %<initBuffer>/
          }
        %else
          %<initBuffer>/
        %endif
      %endif
    %endif
    %<SLibCallFCSS(sysIdx, csIdx, accessSysIdx, ...
       portEl, tidVal, fciCont, "Enable")>
    %closefile tmpBuf
    %return tmpBuf
  %else
    %if checkUsage && (fcnPort == -1)
      %<SLibReportObsoleteFcnCallAPI("LibExecuteFcnEnable","LibBlockExecuteFcnEnable", fcnCallBlock)>
    %endif
    %with System[fcnCallBlock.BlockIdx[0]]
      %with fcnCallBlock
        %assign retBuf = CallModelBlockAsyncFcnCallInput(fcnCallBlock, fcnPort, tidVal, "Enable")
      %endwith
    %endwith
  %endif
  %return retBuf
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibExecuteFcnEnable===================
%%Abstract:
%%ForusebyinlinedS-Functionswithfunctioncalloutputs.Returnsa
%%stringtoeithercallfunction-callsubsystemwiththeappropriatenumber
%%ofargumentsorthegeneratethesubsystem'scoderightthere(inlined).
%%
%%Example:
%%%foreachfcnCallIdx=NumSFcnSysOutputCallDsts
%%%%callthedownstreamsystem
%%%withSFcnSystemOutputCall[fcnCallIdx]
%%%%skipunconnectedfunctioncalloutputs
%%%ifISEQUAL(BlockToCall,"unconnected")
%%%continue
%%%endif
%%%assignsysIdx=BlockToCall[0]
%%%assignblkIdx=BlockToCall[1]
%%%assignssBlock=System[sysIdx].Block[blkIdx]
%%%<LibExecuteFcnCall(ssBlock,FcnPortElement,...
%%ParamSettings.SampleTimesToSet[0][1])>/
%%%endwith
%%%endforeach
%%
%%BlockToCallandFcnPortElementareelementsoftheSFcnSystemOutputCall
%%record.
%%
%function LibExecuteFcnEnable(ssBlock, portEl, tidVal) void
  %return SLibExecuteFcnEnableHelper(ssBlock, portEl, -1, tidVal,TLC_TRUE)
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%
%function SLibExecuteFcnDisableHelper(fcnCallBlock, portEl, fcnPort, tidVal,checkUsage)
  %assign isSubsystem = (fcnCallBlock.Type == "SubSystem")
 
  %if isSubsystem
    %with fcnCallBlock
      %assign bType = (Type == "SubSystem") ? "Subsystem" : ""
      %assign sysIdx = LibBlockParamSetting(bType, "SystemIdx")
    %endwith
 
    %if checkUsage && ISFIELD(System[sysIdx],"IsBranchedSys")
      %<SLibReportObsoleteFcnCallAPI("LibExecuteFcnDisable","LibBlockExecuteFcnDisable",System[sysIdx])>
    %endif
 
    %assign csIdx = fcnCallBlock.CallSiteIdx
    %assign cs = System[sysIdx].CallSites[csIdx]
    %assign accessSysIdx = System[cs[0]].HStructDeclSystemIdx
    %assign fciCont = SLibIsFcnCallerContinuous(tidVal)
    %openfile tmpBuf
    %<SLibCallFCSS(sysIdx, csIdx, accessSysIdx, ...
       portEl, tidVal, fciCont, "Disable")>
    %closefile tmpBuf
    %return tmpBuf
  %else
    %if checkUsage && (fcnPort == -1)
      %<SLibReportObsoleteFcnCallAPI("LibExecuteFcnDisable","LibBlockExecuteFcnDisable",fcnCallBlock)>
    %endif
    %with System[fcnCallBlock.BlockIdx[0]]
      %with fcnCallBlock
        %assign retBuf = CallModelBlockAsyncFcnCallInput(fcnCallBlock, fcnPort, tidVal, "Disable")
      %endwith
    %endwith
  %endif
  %return retBuf
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibExecuteFcnDisable===================
%%Abstract:
%%ForusebyinlinedS-Functionswithfunctioncalloutputs.Returnsa
%%stringtoeithercallfunction-callsubsystemwiththeappropriatenumber
%%ofargumentsorthegeneratethesubsystem'scoderightthere(inlined).
%%
%%Example:
%%%foreachfcnCallIdx=NumSFcnSysOutputCallDsts
%%%%callthedownstreamsystem
%%%withSFcnSystemOutputCall[fcnCallIdx]
%%%%skipunconnectedfunctioncalloutputs
%%%ifISEQUAL(BlockToCall,"unconnected")
%%%continue
%%%endif
%%%assignsysIdx=BlockToCall[0]
%%%assignblkIdx=BlockToCall[1]
%%%assignssBlock=System[sysIdx].Block[blkIdx]
%%%<LibExecuteFcnCall(ssBlock,FcnPortElement,...
%%ParamSettings.SampleTimesToSet[0][1])>/
%%%endwith
%%%endforeach
%%
%%BlockToCallandFcnPortElementareelementsoftheSFcnSystemOutputCall
%%record.
%%
%function LibExecuteFcnDisable(ssBlock, portEl, tidVal) void
  %return SLibExecuteFcnDisableHelper(ssBlock, portEl, -1, tidVal,TLC_TRUE)
%endfunction
 
 
%function SLibExecuteFcnInitHelper(ssBlock, portEl, tidVal,checkUsage)
  %with ssBlock
    %assign bType = (Type == "SubSystem") ? "Subsystem" : ""
    %assign sysIdx = LibBlockParamSetting(bType, "SystemIdx")
  %endwith
 
  %assert !(checkUsage && ISFIELD(System[sysIdx],"IsBranchedSys"))
 
  %assign csIdx = ssBlock.CallSiteIdx
  %assign cs = System[sysIdx].CallSites[csIdx]
  %assign accessSysIdx = System[cs[0]].HStructDeclSystemIdx
  %assign fciCont = SLibIsFcnCallerContinuous(tidVal)
  %openfile tmpBuf
  %<SLibCallFCSS(sysIdx, csIdx, accessSysIdx, ...
     portEl, tidVal, fciCont, "Initialize")>
  %closefile tmpBuf
  %return tmpBuf
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibCallFCSS============================
%%Abstract:
%%ForusebyinlinedS-Functionswithfunctioncalloutputs.Returnsa
%%stringtoeithercallfunction-callsubsystemwiththeappropriatenumber
%%ofargumentsorthegeneratethesubsystem'scoderightthere(inlined).
%%
%%Note:
%%UsedbyinlinedS-functionstomakeafunction-call,LibCallFCSS
%%returnsthecalltothefunction-callsubsystemwiththeappropriate
%%numberofargumentsortheinlinedcode.AnS-functioncanexecute
%%afunction-callsubsystemonlyviaitsfirstoutputport.
%%
%%SeetheSFcnSystemOutputCallrecordinthemodel.rtwfile.
%%
%%Thereturnstringisdeterminedbythecurrentcodeformat.
%%
%%Example:
%%%foreachfcnCallIdx=NumSFcnSysOutputCallDsts
%%%%callthedownstreamsystem
%%%withSFcnSystemOutputCall[fcnCallIdx]
%%%%skipunconnectedfunctioncalloutputs
%%%ifISEQUAL(BlockToCall,"unconnected")
%%%continue
%%%endif
%%%assignsysIdx=BlockToCall[0]
%%%assignblkIdx=BlockToCall[1]
%%%assignssBlock=System[sysIdx].Block[blkIdx]
%%%assignsysToCall=System[ssBlock.ParamSettings.SystemIdx]
%%%<LibCallFCSS(sysToCall,tSimStruct,FcnPortElement,...
%%ParamSettings.SampleTimesToSet[0][1])>/
%%%endwith
%%%endforeach
%%
%%BlockToCallandFcnPortElementareelementsoftheSFcnSystemOutputCall
%%record.
%%
%%Systemisarecordwithintheglobal::CompiledModelrecord.
%%
%function LibCallFCSS(system, simObject, portEl, tidVal) void
  %assign sysIdx = system.SystemIdx
  %if !EXISTS("BlockToCall")
    %if EXISTS("SFcnSystemOutputCall")
      %assign BlockToCall = SFcnSystemOutputCall[0].BlockToCall
    %else
      %<SLibReportErrorWithIdAndArgs("RTW:tlc:IncorrectLibFcnCall", "LibCallFCSS")>
    %endif
  %endif
  %if ISFIELD(System[sysIdx],"IsBranchedSys")
    %<SLibReportObsoleteFcnCallAPI("LibCallFCSS","LibBlockExecuteFcnCall",system)>
  %endif
 
  %if FcnSubsystemIsAsycnTopSS(system)
    %assign sysTid = LibGetSubsystemTID(system, TLC_TRUE)
    %assert LibAsynchronousTriggeredTID(sysTid)
    %assign topAsyncSfcn = FcnGetTaskTopSfcnBlock(sysTid)
    %if ISEMPTY(topAsyncSfcn)
      %% If the sfcn block is not the tops sfcn of the rate,
      %% call task entry fcn for the rate. This sfcn block is
      %% no repsonsible to generate the function body.
      %%
      %return RTWCGBlockExecuteAsyncEntryFcn(portEl,sysTid)
    %else
      %assign el = SampleTime[sysTid].AsyncSfcnBlkElm
      %return LibBlockExecuteFcnCall(topAsyncSfcn,el)
    %endif
  %else
    %assign ssBlock = System[BlockToCall[0]].Block[BlockToCall[1]]
    %assign csIdx = ssBlock.CallSiteIdx
    %assign cs = system.CallSites[csIdx]
    %assign accessSysIdx = System[cs[0]].HStructDeclSystemIdx
    %assign fciCont = SLibIsFcnCallerContinuous(tidVal)
    %return SLibCallFCSS(sysIdx, csIdx, accessSysIdx, portEl, tidVal, fciCont, "OutputUpdate")
  %endif
%endfunction %% LibCallFCSS
 
%%Function:FcnGenerateOpenFCSSInitialize=========================================================
%%Abstract:
%%Thisfunctiongeneratestheopeningguardaroundcallingtheenable
%%functionforafunction-callsubsystem.IfsetModeistrue,wesetthe
%%specfiedmodetoenabled,otherwisewedonotsetthemodevector.
%%Currently,sinceInitializeiscalledbeforeEnable,Initializedoesnot
%%setthemode,butEnabledoessetthemode.
%%
%function FcnGenerateOpenFCSSInitialize(ssBlock) void
  %with ssBlock
  %assign numModes = ModeVector[0]
  %assign tmpBuffer = ""
  %if numModes > 1
    %openfile tmpBuffer
    CondStates enableState = SUBSYS_DISABLED;
    %foreach mIdx = numModes
      %assign blockMode = LibBlockMode("", "", mIdx)
      if (((CondStates) %<blockMode>) != SUBSYS_DISABLED) {
        enableState = (CondStates) %<blockMode>;
      }
    %endforeach
    if (enableState == SUBSYS_DISABLED) {
    %closefile tmpBuffer
  %endif
  %endwith
  %return tmpBuffer
%endfunction
 
%%Function:FcnGenerateCloseFCSSInitialize========================================================
%%Abstract:
%%Thisfunctiongeneratestheclosingguardaroundcallingtheenable
%%functionforafunction-callsubsystem.
%%
%function FcnGenerateCloseFCSSInitialize(ssBlock) void
  %with ssBlock
  %assign numModes = ModeVector[0]
  %assign tmpBuffer = ""
  %if numModes > 1
    %openfile tmpBuffer
    }
    %closefile tmpBuffer
  %endif
  %endwith
  %return tmpBuffer
%endfunction
 
%%Function:FcnGenerateOpenFCSSEnable=============================================================
%%Abstract:
%%Thisfunctiongeneratestheopeningguardaroundcallingtheenable
%%functionforafunction-callsubsystem.IfsetModeistrue,wesetthe
%%specfiedmodetoenabled,otherwisewedonotsetthemodevector.
%%Currently,sinceInitializeiscalledbeforeEnable,Initializedoesnot
%%setthemode,butEnabledoessetthemode.
%%
%function FcnGenerateOpenFCSSEnable(ssBlock, portEl) void
  %with ssBlock
  %assign numModes = ModeVector[0]
  %assign tmpBuffer = ""
  %if numModes > 1
    %openfile tmpBuffer
    {
      CondStates enableState = SUBSYS_DISABLED;
      %foreach mIdx = numModes
        %assign blockMode = LibBlockMode("", "", mIdx)
        if (((CondStates) %<blockMode>) != SUBSYS_DISABLED) {
          enableState = (CondStates) %<blockMode>;
        }
      %endforeach
      %<LibBlockMode(portEl, "", "")> = SUBSYS_ENABLED;
      if (enableState == SUBSYS_DISABLED) {
    %closefile tmpBuffer
  %elseif numModes == 1
    %openfile tmpBuffer
    %<LibBlockMode(portEl, "", "")> = SUBSYS_ENABLED;
    %closefile tmpBuffer
  %endif
  %endwith
  %return tmpBuffer
%endfunction
 
%%Function:FcnGenerateCloseFCSSEnable============================================================
%%Abstract:
%%Thisfunctiongeneratestheclosingguardaroundcallingtheenable
%%functionforafunction-callsubsystem.
%%
%function FcnGenerateCloseFCSSEnable(ssBlock) void
  %with ssBlock
  %assign numModes = ModeVector[0]
  %assign tmpBuffer = ""
  %if numModes > 1
    %openfile tmpBuffer
      }
    }
    %closefile tmpBuffer
  %endif
  %endwith
  %return tmpBuffer
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibEnableFCSS=========================
%%Abstract:
%%ForusebyinlinedS-Functionswithfunctioncalloutputs.Returnsa
%%stringtoeithercalltheenablemethodforafunction-callsubsystem
%%orgeneratethesubsystem'senablecodeinline(aswellasinitialize
%%codeifthesubsystemresetsstatesonreset).
%%
%%Note:
%%AnS-functioncanexecuteafunction-callsubsystemonlyviaits
%%firstoutputport.
%%
%%SeetheSFcnSystemOutputCallrecordinthemodel.rtwfile.
%%
%%Thereturnstringisdeterminedbythecurrentcodeformat.
%%
%%Example:
%%%foreachfcnCallIdx=NumSFcnSysOutputCallDsts
%%%%callthedownstreamsystem
%%%withSFcnSystemOutputCall[fcnCallIdx]
%%%%skipunconnectedfunctioncalloutputs
%%%ifISEQUAL(BlockToCall,"unconnected")
%%%continue
%%%endif
%%%assignsysIdx=BlockToCall[0]
%%%assignblkIdx=BlockToCall[1]
%%%assignssBlock=System[sysIdx].Block[blkIdx]
%%%assignsysToCall=System[ssBlock.ParamSettings.SystemIdx]
%%%<LibEnableFCSS(sysToCall,tSimStruct,FcnPortElement,...
%%ParamSettings.SampleTimesToSet[0][1])>/
%%%endwith
%%%endforeach
%%
%%BlockToCallandFcnPortElementareelementsoftheSFcnSystemOutputCall
%%record.
%%
%%Systemisarecordwithintheglobal::CompiledModelrecord.
%%
%function LibEnableFCSS(system, simObject, portEl, tidVal) void
  %assign sysIdx = system.SystemIdx
  %if !EXISTS("BlockToCall")
    %if EXISTS("SFcnSystemOutputCall")
      %assign BlockToCall = SFcnSystemOutputCall[0].BlockToCall
    %else
      %<SLibReportErrorWithIdAndArgs("RTW:tlc:IncorrectLibFcnCall", "LibEnableFCSS")>
    %endif
  %endif
  %if ISFIELD(System[sysIdx],"IsBranchedSys")
    %<SLibReportObsoleteFcnCallAPI("LibEnableFCSS","LibBlockExecuteFcnEnable",system)>
  %endif
  %assign ssBlock = System[BlockToCall[0]].Block[BlockToCall[1]]
  %assign csIdx = ssBlock.CallSiteIdx
  %assign cs = system.CallSites[csIdx]
  %assign accessSysIdx = System[cs[0]].HStructDeclSystemIdx
  %assign fciCont = SLibIsFcnCallerContinuous(tidVal)
  %openfile tmpBuf
  %if ssBlock.ParamSettings.StatesWhenEnabling == "reset"
    %openfile initBuffer
    %<SLibCallFCSS(sysIdx, csIdx, accessSysIdx, portEl, tidVal, fciCont, "SystemReset")>
    %closefile initBuffer
    %if !WHITE_SPACE(initBuffer)
      %if ProtectCallInitFcnTwice
        /* protect against calling initialize function twice at startup */
        if (!(%<LibIsFirstInitCond()>)) {
          %<initBuffer>/
        }
      %else
        %<initBuffer>/
      %endif
    %endif
  %endif
  {
    %<SLibCallFCSS(sysIdx, csIdx, accessSysIdx, portEl, tidVal, fciCont, "Enable")>
  }
  %closefile tmpBuf
  %return tmpBuf
%endfunction %% LibEnableFCSS
 
 
%%Function:FcnGenerateOpenFCSSDisable============================================================
%%Abstract:
%%Thisfunctiongeneratestheopeningguardaroundcallingthedisable
%%functionforafunction-callsubsystem.
%%
%function FcnGenerateOpenFCSSDisable(ssBlock, portEl) void
  %with ssBlock
  %assign numModes = ModeVector[0]
  %assign tmpBuffer = ""
  %if numModes > 1
    %openfile tmpBuffer
    {
      CondStates enableState = SUBSYS_DISABLED;
      %<LibBlockMode(portEl, "", "")> = SUBSYS_DISABLED;
      %foreach mIdx = numModes
        %assign blockMode = LibBlockMode("", "", mIdx)
        if (((CondStates) %<blockMode>) != SUBSYS_DISABLED) {
          enableState = (CondStates) %<blockMode>;
        }
      %endforeach
      if (enableState == SUBSYS_DISABLED) {
    %closefile tmpBuffer
  %elseif numModes == 1
    %openfile tmpBuffer
    %<LibBlockMode(portEl, "", "")> = SUBSYS_DISABLED;
    %closefile tmpBuffer
  %endif
  %endwith
  %return tmpBuffer
%endfunction
 
%%Function:FcnGenerateCloseFCSSDisable===========================================================
%%Abstract:
%%Thisfunctiongeneratestheclosingguardaroundcallingthedisable
%%functionforafunction-callsubsystem.
%%
%function FcnGenerateCloseFCSSDisable(ssBlock) void
  %with ssBlock
  %assign numModes = ModeVector[0]
  %assign tmpBuffer = ""
  %if numModes > 1
    %openfile tmpBuffer
      }
    }
    %closefile tmpBuffer
  %endif
  %endwith
  %return tmpBuffer
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibDisableFCSS=========================
%%Abstract:
%%ForusebyinlinedS-Functionswithfunctioncalloutputs.Returnsa
%%stringtoeithercallthedisablemethodforafunction-callsubsystem
%%orgeneratethesubsystem'sdisablecodeinline.
%%
%%Note:
%%AnS-functioncanexecuteafunction-callsubsystemonlyviaits
%%firstoutputport.
%%
%%SeetheSFcnSystemOutputCallrecordinthemodel.rtwfile.
%%
%%Thereturnstringisdeterminedbythecurrentcodeformat.
%%
%%Example:
%%%foreachfcnCallIdx=NumSFcnSysOutputCallDsts
%%%%callthedownstreamsystem
%%%withSFcnSystemOutputCall[fcnCallIdx]
%%%%skipunconnectedfunctioncalloutputs
%%%ifISEQUAL(BlockToCall,"unconnected")
%%%continue
%%%endif
%%%assignsysIdx=BlockToCall[0]
%%%assignblkIdx=BlockToCall[1]
%%%assignssBlock=System[sysIdx].Block[blkIdx]
%%%assignsysToCall=System[ssBlock.ParamSettings.SystemIdx]
%%%<LibDisableFCSS(sysToCall,tSimStruct,FcnPortElement,...
%%ParamSettings.SampleTimesToSet[0][1])>/
%%%endwith
%%%endforeach
%%
%%BlockToCallandFcnPortElementareelementsoftheSFcnSystemOutputCall
%%record.
%%
%%Systemisarecordwithintheglobal::CompiledModelrecord.
%%
%function LibDisableFCSS(system, simObject, portEl, tidVal) void
  %assign sysIdx = system.SystemIdx
  %if !EXISTS("BlockToCall")
    %if EXISTS("SFcnSystemOutputCall")
      %assign BlockToCall = SFcnSystemOutputCall[0].BlockToCall
    %else
      %<SLibReportErrorWithIdAndArgs("RTW:tlc:IncorrectLibFcnCall", "LibDisableFCSS")>
    %endif
  %endif
   %if ISFIELD(System[sysIdx],"IsBranchedSys")
     %<SLibReportObsoleteFcnCallAPI("LibDisableFCSS","LibBlockExecuteFcnDisable",system)>
  %endif
  %assign ssBlock = System[BlockToCall[0]].Block[BlockToCall[1]]
  %assign csIdx = ssBlock.CallSiteIdx
  %assign cs = system.CallSites[csIdx]
  %assign accessSysIdx = System[cs[0]].HStructDeclSystemIdx
  %assign fciCont = SLibIsFcnCallerContinuous(tidVal)
  %openfile tmpBuf
  %<SLibCallFCSS(sysIdx, csIdx, accessSysIdx, portEl, tidVal, fciCont, "Disable")>
  %closefile tmpBuf
  %return tmpBuf
%endfunction %% LibDisableFCSS
 
%%Function:SLibIsFcnCallerContinuous=============================================================
%%Abstract:
%%Thisfunctiondeterminesifcallings-functionblockhasacontinous
%%sampletime.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%
%function SLibIsFcnCallerContinuous (tid)
  %%
  %assign tidVal = %<tid>
  %if TYPE(tidVal) == "Number" && tidVal >= 0
    %assign fciST = ::CompiledModel.SampleTime[tidVal].PeriodAndOffset[0]
    %assign fciOF = ::CompiledModel.SampleTime[tidVal].PeriodAndOffset[1]
    %return (fciST == 0.0 && fciOF == 0.0)
  %else
    %return TLC_FALSE
  %endif
%endfunction
 
%%Function:SLibCallFCSS==========================================================================
%%Abstract:
%%ThisfunctioniscalledbyLibCallFCSSandLibExecuteFcnCall
%%andfriends
%%Iteitherreturnsthegeneratedcodeforinlined
%%orafunctioncalltoanon-inlinedfuctioncallsubsystem.
%%
%%SeeLibCallFCSSandLibExecuteFcnCallforfurtherdocumentation.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1396738_inlined_VC1.m
%%
%function SLibCallFCSS(sysIdx, csIdx, accessSysIdx, portEl, tidVal, fciCont, ...
  callType) void
  %assign fcnCallSys = ::CompiledModel.System[sysIdx]
  %assign accelGuardStart = ""
  %assign accelGuardEnd = ""
 
  %assign fcnCallSys.CurrentTID = FcnGetSubsystemCodeBufTID(fcnCallSys)
 
  %if fciCont && fcnCallSys.RunFcnCallSSInMinorStep == "yes"
    %assign fciCont = 0
    %%
    %% For Simulink accelerator, do not execute function-call subsystem
    %% code when a function-call initiator is continuous (e.g., an async ISR
    %% pseudo source) and we are in the Simulink consistency check stage.
    %%
    %if Accelerator || IsModelReferenceSimTarget ()
      %assign accelGuardStart = "if (!%<RTMSolverAssertCheck()>) {"
      %assign accelGuardEnd = "}"
    %endif
  %endif
 
  %assign inlinedFCSS = LibSystemIsInlined(fcnCallSys)
 
  %% Return nothing if empty
  %if LibSystemFcnIsEmptyForTID(fcnCallSys,callType)
    %assign fcnCallSys.CurrentTID = -1
    %return ""
  %endif
  %%
  %% 1. S-Function always have SimStruct.
  %% 2. RealTime only has SimStruct if it is forced to be a function call
  %% (because it has a non-inlined s-function calling it)
  %% 3. Embedded-C never needs SimStruct.
  %%
  %assign argList = []
  %assign numArgs = 0
  %if Accelerator && LibAsynchronousTriggeredTID(tidVal)
    %% Accelerator does not maintain timing information for
    %% asynchronous tasks, asynchronous task should use
    %% base rate timing information. See g313672
    %assign tidVal = 0
  %endif
  %assign fcnInfo = LibGetFcnInfo(fcnCallSys, callType, fcnCallSys.CurrentTID)
  %if (inlinedFCSS)
    %%
    %if FcnSysNeedAddRTMArg(fcnCallSys, callType)
      %assign simObject = SLibGetSimStruct()
      %if RTMGetModelSS() != simObject
        %assign argList = argList + ...
          "%<::tSimStructType> *const %<RTMGetModelSS()> = %<simObject>"
        %assign numArgs = numArgs + 1
      %endif
    %endif
    %if LibSystemFcnNeedsCPI(fcnCallSys,callType)
      %assign argList = argList + "int_T %<::tControlPortIdx> = %<portEl>"
      %assign numArgs = numArgs + 1
    %endif
    %if LibSystemFcnNeedsTID(fcnCallSys,callType)
      %assign argList = argList + "int_T %<::tTID> = %<tidVal>"
      %assign numArgs = numArgs + 1
    %endif
  %else
    %assign cgirName = fcnInfo.CGIRName
 
    %% Non-inlined FCSS
    %assign calleeModIdx = fcnCallSys.CGIRModuleIdx
    %assign calleeModule = ::CompiledModel.RTWCGModules.RTWCGModule[calleeModIdx]
 
    %assign hasTIDArg = 0
    %assign hasCPIArg = 0
    %assign hasRTMArg = 0
 
    %if ISFIELD(calleeModule, "SystemFunctions") && ...
      ISFIELD(calleeModule.SystemFunctions, cgirName)
      %assign fcnIdx = GETFIELD(calleeModule.SystemFunctions, cgirName)
      %assign calleeFcn = calleeModule.Function[fcnIdx]
      %assign hasTIDArg = calleeFcn.TIDArgIndex > -1
      %assign hasCPIArg = calleeFcn.CPIArgIndex > -1
      %assign hasRTMArg = calleeFcn.SimStructArgIndex > -1
    %endif
 
    %if !hasRTMArg && FcnSysNeedAddRTMArg(fcnCallSys, callType)
      %assign simObject = SLibGetSimStruct()
      %assign argList = argList + "%<simObject>"
      %assign numArgs = numArgs + 1
    %endif
    %if !hasCPIArg && LibSystemFcnNeedsCPI(fcnCallSys, callType)
      %assign argList = argList + "%<portEl>"
      %assign numArgs = numArgs + 1
    %endif
    %if !hasTIDArg && LibSystemFcnNeedsTID(fcnCallSys, callType)
      %assign argList = argList + "%<tidVal>"
      %assign numArgs = numArgs + 1
    %endif
  %endif
  %%
  %assign cgirName = fcnInfo.CGIRName
  %assign fcnCallSysFcn = fcnInfo.Name
  %% Dump the args array to a string
  %assign args = ""
  %%
  %% We first try call a function call subsystem within the given context
  %% (call outputs from outputs).
  %%
  %assign argVec = []
  %assign modIdx = ::CurrentModuleIdx
  %assign fcnIdx = ::CurrentFunctionIdx
  %if SLibTLCSystemFcnCallExists(callType, sysIdx, csIdx, modIdx, fcnIdx)
    %assign callInfo = ...
      SLibTLCSystemFcnCallInfo(callType, sysIdx, csIdx, modIdx, fcnIdx)
    %assign argVec = callInfo.Args
    %assign cgirName = callInfo.Name
  %else
    %%
    %% If the context is unknown, we dispach the function call
    %% to use global argument references.
    %%
    %assign modIdx = ::CompiledModel.RTWCGModules.NumRTWCGModules-1
    %assign fcnIdx = ::CompiledModel.RTWCGModules.TestInterfaceFcnIdx
 
    %if SLibTLCSystemFcnCallExists(callType, sysIdx, csIdx, modIdx, fcnIdx)
      %assign callInfo = ...
        SLibTLCSystemFcnCallInfo(callType, sysIdx, csIdx, modIdx, fcnIdx)
      %assign argVec = callInfo.Args
      %assign cgirName = callInfo.Name
    %endif
  %endif
  %openfile callBuffer
  %if inlinedFCSS
    %assign needBrace = (numArgs > 0)
    %if (needBrace > 0)
      {
    %endif
    %if (numArgs > 0)
      %foreach argIdx = numArgs
        %;
      %endforeach
    %endif
    %assign fcnCache = "SLibGetBody%<callType>FcnCache"
    %assign fcnCacheBuf = %<fcnCache>(fcnCallSys)
    %if fciCont
      if (%<RTMIs("MajorTimeStep")>) {
      %<fcnCacheBuf>
      }
    %else
      %<accelGuardStart>
      %<fcnCacheBuf>
      %<accelGuardEnd>
    %endif
    %if (needBrace > 0)
      }
    %endif
  %else
    %assign comma = ""
    %if (numArgs > 0)
      %foreach argIdx = numArgs
        %assign args = args + comma + argList[argIdx]
        %assign comma = ", "
      %endforeach
    %endif
    %assign addArgs = FcnGetAdditionalArgs(cgirName, argVec, callType, ...
      sysIdx, accessSysIdx, csIdx, TLC_FALSE, TLC_FALSE)
    %if !WHITE_SPACE(addArgs)
      %assign args = args + comma + addArgs
    %endif
 
    %if fciCont
      if (%<RTMIs("MajorTimeStep")>) {
        %if !EXISTS(callInfo.OpeningTraceComment)
      %<fcnCallSysFcn>(%<args>);
        %else
          %% add traceability comment to the function call site
          %<callInfo.OpeningTraceComment>%<fcnCallSysFcn>%<callInfo.ClosingTraceComment>(%<args>);
        %endif
      }
    %else
      %<accelGuardStart>
      %if !EXISTS(callInfo.OpeningTraceComment)
      %<fcnCallSysFcn>(%<args>);
      %else
        %% add traceability comment to the function call site
        %<callInfo.OpeningTraceComment>%<fcnCallSysFcn>%<callInfo.ClosingTraceComment>(%<args>);
      %endif
      %<accelGuardEnd>
    %endif
  %endif %% inlinedFCSS
  %closefile callBuffer
  %assign fcnCallSys.CurrentTID = -1
  %if !WHITE_SPACE(callBuffer)
    %return callBuffer
  %else
    %return ""
  %endif
%endfunction %% SLibCallFCSS
 
%<LibAddToCompiledModel("LibTID01Eq_Seen", 0)>
%%Function:LibTID01Eq============================================================================
%%Abstract:
%%Return1ifTID0and1areequivalenttasks,otherwisereturn0.
%%
%%Note:Thisfunctionisleftforbackwardcompatibilityonly.Use
%%::CompiledModel.FixedStepOpts.TID01EQinsteadofthis
%%function.Thisfunctionmayproduceincorrectresultsdue
%%toround-offerrors.
%%
%function LibTID01Eq() void
  %if !LibTID01Eq_Seen
    %assign ::CompiledModel.LibTID01Eq_Seen = 1
    %<SLibReportWarningWithId("RTW:tlc:DetectLibTID01Eq")>
  %endif
  %if NumSynchronousSampleTimes > 1
    %assign periodTID0 = SampleTime[0].PeriodAndOffset[0]
    %assign periodTID1 = SampleTime[1].PeriodAndOffset[0]
    %assign stepSize = FixedStepOpts.FixedStep
    %if periodTID0 == 0.0 && (stepSize == periodTID1)
      %return 1
    %endif
  %endif
  %return 0
%endfunction
 
%with ::CompiledModel
%assign RootSystemTasks = []
%foreach tidIdx = NumRuntimeExportedRates
  %assign RootSystemTasks = RootSystemTasks + tidIdx
%endforeach
%assign ::CompiledModel = ::CompiledModel + RootSystemTasks
%endwith
 
%%Function:LibSystemTasks========================================================================
%%Abstract:
%%LibSystemTasksreturnsavectorcontainingthesubsystem'sTIDs.
%%
%%Note,forconvenience,themodeltasksaregroupinavectornamed
%%RootSystemTasksandattachedto::CompiledModel
%%
%function LibSystemTasks(system) void
  %if system.Type == "root"
    %return ::CompiledModel.RootSystemTasks
  %endif
  %assign sysIdx = system.CallSites[0][2]
  %assign blkIdx = system.CallSites[0][3]
  %assign ssBlock = ::CompiledModel.System[sysIdx].Block[blkIdx]
  %if TYPE(ssBlock.SubsystemTID) == "Vector"
    %return ssBlock.SubsystemTID
  %else
    %return [%<ssBlock.SubsystemTID>]
  %endif
%endfunction
 
%%Function:LibTasksEqual=========================================================================
%%Abstract:
%%Determineifallspecifiedtasksareequal(i.e.havethesameTID)
%%
%%Arguments:
%%taskVector:VectorofTIDs
%%
%%
%function LibTasksEqual(taskVector) void
  %assign task = taskVector[0]
  %foreach idx = SIZE(taskVector, 1) - 1
    %if !ISEQUAL(taskVector[idx+1], task)
      %return 0
    %endif
  %endforeach
  %return 1
%endfunction
 
%%Function:LibIsSingleRateSystem=================================================================
%%Abstract:
%%LibIsSingleRateSystemreturnsoneifthesystemisasinglerate
%%system,andzerootherwise.
%%
%%Thesystemparamsettingforsinglerateisusedtodetermineresult.Notethat
%%modelwideeventssuchasparametersampletimearenotfactoredintothe
%%setting
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function LibIsSingleRateSystem(system) void
  %if system.Type == "root"
    %assign sr = ::CompiledModel.SingleRate
  %else
    %assign sysIdx = system.CallSites[0][2]
    %assign blkIdx = system.CallSites[0][3]
    %with ::CompiledModel.System[sysIdx].Block[blkIdx]
      %assign bType = (Type == "SubSystem") ? "Subsystem" : ""
      %assign sr = LibBlockParamSetting(bType, "SingleRate")
    %endwith
  %endif
  %if sr == "yes"
    %return 1
  %else
    %return 0
  %endif
%endfunction
 
%%Function:LibIsRateTransitionBlock==============================================================
%%Abstract:
%%LibIsRateTransitionBlockreturnsoneifablockisbeingusedasarate
%%transitionandzerootherwise.Thebuild-inunitdelayandzoh
%%blockcanberatetransitionblocks.S-functionblockscanalso
%%beratetransitionblocksiftheyspecifytheSS_OPTIONtodoso.
%%
%function LibIsRateTransitionBlock(system, block)
  %if !LibIsSingleRateSystem(system) && SIZE(TID,1) == 1 && ...
    EXISTS("SampleTimeIdx")
    %if (TID != SampleTimeIdx)
      %return 1
    %endif
  %endif
  %return 0
%endfunction
 
 
%%Function:FcnERTIsSampleHitInMain===============================================================
%%Abstract
%%CalledbyFcnGenerateTidGuardOpenCodeInMainforERTcodeformat.
%%
%%NOTE:ThisfunctionissimilartoFcnERTIsSampleHitfunctionexceptforthe
%%MajorTimeStepcheck(sincethiscodewillbeinmain.c)
%function FcnERTIsSampleHitInMain(tid) void
  %assert SLibIsERTCodeFormat() && !IsModelReferenceTarget()
  %if LibAsynchronousTriggeredTID(tid) && GenRTModel
    %% Generated code allways rate group async task
    %% code. LibIsSampleHit(asyncTid) is not neccessary
    %% for async code. It always returns true
    %return "1"
  %endif
  %if !SLibSingleTasking()
    %% Multitasking
    %if Tid01Eq && ISEQUAL(tid,1)
      %if SLibIsPeriodicRateGrouping()
        %return "1"
      %else
        %return "%<LibTID()> == 0"
      %endif
    %else
      %return "%<LibTID()> == %<tid>"
    %endif
  %elseif ISEQUAL(tid,0)
    %% Singletasking and tid==0; base rate always runs
    %return "1"
  %elseif NumContStates > 0
    %% Singletasking, need task counter
    %if RTMTaskCountersIsReqFcn()
      %assign taskCountStr = RTMGet("TaskCounters") + "." + ...
        SLibERTMultiRateCounterField(tid) + " == 0"
      %return "%<taskCountStr>"
    %else
      %return "1"
    %endif
  %elseif Tid01Eq && ISEQUAL(tid,1)
    %return "1"
  %else
    %% Otherwise
    %if RTMTaskCountersIsReqFcn()
      %return RTMGet("TaskCounters") + "." + ...
        SLibERTMultiRateCounterField(tid) + ...
        " == 0"
    %else
      %return "1"
    %endif
  %endif
%endfunction
 
 
%%Function:FcnERTsSampleHit======================================================================
%%Abstract
%%CalledbyLibIsSampleHitforERTcodeformat.Nottobecalldirectly.
%%TopTester:test/toolbox/simulink/blocks/lib_Discrete/DiscreteTimeIntegrator/rtw/tdintegrt.m
%%TopTester:test/toolbox/simulink/variants/tMdlrefToVSS.m
%%TopTester:test/toolbox/simulink/blocks/CPPCodeGen/tsmlk_core_cpp_coverage.m
%%TopTester:test/toolbox/simulink/variants/tTypesToPrivate.m
%%
%function FcnERTIsSampleHit(tid) void
  %assign modIdx = ::CurrentModuleIdx
  %if modIdx > -1
    %assign thisModule = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
    %assign thisSystem = ::CompiledModel.System[thisModule.CGSystemIdx]
    %if LibIsSingleRateSystem(thisSystem)
      %return "1"
    %endif
  %endif
 
  %% Export Function does not need local tid as each entry point is explicitly
  %% scheduled. g1735899
  %if !SLibSingleTasking() && !SLibIsExportFcnDiagram()
    %% Multitasking
    %if Tid01Eq && ISEQUAL(tid,1)
      %if NumContStates > 0 || IsModelReferenceTarget()
        %if SLibIsPeriodicRateGrouping()
          %return "%<RTMIs("MajorTimeStep")>"
        %else
          %return "%<RTMIs("MajorTimeStep")> && /n" + "%<LibTID()> == 0"
        %endif
      %else
        %if SLibIsPeriodicRateGrouping()
          %return "1"
        %else
          %return "%<LibTID()> == 0"
        %endif
      %endif
    %else
      %return "%<LibTID()> == %<tid>"
    %endif
  %elseif ISEQUAL(tid,0)
    %% Singletasking and tid==0; base rate always runs
    %return "1"
  %elseif IsModelReferenceTarget()
    %assert ::CompiledModel.NumRuntimeExportedRates > 1
    %assert TYPE(tid) == "Number" && tid > 0
    %assign ans = ""
    %if Tid01Eq && ISEQUAL(tid,1)
      %assert LibIsContinuous(0)
      %assign ans = "%<RTMIs("MajorTimeStep")>"
    %else
      %if LibIsContinuous(0)
        %assign ans = "%<RTMIs("MajorTimeStep")> && "
      %endif
      %assign ans = "%<ans>%<RTMIsSampleHit(tid)>"
    %endif
    %return ans
  %elseif NumContStates > 0
    %% Singletasking, need MajorStepGuard + task counter
    %if RTMTaskCountersIsReqFcn()
      %assign taskCountStr = RTMGet("TaskCounters") + "." + ...
        SLibERTMultiRateCounterField(tid) + " == 0"
      %return "%<RTMIs("MajorTimeStep")> &&/n" + "%<taskCountStr>"
    %else
      %return "%<RTMIs("MajorTimeStep")>"
    %endif
  %elseif Tid01Eq && ISEQUAL(tid,1)
    %return "1"
  %else
    %% Otherwise
    %if RTMTaskCountersIsReqFcn()
      %return RTMGet("TaskCounters") + "." + ...
        SLibERTMultiRateCounterField(tid) + ...
        " == 0"
    %else
      %return "1"
    %endif
  %endif
%endfunction
 
%%Function:LibIsSampleHit========================================================================
%%Abstract:
%%LibIsSampleHitreturnstheappropriateTIDscopegiventhatthetidis
%%
%%Discrete:ssIsSampleHit(S,%<tid>,tid)
%%Continuous:ssIsContinuousTask(S,tid)
%%
%%ThisfunctioncannotbecalledwithaTIDthatisneither
%%discretenorcontinuous.
%%
%%S-functionblocksshouldnotusethisfunctiondirectly.Theyshould
%%insteaduseLibIsSFcnSampleHit().
%%
%%Arguments:
%%tid:Globalintegertaskidentifier(TID)ofblock
%%or
%%tid:Stringindicatingthatyouareaccessingdiscretetasks
%%usinganindexingarray.Thisformisusefulwhenlooping
%%overthesampletimes.StringindexingforERTcodeformat
%%issuppliedforbackwardscompatibility,however,results
%%ininefficientcode.
%%
%%Returns:
%%Non-ERTcodeformats:
%%
%%Oneofthefollowingsamplehitmacros:
%%
%%rtmIsSampleHit(S,%<tid>,tid)foradiscreteTID
%%rtmIsContinuousTask(S,tid)foracontinuousTID
%%
%%ERTcodeformat:
%%
%%Appropriatetidcheck(e.g.,tid==0)
%%
%%TopTester:test/toolbox/simulink/blocks/CPPCodeGen/tsmlk_core_cpp_coverage.m
%%TopTester:test/toolbox/simulink/variants/tTypesToPrivate.m
%%TopTester:test/toolbox/simulink/variants/tMdlrefToVSS.m
%%TopTester:test/toolbox/simulink/blocks/lib_Discrete/DiscreteTimeIntegrator/rtw/tdintegrt.m
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%
%function LibIsSampleHit(tid) void
  %% See Also:
  %% LibIsSFcnSampleHit
  %%
  %if LibAsynchronousTriggeredTID(tid) && GenRTModel
    %% Generated code allways rate group async task
    %% code. LibIsSampleHit(asyncTid) is not neccessary
    %% for async code. It always returns true
    %return "1"
  %endif
  %if TYPE(tid) == "String"
    %if LibTriggeredTID(tid) || tid == "constant"
      %<SLibReportErrorWithIdAndArgs("RTW:tlc:InvalidTID", tid)>
    %endif
    %if SLibIsERTCodeFormat()
      %return FcnERTIsSampleHit(tid)
    %else
      %return RTMIsSampleHit(tid)
    %endif
  %else
    %if TYPE(tid) == "Number" && tid < 0
      %<SLibReportErrorWithIdAndArgs("RTW:tlc:InvalidTID", tid)>
    %endif
    %if SLibIsERTCodeFormat()
      %return FcnERTIsSampleHit(tid)
    %endif
    %assign period = ::CompiledModel.SampleTime[tid].PeriodAndOffset[0]
    %assign offset = ::CompiledModel.SampleTime[tid].PeriodAndOffset[1]
    %if period == 0.0 && offset == 0.0
      %return RTMIsContinuousTask()
    %else
      %return RTMIsSampleHit(tid)
    %endif
  %endif
%endfunction %% LibIsSampleHit
 
 
%%Function:LibIsSpecialSampleHit=================================================================
%%Abstract:
%%LibIsSpecialSampleHitreturnstheappropriatespecialsamplehitmacro.
%%
%%S-functionblocksshouldnotusethisfunctiondirectly.Theyshould
%%insteaduseLibIsSFcnSpecialSampleHit().
%%(SeetheSimulinkCoderdocumentationformore
%%informationaboutmulti-taskingmodels.)
%%
%%Arguments:
%%sti:Sampletimeindexofblock(onlyrelevantforZero-OrderHoldand
%%UnitDelayblocks).Thesampletimeindexistheindexofthe
%%slowersampletime.
%%tid:taskidentifier(TID)ofblock.TheTIDistheindexofthetask
%%withthefastersampletime.
%%
%%Returns:
%%Non-ERT:rtmIsSpecialSampleHit(rtM,a,b,tid)
%%ERT:Appropriaterateinteractionflag
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/exportFcns/tExportFcnsWithInlineVariants.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%
%function LibIsSpecialSampleHit(sti, tid) void
  %% See Also:
  %% LibIsSFcnSpecialSampleHit
  %%
  %if SLibIsERTCodeFormat()
    %if SLibSingleTasking()
      %assign ::CompiledModel.RequireMultiRateSampleHits = 1
      %return LibIsSampleHit(%<sti>)
    %else
      %<SLibSetNeedRateInteraction(sti,tid)>
      %if IsModelReferenceTarget()
        %assign returnVal = RTMIsSpecialSampleHit(%<sti>, %<tid>)
      %elseif SuppressMultiTaskScheduler || ...
        (UseTargetTaskScheduler() && !SLibSingleTasking())
        %assign returnVal = ...
          "%<RTMGet("PerTaskSampleHits") + "." + ...
          SLibERTMultiRateTimingField(sti,tid)> == 1"
        %% Base system update need maintain SpecialSampleHit flags
        %assign baseSystem = System[GetBaseSystemIdx()]
        %<SLibAccessThisSysFcnArgHelper(baseSystem.Interface.RTMArgDef,"Update","",tid, TLC_TRUE)>
      %else
        %assign returnVal = ...
          "%<RTMGet("PerTaskSampleHits") + "." + ...
          SLibERTMultiRateTimingField(sti,tid)>"
      %endif
      %if (NumContStates > 0) && ISEQUAL(%<tid>, 0)
        %assign returnVal = "%<RTMIs("MajorTimeStep")>" + " && " + returnVal
      %endif
      %return returnVal
    %endif
  %else
    %return RTMIsSpecialSampleHit(%<sti>, %<tid>)
  %endif
%endfunction
 
%<LibAddToCompiledModel("BlockInstanceDataCache", 0)>
%%Function:LibGenerateBlockInstanceData==========================================================
%%Abstract:
%%LibCacheBlockInstanceDatageneratesthedataallocationcodefor
%%eachblockinaSimulinksystem.Thisfunctionupdates
%%theglobalvariable,::CompiledModel.BlockInstanceDataCache.
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function LibCacheBlockInstanceData() void
  %assign rootSystem = System[NumSystems-1]
  %openfile buffer
  %with rootSystem
    %foreach blkIdx = NumBlocks
      %openfile tmpBuffer
      %<GENERATE(Block[blkIdx], "BlockInstanceData", rootSystem)>/
      %closefile tmpBuffer
      %if WHITE_SPACE(tmpBuffer) == 0
        {
          %<tmpBuffer>/
        }
      %endif
    %endforeach
  %endwith
  %closefile buffer
  %assign ::CompiledModel.BlockInstanceDataCache = buffer
%endfunction
 
%%Function:LibBlockInstanceDataIsEmpty===========================================================
%%Abstract:
%%LibBlockInstanceDataIsEmptydeterminesifthereisanyblockinstance
%%dataforthismodel.Itreturnsoneifthecacheisonlywhitespace
%%andzerootherwise.
%%
%%Returns:
%%1if::CompiledModel.BlockInstanceDataCacheisonlywhitespace
%%0otherwise
%%
%function LibBlockInstanceDataIsEmpty() void
  %<LibTrapCacheAssert(BlockInstanceDataCache)>
  %return WHITE_SPACE(BlockInstanceDataCache)
%endfunction
 
%%Function:LibDumpBlockInstanceData==============================================================
%%Abstract:
%%LibDumpBlockInstanceDataoutputsthecurrentblockinstancedata
%%cachetotheoutputbuffer.Thedatacachethatisoutputis
%%storedin::CompiledModel.BlockInstanceDataCache.
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function LibDumpBlockInstanceData() Output
  %<LibTrapCacheAssert(BlockInstanceDataCache)>
  %if !WHITE_SPACE(BlockInstanceDataCache)
 
    /* block instance data */
    %<BlockInstanceDataCache>
  %endif
  %<SLibResetTLCGlobal("BlockInstanceDataCache")>/
%endfunction
 
 
%%------------------------------%
%%Endoffunctionlibrarycode%
%%------------------------------%
 
%%Function:SLibSetSkipInitializationFlag=========================================================
%%Abstract:
%%Lowlevelfunctionusedbydiscreteintegratorandunit-delayblockto
%%avoidre-initializingmemorytozero.Thisfunctioniscalledin
%%BlockInstanceSetup.Whentheparameterisscalar,initialization
%%requirementsaredeterminedupfront(once).Ifthereisnoinitial
%%valueparameter,callthisfunctionwith[]fortheparam.
%%TopTester:test/toolbox/simulink/blocks/CPPCodeGen/tsmlk_core_cpp_coverage.m
%%
%function SLibSetSkipInitializationFlag(system,block,param) void
  %if ISEMPTY(param)
    %<SETFIELD(block, "SkipInitialization", ...
      !SLibXBInitRequired(system,block,[],"","",0))>
  %else
    %if system.StatesCanReset == "no" && !FcnParamInitRequired(param, -1)
      %<SETFIELD(block,"SkipInitialization",1)>
    %else
      %<SETFIELD(block,"SkipInitialization",0)>
    %endif
  %endif
%endfunction
 
 
%%Function:SLibXBInitRequired====================================================================
%%Abstract:
%%Wheneverpossible,avoidre-initializingthestatesandblockoutputsto
%%zerosincetheyareinitializedtozerointhemodel'sregistration
%%function.Initializationisnecessaryinthefollowingcases:
%%
%%1)Thecodewillroll(toavoidanemptyfor-loop).
%%2)Thecodeislocatedinsidethesystem'sinitializefunction(the
%%statesmustre-initializewheneverthesystemenables).
%%3)Initialcondition(IC)valueisnotzeroornotempty
%%
%%Thischeckwillnotbenecessarywhenstateandblockoutputs
%%initializationischangedfromrun-timetostaticinitialization.
%%
%%Note:
%%Alwaysreturnstrueiftheparameteriscomplexorthecodeformat
%%isotherthanEmbedded-C.
%%
%%
%%Arguments:
%%system:ReferencetoaSimulinksystem
%%block:Referencetoablock
%%param:Parameter(Ifthereisnoinitialvalueparameter,call
%%thisfunctionwith[]fortheparam)
%%ucv:Usercontrolvariablestring
%%lcv:Loopcontrolvariablestring
%%idx:Indexintoparametervector
%%
%%Returns:
%%1ifinitializationofstatesandblockoutputsisrequired
%%0otherwise
%%
%%TopTester:test/toolbox/simulink/blocks/CPPCodeGen/tsmlk_core_cpp_coverage.m
%%
%function SLibXBInitRequired(system, block, param, ucv, lcv, idx) void
 
  %if system.StatesCanReset == "yes"
    %return 1
  %else
    %return !ISEMPTY(param) && SLibParamInitRequired(param,ucv,lcv,idx)
  %endif
 
%endfunction
 
 
%%Function:SLibParamInitRequired=================================================================
%%Abstract:
%%Wheneverpossible,avoidre-initializingparameterstozerosincethey
%%areinitializedtozerointhemodel'sregistrationfunction.
%%Parameterinitialization(onit'sownwithoutenableandreset
%%considerations)isnecessaryinthefollowingcases:
%%
%%1)Thecodewillroll(toavoidanemptyfor-loop).
%%2)Initialcondition(IC)valueisnotzero.
%%
%%Note:
%%Alwaysreturnstrueiftheparameteriscomplexorthecodeformat
%%isotherthanEmbedded-C.
%%
%%Arguments:
%%param:Parameter
%%ucv:Usercontrolvariablestring
%%lcv:Loopcontrolvariablestring
%%idx:Indexintoparametervector
%%
%%Returns:
%%1ifinitializationisrequired
%%0otherwise
%%
%%
%function SLibParamInitRequired(param, ucv, lcv, idx) void
 
  %% If we are initializing any of the elements in the array (checked by SkipInitialization)
  %% then we need to initialize all of the elements if rolling.
  %% Otherwise, check this element to see if it needs to be initialized.
  %if ((SLibGetWidthOfValueFromParamRec(param) > 1) && (ucv != "" || lcv != ""))
    %return 1
  %else
    %return FcnParamInitRequired(param, idx)
  %endif
%endfunction
 
 
%%Function:FcnParamInitRequired==================================================================
%%Abstract:
%%Helperfunction;useidx==-1tocheckalltheelements
%%TopTester:test/toolbox/simulink/blocks/CPPCodeGen/tsmlk_core_cpp_coverage.m
%%
%function FcnParamInitRequired(param, idx) void
 
  %assign prmValue = SLibGetValueFromParamRec(param, TLC_TRUE)
  %assign nRows = SIZE(prmValue,0)
  %assign nCols = SIZE(prmValue,1)
  %assign width = nRows * nCols
 
  %if !SLibIsERTTarget()
    %return 1
  %endif
 
  %assign ASTNode = param.ASTNode
 
  %switch (ASTNode.Op)
    %case "SL_INLINED"
    %case "SL_CALCULATED"
      %% if the parameter is inlined or calculated, it is a candidate for
      %% the optimization
      %assign complex = SLibGetASTNodeIsComplex(ASTNode)
 
      %if complex
        %return 1
      %endif
 
      %assign dtype = SLibGetASTNodeDataTypeId(ASTNode)
      %% Can use param.Value in following line
      %% since param.Value == ModelParameter.Value
      %if TYPE(idx) == "Number" && idx == -1
        %foreach idx2 = width
          %assign icValue = SLibParameterValue(prmValue, dtype, complex, 0, idx2)
          %if !ISEQUAL(icValue,0)
            %return 1
          %endif
        %endforeach
      %else
        %assign icValue = SLibParameterValue(prmValue, dtype, complex, 0, idx)
        %if !ISEQUAL(icValue,0)
          %return 1
        %endif
      %endif
 
      %break
 
    %default
      %% if the parameter is tunable or not inlined, don't optimize away
      %% initialization
        %return 1
      %break
  %endswitch
 
  %return 0
%endfunction
 
 
%%=============================================================================
%%EnablesubsystemsusethessIsFirstInitCondmacrotodeterminetimezero.
%%InordertooptionallygeneratethebooleanintheERTreal-timeobject,
%%wetracktheusageofthismacrowithLibIsFirstInitCond().
%%
 
%<LibAddToCompiledModel("IsFirstInitCondMacroUsed", 0)>
%%Function:SLibGetIsFirstInitCondAccessed========================================================
%%Abstract:
%%SLibGetIsFirstInitCondAccessedreturnsthevalueoftheglobalflag
%%::CompiledModel.IsFirstInitCondMacroUsed.
%%
%function SLibGetIsFirstInitCondAccessed() void
  %return IsFirstInitCondMacroUsed
%endfunction
 
 
%%Function:SLibIsFirstInitCond===================================================================
%%Abstract:
%%ImplementsLibIsFirstInitCond.ThisbypassestheExportFunctionsMode
%%check.Thisbypassisgenerallynotsafeexcepttoimplementenabling
%%semantics.Thefollowing'positive'caseissafeifthecallismade
%%duringtheInitialize(orStart,althoughsuperfluous)functionsince
%%theinitCondFlagisstillmaintainedproperlyinthemodelInitialize
%%(andStart)functionswhenExportFunctionsMode==1:
%%if(%<LibIsFirstInitCond>){...}
%%Thefollowing'negative'caseissafeonlyifguardedby:
%%%ifProtectCallInitFcnTwice
%%if(!%{...}
%%%endif
%%
%function SLibIsFirstInitCond() void
  %assign ::CompiledModel.IsFirstInitCondMacroUsed = 1
  %return RTMIs("FirstInitCond")
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibIsFirstInitCond=====================
%%Abstract:
%%LibIsFirstInitCondreturnsgeneratedcodeintendedforplacementin
%%theinitializationfunction.Thiscodedetermines,duringrun-time,
%%whethertheinitializationfunctionisbeingcalledforthefirsttime.
%%
%%Thisfunctionalsosetsaflagtodetermineifthefirst-initialize-condition
%%flagisneeded.
%%
%%ThisfunctionistheTLCversionoftheSimStructmacro:ssIsFirstInitCond
%%
%function LibIsFirstInitCond() void
  %if ExportFunctionsMode == 1
    %<SLibReportErrorWithId("RTW:tlc:FirstInitInExpFcn")>
  %endif
  %return SLibIsFirstInitCond()
%endfunction
 
 
 
 
%%Function:SLibCallerHStuctDeclSystem============================================================
%%Abstract:
%%returnrootorcallers'HStructDeclSystem(caller'sreusedparent)
%%
%function SLibCallerHStuctDeclSystem(system, callSiteIdx) void
 
  %assign parentIdx = system.CallSites[callSiteIdx][0]
  %assign rSysIdx = ::CompiledModel.System[parentIdx].HStructDeclSystemIdx
  %assign parent = ::CompiledModel.System[rSysIdx]
 
  %return parent
 
%endfunction %% SLibCallerHStuctDeclSystem
 
%%Function:SLibCallerReusedParentSystem==========================================================
%%Abstract:
%%returnrootorcallers'ReusedParentSystemIdx
%%
%function SLibCallerReusedParentSystem(system, callSiteIdx) void
 
  %assign parentIdx = system.CallSites[callSiteIdx][0]
  %assign rSysIdx = ::CompiledModel.System[parentIdx].ReusedParentSystemIdx
 
  %return ::CompiledModel.System[rSysIdx]
 
%endfunction %% SLibCallerHStuctDeclSystem
 
%%Function:SLibResetNextVHTDueToEnable===========================================================
%%Abstract:
%%Thismethodiscalledbyablock'sprivateenablemethodtoproperly
%%handlevariablesampletimeinsideanenabledsubsystem.
%%ThesubsystemwillbecallingBdSystemOutputbeforethesampleHit
%%vectorisupdatedsoweneedtosettheblock'sentrytotrueto
%%makesureitgetstorunitsoutputfunctioninthenextopportunity
%%
%function SLibResetNextVHTDueToEnable(block) void
  %assign tid = block.VarTsTID
  %if IsModelReferenceForASimstructBasedTarget()
    %assign idx = %<tid>
  %else
    %assign idx = CAST("Number", ::CompiledModel.SampleTime[tid].PeriodAndOffset[1])
  %endif
  %openfile buffer
  /* Force a sample hit at this major time step */
  %if IsModelReferenceForASimstructBasedTarget()
    %<FcnGenSpecialAccess(FcnInferredSystemAndAccessRTMArgDef(), "SampleHit", "set", 2, ...
      ["%<tid>", "0"], "1", SLibGetSimStruct())>;
  %else
    %<RTMuSetIdxed("SampleHit", tid, 1)>;
  %endif
  %<RTMuSetIdxed("TaskTime", tid, LibGetT())>;
  %<RTMuSetIdxed("VarNextHitTime", "%<idx>", LibGetT())>;
  %closefile buffer
  %return buffer
%endfunction %% SLibResetNextVHTDueToEnable
 
%%Function:SLibFcnComputeInput===================================================================
%%Abstract:
%%Thisfunctionisusedbyblocksthatconditionallyneedtheirinputs,
%%e.g.,switchblock.Thisfunctiongeneratesoutputcodeforthe
%%conditionallyexecutedsubsystemdrivingthespecifiedinput.
%%
%function SLibFcnComputeInput(block, portIdx) Output
  %assign sysToCall = SLibBlockSystemToCallForInput(portIdx)
  %assign sysIdx = sysToCall[0]
  %assign callSiteIdx = sysToCall[1]
  %if sysIdx >= 0
    %assign ss = ::CompiledModel.System[sysIdx]
    %if !LibSystemFcnIsEmpty(ss, "Output")
      %<LibGenSystemFcnCall(ss, "Output", callSiteIdx)>/
    %endif
  %endif
%endfunction %%SLibFcnComputeInput
 
%%Function:SLibFcnComputeOutput==================================================================
%%Abstract:
%%Thisfunctionisusedbyblocksthatconditionallycalltheiroutputs,
%%Thisfunctiongeneratesoutputcodefortheconditionallyexecuted
%%subsystemdrivenbythespecifiedoutputport.
%%
%function SLibFcnComputeOutput(block, portIdx) Output
  %assign sysToCall = SLibBlockSystemToCallForOutput(portIdx)
  %assign sysIdx = sysToCall[0]
  %assign callSiteIdx = sysToCall[1]
  %if sysIdx >= 0
    %assign ss = ::CompiledModel.System[sysIdx]
    %if !LibSystemFcnIsEmpty(ss, "Output")
      %<LibGenSystemFcnCall(ss, "Output", callSiteIdx)>/
    %endif
  %endif
%endfunction %%SLibFcnComputeOutput
 
%%Function:SLibZeroOutDerivativesForSystem=======================================================
%%Abstract:
%%Thisfunctionwillgeenratethecodetozerooutthederivatives
%%inaconditionallyexecutedsubsystem.Noteitis
%%thecallersresponsibilitytodeclaretheloopindexiand
%%thedoublepointerdx.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmDemoSubsysFcncall5_VC1.m
%%
%function SLibZeroOutDerivativesForSystem(ssBlock,system) Output
 
%%%assignidx=system.Interface.ContStatesArgDef.FirstLocation
  %with ssBlock
    %assign cStates = LibBlockParamSetting("Subsystem", "SystemContStates")
  %endwith
  %assign ncStates = cStates[0]
  %if (ncStates == 0)
    %return
  %endif
  %assign idx = cStates[1]
  %assign cs = ::CompiledModel.ContStates.ContState[idx]
  %assign blkIdx = cs.SigSrc[2]
  %assign isMdlRef = FcnOwnerBlkType(cs) == "ModelReference"
  %assign varGroupIdx = cs.VarGroupIdx[2]
  %assign cross = system.CrossNoArgFcnBound
  %assign blockPath = SLibCGIRVarGroupPath( ...
    varGroupIdx, system.HStructDeclSystemIdx, cross)
 
  %% Cstates for model reference block is stored in a structure
  %assign dxId = "%<blockPath>%<cs.Identifier>"
 
  %if ncStates > 1
    %if isMdlRef
      dx = (real_T *) &(%<dxId>);
    %elseif cs.Width >1
      dx = &(%<dxId>[0]);
    %else
      dx = &(%<dxId>);
    %endif
    %assign dxZeroUpperLimitPlus1 = ncStates
    for (i=0; i < %<dxZeroUpperLimitPlus1>; i++) {
    dx[i] = 0.0;
    }
  %else
    %if isMdlRef
      {
        real_T *dx = (real_T *) &(%<dxId>);
        (*dx) = 0.0;
      }
    %else
      %<dxId> = 0.0;
    %endif
  %endif
%endfunction
 
%%Function:SLibZeroOutZcSignalsForSystem=========================================================
%%Abstract:
%%ThisfunctionwillgeneratethecodetozerooutthezcSignals
%%inaconditionallyexecutedsubsystem.
%%foradzc
%function SLibZeroOutZcSignalsForSystem(ssBlock,system) Output
  %with ssBlock
    %assign nNSZC = LibBlockParamSetting("Subsystem", "NumNonsampledZCs")
  %endwith
  %if (nNSZC == 0)
    %return
  %endif
 
  %assert(SolverType == "VariableStep")
  %% This is not done before and happend to be ok becuase the zcsWith
  %% of modelref zcSignal is always 1. even so, the pointer is not casted.
  %% Need to handle model reference block (see
  %% SLibZeroOutDerivativesForSystem function)
  %assert(!IsModelReferenceTarget())
 
  %with ssBlock
    %assign idx = LibBlockParamSetting("Subsystem", "BlkZcRecOffset")
    %assign nZCs = LibBlockParamSetting("Subsystem", "NumZcSignalEls")
  %endwith
 
  %assign blkZcRec = ::CompiledModel.ZcRec.BlkZcRec[idx]
  %assign isMdlRef = FcnOwnerBlkType(blkZcRec) == "ModelReference"
  %assign idxVec = SLibGetSystemAndCallSideIndex(blkZcRec)
  %assign cross = system.CrossNoArgFcnBound
  %assign sysIdx = idxVec[0]
  %assign csIdx = idxVec[1]
  %assign varGroupIdx = FcnSysVarGroupIndex(System[sysIdx], ...
    "ZCSV", csIdx)
  %assign blockPath = SLibCGIRVarGroupPath...
      (varGroupIdx, system.HStructDeclSystemIdx, cross)
  %assign zcSignalInfo = blkZcRec.ZcSignalInfo[0]
  %assign name = FcnGetZCSignalCGVarName(zcSignalInfo)
  %if nZCs > 1
    %if isMdlRef
      real_T* zcsv = (real_T*)&(%<blockPath>%<name>);
    %elseif zcSignalInfo.Width > 1
      real_T* zcsv = &(%<blockPath>%<name>[0]);
    %else
      real_T* zcsv = &(%<blockPath>%<name>);
    %endif
    int_T i;
    %assign dxZeroUpperLimitPlus1 = nZCs
    for (i=0; i < %<dxZeroUpperLimitPlus1>; i++) {
      zcsv[i] = 0.0;
    }
  %else
    %if isMdlRef
      real_T *zcsv = (real_T *) &(%<blockPath>%<name>);
      (*zcsv) = 0.0;
    %else
      %<blockPath>%<name> = 0.0;
    %endif
  %endif
%endfunction
 
 
%%FunctionSLibSetStatesDisabled===========================================
%%Abstract:
%%Thisfunctiongeneratescodetosetthesystemstatestothevalue
%%passed
%%TopTester:test/toolbox/simulink/variants/tMdlrefToVSS.m
%%
%function SLibSetStatesDisabled(ssBlock,system,value) Output
  %with ssBlock
    %assign cStates = LibBlockParamSetting("Subsystem", "SystemContStates")
  %endwith
  %assign ncStates = cStates[0]
  %if (ncStates == 0)
    %return
  %endif
 
  %assert(SolverType == "VariableStep")
 
  %assign idx = cStates[1]
  %assign cs = ::CompiledModel.ContStates.ContState[idx]
  %assign varGroupIdx = cs.VarGroupIdx[1]
  %assign cross = system.CrossNoArgFcnBound
  %assign blockPath = SLibCGIRVarGroupPath( ...
    varGroupIdx, system.HStructDeclSystemIdx, cross)
 
  %if ncStates > 1
    %if FcnOwnerBlkType(cs) == "ModelReference"
      %assign blk = System[cs.SigSrc[0]].Block[cs.SigSrc[2]]
      %assign intrf = GetModelrefInterface(blk)
      %assign mdlRefCsWith = CAST("Number", %<intrf.xOptWidth>)
      %assign isArray = mdlRefCsWith > 1
    %else
      %assign isArray = cs.Width > 1
    %endif
 
    %if isArray >1
      (void) %<LibGenMemFcnCall("memset", ...
        "&(%<blockPath>%<cs.Identifier>[0])", value, ...
        "%<ncStates>*sizeof(boolean_T)")>;
    %else
      (void) %<LibGenMemFcnCall("memset", ...
        "&(%<blockPath>%<cs.Identifier>)", value, ...
        "%<ncStates>*sizeof(boolean_T)")>;
    %endif
  %else
    %<blockPath>%<cs.Identifier> = %<value>;
  %endif
%endfunction
 
%%Function:SLibUnusedParameter===================================================================
%%
%function SLibUnusedParameter(param)
  %if IsModelReferenceTarget()
    %openfile retBuf
    (void) (%<param>);
    %closefile retBuf
  %else
    %openfile retBuf
    %<LibGenUnusedParamFcnCall("RT_UNUSED_PARAMETER", "%<param>")>;
    %closefile retBuf
  %endif
  %return retBuf
%endfunction
 
 
%%Function:SLibGenNonReusableSubsysFcnAsClassMemFcn==============================================
%%Shouldanon-reusablesubsystemfunctionbegeneratedasamemberfunction
%%inthemodelclass?
%function SLibGenNonReusableSubsysFcnAsClassMemFcn(system)
  %assign result = GenerateClassInterface && ...
                   !IsModelReferenceBaseSys(system) && ...
                   LibSystemIsNonReusedFcn(system)
 
  %return result
%endfunction %% SLibGenNonReusableSubsysFcnAsClassMemFcn
 
%%Function:SLibGenSubsysFcnAsClassMemFcn=========================================================
%%Shouldasubsystemfunctionbegeneratedasamemberfunction
%%inthemodelclass?
%function SLibGenSubsysFcnAsClassMemFcn(system)
  %if !SLibReusableSubsystemCppEncapEnabled()
    %return SLibGenNonReusableSubsysFcnAsClassMemFcn(system)
  %endif
 
  %assign result = GenerateClassInterface && ...
                   !IsModelReferenceBaseSys(system) && ...
                   (LibSystemIsNonReusedFcn(system) || LibSystemIsReusedFcn(system)) && ...
                   !LibSystemIsReusedLibraryFcn(system)
 
  %return result
%endfunction %% SLibGenSubsysFcnAsClassMemFcn
 
%%Function:SLibGetAlignmentSyntax================================================================
%%Shouldanon-reusablesubsystemfunctionbegeneratedasamemberfunction
%%inthemodelclass?
%function SLibGetAlignmentSyntax(mdlName, symbol, dataType, align, alignType)
  %assert (align > 0)
  %assign ret = ""
  %assign das = FEVAL("rtwprivate", "da_syntax", mdlName, symbol, dataType, align, alignType)
  %if !ISEMPTY(das.err)
    %openfile errMsg
    %<das.err>
    %closefile errMsg
    %<SLibReportErrorWithIdAndArgs("RTW:tlc:GenericMsg", errMsg)>
  %else
    %assign ret = das.syntax
  %endif
  %return ret
 
%endfunction
 
%%Function:SLibDumpPublicServerInterfaces========================================================
%%Abstract:
%%TopTester:test/toolbox/simulink/variants/inlineVariants/wiperexample/twipervariant.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tVariantSimulinkFunctionAutoInherit.m
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function SLibDumpPublicServerInterfaces() void
  %if Accelerator || IsModelReferenceSimTarget() || isRAccel || SLibAutosarActive()
    %return
  %endif
  %with ::CompiledModel
  %if NumSimulinkFunctions == 0
    %return
  %endif
 
  %% Perform error checking
  %createrecord serverInterface { NumberOfServers 0 }
  %assign numFunctionsInThisModel = 0
  %foreach fcnIdx = NumSimulinkFunctions
    %assign fcn = SimulinkFunction[fcnIdx]
    %if SLibSimulinkFunctionNeedsDeclaration(fcn)
      %assign numFunctionsInThisModel = numFunctionsInThisModel + 1
      %assign proto = SLibDeclareSimulinkFunction(fcn, TLC_TRUE, TLC_TRUE)
      %createrecord fcnRec { ...
        serverName "" ...
        model "" ...
        definedInThisModel TLC_FALSE ...
        fcnIdx -1 ...
        serverPrototype "" }
      %if ::GenerateClassInterface && (fcn.FullPathToFunction == "P")
        %assign classConfObj = FcnGetRTWCPPStepPrototypeRecord()
        %assign theClassName = classConfObj.ModelClassName
        %assign fcnRec.serverName = theClassName + "::" + fcn.CGFunctionName
      %else
        %assign fcnRec.serverName = fcn.CGFunctionName
      %endif
      %assign fcnRec.model = ::CompiledModel.Name
      %assign fcnRec.fcnIdx = fcnIdx
      %assign fcnRec.definedInThisModel = fcn.IsDefinedInThisModel == "yes"
      %assign fcnRec.serverPrototype = proto
      %addtorecord serverInterface FunctionRecord %<fcnRec>
    %endif
  %endforeach
 
  %% It is possible that all the functions in the model are private,
  %% for example, they are all utility functions for DES or Messages.
  %% In this case, return early to simplify subsequent logic.
  %if numFunctionsInThisModel == 0
    %return
  %endif
 
  %assert ::CompiledModel.GenUtilsSrcInSharedLocation == 1
 
  %assign serverInterface.NumberOfServers = numFunctionsInThisModel
  %assign result = FEVAL("rtwprivate", "addServerFunctionsToSCM", "%<LocalSharedCodeManagerFile>", serverInterface)
  %if !ISEMPTY(result.code)
    %if result.code == "ERROR"
      %<LibReportFatalError(result.message)>
    %elseif result.code == "WARNING"
      %<LibReportWarning(result.message)>
    %endif
  %endif
 
  %% Write out headers
  %% For sure if the header file doesn't exist, generate it.
  %foreach fcnIdx = NumSimulinkFunctions
    %assign fcn = SimulinkFunction[fcnIdx]
    %if SLibSimulinkFunctionNeedsDeclaration(fcn) && !(GenerateClassInterface && fcn.FullPathToFunction != "G")
      %assign fileName = "%<::CompiledModel.RTWInfoMatFile.sharedSourcesDir>%<fcn.CGFunctionName>"
      %if FILE_EXISTS(fileName + ".h") == 0 || fcn.IsDefinedInThisModel == "yes"
        %assign fcn.WriteHeaderFile = "yes"
      %endif
    %endif
  %endforeach
 
  %% Then also write out ones that need to be updated
  %assign writeHeaderFileFcnIdx = result.writeHeaderFileFcnIdx
  %assign numHdrFiles = SIZE(writeHeaderFileFcnIdx, 1)
  %foreach fcnIdx = numHdrFiles
    %assign fcn = SimulinkFunction[writeHeaderFileFcnIdx[fcnIdx]]
    %assign fcn.WriteHeaderFile = "yes"
  %endforeach
 
  %% Now write them out
  %foreach fcnIdx = NumSimulinkFunctions
    %assign fcn = SimulinkFunction[fcnIdx]
    %if SLibAutosarActive() && fcn.IsDefinedInThisModel == "no" && ...
      !IsModelReferenceTarget()
      %% Skip generating header file for AUTOSAR targets if:
      %% (a) The function is not defined in this model, that is, the model only
      %% contains the function-caller block.
      %% (b) The model is not a referenced model
      %% The model where the function is defined will be responsible for
      %% generating the header file. If such a model does not exist, then
      %% no header file will get generated.
      %continue
    %endif
 
    %if SLibSimulinkFunctionNeedsDeclaration(fcn) && !(GenerateClassInterface && fcn.FullPathToFunction != "G")
      %assign baseFileName = fcn.CGFunctionName
      %assign fileName = "%<::CompiledModel.RTWInfoMatFile.sharedSourcesDir>%<fcn.CGFunctionName>"
      %if fcn.WriteHeaderFile == "yes"
        %if !ISFIELD(::CompiledModel, "RTWInfoMatFile")
          %<LoadRTWInfoMatFileforTLC()>
        %endif
        %assign proto = SLibDeclareSimulinkFunction(fcn, TLC_FALSE, TLC_FALSE)
        %openfile fcnSignature
        #ifndef RTW_HEADER_%<fcn.CGFunctionName>_
        #define RTW_HEADER_%<fcn.CGFunctionName>_
 
        /* Shared type includes */
        #include "%<SLibCoderTypesFilename()>"
        %<LibPushEmptyStackSharedUtils()>
        %assign multiWord = TLC_FALSE
 
        %foreach idx = SIZE(fcn.SymbDimsHeaderFiles, 1)
          %assign header = fcn.SymbDimsHeaderFiles[idx]
          %if header[0] == "<" || header[0] == "/""
            %<LibAddtoSharedUtilsIncludes(header)>
          %else
            %assign header = "/"" + header + "/""
            %<LibAddtoSharedUtilsIncludes(header)>
          %endif
        %endforeach
        %foreach idx = SIZE(fcn.ArgTypeIds, 1)
          %assign dtId = fcn.ArgTypeIds[idx]
          %assign header = LibHeaderForDataTypeIdx(dtId)
          %if !ISEMPTY(header)
            %<LibAddtoSharedUtilsIncludes(header)>
          %elseif LibIsDataTypeMultiWordFixpt(dtId)
            %assign multiWord = TLC_TRUE
          %endif
        %endforeach
        %if multiWord
          #include "%<SLibCoderMultiwordTypesFilename()>"
        %endif
        %if SLibDeclareHalfPrecisionUsage()
          #include "%<SLibCoderHalfTypeHdrFilename()>"
        %endif
 
        %assign sharedTypesHeaders = LibPopStackSharedUtilsIncludes()
        %foreach idx = SIZE(sharedTypesHeaders, 1)
          #include %
        %endforeach
 
        %% include Compiler.h to define AUTOSAR compiler abstraction macros
        %if SLibAutosarCompilerAbstractionRequired()
            #include "Compiler.h"
        %endif
 
 
        %if (fcn.IsVariantSimulinkFunction == "yes")
          %assign isGlobalFcn = (fcn.IsGlobal == "yes")
          %if !isGlobalFcn
            %assign variantCondition = fcn.VariantCondition
            %assign ifCond = SLibIfVariantConditionForm(variantCondition)
            %assign ifEndCond = SLibEndIfVariantConditionForm(variantCondition)
          %endif
          %% Do not guard function declaration if public Simulink Function with declaration in the shared folder.
          %% TopTester: test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tmLatchInputFromServer1_VC1.m
          %if !isGlobalFcn
            %<ifCond>
          %endif
          %if !GenerateClassInterface
            %if CGMODEL_ACCESS("CGModel.isIndividualFunctionMappingEnabled")
              %<SLibGetFcnMemSecPragmaForFunction(fcn.CGFunctionName, "SimulinkFunction", fcn.Name, "Pre")>/
            %else
              %<SLibGetFcnMemSecPragmaOnDecl(fcn.CGFunctionName, "MemSecFuncExecute", "Pre")>/
            %endif
          %endif
          %<proto>
          %if !GenerateClassInterface
            %if CGMODEL_ACCESS("CGModel.isIndividualFunctionMappingEnabled")
              %<SLibGetFcnMemSecPragmaForFunction(fcn.CGFunctionName, "SimulinkFunction", fcn.Name, "Post")>/
            %else
              %<SLibGetFcnMemSecPragmaOnDecl(fcn.CGFunctionName, "MemSecFuncExecute", "Post")>/
            %endif
          %endif
          %if !isGlobalFcn
            %<ifEndCond>
          %endif
        %else
          %if !GenerateClassInterface
            %if CGMODEL_ACCESS("CGModel.isIndividualFunctionMappingEnabled")
              %<SLibGetFcnMemSecPragmaForFunction(fcn.CGFunctionName, "SimulinkFunction", fcn.Name, "Pre")>/
            %else
              %<SLibGetFcnMemSecPragmaOnDecl(fcn.CGFunctionName, "MemSecFuncExecute", "Pre")>/
            %endif
          %endif
          %<proto>
          %if !GenerateClassInterface
            %if CGMODEL_ACCESS("CGModel.isIndividualFunctionMappingEnabled")
              %<SLibGetFcnMemSecPragmaForFunction(fcn.CGFunctionName, "SimulinkFunction", fcn.Name, "Post")>/
            %else
              %<SLibGetFcnMemSecPragmaOnDecl(fcn.CGFunctionName, "MemSecFuncExecute", "Post")>/
            %endif
          %endif
        %endif
 
        #endif
        %closefile fcnSignature
        %openfile bannerBuf
        /*
        * %<fileName>.h
        *
        %<SLibCommonUtilHeaderInfo()>/
        */
        %closefile bannerBuf
        %assign file = LibCreateSourceFileAtPath("Header","Simulink",fileName,baseFileName)
        %<SLibSetModelFileAttribute(file, "Group", "utility")>
        %<LibSetSourceFileSection(file, "Functions", fcnSignature)>
        %<LibSetSourceFileSection(file, "Banner", bannerBuf)>
        %<SLibSetModelFileIndent(file, TLC_TRUE)>
        %<SLibSetModelFileShared(file, TLC_TRUE)>
      %else
        %<SLibAddGeneratedFileToList(fileName+".h", "utility", "header","")>
      %endif
    %endif
  %endforeach
 
  %endwith
%endfunction
 
%function SLibIsModelTypesModelClassNamespace()
  %return SLibModelTypesNamespaceEnabled() && ...
          CGMODEL_ACCESS("CGModel.getIsModelTypesInModelClass")
%endfunction
 
%function SLibGetModelTypesNamespacePrefix()
  %return SLibGetSystemTypesNamespacePrefix(::CompiledModel.System[GetBaseSystemIdx()])
%endfunction
 
%function SLibIsSystemTypesModelClassNamespace(system)
  %return SLibIsModelTypesModelClassNamespace() && !LibSystemIsReusedLibraryFcn(system)
%endfunction
 
%function SLibGetSystemTypesNamespacePrefix(system)
  %assign prefix = ""
  %if SLibIsSystemTypesModelClassNamespace(system)
    %if !ISEMPTY(::NamespaceName)
      %assign prefix = "%<::NamespaceName>::"
    %endif
    %assign prefix = prefix + "%<::CPPClassName>::"
  %endif
  %return prefix
%endfunction
 
%function SLibCacheCPPEncapModelData(field, buffer) void
  %if !ISFIELD(::CompiledModel, "CPPEncapModelData")
    %createrecord dataRec { %<field> buffer }
    %<LibAddToCompiledModel("CPPEncapModelData", dataRec)>
  %elseif !ISFIELD(::CompiledModel.CPPEncapModelData, field)
    %addtorecord ::CompiledModel.CPPEncapModelData %<field> buffer
  %else
    %assign ::CompiledModel.CPPEncapModelData.%<field> = ::CompiledModel.CPPEncapModelData.%<field> + buffer
  %endif
%endfunction
 
%endif %% _SYSLIB_
 
%%[EOF]syslib.tlc