From ee5f32a3824ad95b53990e81e963e2cae54bff0f Mon Sep 17 00:00:00 2001 From: Nikos Nikoleris Date: Fri, 3 Apr 2020 12:07:13 +0100 Subject: [PATCH] sim: Add function that returns all variables in a MathExpr This changes adds support for retrieving all variables in a math expression. The added function can be called in all valid expressions and will return the variables in a vector of strings. Change-Id: I086ba04aa1f798400c97a0b6bf982018a2457c64 Signed-off-by: Nikos Nikoleris Reviewed-on: https://gem5-review.googlesource.com/c/public/gem5/+/27889 Reviewed-by: Bobby R. Bruce Maintainer: Jason Lowe-Power Tested-by: kokoro --- src/sim/mathexpr.cc | 16 +++++++++++++++- src/sim/mathexpr.hh | 25 ++++++++++++++++++++++--- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/src/sim/mathexpr.cc b/src/sim/mathexpr.cc index f80c53582..0cbcd90f3 100644 --- a/src/sim/mathexpr.cc +++ b/src/sim/mathexpr.cc @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 ARM Limited + * Copyright (c) 2016, 2020 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall @@ -174,3 +174,17 @@ MathExpr::toStr(Node *n, std::string prefix) const { return ret; } +void +MathExpr::getVariables(const Node *n, + std::vector &variables) const +{ + if (!n || n->op == sValue || n->op == nInvalid) { + return; + } else if (n->op == sVariable) { + variables.push_back(n->variable); + } else { + getVariables(n->l, variables); + getVariables(n->r, variables); + } +} + diff --git a/src/sim/mathexpr.hh b/src/sim/mathexpr.hh index b8db73926..3dfe2b829 100644 --- a/src/sim/mathexpr.hh +++ b/src/sim/mathexpr.hh @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 ARM Limited + * Copyright (c) 2016, 2020 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall @@ -42,6 +42,7 @@ #include #include #include +#include class MathExpr { public: @@ -66,6 +67,22 @@ class MathExpr { */ double eval(EvalCallback fn) const { return eval(root, fn); } + /** + * Return all variables in the this expression. + * + * This function starts from the root node and traverses all nodes + * while adding the variables it finds to a vector. Returns the + * found variables in a vector of strings + * + * @return A Vector with the names of all variables + */ + std::vector getVariables() const + { + std::vector vars; + getVariables(root, vars); + return vars; + } + private: enum Operator { bAdd, bSub, bMul, bDiv, bPow, uNeg, sValue, sVariable, nInvalid @@ -119,8 +136,10 @@ class MathExpr { /** Eval a node */ double eval(const Node *n, EvalCallback fn) const; + + /** Return all variable reachable from a node to a vector of + * strings */ + void getVariables(const Node *n, std::vector &vars) const; }; #endif - - -- 2.30.2