%%============================================================================
%%File:commonbodlib.tlc
%%
%%Abstract:
%%ThissystemTLClibraryfilecontainsfunctionsthatarecommon
%%betweenthedifferentcodegeneratorsforproducingthemodel's
%%sourcefile.
%%
%%Thefunctionsprovideforcachingcodeforallsystemsandalsodumping
%%thecachedbuffers.
%%
%%Note:TheonlyCodeFormatdependenciesallowedinthisfilearefor:
%%1)Creatingfunctionprototypesforsubsystems
%%2)Cachingbodycode
%%
%%
%%Copyright1994-2019TheMathWorks,Inc.
%%
%%============================================================================
%include "dumpcodemetrics.tlc"
%selectfile NULL_FILE
 
%if EXISTS("_COMMONBODLIB_") == 0
%assign _COMMONBODLIB_ = 1
 
%%FunctionFcnForcedHasTIDArg(sys)void
%%Abstract:
%%Returntrueisparametertidisforcedtoinclude
%%foruniformsubsysteminterface.
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSink/tmVarSinkRateTransBlk_VC1.m
%%
%function FcnForcedHasTIDArg(sys)
  %return (sys.Type == "root") && RootBodyTIDneeded
%endfunction
 
%%Function:FcnSysAccessedTID=================================================
%%Abstract:
%%returns1ifTIDwasused,thenresettheflag
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSink/tmVarSinkRateTransBlk_VC1.m
%%
%function FcnSysAccessedTID() void
  %if TLC_TRUE == ::CompiledModel.NeedTID
    %return 1
  %else
    %return 0
  %endif
%endfunction
 
%%Function:SLibSetTIDAddedInTLC==============================================
%%Abstract:
%%SetstheflagthatwillensureunusedTIDargumenthandling.
%%
%%TopTester:test/toolbox/simulink/variants/defaultVariants
%%
%function SLibSetTIDAddedInTLC(system) void
  %assign system.TIDArgAddedInTLC = 1
%endfunction
 
%%Function:FcnSetSystemFcnNeedTIDFlag========================================
%%Abstract:
%%SetNeedTIDIn%<Type>flagiftidisaccessed.
%%SetForcedNeedTIDIn%<type>Fcnflagsiftidisforcedtobeincluded
%%insubsysteminterface.
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSink/tmVarSinkRateTransBlk_VC1.m
%%
%function FcnSetSystemFcnNeedTIDFlag(system, type) void
  %if FcnSysAccessedTID()
    %<LibSetSystemField(system, "NeedTIDIn%<type>", TLC_TRUE)>
  %elseif FcnForcedHasTIDArg(system)
    %<LibSetSystemField(system, "NeedTIDIn%<type>", TLC_FALSE)>
    %addtorecord system ForcedNeedTIDIn%<type> TLC_TRUE
  %endif
%endfunction
 
%%Function:FcnHandlesUnusedTIDArg============================================
%%Abstract:
%%
%%TopTester:test/toolbox/simulink/variants/defaultVariants
%%
%function FcnHandlesUnusedTIDArg(ss, type) void
  %openfile retBuf
  %if !SLibIsExplicitTaskingExportFcnRateGrouping(type, ss.CurrentTID)
    %if 1 == ss.TIDArgAddedInTLC && LibSystemFcnNeedsTID(ss,type)
      %if ISFIELD(ss, "ForcedNeedTIDIn" + type)
        %assert !LibGetSystemField(ss, "NeedTIDIn" + type)
        %<SLibUnusedParameter(::tTID)>
 
      %elseif SLibSystemFcnPeriodicRateGrouping(ss, type) && ...
        LibGetSystemField(ss, "NeedTIDIn" + type)
        /* If subsystem generates rate grouping %<type> functions,
        * when %<::tTID> is used in %<type> function for one rate,
        * all %<type> functions include %<::tTID> as argument.
        * As result, some %<type> functions may have unused %<::tTID>.
        */
        %<SLibUnusedParameter(::tTID)>
      %endif
    %elseif SLibGetNeedLocalTIDInSystem(ss, type) && ...
      SLibSystemFcnPeriodicRateGrouping(ss, type)
      /* If subsystem generates rate grouping %<type> functions,
      * when %<::tTID> is used in %<type> function for one rate,
      * all %<type> functions include %<::tTID> as a local variable.
      * As result, some %<type> functions may have unused %<::tTID>.
      */
      %<SLibUnusedParameter(::tTID)>
    %endif
  %endif
  %closefile retBuf
   
  %return retBuf
%endfunction %%FcnHandlesUnusedTIDArg
 
 
%%Function:FcnHandlesUnusedRTMForSimplifiedInterface======================
%%Abstract:
%%Formodelrefsimplifiedinterface,RTMmaybeaddedbutnotusedinthe
%%functionbody.Thisfunctionaddsunusedparametercodetosuch
%%functions.
%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tmg1672961.m
%function FcnHandlesUnusedRTMForSimplifiedInterface(ss, sysFcn)
  %% This function handles the situation when the RTM is added to a function
  %% interface whereas the function has no body, thus the RTM is unused.
  %% In this case, RTMArg is NOT NEEDED, thus SysFcnArgNeeded should return false.
  %% On the other hand, the RTM is always added to the interface for simplified
  %% interface to make the interface predictable. Therefore, the function
  %% prototype should have RTM as its arg.
  %% Since this function ONLY handles this situation, it uses a string comparison
  %% to checks whether the function's parameter is equal to the added RTM arg.
  %assign tid = ss.CurrentTID
  %openfile retBuf
    %if ::CompiledModel.RTWCGModules.RTWCGModule[ss.CGIRModuleIdx].SimplifiedInterface
      %assign rtmArgDef = ss.Interface.RTMArgDef
      %assign isPeriodicRateGrouping = SLibSystemFcnPeriodicRateGrouping(ss, sysFcn)
      %if !SysFcnArgNeeded(sysFcn, rtmArgDef, tid, isPeriodicRateGrouping)
        %if isPeriodicRateGrouping && !WHITE_SPACE(tid)
          %assign fieldName = "%<sysFcn>TID%<tid>FcnInfo"
        %else
          %assign fieldName = "%<sysFcn>FcnInfo"
        %endif
        %if ISFIELD(ss.InstanceCache, fieldName)
          %assign fcnInfo = GETFIELD(ss.InstanceCache, fieldName)
          %assign rtmParam = "%<tSimStructType> * const %<tSimStruct>"
          %if fcnInfo.Params == rtmParam
            %<SLibUnusedParameter(tSimStruct)>
          %endif
        %endif
      %endif
    %endif
  %closefile retBuf
  %return retBuf
%endfunction
 
 
%%Function:FcnDeclareCPIIfNeeded=============================================
%%Abstract:
%%returns1ifCPI(ControlPortIndex)wasusedinafunction-call
%%subsystem.
%%
%function FcnDeclareCPIIfNeeded(system, fcn) void
  %assign tempName = "NeedCPIIn" + fcn
  %return LibGetSystemField(system, tempName)
%endfunction
 
 
%%Function:SLibSystemNonEmpty================================================
%%Abstract:
%%Returnstrueifasystemgeneratessomecode
%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tmg1672961.m
%function SLibSystemNonEmpty(system)
  %assign nonEmpty = ...
    !LibSystemFcnIsEmpty(system, "Start") || ...
    !LibSystemFcnIsEmpty(system, "ConstCode") || ...
    !LibSystemFcnIsEmpty(system, "SetupRuntimeResources") || ...
    !LibSystemFcnIsEmpty(system, "Initialize") || ...
    !LibSystemFcnIsEmpty(system, "SystemInitialize") || ...
    !LibSystemFcnIsEmpty(system, "SystemReset") || ...
    !LibSystemFcnIsEmpty(system, "Output") || ...
    !LibSystemFcnIsEmpty(system, "Update") || ...
    !LibSystemFcnIsEmpty(system, "Derivative") || ...
    !LibSystemFcnIsEmpty(system, "Projection") || ...
    !LibSystemFcnIsEmpty(system, "ForcingFunction") || ...
    !LibSystemFcnIsEmpty(system, "MassMatrix") || ...
    !LibSystemFcnIsEmpty(system, "OutputUpdate") || ...
    !LibSystemFcnIsEmpty(system, "FinalizeDims") || ...
    !LibSystemFcnIsEmpty(system, "SetDims") || ...
    !LibSystemFcnIsEmpty(system, "Enable") || ...
    !LibSystemFcnIsEmpty(system, "Disable") || ...
    !LibSystemFcnIsEmpty(system, "CleanupRuntimeResources")
  %return (nonEmpty)
%endfunction %% SLibSystemNonEmpty
 
 
%%Function:SLibSystemTerminateNonEmpty=======================================
%%Abstract:
%%Returnstrueifasystemterminategeneratessomecode
%%
%%TopTester:/test/toolbox/simulink/variants/codevariants/tmg1672961.m
%%
%function SLibSystemTerminateNonEmpty(system) void
  %return !LibSystemFcnIsEmpty(system, "Terminate")
%endfunction %% SLibSystemTerminateNonEmpty
 
 
%%Function:SLibPassThroughArgsRequired=======================================
%%Abstract:
%%Returnstrueifthesysteminquestionrequiresargumentstobypassed.
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/tg1375551.m
%%TopTester:test/toolbox/simulink/blocks/lib_Discrete/DiscreteTimeIntegrator/rtw/tNumerics_dintegrt_globalin.m
%%
%function SLibPassThroughArgsRequired(system) void
  %if LibSystemIsRoot(system)
    %if MultiInstanceERTCode || GenerateClassInterface || UsingMalloc ...
      || SLibFcnProtoCtrlActive() || CodeFormat == "S-Function"
      %return TLC_TRUE
    %endif
  %elseif LibSystemIsNonReusedFcn(system)
    %if (CodeFormat == "S-Function") || ...
         ISFIELD(system,"RTWSystemCodeOptIntf") || ...
        (system.CrossNoArgFcnBound && (UsingMalloc || IsModelRefScalableBuild()))
      %return TLC_TRUE
    %endif
  %elseif LibSystemIsReusedFcn(system)
    %return TLC_TRUE
  %endif
  %return TLC_FALSE
%endfunction %% SLibPassThroughArgsRequired
 
 
%%Function:SLibCopyRootInputsArgAccessedFlags================================
%%Abstract:
%%ThisfunctionisusedtocopytheaccessflagsintherootIOrecords
%%fromacalleetothecallerfunction.
%%
%%TopTester:test/toolbox/simulink/blocks/lib_Discrete/DiscreteTimeIntegrator/rtw/tNumerics_dintegrt_globalin.m
%%
%function SLibCopyRootInputsArgAccessedFlags(aSystemRec, calleeName) void
  %%
  %if LibSystemIsRoot(aSystemRec) && SLibPassThroughArgsRequired(aSystemRec)
    %%
    %assign cTID = aSystemRec.CurrentTID
    %assign isRG = SLibSystemFcnPeriodicRateGrouping(aSystemRec, calleeName)
    %with ::CompiledModel.ExternalInputs
      %foreach idx = NumExternalInputs
        %assign extInp = ExternalInput[idx]
        %if extInp.StorageClass == "Auto" && ...
          SysFcnArgNeeded(calleeName, extInp, cTID, isRG)
          %<SLibAccessArgHelper(extInp,"",cTID)>
        %endif
      %endforeach
    %endwith
    %with ::CompiledModel.ExternalOutputs
      %foreach idx = NumExternalOutputs
        %assign extOut = ExternalOutput[idx]
        %if SysFcnArgNeeded(calleeName, extOut, cTID, isRG)
          %<SLibAccessArgHelper(extOut,"",cTID)>
        %endif
      %endforeach
    %endwith
  %endif
%endfunction
 
%%Function:SLibCGCallSubFcn==================================================
%%Abstract:
%%Thisfunctionisusedtocallsubfunctionsinamodule.Itcallsaspecific
%%TLCfunctionforeachargumentgeneratedinRTWCG.
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/tg1375551.m
%%
%function SLibCGCallSubFcn(aFcnName, aArgVec, modIdx, fcnIdx, callIdx) void
  %%
  %assign thisModule = RTWCGModules.RTWCGModule[modIdx]
  %assign thisFcn = thisModule.Function[fcnIdx]
  %assign thisCall = thisFcn.FunctionCall[callIdx]
  %assign calleeModIdx = thisCall.CalleeIdx[0]
  %assign calleeFcnIdx = thisCall.CalleeIdx[1]
  %assign calleeInstIdx = thisCall.CalleeIdx[2]
  %assign calleeModule = RTWCGModules.RTWCGModule[calleeModIdx]
  %assign callee = calleeModule.Function[calleeFcnIdx]
  %assign sep = ""
  %%
 
  %assign thisModuleReusedParentSystemIdx = ::CompiledModel.System[thisModule.CGSystemIdx].ReusedParentSystemIdx
  %assign DW_InterfaceData = SLibCG_GetInterfaceData(thisModuleReusedParentSystemIdx, ::BlockFcn, "DWork")
  %assign DWArgIsNeeded = SysFcnArgNeeded(aFcnName, DW_InterfaceData, ::CompiledModel.System[thisModule.CGSystemIdx].CurrentTID, SLibIsPeriodicRateGrouping())
  %if DWArgIsNeeded
    %<SLibCG_TrackDW(thisModuleReusedParentSystemIdx)>
  %endif
   
  %if thisFcn.IsShared
    %assign argStr = ""
    %foreach argIdx = callee.NumArgs
      %if callee.ArgAccessed[argIdx] > 0
        %assign argStr = argStr + sep + aArgVec[argIdx]
        %assign sep = ", "
      %endif
    %endforeach
    %return callee.Name + "(" + argStr + ")"
  %endif
  %assign system = ::CompiledModel.System[thisModule.CGSystemIdx]
  %assign sysIdx = system.SystemIdx
  %assign isScalableMRSys = ...
      IsModelReferenceBaseSys(system) && IsModelRefScalableBuild()
  %%
  %<SLibCopyRootInputsArgAccessedFlags(system, callee.Name)>
  %<SLibCopyArgAccessedFlags(sysIdx, callee.Name, ::BlockFcn, ...
    system.CurrentTID, isScalableMRSys)>
  %%
  %% (modIdx > calleeModIdx) the current module is calling a function
  %% from a child module. We need to generated complete argument accesses
  %% in this case, similar to those that are created for reusable subsystem
  %% function calls.
  %%
  %if modIdx > calleeModIdx
    %assign hasRTMArg = callee.SimStructArgIndex > -1
    %assign rtmNeeded = TLC_FALSE
    %if !hasRTMArg && ...
      FcnSysNeedAddRTMArg(system, callee.Name)
      %assign rtmNeeded = TLC_TRUE
    %endif
     
    %assign argStr = FcnGetAdditionalArgs(callee.Name, aArgVec, callee.Name, ...
      calleeModule.CGSystemIdx, thisModule.CGSystemIdx, calleeInstIdx, TLC_FALSE, rtmNeeded)
    %return callee.Name + "(" + argStr + ")"
  %else
    %assign argStr = ""
    %%
    %% (modIdx < calleeModIdx) the current module is calling a function
    %% from a parent module. In this case we need to generate the argument
    %% list from the parent system.
    %%
    %if modIdx < calleeModIdx
      %%
      %% FcnGenerateSubFcnBody will create the PassThroughArgs for the
      %% the current callee function call record
      %%
      %assign calleeSystem = ::CompiledModel.System[calleeModule.CGSystemIdx]
      %%
      %if SLibPassThroughArgsRequired(calleeSystem)
        %assign currentFcn = ::BlockFcn
        %assign saveTID = calleeSystem.CurrentTID
        %% Parent module's CurrentTID has not been setup yet; Need to use
        %% the context's, i.e., the caller's
        %assign calleeSystem.CurrentTID = system.CurrentTID
        %assign block = FcnRootOpaqueBlock()
        %assign prevModuleIdx = ::CurrentModuleIdx
        %assign prevFunctionIdx = ::CurrentFunctionIdx
        %assert calleeModIdx == calleeSystem.CGIRModuleIdx
        %assign ::CurrentModuleIdx = calleeModIdx
        %assign ::CurrentFunctionIdx = -1
        %<FcnGenerateSubFcnBody(block, calleeModule, calleeFcnIdx, TLC_TRUE)>
         
        %assert ::CurrentModuleIdx == calleeModIdx
        %assign ::CurrentFunctionIdx = prevFunctionIdx
        %assign ::CurrentModuleIdx = prevModuleIdx
        %assign calleeSystem.CurrentTID = saveTID
        %assign ::BlockFcn = currentFcn
      %endif
    %endif
    %assign passThroughArgs = callee.PassThroughArgs
    %if thisModule.SimplifiedInterface && !SLibIsFcnSubFunction(system, thisFcn.Name)
      %% A simplified interface function calling a sub-function
      %if ISFIELD(callee, "PassThroughArgsFullPath")
        %assign passThroughArgs = callee.PassThroughArgsFullPath
      %endif
    %endif
    %if calleeModule.AccessesArgsGlobally
      %foreach argIdx = callee.NumArgs
        %if callee.ArgAccessed[argIdx] > 0
          %assign addArg = TLC_FALSE
          %assign idNum = SLibSafeIDNUM(callee.ArgSource, argIdx)
          %assign argSrc = idNum[0]
          %switch argSrc
            %case "CPI"
            %case "TID"
            %case "X"
              %assign addArg = TLC_TRUE
              %break
            %case "RTM"
              %assign addArg = calleeModule.NeedsSimStruct
              %break
            %default
              %if ISFIELD(system,"RTWSystemCodeOptIntf") && ...
                (argSrc == "I" || argSrc == "O")
                %assign addArg = TLC_TRUE
              %endif
              %break
          %endswitch
          %if addArg
            %assign argStr = argStr + sep + aArgVec[argIdx]
            %assign sep = ", "
          %endif
        %endif
      %endforeach
    %else
      %foreach argIdx = callee.NumArgs
        %if callee.ArgAccessed[argIdx] > 0
          %assign argStr = argStr + sep + aArgVec[argIdx]
          %assign sep = ", "
        %endif
      %endforeach
    %endif
    %if callee.GpuKernel
      %assign kernelInvoke = "<<<" + aArgVec[0] + ", " + aArgVec[1] + ">>>"
    %else
      %assign kernelInvoke = ""
    %endif
    %%
    %% Make sure that we don't override a previously
    %% set HasPassThroughArgsAtCall flag. Only the first call site matters,
    %% as subsequent callsites might have arguments if the called function
    %% has been processed.
    %%
    %if !callee.HasPassThroughArgsAtCallSet
      %assign callee.HasPassThroughArgsAtCallSet = TLC_TRUE
      %assign callee.HasPassThroughArgsAtCall = !ISEMPTY(passThroughArgs)
    %endif
    %if ISEMPTY(passThroughArgs)
      %return callee.Name + kernelInvoke + "(" + argStr + ")"
    %else
      %%
      %% Subfunction called by iterator systems get the address of a
      %% BlockIO or DWork array element passed not just the base pointer.
      %%
      %% e.g. localBlockIO --> &localBlockIO[iterBlock_idx]
      %%
      %% The array element is accessed by pointer dereference inside
      %% of the sub-function.
      %%
      %% e.g. localBlockIO->someElement
      %%
      %if !system.GeneratingSubFunctions
        %assign argRepl = system.ArgumentReplacements
        %foreach replIdx = SIZE(argRepl, 1)/2
          %assign argIdx = replIdx * 2
          %assign passThroughArgs = ...
            FEVAL("regexprep", passThroughArgs, ...
            "(^|/W|,)" + argRepl[argIdx] + "($|/W|,)", ...
            "$1" + argRepl[argIdx+1] + "$2")
        %endforeach
      %endif
      %return callee.Name + kernelInvoke + "(" + argStr + sep + passThroughArgs + ")"
    %endif
  %endif
%endfunction %% SLibCGCallSubFcn
 
%%Function:SLibGetRootLevelArgDefs===========================================
%%Abstract:
%%Thisfunctionisusedtogeneratethepassthroughargumentlistforthe
%%rootsystem.Itisusedtoproperlypassinmodeldatasuchasmodelinputs
%%andoutputs(rootIO)tosubfunctionsthataredirectlycalledfromthe
%%rootsystem.
%%
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Product/rtw/tProductBlk_Codegencheck_SFcnTarget.m
%%TopTester:matlab/test/toolbox/simulink/blocks/lib_MathOperations/Product/rtw/tProductBlk_Codegencheck_ERTSFcn_Target.m
%%
%function SLibGetRootLevelArgDefs(aSystemRec, aFunctionRec) void
  %%
  %if !SLibPassThroughArgsRequired(aSystemRec)
    %return
  %endif
  %%
  %assign fcnName = aFunctionRec.Name
  %assign cTID = aSystemRec.CurrentTID
  %assign isRG = SLibSystemFcnPeriodicRateGrouping(aSystemRec, fcnName)
  %assign args = ""
  %assign argDefs = ""
  %assign comma = ""
  %assert LibSystemIsRoot(aSystemRec)
 
  %% For AUTOSAR: In multi-instance models, the only function call
  %% subsystem argument is "self".
  %if SLibAutosarActive() && aFunctionRec.IsEntryPointSubFcn
    %assign aFunctionRec.PassThroughArgDefs = "%<FcnGetMultiInstanceRunnableArgs(0)>"
    %assign aFunctionRec.PassThroughArgs = "%<FcnGetMultiInstanceRunnableArgs(1)>"
    %return
  %endif
 
  %%
  %% Root inputs
  %%
  %if CodeFormat != "S-Function"
    %%
    %assign useRootIOStructures = MultiInstanceERTCode && ...
      RootIOStructures && !GenerateClassInterface && !SLibFcnProtoCtrlActive()
    %%
    %with ::CompiledModel.ExternalInputs
      %if useRootIOStructures
        %assign rootInputsRequired = TLC_FALSE
        %foreach idx = NumExternalInputs
          %assign extInp = ExternalInput[idx]
          %if extInp.StorageClass == "Auto" && ...
            SysFcnArgNeeded(fcnName, extInp, cTID, isRG)
            %assign rootInputsRequired = TLC_TRUE
            %break
          %endif
        %endforeach
        %if rootInputsRequired
          %assign args = args + comma + ::tInput
          %assign argDefs = argDefs + comma + ::tInputType + " *" + ::tInput
          %assign comma = ", "
        %endif
      %else
        %foreach idx = NumExternalInputs
          %assign extInp = ExternalInput[idx]
          %if extInp.StorageClass == "Auto" && ...
            SysFcnArgNeeded(fcnName, extInp, cTID, isRG)
            %%
            %assign width = LibGetRecordSymbolicWidth(extInp)
            %assign optStar = " "
            %assign optWidth = width == "1" ? "" : "[%<width>]"
            %assign dType = LibGetRecordDataTypeName(extInp, "")
            %assign reqLocalAccess = extInp.RequiresGlobalAccess == "no"
            %assign argName = ""
            %%
            %if SLibFcnProtoCtrlActive()
              %if reqLocalAccess
                %assign fcnData = FcnGetFunctionPrototypeRecord()
                %assign spec = FcnGetFcnDataForPort(fcnData, "Inport", idx)
                %assign argName = spec.ArgName
                %if width == "1" && spec.Category == "Pointer"
                  %assign optStar = " *"
                %endif
              %else
                %continue
              %endif
            %elseif GenerateClassInterface
              %assign classConfObj = FcnGetRTWCPPStepPrototypeRecord()
              %if !classConfObj.hasGlobalAccessForInport && reqLocalAccess
                %assign spec = FcnGetFcnDataForPort(classConfObj, "Inport", idx)
                %assign argName = spec.ArgName
                %if width == "1" && spec.Category == "Pointer"
                  %assign optStar = " *"
                %endif
              %else
                %continue
              %endif
            %endif
            %if ISEMPTY(argName)
              %assign argName = ::tInput + UQualifier + LibGetRecordIdentifier(extInp)
              %assign dtID = LibGetRecordDataTypeId(extInp)
              %if width == "1" && SLibDeclareDataAsPointer(dtID)
                 %assign optStar = " *"
              %endif
            %endif
            %assign args = args + comma + argName
            %assign argDefs = ...
              argDefs + comma + dType + optStar + argName + optWidth
            %assign comma = ", "
          %endif
        %endforeach
      %endif
    %endwith
    %with ::CompiledModel.ExternalOutputs
      %if useRootIOStructures
        %assign rootOutputsRequired = TLC_FALSE
        %foreach idx = NumExternalOutputs
          %assign extOut = ExternalOutput[idx]
          %if SysFcnArgNeeded(fcnName, extOut, cTID, isRG)
            %assign rootOutputsRequired = TLC_TRUE
            %break
          %endif
        %endforeach
        %if rootOutputsRequired
          %assign args = args + comma + tOutput
          %assign argDefs = argDefs + comma + tOutputType + " *" + tOutput
          %assign comma = ", "
        %endif
      %else
        %foreach idx = NumExternalOutputs
          %assign extOut = ExternalOutput[idx]
          %if SysFcnArgNeeded(fcnName, extOut, cTID, isRG)
            %%
            %assign width = LibGetRecordSymbolicWidth(extOut)
            %assign optStar = " "
            %assign optWidth = width == "1" ? "" : "[%<width>]"
            %assign dType = LibGetRecordDataTypeName(extOut, "")
            %assign reqLocalAccess = extOut.RequiresGlobalAccess == "no"
            %assign argName = ""
            %%
            %if SLibFcnProtoCtrlActive()
              %if reqLocalAccess
                %assign fcnData = FcnGetFunctionPrototypeRecord()
                %assign spec = FcnGetFcnDataForPort(fcnData, "Outport", idx)
                %assign argName = spec.ArgName
                %if width == "1" && spec.Category == "Pointer"
                  %assign optStar = " *"
                %endif
              %else
                %continue
              %endif
            %elseif GenerateClassInterface
              %assign classConfObj = FcnGetRTWCPPStepPrototypeRecord()
              %if !classConfObj.hasGlobalAccessForOutport && reqLocalAccess
                %assign spec = FcnGetFcnDataForPort(classConfObj, "Outport", idx)
                %assign argName = spec.ArgName
                %if width == "1" && spec.Category == "Pointer"
                  %assign optStar = " *"
                %endif
              %else
                %continue
              %endif
            %elseif width == "1"
              %assign optStar = " *"
            %endif
            %if ISEMPTY(argName)
              %assign outpBlk = System[extOut.Block[0]].Block[extOut.Block[1]]
              %assign argName = tOutput + YQualifier + LibGetRecordIdentifier(outpBlk)
              %assign dtID = LibGetRecordDataTypeId(extOut)
              %if width == "1" && SLibDeclareDataAsPointer(dtID)
                %assign optStar = " *"
              %endif
            %endif
            %assign args = args + comma + argName
            %assign argDefs = ...
              argDefs + comma + dType + optStar + argName + optWidth
            %assign comma = ", "
          %endif
        %endforeach
      %endif
    %endwith
  %endif
  %%
  %%
  %%
  %with aSystemRec.Interface
    %if !GenerateClassInterface
      %%
      %% rtModel argument
      %%
      %if CodeFormat == "S-Function"
        %if !SLibCG_FcnHasRTMArg(aFunctionRec) && ...
          (SysFcnArgNeeded(fcnName, RTMArgDef, cTID, isRG) || ...
          SysFcnArgNeeded( fcnName, BlockIOArgDef, cTID, isRG) || ...
          SysFcnArgNeeded( fcnName, DWorkArgDef, cTID, isRG) || ...
          SysFcnArgNeeded( fcnName, ParameterArgDef, cTID, isRG) || ...
          SysFcnArgNeeded( fcnName, ContStatesArgDef, cTID, isRG) || ...
          SysFcnArgNeeded( fcnName, ContStatesDisabledArgDef, cTID, isRG) || ...
          SysFcnArgNeeded( fcnName, ContStatesAbsoluteToleranceArgDef, cTID, isRG) || ...
          SysFcnArgNeeded( fcnName, ContStatesPerturbMinArgDef, cTID, isRG) || ...
          SysFcnArgNeeded( fcnName, ContStatesPerturbMaxArgDef, cTID, isRG) || ...
          SysFcnArgNeeded( fcnName, ZCSVArgDef, cTID, isRG))
          %assign rtmArg = FcnUpdateRTModelInterfaceArg(aSystemRec, ::tSimStruct)
          %assign args = args + comma + rtmArg
          %assign argDefs = argDefs + comma + ::tSimStructType + " *" + ::tSimStruct
          %assign comma = ", "
        %endif
      %elseif MultiInstanceERTCode
        %%
        %% rtModel argument
        %%
        %assign rtmAccessed = TLC_FALSE
        %if !SLibCG_FcnHasRTMArg(aFunctionRec) && ...
          SysFcnArgNeeded(fcnName, RTMArgDef, cTID, isRG)
          %assign rtmArg = FcnUpdateRTModelInterfaceArg(aSystemRec, ::tSimStruct)
          %assign args = args + comma + rtmArg
          %assign argDefs = argDefs + comma + ::tSimStructType + " *" + ::tSimStruct
          %assign comma = ", "
          %assign rtmAccessed = TLC_TRUE
        %endif
 
        %assign sysIdx = aSystemRec.SystemIdx
        %assign thisModule = ::CompiledModel.RTWCGModules.RTWCGModule[aSystemRec.CGIRModuleIdx]
        %assign isSimpInterf = thisModule.SimplifiedInterface
        %assign useSelf = TLC_FALSE
        %if isSimpInterf
          %assign selfGroupIdx = SLibGetSelfCoderDataGroupIndex()
          %assert selfGroupIdx >= 0
          %assign selfGroup = ::CompiledModel.CoderDataGroup[selfGroupIdx]
          %assign selfGroupArgDefToken = "CoderDataGroup" + selfGroup.Name + "ArgDef"
          %if EXISTS(selfGroupArgDefToken) && SysFcnArgNeeded(fcnName, %<selfGroupArgDefToken>, cTID, isRG)
            %assign useSelf = TLC_TRUE
          %endif
        %endif
        %assign argsFullPath = args
        %%
        %% Block IO argument
        %%
        %if SysFcnArgNeeded(fcnName, BlockIOArgDef, cTID, isRG) && !useSelf
          %% Get vargroup corresponding to the base system
          %assign varGroupIdx = FcnSysVarGroupIndex(aSystemRec, "BlockIO", 0)
          %if varGroupIdx > -1
            %assign argName = VarGroups.VarGroup[varGroupIdx].Name
            %if isSimpInterf
              %% For simplified interface, BlockIO is InSelf
              %assign parentVGIdx = SLibVarGroupParentIndex(varGroupIdx)
              %assert parentVGIdx > -1
              %assign path = SLibCGIRVarGroupPath(parentVGIdx, sysIdx, aSystemRec.CrossNoArgFcnBound)
              %assign argExprFullPath = "&(" + path + argName +")"
              %assign argsFullPath = argsFullPath + comma + argExprFullPath
            %endif
          %else
            %assign argName = ::tBlockIO
          %endif
           
          %assign args = args + comma + argName
          %assign argDefs = argDefs + comma + ::tBlockIOType + " *" + argName
          %assign comma = ", "
        %endif
        %%
        %% Constant block IO (not passed in as an argument)
        %%
        %%
        %% DWork argument
        %%
        %if SysFcnArgNeeded(fcnName, DWorkArgDef, cTID, isRG) && !useSelf
          %% Get vargroup corresponding to the base system
          %assign varGroupIdx = FcnSysVarGroupIndex(aSystemRec, "DWork", 0)
          %if varGroupIdx > -1
            %assign argName = VarGroups.VarGroup[varGroupIdx].Name
            %if isSimpInterf
              %assign parentVGIdx = SLibVarGroupParentIndex(varGroupIdx)
              %assert parentVGIdx > -1
              %assign path = SLibCGIRVarGroupPath(parentVGIdx, sysIdx, aSystemRec.CrossNoArgFcnBound)
              %assign argExprFullPath = "&(" + path + argName +")"
              %assign argsFullPath = argsFullPath + comma + argExprFullPath
            %endif
          %else
            %assign argName = ::tDWork
          %endif
 
          %assign args = args + comma + argName
          %assign argDefs = argDefs + comma + ::tDWorkType + " *" + argName
          %assign comma = ", "
        %endif
        %%
        %% Parameter H-Struct argument
        %%
        %if SysFcnArgNeeded(fcnName, ParameterArgDef, cTID, isRG)
          %assign args = args + comma + ::tParameters
          %assign argDefs = argDefs + comma + ::tParametersType + " *" + ::tParameters
          %assign argsFullPath = argsFullPath + comma + ::tParameters
          %assign comma = ", "
        %endif
        %%
        %% Continuous States argument
        %%
        %if SysFcnArgNeeded(fcnName, ContStatesArgDef, cTID, isRG)
          %assign args = args + comma + ::tContState
          %assign argDefs = argDefs + comma + ::tContStateType + " *" + ::tContState
          %assign comma = ", "
        %endif
        %%
        %% Continuous States Disabled argument
        %%
        %if SysFcnArgNeeded(fcnName, ContStatesDisabledArgDef, cTID, isRG)
          %assign args = args + comma + ::tXdis
          %assign argDefs = argDefs + comma + ::tXdisType + " *" + ::tXdis
          %assign comma = ", "
        %endif
        %%
        %% Continuous States Absolute Tolerance argument
        %%
        %if SysFcnArgNeeded(fcnName, ContStatesAbsoluteToleranceArgDef, cTID, isRG)
          %assign args = args + comma + ::tXAbsTol
          %assign argDefs = argDefs + comma + ::tXAbsTolType + " *" + ::tXAbsTol
          %assign comma = ", "
        %endif
        %%
        %% Continuous States Perturb Min argument
        %%
        %if SysFcnArgNeeded(fcnName, ContStatesPerturbMinArgDef, cTID, isRG)
          %assign args = args + comma + ::tXPerturbMin
          %assign argDefs = argDefs + comma + ::tXPerturbMinType + " *" + ::tXPerturbMin
          %assign comma = ", "
        %endif
        %%
         
        %% Continuous States Perturb Max argument
        %%
        %if SysFcnArgNeeded(fcnName, ContStatesPerturbMaxArgDef, cTID, isRG)
          %assign args = args + comma + ::tXPerturbMax
          %assign argDefs = argDefs + comma + ::tXPerturbMaxType + " *" + ::tXPerturbMax
          %assign comma = ", "
        %endif
        %%
        %%
         
         
        %% ZcSignalValue argument
        %%
        %if SysFcnArgNeeded(fcnName, ZCSVArgDef, cTID, isRG)
          %assign args = args + comma + ::tZCSignalValue
          %assign argDefs = argDefs + comma + ::tZCSignalValueType + " *" + ...
            ::tZCSignalValue
          %assign comma = ", "
        %endif
        %%
        %% Zero Crossing Event argument
        %%
        %if SysFcnArgNeeded(fcnName, ZCEventArgDef, cTID, isRG)
          %assign args = args + comma + ::tPrevZCState
          %assign argDefs = argDefs + comma + ::tPrevZCStateType + " *" + ...
            ::tPrevZCState
          %assign comma = ", "
        %endif
        %%
        %% Coder Group argument
        %%
        %foreach coderGroupIndex = ::CompiledModel.NumCoderDataGroups
          %assign coderGroup = ::CompiledModel.CoderDataGroup[coderGroupIndex]
          %assign coderGroupArgDefToken = "CoderDataGroup" + coderGroup.Name + "ArgDef"
          %% Skip the coder data group if it is already added (e.g. synthesized self added as RTM),
          %% or can be accessed through self.
          %assign skipGroup = SLibIsSynthesizedRTM(coderGroup) && rtmAccessed || ...
            SLibIsSelfStructured() && !coderGroup.IsSelf && SLibAccessGroupThroughSelf(coderGroup)
          %if skipGroup
            %continue
          %endif
          %if EXISTS(coderGroupArgDefToken) && SysFcnArgNeeded(fcnName, %<coderGroupArgDefToken>, cTID, isRG)
            %assign coderGroupVarGroup = SLibVarGroupForCoderGroup(coderGroup)
            %assign argToken = "::tCoderDataGroup" + coderGroup.Name
            %assign argName = coderGroup.IsSelf ? ...
              coderGroupVarGroup.SelfStructureArgumentName : %<argToken>
 
            %% Make sure arg is not already added in the function interface for outlined block functions
            %assign coderGroupAccessed = TLC_FALSE
            %if aFunctionRec.IsOutlinedBlockFcn
              %foreach argIdx = aFunctionRec.NumArgs
                %if aFunctionRec.ArgNames[argIdx] == argName ...
                  && aFunctionRec.ArgAccessed[argIdx] > 0
                  %assign coderGroupAccessed = TLC_TRUE
                  %break
                %endif
              %endforeach
            %endif
            %if coderGroupAccessed
              %continue
            %endif
 
            %assign typeToken = argToken + "Type"
            %assign typeName = coderGroup.IsSelf ? ...
              coderGroupVarGroup.SelfStructureTypeName : %<typeToken>
            %assign args = args + comma + argName
            %assign argsFullPath = argsFullPath + comma + argName
            %assign argDefs = argDefs + comma + typeName + " *" + argName
            %assign comma = ", "
          %endif
        %endforeach
         
        %assert MultiInstanceERTCode
        %addtorecord aFunctionRec PassThroughArgsFullPath argsFullPath
         
        %%
        %% ZCEvent H-Struct argument **** part of dwork
        %%
        %%
        %% Canonical Parameters *** not applicable for the root system
        %%
        %%
        %% CanonicalDWork *** not applicable for the root system
        %%
      %endif
    %endif
  %endwith
  %assign aFunctionRec.PassThroughArgDefs = argDefs
  %assign aFunctionRec.PassThroughArgs = args
%endfunction
 
%%Function:FcnResetModelRefLocalVars=========================================
%%Abstract:
%%Resetsthecachedmodelreferencelocalvariabledeclarationfor
%%givenfunction(throughmoduleandfunctionindex).
%%
%function FcnResetModelRefLocalVars(aModule, aSubFcnIdx) void
  %assign fcn = aModule.Function[aSubFcnIdx]
  %assign system = ::CompiledModel.System[aModule.CGSystemIdx]
  %<SLibResetModelRefLocalVars(system, fcn.Name, "")>
%endfunction
 
%%Function:FcnGenerateSubFcnBody=============================================
%%Abstract:
%%Generatesandreturnsthefunctionbodyforagivensub-function
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1331407_VC1.m
%function FcnGenerateSubFcnBody(aOpaqueBlock, aModule, aSubFcnIdx, aCalledFromChildMod) void
  %assert -1 == ::CurrentFunctionIdx
  %assign ::CurrentFunctionIdx = aSubFcnIdx
  %assign fileName = aModule.TLCFileName + "_Functions"
  %assign fcn = aModule.Function[aSubFcnIdx]
  %assign fcnName = fcn.Name
  %assign system = ::CompiledModel.System[::CompiledModel.System[aModule.CGSystemIdx].NonInlinedParentSystemIdx]
  %assign lboDef = ::CompiledModel.BlockOutputs.LocalBlockOutputDefaults
  %assign ldwDef = ::CompiledModel.DWorks.DWorkDefaults
  %assign callerFcn = ::BlockFcn
  %assign ::BlockFcn = fcnName
  %<LibSetGlobalSysFcnsForArgAccess([])>
  %assign sysField = fcnName + "Fcn"
  %if !ISFIELD(system, sysField)
    %addtorecord system %<sysField> fcnName
  %endif
  %assign localRecordField = "DeclareIn" + fcnName + "FcnScope"
  %if !ISFIELD(lboDef, localRecordField)
    %addtorecord lboDef %<localRecordField> 0
  %endif
  %if !ISFIELD(ldwDef, localRecordField)
    %addtorecord ldwDef %<localRecordField> 0
  %endif
  %assign ::GlobalGeneratingSubFunctions = TLC_TRUE
  %assign system.GeneratingSubFunctions = TLC_TRUE
  %assign reusedParent = ::CompiledModel.System[system.ReusedParentSystemIdx]
  %assign isScalableMRSys = ...
        IsModelReferenceBaseSys(reusedParent) && IsModelRefScalableBuild()
  %with system
    %assign tlcFcnName = fcnName + "_Fcn%<aSubFcnIdx>"
    %assign fcnBody = GENERATE_TYPE(aOpaqueBlock, tlcFcnName, fileName)
    %if aCalledFromChildMod
      %<SLibCopyRootInputsArgAccessedFlags(system, fcnName)>
      %<SLibCopyArgAccessedFlags(aModule.CGSystemIdx, fcnName, callerFcn, ...
        system.CurrentTID, isScalableMRSys)>
    %endif
  %endwith
  %if !fcn.IsShared
    %if LibSystemIsRoot(system)
      %<SLibGetRootLevelArgDefs(system, fcn)>
    %else
      %assign fcnInfo = SLibSystemFcnInfoRecord(system, fcnName)
      %assign passThroughArgDefs = fcnInfo.Params
      %%
      %if !ISEMPTY(passThroughArgDefs) && !WHITE_SPACE(passThroughArgDefs)
        %assign fcn.PassThroughArgDefs = passThroughArgDefs
        %assign fcn.PassThroughArgs = ...
          FEVAL("rtwprivate", "getargstr", passThroughArgDefs)
      %endif
      %if isScalableMRSys && TLC_TRUE == reusedParent.ContainsNonreusedFcn
        %<SLibAccessMdlRefGlobals(fcn)>
      %endif
    %endif
  %endif
  %assign ::GlobalGeneratingSubFunctions = TLC_FALSE
  %assign system.GeneratingSubFunctions = TLC_FALSE
  %%
  %assign ::BlockFcn = callerFcn
  %assert ::CurrentFunctionIdx == aSubFcnIdx
  %assign ::CurrentFunctionIdx = -1
  %return fcnBody
%endfunction
 
%%Function:SLibFcnHasArgs====================================================
%%Abstract:
%%Returnstrueifafunctionhasanyargumentsthathavebeenaccessed.
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/tg1375551.m
%%
%function SLibFcnHasArgs(aFcnRecord) void
  %foreach argIdx = aFcnRecord.NumArgs
    %if aFcnRecord.ArgAccessed[argIdx] > 0
      %return TLC_TRUE
    %endif
  %endforeach
  %return TLC_FALSE
%endfunction %% SLibFcnHasArgs
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/tg1375551.m
%%
%function FcnGetSubFcnGlobalVars(system, fcn) void
  %if !fcn.IsEntryPointSubFcn
    %return ""
  %endif
   
  %assign saveBlockFcn = ::BlockFcn
  %assign ::BlockFcn = fcn.Name
  %assign backTID = system.CurrentTID
  %assign system.CurrentTID =fcn.FcnTID
  %assign globalVars = LibInitializeGlobalVars(system, fcn.Name)
  %assign system.CurrentTID = backTID
  %assign ::BlockFcn = saveBlockFcn
   
  %return globalVars
%endfunction %% FcnGetSubFcnGlobalVars
 
%%Function:FcnGenMatFileIterationWrapperFunctionPrototype================================================
%%Description:
%%Generatetheprototyeforthebasicloopingwrapperfunction
%%
%function FcnGenMatFileIterationWrapperFunctionPrototype(fcnName)
  %return "void %<fcnName>_wrapper_loop(void* pMatrix, const void* aMatrix, int iterations)"
%endfunction
 
%%Function:FcnGenMatFileNWrapperFunctionPrototype================================================
%%Description:
%%GeneratetheprototyeforaNwrapperfunction
%%
%function FcnGenMatFileNWrapperFunctionPrototype(fcnName, iterations)
  %return "void %<fcnName>_wrapper%<iterations>(void* pMatrix, const void* aMatrix)"
%endfunction
 
%%Function:FcnGenMatFileNWrapperFunctionPrototypes================================================
%%Description:
%%GeneratetheprototyesforallNwrapperfunctionsofagivenfcn
%%
%function FcnGenMatFileNWrapperFunctionPrototypes(fcn)
  %assign fcnPrototypes = ""
  %if ISFIELD(fcn, "LoggingNWrappers")
    %foreach iterationIndex = fcn.NumLoggingNWrappers
      %assign iterations = fcn.LoggingNWrappers[iterationIndex]
      %assign fcnPrototypes = fcnPrototypes + FcnGenMatFileNWrapperFunctionPrototype(fcn.Name, iterations) + ";/n"
    %endforeach
  %endif
  %return fcnPrototypes
%endfunction
 
%%Function:FcnGenMatFileLoggingWrapperFunctionPrototype================================================
%%Description:
%%Generatetheprototypeforthebasewrapperfunction
%%
%function FcnGenMatFileLoggingWrapperFunctionPrototype(fcn)
  %assign fcnProto = ""
  %if ISFIELD(fcn, "NumArgs") && fcn.NumArgs > 0 && ...
      ISFIELD(fcn, "LoggingWrapperType") && fcn.LoggingWrapperType == "Simple"
    %assign fcnProto = "void %<fcn.Name>_wrapper(void* pMatrix, const void* aMatrix)"
  %endif
  %return fcnProto
%endfunction
 
%%Function:FcnGenAllMatFileWrapperFunctionPrototypes================================================
%%Description:
%%Generatetheprototyesforallwrapperfunctionsofagivenfcn
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/-tVariantSimulinkFunctionAutoInherit.m
%%
%function FcnGenAllMatFileWrapperFunctionPrototypes(fcn)
  %assign fcnPrototypes = FcnGenMatFileLoggingWrapperFunctionPrototype(fcn)
  %if fcnPrototypes != "" && ISFIELD(fcn, "LoggingNWrappers")
    %assign fcnName = fcn.Name
    %if fcn.NumLoggingNWrappers == 1
      %assign iterations = fcn.LoggingNWrappers[0]
      %assign fcnPrototypes = fcnPrototypes + ";/n" + ...
        FcnGenMatFileNWrapperFunctionPrototype(fcnName, iterations)
    %else
      %assign fcnPrototypes = fcnPrototypes + ";/n" + ...
        FcnGenMatFileIterationWrapperFunctionPrototype(fcnName)
      %foreach iterationIndex = fcn.NumLoggingNWrappers
        %assign iterations = fcn.LoggingNWrappers[iterationIndex]
        %assign fcnPrototypes = fcnPrototypes + ";/n" + ...
          FcnGenMatFileNWrapperFunctionPrototype(fcnName, iterations)
      %endforeach
    %endif
  %endif
  %return fcnPrototypes
%endfunction
 
%%Function:FcnGenMatFileLoggingWrapperFunction================================================
%%Description:
%%Cacheallcodeformatfileloggingwrapperfunctions
%%
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Product/rtw/tRowMajorEMLSupport.m
%%
%function FcnGenMatFileLoggingWrapperFunction(fcn)
  %openfile fcnBuffer
  %if ISFIELD(fcn, "NumArgs") && fcn.NumArgs > 0 && ...
      ISFIELD(fcn, "LoggingWrapperType") && fcn.LoggingWrapperType == "Simple"
    %assign argType = fcn.ArgTypes[0]
    %assign baseName = SLibGetTypeNameFromCGType(argType)
    %assign fcnName = fcn.Name
 
    %<FcnGenMatFileLoggingWrapperFunctionPrototype(fcn)>
    {
      %<baseName>* bpMatrix = (%<baseName>*) pMatrix;
      const %<baseName>* baMatrix = (const %<baseName>*) aMatrix;
      %<fcnName>(baMatrix, bpMatrix);
    }
     
    %if ISFIELD(fcn, "LoggingNWrappers")
      %assign width = fcn.LoggedTypeWidth
      %if fcn.NumLoggingNWrappers == 1
        %assign iterations = fcn.LoggingNWrappers[0]
        %<FcnGenMatFileNWrapperFunctionPrototype(fcnName, iterations)>
        {
          %<baseName>* bpMatrix = (%<baseName>*) pMatrix;
          const %<baseName>* baMatrix = (const %<baseName>*) aMatrix;
          int i = 0;
          while(i < %<iterations>)
          {
            %<fcnName>(baMatrix + i * %<width>, bpMatrix + i * %<width>);
            i = i + 1;
          }
        }
      %else
        %<FcnGenMatFileIterationWrapperFunctionPrototype(fcnName)>
        {
          %<baseName>* bpMatrix = (%<baseName>*) pMatrix;
          const %<baseName>* baMatrix = (const %<baseName>*) aMatrix;
          int i = 0;
          while(i < iterations)
          {
            %<fcnName>(baMatrix + i * %<width>, bpMatrix + i * %<width>);
            i = i + 1;
          }
        }
        %foreach iterationIndex = fcn.NumLoggingNWrappers
          %assign iterations = fcn.LoggingNWrappers[iterationIndex]
          %<FcnGenMatFileNWrapperFunctionPrototype(fcnName, iterations)>
          {
            %<fcn.Name>_wrapper_loop(pMatrix, aMatrix, %<iterations>);
          }
        %endforeach
      %endif
    %endif
  %endif
  %closefile fcnBuffer
  %return fcnBuffer
%endfunction
 
%%Function:SLibGenNotReusableModuleSubFunctionAsClassMemFcn
%%Shouldasubfunctioncalledbyasubsystemthatisnotreusable
%%begeneratedasamemberfunctioninthemodelclass?
%function SLibGenNotReusableModuleSubFunctionAsClassMemFcn(system)
  %assign result = GenerateClassInterface && ...
                   !IsModelReferenceBaseSys(system) && ...
                   !LibSystemIsReusedFcn(system)
  %return result
%endfunction
 
%%Function:SLibGenModuleSubFunctionAsClassMemFcn
%%Shouldasubfunctioncalledbyasubsystem
%%begeneratedasamemberfunctioninthemodelclass?
%function SLibGenModuleSubFunctionAsClassMemFcn(system)
  %if !SLibReusableSubsystemCppEncapEnabled()
    %return SLibGenNotReusableModuleSubFunctionAsClassMemFcn(system)
  %endif
 
  %assign result = GenerateClassInterface && ...
                   !IsModelReferenceBaseSys(system) && ...
                   !LibSystemIsReusedLibraryFcn(system)
  %return result
%endfunction
 
%%Function:SLibModuleHasMissingArgs==========================================
%%Abstract:
%%Returnstrueiffunctioncallsinsubfunctionhavemissingarguments
%%inagivenmodule
%%
%function SLibModuleHasMissingArgs(aModule, aTestInterfaceFcnIdx) void
  %assign hasMissingArgs = TLC_FALSE
  %foreach fcnIdx = aModule.NumSubFunctions
    %if fcnIdx != aTestInterfaceFcnIdx
      %assign fcn = aModule.Function[fcnIdx]
      %%
      %% Reset the flag that indicates HasPassThroughArgsAtCall has been set
      %%
      %assign fcn.HasPassThroughArgsAtCallSet = TLC_FALSE
      %%
      %% If fcn.PassThroughArgs doesn't match HasPassThroughArgsAtCall, then
      %% we have a callsite to this function with a none matching argument list.
      %% In thid case we have to continue with the argument propagation.
      %%
      %if !ISEMPTY(fcn.PassThroughArgs) != fcn.HasPassThroughArgsAtCall
         %assign hasMissingArgs = TLC_TRUE
      %endif
    %endif
  %endforeach
  %return hasMissingArgs
%endfunction
   
   
%%Function:FcnGenModuleSubFunctions==========================================
%%Abstract:
%%Thisfunctiongeneratesthesubfunctionscalledbysystemfunctionsin
%%themodule.Eachfunctionisgeneratedseparatelyusingitsownfunction
%%typeforargumenttracking.Thefunctionsaregeneratedinreverse
%%callgraphorder.
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/tg1375551.m
%%TopTester:test/toolbox/simulink/variants/flexibleVariants/tFlexibleVariantsCodeGen2.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/dimensionVariants/tDimensionVariants9.m
%%TopTester:test/toolbox/simulink/variants/tVariantManager3.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tVariantSource7.m
%%
%function FcnGenModuleSubFunctions(module, testInterfaceFcnIdx) void
  %assign block = FcnRootOpaqueBlock()
  %assign fileName = module.TLCFileName + "_Functions"
  %assign system = ::CompiledModel.System[module.CGSystemIdx]
  %assign system.CurrentTID = ""
  %assign genSharedUtils = (::CompiledModel.GenUtilsSrcInSharedLocation == 1)
  %assign useEncapsCPP = ::GenerateClassInterface && ...
    (IsBaseSystem(system) || SLibGenModuleSubFunctionAsClassMemFcn(system))
  %%
   
  %if module.HasRecursion && ...
    (module.HasOptAccessArgs || SLibPassThroughArgsRequired(system))
    %assign numRecursions = 0
    %%
    %% Recurse until we have no missing arguments
    %%
    %foreach recursionIdx = module.NumSubFunctions
      %foreach fcnIdx = module.NumSubFunctions
        %if fcnIdx != testInterfaceFcnIdx
          %<FcnGenerateSubFcnBody(block, module, fcnIdx,TLC_FALSE)>
        %endif
      %endforeach
      %assign numRecursions = numRecursions + 1
      %if !SLibModuleHasMissingArgs(module, testInterfaceFcnIdx)
        %break
      %endif
    %endforeach
    %%
    %% Assert that the argument propagation converges before we reach
    %% maximum necessary interations.
    %%
    %assert numRecursions < module.NumSubFunctions
    %%
    %if IsModelReferenceBaseSys(system) && IsModelRefScalableBuild() && ...
      !::GenerateClassInterface
      %foreach fcnIdx = module.NumSubFunctions
        %if fcnIdx != testInterfaceFcnIdx
          %<FcnResetModelRefLocalVars(module, fcnIdx)>
        %endif
      %endforeach
    %endif
  %endif
  %%
   
  %assign notRootFileName = NotRootFileName(system)
  %assign needNamespace = TLC_FALSE
   
  %assign exported = ""
  %assign entryPoint = ""
  %assign subFcnProt = ""
  %assign shaFcnProt = "" %% shared function prototypes
  %assign subFcnCode = ""
  %assign inlineProt = ""
  %assign inlineCode = ""
  %assign extApiProt = ""
  %assign extApiCode = ""
  %assign memberProt = ""
  %openfile exported
  %openfile entryPoint
  %openfile subFcnProt
  %openfile subFcnCode
  %openfile shaFcnProt
  %openfile inlineProt
  %openfile inlineCode
  %openfile extApiProt
  %openfile extApiCode
  %openfile memberProt
  %foreach fcnIdx = module.NumSubFunctions
    %if fcnIdx == testInterfaceFcnIdx || ...
      module.Function[fcnIdx].IsAlreadyEmitted
      %continue
    %endif
    %assign fcn = module.Function[fcnIdx]
    %assign prevBlockFcn = ::BlockFcn
    %assign ::BlockFcn = fcn.Name
    %if fcn.IsShared
      %<LibPushEmptyStackSharedUtils()>
    %endif
    %assign fcnBody = FcnGenerateSubFcnBody(block, module, fcnIdx,TLC_FALSE)
    %assign hasPassThroughArgs = !ISEMPTY(fcn.PassThroughArgs)
    %assign globalVars = FcnGetSubFcnGlobalVars(system,fcn)
    %if hasPassThroughArgs
      %assign passThroughArgDefs = fcn.PassThroughArgDefs
    %else
      %assign passThroughArgDefs = ""
    %endif
    %assign fcnClose = ")"
    %assign seperator = ", "
    %assign hasArgs = SLibFcnHasArgs(fcn)
    %if !hasArgs || !hasPassThroughArgs
      %assign seperator = ""
      %if !hasArgs && !hasPassThroughArgs
        %assign fcnClose = "void)"
      %endif
    %endif
    %assign fcnProto = fcn.ProtoType + seperator + passThroughArgDefs + fcnClose
    %assign fcnProto = FEVAL("regexprep", fcnProto, "//()", "(void)")
    %assign localVars = ...
      fcn.HasLocalData ? FcnDeclareAccessedLocalVariables(system) : ""
    %%
    %% Function prototype dispatching
    %%
    %selectfile NULL_FILE
    %assign extern = ""
    %assign repFcn = ""
    %if fcn.IsShared
      %if !genSharedUtils
        %if !SLibLookupUtilityDecl(fcn.Name)
          %<SLibInsertUtilityDecl(fcn.Name)>
          %selectfile shaFcnProt
        %endif
      %endif
    %elseif useEncapsCPP
      %assign fcnProto = FEVAL("regexprep", fcnProto, "^static/W*", "", "once")
      %assign fcnProto = FEVAL("regexprep", fcnProto, "^extern/W*", "", "once")
      %selectfile memberProt
    %elseif fcn.IsExported || fcn.IsExportedImport
      %if fcn.IsEntryPointSubFcn
        %assign rtnTypeStr = ...
          SLibAutosarCompilerAbstractionForFcnDeclRtnType("void", "FuncCalledByRTE", "")
        %assign fcnProto = FEVAL("regexprep", fcnProto, "void", rtnTypeStr, "once")
        %selectfile entryPoint
      %else
        %selectfile exported
      %endif
    %else
      %selectfile subFcnProt
    %endif
     
    %if !fcn.IsAccessMethod
      %openfile guardedProto
 
      %if !fcn.IsShared
        %% Should fcn => system ??
        %<SLibIfSystemVariantCondition(fcn)>
      %endif
 
      %<SLibGetFcnMemSecPragmaForSystemOnDecl(fcn.Name, "MemSecFuncSharedUtil", "Pre", system)>/
      %<extern> %<fcnProto>;
      %<SLibGetFcnMemSecPragmaForSystemOnDecl(fcn.Name, "MemSecFuncSharedUtil", "Post", system)>/
      %if !fcn.IsShared
        %<SLibEndIfSystemVariantCondition(fcn)>
      %endif
 
      %closefile guardedProto
     
      %if ISFIELD(fcn, "HeaderFile") && ...
        !ISEMPTY(fcn.HeaderFile) && ...
        (fcn.DefinitionFile != system.SystemHeaderFileName) && ...
        !SLibIsCompactFileFormat()
         
        %assign modelTypesHeader = SLibGetFileNameForCode("mdl_types_hdr") + ".h"
        %assign declFileName = SLibGetFileNameWithoutExtension(fcn.HeaderFile)
        %assign declFile = SLibAddModelFile("SystemHeader", "Simulink", declFileName)
        %assign declFileGroup = "interface"
        %<SLibSetModelFileAttribute(declFile, "Group", declFileGroup)>
         
        %<SLibSetModelFileAttribute(declFile, "RequiredIncludes", "rtwtypes.h")>
        %<SLibSetModelFileAttribute(declFile, "RequiredIncludes", modelTypesHeader)>
        %<SLibSetModelFileAttribute(declFile, "Declarations", guardedProto)>
      %else
        %<guardedProto>
      %endif
    %endif
  
    %selectfile NULL_FILE
 
    %%
    %% Function body code generation
    %%
    %assign fcnComment = ""
    %if !ISEMPTY(fcn.BlockName) && !ISEMPTY(fcn.BlockType)
      %assign fcnType = ""
      %if !ISEMPTY(fcn.FunctionType)
        %assign fcnType = fcn.FunctionType + " function"
      %else
        %assign fcnType = "Function"
      %endif
      %assign fcnComment = "%<fcnType> for " + fcn.BlockType + ...
        ": '" + fcn.BlockName + "'"
    %endif
    %if !ISEMPTY(fcn.Abstract)
      %if !ISEMPTY(fcnComment)
        %assign fcnComment = fcnComment + "/n"
      %endif
      %assign fcnComment = fcnComment + fcn.Abstract
    %endif
    %assign fcnDefinition = ""
    %openfile fcnDefinitionHeader
    %%
    %% Shared function handling
    %%
    %if fcn.IsShared
      %if genSharedUtils
        %assign headers = fcn.FcnHeaders
        %assign numHeaders = SIZE(headers, 1)
        %foreach idx = numHeaders
          %assign header = ::CompiledModel.RTWCGStrings[headers[idx]]
          %% hasTLCGenCallBack=false; isGeneratedUtility=true
          %<FcnTrackHeaderFileUsage(header, TLC_FALSE, TLC_TRUE)>
        %endforeach
      %endif
    %endif
    %%
    %if useEncapsCPP && !fcn.IsShared
      %assign memberFcnName = CPPClassName + "::" + fcn.Name
      %assign fcnProtoForDef = ...
        FEVAL("regexprep", fcnProto, fcn.Name, memberFcnName, "once")
    %else
      %assign fcnProtoForDef = fcnProto
      %% If the prototype is for an exported function, and
      %% we're preserving extern in fcn declarations, the prototype
      %% will have an extern in it. This is not want we want for
      %% the function definition prototype; strip it off.
      %if fcn.IsExported && LibPreserveExternInFcnDecls()
        %assign fcnProtoForDef = FEVAL("regexprep", fcnProtoForDef, "extern/W*", "", "once")
      %endif
    %endif
     
    %%reset needNamespace for each loop
    %assign needNamespace = TLC_FALSE
    %if useEncapsCPP && !fcn.IsShared
        %assign needNamespace = SLibSystemNeedsNamespace(system)
    %endif
     
    %%
    %% Sub-functions are MemSecFuncSharedUtil
    %%
    %assign msFcnType = "MemSecFuncSharedUtil"
    %assign generatedFor = FcnGeneratedFor(system)
    %if fcn.IsShared
      %assign fcn_category = "utility"
    %else
      %assign fcn_category = "model"
    %endif
    %createrecord fcnInfo { Name fcn.Name; Returns ""; ...
      Params passThroughArgDefs; Abstract fcnComment; Category fcn_category; ...
      GeneratedBy "commonbodlib.tlc"; Type "Sub"; GeneratedFor generatedFor }
    %%
    %if needNamespace
     %<SLibEmitNamespaceStartForSystem(system)>
    %else
      %% before dumping a non-member function, close the namespace if it is opened
      %% when fcn.IsShared and genSharedUtils, should not affect namespace here because it is generated to other file
      %if (fcn.IsShared && !genSharedUtils)
        %<SLibEmitNamespaceCloseForSystem(system)>
      %endif
    %endif
         
    %<SLibDumpFunctionBanner(fcnInfo)>
    %closefile fcnDefinitionHeader
    %openfile fcnCommonBody
    %if !fcn.IsShared
      %<SLibIfSystemVariantCondition(fcn)>
    %endif
    %<fcnProtoForDef>
    {
      %if SLibAutosarActive() && MultiInstanceERTCode && fcn.IsEntryPointSubFcn
        %% For Autosar we need to fetch PIM structures (e.g., Block I/O,
        %% DW, RTM) into local variables.
        %assign blkFcnLocalVars = SLibDumpLocalVariablesForBlockFcn(rootSystem, fcn.Name)
        %if !ISEMPTY(blkFcnLocalVars)
          %<blkFcnLocalVars>
        %endif
      %endif
      %assign mrLocalVars = FcnDumpMRLocalVars(system, fcn.Name, "")
      %if !ISEMPTY(mrLocalVars)
        %<mrLocalVars>
      %endif
      %if !ISEMPTY(localVars)
        %if TYPE(localVars) == "Vector"
          %
        %else
          %assert TYPE(localVars) == "String"
          %<localVars>
        %endif
      %endif
      %if !ISEMPTY(globalVars) && !WHITE_SPACE(globalVars)
        %<globalVars>
        {
      %endif
          %<fcnBody>
      %if !ISEMPTY(globalVars) && !WHITE_SPACE(globalVars)
        }
      %endif
    }
    %if fcn.IsShared
      %assign wrapperBody = FcnGenMatFileLoggingWrapperFunction(fcn)
      %<wrapperBody>
    %endif
    %if !fcn.IsShared
      %<SLibEndIfSystemVariantCondition(fcn)>
    %endif
    %closefile fcnCommonBody
 
    %if fcn.IsShared
      %if !SLibLookupUtility(fcn.Name)
        %<SLibInsertUtility(fcn.Name)>
        %if genSharedUtils
          %% Create function definition buffer without Pragma
          %% to avoid duplicated pragmas after calling SLibDumpUtilsSourceCode
          %openfile fcnDefinitionNOPragma
          %<fcnDefinitionHeader>
          %<fcnCommonBody>
          %closefile fcnDefinitionNOPragma
          %assign wrapperProto = FcnGenAllMatFileWrapperFunctionPrototypes(fcn)
          %if wrapperProto != ""
            %assign wrapperProto = wrapperProto + ";/n"
          %endif
          %assign fcnProtoForUtil = fcnProto + ";/n" + wrapperProto
          %<SLibDumpUtilsSourceCode(fcn.Name, fcnProtoForUtil, fcnDefinitionNOPragma)>
        %else
          %selectfile subFcnCode
        %endif
      %endif
    %else
      %selectfile subFcnCode
    %endif
    %if fcn.IsShared
      %assign includesBuf = LibPopStackSharedUtilsIncludes()
    %endif
         
    %% create function definition buffer with Pragma wrapped
    %openfile fcnDefinition
    %if fcn.IsOutlinedBlockFcn
      /* RateTransition function %<fcn.Name> */
    %endif
    %<fcnDefinitionHeader>
    %if ISFIELD(fcn, "AccessFunctionMemorySectionUUID")
      %<SLibGetFcnMemSecPragmaForAccessMethod(fcn, "Pre")>
    %else
      %<SLibGetFcnMemSecPragmaForSystem(fcn.Name, msFcnType, "Pre", system)>
    %endif
    %<fcnCommonBody>
    %if ISFIELD(fcn, "AccessFunctionMemorySectionUUID")
      %<SLibGetFcnMemSecPragmaForAccessMethod(fcn, "Post")>
    %else
      %<SLibGetFcnMemSecPragmaForSystem(fcn.Name, msFcnType, "Post", system)>
    %endif
    %closefile fcnDefinition
    %if !fcn.IsExportedImport
      %if ISFIELD(fcn, "DefinitionFile") && ...
        !ISEMPTY(fcn.DefinitionFile) && ...
        (fcn.DefinitionFile != system.SystemSourceFileName) && ...
        !SLibIsCompactFileFormat()
        %assign defFileName = SLibGetFileNameWithoutExtension(fcn.DefinitionFile)
        %assign defFileMatchesSubsystemFile = ISEQUAL(defFileName, system.SystemSourceFileName)
        %assign defFile = SLibAddModelFile("SystemBody", "Simulink", defFileName)
        %assign defFileGroup = "interface"
        %<SLibSetModelFileAttribute(defFile, "Group", defFileGroup)>
         
        %<SLibSetModelFileAttribute(defFile, "RequiredIncludes", "rtwtypes.h")>
        %if ISFIELD(fcn,"HeaderFile") && !ISEMPTY(fcn.HeaderFile) && !defFileMatchesSubsystemFile
          %<SLibSetModelFileAttribute(defFile, "RequiredIncludes", fcn.HeaderFile)>
        %endif
        %if defFileName != LibGetMdlSrcBaseName() %% g1806081
          %assign modelHeader = SLibGetFileNameForCode("mdl_hdr") + ".h"
          %<SLibSetModelFileAttribute(defFile, "RequiredIncludes", modelHeader)>
          %if !SLibIsCompactFileFormat()
            %assign modelPrivHeader = SLibGetFileNameForCode("mdl_priv_hdr") + ".h"
            %<SLibSetModelFileAttribute(defFile, "RequiredIncludes", modelPrivHeader)>
          %endif
        %endif
        %<SLibSetModelFileAttribute(defFile, "Functions", fcnDefinition)>
      %else
        %<fcnDefinition>
      %endif
    %endif
    %assign ::BlockFcn = prevBlockFcn
  %endforeach %% fcnIdx = module.NumSubFunctions
  %if system.SystemNamespaceFlag == 1
    %selectfile subFcnCode
    %<SLibEmitNamespaceCloseForSystem(system)>
  %endif
  %closefile memberProt
  %closefile extApiCode
  %closefile extApiProt
  %closefile inlineCode
  %closefile inlineProt
  %closefile subFcnCode
  %closefile subFcnProt
  %closefile shaFcnProt
  %closefile exported
  %closefile entryPoint
  %assign unused = UNLOAD_GENERATE_TYPE(block, fileName)
  %%
  %<LibSetSystemField(system, "CachedSubFunctions", subFcnCode)>
  %%
  %if !WHITE_SPACE(subFcnProt)
    %assign comment = "/* Forward declaration for local functions *//n"
    %assign subFcnProt = comment + subFcnProt
    %<SLibCacheSystemCodeToFile("sys_sub_fcn_fwd_decl", system, subFcnProt)>
  %endif
  %%
  %if !WHITE_SPACE(shaFcnProt)
    %<SLibCacheCodeToFile("mdl_priv_fcn_decl", shaFcnProt)>
  %endif
  %%
  %if !WHITE_SPACE(entryPoint)
    %openfile entryPointBuf
     
    /* Exported entry point functions */
    %<entryPoint>
    %closefile entryPointBuf
    %if SLibAutosarActive()
      %if !ISFIELD(::CompiledModel.RTWAutosar,"ExportedFunctionDecls")
        %addtorecord ::CompiledModel.RTWAutosar ExportedFunctionDecls entryPointBuf
      %endif
    %else
      %<SLibCacheSystemCodeToFile("sys_fcn_decl", system, entryPointBuf)>
    %endif
  %endif
  %%
  %if !WHITE_SPACE(exported)
    %assign comment = "/* Exported functions */"
    %assign exportedFcn = comment + exported
    %assign exported = ...
      GetHideChildDefineSymbol("ifndef") + ...
      exportedFcn + ...
      GetHideChildDefineSymbol("endif")
       
    %<SLibCacheSystemCodeToFile("sys_exported_fcn_decl", system, exported)>
  %endif
  %%
  %if useEncapsCPP
    %<LibAddToSystemField(system, "SystemMemberPrototype", memberProt)>
  %endif
%endfunction
 
 
%%Function:FcnGenBodySysCache================================================
%%Description:
%%Cacheallcodeforamodule(includingroot).
%%
%function FcnGenBodySysCache(module) void
  %% Assert (!system.SystemCached)
  %assign system = System[module.CGSystemIdx]
  %assign isRoot = (system.Type == "root")
  %assign testFcnIdx = isRoot ? ...
    ::CompiledModel.RTWCGModules.TestInterfaceFcnIdx : -1
   
  %if system.IsRateGroupedSLFcn == TLC_TRUE && !Accelerator
    %% Contents of rate grouped simulink function subsystems are emitted by the root module
    %return
  %endif
 
  %if (system.CrossNoArgFcnBound && (UsingMalloc || (MultiInstanceERTCode && !GenerateClassInterface)))
    %% The first of these tracks if *any* subsystem has the "cross" flag set
    %% (need this to know whether to put extra fields in RT_MODEL).
    %% The second tracks if *this* subsystem has the "cross" flag set
    %% (need this to communicate this info across GENERATE_TYPE boundary,
    %% so generated code knows how to address certain globals).
    %% thisSubsysCross will get reset to false at the bottom of this function.
    %assign ::AnyCross = TLC_TRUE
    %assign ::ThisSubsysCross = TLC_TRUE
  %endif
 
  %%
  %% Generated code for sub-functions and exported functions
  %%
  %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate code for sub-functions and exported functions")>
  %if module.NumSubFunctions > 0
    %with ::CompiledModel
      %<FcnGenModuleSubFunctions(module, testFcnIdx)>
    %endwith
  %endif
  %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate code for sub-functions and exported functions")>
   
  %% Allowing sub functions of rate grouped SLF to be emitted. This is needed when a SLF
  %% contains a SF chart that generates a function.
  %% test/toolbox/simulink/mdelref/fcncall/scheduling/tExpChartLvlFcn_3/lvlTwo_G1384883_Standalone
  %if system.IsRateGroupedSLFcn == TLC_TRUE
    %% Body of rate grouped simulink functions are emitted by the root module
    %return
  %endif
   
  %if (ISFIELD(system,"NoCode"))
    %if (system.NoCode == "yes")
      %<SLibExtModeHostOnlyStub(system)>
      %assign ::ThisSubsysCross = TLC_FALSE
      %return ""
    %endif
  %endif
   
  %% EnableFcn, InitializeFcn, and StartFcn fields should always exist in
  %% System record
  %% However, there may not be any blocks in the system that generate initialize
  %% or enable code. Thus, we must cache those two functions first -- Start
  %% will call them if they are non-empty.
 
  %if ISFIELD(system,"SetupRuntimeResourcesFcn")
    %<SLibFcnGenBodySysFcnEntry(system,"SetupRuntimeResources","SetupRuntimeResources",...
                                TLC_TRUE,TLC_TRUE,TLC_FALSE,TLC_FALSE)>
  %endif
   
  %% Cache Initialize before Enable so Initialize args get added to Enable
  %if ISFIELD(system,"InitializeFcn")
    %<SLibFcnGenBodySysFcnEntry(system,"Initialize","InitializeConditions",...
                                TLC_TRUE,TLC_TRUE,TLC_FALSE,TLC_FALSE)>
  %endif
   
  %if ISFIELD(system,"SystemInitializeFcn")
    %<SLibFcnGenBodySysFcnEntry(system,"SystemInitialize","SystemInitialize",...
                                TLC_TRUE,TLC_TRUE,TLC_FALSE,TLC_FALSE)>
  %endif
 
  %if ISFIELD(system,"SystemResetFcn")
    %<SLibFcnGenBodySysFcnEntry(system,"SystemReset","SystemReset",...
                                TLC_TRUE,TLC_TRUE,TLC_FALSE,TLC_FALSE)>
  %endif
   
  %if ISFIELD(system, "FinalizeDimsFcn")
    %<SLibFcnGenBodySysFcnEntry(system,"FinalizeDims","FinalizeDims",...
                                TLC_FALSE,TLC_FALSE,TLC_FALSE,TLC_FALSE)>
  %endif
  
  %if ISFIELD(system, "SetDimsFcn")
    %<SLibFcnGenBodySysFcnEntry(system,"SetDims","SetDims",...
                                TLC_FALSE,TLC_FALSE,TLC_FALSE,TLC_FALSE)>
  %endif
   
  %if ISFIELD(system,"EnableFcn")
    %<SLibFcnGenBodySysFcnEntry(system,"Enable","Enable",...
                                TLC_TRUE,TLC_TRUE,TLC_FALSE,TLC_FALSE)>
  %endif
   
  %if ISFIELD(system,"CleanupRuntimeResourcesFcn")
    %<SLibFcnGenBodySysFcnEntry(system,"CleanupRuntimeResources","CleanupRuntimeResources",...
                                TLC_TRUE,TLC_TRUE,TLC_FALSE,TLC_FALSE)>
  %endif
 
  %% Don't cache start function since it will never be called, Accelerator
  %% runs start function via Simulink.
  %if Accelerator && CGMODEL_ACCESS("CGModel.AcceleratorExpandedSystemFcns") == 0
    %<LibSetSystemField(system, "CachedStartFcn", "")>
  %else
    %<SLibFcnGenBodySysFcnEntry(system,"Start","Start",...
                                TLC_TRUE,TLC_TRUE,TLC_FALSE,TLC_FALSE)>
  %endif
   
  %if ISFIELD(system, "ModelInitializeFcn")
    %<SLibFcnGenBodySysFcnEntry(system,"ModelInitialize","ModelInitialize",...
                                TLC_FALSE,TLC_FALSE,TLC_FALSE,TLC_FALSE)>
  %endif
   
  %if 1 == system.StandaloneSubsystem
    %assign zcInit = SLibGetPrevZCStateInitCode(system)
    %if !ISEMPTY(zcInit)
      %<LibAddToSystemField(system, "CachedInitializeDataBody", zcInit)>
    %endif
  %endif
   
  %assign isPartForRoot = SLibPartitionGroupingSystem(system)
   
  %if ISFIELD(system,"DerivativeFcn") && (!isRoot || (NumContStates > 0))
    %<SLibFcnGenBodySysFcnEntry(system,"Derivative","Derivatives",...
                                TLC_TRUE,TLC_FALSE,TLC_TRUE, ...
                                isPartForRoot)>
  %endif
 
   
  %if ISFIELD(system,"ProjectionFcn") && (!isRoot || (NumContStates > 0))
    %<SLibFcnGenBodySysFcnEntry(system,"Projection","Projection",...
                                TLC_TRUE,TLC_FALSE,TLC_FALSE, ...
                                isPartForRoot)>
  %endif
 
 
  %if ISFIELD(system,"ForcingFunctionFcn") && (ModelIsLinearlyImplicit == "yes") && (!isRoot || (NumContStates > 0))
    %<SLibFcnGenBodySysFcnEntry(system,"ForcingFunction","ForcingFunction",...
                                TLC_TRUE,TLC_FALSE,TLC_FALSE, ...
                                isPartForRoot)>
  %endif
 
 
  %if ISFIELD(system,"MassMatrixFcn") && (ModelIsLinearlyImplicit == "yes") && (!isRoot || (NumContStates > 0))
    %<SLibFcnGenBodySysFcnEntry(system,"MassMatrix","MassMatrix",...
                                TLC_TRUE,TLC_FALSE,TLC_FALSE, ...
                                isPartForRoot)>
  %endif
 
   
  %if ISFIELD(system,"ZeroCrossingFcn") && (!isRoot || (NumNonsampledZCs > 0))
    %<SLibFcnGenBodySysFcnEntry(system,"ZeroCrossing","ZeroCrossings",...
                                TLC_TRUE,TLC_FALSE,TLC_FALSE, ...
                                isPartForRoot)>
  %endif
 
 
  %if ISFIELD(system,"DisableFcn")
    %<SLibFcnGenBodySysFcnEntry(system,"Disable","Disable",...
                                TLC_TRUE,TLC_TRUE,TLC_FALSE,TLC_FALSE)>
  %endif
 
  %if ISFIELD(system,"UpdateFcn")
    %<SLibFcnGenBodySysFcnEntry(system,"Update","Update",...
                                TLC_TRUE,TLC_TRUE,TLC_TRUE,TLC_TRUE)>
  %endif
 
  %if ISFIELD(system,"ConstCodeFcn")
    %<SLibFcnGenBodySysFcnEntry(system,"ConstCode","ConstCode",...
                                TLC_TRUE,TLC_TRUE,TLC_FALSE,TLC_FALSE)>
  %endif
 
  %% Cache Outputs function after update fcn because the
  %% the Output method checks if output or update is empty
  %% before generating special code for conditionally
  %% executed systems (such as setting the mode in an enabled
  %% subsystem). It is possible with CGIR for the Output buffer
  %% of an enabled subsystem to be empty, but the Update buffer
  %% to be nonempty.
  %if !system.DeletedInIR
    %if ISFIELD(system,"OutputFcn")
      %<SLibFcnGenBodySysFcnEntry(system,"Output","Outputs",...
                                  TLC_TRUE,TLC_TRUE,TLC_TRUE,TLC_TRUE)>
    %elseif ISFIELD(system,"OutputUpdateFcn")
      %<SLibFcnGenBodySysFcnEntry(system,"OutputUpdate","OutputUpdate",...
                                  TLC_TRUE,TLC_TRUE,TLC_TRUE,TLC_TRUE)>
    %endif
  %endif
 
  %%
  %% For ert model reference the registration function will be in the top level
  %% subsystem file. If all blocks have constant sample time, only registration
  %% function will be generated. The registration function will be dumped in
  %% in ertreg.tlc.
  %assign isMdlRefSys = IsModelReferenceBaseSys(system)
  %assign nonEmpty = isRoot || isMdlRefSys || SLibSystemNonEmpty(system) || ...
    LibIsServer(system)
  %<LibSetSystemField(system, "SystemNonEmpty", nonEmpty)>
  %<LibSetSystemField(system, "SystemCached", TLC_TRUE)>
 
  %% For the model reference base system, we generate the interface
  %% and prototype in FcnGenBodySysCache. This is because information
  %% from Output may be needed in Update to determine if an
  %% rtModel argument is needed (one reason is the firstInitCond).
  %%
  %% NOTE(mdt): We do not need to this here for OutputUpdate because
  %% we call ModelrefMarkRTMIfNeeded at the end of
  %% FcnGenBodyOutputUpdateFcnCache after both Output and Update
  %% have already been generated. This avoids the problem that
  %% happens when Output and Update are called separately.
  %if isMdlRefSys
    %if ISFIELD(system,"UpdateFcn")
      %assign ::BlockFcn = "Update"
      %<LibSetGlobalSysFcnsForArgAccess([])>
      %if ISFIELD(system, "UpdateOOCC")
        %<LibSetGlobalSysFcnsForArgAccess(system.UpdateOOCC)>
      %endif
      %<LibDefineSystemFcn(system, "Update")>
      %assign ::BlockFcn = "Unknown"
    %endif
     
    %if ISFIELD(system,"OutputFcn") && !system.DeletedInIR
      %assign ::BlockFcn = "Output"
      %<LibSetGlobalSysFcnsForArgAccess([])>
      %if ISFIELD(system, "OutputOOCC")
        %<LibSetGlobalSysFcnsForArgAccess(system.OutputOOCC)>
      %endif
      %<LibDefineSystemFcn(system, "Output")>
      %assign ::BlockFcn = "Unknown"
    %endif
  %endif
   
  %% cache global vars after all system functions have been cached
  %if isMdlRefSys && SLibIsExportFcnDiagram()
    %with system.Interface
    %% Add initialization of uninitalized canonical parameters to start function.
    %% This is needed here because of code execution order issues. Canonical
    %% params for model ref are marked as "accessed" when invoking
    %% FcnAddParametersAndReturn for the rate grouped SLF (sysFcn="Output").
    %% See the call to %<SLibAccessMdlRefCanParam(argSrcIdx, "Start")>
    %% when looping through canonical params. However, the "Start" function
    %% has already been cached, so the globals that are marked as "accessed"
    %% never actually get initialized. I need this loop here to initialize
    %% those missed global vars. The call to SLibAccessMdlRefCanParam
    %% passes in "Start" so I'm looking for "GlobalStartAccessed" here.
    %% see :test/toolbox/simulink/modelref/fcncall/client_server/tCodegen2 -lvlTwo_g1062759
    %openfile tmpbufParam
    %foreach argIdx = NumCanonicalPrmArgDefs
      %assign argDef = CanonicalPrmArgDef[argIdx]
      %if (!ISFIELD(argDef, "ConnectedToSimulinkFunction") || argDef.ConnectedToSimulinkFunction == "no") ...
        && SystemGlobalDeclIsNeeded(argDef) ...
        && ISFIELD(argDef, "GlobalStartAccessed") ...
        && !ISFIELD(argDef, "GlobalInitialized")
        %<argDef.GlobalIdentifier> = %<LibGetRecordIdentifier(argDef)>;
      %endif
    %endforeach
    %closefile tmpbufParam
    %assign fcnRecord = SLibSystemFcnInfoRecord(system, "Start")
    %if !WHITE_SPACE(tmpbufParam)
      %assign fieldName = "CachedStartGlobalVars"
      %if !LibIsSystemField(system, fieldName)
        %<LibSetSystemField(system, fieldName, tmpbufParam)>
      %else
        %<LibAddToSystemField(system, fieldName, tmpbufParam)>
      %endif
      %% Global access not accounted for when caching start fcn
      %% therefore we need to recompute the prototype
      %<LibSetSystemField(system,"StartFcnInfo",fcnRecord)>
    %endif
       
    %% Delayed caching of start prototype
    %if !LibSystemFcnIsEmptyHelper(system,"Start","")
      %<LibCacheSubsystemPrototype(system,fcnRecord)>
    %endif
 
    %% Add initialization of uninitalized canonical I/O to system init function.
    %% This is needed to deal with the consequences of inlining the rate grouped
    %% simulink function's init code into model init. When the rate grouped
    %% SLF acceses a global, it expects that global to be initialized by its
    %% init or start fcn. Prior to rate grouping, that init or start fcn would
    %% not have all model canonical I/O passed as arguments. Hence, the need
    %% for marking the arg as needing global access. However, when that SLF init
    %% code is inlined into model init, that accessed var may actually be passed into
    %% model init as an argument. So, arg tracking decides that global access is
    %% not needed (it can just use the passed in arg). So, without the init fcn
    %% marking a need for global access, the initialization of the global needed
    %% by the SLF is not accomplished. We end up with a seg-v due to unitialize
    %% data access. See
    %% test/toolbox/simulink/modelref/fcncall/scheduling/tModelRefBasic_Concat_SimulinkFcns.m
    %openfile tmpbuf
    %foreach argIdx=NumCanonicalInputArgDefs
      %assign argDef = CanonicalInputArgDef[argIdx]
      %if (!ISFIELD(argDef, "ConnectedToSimulinkFunction") || argDef.ConnectedToSimulinkFunction == "no") ...
        && SystemGlobalDeclIsNeeded(argDef) ...
        && ISFIELD(argDef, "GlobalInitializationNeeded") ...
        && !ISFIELD(argDef, "GlobalInitialized")
        %<argDef.GlobalIdentifier> = %<LibGetRecordIdentifier(argDef)>;
      %endif
    %endforeach
    %foreach argIdx=NumCanonicalOutputArgDefs
      %assign argDef = CanonicalOutputArgDef[argIdx]
      %if (!ISFIELD(argDef, "ConnectedToSimulinkFunction") || argDef.ConnectedToSimulinkFunction == "no") ...
        && SystemGlobalDeclIsNeeded(argDef) ...
        && ISFIELD(argDef, "GlobalInitializationNeeded") ...
        && !ISFIELD(argDef, "GlobalInitialized")
        %<argDef.GlobalIdentifier> = %<LibGetRecordIdentifier(argDef)>;
      %endif
    %endforeach
    %closefile tmpbuf
    %if !WHITE_SPACE(tmpbuf)
      %assign fieldName = "CachedSystemInitializeGlobalVars"
      %if !LibIsSystemField(system, fieldName)
        %<LibSetSystemField(system, fieldName, tmpbuf)>
      %else
        %<LibAddToSystemField(system, fieldName, tmpbuf)>
      %endif
    %endif
    %endwith
  %endif
   
  %% Reset flag for next subsystem
  %assign ::ThisSubsysCross = TLC_FALSE
%endfunction %% FcnGenBodySysCache
 
 
%%Function:FcnGenSystemTerminate=============================================
%%Description:
%%Cacheallterminatecodeforasubsystem.Ultimately,thisfunction
%%shouldalsobeabletocachecodefortherootsystem.
%%
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/dimensionVariants/tDimensionVariants9.m
%%
%function FcnGenSystemTerminate(system) void
  %% Assert (!system.SystemTerminateCached)
 
  %if (ISFIELD(system,"NoCode"))
    %if (system.NoCode == "yes")
      %<SLibExtModeHostOnlyStub(system)>
      %return ""
    %endif
  %endif
 
  %<FcnGenBodyTerminateFcnCache(system)>
 
  %assign terminateNonEmpty = SLibSystemTerminateNonEmpty(system)
  %<LibSetSystemField(system, "SystemTerminateNonEmpty", terminateNonEmpty)>
  %<LibSetSystemField(system, "SystemTerminateCached", TLC_TRUE)>
 
%endfunction %% FcnGenSystemTerminate
 
 
%%Function:FcnCacheLocalVars=================================================
%%Abstract:
%%Generatesthelocalvariabledeclarationforagivenfunctiontypeand
%%cachesitinthesystemsinstancerecord.
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tIVfcnCall_neg.m-tRootOutportStorageClass.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants_subsys.m-tmg1672961.m
%function FcnCacheLocalVars(system, fcnType) void
  %assign multiTID = (fcnType == "Update") || ...
                     (fcnType == "Output") || ...
                     (fcnType == "OutputUpdate") || ...
                     (SLibContFcnPartitionGrouping(fcnType) && ...
                     SLibPartitionGroupingSystem(system))
                    
  %if SLibNonEmptyModel()
    %if (fcnType == "Update") && (CombineOutputUpdateFcns != 0) && ...
        LibSystemIsRoot(system)
        %return
    %endif
     
    %assign localVar = FcnDeclareAccessedLocalVariables(system)
    %if LibIsDeploymentDiagram() && (system == rootSystem)
      %if !WHITE_SPACE(SLibDeploymentGetLocalVars(fcnType))
        %assign localVar = localVar + SLibDeploymentGetLocalVars(fcnType)
      %endif
    %endif
 
    %if fcnType == "ModelInitialize"
      %openfile servicePortInit
      %<SLibCacheServicePortDWork()>
      %closefile servicePortInit
       %if !WHITE_SPACE(servicePortInit)
         %assign localVar = localVar + servicePortInit
       %endif
    %endif
     
    %% For rate grouped Simulink functions in modelref the local
    %% var decls need to be transfered from the original SLF system
    %% (which does not get emitted) to the root system that really
    %% contains the rate grouped SLF. Without this transfer, local
    %% vars are never declared.
    %assign isMdlRefHiddenRoot = TLC_FALSE
    %if IsModelReferenceTarget() && ::CurrentModuleIdx == RTWCGModules.NumRTWCGModules - 2
      %assign isMdlRefHiddenRoot = TLC_TRUE
    %endif
    %if LibSystemIsRoot(system) || isMdlRefHiddenRoot
      %% Add in local vars for rate grouped Simulink Functions
      %assign numSubsys = NumSystems-1
      %foreach sysIdx = numSubsys
        %assign aSubsys = System[sysIdx]
        %if aSubsys.IsRateGroupedSLFcn
          %assign slfLocalVars = FcnDeclareAccessedLocalVariables(aSubsys)
          %if !ISEMPTY(slfLocalVars)
            %if ISEMPTY(localVar)
              %assign localVar = slfLocalVars
            %else
              %assert TYPE(localVar) == TYPE(slfLocalVars)
              %if TYPE(localVar) == "Vector"
                %assert (SIZE(localVar,1) >= SIZE(slfLocalVars,1))
                %assign numLocalVar = SIZE(slfLocalVars,1)
                %foreach bufIdx = numLocalVar
                  %assign localVar[bufIdx] = localVar[bufIdx] + slfLocalVars[bufIdx]
                %endforeach
              %elseif TYPE(localVar) == "String"
                %assign localVar = localVar + slfLocalVars
              %endif
            %endif
          %endif
        %endif
      %endforeach
    %endif
     
    %assert (TYPE(localVar) == "String" && !multiTID) || ...
             multiTID
    %if multiTID
      %<LibSetSystemFieldForTID(system, fcnType,"LocalBO", localVar)>
    %else
      %if !ISEMPTY(localVar)
        %<LibSetSystemField(system, "Cached" + fcnType + "LocalBO", localVar)>
      %endif
    %endif
  %endif
%endfunction
 
%%Function:FncGenInitStatesInRootStart======================================
%%Abstract:
%%Thisfunctiongeneratecodeinitializestates
%%ifneeded
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSink/tmVarSinkRateTransBlk_VC1.m
%%
%function FncGenInitStatesInRootStart()
  %assign ss = System[NumSystems - 1] %% root system
  %openfile retBuf
  %% Load intial states if needed.
  %if ::CompiledModel.LoadInitialState == "yes"
 
    /* initial state override */
    %assign origBlockFcn = ::BlockFcn
    %assign ::BlockFcn = "Start"
    %<FcnLoadInitialState()>/
    %assign ::BlockFcn = origBlockFcn
  %endif
  %closefile retBuf
  %return retBuf
%endfunction %% FncGenInitStatesInRootStart
 
 
%%Function:FcnGenInitMassMatrixPr===================
%%Abstract:
%%ThisfunctiongeneratescodethatinitializesMassMatrixProffsetsinDWork
%%MassMatrixProffsetsareonlygeneratedatthemodelrootlevel.
%%
%function FcnGenInitMassMatrixPr(system) void
  %assert (ModelIsLinearlyImplicit == "yes")
  %assert (system.Type == "root")
     
  %openfile tempbuf
   
      /* Root-level init GlobalMassMatrixPr offset */
      {
        %foreach mmIdx = ::CompiledModel.MassMatrices.NumMassMatrices
          %assign mm = ::CompiledModel.MassMatrices.MassMatrix[mmIdx]
          %assign prOffset = mm.IndexPr
          %assign grSrc = mm.GrSrc
          %assign comment = "/* '%<SLibGrBlockName(grSrc)>' */"
           
          %assign grSubSys = ::CompiledModel.BlockHierarchyMap.Subsystem[grSrc[0]]
          %assign grBlock = grSubSys.Block[grSrc[1]]
          %assign isSubsys = grBlock.Type == "SubSystem"
           
          %assign dwIdx = -1 %% invalid
          %assign dw = ""
          %assign foundMassMatrixDWork = TLC_FALSE
          %foreach blkDW = grBlock.NumDWorks
            %assign dwIdx = grBlock.DWork[blkDW]._idx
            %assign dw = ::CompiledModel.DWorks.DWork[dwIdx]
            %if dw.Name == "MASS_MATRIX_PR"
              %assign foundMassMatrixDWork = TLC_TRUE
              %break
            %endif
          %endforeach
          %assert foundMassMatrixDWork
          %with system
             
            %if ISFIELD(mm, "ForEachSSLoopBnds")
              %% The owner block is inside For Each subsystem.
              %% Need to initialize the DWork value correctly for each iteration
              %assign ::NeedForEachLoopInReg = TLC_TRUE
              %assign ::NumForEachLoopHierarchyLevel = SIZE(mm.ForEachSSLoopBnds,1)
              %assign ::ForEachLoopHierarchyLevel = ::NumForEachLoopHierarchyLevel
              %assign mmPrOffset = LibIsDeploymentDiagram() ? ...
                "%<SLibDeploymentGetSystemMassMatrixPr(grSrc[0], grSrc[1], prOffset, isSubsys)>" : "%<prOffset>"
             {
               %% Form loop for every parent For Each subsystem
               %foreach ssIdx = SIZE(mm.ForEachSSLoopBnds,1)
                 %assign iterVar = "i_%<ForEachLoopHierarchyLevel>"
                 %assign ::ForEachLoopHierarchyLevel = ::ForEachLoopHierarchyLevel - 1
                 int32_T %<iterVar>;
                 for (%<iterVar> = 0; %<iterVar> < %; %<iterVar>++) {
                   %assign mmPrOffset = mmPrOffset + "+" + iterVar + "*%"
                 %endforeach
                 %assign ::ForEachLoopHierarchyLevel = 1
            %else
              %assign mmPrOffset = LibIsDeploymentDiagram() ? ...
                "%<SLibDeploymentGetSystemMassMatrixPr(grSrc[0], grSrc[1], prOffset, isSubsys)>" : "%<prOffset>"
            %endif
           
            %<SLibBlockMassMatrixPrOffsetInternal("", "", 0, dwIdx, dw, 1)> = %<mmPrOffset>; %<comment>
 
            %if ISFIELD(mm, "ForEachSSLoopBnds")
              %% Close the loop for every parent For Each subsystem
              %foreach ssIdx = SIZE(mm.ForEachSSLoopBnds,1)
                 }
              %endforeach
             }
              %assign ::NeedForEachLoopInReg = TLC_FALSE
            %endif
           
          %endwith
        %endforeach
      }
             
  %closefile tempbuf
   
  %return tempbuf
   
%endfunction %% FcnGenInitMassMatrixPr
 
 
 
%function FcnGenInitMassMatrixPrInRoot() void
 
  %openfile retBuf
  
  %if (::CompiledModel.ModelIsLinearlyImplicit == "yes") && !IsModelReferenceTarget()
 
    %assign ss = System[NumSystems - 1] %% root system
     
    %<FcnGenInitMassMatrixPr(ss)>
 
  %endif
   
  %closefile retBuf
  %if !WHITE_SPACE(retBuf)
    %return retBuf
  %else
    %return ""
  %endif
 
%endfunction %% FncGenInitMassMatrixPrInRoot
 
 
%%FunctionFcnNonRootSystemHasModes(system)===================================
%%Description:
%%Returnwhethersystemisnotrootandhasmodes
%function FcnNonRootSystemHasModes(system) void
  %if system.Type == "root"
    %return TLC_FALSE
  %else
    %assign callSites = system.CallSites
    %assign graphParentSys = ::CompiledModel.System[callSites[0][2]]
    %assign ssBlock = graphParentSys.Block[callSites[0][3]]
    %return ssBlock.ModeVector[0] > 0
  %endif
%endfunction
 
 
%%Function:FcnGenerateTerminate==============================================
%%Description:
%%Generateterminatecodeforthesystem
%%
%%TopTester:test/toolbox/simulink/variants/tVariantGecks6.m-tVariantManager3.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/dimensionVariants/tDimensionVariants9.m
%%
%function FcnGenerateTerminate(system)
  %openfile tmpBuffer
  %with system
    %if system.Type == "root"
      %foreach idx = LibGetNumAsyncTasks()
        %assign tid = idx + NumRuntimeExportedRates
        %if RTMAbsTimeNeedTransProtection(tid) && ...
          SLibConcurrentTasks()
          %<SLibCGIRMutexOp(3,SLibGetTimerSemID(tid))>
        %endif
      %endforeach
    %endif
    %if SLibNonEmptyModel()
      %assign rootOpaqueBlock = FcnRootOpaqueBlock()
      %assign ::CurrentModuleIdx = system.CGIRModuleIdx
      %assign termCode = FcnGenerateCodeFromModule(rootOpaqueBlock, system, "Terminate")
      %assign ::CurrentModuleIdx = -1
      %<termCode>
      %if system.Type == "root" && ::isRAccel
    %if ::raccelObserverLog
          observerLogCleanup();
        %endif
        %assign nulldef = SLibGetNullDefinitionFromTfl()
        %if FEVAL("Simulink.sdi.useSLIOForLogging")
          if(rt_slioCatalogue() != %<nulldef>){
            void **slioCatalogueAddr = rt_slioCatalogueAddr();
            rtwSaveDatasetsToMatFile(...
              rtwGetPointerFromUniquePtr(rt_slioCatalogue()), ...
              rt_GetMatSigstreamLoggingFileName());
            rtwTerminateSlioCatalogue(slioCatalogueAddr);
            *slioCatalogueAddr = NULL;
          }
        %endif
      %endif
    %endif
  %endwith
  %% Stateflow global machine terminate
  %if IsBaseSystem(system)
    %<SLibWriteMachineTerminate()>/
    %% slplugin function call for model reference accel mode
    %if IsModelReferenceSimTarget() && !GenerateClassInterface
      if(!slIsRapidAcceleratorSimulating()) {
        %assign simS = RTMsGet(system, "MdlRefSfcnS")
        slmrRunPluginEvent(%<simS>, "%<CompiledModel.Name>", "SIMSTATUS_TERMINATING_MODELREF_ACCEL_EVENT");
      }
    %endif
    %<SLibDumpOpaqueTypeDestructCode(::CompiledModel.System[GetBaseSystemIdx()], "OpaqueTypeDestruct", TLC_TRUE)>
  %endif
 
  %closefile tmpBuffer
  %if !WHITE_SPACE(tmpBuffer)
    %% If "Terminate function required" is OFF, do not generate terminate code
    %% since it will not get used in generated code. Also warn the user that
    %% the terminate code is getting discarded.
    %if !IncludeMdlTerminateFcn
      %<FcnThrowTerminateFcnWarning()>
      %assign tmpBuffer = ""
    %endif
    %return tmpBuffer
  %else
    %return ""
  %endif
%endfunction %% FcnGenerateTerminate
 
%%Function:FcnThrowTerminateFcnWarning=======================================
%%Description:
%%Throwwarningthatcodegenerationdidnotgenerateaterminatefunction.
%%Thewarningwillbethrownonlyonce.
%%
%function FcnThrowTerminateFcnWarning() void
  %if !ISFIELD(::CompiledModel,"TerminateFcnWarningThrown")
    %if SLibIsExportFcnDiagram()
      %<SLibReportWarningWithId("Coder:buildProcess:TerminateFunctionNecessaryExportFcnModel")>
    %else
      %<SLibReportWarningWithId("Coder:buildProcess:TerminateFunctionNecessaryRequiredOff")>
    %endif
    %<LibAddToCompiledModel("TerminateFcnWarningThrown",TLC_TRUE)>
  %endif
%endfunction %% FcnThrowTerminateFcnWarning
 
 
%%Function:FcnGenBodyTerminateFcnCache(system)===============================
%%Description:
%%CachessystemTerminatefunction
%%
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/dimensionVariants/tDimensionVariants9.m
%%
%function FcnGenBodyTerminateFcnCache(system) void
  %assign terminateFcn = FcnGenerateTerminate(system)
  %if IsBaseSystem(system)
    %assign terminateProf = SLibGenProfSysTerminate(system)
    %<LibSetSystemField(system, "CachedTerminateProfileEndCode", terminateProf)>
  %endif
  %<LibSetSystemField(system, "CachedTerminateFcn", terminateFcn)>
  %<FcnCacheLocalVars(system, "Terminate")>
  %<LibDefineSystemFcn(system, "Terminate")>
%endfunction %% FcnGenBodyTerminateFcnCache
 
%%Function:FcnGenerateTidGuardOpenCodeInMain(tid)=====================
%%ReturnTIDguardopenpotion.
%%Ifrategroupingison,return""because
%%rategroupedcodedoesnotneedtidguard
%%
%%NOTE:ThisfunctionissimilartoFcnGenerateTidGuardOpenCodefunction
%%exceptfortheMajorTimeStepcheck(sincethiscodewillbeinmain.c)
%function FcnGenerateTidGuardOpenCodeInMain(tid)
  %if SLibIsPeriodicRateGrouping()
    %return "{ %<LibTaskComment(tid)>"
  %else
    %assign tidGuard = FcnERTIsSampleHitInMain(tid)
    %if tidGuard == "1"
      %return "{ %<LibTaskComment(tid)>"
    %else
      %return "if (%<tidGuard>) { %<LibTaskComment(tid)>"
    %endif
  %endif
%endfunction %% FcnGenerateTidGuardOpenCode
 
%%Function:FcnGenerateTidGuardOpenCode(tid)===========================
%%ReturnTIDguardopenpotion.
%%Ifrategroupingison,return""because
%%rategroupedcodedoesnotneedtidguard
%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function FcnGenerateTidGuardOpenCode(tid)
  %if SLibIsPeriodicRateGrouping()
    %return "{ %<LibTaskComment(tid)>"
  %else
    %assign tidGuard = LibIsSampleHit(tid)
    %if tidGuard == "1"
      %return "{ %<LibTaskComment(tid)>"
    %else
      %return "if (%<tidGuard>) { %<LibTaskComment(tid)>"
    %endif
  %endif
%endfunction %% FcnGenerateTidGuardOpenCode
 
%%Function:FcnGenerateTidGuardCloseCode(tid)===========================
%%ReturnTIDguardclosepotion.
%%Ifrategroupingison,return""because
%%rategroupedcodedoesnotneedtidguard
%%
%function FcnGenerateTidGuardCloseCode(tid)
  %return "}"
%endfunction %% FcnGenerateTidGuardCloseCode
 
 
%%Function:SystemNeedTidGuard(system,tid)=====================
%%Returntrueiftidguardisneedinsubsystemcodeforspecific
%%tid
%%
%function SystemNeedTidGuard(system, tid)
  %assign needTidGuard = TLC_TRUE
 
  %if LibIsSingleRateSystem(system)
    %assign needTidGuard = TLC_FALSE
  %elseif SLibSingleTasking() && TID == 0 && ...
    (Accelerator || (CodeFormat!="S-Function"))
    %assign needTidGuard = TLC_FALSE
  %endif
   
  %return needTidGuard
%endfunction
 
%%Function:FcnGenerateTimeManagementForAsyncTs===========
%%Abstractu:
%%Generatecodeforasynchronoustasktomanagetimer.
%%Anasynchronoustaskcanupdateitstimerfrombaserate
%%timer,itscallertask,orexternaltimer.
%%
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function FcnGenerateTimeManagementForAsyncTs(fcnType, tid,loc)
  %assert LibAsynchronousTriggeredTID(tid) || SLibExplicitTaskingTID(tid)
   
  %if !SLibNeedAbsoluteTimeForTID(tid) || !ClockTickForTIDIsReqFcn(tid)
    %% Instead of using condition !LibAsyncTaskAccessTimeInFcn(tid, ::BlockFcn),
    %% use !SLibNeedAbsoluteTimeForTID(tid) || !ClockTickForTIDIsReqFcn(tid)
    %% (g1182394).
    %return ""
  %endif
  %assign ts = SampleTime[tid]
   
  %% If async timer is Self_internal, timer increase by 1
  %% when timer is update. Timer should be updated in Outputs function
  %% once and only once. Timer can't be updated in other fcn type.
  %if ts.TimeSource == "Self_internal"
    %if (fcnType != "Outputs" && fcnType != "Output") || loc == "top"
      %return ""
    %endif
  %else
    %if loc == "bottom"
      %return ""
    %endif
  %endif
   
  %% If sample time is Asynchronous and need abs time,
  %% and this subsystem is the top one associated with
  %% the async sample time, then
  %% fcnCall need update absolute time whenever it
  %% runs.
  %openfile retBuf
  %if (ts.Asynchronous == "yes" || ts.ExplicitTasking == "yes") && ...
    ts.NeedAbsoluteTime == "yes"
    %if ts.TimeSource == "BaseRate"
      %<FcnAsyncTaskUpdatesTimersFromBaseRate(tid)>
    %elseif ts.TimeSource == "Self" && ...
      !ISFIELD(SampleTime[tid], "AsyncSfcnBlkIdx")
      %if ISFIELD(ts,"EventTaskTimeClock")
        %<LibGetClockTick(tid)> = %<ts.EventTaskTimeClock>(%<ts.SGID>);
      %elseif SampleTime[tid].IsUnionTs != "yes"
        %<LibGetClockTick(tid)> = getTick(%<tid>);
      %endif
    %elseif SampleTime[tid].TimeSource == "Self_internal"
      %<LibGetClockTick(tid)>++;
    %elseif SampleTime[tid].TimeSource == "Caller"
      %<LibGetClockTick">LibGetClockTick(tid)> = %<LibGetClockTick">LibGetClockTick(FcnGetAsyncPromotedTID(tid))>;
    %endif
  %endif
  %closefile retBuf
  %return retBuf
%endfunction
 
%%Function:SLibGetSysFcnBodyHelper=================
%%
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibGetSysFcnBodyHelper(system, fcnType, dontChkEmpty, tid)
  %assign system.CurrentTID = tid
  
  %assign dontChkEmpty = dontChkEmpty || ...
    (fcnType == "OutputUpdate" && ...
    (LibSystemIsForceNonInline(system) || LibIsServer(system) && system.IsConstUncalledFunction == "no"))
   
  %openfile retBuf
 
  %assert TYPE(tid) == "Number" || ISEQUAL(tid, "")
   
  %if LibAsynchronousTriggeredTID(tid) && ...
    !SLibNonInlinedModelWideEventTID(tid)
    %% asynchronous tid
    %% below added for
    %% runsuite tClientServer3 -testspec:testInOutArgs
    %% Do not skip an empty function when it is exported
    %if SLibIsExplicitTaskingExportFcnRateGrouping(fcnType, tid)
      %assign hasFcnBody = TLC_TRUE
    %else
      %assign hasFcnBody = (dontChkEmpty || ...
        !LibSystemFcnIsEmptyForTID(system,fcnType)) && ...
        !IsBaseSystem(system)
    %endif
     
  %elseif ISEQUAL(tid, "") && ...
    ((!FcnSysModuleIsRateGrouping(system,fcnType) && RateGroupedAsyncFcns) || !SLibIsExportFcnDiagram())
    %if !IsModelReferenceSimTarget()
      %assign hasFcnBody = dontChkEmpty || ...
        !LibSystemFcnIsEmptyHelper(system, fcnType, tid)
    %else
      %% This code is needed because for model ref sim target, the tid of a simulink function SS
      %% does not appear to be the actual tid of the subsystem in the model. In the case
      %% of a simulink function, the tid might be 1 for the SLF SS in rtw
      %% codegen but would be "" for modelref sim codegen. If it is ""
      %% then we need to loop over all tids to see if the SLF subsystem is
      %% really empty. This may result in empty/uncalled SS code in the sim
      %% code, but since it is simulation this is not a problem.
      %assign hasFcnBody = dontChkEmpty || ...
       !LibSystemFcnIsEmpty(system,fcnType)
    %endif
  %else
    %% tid that is a top level entry point
    %assign hasFcnBody = dontChkEmpty || ...
      !LibSystemFcnIsEmptyForTID(system,fcnType)
  %endif
 
  %if hasFcnBody
    %assign fcnBody = SLibGetBody%<fcnType>FcnCache(system)
    %<fcnBody>
  %endif
 
  %if FcnAddMdlRefTid1Interface(system, tid)
    %<SLibGetSysFcnBodyHelper(system, fcnType, dontChkEmpty, 1)>
  %endif
 
  %closefile retBuf
  %assign system.CurrentTID = -1
  %return retBuf
%endfunction
 
%function FcnGetCodeCacheTid(system, fcnType, tid) void
  %assign tid01eq = ISEQUAL(SolverType, "FixedStep") && FixedStepOpts.TID01EQ
  %if tid01eq && tid == 1
    %assign tid = 0
  %endif
  %return SLibSynchronousTID(tid) && ...
      !SLibSystemFcnPeriodicRateGrouping(system, fcnType) ? "" : ...
      tid
%endfunction
   
%%Function:SLibGetRateGroupedFcnBody===========
%%ReturnedrategroupedFcnbody
%%Only"Update""Output""OutputUdate"fcnbodycan
%%berategrouped.
%%Ifsystemtidisasynchronoustid,
%%alwaysreturnrategroupedfcnbody.
%%Ifsystemtidissynchronoustid,
%%-returnrategroupedbodyifsystemisrategrouped
%%-otherwise,returnnon-rate-groupedbody.
%function SLibGetRateGroupedFcnBody(system, fcnType, dontChkEmpty)
  %openfile retBuf
  %%
  %assert fcnType == "Update" || ...
    fcnType == "Output" || fcnType == "OutputUpdate"
  
  %assign ssTaskToFirstTid = FcnGetSubsystemTaskToFirstTID(system)
  %foreach idx = SIZE(ssTaskToFirstTid, 1)
    %assign tid = FcnGetCodeCacheTid(system, fcnType, ssTaskToFirstTid[idx])
    %<SLibGetSysFcnBodyHelper(system, fcnType, dontChkEmpty, tid)>
  %endforeach
 
  %closefile retBuf
  %return retBuf
%endfunction %% SLibGetRateGroupedFcnBody
 
%function SLibIsMemberMethod(system, fcnType)
  %assign ssTaskToFirstTid = FcnGetSubsystemTaskToFirstTID(system)
  %foreach idx = SIZE(ssTaskToFirstTid, 1)
    %assign tid = FcnGetCodeCacheTid(system, fcnType, ssTaskToFirstTid[idx])
    %assign fcnInfo = LibGetFcnInfo(system, fcnType, tid)
 
    %assign openStr = fcnInfo.Open
   
    %if EXISTS(::CPPClassName) && ::CPPClassName != ""
      %assign classPrefix = ::CPPClassName + "::"
      %if !ISEMPTY(FEVAL("strfind", openStr, classPrefix)) && ...
        ISEMPTY(FEVAL("strfind", fcnInfo.Name, classPrefix))
          %return TLC_TRUE
      %endif
    %endif
  %endforeach
  %return TLC_FALSE
%endfunction
 
%%Function:SLibCheckForMemFcn==================================
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%function SLibCheckForMemFcn(system, needToDumpSysFcn)
   %assign isRoot = (system.Type == "root")
   %assign dontChkEmpty = isRoot
   
   %if needToDumpSysFcn
    %if ISFIELD(system,"SetupRuntimeResourcesFcn")
      %if !LibSystemFcnIsEmpty(system, "SetupRuntimeResources")
    %return SLibIsMemberMethod(system,"SetupRuntimeResources")
      %endif
    %endif
    %if ISFIELD(system,"InitializeFcn")
      %if !LibSystemFcnIsEmpty(system, "Initialize")
    %return SLibIsMemberMethod(system,"Initialize")
      %endif
    %endif
    %if ISFIELD(system,"SystemInitializeFcn")
      %if !LibSystemFcnIsEmpty(system, "SystemInitialize")
    %return SLibIsMemberMethod(system,"SystemInitialize")
      %endif
    %endif
    %if ISFIELD(system,"SystemResetFcn")
      %if !LibSystemFcnIsEmpty(system, "SystemReset")
    %return SLibIsMemberMethod(system,"SystemReset")
      %endif
    %endif
    %% EnableFcn always exists
    %if ISFIELD(system,"EnableFcn")
      %if !LibSystemFcnIsEmpty(system,"Enable")
    %return SLibIsMemberMethod(system,"Enable")
      %endif
    %endif
    %% DisableFcn always exists
    %if ISFIELD(system,"DisableFcn")
      %if !LibSystemFcnIsEmpty(system,"Disable")
    %return SLibIsMemberMethod(system, "Disable")
      %endif
    %endif
    %% FinalizeDimsFcn may or may not exist
    %if ISFIELD(system, "FinalizeDimsFcn")
      %if !LibSystemFcnIsEmpty(system, "FinalizeDims")
        %return SLibIsMemberMethod(system, "FinalizeDims")
      %endif
    %endif
    %% SetDimsFcn may exist
    %if ISFIELD(system, "SetDimsFcn")
      %if !LibSystemFcnIsEmpty(system, "SetDims")
        %return SLibIsMemberMethod(system, "SetDims")
      %endif
    %endif
    %% StartFcn always exists
    %if ISFIELD(system,"StartFcn")
      %if dontChkEmpty || !LibSystemFcnIsEmpty(system,"Start")
    %return SLibIsMemberMethod(system, "Start")
      %endif
    %endif
    %if ISFIELD(system,"OutputFcn")
      %return SLibIsMemberMethod(system, "Output")
    %endif
    %if ISFIELD(system,"UpdateFcn")
      %return SLibIsMemberMethod(system, "Update")
    %endif
    %if ISFIELD(system,"DerivativeFcn") && (!isRoot || (NumContStates > 0))
      %if dontChkEmpty || !LibSystemFcnIsEmpty(system,"Derivative")
    %return SLibIsMemberMethod(system, "Derivative")
      %endif
    %endif
    %if ISFIELD(system,"ProjectionFcn") && (!isRoot || (NumContStates > 0))
      %if dontChkEmpty || !LibSystemFcnIsEmpty(system,"Projection")
    %return SLibIsMemberMethod(system, "Projection")
      %endif
    %endif
    %if ISFIELD(system,"ForcingFunctionFcn") && (ModelIsLinearlyImplicit == "yes") && (!isRoot || (NumContStates > 0))
      %if dontChkEmpty || !LibSystemFcnIsEmpty(system,"ForcingFunction")
    %return SLibIsMemberMethod(system, "ForcingFunction")
      %endif
    %endif
    %if ISFIELD(system,"MassMatrixFcn") && (ModelIsLinearlyImplicit == "yes") && (!isRoot || (NumContStates > 0))
      %if dontChkEmpty || !LibSystemFcnIsEmpty(system,"MassMatrix")
    %return SLibIsMemberMethod(system, "MassMatrix")
      %endif
    %endif
    %if ISFIELD(system,"ZeroCrossingFcn") && (!isRoot || (NumNonsampledZCs > 0))
      %if dontChkEmpty || !LibSystemFcnIsEmpty(system,"ZeroCrossing")
    %return SLibIsMemberMethod(system, "ZeroCrossing")
      %endif
    %endif
    %if ISFIELD(system,"OutputUpdateFcn")
      %return SLibIsMemberMethod(system, "OutputUpdate")
    %endif
    %if ISFIELD(system,"CleanupRuntimeResourcesFcn")
      %if !LibSystemFcnIsEmpty(system, "CleanupRuntimeResources")
    %return SLibIsMemberMethod(system,"CleanupRuntimeResources")
      %endif
    %endif
    %% TerminateFcn should always exist
    %if (!isRoot || !(Accelerator && CGMODEL_ACCESS("CGModel.AcceleratorExpandedSystemFcns") == 0)) && ...
      (dontChkEmpty || !LibSystemFcnIsEmpty(system,"Terminate"))
      %return SLibIsMemberMethod(system, "Terminate")
    %endif
    %if ISFIELD(system, "ConstCodeFcn")
      %if !LibSystemFcnIsEmpty(system,"ConstCode")
        %return SLibIsMemberMethod(system, "ConstCode")
      %endif
    %endif
    %return TLC_FALSE
  %else
    %return TLC_FALSE
  %endif %% needToDumpSysFcn
%endfunction
 
%%Function:SLibGetSystemFcnBodyCacheHelper==================================
%%Abstract:
%%HelperfunctionforSLibGetSystemFcnBodyCache
%%
%%TopTester:test/toolbox/simulink/blocks/lib_SignalAttributes/InitialCondition/rtw/tinitcond.m
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref2.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%function SLibGetSystemFcnBodyCacheHelper(system, needToDumpSysFcn)
  %assign isRoot = (system.Type == "root")
  %assign dontChkEmpty = isRoot
  %openfile codeBuffer
   
  %if needToDumpSysFcn
    %if ISFIELD(system,"SetupRuntimeResourcesFcn")
      %if !LibSystemFcnIsEmpty(system, "SetupRuntimeResources")
    %<SLibGetBodySetupRuntimeResourcesFcnCache(system)>
      %endif
    %endif
    %if ISFIELD(system,"InitializeFcn")
      %if !LibSystemFcnIsEmpty(system, "Initialize")
    %<SLibGetBodyInitializeFcnCache(system)>
      %endif
    %endif
    %if ISFIELD(system,"SystemInitializeFcn")
      %if !LibSystemFcnIsEmpty(system, "SystemInitialize")
    %<SLibGetBodySystemInitializeFcnCache(system)>
      %endif
    %endif
    %if ISFIELD(system,"SystemResetFcn")
      %if !LibSystemFcnIsEmpty(system, "SystemReset")
    %<SLibGetBodySystemResetFcnCache(system)>
      %endif
    %endif
    %% EnableFcn always exists
    %if ISFIELD(system,"EnableFcn")
      %if !LibSystemFcnIsEmpty(system,"Enable")
    %<SLibGetBodyEnableFcnCache(system)>
      %endif
    %endif
    %% DisableFcn always exists
    %if ISFIELD(system,"DisableFcn")
      %if !LibSystemFcnIsEmpty(system,"Disable")
    %<SLibGetBodyDisableFcnCache(system)>
      %endif
    %endif
    %% FinalizeDimsFcn may or may not exist
    %if ISFIELD(system, "FinalizeDimsFcn")
      %if !LibSystemFcnIsEmpty(system, "FinalizeDims")
        %<SLibGetBodyFinalizeDimsFcnCache(system)>
      %endif
    %endif
    %% SetDimsFcn may exist
    %if ISFIELD(system, "SetDimsFcn")
      %if !LibSystemFcnIsEmpty(system, "SetDims")
        %<SLibGetBodySetDimsFcnCache(system)>
      %endif
    %endif
    %% StartFcn always exists
    %if ISFIELD(system,"StartFcn")
      %if dontChkEmpty || !LibSystemFcnIsEmpty(system,"Start")
    %<SLibGetBodyStartFcnCache(system)>
      %endif
    %endif
    %if ISFIELD(system,"OutputFcn")
      %<SLibGetRateGroupedFcnBody(system, "Output", dontChkEmpty)>
    %endif
    %if ISFIELD(system,"UpdateFcn")
      %<SLibGetRateGroupedFcnBody(system, "Update", dontChkEmpty)>
    %endif
    %if ISFIELD(system,"DerivativeFcn") && (!isRoot || (NumContStates > 0))
      %if dontChkEmpty || !LibSystemFcnIsEmpty(system,"Derivative")
    %<SLibGetBodyDerivativeFcnCache(system)>
      %endif
    %endif
    %if ISFIELD(system,"ProjectionFcn") && (!isRoot || (NumContStates > 0))
      %if dontChkEmpty || !LibSystemFcnIsEmpty(system,"Projection")
    %<SLibGetBodyProjectionFcnCache(system)>
      %endif
    %endif
    %if ISFIELD(system,"ForcingFunctionFcn") && (ModelIsLinearlyImplicit == "yes") && (!isRoot || (NumContStates > 0))
      %if dontChkEmpty || !LibSystemFcnIsEmpty(system,"ForcingFunction")
    %<SLibGetBodyForcingFunctionFcnCache(system)>
      %endif
    %endif
    %if ISFIELD(system,"MassMatrixFcn") && (ModelIsLinearlyImplicit == "yes") && (!isRoot || (NumContStates > 0))
      %if dontChkEmpty || !LibSystemFcnIsEmpty(system,"MassMatrix")
    %<SLibGetBodyMassMatrixFcnCache(system)>
      %endif
    %endif
    %if ISFIELD(system,"ZeroCrossingFcn") && (!isRoot || (NumNonsampledZCs > 0))
      %if dontChkEmpty || !LibSystemFcnIsEmpty(system,"ZeroCrossing")
    %<SLibGetBodyZeroCrossingFcnCache(system)>
      %endif
    %endif
    %if ISFIELD(system,"OutputUpdateFcn")
      %<SLibGetRateGroupedFcnBody(system, "OutputUpdate", dontChkEmpty)>
    %endif
    %if ISFIELD(system,"CleanupRuntimeResourcesFcn")
      %if !LibSystemFcnIsEmpty(system, "CleanupRuntimeResources")
    %<SLibGetBodyCleanupRuntimeResourcesFcnCache(system)>
      %endif
    %endif
    %% TerminateFcn should always exist
    %if (!isRoot || !(Accelerator && CGMODEL_ACCESS("CGModel.AcceleratorExpandedSystemFcns") == 0)) && ...
      (dontChkEmpty || !LibSystemFcnIsEmpty(system,"Terminate")) && ...
      IncludeMdlTerminateFcn
      %<SLibGetBodyTerminateFcnCache(system)>
    %endif
    %if ISFIELD(system, "ConstCodeFcn")
      %if !LibSystemFcnIsEmpty(system,"ConstCode")
        %<SLibGetBodyConstCodeFcnCache(system)>
      %endif
    %endif
  %endif
  %closefile codeBuffer
  %return codeBuffer
%endfunction
 
%%Function:NotRootFileName==================================================
%%Abstract:
%%Returntrueifthecodeforthissystemdoesnotgotomodel.c
%%
%function NotRootFileName(system)
  %assign isRoot = (system.Type == "root")
  %assign notRootFileName = 0
  %if !isRoot
    %assign rootFileName = GetRootSystemSourceFileName()
    %assign notRootFileName = (system.SystemSourceFileName != rootFileName)
  %endif
  %return notRootFileName
%endfunction
 
%%Function:SLibDumpGlobalVarDeclaration=====================================
%%Abstract:
%%Dumpglobalvariabledeclrationinthespecifiedfile.
%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibDumpGlobalVarDeclaration(system, file) void
  %if !system.StandaloneSubsystem
    %assign buf = LibDeclareGlobalVars(system,"")
    %if !WHITE_SPACE(buf)
      %assign sysInfo = GetSystemNameForComments(system)
      %openfile globalBuf
       
      /* Declare global variables for system: %<sysInfo> */
      %<buf>/
      %closefile globalBuf
      %<SLibSetModelFileAttribute(file, "Declarations",globalBuf)>
    %endif
  %endif
%endfunction
 
 
%%Function:LibSetSharedFunctionOutputDir
%%TopTester:test/toolbox/rtw/targets/ert/model2model/pir2engine/-tPir2EngineLutGecks04.m
%%
%function LibSetSharedFunctionOutputDir(system, includeSourceFile)
  %assign duplicate = LibAddToReusableLibModelSources(system.SystemSourceFileName)
  %assign libname = SLibGetReusableLibraryOutputDirectory(system)
  %assign usingLibraryCode = CGMODEL_ACCESS("CGModel.getSystemUsesLibraryCode", system.SystemIdx)
  %if (usingLibraryCode)
    %assign libname = CGMODEL_ACCESS("CGModel.getCompiledLibraryFileLocation", system.SystemIdx)
  %endif
   
  %if includeSourceFile
    %assign srcFile = SLibGetFileRecForSystemCode("sys_fcn_defn", system, TLC_TRUE, TLC_FALSE)
    %<LibSetSourceFileOutputDirectory(srcFile, libname)>
  %endif
   
  %assign hdrFile = SLibGetFileRecForSystemCode("sys_fcn_decl", system, TLC_TRUE, TLC_FALSE)
  %<LibSetSourceFileOutputDirectory(hdrFile, libname)>
   
  %% Add source file
  %if LibIsSystemExistingLibrary(system) && !duplicate
    %if includeSourceFile
      %assign FileName = SLibGetFileNameForSystemCode("sys_fcn_defn", system)
      %assign sourceExt = ::LangFileExt
      %if (usingLibraryCode)
        %%assign group = "sharedlibraryutility"
        %<SLibAddGeneratedFileToList("%<FileName>.%<sourceExt>", ...
        "sharedlibraryutility","source",libname)>
      %else
      %<SLibAddGeneratedFileToList("%<FileName>.%<sourceExt>", ...
        "utility","source",libname)>
    %endif
      %<LibSetSourceFileSection(srcFile, "WrittenToDisk", TLC_TRUE)>
    %endif
     
    %% Add header file
    %assign FileName = SLibGetFileNameForSystemCode("sys_fcn_decl", system)
    %if (usingLibraryCode)
        %<SLibAddGeneratedFileToList("%<FileName>.h","sharedlibraryutility", ...
        "header",libname)>
    %else
    %<SLibAddGeneratedFileToList("%<FileName>.h","utility", ...
      "header",libname)>
    %endif
    %<LibSetSourceFileSection(hdrFile, "WrittenToDisk", TLC_TRUE)>
  %endif
  %return duplicate
%endfunction
 
 
%%Function:LibSetPublicServerOutputDir
%function LibSetPublicServerOutputDir(system) void
  %assign libname = SLibGetReusableLibraryOutputDirectory(system)
  %assign hdrFile = SLibGetFileRecForSystemCode("sys_fcn_decl", system, TLC_TRUE, TLC_FALSE)
  %<LibSetSourceFileOutputDirectory(hdrFile, libname)>
%endfunction
 
%%Function:LibSkipSystemFcnEmission
%%Abstract:Returnsifweneedtoskipemittingsystemfunction.
%%ThisistruewhenthefunctionisalreadyemittedinC++.
%function LibSkipSystemFcnEmission(system) void
  %assign skipEmittingSystemFcn = TLC_FALSE
  %if CGMODEL_ACCESS("CGModel.DirectEmitSubsystemFiles")
    %assign thisModule = ...
      ::CompiledModel.RTWCGModules.RTWCGModule[system.CGIRModuleIdx]
    %if !EXISTS(thisModule.Function)
      %return skipEmittingSystemFcn
    %endif
    %assign numFunctionRecords = SIZE(thisModule.Function)
    %assign numFunctions = numFunctionRecords[1]
    %assign prevFunctionsAreEmitted = TLC_TRUE
    %foreach idx = numFunctions
      %assign func = thisModule.Function[idx]
      %assign skipEmittingSystemFcn = ...
        prevFunctionsAreEmitted && (func.IsAlreadyEmitted == 1)
      %assign prevFunctionsAreEmitted = skipEmittingSystemFcn
    %endforeach
  %endif
  %return skipEmittingSystemFcn
%endfunction
%%endfunctionLibSkipSystemFcnEmission
 
%%Function:SLibDumpSystemHeadersAndBanner====================================
%%Abstract:
%%Dumptheheaderfilesrequiredbyasubsystem
%%Dumpbannersinthesubsystemfile
%function SLibDumpSystemHeadersAndBanner(system) void
    %assign modelName = ::CompiledModel.Name
    %assign includeBuf = ""
    %assign bannerBuf = ""
     
    %% This is where we tell the emitter to put Reusable Library Code
    %% and header files into their own Directory, not that of the model
    %if LibSystemIsReusedLibraryFcn(system)
      %assign duplicate = LibSetSharedFunctionOutputDir(system, TLC_TRUE)
    %else
      %assign duplicate = LibAddToModelSources(system.SystemSourceFileName)
    %endif
 
    %assign ::CompiledModel.HaveSeparateSourceFiles = 1
 
    %if !duplicate
      %assign fileOwnerSys = ::CompiledModel.System[system.FileNameOwnerIdx]
 
      %% If we are allowing nonreusable functions to live inside
      %% reusable functions, then handle all necessary extern
      %% global declarations in subsystem files.
      %if ::CompiledModel.AllowNoArgFcnInReusedFcn
        %<SLibGlobalFileHandling(fileOwnerSys, system)>
      %endif
      %openfile bannerBuf
      %% Dump comments, only if its the first time
      /*
      %<SLibSystemBanner(fileOwnerSys)>/
      *
      * Note that the functions contained in this file are part of a Simulink
      * model, and are not self-contained algorithms.
      */
      %closefile bannerBuf
      %openfile includeBuf
      %assign sysFileName = system.SystemHeaderFileName
      %assign fullSysFileName = sysFileName + ".h"
      %assign srcFileName = system.SystemSourceFileName + ".c"
      %if !CGMODEL_ACCESS("FileRepository.getIsFileAlreadyIncluded", fullSysFileName, srcFileName) && ...
        !((SLibAutosarActive() && LibIsGlobalServer(fileOwnerSys)) || ...
        (LibIsServer(fileOwnerSys) && fileOwnerSys.IsConstUncalledFunction == "yes"))
        #include "%<sysFileName>.h"
      %endif
       
      %% Do not put out an include for global data into a library source file
      %if !LibSystemIsReusedLibraryFcn(system)
        %if IsModelReferenceTarget()
          %assign fileName = SLibGetSystemOutputHdrFileBaseName(System[NumSystems-2])
          %% Only include the header file if the system file name is different
          %% than the model reference base system file name. Note that
          %% system.SystemFileName is included above
          %if fileName != sysFileName
            /* Include model header file for global data */
            #include "%<fileName>.h"
          %endif
        %else
          %assign modelHdrFile = LibGetMdlPubHdrBaseName() + ".h"
          %if !CGMODEL_ACCESS("FileRepository.getIsFileAlreadyIncluded", modelHdrFile , srcFileName)
          /* Include model header file for global data */
          %<SLibIncludeModelHeader()>
          %endif
        %endif
        %<SLibIncludePrivateHeader()>
      %else
        %% If we're an RLS, and there's any constant parameters, we need to include
        %% the constant parameter extern declaration.
        %if SLibHasSharedConstantParameters()
          %assign externDecls = LibGetSystemField(system, "SharedConstantsExterns")
          %<externDecls>
        %endif
        %assign rlsConstDecl = LibGetSystemField(system, "RLSConstantDecl")
        %<rlsConstDecl>
        %<LibDumpSharedDataIncludes(system)>
      %endif
      %if isRSim && (LibGetMdlSrcBaseName() != system.SystemSourceFileName)
        %assign hasFrF = FcnCheckSystemForFromFileBlock(system)
        %if hasFrF
          extern FrFInfo %<::CompiledModel.Name>_gblFrFInfo[];
        %endif
      %endif
 
      %closefile includeBuf
    %endif %% if !duplicate ... - comments dumped
 
    %<SLibCacheSystemCodeToFile("sys_src_ban", system, bannerBuf)>
    %<SLibCacheSystemCodeToFile("sys_src_incl", system, includeBuf)>
%endfunction
 
%%Function:SLibGetNeedDumpSysFcn
%%Abstract:Returnsifweneedtodumpsystemfunction.
%function SLibGetNeedDumpSysFcn(system)
  %assign res = [ TLC_FALSE, TLC_FALSE, "" ]
  %% Dump any variables needed by standalone subsystems
  %assign standVars = ""
  %if system.StandaloneSubsystem
    %assign standVars = SLibDumpStandaloneVarDeclarationsForSystem(system)
  %endif
 
  %assign needToDumpSysFcn = ((LibIsSystemNonEmpty(system) || ...
    LibIsSystemTerminateNonEmpty(system) || ...
    LibSystemIsForceNonInline(system) || ...
    !ISEMPTY(standVars) || ...
    (system.FileNameOwnerIdx == (system.SystemIdx) && ...
      !FcnCustomDataBuffersIsEmpty(system.SystemSourceFileName,"source",""))) && ...
    !LibSystemIsInlined(system))
   
  %%
  %% We are in the process of updating stateflow to mark the stateflow
  %% subsystem as "Function", if it is generating a function for the
  %% function call subsystem. When all changes are in A, we can enable
  %% the following Assertion.
  %% For now, stateflow may be inlined, therefore, we need to check
  %% the following:
  %%
  %assign needToDump = needToDumpSysFcn || ...
    !ISEMPTY(LibGetSystemField(system, "CachedSubFunctions"))
 
  %assign res[0] = needToDump
  %assign res[1] = needToDumpSysFcn
  %assign res[2] = standVars
 
  %return res
%endfunction
 
%%Function:SLibGetSystemBodyCache============================================
%%Abstract:
%%Getordumpthecachedbodyforthespecifiedsystem(includingroot).
%%
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/blocks/tselector_blkDialog.m
%%
%function SLibGetSystemBodyCache(system)
  %if LibIsSystemDumped(system)
    %return ""
  %endif
 
  %assign notRootFileName = NotRootFileName(system)
 
  %assign res = SLibGetNeedDumpSysFcn(system)
 
  %assign needToDump = res[0]
  %assign needToDumpSysFcn = res[1]
  %assign standVars = res[2]
  %assign skipSystemEmission = TLC_FALSE
 
  %if !needToDump
    %if notRootFileName && (system.FileNameOwnerIdx == (system.SystemIdx))
      %% For RLS's, if we're not generating a source file, make sure we still
      %% specify that the header file is going to shared utilities, as it will still
      %% be generated
      %if LibSystemIsReusedLibraryFcn(system)
        %assign dup = LibSetSharedFunctionOutputDir(system, TLC_FALSE)
        %% Filter the shared source file from the file repository to prevent
        %% emission of an empty file
        %assign fileIdx = SOURCE_FILE_EXISTS("%<system.Identifier>.%<::LangFileExt>")
        %if fileIdx >=0
            %<SLibDirectAccessSetFileAttribute(::CompiledModel.ModelFiles.ModelFile[fileIdx], "Filter", TLC_TRUE)>
 
            %% Also, since this subsystem isn't going to be emitted, remove the stale code generation context if we're building a
            %% a code generation context inside a library
            %if CGMODEL_ACCESS("CGModel.isCodeGenContextBuild")
                %assign shFileDMRLocation = SLibGetReusableLibraryOutputDirectory(system)
                %assign success = FEVAL("coder.internal.removeStaleCGContext", shFileDMRLocation, ::CompiledModel.Name, system.Name)
                %assert(success)
        %endif
      %endif
 
      %endif
 
      %assign skipSystemEmission = LibSkipSystemFcnEmission(system)
      %if !IsModelReferenceTarget() && !LibIsServer(system) && !skipSystemEmission
        %assign warnTxt = "The subsystem %<system.Name> specifies "...
          "file name options. However, no code is generated for this subsystem. The specified "...
          "source code file will not be created. "
        %<LibReportWarning(warnTxt)>
      %endif
    %endif
    %<LibSetSystemField(system, "SystemDumped", TLC_TRUE)>
     
    %if !skipSystemEmission
      %return ""
    %endif
  %endif
   
  %openfile codeBuffer1
    %<LibGetSystemField(system, "CachedSubFunctions")>/
  %closefile codeBuffer1
   
  %assign codeBuffer2 = SLibGetSystemFcnBodyCacheHelper(system, needToDumpSysFcn)
  %assign isMemFcn = TLC_FALSE
  %if GenerateClassInterface
    %assign isMemFcn = SLibCheckForMemFcn(system, needToDumpSysFcn)
  %endif
  %assign needNamespace = TLC_FALSE
  %if isMemFcn
    %assign needNamespace = SLibSystemNeedsNamespace(system)
  %endif
     
  %%
  %% Comparing with ::CompiledModel.Name will not hold good for RTWSFCN/ACCEL
  %% But, it's OK since we will not generate separate files for them
  %% Systems generating into model.c are handled by srtbody.tlc and dumped
  %% there directly
 
  %assign retBuf = ""
 
  %if notRootFileName
    %<SLibDumpSystemHeadersAndBanner(system)>
 
    %if (ISFIELD(system,"DSMsThatNeedFwdDecl"))
      %openfile includeDWorkDecl
      %assign DeclsNeeded = system.DSMsThatNeedFwdDecl
      %foreach dsmIdx = SIZE(DeclsNeeded,1)
          %assign declId = DeclsNeeded[dsmIdx]
          %assign dwRec = ::CompiledModel.DWorks.DWork[declId]
          %<FcnAlwaysGenerateBlockDWorkExternalDefinition(dwRec)>
      %endforeach
      %closefile includeDWorkDecl
      %<SLibCacheSystemCodeToFile("sys_data_decl", system,includeDWorkDecl )>
    %endif
     
    %<SLibCacheSystemCodeToFile("sys_fcn_defn", system, codeBuffer1)>
    %if needNamespace %%don't need to check for memfcn, it is done when assigning needNamespace
      %openfile nsopen
      %<SLibEmitNamespaceStartForSystem(system)>
      %closefile nsopen
      %<SLibCacheSystemCodeToFile("sys_fcn_defn", system, nsopen)>
    %endif
    %if isMemFcn == TLC_FALSE %%the check for namespace flag is in SLibEmitNamespaceCloseForNonMemFcn
      %openfile nsStr
        %<SLibEmitNamespaceCloseForSystem(system)>
      %closefile nsStr
      %<SLibCacheSystemCodeToFile("sys_fcn_defn", system, nsStr)>
    %endif
         
    %<SLibCacheSystemCodeToFile("sys_fcn_defn", system, codeBuffer2)>
     
    %openfile nsclose
    %<SLibEmitNamespaceCloseForSystem(system)>
    %closefile nsclose
    %<SLibCacheSystemCodeToFile("sys_fcn_defn", system, nsclose)>
            
    %<SLibCacheSystemCodeToFile("sys_stand_var_decl", system, standVars)>
    %assign isRls = LibSystemIsReusedLibraryFcn(system)
    %assign isGlobalServer = LibIsGlobalServer(system)
    %assign opFile = SLibGetFileRecForSystemCode("sys_stand_var_decl", system, isRls, isGlobalServer)
    %if !GenerateClassInterface
      %<SLibDumpGlobalVarDeclaration(system, opFile)>
    %endif
    %<LibSetSystemField(system, "SystemDumped", TLC_TRUE)>
    %% retBuf is ""
  %else %% dumping into root (model.c) or (model_acc.c)
    %assert !IsModelReferenceTarget()
    %<SLibCacheCodeToFile("mdl_stand_var_decl", standVars)>
    %assign rootFile = SLibGetFileRecForCode("mdl_stand_var_decl")
    %<SLibDumpGlobalVarDeclaration(system, rootFile)>
 
    %openfile retBuf
    %<codeBuffer1>/
    %if needNamespace
      %<SLibEmitNamespaceStartForSystem(System[NumSystems-1])>
    %endif
    %if isMemFcn == TLC_FALSE
      %<SLibEmitNamespaceCloseForSystem(System[NumSystems-1])>
    %endif
    %<codeBuffer2>/
   %<SLibEmitNamespaceCloseForSystem(System[NumSystems-1])>
    %closefile retBuf
  %endif %% if notRootFileName
 
  %return retBuf
 
%endfunction %% SLibGetSystemBodyCache
 
%%Function:FcnCheckSystemForFromFileBlock(system)
%%Description:
%%returnstrueifthesystemcontainsaFromFileblock
%%falseotherwise.
%function FcnCheckSystemForFromFileBlock(system)
  %foreach idx = system.NumBlocks
    %if system.Block[idx].Type == "FromFile"
      %return 1
    %endif
  %endforeach
  %return 0
%endfunction %% FcnCheckSystemForFromFileBlock
 
%%GeneratestheSetupRuntimeResourcesfunction.
%%
%function SLibGetBodySetupRuntimeResourcesFcnCache(ss) void
  %openfile tmpBuffer
  %<LibDumpFcnOpen(ss,"SetupRuntimeResources")>/
  %<FcnDumpMRLocalVars(ss, "SetupRuntimeResources", "")>/
  %<LibDumpSystemSSVars(ss,"SetupRuntimeResources")>/
  %<LibGetSystemLocalVars(ss,"SetupRuntimeResources","")>
  %<SLibGetFcnLocalVars(ss,"SetupRuntimeResources","")>
  %<LibDumpSystemUserCode(ss,"SetupRuntimeResources","Header")>/
  %<LibDumpGlobalVars(ss, "SetupRuntimeResources")>/
  %<LibDumpFcnBegin(ss,"SetupRuntimeResources")>/
  %<LibDumpSystemUserCode(ss,"SetupRuntimeResources","Body")>/
  %<LibDumpSystemFcn(ss,"SetupRuntimeResources")>/
  %<LibDumpSystemUserCode(ss,"SetupRuntimeResources","Trailer")>/
  %<LibDumpFcnClose(ss,"SetupRuntimeResources")>
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %openfile retBuffer
    %if LibSystemIsInlined(ss)
    %<SLibGetFcnComment(ss,"SetupRuntimeResources")>/
    %else
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"SetupRuntimeResources")
      %assign fcnInfo = LibGetFcnInfo(ss, "SetupRuntimeResources", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss, "SetupRuntimeResources")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "SetupRuntimeResources" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
      %undef fcnRec
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
%%Function:SLibGetBodyInitializeFcnCache(ss)=================================
%%Description:
%%Generatestheinitializefunctionforthesesystemtypes.
%%oenable(statesreset)
%%oenablewithtrigger(statesreset)
%%
%function SLibGetBodyInitializeFcnCache(ss) void
  %openfile tmpBuffer
  %<LibDumpFcnOpen(ss,"Initialize")>/
  %<FcnDumpMRLocalVars(ss, "Initialize", "")>/
  %<LibDumpSystemSSVars(ss,"Initialize")>/
  %<LibGetSystemLocalVars(ss,"Initialize","")>
  %<SLibGetFcnLocalVars(ss,"Initialize","")>
  %<LibDumpSystemUserCode(ss,"Initialize","Header")>/
  %<LibDumpGlobalVars(ss, "Initialize")>/
  %<LibDumpFcnBegin(ss,"Initialize")>/
  %<LibDumpSystemUserCode(ss,"Initialize","Body")>/
  %<LibDumpSystemFcn(ss,"Initialize")>/
  %<LibDumpSystemUserCode(ss,"Initialize","Trailer")>/
  %<LibDumpFcnClose(ss,"Initialize")>
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %openfile retBuffer
    %if LibSystemIsInlined(ss)
    %<SLibGetFcnComment(ss,"Initial conditions")>/
    %else
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"Initial conditions")
      %assign fcnInfo = LibGetFcnInfo(ss, "Initialize", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss, "Initial conditions")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "Initialize" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
      %undef fcnRec
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
%%Function:SLibGetBodySystemInitializeFcnCache(ss)=================================
%%Description:
%%Generatesthesysteminitializefunction.
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%
%function SLibGetBodySystemInitializeFcnCache(ss) void
  %openfile tmpBuffer
  %<LibDumpFcnOpen(ss,"SystemInitialize")>/
  %<FcnDumpMRLocalVars(ss, "SystemInitialize", "")>/
  %<LibDumpSystemSSVars(ss,"SystemInitialize")>/
  %<LibGetSystemLocalVars(ss,"SystemInitialize","")>
  %<SLibGetFcnLocalVars(ss,"SystemInitialize","")>
  %<LibDumpSystemUserCode(ss,"Initialize","Header")>/
  %<LibDumpGlobalVars(ss, "SystemInitialize")>/
  %<LibDumpFcnBegin(ss,"SystemInitialize")>/
  %<LibDumpSystemUserCode(ss,"Initialize","Body")>/
  %<LibDumpSystemFcn(ss,"SystemInitialize")>/
  %<LibDumpSystemUserCode(ss,"Initialize","Trailer")>/
  %if ExportFunctionsMode == 1
    %<LibDumpExpFucUpdateRootOutput(ss,"SystemInitialize")>/
  %endif
  %<LibDumpFcnClose(ss,"SystemInitialize")>
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %openfile retBuffer
    %if LibSystemIsInlined(ss)
    %<SLibGetFcnComment(ss,"System initialize")>/
    %else
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"System initialize")
      %assign fcnInfo = LibGetFcnInfo(ss, "SystemInitialize", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss, "System initialize")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "SystemInitialize" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
      %undef fcnRec
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
%%Function:SLibGetBodySystemResetFcnCache(ss)=================================
%%Description:
%%Generatesthesystemresetfunction.
%%
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortReset3.m
%%
%function SLibGetBodySystemResetFcnCache(ss) void
  %openfile tmpBuffer
  %<LibDumpFcnOpen(ss,"SystemReset")>/
  %<FcnDumpMRLocalVars(ss, "SystemReset", "")>/
  %<LibDumpSystemSSVars(ss,"SystemReset")>/
  %<LibGetSystemLocalVars(ss,"SystemReset","")>
  %<SLibGetFcnLocalVars(ss,"SystemReset","")>
  %<LibDumpSystemUserCode(ss,"SystemReset","Header")>/
  %<LibDumpGlobalVars(ss, "SystemReset")>/
  %<LibDumpFcnBegin(ss,"SystemReset")>/
  %<LibDumpSystemUserCode(ss,"SystemReset","Body")>/
  %<LibDumpSystemFcn(ss,"SystemReset")>/
  %<LibDumpSystemUserCode(ss,"SystemReset","Trailer")>/
  %<LibDumpFcnClose(ss,"SystemReset")>
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %openfile retBuffer
    %if LibSystemIsInlined(ss)
    %<SLibGetFcnComment(ss,"Reset conditions")>/
    %else
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"System reset")
      %assign fcnInfo = LibGetFcnInfo(ss, "SystemReset", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss, "System reset")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "SystemReset" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
      %undef fcnRec
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
%%Function:SLibGetBodyCleanupRuntimeResourcesFcnCache(ss)=================================
%%Description:
%%GeneratestheCleanupRuntimeResourcesfunction.
%%TopTester:test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref2.m
%%
%function SLibGetBodyCleanupRuntimeResourcesFcnCache(ss) void
  %openfile tmpBuffer
  %<LibDumpFcnOpen(ss,"CleanupRuntimeResources")>/
  %<FcnDumpMRLocalVars(ss, "CleanupRuntimeResources", "")>/
  %<LibDumpSystemSSVars(ss,"CleanupRuntimeResources")>/
  %<LibGetSystemLocalVars(ss,"CleanupRuntimeResources","")>
  %<SLibGetFcnLocalVars(ss,"CleanupRuntimeResources","")>
  %<LibDumpSystemUserCode(ss,"CleanupRuntimeResources","Header")>/
  %<LibDumpGlobalVars(ss, "CleanupRuntimeResources")>/
  %<LibDumpFcnBegin(ss,"CleanupRuntimeResources")>/
  %<LibDumpSystemUserCode(ss,"CleanupRuntimeResources","Body")>/
  %<LibDumpSystemFcn(ss,"CleanupRuntimeResources")>/
  %<LibDumpSystemUserCode(ss,"CleanupRuntimeResources","Trailer")>/
  %<LibDumpFcnClose(ss,"CleanupRuntimeResources")>
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %openfile retBuffer
    %if LibSystemIsInlined(ss)
    %<SLibGetFcnComment(ss,"CleanupRuntimeResources")>/
    %else
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"CleanupRuntimeResources")
      %assign fcnInfo = LibGetFcnInfo(ss, "CleanupRuntimeResources", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss, "CleanupRuntimeResources")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "CleanupRuntimeResources" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
      %undef fcnRec
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
%%Function:FcnLoadInitialState===============================================
%%Abstract:
%%LoadInitialvaluesforcontinuousanddiscretestatesthatarenon-zero.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSink/tmVarSinkRateTransBlk_VC1.m
%%
%function FcnLoadInitialState() Output
  %%
  %% Continuous States
  %%
  %foreach csIdx = ContStates.NumContStates
    %assign cs = ContStates.ContState[csIdx]
    %assign ic = cs.InitialValue
    %if ISEMPTY(ic) || !cs.DataLoggingOn
      %continue
    %endif
    %assign isMdlRef = FcnOwnerBlkType(cs) == "ModelReference"
    %if cs.Width == 1 && !isMdlRef
      %assign sgnl = SLibContinuousState(cs,"","",0,NumSystems-1, TLC_FALSE)
      %<sgnl> = %;
    %else
      %assign addr = SLibContinuousStateAddr(cs, NumSystems-1)
      {
    %assign comma = ""
    %assign varName = "rtcs%<csIdx>_%<cs.Identifier>"
    static const real_T %<varName>[%<cs.Width>] = {
          %if SIZE(ic,1) == 1
            %foreach idx = cs.Width
              %<comma>%
              %assign comma = ","
            %endforeach
          %else
            %foreach idx = cs.Width
              %<comma>%
              %assign comma = ","
            %endforeach
          %endif
    };
    (void) %<LibGenMemFcnCall("memcpy", addr, varName, ...
      "%<cs.Width>*sizeof(real_T)")>;
      }
    %endif
    %%==========================================================
    %% If the continuous is defined in an integrator, we
    %% need to tell the integrator block that the initial value
    %% does not need to be loaded any more.
    %%===========================================================
    %if cs.SigSrc[0] >= 0 && cs.SigSrc[2] >=0
      %assign system = System[cs.SigSrc[0]]
      %assign block = System[cs.SigSrc[0]].Block[cs.SigSrc[2]]
      %if block.Type=="Integrator"
        %with system
          %with block
            %<GENERATE(block, "ClearICNeedsLoading", system)>
          %endwith
        %endwith
      %endif
    %endif
     
  %endforeach
  %%
  %% Discrete States
  %%
  %foreach dwIdx = DWorks.NumDWorks
    %assign ds = DWorks.DWork[dwIdx]
    %assign ic = ds.InitialValue
    %if ISEMPTY(ic) || !ds.DataLoggingOn
      %continue
    %endif
    %with System[NumSystems-1]
      %with System[ds.SigSrc[0]].Block[ds.SigSrc[2]]
        %if !ISFIELD(ds, "FirstRootIdx")
          %addtorecord ds FirstRootIdx dwIdx
        %endif
    %assign sgnl = LibBlockDWork(ds,"","",0)
    %assign addr = LibBlockDWorkAddr(ds,"","",0)
      %endwith
    %endwith
    %if SLibDWorkWidth(ds) == 1
      %<sgnl> = %;
    %else
      {
    %assign comma = ""
    %assign varName = "rtds%<dwIdx>_%<LibGetRecordIdentifier(ds)>"
    %assign dtype = SLibGetRecordDataTypeName(ds,"")
    static const %<dtype> %<varName>[%<SLibDWorkWidth(ds)>] = {
      %if SLibDWorkIsComplex(ds)
        %foreach idx = SLibDWorkWidth(ds)
          %<comma>{%<REAL(ic[idx])>, %<IMAG(ic[idx])>}
          %assign comma = ","
        %endforeach
      %else
        %foreach idx = SLibDWorkWidth(ds)
          %<comma>%
          %assign comma = ","
        %endforeach
      %endif
    };
    (void) %<LibGenMemFcnCall("memcpy", addr, varName, ...
      "%<SLibDWorkWidth(ds)>*sizeof(%<dtype>)")>;
      }
    %endif
 
  %endforeach
%endfunction %% FcnLoadInitialState
 
%%Function:FcnInitializeDatasetInput==========================================
%%Abstract:
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tVariantSimulinkFunctionAutoInherit.m
%function FcnInitializeDatasetInput(system) Output
  %<SLibAddToNonSharedIncludes("sigstream_rtw.h")>
  %<SLibAddToNonSharedIncludes("simtarget/slSimTgtSigstreamRTW.h")>
  %<SLibAddToNonSharedIncludes("simtarget/slSimTgtSlioCoreRTW.h")>
  %<SLibAddToNonSharedIncludes("simtarget/slSimTgtSlioClientsRTW.h")>
  %<SLibAddToNonSharedIncludes("simtarget/slSimTgtSlioSdiRTW.h")>
  {
    bool externalInputIsInDatasetFormat = false;
    %if ExternalInputs.NumAperiodicPartitions > 0
      bool hasAperiodicPartitionHitTimes = false;
    %endif
    void *pISigstreamManager = rt_GetISigstreamManager();
    rtwISigstreamManagerGetInputIsInDatasetFormat( ...
      pISigstreamManager, ...
      &externalInputIsInDatasetFormat ...
      );
    if (externalInputIsInDatasetFormat) {
      %foreach idx = ExternalInputs.NumExternalInputs
        %% TopTester: matlab/test/toolbox/simulink/sl_loading/tDatasetFormat.m
        %assign extInp = ExternalInputs.ExternalInput[idx]
        %% Inactive (SVCE false) inports built in raccel will not be present. Hence, skip init'ing them
        %% TopTester: matlab/test/toolbox/simulink/variants/inlineVariants/ivGeneral/tRootIOFcnCall.m -testspec:lvlTwo_mG1377701_ra
        %if ISFIELD(extInp, "Inactive")
            %continue
        %endif
        %assign fcnCall = extInp.FunctionCallInitiator == "yes"
        %assign hasFcnCallInfo = LibIsSystemField(system, "FcnCallInputInfo")
        %if fcnCall
          %% TopTester: test/toolbox/simulink/variants/inlineVariants/ivGeneral/tsimfcsys_rapidaccel.m
          %if hasFcnCallInfo
          %with system
            %with FcnRootOpaqueBlock()
              %assign currentBlockFcn = ::BlockFcn
              %assign ::BlockFcn = "Start"
              %assign fcnCallInfo = LibGetSystemField(system, "FcnCallInputInfo")
              %assign fcnCallIdx = 0
              %foreach idx2 = SIZE(fcnCallInfo.FcnCallInfo,1)
                %assign info = fcnCallInfo.FcnCallInfo[idx2]
                %if(info.PortIdx == idx)
                  %assign fcnCallIdx = idx2
                  %break
                %endif
              %endforeach
              %assign dworkIdx = fcnCallInfo.FcnCallInfo[fcnCallIdx].dworkIndex
              %assign dwork = ::CompiledModel.DWorks.DWork[dworkIdx]
              %assign youtAddr = LibBlockDWorkAddr(dwork, "", "", 0)
              rtwISigstreamManagerSetDestinationBase( ...
                pISigstreamManager, ...
                %<idx>, ...
                %<youtAddr> ...
                );
              %assign ::BlockFcn = currentBlockFcn
            %endwith %% %with FcnRootOpaqueBlock()
          %endwith %% %with system
          %endif
        %else %% %if fcnCall
          %assign yout = SLibGetExtUIdentifier(extInp, "0", "%<tRealPart>")
          %assign youtAddr = "&" + yout
          rtwISigstreamManagerSetDestinationBase( ...
            pISigstreamManager, ...
            %<idx>, ...
            %<youtAddr> ...
            );
        %endif %% %if fcnCall
      %endforeach
    }
       
    %if ExternalInputs.NumAperiodicPartitions > 0
      rtwISigstreamManagerHasAperiodicPartitionHitTimes( ...
        pISigstreamManager, ...
        &hasAperiodicPartitionHitTimes ...
        );
      if (hasAperiodicPartitionHitTimes) {
        %foreach idx = ExternalInputs.NumAperiodicPartitions
          %assign upInfo = ExternalInputs.AperiodicPartitions[idx]
          %assign name = upInfo.Name
          gblAperiodicPartitionSignalIds[%<idx>] = ...
            rtwISigstreamManagerAperiodicPartitionDestinationIdx( ...
            pISigstreamManager, ...
            "%<name>");
          if (gblAperiodicPartitionSignalIds[%<idx>] != -1) {
            rtwISigstreamManagerSetDestinationBase( ...
              pISigstreamManager, ...
              gblAperiodicPartitionSignalIds[%<idx>], ...
              &gblUconstrainedPartitionNumHits[%<idx>]);
          }
        %endforeach
      }
    %endif
    %if ::raccelObserverLog
        observerLogInit();
    %endif
  }
%endfunction %% FcnInitializeDatasetInput
 
%%Function:FcnCreateOSigstreamManager=========================================
%%Abstract:
%%CreatesaninstanceofSigstreamManagertobeusedforloggingduringthe
%%simulation.
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tVariantSimulinkFunctionAutoInherit.m
%%
%function FcnCreateOSigstreamManager() Output
  %if FEVAL("Simulink.sdi.useSLIOForLogging")
    %<SLibAddToNonSharedIncludes("simtarget/slSimTgtSigstreamRTW.h")>
    %<SLibAddToNonSharedIncludes("simtarget/slSimTgtSlioCoreRTW.h")>
    %<SLibAddToNonSharedIncludes("simtarget/slSimTgtSlioClientsRTW.h")>
    %<SLibAddToNonSharedIncludes("simtarget/slSimTgtSlioSdiRTW.h")>
    %assign nulldef = SLibGetNullDefinitionFromTfl()
    {
      void **slioCatalogueAddr = rt_slioCatalogueAddr();
      void * r2 = %<nulldef>;
      void **pOSigstreamManagerAddr = %<nulldef>;
      const int maxErrorBufferSize = 16384; %% 16k
      char errMsgCreatingOSigstreamManager[16384];
      bool errorCreatingOSigstreamManager = false;
      const char * errorAddingR2SharedResource = %<nulldef>;
      *slioCatalogueAddr = rtwGetNewSlioCatalogue(rt_GetMatSigLogSelectorFileName());
      errorAddingR2SharedResource = rtwAddR2SharedResource(rtwGetPointerFromUniquePtr(rt_slioCatalogue()), %<::CompiledModel.ErrorXMLMode> );
      if (errorAddingR2SharedResource != %<nulldef>) {
        rtwTerminateSlioCatalogue(slioCatalogueAddr);
        *slioCatalogueAddr = %<nulldef>;
        %<RTMSetErrStat("errorAddingR2SharedResource")>;
        return;
      }
      r2 = rtwGetR2SharedResource(rtwGetPointerFromUniquePtr(rt_slioCatalogue()));
      pOSigstreamManagerAddr = rt_GetOSigstreamManagerAddr();
      errorCreatingOSigstreamManager = rtwOSigstreamManagerCreateInstance(
        rt_GetMatSigLogSelectorFileName(),
        r2,
        pOSigstreamManagerAddr,
        errMsgCreatingOSigstreamManager,
        maxErrorBufferSize
        );
      if (errorCreatingOSigstreamManager) {
        *pOSigstreamManagerAddr = %<nulldef>;
        %<RTMSetErrStat("errMsgCreatingOSigstreamManager")>;
        return;
      }
    }
  %endif
%endfunction %% FcnCreateOSigstreamManager
 
%%Function:SLibGetBodyStartFcnCache(ss)======================================
%%Description:
%%Generatesthestartfunctionforsystems
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmVariantsRSim.m
%%TopTester:test/toolbox/simulink/blocks/lib_Discrete/DiscreteTimeIntegrator/rtw/tdintegrt.m
%%
%function SLibGetBodyStartFcnCache(ss) void
  %assign isRootInSfcn = (ss.Type == "root") && ...
    (CodeFormat == "S-Function") && !Accelerator
 
  %openfile tmpBuffer
  %<LibDumpFcnOpen(ss,"Start")>/
  %<FcnDumpMRLocalVars(ss, "Start", "")>/
  %if isRootInSfcn
    %<LibDumpSfunTargetChecks()> /
    {
  %endif
  %<LibDumpSystemSSVars(ss,"Start")>/
  %<LibGetSystemLocalVars(ss,"Start","")>
  %<SLibGetFcnLocalVars(ss,"Start","")>
  %<LibDumpSystemUserCode(ss,"Start","Header")>/
  %<LibDumpGlobalVars(ss, "Start")>/
  %<LibDumpFcnBegin(ss,"Start")>/
  %% open code
  %openfile tmpBuffer2
  %if (ss.Type == "root") && ::isRAccel
    %<FcnCreateOSigstreamManager()>
    %<FcnInitializeDatasetInput(ss)>
    %if EXISTS(CompiledModel.SupportSimEventsRegistration)
      /* Initialize Discrete Event Systems*/
      sldeInitialize();
    %endif
  %endif
  %if ss.Type == "root" && (::isRAccel || isRSim)
    %<SLibDumpOpaqueTypeConstructCode(::CompiledModel.System[GetBaseSystemIdx()])>
  %endif
  %<LibDumpSystemUserCode(ss,"Start","Body")>/
  %<LibDumpSystemFcn(ss,"Start")>/
  %<LibDumpSystemUserCode(ss,"Start","Trailer")>/
  %%
  %% For some targets, we allow root to call Initialize and Enable
  %% within the context of start
  %%
  %if (ss.Type == "root")
    %if RootBodyStartCallsInitEnab
      %if (!LibSystemFcnIsEmpty(ss, "SystemInitialize"))
        %assign fcnInfo = LibGetSystemField(ss, "SystemInitialize" + "FcnInfo")
        %assign comArgs = fcnInfo.CommonArgs
        %<fcnInfo.Name>(%<comArgs>);
      %endif
      %if (!LibSystemFcnIsEmpty(ss, "Enable"))
    %assign fcnInfo = LibGetSystemField(ss, "Enable" + "FcnInfo")
    %assign comArgs = fcnInfo.CommonArgs
    %<fcnInfo.Name>(%<comArgs>);
      %endif
    %endif
    %% Load intial states if needed.
    %<FncGenInitStatesInRootStart()>
  %endif
  %if isRootInSfcn
    %assign prevBlockFcn = ::BlockFcn
    %assign ::BlockFcn = "Start"
    %assign buff = ""
    %openfile buff
    %<SLibInitPrevZCSignalStates()>
    %closefile buff
    %assign ::BlockFcn = prevBlockFcn
    %if !WHITE_SPACE(buff)
       
      /* Previous zero-crossing state intialization */
      %<buff>
    %endif
    }
  %endif
  %closefile tmpBuffer2
  %% extra code for exported function to update external outputs
  %<tmpBuffer2>/
  %% close code
  %<LibDumpFcnClose(ss,"Start")>
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %openfile retBuffer
    %if LibSystemIsInlined(ss)
    %<SLibGetFcnComment(ss,"Start")>/
    %else
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"Start")
      %assign fcnInfo = LibGetFcnInfo(ss, "Start", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss, "Start")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "Start" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
 
%%Function:SLibGetBodyOutputFcnCache(ss)=====================================
%%Description:
%%Generatestheoutputfunctionforanenablesubsystem.
%%
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/sim/tg1167032.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tmemLayoutBlksInactivPorts.m
%%
%function SLibGetBodyOutputFcnCache(ss) void
  %if SLibSystemFcnPeriodicRateGrouping(ss, "Output") || ...
    LibAsynchronousTriggeredTID(ss.CurrentTID) || ...
    (SLibPartitionGroupingSystem(ss))
    %assign tid = ss.CurrentTID
  %else
    %assign tid = ""
  %endif
   
  %if LibAsynchronousTriggeredTID(tid) && !SLibNonInlinedModelWideEventTID(tid)
    %if (SLibIsMultiRateAndPeriodicRateGrouping(ss) || ...
      !FcnIsForcedInlinedForAsync(ss,tid) || ...
      LibIsDeploymentDiagram() || ...
      SLibIsExplicitTaskingExportFcnRateGrouping("Output", tid))
      %assign systemFcnIsEmpty = LibSystemFcnIsEmptyForTID(ss, "Output")
    %else
      %assign systemFcnIsEmpty = TLC_TRUE
    %endif
  %else
    %% Added ::isRAccel for test/toolbox/simulink/modelref/fcncall/client_server/inout_args/tinout_args1
    %if ISEQUAL(tid, "") && (!SLibIsExportFcnDiagram() || ::isRAccel)
      %% If not grouping rating, system output
      %% fcn always exists
      %assign systemFcnIsEmpty = TLC_FALSE
    %else
      %assign systemFcnIsEmpty = LibSystemFcnIsEmptyForTID(ss, "Output")
    %endif
  %endif
   
  %if IsModelReferenceBaseSys(ss)
    %% Create and initialize it here. It may be updated at the end
    %% of the function
    %addtorecord ss ModelRefOutputFcnIsEmpty%<tid> "yes"
  %endif
 
  %if systemFcnIsEmpty
    %return ""
  %endif
 
  %assign isSSMapped = SLibPartitionGroupingSystem(ss)
  %if isSSMapped
    %assert TYPE(tid) == "Number"
  %endif
  %openfile tmpBuffer
  %if !isSSMapped
    %<LibDumpFcnOpen(ss,"Output")>/
  %endif
  %<FcnDumpMRLocalVars(ss, "Output", tid)>/
  %% Profiler declaration code
  %<LibDumpSystemProfileCode(ss,"Output", "Decls")>/
  %<LibDumpSystemSSVars(ss,"Output")>/
  %if !isSSMapped
    %<LibGetSystemLocalVars(ss,"Output",tid)>
    %<SLibGetFcnLocalVars(ss,"Output",tid)>
  %endif
  %<LibDumpSystemUserCode(ss,"Output","Header")>/
  %if !LibSystemFcnIsEmpty(ss, "Output")
    %if !isSSMapped
      %<LibDumpGlobalVars(ss, "Output%<tid>")>/
    %else
      %<LibDumpGlobalVars(ss, "Output%<tid>%<ss.CurrentPID>")>/
    %endif
  %endif
  %if !ISEQUAL(ss.Type, "root")
    %<LibDumpFcnBegin(ss,"Output")>/
  %endif
   
  %%
  %% Generated S-Function data store reads
  %%
  %if (ss.Type == "root") && (CodeFormat == "S-Function") && !Accelerator
    %assign ::BlockFcn = "Output"
    %<SLibGenDataStoreReads(::tSimStruct)>
    %assign ::BlockFcn = "Unknown"
  %endif
   
  %% Profiler start code
  %<LibDumpSystemProfileCode(ss,"Output", "Start")>/
 
  %% When we are generating for model reference, write out
  %% part of the ERT timing Engine.
  %% output code
  %if !isSSMapped
    %<UpdateRateTransitionFlagsHelper(ss, tid, TLC_FALSE)>
  %endif
  %<LibDumpSystemUserCode(ss,"Output","Body")>/
 
  %if isSSMapped
    %<LibDumpSystemFcn(ss,"Output%<tid>%<ss.CurrentPID>")>/
  %else
     %<LibDumpSystemFcn(ss,"Output%<tid>")>/
  %endif
  %<LibDumpSystemUserCode(ss,"Output","Trailer")>/
  %if !isSSMapped || SLibPartitionNeedTIDArg(ss.CurrentPID)
    %<FcnHandlesUnusedTIDArg(ss, "Output")>
  %endif
  %<FcnHandlesUnusedRTMForSimplifiedInterface(ss, "Output")>
   
  %% Profiler finish code
  %<LibDumpSystemProfileCode(ss,"Output", "End")>/
 
  %%
  %% Generated S-Function data store writes
  %%
  %if (ss.Type == "root") && (CodeFormat == "S-Function") && !Accelerator
    %assign ::BlockFcn = "Output"
    %<SLibGenDataStoreWrites(::tSimStruct)>
    %assign ::BlockFcn = "Unknown"
  %endif
  %if !isSSMapped
    %<LibDumpFcnClose(ss,"Output")>
  %endif
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %openfile retBuffer
    %assign expFcn = SLibIsExplicitTaskingExportFcnRateGrouping("Output",ss.CurrentTID)
    %if LibSystemIsInlined(ss) && (!isSSMapped) && !expFcn
    %<SLibGetFcnComment(ss,"Outputs")>/
    %elseif !isSSMapped && !expFcn
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"Outputs")
      %assign fcnInfo = LibGetFcnInfo(ss, "Output", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss,"Outputs")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "Output" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
      %<addToBackupCodeMetrics(ss, fcnInfo.Name, fcnInfo.Name, tid)>
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
 
    %if IsModelReferenceBaseSys(ss)
      %assign ss.ModelRefOutputFcnIsEmpty%<tid> = "no"
    %endif
 
  %endif
 
  %return retBuffer
%endfunction %% SLibGetBodyOutputFcnCache
 
%%Function:SLibGetBodyUpdateFcnCache(ss)=====================================
%%Description:
%%Generatestheupdatefunctionforanenablesubsystem.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants2.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants3.m
%%
%function SLibGetBodyUpdateFcnCache(ss) void
  %if SLibNonInlinedIRTEventTID(ss.CurrentTID)
    %return ""
  %endif
   
  %if SLibSystemFcnPeriodicRateGrouping(ss, "Update") || ...
    LibAsynchronousTriggeredTID(ss.CurrentTID) || ...
    (SLibPartitionGroupingSystem(ss))
    %assign tid = ss.CurrentTID
  %else
    %assign tid = ""
  %endif
 
  %if IsModelReferenceBaseSys(ss)
    %addtorecord ss ModelRefUpdateFcnIsEmpty%<tid> "yes"
  %endif
   
  %assign isSSMapped = SLibPartitionGroupingSystem(ss)
  %if isSSMapped
    %assert TYPE(tid) == "Number"
  %endif
  %openfile tmpBuffer
  %if !isSSMapped
    %<LibDumpFcnOpen(ss,"Update")>/
  %endif
  %<FcnDumpMRLocalVars(ss, "Update", tid)>/
  %% Profiler declaration code
  %<LibDumpSystemProfileCode(ss,"Update", "Decls")>/
 
  %<LibDumpSystemSSVars(ss,"Update")>/
  %if !isSSMapped
    %<LibGetSystemLocalVars(ss,"Update",tid)>
    %<SLibGetFcnLocalVars(ss,"Update",tid)>
  %endif
  %<LibDumpSystemUserCode(ss,"Update","Header")>/
  %if isSSMapped
    %<LibDumpGlobalVars(ss, "Update%<tid>%<ss.CurrentPID>")>/
  %else
    %<LibDumpGlobalVars(ss, "Update%<tid>")>/
  %endif
  %if !isSSMapped
    %<LibDumpFcnBegin(ss,"Update")>/
  %endif
 
  %% Profiler start code
  %<LibDumpSystemProfileCode(ss,"Update", "Start")>/
   
  %% open code
  %<LibDumpSystemUserCode(ss,"Update","Body")>/
  %if isSSMapped
    %<LibDumpSystemFcn(ss,"Update%<tid>%<ss.CurrentPID>")>/
  %else
    %<LibDumpSystemFcn(ss,"Update%<tid>")>/
  %endif
  %<LibDumpSystemUserCode(ss,"Update","Trailer")>/
  %<FcnHandlesUnusedTIDArg(ss, "Update")>
  %<FcnHandlesUnusedRTMForSimplifiedInterface(ss, "Update")>
 
  %% Profiler finish code
  %<LibDumpSystemProfileCode(ss,"Update", "End")>/
  %if !isSSMapped
    %<LibDumpFcnClose(ss,"Update")>
  %endif
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %openfile retBuffer
    %if LibSystemIsInlined(ss) && (!isSSMapped)
    %<SLibGetFcnComment(ss,"Update")>/
    %elseif !isSSMapped
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"Update")
      %assign fcnInfo = LibGetFcnInfo(ss, "Update", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss,"Update")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "Update" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
      %<addToBackupCodeMetrics(ss, fcnInfo.Name, fcnInfo.Name, tid)>
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
    %if IsModelReferenceBaseSys(ss)
      %assign ss.ModelRefUpdateFcnIsEmpty%<tid> = "no"
    %endif
  %endif
  %return retBuffer
%endfunction %%SLibGetBodyUpdateFcnCache
 
%%Function:SLibGetBodyDerivativeFcnCache(ss)=================================
%%Description:
%%Generatesthederivativesfunctionforanenablesystemcontaining
%%continuousstates.NotethatDerivativeFcnonlyexistsifthe
%%systemhascontinuousstates.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants3.m
%%
%function SLibGetBodyDerivativeFcnCache(ss) void
  %openfile tmpBuffer
  %assign isSSMapped = SLibIsMappedInDeploymentDiagram(ss)
  %if (SLibIsERTCodeFormat()) && LibSystemIsRoot(ss) && !isSSMapped
    %assign fcnRec = LibGetSystemField(ss, "DerivativeFcnInfo")
    %if !GenerateClassInterface
      %assign fcnName = "%<fcnRec.Name>"
    %else
      %assign classConfObj = FcnGetRTWCPPStepPrototypeRecord()
      %assign fcnName = "%<classConfObj.ModelClassName>::%<fcnRec.Name>"
    %endif
    %<SLibGetFcnMemSecPragma(fcnName, "MemSecFuncExecute", "Pre")>/
    %assign fcnReturns = "void"
    %assign fcnParams = "%<SLibModelFcnArgs("Derivative",0,"")>"
    %createrecord fcnInfo {Name fcnName; Returns fcnReturns; Params fcnParams}
    %openfile localVariables
    %if MultiInstanceERTCode && !GenerateClassInterface
      %<SLibDumpLocalVariablesForBlockFcn(rootSystem, "Derivative")>
    %endif
    %closefile localVariables
     
    %<fcnReturns> %<fcnName>(%<fcnParams>)
    {
      %if !WHITE_SPACE(localVariables)
        %<localVariables>
      %endif
  %else
    %assign fcnInfo = LibGetFcnInfo(ss, "Derivative", ss.CurrentTID)
    %if !isSSMapped || SLibPartitionNeedContFcnDecl(ss.CurrentPID)
      %% If this is not generated for partition grouping or, in MDS
      %% this is generated for synthesized task with continuous rate,
      %% we then need the fcn open
      %<LibDumpFcnOpen(ss,"Derivative")>/
    %else
      %% If this is generated for explicit partition, ignore fcn open
      %% but adding a left bracket to create a name scope
      {
    %endif
  %endif
   
  %<FcnDumpMRLocalVars(ss, "Derivative", "")>/
  %% Profiler declaration code
  %<LibDumpSystemProfileCode(ss,"Derivative", "Decls")>/
 
  %assign tidTrailer = isSSMapped ? "%<ss.CurrentTID>" : ""
  %assign pidTrailer = isSSMapped ? "%<ss.CurrentPID>" : ""
   
  %<LibDumpSystemSSVars(ss,"Derivative%<tidTrailer>%<pidTrailer>")>/
  %<LibGetSystemLocalVars(ss,"Derivative","%<tidTrailer>")>
  %<SLibGetFcnLocalVars(ss,"Derivative","%<tidTrailer>")>
  %<LibDumpSystemUserCode(ss,"Derivative","Header")>/
  %<LibDumpGlobalVars(ss, "Derivative%<tidTrailer>%<pidTrailer>")>/
  %<LibDumpFcnBegin(ss,"Derivative")>/
   
  %% Profiler start code
  %<LibDumpSystemProfileCode(ss,"Derivative", "Start")>/
 
  %% open code
  %<LibDumpSystemUserCode(ss,"Derivative","Body")>/
  %<LibDumpSystemFcn(ss,"Derivative%<tidTrailer>%<pidTrailer>")>/
  %<LibDumpSystemUserCode(ss,"Derivative","Trailer")>/
   
  %% Profiler finish code
  %<LibDumpSystemProfileCode(ss,"Derivative", "End")>/
   
  %<LibDumpFcnClose(ss,"Derivative")>
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %assign isSSMapped = SLibIsMappedInDeploymentDiagram(ss)
    %openfile retBuffer
    %if LibSystemIsInlined(ss) && (!isSSMapped)
      %<SLibGetFcnComment(ss,"Derivatives")>/
    %elseif (!isSSMapped) || SLibPartitionNeedContFcnDecl(ss.CurrentPID)
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"Derivatives")
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss,"Derivatives")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "Derivative" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
 
%%Function:SLibGetBodyProjectionFcnCache(ss)=================================
%%Description:
%%Generatestheprojectionfunctionforanenablesystemcontaining
%%continuousstates.NotethatProjectionFcnonlyexistsifthe
%%systemhascontinuousstates.
%%
%%TopTester:test/toolbox/simulink/blocks/lib_SignalAttributes/InitialCondition/rtw/tinitcond.m
%%
%function SLibGetBodyProjectionFcnCache(ss) void
  %assign tmpBuffer = ""
  %if CodeFormat == "S-Function" && ModelHasProjections == "yes" || ...
    CodeFormat != "S-Function"
    %openfile tmpBuffer
    %assign isSSMapped = SLibIsMappedInDeploymentDiagram(ss)
    %if (SLibIsERTCodeFormat()) && LibSystemIsRoot(ss) && !isSSMapped
      %assign fcnRec = LibGetSystemField(ss, "ProjectionFcnInfo")
      %if !GenerateClassInterface
        %assign fcnName = "%<fcnRec.Name>"
      %else
        %assign classConfObj = FcnGetRTWCPPStepPrototypeRecord()
        %assign fcnName = "%<classConfObj.ModelClassName>::%<fcnRec.Name>"
      %endif
      %<SLibGetFcnMemSecPragma(fcnName, "MemSecFuncExecute", "Pre")>/
      %assign fcnReturns = "void"
      %assign fcnParams = SLibModelFcnArgs("Projection",0,"")
      %createrecord fcnInfo {Name fcnName; Returns fcnReturns; Params fcnParams}
      %openfile localVariables
      %if MultiInstanceERTCode && !GenerateClassInterface
        %<SLibDumpLocalVariablesForBlockFcn(rootSystem, "Projection")>
      %endif
      %closefile localVariables
       
      %<fcnReturns> %<fcnName>(%<fcnParams>)
      {
        %if !WHITE_SPACE(localVariables)
          %<localVariables>
        %endif
    %else
      %assign fcnInfo = LibGetFcnInfo(ss, "Projection", ss.CurrentTID)
      %if !isSSMapped || SLibPartitionNeedContFcnDecl(ss.CurrentPID)
        %<LibDumpFcnOpen(ss,"Projection")>/
      %else
        {
      %endif
    %endif
     
    %assign tidTrailer = isSSMapped ? "%<ss.CurrentTID>" : ""
    %assign pidTrailer = isSSMapped ? "%<ss.CurrentPID>" : ""
 
    %<FcnDumpMRLocalVars(ss, "Projection", "%<tidTrailer>")>/
    %<LibDumpSystemSSVars(ss,"Projection%<tidTrailer>%<pidTrailer>")>/
    %<LibGetSystemLocalVars(ss,"Projection","%<tidTrailer>")>
    %<SLibGetFcnLocalVars(ss,"Projection","%<tidTrailer>")>
    %<LibDumpSystemUserCode(ss,"Projection","Header")>/
    %<LibDumpGlobalVars(ss, "Projection%<tidTrailer>%<pidTrailer>")>/
    %<LibDumpFcnBegin(ss,"Projection")>/
    %% open code
    %<LibDumpSystemUserCode(ss,"Projection","Body")>/
    %<LibDumpSystemFcn(ss,"Projection%<tidTrailer>%<pidTrailer>")>/
    %<LibDumpSystemUserCode(ss,"Projection","Trailer")>/
    %<LibDumpFcnClose(ss,"Projection")>
    %closefile tmpBuffer
  %endif
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %assign isSSMapped = SLibIsMappedInDeploymentDiagram(ss)
    %openfile retBuffer
    %if LibSystemIsInlined(ss) && (!isSSMapped)
      %<SLibGetFcnComment(ss,"Projection")>/
    %elseif !isSSMapped || SLibPartitionNeedContFcnDecl(ss.CurrentPID)
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"Projection")
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss,"Projection")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "Projection" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
%%Function:SLibGetBodyForcingFunctionFcnCache(ss)=================================
%%Description:
%%GeneratestheForcingFunctionfunctionforanenablesystemcontaining
%%continuousstates.NotethatForcingFunctionFcnonlyexistsifthe
%%systemhascontinuousstates.
%%
%function SLibGetBodyForcingFunctionFcnCache(ss) void
  %assign tmpBuffer = ""
  %if ModelIsLinearlyImplicit == "yes"
    %openfile tmpBuffer
    %assign isSSMapped = SLibIsMappedInDeploymentDiagram(ss)
    %if (SLibIsERTCodeFormat()) && LibSystemIsRoot(ss) && !isSSMapped
      %assign fcnRec = LibGetSystemField(ss, "ForcingFunctionFcnInfo")
      %if !GenerateClassInterface
        %assign fcnName = "%<fcnRec.Name>"
      %else
        %assign classConfObj = FcnGetRTWCPPStepPrototypeRecord()
        %assign fcnName = "%<classConfObj.ModelClassName>::%<fcnRec.Name>"
      %endif
      %<SLibGetFcnMemSecPragma(fcnName, "MemSecFuncExecute", "Pre")>/
      %assign fcnReturns = "void"
      %assign fcnParams = SLibModelFcnArgs("ForcingFunction",0,"")
      %createrecord fcnInfo {Name fcnName; Returns fcnReturns; Params fcnParams}
      %openfile localVariables
      %if MultiInstanceERTCode && !GenerateClassInterface
        %<SLibDumpLocalVariablesForBlockFcn(rootSystem, "ForcingFunction")>
      %endif
      %closefile localVariables
       
      %createrecord fcnInfo {Name fcnName; Returns fcnReturns; Params fcnParams}
      %<fcnReturns> %<fcnName>(%<fcnParams>)
      {
        %if !WHITE_SPACE(localVariables)
           %<localVariables>
        %endif
    %else
      %assign fcnInfo = LibGetFcnInfo(ss, "ForcingFunction", ss.CurrentTID)
      %if !isSSMapped || SLibPartitionNeedContFcnDecl(ss.CurrentPID)
        %<LibDumpFcnOpen(ss,"ForcingFunction")>/
      %else
        {
      %endif
    %endif
     
    %assign tidTrailer = isSSMapped ? "%<ss.CurrentTID>" : ""
    %assign pidTrailer = isSSMapped ? "%<ss.CurrentPID>" : ""
     
    %<FcnDumpMRLocalVars(ss, "ForcingFunction", "%<tidTrailer>")>/
    %<LibDumpSystemSSVars(ss,"ForcingFunction%<tidTrailer>%<pidTrailer>")>/
    %<LibGetSystemLocalVars(ss,"ForcingFunction","%<tidTrailer>")>
    %<SLibGetFcnLocalVars(ss,"ForcingFunction","%<tidTrailer>")>
    %<LibDumpSystemUserCode(ss,"ForcingFunction","Header")>/
    %<LibDumpGlobalVars(ss, "ForcingFunction%<tidTrailer>%<pidTrailer>")>/
    %<LibDumpFcnBegin(ss,"ForcingFunction")>/
    %% open code
    %<LibDumpSystemUserCode(ss,"ForcingFunction","Body")>/
    %<LibDumpSystemFcn(ss,"ForcingFunction%<tidTrailer>%<pidTrailer>")>/
    %<LibDumpSystemUserCode(ss,"ForcingFunction","Trailer")>/
    %% close code
    %<LibDumpFcnClose(ss,"ForcingFunction")>
    %closefile tmpBuffer
  %endif
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %assign isSSMapped = SLibIsMappedInDeploymentDiagram(ss)
    %openfile retBuffer
    %if LibSystemIsInlined(ss) && (!isSSMapped)
      %<SLibGetFcnComment(ss,"ForcingFunction")>
    %elseif (!isSSMapped) || SLibPartitionNeedContFcnDecl(ss.CurrentPID)
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"ForcingFunction")
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss,"ForcingFunction")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "Forcing" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
 
%%Function:SLibGetBodyMassMatrixFcnCache(ss)=================================
%%Description:
%%GeneratestheMassMatrixfunctionforanenablesystemcontaining
%%continuousstates.NotethatMassMatrixFcnonlyexistsifthe
%%systemhascontinuousstates.
%%
%function SLibGetBodyMassMatrixFcnCache(ss) void
  %assign tmpBuffer = ""
  %if ModelIsLinearlyImplicit == "yes"
    %openfile tmpBuffer
    %assign isSSMapped = SLibIsMappedInDeploymentDiagram(ss)
    %if (SLibIsERTCodeFormat()) && LibSystemIsRoot(ss) && !isSSMapped
      %assign fcnRec = LibGetSystemField(ss, "MassMatrixFcnInfo")
      %if !GenerateClassInterface
        %assign fcnName = "%<fcnRec.Name>"
      %else
        %assign classConfObj = FcnGetRTWCPPStepPrototypeRecord()
        %assign fcnName = "%<classConfObj.ModelClassName>::%<fcnRec.Name>"
      %endif
      %<SLibGetFcnMemSecPragma(fcnName, "MemSecFuncExecute", "Pre")>/
      %assign fcnReturns = "void"
      %assign fcnParams = SLibModelFcnArgs("MassMatrix",0,"")
      %createrecord fcnInfo {Name fcnName; Returns fcnReturns; Params fcnParams}
      %openfile localVariables
      %if MultiInstanceERTCode && !GenerateClassInterface
        %<SLibDumpLocalVariablesForBlockFcn(rootSystem, "MassMatrix")>
      %endif
      %closefile localVariables
       
      %<fcnReturns> %<fcnName>(%<fcnParams>)
      {
        %if !WHITE_SPACE(localVariables)
           %<localVariables>
        %endif
    %else
      %assign fcnInfo = LibGetFcnInfo(ss, "MassMatrix", ss.CurrentTID)
      %if !isSSMapped || SLibPartitionNeedContFcnDecl(ss.CurrentPID)
        %<LibDumpFcnOpen(ss,"MassMatrix")>/
      %else
        {
      %endif
    %endif
     
    %assign tidTrailer = isSSMapped ? "%<ss.CurrentTID>" : ""
    %assign pidTrailer = isSSMapped ? "%<ss.CurrentPID>" : ""
     
    %<FcnDumpMRLocalVars(ss, "MassMatrix", "%<tidTrailer>")>/
    %<LibDumpSystemSSVars(ss,"MassMatrix%<tidTrailer>%<pidTrailer>")>/
    %<LibGetSystemLocalVars(ss,"MassMatrix","%<tidTrailer>")>
    %<SLibGetFcnLocalVars(ss,"MassMatrix","%<tidTrailer>")>
    %<LibDumpSystemUserCode(ss,"MassMatrix","Header")>/
    %<LibDumpGlobalVars(ss, "MassMatrix%<tidTrailer>%<pidTrailer>")>/
    %<LibDumpFcnBegin(ss,"MassMatrix")>/
    %% open code
    %<LibDumpSystemUserCode(ss,"MassMatrix","Body")>/
    %<LibDumpSystemFcn(ss,"MassMatrix%<tidTrailer>%<pidTrailer>")>/
    %<LibDumpSystemUserCode(ss,"MassMatrix","Trailer")>/
    %% close code
    %<LibDumpFcnClose(ss,"MassMatrix")>
    %closefile tmpBuffer
  %endif
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %assign isSSMapped = SLibIsMappedInDeploymentDiagram(ss)
    %openfile retBuffer
    %if LibSystemIsInlined(ss) && (!isSSMapped)
    %<SLibGetFcnComment(ss,"MassMatrix")>/
    %elseif (!isSSMapped) || SLibPartitionNeedContFcnDecl(ss.CurrentPID)
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"MassMatrix")
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss,"MassMatrix")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "MassMatrix" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
 
%%Function:SLibGetBodyZeroCrossingFcnCache(ss)===============================
%%Description:
%%GeneratestheZeroCrossingsfunctionforanenable/atomicsystem
%%containingcontinuousstates.
%%
%function SLibGetBodyZeroCrossingFcnCache(ss) void
  %openfile tmpBuffer
  %assign isSSMapped = SLibIsMappedInDeploymentDiagram(ss)
  %if !isSSMapped || SLibPartitionNeedContFcnDecl(ss.CurrentPID)
    %<LibDumpFcnOpen(ss,"ZeroCrossing")>/
  %else
    {
  %endif
   
  %assign tidTrailer = isSSMapped ? "%<ss.CurrentTID>" : ""
  %assign pidTrailer = isSSMapped ? "%<ss.CurrentPID>" : ""
   
  %<FcnDumpMRLocalVars(ss, "ZeroCrossing", "%<tidTrailer>")>/
  %<LibDumpSystemSSVars(ss,"ZeroCrossing%<tidTrailer>%<pidTrailer>")>/
  %<LibGetSystemLocalVars(ss,"ZeroCrossing","%<tidTrailer>")>
  %<SLibGetFcnLocalVars(ss,"ZeroCrossing","%<tidTrailer>")>
  %<LibDumpSystemUserCode(ss,"ZeroCrossing","Header")>/
  %<LibDumpGlobalVars(ss, "ZeroCrossing%<tidTrailer>%<pidTrailer>")>/
  %<LibDumpFcnBegin(ss,"ZeroCrossing")>/
  %% open code
  %<LibDumpSystemUserCode(ss,"ZeroCrossing","Body")>/
  %<LibDumpSystemFcn(ss,"ZeroCrossing%<tidTrailer>%<pidTrailer>")>/
  %<LibDumpSystemUserCode(ss,"ZeroCrossing","Trailer")>/
  %% close code
  %<LibDumpFcnClose(ss,"ZeroCrossing")>
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %openfile retBuffer
    %assign isSSMapped = SLibIsMappedInDeploymentDiagram(ss)
    %if LibSystemIsInlined(ss) && !isSSMapped
      %<SLibGetFcnComment(ss,"ZeroCrossings")>/
    %elseif (!isSSMapped) || SLibPartitionNeedContFcnDecl(ss.CurrentPID)
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"ZeroCrossings")
      %assign fcnInfo = LibGetFcnInfo(ss, "ZeroCrossing", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss,"ZeroCrossings")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "ZeroCrossing" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
 
%%Function:SLibGetBodyEnableFcnCache(ss)=====================================
%%Description:
%%Generatestheenablefunctionforthesesystemtypes.
%%oenable
%%oenablewithtrigger
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibGetBodyEnableFcnCache(ss) void
  %openfile tmpBuffer
  %<LibDumpFcnOpen(ss,"Enable")>/
  %<FcnDumpMRLocalVars(ss, "Enable", "")>/
  %<LibDumpSystemSSVars(ss,"Enable")>/
  %<LibGetSystemLocalVars(ss,"Enable","")>
  %<SLibGetFcnLocalVars(ss,"Enable","")>
  %<LibDumpSystemUserCode(ss,"Enable","Header")>/
  %<LibDumpGlobalVars(ss, "Enable")>/
  %<LibDumpFcnBegin(ss,"Enable")>/
  %<LibDumpSystemUserCode(ss,"Enable","Body")>/
  %<LibDumpSystemFcn(ss,"Enable")>/
  %<LibDumpSystemUserCode(ss,"Enable","Trailer")>/
  %<LibDumpFcnClose(ss,"Enable")>
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %openfile retBuffer
    %if LibSystemIsInlined(ss)
    %<SLibGetFcnComment(ss,"Enable")>/
    %else
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"Enable")
      %assign fcnInfo = LibGetFcnInfo(ss, "Enable", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss,"Enable")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "Enable" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
 
%%Function:SLibGetBodyDisableFcnCache(ss)====================================
%%Description:
%%Generatesthedisablefunctionforthesesystemtypes.
%%oenable
%%oenablewithtrigger
%%
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%function SLibGetBodyDisableFcnCache(ss) void
  %openfile tmpBuffer
  %<LibDumpFcnOpen(ss,"Disable")>/
  %<FcnDumpMRLocalVars(ss, "Disable", "")>/
  %<LibDumpSystemSSVars(ss,"Disable")>/
  %<LibGetSystemLocalVars(ss,"Disable","")>
  %<SLibGetFcnLocalVars(ss,"Disable","")>
  %<LibDumpSystemUserCode(ss,"Disable","Header")>/
  %<LibDumpGlobalVars(ss, "Disable")>/
  %<LibDumpFcnBegin(ss,"Disable")>/
  %% disable code
  %openfile tmpBuffer2
  %<LibDumpSystemUserCode(ss,"Disable","Body")>/
  %<LibDumpSystemFcn(ss,"Disable")>/
  %<LibDumpSystemUserCode(ss,"Disable","Trailer")>/
  %closefile tmpBuffer2
  %% extra code for exported function to update external outputs
  %if ExportFunctionsMode == 1 && !WHITE_SPACE(tmpBuffer2)
    %<tmpBuffer2>
    %<LibDumpExpFucUpdateRootOutput(ss,"Disable")>/
  %else
    %<tmpBuffer2>/
  %endif
  %% close code
  %<LibDumpFcnClose(ss,"Disable")>
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %openfile retBuffer
    %if LibSystemIsInlined(ss)
    %<SLibGetFcnComment(ss,"Disable")>/
    %else
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"Disable")
      %assign fcnInfo = LibGetFcnInfo(ss, "Disable", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss,"Disable")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "Disable" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %return retBuffer
%endfunction
 
 
%function SLibGetBodyFinalizeDimsFcnCache(ss) void
  %openfile retBuffer
  %if LibSystemIsInlined(ss)
  %<SLibGetFcnComment(ss,"FinalizeDims")>/
  %else
    %assign fcnAbstract = SLibGetFcnCommentContents(ss,"FinalizeDims")
    %assign fcnInfo = LibGetFcnInfo(ss, "FinalizeDims", ss.CurrentTID)
    %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
      Type "FinalizeDims" GeneratedFor FcnGeneratedFor(ss) ...
      BlockDescription SLibGetBlockDescriptionForSS(ss, "FinalizeDims")
    %<SLibDumpFunctionBanner(fcnInfo)>
  %endif
  %<LibDumpFcnOpen(ss,"FinalizeDims")>/
  %<FcnDumpMRLocalVars(ss, "FinalizeDims", "")>/
  %<LibDumpSystemSSVars(ss,"FinalizeDims")>/
  %<LibGetSystemLocalVars(ss,"FinalizeDims","")>
  %<SLibGetFcnLocalVars(ss,"FinalizeDims","")>
  %<LibDumpGlobalVars(ss, "FinalizeDims")>/
  %<LibDumpSystemFcn(ss, "FinalizeDims")>
  %<LibDumpFcnClose(ss,"FinalizeDims")>
  %closefile retBuffer
  %return retBuffer
%endfunction
 
%function SLibGetBodySetDimsFcnCache(ss) void
  %openfile retBuffer
  %if LibSystemIsInlined(ss)
  %<SLibGetFcnComment(ss,"SetDims")>/
  %else
    %assign fcnAbstract = SLibGetFcnCommentContents(ss,"SetDims")
    %assign fcnInfo = LibGetFcnInfo(ss, "SetDims", ss.CurrentTID)
    %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss,"Outputs")
    %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
      Type "SetDims" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
    %<SLibDumpFunctionBanner(fcnInfo)>
  %endif
  %<LibDumpFcnOpen(ss,"SetDims")>/
  %<FcnDumpMRLocalVars(ss, "SetDims", "")>/
  %<LibDumpSystemSSVars(ss,"SetDims")>/
  %<LibGetSystemLocalVars(ss,"SetDims","")>
  %<SLibGetFcnLocalVars(ss,"SetDims","")>
  %<LibDumpGlobalVars(ss, "SetDims")>/
  %<LibDumpSystemFcn(ss, "SetDims")>
  %<LibDumpFcnClose(ss,"SetDims")>
  %closefile retBuffer
  %return retBuffer
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSink/tmVariantSrcSink1_VC1.m
%function SLibGetBodyConstCodeFcnCache(ss) void
  %openfile retBuffer
  %if LibSystemIsInlined(ss)
  %<SLibGetFcnComment(ss,"ConstCode")>/
  %else
    %assign fcnAbstract = SLibGetFcnCommentContents(ss,"ConstCode")
    %assign fcnInfo = LibGetFcnInfo(ss, "ConstCode", ss.CurrentTID)
    %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
      Type "ConstCode" GeneratedFor FcnGeneratedFor(ss) ...
      BlockDescription SLibGetBlockDescriptionForSS(ss, "ConstCode")
    %<SLibDumpFunctionBanner(fcnInfo)>
  %endif
  %<LibDumpFcnOpen(ss,"ConstCode")>/
  %<FcnDumpMRLocalVars(ss, "ConstCode", "")>/
  %<LibDumpSystemSSVars(ss,"ConstCode")>/
  %<LibGetSystemLocalVars(ss,"ConstCode","")>
  %<SLibGetFcnLocalVars(ss,"ConstCode","")>
  %<LibDumpGlobalVars(ss, "ConstCode")>/
  %<LibDumpSystemFcn(ss, "ConstCode")>
  %<LibDumpFcnClose(ss,"ConstCode")>
  %closefile retBuffer
  %return retBuffer
%endfunction
 
%%Function:FcnGetFcnCommentToken(ss,fcn,token,prefix)=======================================
%%Description:
%%Returntoken'scontentforcomments
%%Validtoken:"FcnDescription","GeneratedFor","BlockDescription"
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmSfFcnCall_VC1.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmreuse_across_models.m
%%TopTester:test/toolbox/simulink/blocks/sb2sl/-tsb2slmdlref.m
%%
%function FcnGetFcnCommentToken(ss, fcn, token, prefix) void
  %assign retBuffer = ""
  %if ExportFunctionsMode == 1 && ss.Exported == "yes"
    %assign ssIdentifier = LibGetRecordIdentifier(ss)
    %if ISEQUAL(token, "FcnDescription")
      %return "%<fcn> for exported function: %<ssIdentifier>"
    %elseif ISEQUAL(token, "GeneratedFor")
      %% Only return valid blockpath
      %if !ISEMPTY(ssIdentifier) && ssIdentifier[0] == "<"
        %return ssIdentifier
      %else
        %return ""
      %endif
    %elseif ISEQUAL(token, "BlockDescription")
      %assign cs = ss.CallSites
      %assign numCs = SIZE(cs, 0)
      %assert (numCs > 0)
      %assign retOneBlk = (numCs == 1 || LibSystemIsInlined(ss))
      %assign thisCs = cs[0]
      %assign thisBlk = System[thisCs[2]].Block[thisCs[3]]
    %endif
  %elseif ss.Type == "atomic" && ss.CalledByBlock == "yes"
%%donotreturnanything
    %return ""
  %elseif (ss.Type == "root")
    %if ISEQUAL(token, "FcnDescription")
      %return "%<fcn> for %<ss.Type> system: '%<ss.Name>'"
    %elseif ISEQUAL(token, "GeneratedFor")
      %return "'%<ss.Name>'"
    %elseif ISEQUAL(token, "BlockDescription")
      %return ""
    %endif
  %elseif IsModelReferenceBaseSys(ss)
    %if ISEQUAL(token, "FcnDescription")
      %return "%<fcn> for referenced model: '%<::CompiledModel.Name>'"
    %elseif ISEQUAL(token, "GeneratedFor")
      %return ""
    %elseif ISEQUAL(token, "BlockDescription")
      %return ""
    %endif
  %else
    %assign cs = ss.CallSites
    %assign numCs = SIZE(cs, 0)
    %assert (numCs > 0)
     
    %assign ssType = ss.Type + " system"
    %if LibIsServer(ss)
      %assign ssType = "Simulink Function"
    %endif
    %% If the system is an RLS, we don't care how many callsites it has for its description
    %assign retOneBlk = (numCs == 1 || LibSystemIsInlined(ss) || LibSystemIsReusedLibraryFcn(ss))
    %assign thisCs = cs[0]
    %assign thisBlk = System[thisCs[2]].Block[thisCs[3]]
    %if retOneBlk
      %assign blkName = SLibGrBlockCommentName(ss.GraphCallSites[0])
      %if ISEQUAL(token, "FcnDescription")
        %if LibSystemIsReusedLibraryFcn(ss) && ISFIELD(ss, "RLSCommentName")
          %return "%<fcn> for %<ssType>: %<ss.RLSCommentName>"
        %else
          %return "%<fcn> for %<ssType>: %<blkName>"
        %endif
      %elseif ISEQUAL(token, "GeneratedFor")
        %return "%<blkName>"
      %elseif ISEQUAL(token, "BlockDescription")
        %assign blkName = SLibGrBlockCommentName(ss.GraphCallSites[0])
      %if LibSystemIsInlined(ss) && ISFIELD(thisBlk, "MaskType") && ...
        thisBlk.MaskType == "Stateflow"
          %assign retBuffer = "Chart description for: %<blkName>"
        %else
          %assign retBuffer = "Block description for: %<blkName>"
    %endif
      %endif
    %else
      %assign max = 10
      %assign num = (numCs > max+1) ? max : numCs
      %if ISEQUAL(token, "FcnDescription")
        %assign retBuffer = "%<fcn> for %<ssType>:/n"
        %foreach cIdx = num
          %assign blkName = SLibGrBlockCommentName(ss.GraphCallSites[cIdx])
          %assign retBuffer = retBuffer + prefix + " " + blkName + "/n"
        %endforeach
        %if numCs > num
          %return retBuffer + prefix + " .../n"
        %else
          %return retBuffer
        %endif
      %elseif ISEQUAL(token, "GeneratedFor")
        %assign retBuffer = ""
        %foreach cIdx = num
          %assign blkName = SLibGrBlockCommentName(ss.GraphCallSites[cIdx])
          %if cIdx < num-1
            %assign retBuffer = retBuffer + "%<blkName>,/n"
          %else
            %assign retBuffer = retBuffer + "%<blkName>"
          %endif
        %endforeach
        %if numCs > num
          %return retBuffer + ",..."
        %else
          %return retBuffer
    %endif
      %elseif ISEQUAL(token, "BlockDescription")
        %assign retBuffer = "Common block description:"
      %endif
    %endif
  %endif
  %assign ret_blockdescription = FcnGetBlockDescriptionInFcnBanner(thisBlk)
  %if !ISEMPTY(ret_blockdescription)
    %return retBuffer + "/n" + ret_blockdescription
  %else
    %return ""
  %endif
%endfunction
 
%%Function:FcnGeneratedFor(ss)=======================================
%%Description:
%%Returnsystemorblockpathforfunctioncomments
%%Ifthesystemisreused,first10(11)instancesarereturned
%%
%function FcnGeneratedFor(ss)
  %return FcnGetFcnCommentToken(ss, "", "GeneratedFor", "")
%endfunction
  
%%Function:SLibGetBlockDescriptionForSS(ss)=======================================
%%Description:
%%Returnblockdescriptionforsystem
%%
%function SLibGetBlockDescriptionForSS(ss, fcn)
  %assign needBlkDsc = !(ss.Type == "atomic" && ss.CalledByBlock == "yes") && ...
    (ss.Type != "root") && !IsModelReferenceBaseSys(ss) && ...
    !ss.DescInCallSite && ...
    (fcn == "Output and update" || fcn == "Outputs" || fcn == "SetDims" || fcn == "FinalizeDims")
  %if !needBlkDsc
    %return ""
  %endif
  %return FcnGetFcnCommentToken(ss, fcn, "BlockDescription", "")
%endfunction
 
%%Function:SLibGetFcnComment(ss,fcn)=======================================
%%Description:
%%Returncommentforeachfunctiontypewith/**/format.Ifthesystemisreused
%%thecommentincludesthefirst10(11)instancesofthereusedsystem.
%%
%function SLibGetFcnComment(ss, fcn) void
  %assign retBuffer = "/* " + FcnGetFcnCommentToken(ss, fcn, "FcnDescription", " * ") + " */"
  %return retBuffer
%endfunction
 
%%Function:SLibGetFcnCommentContents(ss,fcn)=======================================
%%Description:
%%Returncommentforeachfunctiontypewithout/**/format.Ifthesystemisreused
%%thecommentincludesthefirst10(11)instancesofthereusedsystem.
%%
%function SLibGetFcnCommentContents(ss, fcn) void
  %return FcnGetFcnCommentToken(ss, fcn, "FcnDescription", "")
%endfunction
 
%%Function:SLibGetBodyOutputUpdateFcnCache(ss)===============================
%%Description:
%%Generatestheoutput/updatefunctionforsystemsthathaveoutput
%%andupdatecombinedintoonefunction.
%%Note:afunction-callisgeneratedevenifitisempty.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/autoInherit/tmWithCombSpecAndInherit_VC1.m
%%
%function SLibGetBodyOutputUpdateFcnCache(ss) void
  %if SLibSystemFcnPeriodicRateGrouping(ss, "OutputUpdate") || ...
    LibAsynchronousTriggeredTID(ss.CurrentTID)
    %assign tid = ss.CurrentTID
  %else
    %assign tid = ""
  %endif
   
  %% Simulink functions can't just be removed if they're empty - unless its actually
  %% a different sampletime from the callsite (async/irt & empty). Since Simulink functions
  %% are always combined output/update, don't need to cover this case in SLibGetBodyOutputFcnCache
  %% This logic seems way more complicated than it should be. The basic idea:
  %% 1> Don't emit code for inlined IRT unless the function is actualled called from IRT
  %% (single rate, or the current tid matched the definition tid)
  %% 2> Don't emit code for noninlined IRT if empty & not actually called from IRT
  %% 3> Don't emit code got rate grouped function
  %% 4> Always emit everything else, even if empty
  %%
  %% The tricky part for #1 & #2 is distinguishing a simulink function with IRT inside from
  %% a siulink function without IRT that is called from IRT only.
  %if LibIsServer(ss)
    %if SLibInitEventTID(tid) || (SLibTermEventTID(tid) && !IsModelReferenceSimTarget())
      %% Remove Init and term code if this is a multirate function and the
      %% function has its own init code. Need to distinguish from multirate
      %% and called from inside someone else's Init function which we do
      %% have to emit the function.
      %assign systemFcnIsEmpty = !LibIsSingleRateSystem(ss) && ...
        !ISEQUAL(tid, FcnGetSubsystemCodeBufTID(ss))
    %elseif SLibNonInlinedModelWideEventTID(tid)
      %% Non-lined IRT doesn't emit if empty and not actually the definition rate
      %assign systemFcnIsEmpty = LibSystemFcnIsEmptyHelper(ss, "OutputUpdate", tid) && ...
        !LibIsSingleRateSystem(ss) && ...
        !ISEQUAL(tid, FcnGetSubsystemCodeBufTID(ss))
    %elseif ss.IsRateGroupedSLFcn
      %% Do not emit the rate grouped Simulink function's subsystem code. It
      %% will be emitted by the root module.
      %assign systemFcnIsEmpty = TLC_TRUE
    %else
      %% Otherwise, this must be emitted even if empty
      %assign systemFcnIsEmpty = TLC_FALSE
    %endif
  %elseif LibAsynchronousTriggeredTID(tid) && !SLibNonInlinedModelWideEventTID(tid)
    %if ISEQUAL(tid, FcnGetSubsystemCodeBufTID(ss)) || ...
      SLibIsExplicitTaskingExportFcnRateGrouping("OutputUpdate",tid)
      %assign systemFcnIsEmpty = LibSystemFcnIsEmptyForTID(ss, "OutputUpdate")
    %else
      %assign systemFcnIsEmpty = TLC_TRUE
    %endif
  %else
    %if ISEQUAL(tid, "") %%!SLibIsPeriodicRateGrouping()
      %% If not grouping rating, system output
      %% fcn always exists if FcnInfo exists
      %assign systemFcnIsEmpty = WHITE_SPACE(LibGetFcnInfo(ss, "OutputUpdate",tid))
    %else
      %assign systemFcnIsEmpty = LibSystemFcnIsEmptyForTID(ss, "OutputUpdate")
    %endif
  %endif
   
  %if IsModelReferenceBaseSys(ss)
    %% Create this field and initialize it to "yes"
    %% This will be updated at the end of function
    %addtorecord ss ModelRefOutputUpdateFcnIsEmpty%<tid> "yes"
  %endif
 
  %if !systemFcnIsEmpty
    %assign isSSMapped = SLibIsMappedInDeploymentDiagram(ss)
    %openfile tmpBuffer
    %% open
    %if !isSSMapped
      %<LibDumpFcnOpen(ss,"OutputUpdate")>/
    %endif
    %<FcnDumpMRLocalVars(ss, "OutputUpdate", tid)>/
    %% Profiler declaration code
    %<LibDumpSystemProfileCode(ss,"OutputUpdate", "Decls")>/
    %% output declarations
    %<LibDumpSystemSSVars(ss,"OutputUpdate")>/
    %if !isSSMapped
      %<LibGetSystemLocalVars(ss,"OutputUpdate",tid)>
    %endif
    %assign localOutputVars = SLibGetFcnLocalVars(ss, "Output", tid)
    %assign localUpdateVars = SLibGetFcnLocalVars(ss, "Update", tid)
    %assign needBraces = !ISEMPTY(localOutputVars) && !ISEMPTY(localUpdateVars)
    %if !needBraces && !isSSMapped
      %<localOutputVars>
      %<localUpdateVars>
    %endif
    %if (SLibFcnProtoCtrlActive() || GenerateClassInterface) && ...
        IsModelReferenceBaseSys(ss)
        %if !GenerateClassInterface
          %assign fcnData = FcnGetFunctionPrototypeRecord()
        %else
          %assign fcnData = FcnGetRTWCPPStepPrototypeRecord()
        %endif
      %<FcnModelStepFcnReturnCode(fcnData, "ReturnDeclaration")>
      %<FcnModelStepBufferInputsCode(fcnData)>
    %endif
    %<LibDumpSystemUserCode(ss,"Output","Header")>/
    %<LibDumpGlobalVars(ss, "OutputUpdate%<tid>")>/
    %<LibDumpFcnBegin(ss,"OutputUpdate")>/
    %% Profiler start code
    %<LibDumpSystemProfileCode(ss,"OutputUpdate", "Start")>/
    %% When we are generating for model reference, write out
    %% part of the ERT timing Engine.
    %assign mdlrefSys = IsModelReferenceBaseSys(ss)
    %% output code
    %<UpdateRateTransitionFlagsHelper(ss, tid, TLC_FALSE)>
    %<LibDumpSystemUserCode(ss,"Output","Body")>/
    %if needBraces && !ISEMPTY(localOutputVars)
      %<"{">
      %<localOutputVars>
    %endif
    %<LibDumpSystemFcn(ss,"Output%<tid>")>/
    %if needBraces && !ISEMPTY(localOutputVars)
      %<"}">
    %endif
    %<LibDumpSystemUserCode(ss,"Output","Trailer")>/
    %% update declarations
    %%
    %assign userCodeBuffer = ""
    %openfile userCodeBuffer
    %<LibDumpSystemUserCode(ss,"Update","Header")>/
    %<LibDumpSystemUserCode(ss,"Update","Body")>/
    %if needBraces && !ISEMPTY(localUpdateVars)
      %<"{">
      %<localUpdateVars>
    %endif
    %<LibDumpSystemFcn(ss,"Update%<tid>")>/
    %if needBraces && !ISEMPTY(localUpdateVars)
      %<"}">
    %endif
    %<LibDumpSystemUserCode(ss,"Update","Trailer")>/
    %closefile userCodeBuffer
    %%
    %if !WHITE_SPACE(userCodeBuffer)
      %assign needBrace = !LibSystemUserCodeIsEmpty(ss,"Update","Header")
      %if needBrace
        {
        %endif
        %<userCodeBuffer>
        %if needBrace
        }
      %endif
    %endif
    %%
    %<FcnHandlesUnusedTIDArg(ss, "Output")>
    %<FcnHandlesUnusedRTMForSimplifiedInterface(ss, "OutputUpdate")>
    %%
    %% extra code for exported function to update external outputs
    %if ExportFunctionsMode == 1
      %<LibDumpExpFucUpdateRootOutput(ss,"OutputUpdate")>/
    %endif
    %% Profiler finish code
    %<LibDumpSystemProfileCode(ss,"OutputUpdate", "End")>/
 
    %if (SLibFcnProtoCtrlActive() || GenerateClassInterface) && ...
        IsModelReferenceBaseSys(ss)
        %if !GenerateClassInterface
          %assign fcnData = FcnGetFunctionPrototypeRecord()
        %else
          %assign fcnData = FcnGetRTWCPPStepPrototypeRecord()
        %endif
      %<FcnModelStepBufferOutputsCode(fcnData)>
      %<FcnModelStepFcnReturnCode(fcnData,"ReturnStatement")>
    %endif
    %if !isSSMapped
      %<LibDumpFcnClose(ss,"OutputUpdate")>
    %endif
    %closefile tmpBuffer
  %else
    %assign tmpBuffer = ""
  %endif
  %assign retBuffer = ""
  %openfile retBuffer
  %if !WHITE_SPACE(tmpBuffer)
    %if LibSystemIsInlined(ss) && (!isSSMapped)
    %<SLibGetFcnComment(ss,"Output and update")>/
    %elseif (!isSSMapped)
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"Output and update")
      %assign fcnInfo = LibGetFcnInfo(ss, "OutputUpdate", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss,"Output and update")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "Output and update" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
      %<addToBackupCodeMetrics(ss, fcnInfo.Name, fcnInfo.Name, tid)>
    %endif
    %<tmpBuffer>/
  %endif
 
  %% Only generate stubs for "main" tid.
  %if (TYPE(tid) != "Number") || !SLibModelWideEventTID(tid) || SLibInitResetTermEventTID(tid)
    %<SLibGenerateFNIStubs(ss)>/
    %<SLibGenerateISRStubs(ss)>/
  %endif
  %closefile retBuffer
  %if IsModelReferenceBaseSys(ss)
    %assign ss.ModelRefOutputUpdateFcnIsEmpty%<tid> = "no"
  %endif
  %return retBuffer
%endfunction
 
%%Function:SLibGetBodyTerminateFcnCache(ss)==================================
%%Description:
%%Generatestheterminatefunctionforsystems
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall4.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmVariantsRSim.m
%%
%function SLibGetBodyTerminateFcnCache(ss) void
  %% We need to change the BlockFcn to terminate because the
  %% rtModel is accessed here. This currently does not cause
  %% any problems, but it would make the Interface record incorrect.
  %assign oldBlockFcn = ::BlockFcn
  %assign ::BlockFcn = "Terminate"
  %assign isRoot = (ss.Type == "root")
  %%
  %openfile tmpBuffer
  %<LibDumpFcnOpen(ss,"Terminate")>/
  %<FcnDumpMRLocalVars(ss, "Terminate", "")>/
  %if IsBaseSystem(ss)
    %<LibDumpSystemProfileCode(ss, "Terminate", "End")>
  %endif
  %<LibDumpSystemSSVars(ss,"Terminate")>/
  %<LibGetSystemLocalVars(ss,"Terminate","")>
  %<SLibGetFcnLocalVars(ss,"Terminate","")>
  %<LibDumpSystemUserCode(ss,"Terminate","Header")>/
  %<LibDumpGlobalVars(ss, "Terminate")>/
  %<LibDumpFcnBegin(ss,"Terminate")>/
  %<LibDumpSystemUserCode(ss,"Terminate","Body")>/
  %<LibDumpSystemFcn(ss,"Terminate")>/
  %if isRoot && UsingMalloc && !Accelerator
    %<SLibGenRootTermMemFreeCode()>/
  %endif
  %<LibDumpSystemUserCode(ss,"Terminate","Trailer")>/
  %<LibDumpFcnClose(ss,"Terminate")>
  %closefile tmpBuffer
  %assign retBuffer = ""
  %if !WHITE_SPACE(tmpBuffer)
    %openfile retBuffer
    %if LibSystemIsInlined(ss)
      %<SLibGetFcnComment(ss,"Termination")>/
    %else
      %assign fcnAbstract = SLibGetFcnCommentContents(ss,"Termination")
      %assign fcnInfo = LibGetFcnInfo(ss, "Terminate", ss.CurrentTID)
      %assign fcnBlockDescription = SLibGetBlockDescriptionForSS(ss,"Termination")
      %addtorecord fcnInfo Abstract fcnAbstract Category "model" GeneratedBy "commonbodlib.tlc" ...
        Type "Terminate" GeneratedFor FcnGeneratedFor(ss) BlockDescription fcnBlockDescription
      %<SLibDumpFunctionBanner(fcnInfo)>
    %endif
    %<tmpBuffer>/
    %closefile retBuffer
  %endif
  %assign ::BlockFcn = oldBlockFcn
  %return retBuffer
%endfunction %% SLibGetBodyTerminateFcnCache
 
 
%%Function:LibDumpSystemFcn(system,fcn)======================================
%%Description:
%%Outputsthecachedcontentsofthespecifiedfunctionforasystem.
%%
%function LibDumpSystemFcn(system,fcn) Output
  %assign tempFcnName = "Cached" + fcn + "Fcn"
  %assign code = LibGetSystemField(system, tempFcnName)
  %if code != "/* rate grouped */"
    %% don't dump this comment line
    %% is comment line is only used
    %% to indicate the code is not
    %% empty, is rate grouped
    %<LibTrapCacheAssert(code)>/
    %<code>/
  %endif
%endfunction %% LibDumpSystemFcn
 
 
%%Function:LibDumpSystemSSVars(system,fcn)===================================
%%Description:
%%Outputsthecachedsimstructvariablesthatareneededbythefunction.
%%
%function LibDumpSystemSSVars(system,fcn) Output
  %assign tempSSVarsName = "Cached" + fcn + "SSVars"
  %assign code = LibGetSystemField(system, tempSSVarsName)
  %<code>/
%endfunction %% LibDumpSystemSSVars
 
%%Function:LibDumpSystemProfileCode(system,fcn,part)========================
%%Description:
%%Outputsthecachedprofilecode
%%fcn:terminate,output,update,outputupdate,derivative
%%part:ProfileDecls,ProfileStart,ProfileEnd
%%
%function LibDumpSystemProfileCode(system,fcn, part) Output
  %assign tempProfile = "Cached" + fcn + "Profile"+ part + "Code"
  %assign code = LibGetSystemField(system, tempProfile)
  %<code>/
%endfunction %% LibDumpSystemProfileCode
 
%%Function:SLibGetFcnLocalVars===============================================
%%Abstract:
%%Returnsthelocalvariabledeclarationforagivensystemfunctionand
%%sampletimeindex(andpartitionindexifpartitiongroupingison)
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibGetFcnLocalVars(system, fcn, tid) void
  %assign retVal = ""
  %assign prefix = "Cached" + fcn
  %if ISEMPTY(tid)
    %assign retVal = LibGetSystemField(system, prefix + "LocalVars")
    %if ISEMPTY(retVal) && LibIsSystemField(system, prefix + "0LocalVars")
      %assign retVal = LibGetSystemField(system, prefix + "0LocalVars")
    %endif
  %else
    %if ISFIELD(system, "CurrentPID") && system.CurrentPID != -1
      %assign retVal = LibGetSystemField(system, prefix + "%<tid>%<system.CurrentPID>LocalVars")
    %else
      %assign retVal = LibGetSystemField(system, prefix + "%<tid>LocalVars")
    %endif
    %% For a synchronous tid, might be cached under tid ""
    %if ISEMPTY(retVal) && ...
      !LibAsynchronousTriggeredTID(tid) && ...
      LibIsSystemField(system, prefix + "LocalVars")
      %assign retVal = LibGetSystemField(system, prefix + "LocalVars")
    %endif
  %endif
  %return retVal
%endfunction
 
%%Function:SLibResetFcnLocalVars=============================================
%%Abstract:
%%Resetsthelocalvariabledeclarationcacheforagivensystemfunction
%%andtaskindex.
%%
%function SLibResetFcnLocalVars(system, fcn, tid) void
  %assign prefix = "Cached" + fcn
  %if ISEMPTY(tid)
    %assign retVal = LibGetSystemField(system, prefix + "LocalVars")
    %if ISEMPTY(retVal) && LibIsSystemField(system, prefix + "0LocalVars")
      %<LibSetSystemField(system, prefix + "0LocalVars", "")>
    %else
      %<LibSetSystemField(system, prefix + "LocalVars", "")>
    %endif
  %else
    %assign retVal = LibGetSystemField(system, prefix + "%<tid>LocalVars")
    %if ISEMPTY(retVal) && LibIsSystemField(system, prefix + "LocalVars")
      %<LibSetSystemField(system, prefix + "LocalVars", "")>
    %else
      %<LibSetSystemField(system, prefix + "%<tid>LocalVars", "")>
    %endif
  %endif
%endfunction
 
%%Function:LibGetSystemLocalVars(system,fcn)=================================
%%Description:
%%Outputsthecachedlocalvariablesthatareneededbythefunction.
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/dimensionVariants/tDimensionVariants9.m
%%
%function LibGetSystemLocalVars(system, fcn, tid) void
  %if ISFIELD(system, "CurrentPID") && system.CurrentPID != -1
    %assign tempLocalBOName = "Cached" + fcn + "%<tid>%<system.CurrentPID>LocalBO"
  %else
    %assign tempLocalBOName = "Cached" + fcn + "%<tid>LocalBO"
  %endif
  %assign localVars = ""
  %if LibIsSystemField(system, tempLocalBOName)
    %assign code = LibGetSystemField(system, tempLocalBOName)
    %if code != "/* rate grouped */"
      %% don't dump this comment line
      %% is comment line is only used
      %% to indicate the code is not
      %% empty, is rate grouped
      %assign localVars = code
    %endif
  %endif
  %return localVars
%endfunction %% LibGetSystemLocalVars
 
%%Function:SLibSystemFcnTypeMayUseTid(fcn)===================================
%%Abstract:
%%Returntrueifthefcnisthetypethatmayusetidinitscodebody.
%%
%function SLibSystemFcnTypeMayUseTid(fcn)
  %return (fcn == "Output" || fcn == "Outputs" || ...
    fcn == "Update" || fcn == "RootUpdate" || ...
    fcn == "OutputUpdate" || fcn == "UpdateContStates")
%endfunction
 
%%Function:LibSystemFcnNeedsTID(system,fcn)==================================
%%Description:
%%returnsTLC_TRUEifthesystemfunctionneedsTIDpassedin,
%%elsereturnsTLC_FALSE
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%TopTester:test/toolbox/simulink/variants/tvariant_merge.m
%function LibSystemFcnNeedsTID(system,fcn) void
  %assign retVal = TLC_FALSE
  %assign tidIsUsedInFcn = TLC_FALSE
   
  %% Only potential multirate function may use TID.
  %if !SLibSystemFcnTypeMayUseTid(fcn)
    %return retVal
  %endif
   
  %% First, figure out whether the tid is used in the function.
  %switch fcn
    %case "UpdateContStates"
    %case "Update"
    %case "RootUpdate"
      %assign tidIsUsedInFcn = LibGetSystemField(system, "NeedTIDInUpdate")
      %break
    %case "Output"
    %case "Outputs"
    %case "OutputUpdate"
      %assign tidIsUsedInFcn = LibGetSystemField(system, "NeedTIDInOutput")
      %break
    %default
      %% Other function types are single rate.
      %% always assert
      %assert TLC_FALSE
  %endswitch
   
  %% Second, find out if tid arg is required to pass in fcn.
  %if LibSystemIsRoot(system)
    %% If target requires tid at root.
    %% Note: GRT target must pass in tid arg because external customers
    %% may rely on this.
    %if RootBodyTIDneeded
      %assign retVal = TLC_TRUE
    %else
      %if SLibSystemFcnPeriodicRateGrouping(system, fcn)
        %% Root level wrapper function that calls each rate-grouped
        %% step function, must pass in tid arg.
        %% This is the case to support static ert main
        %assign retVal = ISEQUAL(system.CurrentTID, "") || ...
          (SLibNeedWrapperStepFcn()!=0 && system.CurrentTID == 0 && ...
          ::GenerateClassInterface && EXISTS(NumServicePorts) && NumServicePorts>0)
      %endif
      %if tidIsUsedInFcn && !retVal
        %% tid is not passed in, but is used
        %% add local tid in fcn scope.
        %<SLibSetNeedLocalTIDInSystem(system,fcn)>
      %endif
    %endif
  %else
    %if tidIsUsedInFcn
      %assign retVal = TLC_TRUE
    %else
      %% If tid is not used, but the fcn callsite assume tid arg.
      %% (e.g. Non-inline sfcn). Force the fcn to have tid arg.
      %assign retVal = SLibSystemFcnTypeMayUseTid(fcn) && FcnForcedHasTIDArg(system)
    %endif
  %endif
   
  %return retVal
%endfunction %% LibSystemFcnNeedsTID
 
 
%%Function:LibSystemFcnNeedsCPI(system,fcn)==================================
%%Description:
%%returnsTLC_TRUEifthesystemfunctionneedsCPI(ControlPortIndex)
%%passedin,elsereturnsTLC_FALSE
%%
%function LibSystemFcnNeedsCPI(system,fcn) void
  %if fcn == "OutputUpdate" || ...
    fcn == "Enable" || ...
    fcn == "Disable"
    %assign tempName = "NeedCPIIn" + fcn
    %return LibGetSystemField(system, tempName)
  %else
    %return TLC_FALSE
  %endif
%endfunction %% LibSystemFcnNeedsCPI
 
%%Function:SLibSystemTidMatch(system,tid)
%%Abstract:
%%Returntruniftidmatchesbasetidofthesubsystem.
%%
%function SLibSystemTidMatch(system, tid)
 
  %if !LibIsSingleRateSystem(system)
    %return TLC_TRUE
  %endif
   
  %assign sysTid = LibGetSubsystemTID(system, TLC_TRUE)
   
  %if ISEQUAL(tid,"")
    %return TLC_TRUE
  %elseif ISEQUAL(tid, sysTid)
    %return TLC_TRUE
  %else
    %assign tid01Eq = ISEQUAL(SolverType, "FixedStep") && FixedStepOpts.TID01EQ
    %return tid01Eq && ...
      (tid == 0 || tid == 1) && ...
      (sysTid == 0 || sysTid == 1)
  %endif
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/subsystemBuild/tIVSubsystemBuild_1.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tIVfcnCall_neg.m
%function SLibSystemUserDataIsEmpty(system, fcnType, tid)
  %if TYPE(tid) == "Number"
    %assert tid >= 0
    %% userCode is not rate grouped, when check if code for specific tid
    %% is empty, should not include user code unless the tid equal to
    %% subsystem tid
    %if system.Type != "root"
      %assign ssTid = FcnGetSubsystemCustomCodeBufTID(system)
      %if !ISEQUAL(tid, ssTid)
        %return TLC_TRUE
      %endif
    %endif
  %endif
   
  %% Since CGIR will generate call-site code when %<fcnType>MethodHasUserData
  %% is true. TLC must generate function for this fcnType even the code is empty.
  %% The only exceptions are:
  %% 1. System is inlined,(no call site code is emitted by CGIR in this case).
  %% 2. Is root system. (call site code is NOT emitted by CGIR, it is generate in TLC
  %% 3. fcn type is terminate. All subsystem terminate code is placed in models
  %% terminate function. (see ProcessRTWdata(RTWdata, system) in custcode.tlc)
  %% 4. fcn type is initialize. (Custom initialize code is cached in in the system
  %% if it has an initialize function, otherwise cache in models start function.
  %%
  %if LibSystemIsInlined(system) || system.Type == "root" || ...
    fcnType == "Terminate" || fcnType == "Initialize"
    %if fcnType == "OutputUpdate"
      %assign userCodeIsEmpty = ...
        WHITE_SPACE(LibGetSystemField(system, "OutputHeader" )) && ...
        WHITE_SPACE(LibGetSystemField(system, "OutputBody" )) && ...
        WHITE_SPACE(LibGetSystemField(system, "OutputTrailer")) && ...
        WHITE_SPACE(LibGetSystemField(system, "UpdateHeader" )) && ...
        WHITE_SPACE(LibGetSystemField(system, "UpdateBody" )) && ...
        WHITE_SPACE(LibGetSystemField(system, "UpdateTrailer"))
    %else
      %assign userCodeIsEmpty = ...
        WHITE_SPACE(LibGetSystemField(system, "%<fcnType>Header" )) && ...
        WHITE_SPACE(LibGetSystemField(system, "%<fcnType>Body" )) && ...
        WHITE_SPACE(LibGetSystemField(system, "%<fcnType>Trailer"))
    %endif
  %else
    %if fcnType == "OutputUpdate"
      %assign fcnType = "Output"
    %endif
    %assign fieldname = "%<fcnType>MethodHasUserData"
    %assign userCodeIsEmpty = !ISFIELD(system, fieldname) || !GETFIELD(system, fieldname)
  %endif
   
  %return userCodeIsEmpty
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tIVfcnCall_neg.m
%function LibSystemFcnIsEmptyHelper(system, fcn, tid)
  %% Output may have been combined with update
  %if fcn == "Output" && !ISFIELD(system,"OutputFcn") && ...
      !(ISFIELD(system,"OutputCalledInUpdate") && ...
      system.OutputCalledInUpdate == "yes")
    %assign fcn = "OutputUpdate"
  %endif
   
  %if SLibSystemFcnIsRateGroupType(fcn)
    %if !SLibIsMultiRateAndPeriodicRateGrouping(system) && !LibAsynchronousTriggeredTID(tid) && ...
      !SLibIsExplicitTaskingExportFcnRateGrouping(fcn, tid) && ...
      !(SLibPartitionGroupingSystem(system) && TYPE(tid) == "Number")
      %% system is not rate grouped, ignore tid value
      %if SLibSystemTidMatch(system,tid)
          %assign tid = ""
      %else
        %return TLC_TRUE
      %endif
    %endif
  %else
    %% sysFcn is not rate grouped, ignore tid value
    %assign tid = ""
  %endif
   
  %if !ISFIELD(system,"%<fcn>Fcn") && system.Type != "root"
    %return TLC_TRUE
  %endif
   
  %assign pidVec = []
  %if SLibPartitionGroupingSystem(system) && TYPE(tid) == "Number"
    %assign pidVec = SLibGetPidFromTid(tid)
  %endif
   
  %if fcn == "OutputUpdate"
    %if system.DeletedInIR
      %return TLC_TRUE
    %endif
    %if SLibPartitionGroupingSystem(system) && TYPE(tid) == "Number"
      %assign rtwCode = []
      %foreach i = SIZE(pidVec, 1)
        %assign rtwCode = rtwCode + ...
          LibGetSystemField(system, "CachedOutput%<tid>%Fcn") + ...
          LibGetSystemField(system, "CachedUpdate%<tid>%Fcn")
      %endforeach
    %else
      %assign rtwCode = LibGetSystemField(system, "CachedOutput%<tid>Fcn") + ...
        LibGetSystemField(system, "CachedUpdate%<tid>Fcn")
    %endif
  %elseif fcn == "Output" && system.DeletedInIR
    %return TLC_TRUE
  %else
    %if SLibPartitionGroupingSystem(system) && TYPE(tid) == "Number"
      %assign rtwCode = []
      %foreach i = SIZE(pidVec, 1)
        %assign rtwCode = rtwCode + ...
          LibGetSystemField(system, "Cached%<fcn>%<tid>%Fcn")
      %endforeach
    %else
      %assign rtwCode = LibGetSystemField(system, "Cached%<fcn>%<tid>Fcn")
    %endif
  %endif
   
  %assign ssCodeIsEmpty = TLC_TRUE
  %if ISEQUAL(tid, "")
    %assign ssCodeIsEmpty = ...
      WHITE_SPACE(LibGetSystemField(system, "Cached%<fcn>ProfileDeclsCode")) && ...
      WHITE_SPACE(LibGetSystemField(system, "Cached%<fcn>ProfileStartCode")) && ...
      WHITE_SPACE(LibGetSystemField(system, "Cached%<fcn>ProfileEndCode"))
  %endif
 
  %% If the TID is not associated with any PID then rtwCode will be []
  %% and WHITE_SPACE(rtwCode) will return TLC_FALSE
  %assign rtwCodeIsEmpty = ISEMPTY(rtwCode) || WHITE_SPACE(rtwCode)
  %assign userCodeIsEmpty = SLibSystemUserDataIsEmpty(system, fcn, tid)
   
  %<LibTrapCacheAssert(rtwCode)>
 
  %if (fcn == "Update" && !ISEQUAL(tid, ""))
    %assign isEmpty = (rtwCodeIsEmpty && userCodeIsEmpty)
  %else
    %assign isEmpty= (rtwCodeIsEmpty && userCodeIsEmpty && ssCodeIsEmpty)
  %endif
 
  %if fcn == "Start" && SLibCacheModelArgsInStart(system)
    %assign isEmpty = TLC_FALSE
  %endif
 
  %if isEmpty == TLC_TRUE && Accelerator && fcn == "Output" && ...
    LibSystemIsRoot(system) && ISEQUAL(tid, "")
    %assign isEmpty = TLC_FALSE
  %endif
  %assign isOutputFcn = (fcn == "Output" || fcn == "Update" || fcn == "OutputUpdate")
  %if isEmpty == TLC_TRUE && IsModelReferenceBaseSys(system) && isOutputFcn
     
    %%Function body is empty since isEmpty==TLC_TRUE
    %%Here we keep track of whether the model has
    %%only model wide events other than tid=""
    %%See g1930056.
    %if TYPE(tid) == "Number"
      %assign emptyTIDandMdlHasOnlyModelWideEvents = TLC_FALSE
    %else
      %%Assume
      %assign emptyTIDandMdlHasOnlyModelWideEvents = TLC_TRUE
      %foreach tid_temp = NumSampleTimes
        %if tid_temp != 0 && !SLibModelWideEventTID(tid_temp)
          %assign emptyTIDandMdlHasOnlyModelWideEvents = TLC_FALSE
          %break
        %endif
      %endforeach
    %endif
         
    %if !IsModelReferenceSimTarget() || SLibParameterChangeEventTID(tid) || ...
        !(MdlRefIsConstSampleBlock() || emptyTIDandMdlHasOnlyModelWideEvents)
      %if ISFIELD(system, "ModelRef%<fcn>FcnIsEmpty%<tid>")
        %% The code has already been dumped
        %assign isEmpty = ISEQUAL(system.ModelRef%<fcn>FcnIsEmpty%<tid>, "yes")
      %else
        %assign mdlRefAllowOptimizeEmpty = SLibIsExportFcnDiagram()
   
        %% Assume it is not empty
        %if !mdlRefAllowOptimizeEmpty && ...
          (!LibAsynchronousTriggeredTID(tid) || SLibNonInlinedModelWideEventTID(tid))
          %assign isEmpty = TLC_FALSE
        %endif
      %endif
    %endif
  %endif
 
  %% Exported functions should never be considered empty. They should be emitted
  %% in almost all cases. The exception is system code for rate grouped simulink
  %% functions. The code will be emitted by the root module.
  %if (SLibIsExplicitTaskingExportFcnRateGrouping(fcn, tid) || ...
    (GenerateClassInterface && !SLibModelWideEventTID(tid) && isOutputFcn && LibIsServer(system))) && !system.IsRateGroupedSLFcn
    %assign isEmpty = TLC_FALSE
  %endif
   
  %return isEmpty
%endfunction %%LibSystemFcnIsEmptyHelper
 
%%Function:LibSystemFcnIsEmpty(system,fcn)===================================
%%Description:
%%FunctionthatreturnsTLC_FALSEifthesystemcontainscachedcodefor
%%thespecifiedfunctionnameforanytask.
%%
%function LibSystemFcnIsEmpty(system,fcn) void
  %assign isEmpty = LibSystemFcnIsEmptyHelper(system, fcn, "")
  %if fcn == "Output" || fcn == "Update" || fcn == "OutputUpdate"
    %foreach tid = NumSampleTimes
      %assign isEmpty = isEmpty && LibSystemFcnIsEmptyHelper(system, fcn, tid)
    %endforeach
  %endif
 
  %if fcn == "Terminate" && UsingMalloc
    %assign isEmpty = TLC_FALSE
  %endif
  %return isEmpty
%endfunction %% LibSystemFcnIsEmpty(system,fcn)
 
%%Function:LibSystemFcnIsEmptyForTID(system,fcn)===================================
%%Description:
%%FunctionthatreturnsTLC_FALSEifthesystemcontainscachedcodefor
%%thespecifiedfunctionnameofspecificTid.
%%
%function LibSystemFcnIsEmptyForTID(system,fcn) void
   %assign tid = SLibSystemFcnPeriodicRateGrouping(system, fcn) ||...
    LibAsynchronousTriggeredTID(system.CurrentTID) ? system.CurrentTID : ""
   
  %assign isEmpty = LibSystemFcnIsEmptyHelper(system, fcn, tid)
 
  %return isEmpty
%endfunction
 
 
%%Function:LibSystemIsForceNonInline=========================================
%%
%%Abstract:
%%Accessorfunctionforsystem'sForceNonInlineflag
%%
%function LibSystemIsForceNonInline(system)
  %return system.ForceNonInline
%endfunction %% LibSystemIsForceNonInline
 
%%Function:LibSystemCalledByNonInlineSfcn=========================================
%%
%%Abstract:
%%Accessorfunctionforsystem'sCalledByNonInlineSfcnflag
%%
%function LibSystemCalledByNonInlineSfcn(system)
  %return system.CalledByNonInlineSfcn
%endfunction %% LibSystemCalledByNonInlineSfcn
 
%%Function:LibSystemIsInlined(system)void===================================
%%Description:
%%ReturnsTLC_TRUEifthesystemisinlined
%%
%function LibSystemIsInlined(system) void
  %return system.RTWSystemCode == 0
%endfunction %% LibSystemIsInlined
 
 
%%Function:LibSystemIsNonReusedFcn(system)void==============================
%%Description:
%%ReturnsTLC_TRUEifthesubsystemisnon-reused
%%
%function LibSystemIsNonReusedFcn(system) void
  %return system.RTWSystemCode == 1
%endfunction %% LibSystemIsNonReusedFcn
 
 
%%Function:LibSystemIsReusedFcn(system)void=================================
%%Description:
%%ReturnsTLC_TRUEifthesubsystemisreused
%%
%function LibSystemIsReusedFcn(system) void
  %return system.RTWSystemCode == 2
%endfunction %% LibSystemIsReusedFcn
 
%%Function:LibIsSystemExistingLibrary=======================================
%%Abstract:
%%Returnsthesystemdumpedflag.
%%
%function LibIsSystemExistingLibrary(system)
  %return EXISTS(system.LibrarySubsystemAlreadyWritten) && system.LibrarySubsystemAlreadyWritten == 1
%endfunction
 
%%Function:LibSystemIsContainedWithinReusedLibraryFcn(system)void=========================
%%Description:
%%ReturnsTLC_TRUEifweencounteranRLSanywhereinthesystem
%%hierarchygoingupwardsfromthecurrentsystemtotheroot.
%%
%function LibSystemIsContainedWithinReusedLibraryFcn(sysIdx, instanceIdx) void
  %assign system = ::CompiledModel.System[sysIdx]
  %if LibSystemIsRoot(system)
    %return TLC_FALSE
  %elseif LibSystemIsReusedLibraryFcn(system)
    %return TLC_TRUE
  %else
     %assign parentCallSiteIdx = system.CallSites[instanceIdx]
     %assign parentSysIdx = parentCallSiteIdx[0]
     %assign parentInstIdx = parentCallSiteIdx[1]
     %return LibSystemIsContainedWithinReusedLibraryFcn(parentSysIdx, parentInstIdx)
  %endif
%endfunction %%LibSystemIsContainedWithinReusedLibraryFcn
 
%%Function:SLibCurrentlyGeneratingSharedFcn()void======================
%%Description:
%%ReturnsTLC_TRUEifthecurrentmodelbeinggeneratedisashared
%%function
%%
%function SLibCurrentlyGeneratingSharedFcn() void
  %assign moduleIdx = ::CurrentModuleIdx >= 0? ::CurrentModuleIdx : GetBaseModuleIdx()
  %assign rtwModule = RTWCGModules.RTWCGModule[moduleIdx]
  %return LibSystemIsReusedLibraryFcn(System[rtwModule.CGSystemIdx])
 
%endfunction %% LibSystemIsReusedLibraryFcn
 
%%Function:LibSystemIsRoot(system)void======================================
%%Description:
%%ReturnsTLC_TRUEifthesystemisroot
%%
%function LibSystemIsRoot(system) void
  %return system.Type == "root"
%endfunction %% LibSystemIsRoot
 
 
%%Function:SLibSystemHasOwnDataScope(system)void============================
%%Description:
%%ReturnsTLC_TRUEifthesystemstoresitsdatainanewscope.
%%
%function SLibSystemHasOwnDataScope(system) void
  %return (system.HStructDeclSystemIdx == system.SystemIdx)
%endfunction %% SLibSystemHasOwnDataScope
 
 
 
 
%%
%%LocalFunctionsusedonlyinthisfile.
%%
%%Function:FcnDeclareAccessedLocalVariables=============================
%%Description:
%%Aroutinetodeclareallaccessedlocalvariables.Rightnowit
%%includsblockoutputsignalsandlocalscratchDWorks.Oncethey
%%aredeclared,the"DeclareInFcnScope"fieldsfortheselocal
%%variablesareresettozero
%%Syntax:
%%FcnDeclareAccessedLocalVariables(system)
%%
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/dimensionVariants/tDimensionVariants9.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/inlineVariants/tInlineVariants3.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%
%function FcnDeclareAccessedLocalVariables(system) void
  %assign outputLocalBO = FcnDeclareAccessedLocalVariableGivenType( ...
    system, "LocalBlockOuput")
  %assign outputLocalSDW = FcnDeclareAccessedLocalVariableGivenType( ...
    system, "LocalDWork")
   
  %% Merge outputLocalBO and outputLocalSDW
   
  %% - one of them could be an empty string, the other maybe a vector or a string.
  %% - if any one of them is a vector, it cannot be an empty vector
  %assert TYPE(outputLocalBO) == TYPE(outputLocalSDW) || ISEMPTY(outputLocalBO) || ISEMPTY(outputLocalSDW)
   
  %if TYPE(outputLocalBO) == "Vector" || TYPE(outputLocalSDW) == "Vector"
    %assign localBOSize = SIZE(outputLocalBO, 1)
    %assign localSDWSize= SIZE(outputLocalSDW,1)
 
    %if localBOSize == 0
      %assign retVal = outputLocalSDW
    %elseif localSDWSize == 0
      %assign retVal = outputLocalBO
    %else
      %assign retVal = outputLocalBO
      %foreach tid = localSDWSize
        %assign retVal[tid] = retVal[tid] + outputLocalSDW[tid]
      %endforeach
    %endif
  %else
    %% BO/DWORK are either string/string, vector/string, string/vector
    %assign retVal = outputLocalBO + outputLocalSDW
  %endif
 
  %return retVal
%endfunction
 
%%Function:FcnDeclareAccessedLocalVariableGivenType========================
%%Description:
%%Aroutinetodeclareallaccessedlocalvariablesaccordingtothe
%%types,localBlockOutputorlocalDWork.Oncethey
%%aredeclared,the"DeclareInFcnScope"fieldfortheseblockoutputsis
%%resettozero.
%%
%%Syntax:
%%FcnDeclareAccessedLocalVariableGivenType(system,type)
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1317695_VC1.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/inlineVariants/tInlineVariants13.m
%%
%function FcnDeclareAccessedLocalVariableGivenType(system, type) void
  %assign LocalBO_Buf = ""
  %assign tid01Eq = ISEQUAL(SolverType, "FixedStep") && FixedStepOpts.TID01EQ
 
  %assign activeFcn = FcnGetActiveFcnForDecl()
  %assign declareInFcnScope = "DeclareIn" + activeFcn + "FcnScope"
   
  %foreach tid = NumSampleTimes
    %if SLibPartitionGroupingSystem(system) && SLibSystemFcnPeriodicRateGrouping(system ,activeFcn)
      %assign pidVec = SLibGetPidFromTid(tid)
      %foreach i = SIZE(pidVec, 1)
        %assign LocalBO_Buf%<tid>% = ""
      %endforeach
    %else
      %assign LocalBO_Buf%<tid> = ""
    %endif
  %endforeach
 
  %switch type
    %case "LocalBlockOuput"
      %assign NumFlatFields = system.Variables.LocalBlockIODef.NumFlatFields
      %assign FirstLocation = system.Variables.LocalBlockIODef.FirstLocation
      %break
    %case "LocalDWork"
      %assign NumFlatFields = system.Interface.LocalSDWorkArgDef.NumFlatFields
      %assign FirstLocation = system.Interface.LocalSDWorkArgDef.FirstLocation
      %break
  %endswitch
 
  %if NumFlatFields > 0
    %assign numLocs = 0
    %foreach idx = NumFlatFields
      %assign ifCond = ""
      %assign endIfCond = ""
      %switch type
        %case "LocalBlockOuput"
          %assign localBO = BlockOutputs.LocalBlockOutput[FirstLocation + idx]
          %assign ifCond = SLibIfVariantCondition(localBO)
          %assign endIfCond = SLibEndIfVariantCondition(localBO)
          %break
        %case "LocalDWork"
          %assign localBO = DWorks.DWork[FirstLocation + idx]
          %assign ifCond = SLibIfVariantCondition(localBO)
          %assign endIfCond = SLibEndIfVariantCondition(localBO)
           
          %% For rapid accelerator parallel ForEach subsystem, local scratch DWork
          %% defined to use as iteration variable should not be declared because
          %% this variable has been moved to as an argument to the function.
          %if SLibNeedHandleParallelForEachSS(system, activeFcn)
            %if (FirstLocation + idx) == IDNUM(system.IndexingSigSrc)[1]
              %continue
            %endif
          %endif
           
          %if SLibOmitRecord(localBO)
            %continue
          %endif
          %break
      %endswitch
 
      %if localBO.%<declareInFcnScope> == 0 || localBO.VarGroupVarIdx > -1
        %assert localBO.%<declareInFcnScope> == 0
        %continue
      %endif
 
      %%
      %assign numLocs = numLocs+1
      %with localBO
        %openfile tmpBuf
        %assign optDims = LibGetRecordVectorDims(localBO)
        %assign dataType = SLibGetRecordOptStdDataTypeName(localBO, "", TLC_TRUE)
        %assign id = LibGetRecordIdentifier(localBO)
        %%yz %<dataType> %<tLocalBlockIO>_%<id>%<optDims>;
         
        %assign constrStr = ""
        %if LibGetRecordIsStdContainer(localBO) && !SLibIsMatrixUsingStdArray()
          %% pass size to std::vector constructor
          %assign cgTypeIdx = SLibGetRecordContainerCGTypeIdx(localBO)
          %assign constrStr = "(" + LibCGTypeSymbolicWidth(cgTypeIdx) + ")"
        %endif
         
        %if localBO.Autosar4p0ImplicitRead == "yes"
          %assert SLibAutosarActive()
          %assign constPrefix = SLibAutosarGetPtrConstPrefix()
          %<constPrefix> %<dataType> *%<id>;
        %elseif localBO.DeclareAsPointer == "no"
          %if ISFIELD(localBO, "Alignment")
            %% if it is struct type, emit the definition regardless of alignment value
            %if localBO.Alignment == -1 || ...
                LibCGTypeIsStruct(localBO.CGTypeIdx) || ...
                LibCGTypeIsComplex(localBO.CGTypeIdx)
              %if !EXISTS(localBO.initialValue)
                %<dataType> %<id>%<optDims>%<constrStr>;
              %else
                %<dataType> %<id>%<optDims> = %<localBO.initialValue>;
              %endif
            %elseif localAlign
              %assign align = SLibGetAlignmentSyntax(::CompiledModel.Name, ...
                id, dataType, localBO.Alignment, "DATA_ALIGNMENT_LOCAL_VAR")
              %<align> %<dataType> %<id>%<optDims>%<constrStr>;
            %endif
          %else
            %<dataType> %<id>%<optDims>%<constrStr>;
          %endif
        %else
          %assert SLibAutosarActive()
          %assign constPrefix = SLibAutosarGetPtrConstPrefix()
          %if LibGetRecordIsMatrix(localBO)
            %<constPrefix> %<dataType> (*%<id>)%<optDims>;
          %else
            %<constPrefix> %<dataType> *%<id>;
          %endif
        %endif
        %closefile tmpBuf
        %assign tmpBuf = SLibWrapBody(ifCond, tmpBuf, endIfCond)
        %if !SLibSystemFcnIsRateGroupType(activeFcn)
          %assign LocalBO_Buf0 = LocalBO_Buf0 + tmpBuf
        %else
          %assign TIDlen = SIZE(TID,1)
          %assign bufferIncludedForTID0 = TLC_FALSE
          %assign thisFieldHasBeenAdded = TLC_FALSE
          %foreach tidIdx = TIDlen
            %assign tid = (TYPE(TID) == "Vector") ? TID[tidIdx]:TID
            %assign pid = (TYPE(partition) == "Vector") ? partition[tidIdx] : partition
            %% When tid is negative, then we may reach the code
            %% %assign LocalBO_Buf%<tid> = LocalBO_Buf%<tid> + tmpBuf
            %% and it will fail because LocalBO_Buf-x does not exist. We
            %% should not put it in LocalBO_Buf0 either, because negative tid
            %% does not mean period sample time. We should just ignore it.
            %if TYPE(tid) == "Number" && tid < 0
              %continue
            %endif
            %if TYPE(tid) == "Number" && !LibAsynchronousTriggeredTID(tid) && !SLibSystemFcnPeriodicRateGrouping(system ,"Output")
              %if !thisFieldHasBeenAdded
                %assign LocalBO_Buf%<tid> = LocalBO_Buf%<tid> + tmpBuf
                %assign thisFieldHasBeenAdded = TLC_TRUE
              %endif
            %elseif TYPE(tid) == "Number" && tid > tid01Eq
              %if pid != -1
                %assign LocalBO_Buf%<tid>%<pid> = LocalBO_Buf%<tid>%<pid> + tmpBuf
              %else
                %assign LocalBO_Buf%<tid> = LocalBO_Buf%<tid> + tmpBuf
              %endif
            %elseif !bufferIncludedForTID0
              %if pid != -1
                %assign LocalBO_Buf0%<pid> = LocalBO_Buf0%<pid> + tmpBuf
              %else
                %assign LocalBO_Buf0 = LocalBO_Buf0 + tmpBuf
              %endif
              %assign bufferIncludedForTID0 = TLC_TRUE
            %endif
          %endforeach
        %endif
      %endwith
      %% Reset the DeclareInFcnScope flag to zero
      %assign localBO.%<declareInFcnScope> = 0
    %endforeach
 
    %% return a string for a non-rate-grouping fcn,
    %% instead of a vector (for rate-grouping fcns).
    %if !SLibSystemFcnIsRateGroupType(activeFcn)
      %if !WHITE_SPACE(LocalBO_Buf0)
        %switch type
          %case "LocalBlockOuput"
            %return "/* local block i/o variables *//n" + ...
              LocalBO_Buf0 + "/n"
            %%break
          %case "LocalDWork"
            %return "/* local scratch DWork variables *//n" + ...
              LocalBO_Buf0 + "/n"
            %%break
        %endswitch
      %else
        %return ""
      %endif
    %endif
 
    %%
    %assign Multirate_LocalBOBuf = []
    %if SLibPartitionGroupingSystem(system)
      %foreach taskIdx = SLibGetNumPartitions()
        %assign Multirate_LocalBOBuf = Multirate_LocalBOBuf + ""
      %endforeach
    %else
      %foreach Tid = NumSampleTimes
        %assign Multirate_LocalBOBuf = Multirate_LocalBOBuf + ""
      %endforeach
    %endif
     
    %% LocalBO of sync tid
    %if SLibSystemFcnPeriodicRateGrouping(system ,"Output")
      %assign bufIdx = 0
      %foreach Tid = NumRuntimeExportedRates
        %if SLibPartitionGroupingSystem(system)
          %% Buffer the local block io in the following order
          %% TID 0 PID 0
          %% ...
          %% TID 0 PID n
          %% ...
          %% TID m PID 1
          %% ...
          %% TID m PID n
          %% This make the code caching logic compatible for
          %% both rate grouping and partition grouping
          %assign pidVec = SLibGetPidFromTid(Tid)
          %foreach i = SIZE(pidVec, 1)
            %if !WHITE_SPACE(LocalBO_Buf%<Tid>%)
              %switch type
                %case "LocalBlockOuput"
                  %assign tmpBuffer = "/* local block i/o variables *//n" ...
                    + LocalBO_Buf%<Tid>% + "/n"
                  %break
                %case "LocalDWork"
                  %assign tmpBuffer = "/* local scratch DWork variables *//n" ...
                    + LocalBO_Buf%<Tid>% + "/n"
                  %break
              %endswitch
            %else
              %assign tmpBuffer = ""
            %endif
            %assign Multirate_LocalBOBuf[bufIdx] = tmpBuffer
            %assign bufIdx = bufIdx + 1
          %endforeach
        %elseif !WHITE_SPACE(LocalBO_Buf%<Tid>)
          %switch type
            %case "LocalBlockOuput"
              %assign tmpBuffer = "/* local block i/o variables *//n" ...
                + LocalBO_Buf%<Tid> + "/n"
              %break
            %case "LocalDWork"
              %assign tmpBuffer = "/* local scratch DWork variables *//n" ...
                + LocalBO_Buf%<Tid> + "/n"
              %break
          %endswitch
        %else
          %assign tmpBuffer = ""
        %endif
        %if !SLibPartitionGroupingSystem(system)
          %assign Multirate_LocalBOBuf[Tid] = tmpBuffer
        %endif
      %endforeach
      %assign Multirate_LocalBOBuf[0] = ...
        LocalBO_Buf + Multirate_LocalBOBuf[0]
    %elseif !LibAsynchronousTriggeredTID(LibGetSubsystemTID(system,TLC_TRUE))
      %openfile tmpBuffer
      %%
      %% The following section is for testing purpose only. We write out
      %% number of local variables into code comments if
      %% BufferReuseCrossBoundaryTesting feature is ON
      %%
      %if FEVAL("feature", "BufferReuseCrossBoundaryTesting") == 1
        /* Total number of local variables in mdlOutput is %<numLocs> */
      %endif
      %%
      %if !WHITE_SPACE(LocalBO_Buf)
        %<LocalBO_Buf>
      %endif
      %foreach Tid = NumRuntimeExportedRates
        %assign tmpBuf = LocalBO_Buf%<Tid>
        %<tmpBuf>
      %endforeach
      %closefile tmpBuffer
      %openfile mr_localBOBuf
      %if !WHITE_SPACE(tmpBuffer)
        %switch type
          %case "LocalBlockOuput"
            /* local block i/o variables */
            %break
          %case "LocalDWork"
            /* local scratch DWork variables */
            %break
        %endswitch
        %<tmpBuffer>
      %endif
      %closefile mr_localBOBuf
      %assign Multirate_LocalBOBuf[0] = mr_localBOBuf
    %endif
 
    %% LocalBO of async tid
    %assign numAsyncTasks = LibGetNumAsyncTasks() + SLibGetNumExplictTasksInUnion()
    %foreach tidIdx = numAsyncTasks
      %assign tid = NumRuntimeExportedRates + tidIdx
      %if SLibPartitionGroupingSystem(system)
        %assign bufIdx = SLibGetNumPartitions() - numAsyncTasks + tidIdx
        %assign pidVec = SLibGetPidFromTid(tid)
        %assert SIZE(pidVec, 1) == 1
        %if !WHITE_SPACE(LocalBO_Buf%<tid>%)
          %switch type
            %case "LocalBlockOuput"
              %assign tmpBuffer = "/* local block i/o variables *//n" ...
                + LocalBO_Buf%<tid>% + "/n"
              %break
            %case "LocalDWork"
              %assign tmpBuffer = "/* local scratch DWork variables *//n" ...
                + LocalBO_Buf%<tid>% + "/n"
              %break
          %endswitch
        %else
          %assign tmpBuffer = ""
        %endif
        %assign Multirate_LocalBOBuf[bufIdx] = tmpBuffer
      %else
        %if !WHITE_SPACE(LocalBO_Buf%<tid>)
          %switch type
            %case "LocalBlockOuput"
              %assign tmpBuffer = "/* local block i/o variables *//n" ...
                + LocalBO_Buf%<tid> + "/n"
              %break
            %case "LocalDWork"
              %assign tmpBuffer = "/* local scratch DWork variables *//n" ...
                + LocalBO_Buf%<tid> + "/n"
              %break
          %endswitch
        %else
          %assign tmpBuffer = ""
        %endif
        %assign Multirate_LocalBOBuf[tid] = tmpBuffer
      %endif
    %endforeach
 
    %return Multirate_LocalBOBuf %% return a vector.
  %endif
 
  %return "" %% return an empty string
%endfunction %% FcnDeclareAccessedLocalVariableGivenType
 
%%Function:SLibGenTerminateBody==============================================
%%Abstract:
%%Cachesallterminatecode
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function SLibGenTerminateBody() void
  %% Cache subsystems
  %assign ::BlockFcn = "Terminate"
  %foreach sysIdx = NumSystems-1
    %if (!LibIsSystemTerminateCached(System[sysIdx]))
      %<FcnGenSystemTerminate(System[sysIdx])>
    %endif
  %endforeach
 
  %% we don't need to generate terminate function for
  %% the root subsystem if current target is
  %% model reference target.
  %if !IsModelReferenceTarget()
    %assign rootSystem = System[NumSystems-1]
 
    %% Cache terminate function
    %% DSP Blockset uses terminate to manage it's database
    %<FcnGenBodyTerminateFcnCache(rootSystem)>
  %endif
  %assign ::BlockFcn = "Unknown"
%endfunction
 
 
%%Function:SLibGetNumericTID==============================================
%%Abstract:
%%getnumericTID.ifTIDistriggered,returnTriggerTIDoftheblock.
%%Ifitisconstant,return0,ifitsubsystem.returnsubsystemTID.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tVariantSource3.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmVSSfeedingInactiveVS_VC1.m
%%
%function SLibGetNumericTID(block)
  %assign tid = ""
  %with block
    %assert TYPE(TID) != "Vector"
    %if TYPE(TID) == "Number"
      %assign tid = TID
    %elseif ISEQUAL(TID,"triggered")
      %assign tid = TriggerTID[0]
    %elseif ISEQUAL(TID,"constant")
      %assign tid = 0
    %elseif ISEQUAL(TID,"Subsystem")
      %assign tid = ISFIELD(block, "TriggerTID") ? ...
                TriggerTID[0] : SubsystemTID
      %assign tid = ISEQUAL(tid,"constant") ? ...
        0 : tid
      %if TYPE(tid) == "Vector" && firstEntryOfTsMapIsGCD == "yes"
        %assign tid = tid[0]
      %endif
    %endif
  %endwith
  %return tid
%endfunction
 
%%FunctionFcnGenAsyncTopSSCode===================================
%%Abstract:
%%ThisfunctiongeneratescodeforAsynctidTopSubsystem.
%%
%%Thisfunctioniscalledaftercodegenerationofrootsystem.
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tMdlRefWithFcnOnDataAsVSSChoice.m
%%TopTester:est/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1396738_inlined_VC1.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/inlineVariants/tInlineVariants10.m
%%TopTester:test/toolbox/simulink/variants/tVariantGecks.m
%%
%function FcnGenAsyncTopSSCode() void
  %assert !IsModelReferenceTarget()
  %assign orgBlockFcn = ::BlockFcn
  %openfile retBuffer
  %assign ::BlockFcn = "OutputUpdate"
 
  %foreach idx = LibGetNumAsyncTasks() + SLibGetNumExplictTasksInUnion()
    %assign tid = idx + NumRuntimeExportedRates
 
    %% %if SampleTime[tid].IsVirtualTs == "yes"
    %% %continue
    %% %endif
    %% If the sample time owner is SimEvents, time management code is generated for union ts
    %% all union ts will work under one clock.
     
    %if SampleTime[tid].IsUnionTs == "yes"
      %if ISFIELD(SampleTime[tid],"TaskEntryFcnProtoType")
        %assign fcnProtoType = SampleTime[tid].TaskEntryFcnProtoType
      %else
        %% G1208670: Don't generate functions for union sample time if the it's
        %% an export function model, or is a temporary model generated during
        %% conversion from export function-call subsystems to an export function
        %% model.
        %if SLibIsExportFcnDiagram() || SLibIsTempModelGeneratedToExportFcn()
          %continue
        %endif
        %if CodeFormat == "S-Function"
          %assign fcnProtoType = "void %<::CompiledModel.Name>_ASYNC%<tid>(%<::tSimStructType>* %<::tSimStruct>, int %<::tControlPortIdx>, int %<::tTID>)"
        %else
          %assign fcnProtoType = "void %<::CompiledModel.Name>_ASYNC%<tid>(int %<::tControlPortIdx>)"
        %endif
      %endif
      %if ISFIELD(SampleTime[tid],"EventTaskTimeClock")
        %<fcnProtoType> {
            %<FcnGenerateTimeManagementForAsyncTs("Outputs", tid,"top")>
            {
                %<SLibDumpOutputUpdateCodeForAsyncTid(tid)>
            }
            %<FcnGenerateTimeManagementForAsyncTs("Outputs", tid,"bottom")>
        }
      %else
        %<fcnProtoType> {
            %<SLibDumpOutputUpdateCodeForAsyncTid(tid)>
        }
      %endif
      %assign rootSystem = System[NumSystems-1]
      %<LibAddToSystemField(rootSystem, "SystemFcnPrototype","%<fcnProtoType>;")>
    %elseif SampleTime[tid].EventSourceType == "SimEvent"
      %if !ISFIELD(SampleTime[tid], "EntryFcnName") || ISEMPTY(SampleTime[tid].EntryFcnName)
        %if CodeFormat == "S-Function"
          %assign fcnProtoType = "void %<::CompiledModel.Name>_ASYNC%<tid>(%<::tSimStructType>* %<::tSimStruct>, int %<::tControlPortIdx>, int %<::tTID>)"
        %else
          %assign fcnProtoType = "void %<::CompiledModel.Name>_ASYNC%<tid>(int %<::tControlPortIdx>)"
        %endif
      %else
        %continue
      %endif
      %openfile codeBody
      %<SLibDumpOutputUpdateCodeForAsyncTid(tid)>
      %closefile codeBody
      %if !WHITE_SPACE(codeBody)
        %<fcnProtoType> {
          %<FcnGenerateTimeManagementForAsyncTs("Outputs", tid,"top")>
          {
              %<codeBody>
          }
          %<FcnGenerateTimeManagementForAsyncTs("Outputs", tid,"bottom")>
        }
      %endif
      %assign rootSystem = System[NumSystems-1]
      %<LibAddToSystemField(rootSystem, "SystemFcnPrototype","%<fcnProtoType>;")>
    %elseif SampleTime[tid].EventSourceType == "SLMessages"
      %if !Accelerator
        %assign fcnProtoType = "void %<::CompiledModel.Name>_ASYNC%<tid>(int %<::tControlPortIdx>)"
        %<fcnProtoType> {
          %<FcnGenerateTimeManagementForAsyncTs("Outputs", tid,"top")>
          %<SLibDumpOutputUpdateCodeForAsyncTid(tid)>
          %<FcnGenerateTimeManagementForAsyncTs("Outputs", tid,"bottom")>
        }
        %assign rootSystem = System[NumSystems-1]
        %<LibAddToSystemField(rootSystem, "SystemFcnPrototype","%<fcnProtoType>;")>
      %endif
    %elseif SampleTime[tid].EventSourceType == "PlainEvent"
      %assign fcnProtoType = "void %<::CompiledModel.Name>_EVENT%<tid>()"
      %<fcnProtoType> {
        %<FcnGenerateTimeManagementForAsyncTs("Outputs", tid,"top")>
        %<SLibDumpOutputUpdateCodeForAsyncTid(tid)>
        %<FcnGenerateTimeManagementForAsyncTs("Outputs", tid,"bottom")>
      }
      %assign rootSystem = System[NumSystems-1]
      %<LibAddToSystemField(rootSystem, "SystemFcnPrototype","%<fcnProtoType>;")>
    %elseif SLibResetOrResetWithInitEventTID(tid) && !Accelerator && !isRAccel
      %assign rootSystem = System[NumSystems-1]
      %assign rootSystem.CurrentTID = tid
      %assign fcnParams = SLibModelFcnArgs("Output",TLC_FALSE,tid)
      %assign fcnReturns = "void"
      %assign fcnName = SampleTime[tid].EntryFcnName
       
      %if SLibAutosarActive()
        %assign resetRunnable = FcnGetAutosarResetRunnable(tid)
        %if !ISEMPTY(resetRunnable)
          %assign fcnName = resetRunnable.Symbol
          %assign memsecUUID = SLibGetFcnMemSecUUIDForFunction("Reset", "%")
          %assign fcnReturns = SLibAutosarCompilerAbstractionForFcnDeclRtnType(fcnReturns, "FuncCalledByRTE", memsecUUID)
          %assign fcnProtoType = "%<fcnReturns> %<fcnName>(%<fcnParams>)"
        %else
          %continue
        %endif
      %else
        %assign namespace = ""
        %if GenerateClassInterface
          %assign FPC = FcnGetRTWCPPStepPrototypeRecord()
          %assign namespace = FPC.ModelClassName + "::"
        %endif
        %assign fcnProtoType = "%<fcnReturns> %<namespace>%<fcnName>(%<fcnParams>)"
      %endif
      %openfile codeBody
      %<FcnGenerateTimeManagementForAsyncTs("Outputs", tid,"top")>
      %<SLibDumpOutputUpdateCodeForAsyncTid(tid)>
      %<FcnGenerateTimeManagementForAsyncTs("Outputs", tid,"bottom")>
      %closefile codeBody
      %assign prevNSFlag = rootSystem.SystemNamespaceFlag
      %if SLibSystemNeedsNamespace(rootSystem)
 
        %<SLibEmitNamespaceStartForSystem(rootSystem)>
      %endif
      %if CGMODEL_ACCESS("CGModel.isIndividualFunctionMappingEnabled") || SLibAutosarActive()
        %<SLibGetFcnMemSecPragmaForFunction(fcnName, "Reset", "%", "Pre")>
      %else
        %<SLibGetFcnMemSecPragmaForSystem(fcnName, "MemSecFuncExecute", "Pre", rootSystem)>
      %endif
      %<fcnProtoType> {
        %if !WHITE_SPACE(codeBody)
          %if SampleTime[tid].EventSourceType == "ResetWithInitEvent"
            %<SLibDumpERTAndModelrefInitMemoryCode(TLC_FALSE, TLC_TRUE, 0)>
          %endif
          %<codeBody>
        %else
          /* (no output/update code required) */
        %endif
      }
      %if CGMODEL_ACCESS("CGModel.isIndividualFunctionMappingEnabled") || SLibAutosarActive()
        %<SLibGetFcnMemSecPragmaForFunction(fcnName, "Reset", "%", "Post")>
      %else
        %<SLibGetFcnMemSecPragmaForSystem(fcnName, "MemSecFuncExecute", "Post", rootSystem)>
      %endif
      %if prevNSFlag == 0
        %<SLibEmitNamespaceCloseForSystem(rootSystem)>
      %endif
      %elseif SLibNonInlinedModelWideEventTID(tid)
      %% do nothing
    %else
      %assign block = FcnGetTaskTopSfcnBlock(tid)
      %if WHITE_SPACE(block)
        %continue
      %endif
      %assign system = System[block.BlkSysIdx]
      %if !ISFIELD(block, "GenCodeForTopAsyncSS")
        %continue
      %endif
      %if block.GenCodeForTopAsyncSS
        %continue
      %else
        %assign block.GenCodeForTopAsyncSS = TLC_TRUE
      %endif
      %if block.SFunctionType == "TLC"
        %openfile tmpBuffer
        %with system
          %with block
            %assign ::BlockFcn = "OutputUpdate"
            %<generateNonExprOutput(block, system, "", 0, TLC_FALSE)> /
            %% For model reference with function-call inputs, also
            %% generate the enable, disable and initialize
            %if IsModelReferenceTarget() || SLibIsExportFcnDiagram()
              %assign ::BlockFcn = "Enable"
              %<GENERATE(block, "Enable", system)> /
              %assign ::BlockFcn = "Disable"
              %<GENERATE(block, "Disable", system)> /
            %endif
          %endwith
        %endwith
        %closefile tmpBuffer
        %if !WHITE_SPACE(tmpBuffer)
          %if !ISFIELD(block, "AsyncCallerGenCode")
            %assign warnTxt = ...
              "The following code generated from sfunction %<block.Name>"...
              "will be discarded /n"...
              "%<tmpBuffer> /n"...
              "Flag AsyncSSCallerGenCode must be added to asynchronous "...
              "sfunction %<block.Name> in BlockInstanceSetup function "...
              "if the asynchronous caller itself generates code. "...
              "Please see vxtask1.tlc for example. "
            %<LibReportWarning(warnTxt)>
          %endif
        %endif
        %assign fcnProtoType = ""
        %if ISFIELD(block, "taskFcnName")
          %assign fcnProtoType = "void %<block.taskFcnName>(void)"
        %elseif ISFIELD(block,"SFcnParamSettings") && ...
          ISFIELD(block.SFcnParamSettings,"ISRNames")
          %assign elm = ::CompiledModel.SampleTime[tid].AsyncSfcnBlkElm
          %assign fcnProtoType = "void %(void)"
        %endif
        %if !WHITE_SPACE(fcnProtoType)
          %<LibAddToSystemField(rootSystem, "SystemFcnPrototype","%<fcnProtoType>;")>
        %endif
      %endif
    %endif
  %endforeach
  %assign ::BlockFcn = orgBlockFcn
  %closefile retBuffer
  %return retBuffer
%endfunction
 
%%Fucntion:SLibGenerateModuleFcn=============================================
%%Abstract:
%%
%function SLibGenerateModuleFcn(module, fcnType) void
  %assign block = FcnRootOpaqueBlock()
  %assign fileName = module.TLCFileName + "_" + fcnType
  %assign fcnBuff = ""
  %openfile fcnBuff
   
  %<GENERATE_TYPE(block, fcnType, fileName)>
  %closefile fcnBuff
  %assign unused = UNLOAD_GENERATE_TYPE(block, fileName)
  %return fcnBuff
%endfunction %% SLibGenerateModuleFcn
 
 
%%Function:SLibGenBodyCache==================================================
%%Abstract:
%%Cachesallbodycode(minustheterminatecodesincemallocsoccur
%%intheregistrationandblockinstancecode).
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants_subsys.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmIterSys_GotoFromBlock_VC1.m
%%TopTester:test/toolbox/simulink/variants/modelVariants/tVariantsBasic.m
%%
%function SLibGenBodyCache() void
 
  %selectfile STDOUT
  %if RTWVerbose
### Caching model source code
  %endif
  %flushfile STDOUT
  %selectfile NULL_FILE
  %if Accelerator
    %<LibAddToSystem(System[NumSystems-1], "FcnCallSubsystemPtrs", ...
      SLibSetupFCSubsystemPtrs())>
  %endif
 
  %% Cache all custom registered symbols
  %<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate custom registered symbols")>
  %with RTWCGModules
    %assign skipLast = IsModelReferenceTarget()
    %foreach modIdx = NumRTWCGModules
      %if skipLast && modIdx == NumRTWCGModules-1
        %break
      %endif
      %assign module = RTWCGModule[modIdx]
      %if ISFIELD(module, "CGSystemIdx")
        %assign fileSys = System[module.CGSystemIdx]
        %if module.HasConstants
          %assign constDef = SLibGenerateModuleFcn(module, "ModuleConstants")
          %<SLibCacheSystemCodeToFile("sys_data_define", fileSys, ...
            constDef)>
        %endif
        %if module.HasPublicTypes
          %assign typeDef = SLibGenerateModuleFcn(module, "PublicModuleTypes")
          %assign typeDefHFile = SLibGetFileRecForCode("mdl_data_typedef")
          %if !WHITE_SPACE(typeDef)
            %<SLibSetModelFileAttribute(typeDefHFile, "Typedefs", typeDef)>
            %<SLibSetModelFileDeferredIncludeCoderTypes(typeDefHFile, TLC_TRUE)>
          %endif
        %endif
        %if module.HasExportedTypes
          %assign typeDef = SLibGenerateModuleFcn(module, "ExportedModuleTypes")
          %<SLibCacheCodeToFile("baseMdl_data_typedef", typeDef)>
        %endif
        %if module.HasVariables
          %assign varDecl = SLibGenerateModuleFcn(module, "ModuleVariables")
          %<SLibCacheSystemCodeToFile("sys_data_decl", fileSys, varDecl)>
        %endif
      %endif
    %endforeach
  %endwith %% RTWCGModules
  %<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate custom registered symbols")>
 
  %<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate system body cache for all modules")>
     
  %assign skipLast = IsModelReferenceTarget()
 
  %foreach modIdx = RTWCGModules.NumRTWCGModules
    %%%
    %% When generating model reference target, we do not need to generate
    %% code for root. (After cleanup, we should be abled to skip
    %% code generation for root)
    %%
 
    %if skipLast && modIdx == RTWCGModules.NumRTWCGModules - 1
      %break
    %endif
    %assert -1 == ::CurrentModuleIdx
    %assign ::CurrentModuleIdx = modIdx
    %assign module = RTWCGModules.RTWCGModule[modIdx]
     
 
    %if ISFIELD(module, "CGSystemIdx")
      %<FcnGenBodySysCache(module)>
    %elseif modIdx == RTWCGModules.NumRTWCGModules - 1
      %% Root system module
      %addtorecord module CGSystemIdx NumSystems-1
      %<FcnGenBodySysCache(module)>
    %endif
    %<SLibUnloadTLCInterface(module)>
 
    %assert ::CurrentModuleIdx == modIdx
    %assign ::CurrentModuleIdx = -1
  %endforeach
  %<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate system body cache for all modules")>
    
  %<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate async tid for top subsystem")>
  %<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate async tid for top subsystem")>
 
  %<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate data typedef for discrete derivative signals")>
  %<SLibGetNonContDerivSig()>
  %<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate data typedef for discrete derivative signals")>
 
  %<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Load fixed-point utilities")>
  %<FixPt_LoadFixPtUtils()>
  %<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Load fixed-point utilities")>
 
   
%endfunction %% SLibGenBodyCache
 
%%Function:FcnOutputFilePath=================================================
%%Abstract:
%%Givenacodertypesfilename,returnthepathtothatfile
%function FcnOutputFilePath(coderTypesFilename) void
  %if !ISEMPTY(::CompiledModel.GenUtilsPath)
    %assign coderTypesFilename = FEVAL("fullfile",::CompiledModel.GenUtilsPath,coderTypesFilename)
  %endif
  %return coderTypesFilename
%endfunction
 
%%Function:SLibFormatCoderTypesFile==========================================
%%Abstract:
%%Formatscodertypesfile
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function SLibFormatCoderTypesFile(fileKey, fileName, filePath) void
  %if !::AnsiDataTypeName.tlcAddBanner_%<fileKey>
    %assign fileRec = SLibGetFileRecForCode(fileKey + "_hdr")
    %<SLibSetModelFileAttribute(fileRec, "Filter", 1)>
    %<SLibAddGeneratedFileToList(filePath, "utility", "header","")>
  %else
    %openfile fileContent
    %include filePath
    %closefile fileContent
    %<SLibCacheCodeToFile(fileKey + "_defines", fileContent)>
    %assign fileRec = SLibGetFileRecForCode(fileKey + "_hdr")
    %<LibSetSourceFileOutputDirectory(fileRec, GenUtilsPath)>
    %openfile fileBanner_buffer
/*
 * %<fileName>
 *
 %<SLibCommonUtilHeaderInfo()>/
 */
    %closefile fileBanner_buffer
    %<SLibCacheCodeToFile(fileKey + "_hdr_ban", fileBanner_buffer)>
  %endif
%endfunction
 
 
%%Function:SLibFormatCoderTypesFile==========================================
%%Abstract:
%%Formatshalf_type.handhalf_type.cfiles
%%
%function SLibFormatHalfTypesFile() void
  %% half_type.h
  %if ISFIELD(::AnsiDataTypeName, "tlcAddBanner_halfType_hdr")
    %<SLibAddGeneratedFileToList(SLibCoderHalfTypeHdrFilePath(), "utility", "header", "")>
    %assign filePath = SLibCoderHalfTypeHdrFilePath()
    %openfile fileContent
    %include filePath
    %closefile fileContent
    %<SLibCacheCodeToFile("halfType_hdr_defines", fileContent)>
    %assign fileRec = SLibGetFileRecForCode("halfType_hdr")
    %<LibSetSourceFileOutputDirectory(fileRec, GenUtilsPath)>
    %openfile buf
/*
 * %<SLibCoderHalfTypeHdrFilename()>
 *
 %<SLibCommonUtilHeaderInfo()>/
 */
    %closefile buf
    %<SLibCacheUtilCodeToFile("halfType_hdr_ban", fileRec, buf)>
  %endif
 
  %% half_type.c
  %if ISFIELD(::AnsiDataTypeName, "tlcAddBanner_halfType_src")
    %<SLibAddGeneratedFileToList(SLibCoderHalfTypeSrcFilePath(), "utility", "source", "")>
    %assign filePath = SLibCoderHalfTypeSrcFilePath()
    %openfile fileContent
    %include filePath
    %closefile fileContent
    %<SLibCacheCodeToFile("halfType_src_defines", fileContent)>
    %assign fileRec = SLibGetFileRecForCode("halfType_src")
    %openfile buf
/*
 * %<SLibCoderHalfTypeSrcFilename()>
 *
 %<SLibCommonUtilHeaderInfo()>/
 */
    %closefile buf
    %<SLibCacheUtilCodeToFile("halfType_src_ban", fileRec, buf)>
 
  %endif
%endfunction
 
%%Function:SLibGenHeaderCache===============================================
%%Abstract:
%%Cachesallsystemheaderfiles.
%%
%%TopTester:test/toolbox/fixpoint/fixpt_autoscale/MLFB/apply_workflow/system_tests
%%TopTester:test/toolbox/simulink/variants/variantBus/tBusModelRef.m
%function SLibGenHeaderCache() void
  %% Generate ANSI data type name info and rtwtypes.h. Need to pass whether full or
  %% minimized (ERT) version of rtwtypes.h is desired as well as the location to place
  %% rtwtypes.h.
  %if SLibIsERTTarget() && ...
    (::CompiledModel.ModelReferenceTargetType != "SIM") && ...
    (::CompiledModel.NumChildSFunctions == 0)
    %% There is a special case when we want overwrite rtwtypes.h with 'full' version.
    %% If not ERT target, must already be full version.
    %% Another condition is the first sub model doesn't contain non-inlined
    %% sfunction, so we get minimized style rtwtypes.h. But top model or next
    %% sub model does, we need to overwrite the minimized style with full
    %% style rtwtypes.h. (That's because we decide whether to use full or
    %% minimized style rtwtypes.h depends on NumChildSfcn, NOT
    %% SupportNonInlinedSFcns option).
    %%
    %assign ::RTWTypesStyle = "minimized"
  %else
    %assign ::RTWTypesStyle = "full"
  %endif
   
  %% Include IR based usage of multiword types.
  %assign multiwordBits = ::CompiledModel.LargestMultiwordBits
  %if ::CompiledModel.DeclaredFixedPointWordSizeUsage > multiwordBits
    %if SLibIsERTTarget() && (::CompiledModel.ModelReferenceTargetType != "SIM") && ...
      ConfigSet.MultiwordTypeDef == "User defined"
 
      %<SLibReportErrorWithIdAndArgs("RTW:tlc:MWLenIssue", ...
          ["%<::CompiledModel.DeclaredFixedPointWordSizeUsage>", "%<multiwordBits>", ...
           "%<::CompiledModel.DeclaredFixedPointWordSizeUsage>"])>
 
    %else
      %assign multiwordBits = ::CompiledModel.DeclaredFixedPointWordSizeUsage
    %endif
  %endif
   
  %% Generate coder types files
  %<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate rtwtypes.h")>
 
  %assign hostBasedSimTarget = SLibIsHostBasedSimulationTarget()
   
  %assign needMdlrefTypes = (IsModelReferenceTarget() || ...
    HasModelReferenceBlocks()) && ::tMdlRefTimingBridgeAccessed
 
  %assign ::needZeroCrossingTypes = ...
    ::CompiledModel.ZeroCrossingDefinitionsRequired==1 || ...
    SLibRTModelNeedsZCTypes()==TLC_TRUE
   
  %assign hasMessages = EXISTS(CompiledModel.SupportSLMessagesRegistration)
   
  %assign needHalfPrecisionType = %<SLibDeclareHalfPrecisionUsage()>
   
  %assign ::AnsiDataTypeName = FEVAL("coder.internal.wrapGenRTWTYPESDOTH", ...
    LibGetModelName(), GenUtilsPath, RTWTypesStyle, ...
    GenUtilsSrcInSharedLocation, multiwordBits, needMdlrefTypes, ...
    TLC_FALSE, hostBasedSimTarget, needZeroCrossingTypes, hasMessages, ...
    needHalfPrecisionType)
  %if TYPE(::AnsiDataTypeName) != "Scope"
    %assign errmsg = FEVAL("lasterr")
    %<LibReportError( "Error occurred when generating rtwtypes.h: %<errmsg>")>
  %endif
  %assign needBuiltinTypeidTypes = ::AnsiDataTypeName.builtin_typeid_types
  %assign needMultiWordTypes = ::AnsiDataTypeName.multiword_types
  %<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate rtwtypes.h")>
 
  %<SLibFormatCoderTypesFile("rtwtypes", SLibCoderTypesFilename(), SLibCoderTypesFilePath())>
   
  %if needMdlrefTypes
    %<SLibFormatCoderTypesFile("mdlrefTypes", SLibCoderModelReferenceTypesFilename(), SLibCoderModelReferenceTypesFilePath())>
  %endif
   
  %if needBuiltinTypeidTypes
    %% Dump Fixpt Odd Size Typedefs
    %% Dump SS_INT* macros
    %% These are not required if needBuiltinTypeidTypes is false
    %assign typesFile = SLibGetFileRecForCode("mdl_data_typedef")
    %openfile tmpBuffer
    %<LibDumpFixptOddSizeTypedefs()>
    %closefile tmpBuffer
    %if !WHITE_SPACE(tmpBuffer)
      %<SLibSetModelFileDeferredIncludeCoderTypes(typesFile, TLC_TRUE)>
      %<SLibSetModelFileAttribute(typesFile, "Typedefs", tmpBuffer)>
    %endif
    %<SLibFormatCoderTypesFile("builtinTypeidTypes", SLibCoderBuiltinTypeidTypesFilename(), SLibCoderBuiltinTypeidTypesFilePath())>
  %endif
   
  %if needMultiWordTypes
    %<SLibFormatCoderTypesFile("multiwordTypes", SLibCoderMultiwordTypesFilename(), SLibCoderMultiwordTypesFilePath())>
  %endif
   
  %if needZeroCrossingTypes
    %<SLibFormatCoderTypesFile("zerocrossingTypes", SLibCoderZerocrossingTypesFilename(), SLibCoderZerocrossingTypesFilePath())>
  %endif
   
  %if needHalfPrecisionType
    %<SLibFormatHalfTypesFile()>
  %endif
   
  %assign usedFilenames = []
  %assign usedNumericFilenames = []
  %assign usedFilenames = usedFilenames + SLibCoderTypesFilename()
  %assign usedNumericFilenames = usedNumericFilenames + SLibCoderTypesFilename()
  %if needMdlrefTypes
    %assign usedFilenames = usedFilenames + SLibCoderModelReferenceTypesFilename()
  %endif
  %if needBuiltinTypeidTypes
    %assign usedFilenames = usedFilenames + SLibCoderBuiltinTypeidTypesFilename()
  %endif
  %if needMultiWordTypes
    %assign usedFilenames = usedFilenames + SLibCoderMultiwordTypesFilename()
    %assign usedNumericFilenames = usedNumericFilenames + SLibCoderMultiwordTypesFilename()
  %endif
  %if needZeroCrossingTypes
    %assign usedFilenames = usedFilenames + SLibCoderZerocrossingTypesFilename()
    %assign usedNumericFilenames = usedNumericFilenames + SLibCoderZerocrossingTypesFilename()
  %endif
  %if needHalfPrecisionType
    %assign usedFilenames = usedFilenames + SLibCoderHalfTypeHdrFilename()
    %assign usedNumericFilenames = usedNumericFilenames + SLibCoderHalfTypeHdrFilename()
  %endif
 
  %addtorecord ::CompiledModel.CoderTypesInfo UsedFilenames usedFilenames
  %addtorecord ::CompiledModel.CoderTypesInfo UsedNumericFilenames usedNumericFilenames
 
  %% Cache system headers
  %<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate system headers cache for all modules")>
  %foreach sysIdx = NumSystems
    %assign system = System[sysIdx]
    %assign skip = IsModelReferenceTarget() && sysIdx == NumSystems -1
    %if !skip
      %assert (!system.StandaloneSubsystem || StandaloneSSSupported)
 
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate utility includes")>
      %<LibCacheUtilityIncludes(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate utility includes")>
 
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate system includes")>
      %<LibCacheSystemIncludes(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate system includes")>
 
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate shared type includes")>
      %<LibCacheSharedTypeIncludes(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate shared type includes")>
 
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate shared data includes")>
      %<LibCacheSharedDataIncludes(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate shared data includes")>
 
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate block i/o struct def")>
      %<LibCacheSystemBlkIOStructDef(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate block i/o struct def")>
 
      %if ((CodeFormat != "S-Function") || Accelerator)
        %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate dwork struct def")>
         %<LibCacheSystemDWorkStructDef(sysIdx)>
        %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate dwork struct def")>
      %endif
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate cstates struct def")>
      %<LibCacheSystemCStatesStructDef(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate cstates struct def")>
 
      %% The global (model-wide) periodic state vector is only generated at the root level.
      %if (sysIdx == GetBaseSystemIdx())
        %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate periodic state vector global def")>
        %<LibCacheSystemPeriodicCStatesStructDef(sysIdx)>
        %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate periodic state vector global def")>
      %endif
 
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate state derivative struct def")>
      %<LibCacheSystemStateDerivStructDef(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate state derivative struct def")>
 
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate state disabled struct def")>
      %<LibCacheSystemStateDisabledStructDef(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate state disabled struct def")>
 
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate state absolute tolerance struct def")>
      %<LibCacheSystemCStateAbsoluteToleranceStructDef(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate state absolute tolerance struct def")>
 
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate state perturb min struct def")>
      %<LibCacheSystemCStatePerturbMinStructDef(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate state perturb min struct def")>
       
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate state perturb max struct def")>
      %<LibCacheSystemCStatePerturbMaxStructDef(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate state perturb max struct def")>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate zero-crossing signal value struct def")>
       
       
      %<LibCacheSystemZCSignalValueStructDef(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate zero-crossing signal value struct def")>
 
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate zero-crossing enable struct def")>
      %<LibCacheSystemZCEStructDef(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate zero-crossing enable struct def")>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate Coder Data Group struct defs")>
      %<LibCacheSystemCoderDataGroupStructDefs(sysIdx)>
      %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate Coder Data Group struct defs")>
      %if (ModelIsLinearlyImplicit == "yes")
                 
        %% The global (model-wide) mass matrix is only generated at the root level.
        %if (sysIdx == GetBaseSystemIdx())
          %%%<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,"Generate mass matrix global def")>
          %<LibCacheSystemMassMatrixGlobalDef(sysIdx)>
          %%%<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate mass matrix global def")>
        %endif
         
      %endif
    %endif
  %endforeach
  %<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,"Generate system headers cache for all modules")>
   
  %if SLibIsERTTarget()
    %<SLibCachSymbolicDimensionConstraints()>
  %endif
 
  %% ===========================================================================
  %% Create the the ERT S-Function rtwtypes.h file
  %%
  %if GenerateErtSFunction
    %assign needZeroCrossingTypes = TLC_FALSE
    %assign needHalfPrecisionType = TLC_FALSE
    %assign gPath = FEVAL("rtwprivate", "rtwattic","getBuildDir")
    %assign ertSfcnRtwtypesBaseName = SLibGetFileNameForCode("rtwtypes_hdr") + "_sf"
    %assign ertSfcnRtwtypesFileName = ertSfcnRtwtypesBaseName + ".h"
    %assign ertSfcnRtwtypesFilePath = FEVAL("fullfile",gPath,ertSfcnRtwtypesFileName)
    %assign ::AnsiDataTypeName = FEVAL("coder.internal.wrapGenRTWTYPESDOTH", ...
      LibGetModelName(), gPath, RTWTypesStyle, ...
      TLC_FALSE, 0, TLC_FALSE, TLC_TRUE, hostBasedSimTarget, needZeroCrossingTypes, ...
      TLC_FALSE, needHalfPrecisionType)
    %openfile contentWithBanner
 /*
 * %<ertSfcnRtwtypesFileName>
 *
 %<SLibCommonUtilHeaderInfo()>/
 */
  
    %include ertSfcnRtwtypesFilePath
    %closefile contentWithBanner
    %openfile fileWithBanner = ertSfcnRtwtypesFilePath
    %<contentWithBanner>
    %closefile fileWithBanner
  %endif
   
%endfunction
 
%function SLibGenConstBlkIOCache() void
  %%
  %% Those structures get accessed in the commonreglib and
  %% this might alter the contents.
  %%
  %assign numSys = GetNumSystemsForCodeGen()
  %foreach sysIdx = numSys
    %<LibCacheSystemConstBlkIOStructDef(sysIdx)>
  %endforeach
%endfunction
 
 
%%Function:SLibExtModeHostOnlyStub===========================================
%%Abstract:
%%Stubsoutsystemthatonlyrunsonhost(forexternalmode).
%%
%function SLibExtModeHostOnlyStub(system) void
  %if ISFIELD(system,"StartFcn")
    %<LibSetSystemField(system, "CachedStartFcn", "")>
  %endif
  %if ISFIELD(system,"EnableFcn")
    %<LibSetSystemField(system, "CachedEnableFcn", "")>
  %endif
  %if ISFIELD(system,"SetupRuntimeResourcesFcn")
    %<LibSetSystemField(system, "CachedSetupRuntimeResourcesFcn", "")>
  %endif
  %if ISFIELD(system,"InitializeFcn")
    %<LibSetSystemField(system, "CachedInitializeFcn", "")>
  %endif
  %if ISFIELD(system,"SystemInitializeFcn")
    %<LibSetSystemField(system, "CachedSystemInitializeFcn", "")>
  %endif
  %if ISFIELD(system,"SystemResetFcn")
    %<LibSetSystemField(system, "CachedSystemResetFcn", "")>
  %endif
  %if ISFIELD(system,"OutputFcn")
    %<LibSetSystemField(system, "CachedOutputFcn", "")>
  %endif
  %if ISFIELD(system,"OutputUpdateFcn")
    %<LibSetSystemField(system, "CachedOutputFcn", "")>
    %<LibSetSystemField(system, "CachedUpdateFcn", "")>
  %endif
  %if ISFIELD(system,"UpdateFcn")
    %<LibSetSystemField(system, "CachedUpdateFcn", "")>
  %endif
  %if ISFIELD(system,"DerivativeFcn")
    %<LibSetSystemField(system, "CachedDerivativeFcn", "")>
  %endif
  %if ISFIELD(system,"ProjectionFcn")
    %<LibSetSystemField(system, "CachedProjectionFcn", "")>
  %endif
  %if ISFIELD(system,"ForcingFunctionFcn")
    %<LibSetSystemField(system, "CachedForcingFunctionFcn", "")>
  %endif
  %if ISFIELD(system,"MassMatrixFcn")
    %<LibSetSystemField(system, "CachedMassMatrixFcn", "")>
  %endif
  %if ISFIELD(system,"InitSystemMatricesFcn")
    %<LibSetSystemField(system, "CachedInitSystemMatricesFcn", "")>
  %endif
  %if ISFIELD(system,"ZeroCrossingFcn")
    %<LibSetSystemField(system, "CachedZeroCrossingFcn", "")>
  %endif
  %if ISFIELD(system,"DisableFcn")
    %<LibSetSystemField(system, "CachedDisableFcn", "")>
  %endif
  %if ISFIELD(system,"CleanupRuntimeResourcesFcn")
    %<LibSetSystemField(system, "CachedCleanupRuntimeResourcesFcn", "")>
  %endif
  %if ISFIELD(system,"TerminateFcn")
    %<LibSetSystemField(system, "CachedTerminateFcn", "")>
  %endif
  %if ISFIELD(system,"ConstCodeFcn")
    %<LibSetSystemField(system, "CachedConstCodeFcn", "")>
  %endif
%endfunction %% SLibExtModeHostOnlyStub
 
%endif %% _COMMONBODLIB_
 
%%[EOF]commonbodlib.tlc