%%
%%
%%
%%
%%Copyright1994-2020TheMathWorks,Inc.
%%
%%Description:
%%ThisTLClibraryfilecontainsfunctionforcachingspecialblock
%%codeintothevariousmodelfiles.
 
%if EXISTS("_CACHELIB_") == 0
%assign _CACHELIB_ = 1
 
%include "codecache_api.tlc"
 
%<LibAddToCompiledModel("ExternsCache", "")>
%<LibAddToCompiledModel("SourceCodeCache", "")>
%<LibAddToCompiledModel("NonFiniteParamAssignmentsCache", "")>
%<LibAddToCompiledModel("NonFiniteBlockIOAssignmentsCache", "")>
%<LibAddToCompiledModel("FunctionPrototypesCache", "")>
%<LibAddToCompiledModel("DefinesCache", "")>
%<LibAddToCompiledModel("IncludesCache", "")>
%<LibAddToCompiledModel("TypedefsCache", "")>
%<LibAddToCompiledModel("GlobalPrmDataCache", "")>
 
%assign tempVar = tempRec {NumBlocks 0}
%<LibAddToCompiledModel("IntegerOnlyWarningCache", tempRec)>
%undef tempVar
%<LibAddToCompiledModel("NumFiles", 0)>
 
 
%%Function:LibTrapCacheAssert================================================
%%Abstract:
%%LibTrapCacheAssertdeterminesiftheaccessofacachevariable
%%isvalid(i.e.cacheVarshouldnotbeaNumber).Iftheaccessis
%%anumberthisfunctiongeneratesanerror,printstheTLC
%%callstackandexits.
%%
%function LibTrapCacheAssert(cacheVar) void
  %if TYPE(cacheVar) == "Number"
    %openfile assertTxt
 
 
Attempt to access a cache variable prior to calling its cache /
generation function.
 
The current cache:
 
%<cacheVar>
    %closefile assertTxt
    %<LibReportFatalError(assertTxt)>
  %endif
%endfunction
 
 
%assign ResetGlobalsErrorString = "#error A TLC Global was used after it was reset. To avoid this error, set the TLC variable 'ResetTLCGlobalsAfterUse' to 0."
 
%%Function:SLibResetTLCGlobal================================================
%%Abstract:
%%ResetTLCglobalsthatareeitheratrootlevelTLCnamespaceorafield
%%ofthe::CompiledModelrecord.ThisfunctioniscontrolledbytheTLCflag
%%'ResetTLCGlobalsAfterUse'.
%%
%function SLibResetTLCGlobal(name) void
  %if ResetTLCGlobalsAfterUse
    %if ISFIELD(::CompiledModel, name)
      %assign ::CompiledModel.%<name> = ResetGlobalsErrorString + name
    %elseif EXISTS(name)
      %assign %<name> = ResetGlobalsErrorString + name
    %endif
  %endif
%endfunction
 
 
%%Function:SLibCacheNonFiniteConstBIOAssignment==============================
%%Abstract:
%%SLibCacheNonFiniteConstBIOAssignmentiscalledtocacheassignmentswhich
%%needtobeplacedintheregistrationfunctionbecauseofnon-finite
%%initialization.Thatis,rtInfs,rtNaNs,andrtMinusInfsparametersare
%%initializedtozerountiltheregistrationfunctioniscalled,
%%re-initializingthemtotheirappropriatevalue.Eachcalltothisfunction
%%appendsyourbuffertotheexistingcachebuffer.
%%
%%Arguments:
%%sysIdx:indexforthesystemtogenerateinitialization
%%instIdx:instanceindexofthesystem.
%%buffer:Buffertobecachedforplacementinsidethemodel's
%%registrationfunction.
%%Example:
%%%openfilebuffer
%%rtP.block.param_1=%<LibRealNonFinite(inf)>;
%%rtP.block.param_i=%<LibRealNonFinite(nan)>;
%%rtP.block.param_n=%<LibRealNonFinite(-inf)>;
%%%closefilebuffer
%%%<SLibCacheNonFiniteConstBIOAssignment(sysIdx,buffer)>
%%
%function SLibCacheNonFiniteConstBIOAssignment(sysIdx, instIdx, buffer) void
  %% The root system may have an instance index of -1, map it back to 0
  %assign instIdx = (instIdx == -1) ? 0 : instIdx
  %assign sysIdx = System[sysIdx].StandaloneParentSysIdx[instIdx]
   
  %if sysIdx != -1
    %<LibAddToSystemField(System[sysIdx],"CachedNonFiniteBlockIOAssignments",buffer)>
  %else
    %% Cache in model initialization
    %assign ::CompiledModel.NonFiniteBlockIOAssignmentsCache = ...
      ::CompiledModel.NonFiniteBlockIOAssignmentsCache + buffer
  %endif
%endfunction
 
%%Function:SLibCacheNonFiniteParamAssignment==================================
%%Abstract:
%%SLibCacheNonFiniteParamAssignmentisusedtocacherun-timeparameter
%%nonfiniteinitialization.Parameterscanbesharedacrosssystemsandare
%%requiredtoinitializenonfinitestheyuseintheirinitializationfunction.
%%Eachcalltothisfunctionappendsyourbuffertotheexistingcachebuffer.
%%
%%Arguments:
%%mdlParam:ModelParamterthathasthenonfiniteinitializationcode
%%buffer:Codebuffertobecached
%%
%function SLibCacheNonFiniteParamAssignment(mdlParam, buffer) void
  %if SIZE(mdlParam.ReferencedBy,0) == 1
    %% Single reference, initialize with standalone subsystem
    %assign sysIdx = mdlParam.OwnerSysIdx[0]
    %% The root system may have an instance index of -1, map it back to 0
    %assign instIdx = (mdlParam.OwnerSysIdx[1] == -1) ? 0 : mdlParam.OwnerSysIdx[1]
    %assign sysIdx = ::CompiledModel.System[sysIdx].StandaloneParentSysIdx[instIdx]
    %if sysIdx != -1
      %<LibAddToSystemField(System[sysIdx],"CachedNonFiniteParamAssignments",buffer)>
      %return
    %endif
  %endif
  %% Cache in model initialization
  %assign ::CompiledModel.NonFiniteParamAssignmentsCache = ...
    ::CompiledModel.NonFiniteParamAssignmentsCache + buffer
%endfunction
 
%%Function:LibDumpNonFiniteAssignmentCache===================================
%%Abstract:
%%LibDumpNonFiniteAssignmentCachedumpsthenon-finiteassignmentscache
%%totheoutputbuffer.
%%
%function LibDumpNonFiniteAssignmentCache() Output
  %% See Also:
  %% LibCacheNonFiniteAssignment
  %%
  %% Dump Standalone subsystem nonfinite assignments
  %foreach sysIdx = NumSystems
    %if System[sysIdx].StandaloneSubsystem
      %assign buffer = LibGetSystemField(System[sysIdx], "CachedNonFiniteParamAssignments") + ...
                       LibGetSystemField(System[sysIdx], "CachedNonFiniteBlockIOAssignments")
 
      %if !WHITE_SPACE(buffer)
        %openfile nonfiniteBuffer
         
        /* non-finite (run-time) assignments */
        %<buffer>
        %closefile nonfiniteBuffer
        %<LibAddToSystemField(System[sysIdx],"CachedInitializeDataBody", ...
          nonfiniteBuffer)>
      %endif
    %endif
  %endforeach
  %% Also dump root model nonfinite assignments, initialize function is called
  %% separately.
  %assign buffer = ::CompiledModel.NonFiniteParamAssignmentsCache + ...
                   ::CompiledModel.NonFiniteBlockIOAssignmentsCache
  %if (!WHITE_SPACE(buffer))
     
    /* non-finite (run-time) assignments */
    %<buffer>
  %endif
%endfunction
 
%%DocFunction{CodeConfigurationFunctions}:LibCacheFunctionPrototype========
%%Abstract:
%%LibCacheFunctionPrototypeshouldbecalledfrominsideBlockTypeSetup
%%tocacheafunctionprototype.Eachcalltothisfunctionappends
%%yourbuffertotheexistingcachebuffer.Theprototypesareplaced
%%insidemodel_private.h
%%
%%Example:
%%%openfilebuffer
%%externint_Tfun1(real_Tx);
%%externreal_Tfun2(real_Ty,int_Ti);
%%%closefilebuffer
%%%<LibCacheFunctionPrototype(buffer)>
%%
%function LibCacheFunctionPrototype(buffer) void
  %if(CGMODEL_ACCESS("CGModel.TLCServerBlockOperationsInCPP"))
    %<LibCacheFunctionPrototypeBuffer(buffer)>
  %else
    %assign ::CompiledModel.FunctionPrototypesCache = ...
      ::CompiledModel.FunctionPrototypesCache + buffer
  %endif
%endfunction
 
%%Function:LibDumpFunctionPrototypesCache====================================
%%Placeanycachedfunctionprototypesintotheoutputstream.
%%
%function LibDumpFunctionPrototypesCache() Output
  %if !WHITE_SPACE(FunctionPrototypesCache)
 
    %<FunctionPrototypesCache>/
  %endif
  %<SLibResetTLCGlobal("FunctionPrototypesCache")>/
%endfunction
 
 
%%DocFunction{CodeConfigurationFunctions}:LibCacheDefine===================
%%Abstract:
%%Eachcalltothisfunctionappendsyourbuffertotheexistingcache
%%buffer.Forblocks,thisfunctionisgenerallycalledfromBlockTypeSetup.
%%
%%ForC,
%%Thisfunctioncaches#definestatementsforinclusionin
%%model_private.h(orinmodel.ciffilepackagingformatissetto
%%compact).
%%
%%LibCacheDefineshouldbecalledfrominsideBlockTypeSetuptocachea
%%#definestatement.Eachcalltothisfunctionappendsyourbufferto
%%theexistingcachebuffer.
%%The#definestatementsareplacedinsidemodel_private.hormodel.c.
%%
%%Example:
%%%openfilebuffer
%%#defineINTERP(x,x1,x2,y1,y2)(y1+((y2-y1)/(x2-x1))*(x-x1))
%%#definethisthat
%%%closefilebuffer
%%%<LibCacheDefine(buffer)>
%%
%%
%function LibCacheDefine(buffer) void
  %assign ::CompiledModel.DefinesCache = ::CompiledModel.DefinesCache + buffer
%endfunction
 
%%Ifwe'reinacodegencontextbuild,we'llthrowawaymodel.handmodel_private.h,
%%Whateverdefineswerecachedtomodelfilesshouldberedirectedtosubsystem.h
%function FcnCacheSFunctionDefinesToRLS(buffer) void
    %if !CGMODEL_ACCESS("CGModel.isCodeGenContextBuild")
        %return
    %endif
    %assign sysIdx = CGMODEL_ACCESS("CGModel.getCUTSysIdx")
    %assign system = ::CompiledModel.System[sysIdx]
    %% Cache the extern decl in subsystem.h
    %<SLibCacheSystemCodeToFile("sys_hdr_incl", system, buffer)>
%endfunction
 
 
%%Function:LibDumpDefinesCache===============================================
%%Abstract:
%%Placeanycacheddefinesintotheoutputstream.
%%
%function LibDumpDefinesCache() Output
  %if !WHITE_SPACE(DefinesCache)
 
    %<DefinesCache>/
  %endif
  %<SLibResetTLCGlobal("DefinesCache")>/
%endfunction
 
%function FcnScanForDuplicateIncludes(incFileName) void
  %assign duplicate = 0
  %foreach idx = ::CompiledModel.NumNonSharedPathHeaders
    %if (::CompiledModel.NonSharedPathHeaders[idx] == incFileName)
      %assign duplicate = 1
      %break
    %endif
  %endforeach
  %foreach idx = ::CompiledModel.NumNonSharedLocalHeaders
    %if (::CompiledModel.NonSharedLocalHeaders[idx] == incFileName)
      %assign duplicate = 1
      %break
    %endif
  %endforeach
  %foreach idx = ::CompiledModel.NumSysPathHeaders
    %if (::CompiledModel.SysPathHeaders[idx] == incFileName)
      %assign duplicate = 1
      %break
    %endif
  %endforeach
  %foreach idx = ::CompiledModel.NumSysLocalHeaders
    %if (::CompiledModel.SysLocalHeaders[idx] == incFileName)
      %assign duplicate = 1
      %break
    %endif
  %endforeach
  %foreach idx = ::CompiledModel.NumBlockPathHeaders
    %if (::CompiledModel.BlockPathHeaders[idx] == incFileName)
      %assign duplicate = 1
      %break
    %endif
  %endforeach
  %foreach idx = ::CompiledModel.NumBlockLocalHeaders
    %if (::CompiledModel.BlockLocalHeaders[idx] == incFileName)
      %assign duplicate = 1
      %break
    %endif
  %endforeach
  %return duplicate
%endfunction
 
 
%%DocFunction{CodeConfigurationFunctions}:LibAddToCommonIncludes==========
%%Abstract:
%%Addsitemstoaunique-ifiedlistof#include/packagespecitems.
%%
%%ShouldbecalledfromblockTLCmethodstospecifygenerationof
%%#includestatementsinmodel.h.Specifylocalsbare,"myinclude.h",
%%andincludepathfilesarespecifiedinbraces,"".Each
%%calltothisfunctionaddsthefiletothelistonlyifitisnotalready
%%there.and"math.h"areconsidereddifferentfilesforthe
%%purposeofuniqueness.The#includestatementsareplacedinside
%%model.h.
%%
%%Example:
%%%<LibAddToCommonIncludes("tpu332lib.h")>
%%
%%
%function LibAddToCommonIncludes(incFileName) void
  %%
  %% ignore empties
  %%
  %if incFileName == ""
    %return
  %endif
   
  %% block may not exist if this is called from any other place other than the BlockTypeSetup
  %% TopTester: test/toolbox/simulink/blocks/sb2sl/tsb2slmdlref.m -testspec:lvlOne_MdlRef
  %if SLibInBlockScope()
    %assign block = SLibGetCurrentBlock()
    %assign blkType = block.Type
    %if block.Type == "S-Function"
       %assign blkType = ParamSettings.FunctionName
    %elseif block.Type == "M-S-Function"
       %assign blkType = ParamSettings.MFile
    %endif
  %endif
   
  %%
  %% scan for duplicates, add if not on any list
  %%
  %assign duplicate = FcnScanForDuplicateIncludes(incFileName)
   
  %if (!duplicate)
    %if incFileName[0] == "<"
      %assign ::CompiledModel.BlockPathHeaders = ...
          ::CompiledModel.BlockPathHeaders + incFileName
      %assign ::CompiledModel.NumBlockPathHeaders = ...
          ::CompiledModel.NumBlockPathHeaders + 1
    %else
      %assign ::CompiledModel.BlockLocalHeaders = ...
          ::CompiledModel.BlockLocalHeaders + incFileName
      %assign ::CompiledModel.NumBlockLocalHeaders = ...
          ::CompiledModel.NumBlockLocalHeaders + 1
    %endif
     
  %endif
    
  %<FcnAddSfuncHeaderToRLSIncludes(incFileName)>/
    
 
%endfunction
 
 
%%Function:FcnAddSfuncHeaderToRLSIncludes==========================================
%%Abstract:
%%IfanRLScontainsanS-function,thisfunctionincludestheS-functions's
%%headertotheRLSheader
%%
%function FcnAddSfuncHeaderToRLSIncludes(incFileName) void
  %if EXISTS(::CurrentSFcnBlockName) && (::CurrentSFcnBlockName != "")
      %assign blockName = ::CurrentSFcnBlockName
      %assign numRLS = CGMODEL_ACCESS("CGModel.getNumRLSFromSfuncMap",blockName)
      %foreach idx = numRLS
          %%Set the module
          %assign sysIdx = CGMODEL_ACCESS("CGModel.getRLSSysIdxFromSfuncMap",blockName, STRING(idx))
          %assign origModuleIdx = ::CurrentModuleIdx
          %assign ::CurrentModuleIdx = System[sysIdx].CGIRModuleIdx
          %% Shared types will cause redundant includes
          %assign containsSharedTypes = ISFIELD(System[sysIdx], "IncludedSharedDataTypes") && ...
                                        FcnAddHeaderHelper(incFileName, System[sysIdx].IncludedSharedDataTypes)
          %if !containsSharedTypes && ::CompiledModel.GenUtilsSrcInSharedLocation == 1
            %<FcnTrackHeaderFileUsage(incFileName,TLC_FALSE, TLC_FALSE)>/
          %endif
          %%Unset the module
          %assign ::CurrentModuleIdx = origModuleIdx
      %endforeach
  %endif
 
  %% If we're in a codegen context build, we need to redirect the #includes
  %% that were intended for model.h and model_private.h to subsystem.h
  %if !CGMODEL_ACCESS("CGModel.isCodeGenContextBuild")
     %return
  %endif
 
  %assign sysIdx = CGMODEL_ACCESS("CGModel.getCUTSysIdx")
  %assign system = ::CompiledModel.System[sysIdx]
  %% Cache the extern decl in subsystem.h
            
  %openfile incFileBuffer
  #include "%<incFileName>"
  %closefile incFileBuffer
  %<SLibCacheSystemCodeToFile("sys_hdr_incl", system, incFileBuffer)>
 
%endfunction
 
%%HelperfunctionforaddSfuncHeaderToRLSIncludes
%function FcnAddHeaderHelper(incFileName, buffer) void
    %foreach idx = SIZE(buffer,1)
        %if buffer[idx] == "/"" + incFileName + "/"" || ...
            buffer[idx] == "<" + incFileName + ">"
            %return TLC_TRUE
        %endif
    %endforeach
    %return TLC_FALSE
%endfunction
 
%%Function:SLibAddToCommonIncludes==========================================
%%Abstract:
%%Addsitemstoaunique-ifiedlistof#include/packagespecitems.
%%
%%Shouldbecalledfromnon-blockTLCmethodstospecifygenerationof
%%#includestatements.Localincludesarespecifiedbare,"myinclude.h",
%%andincludepathfilesarespecifiedinbraces,"".Each
%%calltothisfunctionaddsthefiletothelistonlyifitisnotalready
%%there.and"math.h"areconsidereddifferentfilesforthe
%%purposeofuniqueness.The#includestatementsareplacedinside
%%model.h.
%%
%%This"S"versionofaddingtocommonincludesaddstheincludefile
%%aboveallofthefilesaddedbyLibAddToCommonIncludes,butbelowany
%%filenamesalreadyaddedbythisfunction.
%%
%%Example:
%%%<SLibAddToCommonIncludes("")>
%%
%%
%function SLibAddToCommonIncludes(incFileName) void
  %%
  %% ignore empties
  %%
  %if incFileName == ""
    %return
  %endif
  %%
  %% scan for duplicates, add if not on any list
  %%
  %assign duplicate = FcnScanForDuplicateIncludes(incFileName)
  %if (!duplicate)
    %if incFileName[0] == "<"
      %assign ::CompiledModel.SysPathHeaders = ...
          ::CompiledModel.SysPathHeaders + incFileName
      %assign ::CompiledModel.NumSysPathHeaders = ...
          ::CompiledModel.NumSysPathHeaders + 1
    %else
      %assign ::CompiledModel.SysLocalHeaders = ...
          ::CompiledModel.SysLocalHeaders + incFileName
      %assign ::CompiledModel.NumSysLocalHeaders = ...
          ::CompiledModel.NumSysLocalHeaders + 1
    %endif
  %endif
%endfunction
 
%%Function:SLibAddToNonSharedIncludes===================================
%%Abstract:
%%ThisfunctionislikeSLibAddToCommonIncludes,butfilesaddedwith
%%thisfunctionwillnotbeincludedinfunctionsfromsubsystemsthat
%%arereusedacrossmodelbuilds.
%%
%%Example:
%%%<SLibAddToNonSharedIncludes("")>
%%
%%
%function SLibAddToNonSharedIncludes(incFileName) void
  %%
  %% ignore empties
  %%
  %if incFileName == ""
    %return
  %endif
  %%
  %% scan for duplicates, add if not on any list
  %%
  %assign duplicate = FcnScanForDuplicateIncludes(incFileName)
  %if (!duplicate)
    %if incFileName[0] == "<"
      %assign ::CompiledModel.NonSharedPathHeaders = ...
          ::CompiledModel.NonSharedPathHeaders + incFileName
      %assign ::CompiledModel.NumNonSharedPathHeaders = ...
          ::CompiledModel.NumNonSharedPathHeaders + 1
    %else
      %assign ::CompiledModel.NonSharedLocalHeaders = ...
          ::CompiledModel.NonSharedLocalHeaders + incFileName
      %assign ::CompiledModel.NumNonSharedLocalHeaders = ...
          ::CompiledModel.NumNonSharedLocalHeaders + 1
    %endif
  %endif
%endfunction
 
 
%%Function:SLibDumpCommonIncludes============================================
%%Abstract:
%%Callthisfunctiononcefromwithinatarget's___hdr.tlcfile
%%togeneratetheaccumulatedincludesspecifiedbythetarget,the
%%codeformat,andalltheblocks.
%%
%function SLibDumpCommonIncludes(system) void
  %assign isSFcn = (CodeFormat == "S-Function")
  %assign inclBuff = ""
  %assign isRLS = LibSystemIsReusedLibraryFcn(system)
  %if isRLS
    %return
  %else
    %assign ifndefName = Name
  %endif
  %openfile inclBuff
  %if !CGMODEL_ACCESS("CGModel.RemoveCommonIncludesGuards")
    #ifndef %<ifndefName>_COMMON_INCLUDES_
    # define %<ifndefName>_COMMON_INCLUDES_
  %endif
  %foreach idx = ::CompiledModel.NumSysPathHeaders
    %assign incFileName = ::CompiledModel.SysPathHeaders[idx]
    #include %<incFileName>
  %endforeach
  %foreach idx = ::CompiledModel.NumNonSharedPathHeaders
    %assign incFileName = ::CompiledModel.NonSharedPathHeaders[idx]
    #include %<incFileName>
  %endforeach
  %foreach idx = ::CompiledModel.NumBlockPathHeaders
    %assign incFileName = ::CompiledModel.BlockPathHeaders[idx]
    #include %<incFileName>
  %endforeach
  %if isSFcn
    %<LibSFcnPreSimstrucDefines(system)>
  %endif
  %foreach idx = ::CompiledModel.NumSysLocalHeaders
    %assign incFileName = ::CompiledModel.SysLocalHeaders[idx]
    #include %<"/"%<incFileName>/"">
  %endforeach
  %if ISEQUAL(::ConfigSet.InferredTypesCompatibility, TLC_TRUE)
    %% && !ISEQUAL(::ConfigSet.SupportNonInlinedSFcns, TLC_TRUE)
    #define __TMWTYPES__ /* Inferred types compatibility mode */
  %endif
  %foreach idx = ::CompiledModel.NumNonSharedLocalHeaders
    %assign incFileName = ::CompiledModel.NonSharedLocalHeaders[idx]
    #include %<"/"%<incFileName>/"">
  %endforeach
  %foreach idx = ::CompiledModel.NumBlockLocalHeaders
    %assign incFileName = ::CompiledModel.BlockLocalHeaders[idx]
    %assign fileVarCond = CGMODEL_ACCESS("FileRepository.getFileVariantCondition",incFileName)
    %if !ISEMPTY(fileVarCond)
        %
    %endif
     
    #include %<"/"%<incFileName>/"">
 
    %if !ISEMPTY(fileVarCond)
        %
    %endif
 
  %endforeach
  %if isSFcn
    %<LibSFcnPostSimstrucDefines()>
  %endif
  %if !CGMODEL_ACCESS("CGModel.RemoveCommonIncludesGuards")
    #endif /* %<ifndefName>_COMMON_INCLUDES_ */
  %endif
   
  %closefile inclBuff
  %return inclBuff
%endfunction
 
 
%%DocFunction{CodeConfigurationFunctions}:LibCacheIncludes=================
%%Abstract:
%%LibCacheIncludesshouldbecalledfrominsideBlockTypeSetuptocache
%%#includestatements.Eachcalltothisfunctionappendsyourbufferto
%%theexistingcachebuffer.The#includestatementsareplacedinside
%%model_private.h.
%%
%%Example:
%%%openfilebuffer
%%#include"myfile.h"
%%%closefilebuffer
%%%<LibCacheIncludes(buffer)>
%%
%%
%function LibCacheIncludes(buffer) void
  %assign ::CompiledModel.IncludesCache = ...
    ::CompiledModel.IncludesCache + buffer
%endfunction
 
 
%%Function:LibDumpIncludesCache==============================================
%%Abstract:
%%Placeanycachedincludesintotheoutputstream.
%%
%function LibDumpIncludesCache() Output
  %if !WHITE_SPACE(IncludesCache)
 
    %<IncludesCache>/
  %endif
  %<SLibResetTLCGlobal("IncludesCache")>/
%endfunction
 
 
%%DocFunction{CodeConfigurationFunctions}:LibCacheTypedefs=================
%%Abstract:
%%LibCacheTypedefsshouldbecalledfrominsideBlockTypeSetuptocache
%%typedefdeclarations.Eachcalltothisfunctionappendsyourbuffer
%%totheexistingcachebuffer.Thetypedefstatementsareplaced
%%insidemodel.h.
%%
%%Example:
%%%openfilebuffer
%%typedeffoobar;
%%%closefilebuffer
%%%<LibCacheTypedefs(buffer)>
%%
%function LibCacheTypedefs(buffer) void
  %assign ::CompiledModel.TypedefsCache = ...
    ::CompiledModel.TypedefsCache + buffer
%endfunction
 
 
%%Function:LibDumpTypedefsCache==============================================
%%Abstract:
%%Placeanycachedtypedefsintotheoutputstream.
%%
%function LibDumpTypedefsCache() void
  %if !WHITE_SPACE(TypedefsCache)
    %return "/n%<TypedefsCache>"
  %else
    %return ""
  %endif
%endfunction
 
 
%%DocFunction{CodeConfigurationFunctions}:LibCacheExtern===================
%%Abstract:
%%LibCacheExternshouldbecalledfrominsideBlockTypeSetuptocachean
%%externstatement.Eachcalltothisfunctionappendsyourbufferto
%%theexistingcachebuffer.Theexternstatementsareplacedin
%%model_private.h.
%%
%%ACexample:
%%%openfilebuffer
%%externreal_Tmydata;
%%%closefilebuffer
%%%<LibCacheExtern(buffer)>
%%
%function LibCacheExtern(buffer) void
  %assign ::CompiledModel.ExternsCache = ::CompiledModel.ExternsCache + buffer
  %<FcnCacheSFunctionExternDeclToRLS(buffer)>;
%endfunction
 
%%Ifwe'reinacodegencontextbuild,weneedtoredirectallexterndecl
%%thatwereintendedformodel.handmodel_private.htosubsystem.h
%function FcnCacheSFunctionExternDeclToRLS(buffer) void
     %if !CGMODEL_ACCESS("CGModel.isCodeGenContextBuild")
        %return
     %endif
 
    %assign sysIdx = CGMODEL_ACCESS("CGModel.getCUTSysIdx")
    %assign system = ::CompiledModel.System[sysIdx]
    %% Cache the extern decl in subsystem.h
    %<SLibCacheSystemCodeToFile("sys_standalone_extern_data_decl", system, buffer)>
%endfunction
 
%%Function:LibDumpExternsCache===============================================
%%Abstract:
%%Placeanycachedexternsintotheoutputstream.
%%
%function LibDumpExternsCache() Output
  %if !WHITE_SPACE(ExternsCache)
 
    %<ExternsCache>/
  %endif
  %<SLibResetTLCGlobal("ExternsCache")>/
%endfunction
 
%%Function:SLibCacheSourceCode===============================================
%%Abstract:
%%ThisfunctionshouldbecalledfrominsideBlockInstanceSetuptocache
%%sourcecodeatthetopofmodel.c.Thebufferisaddedtotheexisting
%%cachebuffer.
%%
%%Example:
%%%openfilebuffer
%%voidmyfunc(inti){
%%i++;
%%}
%%%closefilebuffer
%%%<SLibCacheSourceCode(buffer)>
%%
%function SLibCacheSourceCode(buffer) void
  %assign ::CompiledModel.SourceCodeCache = ...
    ::CompiledModel.SourceCodeCache + buffer
%endfunction
 
%%Function:SLibDumpSourceCodeCache==========================================
%%Abstract:
%%DumpanysourcecodethatwascachedwitheitherSLibCacheSourceCode()
%%orLibAddToFile().
%%
%function SLibDumpSourceCodeCache() Output
  %% Dump any source code from SLibCacheSourceCode
  %if !WHITE_SPACE(SourceCodeCache)
 
    %<SourceCodeCache>/
  %endif
  %<SLibResetTLCGlobal("SourceCodeCache")>/
  %% Create(dump) any files from LibAddtoFiles
  %foreach idx = ::CompiledModel.NumFiles
    %openfile file = ::CompiledModel.Files.Name[idx]
    %<::CompiledModel.Files.File[idx]>
    %closefile file
    %<SLibAddGeneratedFileToList(::CompiledModel.Files.Name[idx] ,"other","other","")>
    %if ResetTLCGlobalsAfterUse
      %assign ::CompiledModel.Files.File[idx] = 0
    %endif
  %endforeach
%endfunction
 
%%Function:LibCacheGlobalPrmData=============================================
%%Abstract:
%%LibCacheGlobalPrmDatashouldbecalledfrominsideBlockInstanceSetup
%%tocacheglobalblockparameterdata.Eachcalltothisfunction
%%appendsyourbuffertotheexistingcachebuffer.Theglobaldata
%%isplacedinsidemodel.c.Notethatonlyfunctionsinmodel.cwill
%%beabletoseethisdata.Forotherfiles(iesubsystemfiles)tosee
%%thisdata,youmustexternitinthemodel_private.hfile.
%%
%%Example:
%%%openfilebuffer
%%real_TA[]={1.0,0.0,0.0};
%%%closefilebuffer
%%%<LibCacheGlobalPrmData(buffer)>
%%
%function LibCacheGlobalPrmData(buffer) void
  %if UsingMalloc
 
    %openfile errTxt
Attempting to declare global parameter data using TLC function
LibCacheGlobalPrmData.
 
Declaring global parameter data is not consistent with dynamic ...
memory allocation. Perhaps you should create the data in the ...
block's start function.
 
For example, assume a block requires constant and non-constant ...
data. The block creates the data in the start function and stores ...
the location of the data in its PWork. References to the data ...
outside the start function are realized via the block PWork.
 
%<"%function Start(block, system) Output">
  /* initialize data (containing non-finites) */
  {
    static real_T nonFiniteData[] = { 1.0, 0.0, 27.2, 0.0 };
 
    nonFiniteData[1] = %<"%<LibRealNonFinite(inf)>">;
    nonFiniteData[3] = %<"%<LibRealNonFinite(nan)>">;
 
    %<"%<LibBlockPWork(ConstNonFiniteData,"","",0)> = ">
      &nonFiniteData[0];
  }
 
  /* initialize data (all finite) */
  {
    static const real_T finiteData[] = { 1.0, 12.0, 27.2, 45.0 };
    %<"%<LibBlockPWork(ConstFiniteData,"","",0)> =">
      &finiteData[0];
  }
 
  /* allocate memory for non-constant data */
  {
    SomeDataType *data;
    data = (SomeDataType *) malloc(sizeof(SomeDataType));
    VALIDATE_MEMORY(%<"%<RTMGetModelSS()>">, data);
    %<"%<LibBlockPWork(NonConstData,"","",0)> = data;">
  }
%<"%endfunction">
 
Note that static data is only declared with the "const" keyword if ...
the data does not contain non-finites since rtInf, rtMinusInf, and ...
rtNaN are not initialized until run time.
 
Also note that the TLC references ConstNonFiniteData, ConstFiniteData, ...
and NonConstData are made possible with either the TLC function ...
LibDefinePWork or with the S-function's mdlRTW function.
    %closefile errTxt
    %<SLibReportErrorWithId("RTW:tlc:GenericMsg", errTxt)>
  %endif
 
 
  %assign ::CompiledModel.GlobalPrmDataCache = ...
    ::CompiledModel.GlobalPrmDataCache + buffer
%endfunction
 
%%Function:LibDumpGlobalPrmDataCache=========================================
%%Abstract:
%%Placeanycachedglobalparameterdataintotheoutputstream.
%%
%function LibDumpGlobalPrmDataCache() Output
  %if !WHITE_SPACE(GlobalPrmDataCache)
 
    %<GlobalPrmDataCache>/
  %endif
  %<SLibResetTLCGlobal("GlobalPrmDataCache")>/
%endfunction
 
 
%%Function:SLibCacheIntegerOnlyWarning=======================================
%%Abstract:
%%ThisfunctioniscalledbytheLibBlock*routinestocacheanyuseof
%%non-integerdataintheblockinputs/outputs,parameters,states
%%orworkvectors.
%%
%%Arguments:
%%name:Nameoftheblock
%%component:Stringdescribingthepartoftheblockthatis
%%declaringanon-integer.
%%
%function SLibCacheIntegerOnlyWarning(name,component) void
  %assign foundBlock = 0
  %foreach idx = IntegerOnlyWarningCache.NumBlocks
    %if IntegerOnlyWarningCache.Block[idx].Name == name
      %assign foundBlock = 1
      %assign result = FEVAL("findstr", ...
        ::CompiledModel.IntegerOnlyWarningCache.Block[idx].Component, component)
      %if !SIZE(result,0)
        %assign ::CompiledModel.IntegerOnlyWarningCache.Block[idx].Component = ...
          IntegerOnlyWarningCache.Block[idx].Component + " %<component>"
      %endif
      %break
    %endif
  %endforeach
 
  %if !foundBlock
    %assign tmpVar = Block/
    {/
    Name name;/
    Component component/
    }
    %assign ::CompiledModel.IntegerOnlyWarningCache = ...
      IntegerOnlyWarningCache + Block
    %undef tmpVar
    %assign ::CompiledModel.IntegerOnlyWarningCache.NumBlocks = ...
      IntegerOnlyWarningCache.NumBlocks + 1
  %endif
%endfunction
 
 
%%Function:SLibDumpIntegerOnlyWarning========================================
%%Abstract:
%%Thisfunctiondumpsanywarningsoffloat-pointdatathatwere
%%cachedusingSLibCacheIntegerOnlyWarning.
%%
%function SLibDumpIntegerOnlyWarning() void
  %if IntegerOnlyWarningCache.NumBlocks > 0
    %openfile warnTxt
 
The following blocks contain non-integer data but the Integer Code Only
option is selected. You should replace/correct the blocks or uncheck
Integer Code Only via the Code Generation Options dialog.
 
      %if IntegerOnlyWarningCache.NumBlocks > 25
        %assign loop = 20
Total of %<IntegerOnlyWarningCache.NumBlocks> Blocks, only listing first 20.
      %else
        %assign loop = IntegerOnlyWarningCache.NumBlocks
      %endif
Block (details) :
 
      %foreach idx = loop
% ...
(%)
      %endforeach
    %closefile warnTxt
    %selectfile STDOUT
%<warnTxt>
    %selectfile NULL_FILE
    %<SLibReportWarningWithIdAndArgs("RTW:tlc:GenericWarn", warnTxt)>
  %endif
%endfunction
 
%%Function:LibGetFieldSet========================================
%%Abstract:
%%Wehaveplacesinthecodewhereweassertthatafieldexistsor
%%doesn'texisttoensureanotherutilityfunctionhasbeencalled.
%%Thisfunctionisintendedtogivethatsamefunctionalitywhen
%%defaultvaluesexist,thusrenderingISFIELDuseless.
%%
%function LibGetFieldSet(scope, fieldName) void
  %if ConfigSet.TLCAssert
    %return ISFIELD(scope, "FieldSet" + fieldName)
  %else
    %return 1
  %endif
%endfunction
 
%%Function:LibGetFieldSet========================================
%%Abstract:
%%SeeLibGetFieldSet
%%
%function LibSetFieldSet(scope, fieldName) void
  %if ConfigSet.TLCAssert
    %if !ISFIELD(scope, "FieldSet" + fieldName)
      %addtorecord scope FieldSet%<fieldName> 1
    %endif
  %endif
%endfunction
 
%endif %% _CACHELIB_
 
%%[EOF]cachelib.tlc