// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#pragma once

// Code to compute the number of instances of each function
// flat non-inline functions have 1 instance
// non-inline methods have 1 instance per object of the containing class
// inline functions have 1 instance per call site
//
// static local variables (of class type) result in 1 object per instance of the containing function

struct CompiledModule;

// Describes a function call in the AST
struct UnresolvedCall
{
    // The called function name
    std::string _calledFunctionName;

    // Scope that was prepended to the function name
    Scope _explicitScope;

    // Object name that was explicitly specified in the call (can be null)
    const ParseTreeNode* _explicitObject;

    // The class that contains the call
    const ClassType* _callSiteClassType;

    // The namespace/module that contains the call
    Scope _callSiteScope;

    // The name of the object that contains the call
    // Can be empty during type checking
    std::string _callSiteObjectName;

    // Callback to resolve object references
    ResolveReferenceFunction _resolveReferenceCallback;
};

// Information about a specific call without reference to any objects or function instances
struct ResolvedCall
{
    // The name of the function that is called
    std::string _functionName;

    // The node in the AST corresponding to the called function
    // Can be nullptr if there is no corresponding node in the AST
    const FunctionNode* _functionNode;

    // Types that describe function signature
    FunctionDesc _functionDesc;

    // For flat functions, the namespaces that the function is declared in
    Scope _flatFunctionScope;

    // The type of the class that contains the called function
    // Set to the global class for flat functions
    const ClassType* _calledClassType;

    // True if the call is done via an object reference
    bool _callByReference;

    // True if this is a call to an exported class
    bool _callToExportClass;

    // Object name that was explicitly specified in the call
    // Can either be a node, or an object name string
    // or neither
    const ParseTreeNode* _explicitObjectNode;

    boost::optional<std::string> _explicitObjectName;
};

ResolvedCall ResolveFunctionCallForTypeChecking(const CallNode* const callNode,
                                                const ClassType* const callSiteClassType, const Scope& callSiteScope);

ResolvedCall ResolveFunctionCallPostTypeChecking(const CallNode* const callNode,
                                                 const ClassType* const callSiteClassType, const Scope& callSiteScope,
                                                 const std::string& callSiteObjectName,
                                                 const ResolveReferenceFunction resolveReferenceCallback);

ResolvedCall ResolveFunctionCall(const UnresolvedCall& unresolvedCall, const Location& callSiteLocation,
                                 const bool resolveFunctionNode);

ResolvedCall ResolveFlatFunctionCall(const std::string& functionName, const Scope& functionScope,
                                     const Scope& callSiteScope, const Location& location);

ResolvedCall ResolveFlatFunctionCall(const ScopedIdentifierNode* const calledIdentifier, const Scope& callSiteScope);

class FunctionInstanceEnumerator
{
  public:
    struct CalledInstanceDesc
    {
        // For member functions, this is "namespace::object"
        // For flat functions, this is "namespace"
        std::string _prefix;

        // Instance describing the called function
        FunctionInstance _calleeInstance;
    };

    using InstanceAndLocation = std::pair<FunctionInstance, Location>;

  private:
    // Current state of parse tree traversal
    struct Context
    {
        VisitContext _visitContext;
        Scope _namespaceScope;
        std::stack<const ClassType*> _classTypeStack;
    };

    // Maps function parameter name to name of the referenced object
    typedef std::map<std::string, std::string> ParameterReferenceMap;

    // For a function instance: Name of containing object + parameter references
    typedef std::pair<std::string, ParameterReferenceMap> ObjectNameAndParameterReferences;

    // Counts number of instances for inline functions
    typedef std::map<const FunctionNode*, Context> PerFunctionSymbolTable;
    std::map<const FunctionNode*, size_t> _inlineFunctionInstanceCountMap;

    // Contains non-inline instances (indexed by functionNode & object name)
    typedef std::map<ObjectNameAndParameterReferences, size_t> ObjectToInstanceMap;
    std::map<const FunctionNode*, ObjectToInstanceMap> _nonInlineInstanceMap;

    // Contains all instances (indexed by function node)
    std::map<const FunctionNode*, std::list<FunctionInstance>> _allInstanceMap;

    // Counts number of call sites for each function instance
    // Used for auto-inlining
    std::map<FunctionInstance, size_t> _instanceCallCountMap;

    // Tracks called functionNodes that do not support auto-inlining
    // based on their attributes
    std::set<const FunctionNode*> _disallowAutoInlineSet;

    // Maps caller function instance to a description of the called function
    typedef std::map<FunctionInstance, std::list<CalledInstanceDesc>> CalledInstanceDescriptionListMap;
    std::map<const CallNode*, CalledInstanceDescriptionListMap> _callMap;

    // Maps called function instance to calling function instances
    std::map<FunctionInstance, std::set<InstanceAndLocation>> _calleeToCaller;

    // For static local objects, maps (FunctionInstance, DeclareNode) to a unique identifier for the object
    typedef std::map<FunctionInstance, size_t> StaticLocalMap;
    std::map<const DeclareNode*, StaticLocalMap> _staticLocals;

    // Used to give each static local object a unique id
    size_t _staticLocalObjectCount;

    // Unique ID used to differentiate functions passed on parameter references
    size_t _referenceObjectNameSeqNumber;

    // The set of non-inline, unreachable function instances
    std::set<FunctionInstance> _reachableFunctionInstances;

    // The set of functions called by extern class callbacks
    std::set<FunctionInstance> _externClassCallbackCallees;

    // Used for binary operations that are implemented as a call to an inline library function
    // Maps binary operation node to the list of instances associated with the called function
    std::map<const BinaryOpNode*, std::list<FunctionInstance>> _binaryOperationCalls;

    // Used for array accesses into ecc memories
    // Maps array access node to the list of instances associated with the called function
    std::map<const ArrayAccessNode*, std::list<FunctionInstance>> _eccMemoryCalls;

    std::map<FunctionInstance, ParameterReferenceMap> _parameterReferences;

    // Maps (caller function instance, call node) -> parameter references for a particular call
    std::map<std::pair<FunctionInstance, const CallNode*>, ParameterReferenceMap> _parameterReferencesAtCallSites;

    // Maps VariableAccessNode (containing a reference) to the name of the referenced object
    typedef std::map<const VariableAccessNode*, std::string> VariableAccessTable;
    std::map<FunctionInstance, VariableAccessTable> _variableAccessTables;

    // Traverse the parse tree, capture the symbol table at each function
    PerFunctionSymbolTable TraverseParseTree(const ParseTreeNode* root);

    void EvaluateCallbacks(const ParseTreeNode* const root, PerFunctionSymbolTable& perFunctionSymbolTable,
                           const std::function<void(const FunctionInstance&)>& addToWorkList);

    FunctionInstance GetCalledInstance(const CallNode* const callNode, Context& context,
                                       const FunctionInstance& callSiteInstance,
                                       const ClassType* const callSiteClassType, const Scope& callSiteScope,
                                       const ResolveReferenceFunction& resolveReferenceCallback);

    size_t GetInlineInstanceIndex(const FunctionNode* const functionNode);

    void RegisterExportClassInstance(const std::string& objectName, const ClassNode* const classNode,
                                     const ClassCallableFunctionMap& classCallableFunctionMap,
                                     const std::function<void(const FunctionInstance&)>& addToWorkList,
                                     PerFunctionSymbolTable& perFunctionSymbolTable);

    void RegisterObject(const std::string& objectName, const ClassNode* const classNode,
                        const ClassCallableFunctionMap& classCallableFunctionMap,
                        PerFunctionSymbolTable& perFunctionSymbolTable,
                        const std::function<void(const FunctionInstance&)>& addToWorkList);

    size_t GetOrAllocateInstanceIndex(ObjectToInstanceMap& objectToInstanceMap,
                                      const ObjectNameAndParameterReferences& objectNameAndParameterReferences);

    // Maps function parameter index to compile-time known value & type
    // the type is the parameter (function declaration) type not the argument (call site) type
    using ParameterIndexToKnownValue = std::map<size_t, VisitContextPerVariableData>;

    // Maps function instance (explict inline functions only) to parameter values
    std::map<FunctionInstance, ParameterIndexToKnownValue> _inlineParameterValueMap;

    std::map<const ClassType*, std::set<const FunctionNode*>> _classTypeToMethods;
    // Used to dereference callbacks
    struct CallbackDesc
    {
        const ClassType* _classType;
        std::string _objectName;
        std::string _memberName;

        bool operator<(const CallbackDesc& rhs) const
        {
            return std::tie(_classType, _objectName, _memberName) <
                   std::tie(rhs._classType, rhs._objectName, rhs._memberName);
        }
    };

    // Maps object to list of callable methods or callbacks
    std::map<std::string, ClassCallableFunctionMap> _objectToCallableFunctions;

    const CompiledModule& _moduleToCompile;

    const bool _isCompilingToVerilog;

    // Maps (call node, call site function instance) to called object name
    using CallSite = std::pair<const CallNode*, FunctionInstance>;
    std::map<CallSite, std::list<std::string>> _callSiteToCalledObjectName;

    // The function instance currently being enumerated
    std::optional<FunctionInstance> _currentInstance;

  public:
    FunctionInstanceEnumerator(const CompiledModule& moduleToCompile, const bool isCompilingToVerilog);

    void FindUnreachableFunctions();

    void Enumerate(const ParseTreeNode* const root);

    std::vector<std::string> GetObjectNamesForFunction(const FunctionNode* const node) const;

    bool IsInlineable(const FunctionInstance& functionInstance, const size_t minimumCallCount) const;

    CalledInstanceDesc LookupCall(const CallNode* const callNode, const FunctionInstance& callerInstance);

    size_t LookupStaticLocalObjectIndex(const DeclareNode* const declareNode,
                                        const FunctionInstance& containingInstance) const;

    std::list<size_t> GetAllStaticLocalIndices(const DeclareNode* const declareNode) const;

    std::list<FunctionInstance> LookupMethodInstances(const FunctionNode* const functionNode,
                                                      const std::string& objectName) const;

    bool IsInstanceReachable(const FunctionInstance& instance) const;

    std::string GetReferencedObject(const VariableAccessNode* variableAccessNode,
                                    const FunctionInstance& instance) const;

    FunctionInstance LookupBinaryOpCall(const BinaryOpNode* const node);

    FunctionInstance LookupEccMemoryCall(const ArrayAccessNode* const node);

    size_t GetFunctionCallCount(const FunctionNode* const node, const std::string& objectName) const;

    UnresolvedCall DereferenceCallback(const ClassType* callSiteClassType, const std::string& callSiteObjectName,
                                       const std::string& callbackName, const Location& callSiteLocation) const;

    FunctionInstance DereferenceExternalClassCallback(const ClassType* classType,
                                                      const std::string& externClassObjectName,
                                                      const std::string& callbackName, const Location& location) const;

    std::string DereferenceParameter(const FunctionInstance& callerInstance, const CallNode* const callNode,
                                     const std::string& paramName);

    std::string GetCalledObjectName(const CallNode* const callNode, const FunctionInstance& callerInstance);

    bool GenerateCurrentEnumerateFunctionCallTrace(std::ostream& str);

    const std::set<FunctionInstance> GetExternalClassInstanceCallees() const;

    std::optional<InstanceAndLocation> GetCaller(const FunctionInstance& inst) const;
};

void GenerateCallTrace(std::ostream& str, const FunctionInstance& srcInst);


// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#pragma once

#ifdef __cplusplus
extern "C"
{
#endif

    enum VerbosityLevel
    {
        Quiet,
        Normal,
        Verbose
    };

    typedef unsigned BOOL;

    typedef struct
    {
        // The number of iterations to run for
        size_t _numIterations;

        // Random number seed
        size_t _seed;

        // Coefficient of linear force that pulls connected nodes together
        float _pullStrength;

        // Coefficient of inverse square force that pushes nodes away from others
        float _pushStrength;

        // Coefficient of inverse cube force that pushes nodes away from walls
        float _wallStrength;

        // Maximum length of gradient vectors
        float _updateRate;

        // True to animate the placement process
        BOOL _display;
    } PlacementOptions;

    typedef struct
    {
        // True to ensure that generated code runs in the same order as the source code
        // For debugging
        BOOL _debug;

        // True to generate DebugSymbols with stripped file names
        BOOL _stripDebugSymbols;

        // Optimization level
        size_t _optimize;

        // True to add assertions to the IR to verify that narrowing conversions do not lose data
        BOOL _assertNarrowingConversion;

        // True to dump IR before/after optimization
        BOOL _dumpIR;

        // True to dump IR after each optimization step
        BOOL _dumpOpt;

        // True to dump IR to json after all optimizations
        BOOL _serializeIRPostOpt;

        // True to dump IR to json after all optimizations
        BOOL _serializeCIRCTIR;

        // true to generate hardware to detect race conditions
        BOOL _detectRaces;

        // true to generate hardware to inspect control state
        BOOL _controlInspection;

        // true to generate hardware to inspect
        BOOL _inspection;

        // true to enable assertions on release builds of the compiler
        BOOL _releaseAssert;

        // true to allow fifos to stutter when they are almost empty (to improve timing)
        BOOL _allowFifoStutter;

        // true to generate pipelines where individual stages may be stalled (to reduce area)
        BOOL _stallablePipelines;

        // Level of clock gating to apply (0 disables, 1 is per-stage, 2 is full clock gating)
        size_t _clockGatingLevel;

        // Only instantiate a clock gate if it applies to at more than this many register bits
        size_t _clockGatingThreshold;

        // For memory reads that are conditional, try and make the memory read enable signal conditional as well.
        // This can lower power consumption, but in some cases may negatively impact the maximum clock frequency.
        BOOL _conditionalMemoryReads;

        // Controls the number of pipeline registers inserted in the path of the input signals that drive the semaphore
        // module used to limit threads within a pipeline. This is a trade off between clock frequency and power
        // consumption (lower values mean less extra registers and hence less power and less area).
        size_t _semaphoreDelay;

        // true to generate hardware for code coverage
        BOOL _codeCoverage;

        // If code coverage is enabled, only generate code coverage hardware for muxes with less than this number of
        // cases A value of 0 means no limit.
        size_t _codeCoverageMuxThreshold;

        // true to generate metadata files for memories and fifos
        BOOL _dumpMemoryMetadata;

        // Maximum number of each RAM resource allowed
        size_t _maxBlockRam;
        size_t _maxDeepRam;

        // Minimum utilization of RAM resources
        // 0 means 0%, 100 means 100%
        size_t _minBlockRamUtilization;
        size_t _minDeepRamUtilization;

        // Decompose mux with more than this many inputs
        size_t _maxSelectInputs;

        // Decompose multiplication operations with operands wider than this
        size_t _maxMulSrcWidth;

        // Max thread count for functions when max count is not specified
        size_t _maxThreadsDefault;

        // Max thread count for any function (compilation fails if a function could have a thread count greater than
        // this)
        size_t _maxThreadsLimit;

        // Limit on the count of instructions to be scheduled
        size_t _scheduleLimit;

        // Extra latency added to to ease routing
        size_t _additionalLatency;

        // Additional clock cycles to add to the reset sequence
        // Hyper-retiming can require additional cycles be added
        size_t _additionalResetCycles;

        // A maximum number of additional pipeline registers that can be added to function entry points.
        // On platforms that support it, the synthesis tool is allowed to choose the number of registers.
        // On platforms a fixed number of registers will be used.
        //    0 means no auto-pipelining
        //    2 means that each register can be turned into 2 if necessary
        size_t _autoPipelineScale;

        // A maximum number of additional pipeline registers that can be added to cross-region function entry points.
        // On platforms that support it, the synthesis tool is allowed to choose the number of registers.
        // On platforms a fixed number of registers will be used.
        //    0 means no auto-pipelining
        //    2 means that each register can be turned into 2 if necessary
        size_t _autoPipelineCrossRegion;

        // 1 causes pipeline registers to be inserted after each level of combinational logic
        // 4 causes pipeline registers to be inserted after every 4 levels of combinational logic
        size_t _logicRegisterRatio;

        // Atomic blocks can relax scheduling up to this register ratio
        size_t _maxLogicRegisterRatio;

        // Number of cycles to propagate the reset signal
        size_t _resetCycles;

        // Subset of _resetCycles to spend in a fan-out tree
        size_t _resetFanOutCycles;

        // Number of cycles to add to fifo writes
        size_t _fifoWriteDelay;

        // Max distance between enqueue operations when merging fifos during local data propagation
        size_t _fifoMergeDistance;

        // The number of output bits in a carry-chain operation (add/sub) that is considered to be 1 level of logic
        size_t _carryChainWidthPerLogicLevel;

        // Write delay to add to memories that are accessed via read-modify-write
        size_t _rmwMemoryWriteDelay;

        // Read delay to add to memories that are accessed via read-modify-write
        size_t _rmwMemoryReadDelay;

        // Write delay to add to memories that are accessed via read-modify-write
        // In cases where hardened read-modify-write logic can be used
        size_t _rmwHardenedMemoryWriteDelay;

        // In cases where hardened BRAM read-modify-write logic could be used,
        // don't use the hardened logic when the width is > _rmwHardenedMemoryMaxWidth
        // AND height is <= _rmwHardenedMemoryMaxHeight to lessen
        // BRAM requirement/underutilization.
        size_t _rmwHardenedMemoryMaxWidth;
        size_t _rmwHardenedMemoryMaxHeight;

        // Optimize read-modify-write memory access within atomic block for area.
        // By default optimize for Fmax.
        BOOL _rmwMemoryFavorArea;

        // Require that if a memory read and write (access the same address) occur
        // at the same time, that the read will see the old data
        // If FALSE, then let the synthesis tool decide
        BOOL _strictMemoryReadWrite;

        // Delay to account for routing data to/from DSP/BRAM input/output registers (measured in levels of logic)
        size_t _inputOutputRegisterDelay;

        // Threshold for moving variables from registers into memories
        // Measured in memory bits per register bit
        // A value of 0 means variables should always stay in registers
        // A value of N means that a single register should be moved to a memory if
        // the number of memory bits is < N
        float _memToRegThreshold;

        // Threshold for replacing local data propagation FIFO with DSP
        // Measured in number of pipeline stages that FIFO replaces
        // A value of N means that FIFOs for number of pipeline stages <= N should
        // be replaced with DSPs
        size_t _fifoToDspThreshold;

        size_t _verbosity;

        // For limiting string length in generated code
        size_t _maxStringLength;

        // Randomly force each basic block to stall
        size_t _stall;

        // Convert all memories to arrays (ignoring area costs)
        size_t _forceMemToArray;

        // Don't emit debug view - currently used for code coverage tests
        BOOL _suppressDebugView;

        // Maximum optimizer work list size
        // defaults to 0
        size_t _logWorkListSize;

        // Extra pipeline stages to add functions with multiple return sites
        size_t _returnStages;

        // Maximum depth of call stack to write into generated RTL
        size_t _maxStackDepth;

        // The reset fanout is enabled
        BOOL _resetFanout;

        // Remove unnecessary/constant bits from registers
        BOOL _sparseRegOpt;

        // Reduce pipeline length with replicated hardware that performs speculative computations
        BOOL _carrySelect;

        // Don't output the informational header on top of generated Verilog files
        BOOL _noVerilogHeader;

        // True to enable warnings about missing [[transaction_size]]
        BOOL _enableTransactionSizeWarning;

        // True to enable warnings about deprecated features
        BOOL _enableDeprecationWarnings;

        // True to treat warnings as errors
        BOOL _warningsAsErrors;

    } CodeGenOptions;

    typedef struct
    {
        // Role clock frequency (in MHz) (clock 0)
        size_t _frequency;

        // Name of the FPGA to target
        const char* _deviceName;

        // Command line arguments used
        const char* _cmdArgs;

        CodeGenOptions _codegenOptions;

        PlacementOptions _placementOptions;

    } Options;

#ifdef __cplusplus
};
#endif


// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#pragma once

void WriteResourceReport(const std::string& fileName, const Program& program);

void DumpMemoryMetadata(const char* const memoryMetadataFileNameBase, const Program& program);

void DumpSyncRamAndROM(std::ofstream* asrFile, std::ofstream* romFile, const Program& program,
                       const char* const memFileBase);

void DumpFifoRamInfo(std::ofstream* scfFile, std::ofstream* dcfFile, const Program& program);

size_t LogicRamCostFunction(size_t width, size_t depth, size_t numReadPorts);

void WriteResourceUsage(const char* const fileName, const Program& program);


void SerializeIRToJson(const Program& program, const std::string& fileName);


/*
Copyright 2018 Embedded Microprocessor Benchmark Consortium (EEMBC)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Original Author: Shay Gal-on
*/

/* Topic: Description
        This file contains  declarations of the various benchmark functions.
*/

/* Configuration: TOTAL_DATA_SIZE
        Define total size for data algorithms will operate on
*/
#ifndef TOTAL_DATA_SIZE
#define TOTAL_DATA_SIZE 2 * 1000
#endif

#define SEED_ARG      0
#define SEED_FUNC     1
#define SEED_VOLATILE 2

#define MEM_STATIC 0
#define MEM_MALLOC 1
#define MEM_STACK  2

#include "core_portme.h"

#if HAS_STDIO
#include <stdio.h>
#endif
#if HAS_PRINTF
#define ee_printf printf
#endif

/* Actual benchmark execution in iterate */
void *iterate(void *pres);

/* Typedef: secs_ret
        For machines that have floating point support, get number of seconds as
   a double. Otherwise an unsigned int.
*/
#if HAS_FLOAT
typedef double secs_ret;
#else
typedef ee_u32 secs_ret;
#endif

#if MAIN_HAS_NORETURN
#define MAIN_RETURN_VAL
#define MAIN_RETURN_TYPE void
#else
#define MAIN_RETURN_VAL  0
#define MAIN_RETURN_TYPE int
#endif

void       start_time(void);
void       stop_time(void);
CORE_TICKS get_time(void);
secs_ret   time_in_secs(CORE_TICKS ticks);

/* Misc useful functions */
ee_u16 crcu8(ee_u8 data, ee_u16 crc);
ee_u16 crc16(ee_s16 newval, ee_u16 crc);
ee_u16 crcu16(ee_u16 newval, ee_u16 crc);
ee_u16 crcu32(ee_u32 newval, ee_u16 crc);
ee_u8  check_data_types(void);

void   portable_free(void *p);
ee_s32 parseval(char *valstring);

/* Algorithm IDS */
#define ID_LIST             (1 << 0)
#define ID_MATRIX           (1 << 1)
#define ID_STATE            (1 << 2)
#define ALL_ALGORITHMS_MASK (ID_LIST | ID_MATRIX | ID_STATE)
#define NUM_ALGORITHMS      3

/* list data structures */
typedef struct list_data_s
{
    ee_s16 data16;
    ee_s16 idx;
} list_data;

typedef struct list_head_s
{
    struct list_head_s *next;
    struct list_data_s *info;
} list_head;

/*matrix benchmark related stuff */
#define MATDAT_INT 1
#if MATDAT_INT
typedef ee_s16 MATDAT;
typedef ee_s32 MATRES;
#else
typedef ee_f16 MATDAT;
typedef ee_f32 MATRES;
#endif

typedef struct MAT_PARAMS_S
{
    int     N;
    MATDAT *A;
    MATDAT *B;
    MATRES *C;
} mat_params;

/* state machine related stuff */
/* List of all the possible states for the FSM */
typedef enum CORE_STATE
{
    CORE_START = 0,
    CORE_INVALID,
    CORE_S1,
    CORE_S2,
    CORE_INT,
    CORE_FLOAT,
    CORE_EXPONENT,
    CORE_SCIENTIFIC,
    NUM_CORE_STATES
} core_state_e;

/* Helper structure to hold results */
typedef struct RESULTS_S
{
    /* inputs */
    ee_s16              seed1;       /* Initializing seed */
    ee_s16              seed2;       /* Initializing seed */
    ee_s16              seed3;       /* Initializing seed */
    void *              memblock[4]; /* Pointer to safe memory location */
    ee_u32              size;        /* Size of the data */
    ee_u32              iterations;  /* Number of iterations to execute */
    ee_u32              execs;       /* Bitmask of operations to execute */
    struct list_head_s *list;
    mat_params          mat;
    /* outputs */
    ee_u16 crc;
    ee_u16 crclist;
    ee_u16 crcmatrix;
    ee_u16 crcstate;
    ee_s16 err;
    /* ultithread specific */
    core_portable port;
} core_results;

/* Multicore execution handling */
#if (MULTITHREAD > 1)
ee_u8 core_start_parallel(core_results *res);
ee_u8 core_stop_parallel(core_results *res);
#endif

/* list benchmark functions */
list_head *core_list_init(ee_u32 blksize, list_head *memblock, ee_s16 seed);
ee_u16     core_bench_list(core_results *res, ee_s16 finder_idx);

/* state benchmark functions */
void   core_init_state(ee_u32 size, ee_s16 seed, ee_u8 *p);
ee_u16 core_bench_state(ee_u32 blksize,
                        ee_u8 *memblock,
                        ee_s16 seed1,
                        ee_s16 seed2,
                        ee_s16 step,
                        ee_u16 crc);

/* matrix benchmark functions */
ee_u32 core_init_matrix(ee_u32      blksize,
                        void *      memblk,
                        ee_s32      seed,
                        mat_params *p);
ee_u16 core_bench_matrix(mat_params *p, ee_s16 seed, ee_u16 crc);


  long gpr[32];
  long sr;
  long epc;
  long badvaddr;
  long cause;
} trapframe_t;
#endif

#endif


// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#include "pch.h"

ObjectPath AppendToPath(const ObjectPath& path, const std::string& suffix)
{
    ObjectPath result = path;

    result.push_back(suffix);

    return result;
}

std::string SerializePath(const ObjectPath& path, const char delimeter)
{
    std::ostringstream str;

    bool isFirst = true;

    for (const std::string& s : path)
    {
        if (!isFirst)
        {
            str << delimeter;
        }

        str << s;

        isFirst = false;
    }

    return str.str();
}

ObjectPath SubPath(const ObjectPath& src, const size_t offset, const size_t len)
{
    assert((offset + len) <= src.size());

    for (size_t i = 0; i < len; i++)
    {
        result[i] = src[offset + i];
    }

    return result;
}


// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#include "pch.h"

// Included separately to avoid rapidsjon overriding assert definition globally
#include "report.h"

enum class PathLengthPathElement
{
    Object,
    Function,
    BasicBlock,
    Stage,
    OperationName,

    Count
};

enum class PathLengthTupleElement
{
    OperationLength,
    PathLength,

    Count
};

void WritePathLengthReport(const std::string& fileName, const Program& program)
{
    const size_t ColumnCount = static_cast<size_t>(PathLengthTupleElement::Count);
    const size_t PathElementCount = static_cast<size_t>(PathLengthPathElement::Count);

    using ReportBuilderT = ReportBuilder<ColumnCount, PathElementCount>;

    ReportBuilderT::ColumnArray columns = {};

    columns[static_cast<size_t>(PathLengthTupleElement::OperationLength)] = {"Op_Depth", "level"};
    columns[static_cast<size_t>(PathLengthTupleElement::PathLength)] = {"Path_Depth", "level"};

    ReportBuilderT::PathElementNameArray pathElementNames = {};

    pathElementNames[static_cast<size_t>(PathLengthPathElement::Object)] = "Object";
    pathElementNames[static_cast<size_t>(PathLengthPathElement::Function)] = "Function";
    pathElementNames[static_cast<size_t>(PathLengthPathElement::BasicBlock)] = "Basic block";
    pathElementNames[static_cast<size_t>(PathLengthPathElement::Stage)] = "Stage";
    pathElementNames[static_cast<size_t>(PathLengthPathElement::OperationName)] = "Operation";

    const ReportBuilderT::ProjectionVector projections(
        {{"Default View",
          {0, 1, 2, 3, 4},
          {ReportBuilderT::AggregationRule::Max, ReportBuilderT::AggregationRule::Max}}});

    ReportBuilderT report(fileName, columns, pathElementNames, projections);

    for (const Function& function : program._functions)
    {
        ReportBuilderT::Path path = {};

        // Tokenize flat object name into array of nested object names
        path[static_cast<size_t>(PathLengthPathElement::Object)] = TokenizeObjectName(function._objectName, program);

        path[static_cast<size_t>(PathLengthPathElement::Function)] = ReportBuilderT::SimplePathElement(function._name);

        for (const BasicBlock& basicBlock : function._basicBlocks)
        {
            path[static_cast<size_t>(PathLengthPathElement::BasicBlock)] =
                ReportBuilderT::SimplePathElement(GetBasicBlockName(basicBlock));

            const std::vector<PipelineStage> pipelineStages = GetPipelineStages(const_cast<BasicBlock&>(basicBlock));

            for (const PipelineStage& ps : pipelineStages)
            {
                // Distance from the first use to the end of the basic block
                PathLengthTracker pathLengthTracker(program);

                assert(!ps.empty());

                // Make operation names unique, the visualizer drops duplicates
                size_t opId = 0;

                // Track all pipeline registers written by any substage within this stage
                for (const Stage* const subStage : ps)
                {
                    const std::string stageName = "stage" + std::to_string(subStage->_atomicSequence);
                    path[static_cast<size_t>(PathLengthPathElement::Stage)] =
                        ReportBuilderT::SimplePathElement(stageName);

                    for (const Operation& op : subStage->_operations)
                    {
                        const size_t pathLength = pathLengthTracker.UpdateForward(op);
                        const size_t opLength = GetOpPathLength(program, op, pathLengthTracker.GetCarryChainWidth());

                        if (opLength > 0)
                        {
                            const std::string opName = std::to_string(opId) + "_" + GetOpcodeString(program, op);
                            opId++;

                            // Multiple source locations can contribute to this operation,
                            // but the visualizes only allows one file location.
                            // Pick the first location, if any.
                            Location loc = {};
                            const auto it = op._locations.cbegin();
                            if (it != op._locations.cend())
                            {
                                loc._beginLine = it->_lineNumber;
                                loc._endLine = it->_lineNumber + 1;
                                loc._fileIndex = it->_fileIndex;
                                loc._valid = true;
                            }
                            else
                            {
                                loc._valid = false;

                                ReportBuilderT::SimplePathElement(opName);

                            report.AppendRow(path, loc, tuple);
                        }
                    }
                }
            }
        }
    }
}

                            }

                            ReportBuilderT::Tuple tuple = {};
                            tuple[static_cast<size_t>(PathLengthTupleElement::OperationLength)] = opLength;


// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#include "platform.h"
#ifdef _WIN32
#include <windows.h>
#else
#endif
#include <assert.h>
#include <map>
#include <stdint.h>
#include <vector>

#ifdef _WIN32
void SetConsoleColor(const ConsoleColor color)
{
    uint16_t windowsColor = 0;

    switch (color)
    {
    case ConsoleColor::Default:
        windowsColor = 0x0007;
        break;

    case ConsoleColor::Red:
        windowsColor = FOREGROUND_INTENSITY | FOREGROUND_RED;
        break;

    case ConsoleColor::Yellow:
        windowsColor = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN;
        break;

    default:
        assert(false);
    }

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), windowsColor);
}

class WindowsWindow : public Window
{
  private:
    struct Label
    {
        size_t _left;
        size_t _top;
        size_t _right;
        size_t _bottom;

        std::string _label;
    };

  public:
    WindowsWindow(const size_t width, const size_t height)
    {
        _window = CreateWindow("STATIC", "Placement", WS_VISIBLE, 0, 0, static_cast<int32_t>(width),
                               static_cast<int32_t>(height), nullptr, nullptr, GetModuleHandle(nullptr), nullptr);
    }

    ~WindowsWindow()
    {
        for (const auto& p : _brushMap)
        {
            DeleteObject(p.second);
        }

        DestroyWindow(_window);
    }

    void BeginFrame() override
    {
        _labels.clear();

        RECT clientRect = {};
        GetClientRect(_window, &clientRect);

        _windowDC = GetDC(_window);

        // Create a device context that will be rendered into (off-screen)
        _dc = CreateCompatibleDC(_windowDC);

        // Create a bitmap to render into
        _bitmap = CreateCompatibleBitmap(_windowDC, clientRect.right, clientRect.bottom);

        SelectObject(_dc, _bitmap);
    }

    void FillRectangle(const size_t x, const size_t y, const size_t width, const size_t height, const uint32_t clr,
                       const char* const label) override
    {
        if (_brushMap.find(clr) == _brushMap.end())
        {
            _brushMap[clr] = CreateSolidBrush(clr & 0x00ffffff);
        }

        HGDIOBJ oldBrush = SelectObject(_dc, _brushMap[clr]);

        Rectangle(_dc, static_cast<int32_t>(x), static_cast<int32_t>(y), static_cast<int32_t>(x + width),
                  static_cast<int32_t>(y + height));

        SelectObject(_dc, oldBrush);

        if (label)
        {
            Label labelRecord = {};

            labelRecord._left = x;
            labelRecord._top = y;
            labelRecord._right = x + width;
            labelRecord._bottom = y + height;

            labelRecord._label = label;

            _labels.push_back(labelRecord);
        }
    }

    void DrawLine(const size_t x1, const size_t y1, const size_t x2, const size_t y2, const uint32_t clr)
    {
        if (_penMap.end() == _penMap.find(clr))
        {
            _penMap[clr] = CreatePen(PS_SOLID, 1, clr);
        }

        HGDIOBJ oldPen = SelectObject(_dc, _penMap[clr]);

        MoveToEx(_dc, static_cast<int32_t>(x1), static_cast<int32_t>(y1), nullptr);

        LineTo(_dc, static_cast<int32_t>(x2), static_cast<int32_t>(y2));

        SelectObject(_dc, oldPen);
    }

    void DrawString(const size_t x, const size_t y, const std::string& str) override
    {
        TextOut(_dc, static_cast<int32_t>(x), static_cast<int32_t>(y), str.c_str(), static_cast<int32_t>(str.length()));
    }

    void EndFrame() override
    {
        // See if the mouse is over a label
        POINT cursorPos = {};

        if (GetCursorPos(&cursorPos))
        {
            if (ScreenToClient(_window, &cursorPos))
            {
                for (const Label& label : _labels)
                {
                    if ((cursorPos.x >= label._left) && (cursorPos.x < label._right) && (cursorPos.y >= label._top) &&
                        (cursorPos.y < label._bottom))
                    {
                        DrawString(0, 0, label._label);
                    }
                }
            }
        }

        RECT clientRect = {};
        GetClientRect(_window, &clientRect);

        // Copy from off-screen bitmap to the window
        BitBlt(_windowDC, 0, 0, clientRect.right, clientRect.bottom, _dc, 0, 0, SRCCOPY);

        DeleteDC(_dc);

        ReleaseDC(_window, _windowDC);

        // Pump window messages
        MSG msg = {};

        while (PeekMessage(&msg, _window, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

  private:
    HWND _window;
    HDC _windowDC;
    HDC _dc;
    HBITMAP _bitmap;
    std::map<uint32_t, HBRUSH> _brushMap;
    std::map<uint32_t, HPEN> _penMap;
    std::vector<Label> _labels;
};

std::shared_ptr<Window> Window::Create(const size_t width, const size_t height)
{
    return std::make_shared<WindowsWindow>(width, height);
}

#else
void SetConsoleColor(const ConsoleColor color) {}

class FakeWindow : public Window
{
  public:
    FakeWindow() {}

    virtual ~FakeWindow(){};

    virtual void BeginFrame(){};

    virtual void FillRectangle(const size_t x, const size_t y, const size_t width, const size_t height,
                               const uint32_t clr, const char* const label = nullptr)
    {
    }

    virtual void DrawLine(const size_t x1, const size_t y1, const size_t x2, const size_t y2, const uint32_t clr) {}

    virtual void DrawString(const size_t x, const size_t y, const std::string& str) {}

    virtual void EndFrame(){};

    static std::shared_ptr<Window> Create(const size_t width, const size_t height);
};

std::shared_ptr<Window> Window::Create(const size_t width, const size_t height)
{
    return std::make_shared<FakeWindow>();
}

#endif


// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#include "pch.h"

// Included separately to avoid rapidsjon overriding assert definition globally
#include "report.h"

enum class ClockGatingPathElement
{
    Object,
    Function,
    BasicBlock,
    VariableName,

    Count
};

enum class ClockGatingTupleElement
{
    NonGated,
    Total,

    Count
};

void WriteClockGatingReport(const std::string& fileName, const Program& program)
{
    const size_t ColumnCount = static_cast<size_t>(ClockGatingTupleElement::Count);

    using ReportBuilderT = ReportBuilder<ColumnCount, PathElementCount>;

    ReportBuilderT::ColumnArray columns = {};

    columns[static_cast<size_t>(ClockGatingTupleElement::NonGated)] = {"Non-Gated Registers", "Bits"};
    columns[static_cast<size_t>(ClockGatingTupleElement::Total)] = {"Total Registers", "Bits"};

    ReportBuilderT::PathElementNameArray pathElementNames = {};

    pathElementNames[static_cast<size_t>(ClockGatingPathElement::Object)] = "Object";
    pathElementNames[static_cast<size_t>(ClockGatingPathElement::Function)] = "Function";
    pathElementNames[static_cast<size_t>(ClockGatingPathElement::BasicBlock)] = "Basic block";
    pathElementNames[static_cast<size_t>(ClockGatingPathElement::VariableName)] = "Variable";

    const ReportBuilderT::ProjectionVector projections(
        {{"Default View", {0, 1, 2, 3}, {ReportBuilderT::AggregationRule::Sum, ReportBuilderT::AggregationRule::Sum}}});

    ReportBuilderT report(fileName, columns, pathElementNames, projections);

    std::vector<size_t> readSet;
    std::vector<size_t> writeSet;

    ReportBuilderT::Path path = {};

    for (const Function& function : program._functions)
    {
        // Tokenize flat object name into array of nested object names
        path[static_cast<size_t>(ClockGatingPathElement::Object)] = TokenizeObjectName(function._objectName, program);

        path[static_cast<size_t>(ClockGatingPathElement::Function)] = ReportBuilderT::SimplePathElement(function._name);

        for (const BasicBlock& basicBlock : function._basicBlocks)
        {
            path[static_cast<size_t>(ClockGatingPathElement::BasicBlock)] =
                ReportBuilderT::SimplePathElement(GetBasicBlockName(basicBlock));

            const std::vector<PipelineStage> pipelineStages = GetPipelineStages(const_cast<BasicBlock&>(basicBlock));

            // Variable name to gated/total bits
            std::map<std::string, ReportBuilderT::Tuple> nameToTuple;

            for (const PipelineStage& ps : pipelineStages)
            {
                assert(!ps.empty());

                // Track all pipeline registers written by any substage within this stage
                for (const Stage* const subStage : ps)
                {
                    for (const Operation& op : subStage->_operations)
                    {
                        GetAccessedRegisters(op, readSet, writeSet);

                        for (const size_t r : writeSet)
                        {
                            const RegisterDescription& rd = program._registerTable[r];

                            if (RegisterType::Pipeline == rd._type)
                            {
                                const size_t width = rd._width;

                                const auto it = subStage->_clockGates.find(r);

                                const bool isGated = (it != subStage->_clockGates.end()) && (!it->second.empty());

                                ReportBuilderT::Tuple tuple = {};
                                tuple[static_cast<size_t>(ClockGatingTupleElement::NonGated)] = isGated ? 0 : width;
                                tuple[static_cast<size_t>(ClockGatingTupleElement::Total)] = width;

                                const auto it2 = nameToTuple.find(rd._name);
                                if (it2 == nameToTuple.end())
                                {
                                    nameToTuple[rd._name] = tuple;
                                }
                                else
                                {
                                    for (size_t i = 0; i < ColumnCount; i++)
                                    {
                                        it2->second[i] += tuple[i];
                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (const auto& p : nameToTuple)
            {
                path[static_cast<size_t>(ClockGatingPathElement::VariableName)] =
                    ReportBuilderT::SimplePathElement(p.first);

                report.AppendRow(path, basicBlock._location, p.second);
            }
        }
    }
}

const size_t PathElementCount = static_cast<size_t>(ClockGatingPathElement::Count);


Attribution 4.0 International

=======================================================================

Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.

Using Creative Commons Public Licenses

Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.

     Considerations for licensors: Our public licenses are
     intended for use by those authorized to give the public
     permission to use material in ways otherwise restricted by
     copyright and certain other rights. Our licenses are
     irrevocable. Licensors should read and understand the terms
     and conditions of the license they choose before applying it.
     Licensors should also secure all rights necessary before
     applying our licenses so that the public can reuse the
     material as expected. Licensors should clearly mark any
     material not subject to the license. This includes other CC-
     licensed material, or material used under an exception or
     limitation to copyright. More considerations for licensors:
	wiki.creativecommons.org/Considerations_for_licensors

     Considerations for the public: By using one of our public
     licenses, a licensor grants the public permission to use the
     licensed material under specified terms and conditions. If
     the licensor's permission is not necessary for any reason--for
     example, because of any applicable exception or limitation to
     copyright--then that use is not regulated by the license. Our
     licenses grant only permissions under copyright and certain
     other rights that a licensor has authority to grant. Use of
     the licensed material may still be restricted for other
     reasons, including because others have copyright or other
     rights in the material. A licensor may make special requests,
     such as asking that all changes be marked or described.
     Although not required by our licenses, you are encouraged to
     respect those requests where reasonable. More considerations
     for the public:
	wiki.creativecommons.org/Considerations_for_licensees

=======================================================================

Creative Commons Attribution 4.0 International Public License

By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution 4.0 International Public License ("Public License"). To the
extent this Public License may be interpreted as a contract, You are
granted the Licensed Rights in consideration of Your acceptance of
these terms and conditions, and the Licensor grants You such rights in
consideration of benefits the Licensor receives from making the
Licensed Material available under these terms and conditions.

Section 1 -- Definitions.

  a. Adapted Material means material subject to Copyright and Similar
     Rights that is derived from or based upon the Licensed Material
     and in which the Licensed Material is translated, altered,
     arranged, transformed, or otherwise modified in a manner requiring
     permission under the Copyright and Similar Rights held by the
     Licensor. For purposes of this Public License, where the Licensed
     Material is a musical work, performance, or sound recording,
     Adapted Material is always produced where the Licensed Material is
     synched in timed relation with a moving image.

  b. Adapter's License means the license You apply to Your Copyright
     and Similar Rights in Your contributions to Adapted Material in
     accordance with the terms and conditions of this Public License.

  c. Copyright and Similar Rights means copyright and/or similar rights

     Rights.

  d. Effective Technological Measures means those measures that, in the
     absence of proper authority, may not be circumvented under laws
     fulfilling obligations under Article 11 of the WIPO Copyright
     Treaty adopted on December 20, 1996, and/or similar international
     agreements.

  e. Exceptions and Limitations means fair use, fair dealing, and/or
     any other exception or limitation to Copyright and Similar Rights
     that applies to Your use of the Licensed Material.

  f. Licensed Material means the artistic or literary work, database,
     or other material to which the Licensor applied this Public
     License.

  g. Licensed Rights means the rights granted to You subject to the
     terms and conditions of this Public License, which are limited to
     all Copyright and Similar Rights that apply to Your use of the
     Licensed Material and that the Licensor has authority to license.

  h. Licensor means the individual(s) or entity(ies) granting rights
     under this Public License.

  i. Share means to provide material to the public by any means or
     process that requires permission under the Licensed Rights, such
     as reproduction, public display, public performance, distribution,
     dissemination, communication, or importation, and to make material
     available to the public including in ways that members of the
     public may access the material from a place and at a time
     individually chosen by them.

  j. Sui Generis Database Rights means rights other than copyright
     resulting from Directive 96/9/EC of the European Parliament and of
     the Council of 11 March 1996 on the legal protection of databases,
     as amended and/or succeeded, as well as other essentially
     equivalent rights anywhere in the world.

  k. You means the individual or entity exercising the Licensed Rights
     under this Public License. Your has a corresponding meaning.

Section 2 -- Scope.

  a. License grant.

       1. Subject to the terms and conditions of this Public License,
          the Licensor hereby grants You a worldwide, royalty-free,
          non-sublicensable, non-exclusive, irrevocable license to
          exercise the Licensed Rights in the Licensed Material to:

            a. reproduce and Share the Licensed Material, in whole or
               in part; and

            b. produce, reproduce, and Share Adapted Material.

       2. Exceptions and Limitations. For the avoidance of doubt, where
          Exceptions and Limitations apply to Your use, this Public
          License does not apply, and You do not need to comply with
          its terms and conditions.

       3. Term. The term of this Public License is specified in Section
          6(a).

       4. Media and formats; technical modifications allowed. The
          Licensor authorizes You to exercise the Licensed Rights in
          all media and formats whether now known or hereafter created,
          and to make technical modifications necessary to do so. The
          Licensor waives and/or agrees not to assert any right or
          authority to forbid You from making technical modifications
          necessary to exercise the Licensed Rights, including
          technical modifications necessary to circumvent Effective
          Technological Measures. For purposes of this Public License,
          simply making modifications authorized by this Section 2(a)
          (4) never produces Adapted Material.

       5. Downstream recipients.

            a. Offer from the Licensor -- Licensed Material. Every
               recipient of the Licensed Material automatically
               receives an offer from the Licensor to exercise the
               Licensed Rights under the terms and conditions of this
               Public License.

            b. No downstream restrictions. You may not offer or impose
               any additional or different terms or conditions on, or
               apply any Effective Technological Measures to, the
               Licensed Material if doing so restricts exercise of the
               Licensed Rights by any recipient of the Licensed
               Material.

       6. No endorsement. Nothing in this Public License constitutes or
          may be construed as permission to assert or imply that You
          are, or that Your use of the Licensed Material is, connected
          with, or sponsored, endorsed, or granted official status by,
          the Licensor or others designated to receive attribution as
          provided in Section 3(a)(1)(A)(i).

  b. Other rights.

       1. Moral rights, such as the right of integrity, are not
          licensed under this Public License, nor are publicity,
          privacy, and/or other similar personality rights; however, to
          the extent possible, the Licensor waives and/or agrees not to
          assert any such rights held by the Licensor to the limited
          extent necessary to allow You to exercise the Licensed
          Rights, but not otherwise.

       2. Patent and trademark rights are not licensed under this
          Public License.

       3. To the extent possible, the Licensor waives any right to
          collect royalties from You for the exercise of the Licensed
          Rights, whether directly or through a collecting society
          under any voluntary or waivable statutory or compulsory
          licensing scheme. In all other cases the Licensor expressly
          reserves any right to collect such royalties.

Section 3 -- License Conditions.

Your exercise of the Licensed Rights is expressly made subject to the
following conditions.

  a. Attribution.

       1. If You Share the Licensed Material (including in modified
          form), You must:

            a. retain the following if it is supplied by the Licensor
               with the Licensed Material:

                 i. identification of the creator(s) of the Licensed
                    Material and any others designated to receive
                    attribution, in any reasonable manner requested by
                    the Licensor (including by pseudonym if
                    designated);

                ii. a copyright notice;

               iii. a notice that refers to this Public License;

                iv. a notice that refers to the disclaimer of
                    warranties;

                 v. a URI or hyperlink to the Licensed Material to the
                    extent reasonably practicable;

            b. indicate if You modified the Licensed Material and
               retain an indication of any previous modifications; and

            c. indicate the Licensed Material is licensed under this
               Public License, and include the text of, or the URI or
               hyperlink to, this Public License.

       2. You may satisfy the conditions in Section 3(a)(1) in any
          reasonable manner based on the medium, means, and context in
          which You Share the Licensed Material. For example, it may be
          reasonable to satisfy the conditions by providing a URI or
          hyperlink to a resource that includes the required
          information.

       3. If requested by the Licensor, You must remove any of the
          information required by Section 3(a)(1)(A) to the extent
          reasonably practicable.

       4. If You Share Adapted Material You produce, the Adapter's
          License You apply must not prevent recipients of the Adapted
          Material from complying with this Public License.

Section 4 -- Sui Generis Database Rights.

Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:

  a. for the avoidance of doubt, Section 2(a)(1) grants You the right
     to extract, reuse, reproduce, and Share all or a substantial
     portion of the contents of the database;

  b. if You include all or a substantial portion of the database
     contents in a database in which You have Sui Generis Database
     Rights, then the database in which You have Sui Generis Database
     Rights (but not its individual contents) is Adapted Material; and

  c. You must comply with the conditions in Section 3(a) if You Share
     all or a substantial portion of the contents of the database.

For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.

Section 5 -- Disclaimer of Warranties and Limitation of Liability.

  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.

  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.

  c. The disclaimer of warranties and limitation of liability provided
     above shall be interpreted in a manner that, to the extent
     possible, most closely approximates an absolute disclaimer and
     waiver of all liability.

Section 6 -- Term and Termination.

  a. This Public License applies for the term of the Copyright and
     Similar Rights licensed here. However, if You fail to comply with
     this Public License, then Your rights under this Public License
     terminate automatically.

  b. Where Your right to use the Licensed Material has terminated under
     Section 6(a), it reinstates:

       1. automatically as of the date the violation is cured, provided
          it is cured within 30 days of Your discovery of the
          violation; or

       2. upon express reinstatement by the Licensor.

     For the avoidance of doubt, this Section 6(b) does not affect any
     right the Licensor may have to seek remedies for Your violations
     of this Public License.

  c. For the avoidance of doubt, the Licensor may also offer the
     Licensed Material under separate terms or conditions or stop
     distributing the Licensed Material at any time; however, doing so
     will not terminate this Public License.

  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
     License.

Section 7 -- Other Terms and Conditions.

  a. The Licensor shall not be bound by any additional or different
     terms or conditions communicated by You unless expressly agreed.

  b. Any arrangements, understandings, or agreements regarding the
     Licensed Material not stated herein are separate from and
     independent of the terms and conditions of this Public License.

Section 8 -- Interpretation.

  a. For the avoidance of doubt, this Public License does not, and
     shall not be interpreted to, reduce, limit, restrict, or impose
     conditions on any use of the Licensed Material that could lawfully
     be made without permission under this Public License.

  b. To the extent possible, if any provision of this Public License is
     deemed unenforceable, it shall be automatically reformed to the
     minimum extent necessary to make it enforceable. If the provision
     cannot be reformed, it shall be severed from this Public License
     without affecting the enforceability of the remaining terms and
     conditions.

  c. No term or condition of this Public License will be waived and no
     failure to comply consented to unless expressly agreed to by the
     Licensor.

  d. Nothing in this Public License constitutes or may be interpreted
     as a limitation upon, or waiver of, any privileges and immunities
     that apply to the Licensor or You, including from the legal
     processes of any jurisdiction or authority.

=======================================================================

Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.

Creative Commons may be contacted at creativecommons.org.

     closely related to copyright including, without limitation,
     performance, broadcast, sound recording, and Sui Generis Database
     Rights, without regard to how the rights are labeled or


#ifndef complex_hpp
#define complex_hpp

#include <stdint.h>

#if 0

struct complex_t
{
    int32_t re;
    int32_t im;

  static const int shift = 16;
  static const int64_t bias = 1<<(shift-1);

    complex_t()
    {}

private:
    complex_t(int32_t _re, int32_t _im)
        : re(_re)
        , im(_im)
    {}

    friend complex_t operator+(const complex_t &a, const complex_t &b);
    friend complex_t operator-(const complex_t &a, const complex_t &b);
    friend complex_t operator*(const complex_t &a, const complex_t &b);
public:

  static complex_t from_int(int _re, int _im=0)
  {
    return complex_t(_re<<shift, _im<<shift);
  }

  static complex_t from_float(float _re, float _im=0.0f)
  {
    return complex_t((int32_t)(_re*(1<<shift)), (int32_t)(_im*(1<<shift)));
  }

  complex_t &operator=(const complex_t &o)
  {
    re=o.re;
    im=o.im;
    return *this;
  }

  float re_float()
  { return re * (1.0f/(1<<shift)); }

  float im_float()
  { return im * (1.0f/(1<<shift)); }

  int re_int()
  { return (re+ bias)>>shift; }

  int im_int()
  { return (im+ bias)>>shift; }
};

complex_t operator+(const complex_t &a, const complex_t &b)
{
    return complex_t(a.re+b.re, a.im+b.im);
}

complex_t operator-(const complex_t &a, const complex_t &b)
{
    return complex_t(a.re-b.re, a.im-b.im);
}

complex_t operator*(const complex_t &aa, const complex_t &bb)
{
    int64_t a=aa.re, b=aa.im, c=bb.re, d=bb.im;
    return complex_t(
		     (int32_t)((a*c-b*d+complex_t::bias)>>(complex_t::shift)),
		     (int32_t)((b*c+a*d+complex_t::bias)>>(complex_t::shift))
    );
}

#else

struct complex_t
{
   float re;
    float im;

    complex_t()
    {}

    complex_t(float _re, float _im)
        : re(_re)
        , im(_im)
    {}

  static complex_t from_int(int _re, int _im=0)
  {
    return complex_t(_re, _im);
  }

  static complex_t from_float(float _re, float _im=0.0f)
  {
    return complex_t(_re, _im);
  }

  complex_t &operator=(const complex_t &o)
  {
    re=o.re;
    im=o.im;
    return *this;
  }

  float re_float()
  { return re ; }

  float im_float()

  int re_int()
  { return (int)re; }

  int im_int()
  { return (int)im; }
};

complex_t operator+(const complex_t &a, const complex_t &b)
{
    return complex_t(a.re+b.re, a.im+b.im);
}

complex_t operator-(const complex_t &a, const complex_t &b)
{
    return complex_t(a.re-b.re, a.im-b.im);
}

complex_t operator*(const complex_t &aa, const complex_t &bb)
{
    float a=aa.re, b=aa.im, c=bb.re, d=bb.im;
    return complex_t(
		     (a*c-b*d),
		     (b*c+a*d)
    );
}

#endif

#endif


#ifndef fft_man_hpp
#define fft_man_hpp

#include "hls_recurse/state_machine_self_recursion.hpp"

#include "hls_recurse/complex.hpp"

#include "hls_recurse/examples/fft.hpp"

namespace hls_recurse
{

{
    return test_fft(fft,logEvents);
}

template<class T>
int harness_fft_man(T fft)
{
    return harness_fft(fft);
}

}; //

#endif

void f2_fft_man(int log2n, const complex_t *pIn, complex_t *pOut)
{
    man_fft(log2n, pIn, pOut);
}


#ifndef strassen_indexed_hpp
#define strassen_indexed_hpp

#include "hls_recurse/state_machine_self_recursion.hpp"

namespace hls_recurse
{

struct imatrix_t
{
    int n;
    int stride;
    int base;
};

HLS_INLINE_STEP void set(uint32_t *p, const imatrix_t &m, int r, int c, uint32_t val)
{
    assert(r < m.n);
    assert(c < m.n);
    p[m.base+r*m.stride+c]=val;
}

HLS_INLINE_STEP uint32_t get(const uint32_t *p, const imatrix_t &m, int r, int c)
{
    return p[m.base+r*m.stride+c];
}

HLS_INLINE_STEP imatrix_t quad(const imatrix_t &m, int r, int c)
{
    assert(m.n>1);
    assert(0<=r && r<2);
    assert(0<=c && c<2);
    int hn=m.n/2;
    return imatrix_t{ hn, m.stride, m.base+r*hn*m.stride+c*hn };
}

HLS_INLINE_STEP void add_matrix(uint32_t * p, const imatrix_t &dst, const imatrix_t &a, const imatrix_t &b)
{
    int n=dst.n;
    for(int r=0; r<n; r++){
        for(int c=0; c<n; c++){
            p[dst.base + r*dst.stride+c] = p[a.base + r*a.stride+c] + p[b.base + r*b.stride+c];
        }
    }
}

HLS_INLINE_STEP void sub_matrix(uint32_t *p, const imatrix_t &dst, const imatrix_t &a, const imatrix_t &b)
{
    int n=dst.n;
    for(int r=0; r<n; r++){
        for(int c=0; c<n; c++){
            p[dst.base + r*dst.stride+c] = p[a.base + r*a.stride+c] - p[b.base + r*b.stride+c];
        }
    }
}

HLS_INLINE_STEP void add_sub_add_matrix(uint32_t *p, const imatrix_t &dst, const imatrix_t &a, const imatrix_t &b, const imatrix_t &c, const imatrix_t &d)
{
    int n=dst.n;
    for(int r=0; r<n; r++){
        for(int ci=0; ci<n; ci++){
            p[dst.base + r*dst.stride+ci] = p[a.base + r*a.stride+ci]
                                      + p[b.base+r*b.stride+ci]
                                      - p[c.base+r*c.stride+ci]
                                      + p[d.base+r*d.stride+ci];
        }
    }
}

HLS_INLINE_STEP void mul_matrix(uint32_t *p, const imatrix_t &dst, const imatrix_t &a, const imatrix_t &b)
{
    int n=dst.n;
    for(int r=0; r<n; r++){
        for(int c=0; c<n; c++){
            uint32_t acc=0;
            for(int i=0; i<n; i++){
                acc += p[a.base+r*a.stride+i] * p[b.base + i*b.stride+c];
            }
            p[dst.base + r*dst.stride+c]=acc;
        }
    }
}

typedef int ifree_region_t;

HLS_INLINE_STEP imatrix_t alloc_matrix(ifree_region_t &h, int n)
{
    int data=h;
    h+=n*n;

    return imatrix_t{n,n,data};
}

void r_strassen_indexed(uint32_t *p, imatrix_t &dst, const imatrix_t &a, const imatrix_t &b, ifree_region_t hFree)
{
    int n=a.n;

    if(n<=16){
        mul_matrix(p, dst,a,b);
        return;
    }

    n=n/2; // Size of quads

    imatrix_t tmp1=alloc_matrix(hFree, n);
    imatrix_t tmp2=alloc_matrix(hFree, n);

    imatrix_t M1=alloc_matrix(hFree, n);
    add_matrix(p, tmp1,quad(a,0,0),quad(a,1,1));
    add_matrix(p, tmp2,quad(b,0,0),quad(b,1,1));
    r_strassen_indexed(p, M1,tmp1,tmp2, hFree);

    imatrix_t M2=alloc_matrix(hFree, n);
    add_matrix(p, tmp1,quad(a,1,0),quad(a,1,1));
    r_strassen_indexed(p, M2,tmp1,quad(b,0,0), hFree);

    imatrix_t M3=alloc_matrix(hFree, n);
    sub_matrix(p, tmp1,quad(b,0,1),quad(b,1,1));
    r_strassen_indexed(p, M3,quad(a,0,0),tmp1, hFree);

    imatrix_t M4=alloc_matrix(hFree, n);
    sub_matrix(p, tmp1,quad(b,1,0),quad(b,0,0));
    r_strassen_indexed(p, M4,quad(a,1,1),tmp1, hFree);

    imatrix_t M5=alloc_matrix(hFree, n);
    add_matrix(p, tmp1,quad(a,0,0),quad(a,0,1));
    r_strassen_indexed(p, M5,tmp1,quad(b,1,1), hFree);

    imatrix_t M6=alloc_matrix(hFree, n);
    sub_matrix(p, tmp1,quad(a,1,0),quad(a,0,0));
    add_matrix(p, tmp2,quad(b,0,0),quad(b,0,1));
    r_strassen_indexed(p, M6,tmp1,tmp2, hFree);

    imatrix_t M7=alloc_matrix(hFree, n);
    sub_matrix(p, tmp1,quad(a,0,1),quad(a,1,1));
    add_matrix(p, tmp2,quad(b,1,0),quad(b,1,1));
    r_strassen_indexed(p, M7,tmp1,tmp2, hFree);

    add_sub_add_matrix(p, quad(dst,0,0), M1, M4, M5, M7);
    add_matrix(p, quad(dst,0,1), M3, M5);
    add_matrix(p, quad(dst,1,0), M2, M4);
    add_sub_add_matrix(p, quad(dst,1,1), M1,M3,M2,M6);
}

void f_strassen_indexed(imatrix_t &dst, const imatrix_t &a, const imatrix_t &b, ifree_region_t hFree);

void f2_strassen_indexed(uint32_t *p, imatrix_t dst, imatrix_t a, imatrix_t b, ifree_region_t hFree)
{
    int n;
    imatrix_t tmp1, tmp2;
    imatrix_t M1, M2, M3, M4, M5, M6, M7;

    run_function_old<void>(
        Sequence(
            [&](){ n=a.n; },
            If([&](){ return n<=16; },
                [&](){ mul_matrix(p, dst,a,b); },
                Return()
            ),
            [&](){
            n=n/2; // Size of quads

            tmp1=alloc_matrix(hFree, n);
            tmp2=alloc_matrix(hFree, n);

            M1=alloc_matrix(hFree, n);
            add_matrix(p, tmp1,quad(a,0,0),quad(a,1,1));
            add_matrix(p, tmp2,quad(b,0,0),quad(b,1,1));
            },
            Recurse([&](){ return make_hls_state_tuple( M1,tmp1,tmp2, hFree); }),
            [&](){

            M2=alloc_matrix(hFree, n);
            add_matrix(p, tmp1,quad(a,1,0),quad(a,1,1));
            },
            Recurse([&](){ return make_hls_state_tuple( M2,tmp1,quad(b,0,0), hFree); }),
            [&](){

            M3=alloc_matrix(hFree, n);
            sub_matrix(p, tmp1,quad(b,0,1),quad(b,1,1));
            },
            Recurse([&](){ return make_hls_state_tuple( M3,quad(a,0,0),tmp1, hFree); }),
            [&](){

            M4=alloc_matrix(hFree, n);
            sub_matrix(p, tmp1,quad(b,1,0),quad(b,0,0));
            },
            Recurse([&](){ return make_hls_state_tuple( M4,quad(a,1,1),tmp1, hFree); }),
            [&](){

            M5=alloc_matrix(hFree, n);
            add_matrix(p, tmp1,quad(a,0,0),quad(a,0,1));
            },
            Recurse([&](){ return make_hls_state_tuple( M5,tmp1,quad(b,1,1), hFree); }),
            [&](){

            M6=alloc_matrix(hFree, n);
            sub_matrix(p, tmp1,quad(a,1,0),quad(a,0,0));
            add_matrix(p, tmp2,quad(b,0,0),quad(b,0,1));
            },
            Recurse([&](){ return make_hls_state_tuple( M6,tmp1,tmp2, hFree); }),
            [&](){

            M7=alloc_matrix(hFree, n);
            sub_matrix(p, tmp1,quad(a,0,1),quad(a,1,1));
            add_matrix(p, tmp2,quad(b,1,0),quad(b,1,1));
            },
            Recurse([&](){ return make_hls_state_tuple( M7,tmp1,tmp2, hFree); }),
            [&](){

            add_sub_add_matrix(p, quad(dst,0,0), M1, M4, M5, M7);
            add_matrix(p, quad(dst,0,1), M3, M5);
            add_matrix(p, quad(dst,1,0), M2, M4);
            add_sub_add_matrix(p, quad(dst,1,1), M1,M3,M2,M6);
            }
        ),
        dst, a, b, hFree,
        n, tmp1, tmp2,
        M1, M2, M3, M4, M5, M6, M7
    );
}

uint32_t iglobalMem[1<<20];

template<class TImpl>
bool test_strassen_indexed(TImpl strassen_indexed)
{

    ifree_region_t hFree=0;
    uint32_t *p=iglobalMem;

    const unsigned n=256;

    imatrix_t a=alloc_matrix(hFree, n);
    imatrix_t b=alloc_matrix(hFree, n);

    imatrix_t ref=alloc_matrix(hFree, n);

    uint32_t f_rand=1;

    for(unsigned r=0;r<n;r++){
        for(unsigned c=0;c<n;c++){
            // Keep the values small so that it is exact
            set(p, a,r,c,f_rand);
            f_rand=f_rand+1;
            set(p, b,r,c,-f_rand);
            f_rand=f_rand+2;
        }
    }

    for(unsigned r=0;r<n;r++){
        for(unsigned c=0;c<n;c++){
            //printf(" %g", get(p, a,r,c));
        }
        //printf("\n");
    }
    //printf("\n");

    for(unsigned r=0;r<n;r++){
        for(unsigned c=0;c<n;c++){
            //printf(" %g", get(p, b,r,c));
        }
        //printf("\n");
    }

    //printf("Begin standard mul...\n");
    mul_matrix(p, ref, a, b);
    //printf("Begin strassen mul...\n");
    strassen_indexed(p, got, a, b, hFree);

    for(unsigned r=0;r<n;r++){
        for(unsigned c=0;c<n;c++){
            //printf(" %g", get(p, ref,r,c));
        }
        //printf("\n");
    }

    for(unsigned r=0;r<n;r++){
        for(unsigned c=0;c<n;c++){
            //printf(" %g", get(p, got,r,c));
        }
        //printf("\n");
    }

    //printf("Begin check...\n");
    bool ok=true;
    for(unsigned r=0;r<n;r++){
        for(unsigned c=0;c<n;c++){
            uint32_t rr=get(p, ref,r,c);
            uint32_t gg=get(p, got,r,c);
            //printf("%d, %d : %g ref=%g\n", r,c, gg, rr);
            if( rr!=gg ){
                //printf("  fail\n");
                ok=false;
            }
        }
    }
    return ok;
}

}; // hls_recurse

#endif


#ifndef strassen_indexed_v2_man_hpp
#define strassen_indexed_v2_man_hpp

#include "hls_recurse/state_machine_self_recursion.hpp"

#include "hls_recurse/examples/strassen_indexed_v2.hpp"

namespace hls_recurse
{

void f2_strassen_indexed_v2_man(uint32_t *p, ipmatrix_t &_dst, const ipmatrix_t &_a, const ipmatrix_t &_b, ipfree_region_t _hFree)
{
    man_strassen_indexed_v2(p,_dst,_a,_b,_hFree);
}

template<class TImpl>
bool test_strassen_indexed_v2_man(TImpl strassen_indexed_v2,bool logEvents=false)
{
    return test_strassen_indexed_v2(strassen_indexed_v2,logEvents);
}

template<class TImpl>
int harness_strassen_indexed_v2_man(TImpl strassen_indexed_v2)

{
    return harness_strassen_indexed_v2(strassen_indexed_v2);
}


template<class TBindings...>
hls_bindings_tuple<TBindings...> Inputs(TBindings &...bindings)
{
    return hls_bindings_tuple<TBindings...>(...bindings);
}

template<class TBindings...>
hls_bindings_tuple<TBindings...> Locals(TBindings &...locals)
{
    return hls_bindings_tuple<TBindings...>(...locals);
}

template<class TRet, class TImpl, class ...TState>
TRet run_function(
    const TParams &params,
    const TLocals &locals
    const TImpl &...body
)
{
    typedef CallStack<TRet, TState...> call_stack_t;

	typename call_stack_t::stack_entry_t stack[1024];

	call_stack_t call_stack(stack, state...);

	unsigned length=body.total_state_count;

    call_stack.SetContext(make_hls_state_tuple(decay_val(state)...));

	unsigned s=0;
	while(1){
  		if(
			(s==length) // implicit return
			||
			(s==StateCode_Return) // explicit return
		){
			if(call_stack.IsEmpty()){
				// end of the state machine, no more context. Return
				break;
			}else{
				// end of the state machine, more context. pop to previous frame
				s=call_stack.PopContext();

			}
		}else{
			const traits_t Traits = (traits_t)(InheritedTrait_SequenceEnd|InheritedTrait_ReturnPosition);

            s=body.template step<0,Traits,call_stack_t>(s, call_stack);


#ifndef sequence_perf_hpp
#define sequence_perf_hpp

// Get step
#include "while_perf.hpp"

namespace hls_recurse
{

uint32_t sequence_perf_native(uint32_t x)
{
    uint32_t i=0xCCCCCCCCul;

    while(x>1000){
        x=step(x);
        i=i+1;
        i=i^0x12345678;
        i=i+2;
        i=i^0x12345678;
        i=i+3;
        i=i^0x12345678;
        i=i+4;
        i=i^0x12345678;

    }
    return i;
}

uint32_t sequence_perf_sm(uint32_t x)
{
    uint32_t i=0xCCCCCCCCul;

    auto body=Sequence(
        [&](){ i=i+1; },

        [&](){ i=i+2; },
<TARGET>
        [&](){ i=i+3; },
        [&](){ i=i^0x12345678ul; },
        [&](){ i=i+4; },
        [&](){ i=i^0x12345678ul; }
    );

    while(x>1000){
        x=step(x);
        run_state_machine(body);
    }
    return i;
}

template<class T>
bool test_sequence_perf(T sequence_perf)
{
    uint32_t n=0xCCCCCCCCul; // Requires ~ 2000000 iterations
    uint32_t res=sequence_perf(n);
    printf("n=%u, res=%u\n", n, res);
    return res==4060911068;
}

}; // hls_recurse

#endif


#include "hls_recurse/state_machine_self_recursion.hpp"

#include <cstdio>
#include <vector>
#include <cstdlib>
#include <complex>
#include <iostream>

#include "hls_recurse/utility.hpp"

using namespace hls_recurse;

void test1()
{
    uint32_t s1=10;

    generic_context_t<hls_state_tuple<uint32_t> > storage[16];

    v0::CallStack<void,uint32_t> stack(storage, s1);

    stack.PushContext(100);
    s1=5;
    stack.PushContext(2000);
    s1=7;

    assert(stack.PopContext()==2000);
    assert(s1==5);
    assert(stack.PopContext()==100);
    assert(s1==10);
}

void test2()
{
    uint32_t s1=10;

    generic_context_t<hls_state_tuple<uint32_t,float> > storage[16];
    v0::CallStack<void,uint32_t,float> stack(storage, s1,s2);

    stack.PushContext(100);
    s1=5;
    s2=50.0;
    stack.PushContext(2000);
    s1=7;
    s2=70.0;

    assert(stack.PopContext()==2000);
    assert(s1==5);
    assert(s2==50.0);
    assert(stack.PopContext()==100);
    assert(s1==10);
    assert(s2==100.0);
}

void test3()
{
    uint32_t s1=10;
    float s2=100.0;

    generic_context_t<hls_state_tuple<uint32_t,float> > storage[16];
    v0::CallStack<void,uint32_t,float> stack(storage,s1,s2);

    auto x1=[](){
        return make_hls_state_tuple(uint32_t(5), float(50.0));
    };
    RecurseStep<decltype(x1)> step1(x1);
    unsigned n=step1.step<2000,(traits_t)0>(2000, stack);
    assert(n==0);

    auto x2=[](){
        return make_hls_state_tuple(uint32_t(7), float(70.0));
    };
    RecurseStep<decltype(x2)> step2(x2);
    n=step2.step<3000,(traits_t)0>(3000, stack);
    assert(n==0);

    assert(stack.PopContext()==3001);
    assert(s1==5);
    assert(s2==50.0);

    assert(stack.PopContext()==2001);
    assert(s1==10);
    assert(s2==100.0);
}

class SumV0
    : public Function<SumV0, void, uint32_t,float*>
{
private:
    uint32_t n;
    float *f;
public:
    template<class TVisitor>
    void VisitBody(TVisitor visitor)
    {
        visitor(
            IfElse([&](){ return n>1; },
                Sequence(
                    Recurse([&](){ return make_hls_state_tuple(n/2, f); }),
                    Recurse([&](){ return make_hls_state_tuple(n-(n/2), f+n/2); }),
                    [&](){  f[0] += f[n/2];  }
                ),Sequence(
                    [](){ fprintf(stderr, "Base case\n"); }
                )
            )
        );
    }

    SumV0(stack_entry_t *stack)
        : function_base_t(*this, stack, n, f)
    {}
};

void test4()
{
    uint32_t n=4;
    float x[4]={1.0, 2.0, 3.0, 4.0};

    SumV0::stack_entry_t stack[1024];
    SumV0 sumv0(stack);

    sumv0(n,x);

    assert(x[0]==10);
}

int main()
{
    uint64_t a, b;

    test1();
    test2();
    test3();
    test4();

    fprintf(stderr, "\nSuccess\n");
    return 0;
};


#include "hls_recurse/examples/ackerman.hpp"

using namespace hls_recurse;

    return test_ackerman(vhls_ackerman);
};

uint32_t vhls_ackerman(uint32_t m, uint32_t n)
{
    return f2_ackerman(m,n);
}


    int failed=0;
    for(unsigned i=1; i<nRef; i++){
        uint32_t got=vhls_fib(i);
        printf("got=%u\n", got);
        if(got!=aRef[i]){
            failed++;
        }
    }

    return failed==0;
}

int main()
{
	return test_fib() ? 0 : 1;
};


#include "hls_recurse/examples/sudoku.hpp"

using namespace hls_recurse;

bool vhls_sudoku(int puzzle[81])
{
    #pragma HLS INTERFACE ap_memory depth=81 port=puzzle
    return f2_sudoku(puzzle);
}

int main()

{
    return test_sudoku(vhls_sudoku);
};


#include "hls_recurse/examples/sort_indexed.hpp"

#include <stdlib.h>

using namespace hls_recurse;

int main()
{

    fprintf(stderr, "Pass\n");

    return 0;
};

    if(!test_sort_indexed(man_sort_indexed)){
        fprintf(stderr, "SORT_INDEXED/manual failed.\n");
    }


#include "hls_recurse/examples/sort.hpp"

#include <stdlib.h>

using namespace hls_recurse;

int main()
{

    if(!test_sort(f2_sort)){
        fprintf(stderr, "SORT/state2 failed.\n");
    }

    fprintf(stderr, "Pass\n");

    return 0;
};

    if(!test_sort(man_sort)){
        fprintf(stderr, "SORT/manual failed.\n");
    }


typedef float in_float_t;
typedef float out_float_t;
typedef float inout_float_t;

#define N 32

void covariance(inout_float_t data[1024], inout_float_t cov[1024]);


void gramSchmidt(inout_float_t a[1024], inout_float_t r[1024],
                 inout_float_t q[1024]);


typedef int in_int_t;
typedef int out_int_t;
typedef int inout_int_t;

void los(in_int_t obstacles_0[1024], in_int_t obstacles_1[1024],
         in_int_t obstacles_2[1024], in_int_t obstacles_3[1024],
         in_int_t obstacles_4[1024], in_int_t obstacles_5[1024],
         in_int_t obstacles_6[1024], in_int_t obstacles_7[1024],
         out_int_t results_0[1024], out_int_t results_1[1024],

         out_int_t results_2[1024], out_int_t results_3[1024],
         out_int_t results_4[1024], out_int_t results_5[1024],


typedef int in_int_t;
typedef int out_int_t;
typedef int inout_int_t;
typedef float in_float_t;
typedef float out_float_t;
typedef float inout_float_t;

#define N 1024
#define M 3

void levmarq(in_int_t ny, in_float_t dysq[N], in_float_t y[N], in_int_t npar,
             inout_float_t g[M], inout_float_t d[M], inout_float_t h[M][M]);


/*

  Benchmark:	BNNKernel
  FileName:		inlined.cpp
  Author:		Jianyi Cheng
  Date:			12 Sep 2019

*/

#include "bnn.h"

void inlined(int addr_in[10000], int alpha, int w[10000], int addr_out[10000], int data[10000], int in[10000], int mean[10000]){
  int lut, m,i,j,k, x, y, z, temp;

  for (i=0; i<100; i++){
	for (j=0;j<100;j++){
		x = i*100+j;
		lut=in[x]^w[x];
		data[x] += lut*alpha;
	}

		  m=mean[y];
		  temp = data[y];
		  if (temp > 0)
			z = temp -m;
		  else
			z = temp +m;
		  data[y] = z;
		}

	}
  }
}


/*

  Benchmark:		gSum
  FileName:		gSum_tb.cpp
  Author:		Jianyi Cheng
  Date:			12 Sep 2019

*/

#include <iostream>
#include "gSum.h"
#define K 100

int main(){


/*

  Benchmark:      sparseMatrixPower
  FileName:       smm_tb.cpp
  Author:         Jianyi Cheng
  Date:           12 Sep 2019

*/

#include "smm.h"
#include <iostream>

int main(){
  int data[200], az[100], w[10000], data1[200];
  int temp;

  for(int i=0; i<100; i++){
    data[i] = 1;
    data[i+100] = 0;
    az[i] = i%5;
  }

  for(int i=0; i<10000; i++){
    w[i] = i%10;
  }

  smm(data, az, w);

  for (int j=0; j<100; j++){
    temp = az[j];
    if (temp != 1){
      for (int i=0; i<100; i++){
        data1[i+100] += w[i*100+j]*data[i];
      }
    }
  }

  int res = 0;
  for(int i = 0; i< 200; i++)
    res += (data[i] == data1[i]);

  if (res = 200)
    return 0;

  else {
    std::cout << res << "\n";
    return 1;
  }