Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.160.70 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796236867; b=4xykmWlmFsNEPoBFcs2On/BvFm0JU5VzoW7s3ym5mzZYZ78Rml8Im2Jr3vzzZRG3hSUk tMb5y2T+qXZivjjgoCtj8da5WL5E9VQxKYAFVLhPN39GJfMj280eYmBRXWPHun1RN11jJ 5mlFsqd71vGzMbh+GgZMeX4MGAnIPzwwNqMUZp+/4hRoPM2xNEqpThAT/SjfEuWsOWPnR fLnMqiw4H/g7B5Xg+4j5hvVt+nkJ2xXEG0EE35wvJODVhlR9a3ykY5iHbLZqZI7tVo1mt GjF1+PUaBP770T14jrx184ipOuJlFYQxLvWJtVFxVgsLcvY08Ey+eRQGZmxZ1XL7ilA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796236867; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=t0Sv6g27me1qFKkmfB857dpu9EdFKGwUgR7MLDRWo3c=; b=pO9QC028jb3fcMbbJl8LYhpMCAnMtXD2N2/HfAaaUbGMEMU0/68S61rE/91SqJIvFXsP +e2eMMRdhO0xEG8Fz+z42V6Tn2dqtEUSJHWhDU7bgUv2clBERDQaN5YIhmbhIsryYrTT+ 5/rmqIvojia52pkr3UW12wZmybLXfFgfXkSLpn4FZYyGcadSO+qTMddO1rkNU0LIu9QwW 5RdiP7yISJprhliPdzVt4KtCQToxvKNltliUxYtgmCcxWi0YqwdPptFlUSCffD5YsgGEM OZjxO93r6eq8+EhtR0In/UGHwQg9orMbgRF8gE7nRS3JsdlkrVtBunDvXXDp5kuWMsg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b="FGNnSbT/"; arc=none smtp.remote-ip=209.85.160.70 Received: from mail-oa1-f70.google.com (mail-oa1-f70.google.com [209.85.160.70]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E1C0C606A32F for ; Wed, 2 Dec 2026 18:40:55 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E1C0C606A32F Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=FGNnSbT/ Received: by mail-oa1-f70.google.com with SMTP id 586e51a60fabf-46ac13882ccso8360593fac.1 for ; Wed, 02 Dec 2026 10:40:55 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1796236855; x=1796841655; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=t0Sv6g27me1qFKkmfB857dpu9EdFKGwUgR7MLDRWo3c=; b=FGNnSbT/stP9ZuDvT5tthGHRbWbr4hXb2846EYSUv8/k0n1hmxmKrPvSKtmFOkupqG gDE3I7I9ugH/KaDo+AZSwFN2Bcoh8/qKNL06IOi1aQYhPS/WkilGaeeKp47UpnuMPNB/ noNJsRcmLpqn55Mnf/EFSEqrRQ/K4nZ3WWr5btN7dSUxUPdwSn9PwoGWOPb8f0CAKJDN neFmNVv/bCERAsvaNo8mQtoi/GGj6zWSQJ8DGpVD5e2qBzN55XpWGYR7rgv1oqm9Yhae Feb/PfH+gVettb1r9LbkhGulJN73HCEHoBenlo3BVGlOJCdZrH9z1TX0pQwHHvGkCEBM w3hQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796236855; x=1796841655; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=t0Sv6g27me1qFKkmfB857dpu9EdFKGwUgR7MLDRWo3c=; b=l5yDXlf4sB8yd1Dqlp2X52kK4fa0fC26WWGPnBBhf0LaiYywtzByp5vn1xszOwH5bk uKwf5aFZehcQyb2K7qVcfihVir4Fmhy1WM5nxS2v+dAuCQA9cOiXxgb5aFpsADUJPc75 NNwFe4tpI4pBPIvYuMLpilZRxEJYcIhhzqE4An/wEDb5+ApkthlxfCNb31+9rTzUG4n5 kl1OuiSO86sjZ1BEkLSof5OGUqtBXP8UGnrSu4jYDz0A9sH/Y3LNcWo0huo/4ThcRGYz vy93sLso13rsLy3vS8/8aQQnCEI55VZYWD1seCiOeEcefq4s1Rgyn0OmuMYFpdOuOGDg ORSQ== X-Forwarded-Encrypted: i=1; AL+hErEM6PWwBmp9jNDhx9D9YpcY1eq1LBS5nn3qX9ic0kqiYfOvABS3fmOp+uSexfV++6pdSyvcQBwFQf3Z/+9AZZp0@vger.kernel.org X-Gm-Message-State: APuU4Z+0E5zB2n8QvZWogkvM/wlSyawbkwok/j8XVXe0pce4uokLXrDP hs/AQpEkHWv8HYHdYdSdw7tiXEkeQ9RU4JqbwWnoCMbbb7aYHrWKWO5QquZbwhJyTymdXo4VUOh nrAyHwYWN/A== X-Received: from oiav7-n2.prod.google.com ([2002:a05:6808:8587:20b0:543:3025:5ff4]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6808:c1b0:b0:539:ad19:d0cf with SMTP id 5614622812f47-57a09c11039mr38023213b6e.20.1796236854604; Wed, 02 Dec 2026 10:40:54 -0800 (PST) Date: Wed, 2 Dec 2026 10:40:07 -0800 In-Reply-To: X-Mailing-List: linux-perf-users@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: X-Mailer: git-send-email 2.56.1.911.g883d8bcb20-goog Message-ID: Subject: [PATCH v2 02/36] perf pmu-events: Fix Simplify() and Equals() bugs in metric.py From: Ian Rogers To: Peter Zijlstra , Ingo Molnar , Arnaldo Carvalho de Melo , Namhyung Kim , Mark Rutland , Alexander Shishkin , Jiri Olsa , Adrian Hunter , James Clark Cc: Dapeng Mi , Zide Chen , Thomas Falcon , Chun-Tse Shao , Lalit Maganti , linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org, Ian Rogers Content-Type: text/plain; charset="UTF-8" Fix constant folding and equality bugs in metric.py: - Operator.Simplify(): evaluate constant expressions using Decimal matching perf's expr.y semantics instead of ast.literal_eval(), which raises ValueError on *, /, %, <, >, &, |, and ^, and check isinstance(lhs, Constant) on the simplified lhs rather than self.lhs. - Function.Simplify(): add the missing return on d_ratio constant folding and evaluate d_ratio/min/max directly instead of calling ast.literal_eval(). - Function.Equals(): handle one-sided rhs is None instead of returning True or raising AttributeError. - Constant.__init__(): normalize -0 to 0. Add unit tests covering these cases and aggr_nr() parsing. Fixes: 40769665b63d ("perf jevents: Parse metrics during conversion") Fixes: 3241cd11d9a0 ("perf jevents metric: Correct Function equality") Signed-off-by: Ian Rogers --- tools/perf/pmu-events/metric.py | 50 ++++++++++++++++++++++------ tools/perf/pmu-events/metric_test.py | 40 ++++++++++++++++++++++ 2 files changed, 80 insertions(+), 10 deletions(-) diff --git a/tools/perf/pmu-events/metric.py b/tools/perf/pmu-events/metric.py index f5d81eccd5c3..04bb29ce7722 100644 --- a/tools/perf/pmu-events/metric.py +++ b/tools/perf/pmu-events/metric.py @@ -273,9 +273,32 @@ class Operator(Expression): lhs = self.lhs.Simplify() rhs = self.rhs.Simplify() if isinstance(lhs, Constant) and isinstance(rhs, Constant): - return Constant(ast.literal_eval(lhs.value + self.operator + rhs.value)) - - if isinstance(self.lhs, Constant): + l = decimal.Decimal(lhs.value) + r = decimal.Decimal(rhs.value) + if self.operator == '|': + return Constant(0 if l == 0 and r == 0 else 1) + if self.operator == '&': + return Constant(1 if l != 0 and r != 0 else 0) + if self.operator == '^': + return Constant(1 if (l == 0) != (r == 0) else 0) + if self.operator == '<': + return Constant(1 if l < r else 0) + if self.operator == '>': + return Constant(1 if l > r else 0) + if self.operator == '+': + return Constant(l + r) + if self.operator == '-': + return Constant(l - r) + if self.operator == '*': + return Constant(l * r) + if self.operator == '/' and r != 0: + return Constant(l / r) + if self.operator == '%' and int(r) != 0: + li, ri = int(l), int(r) + # Match C integer remainder (truncating toward zero) used by perf's expr.y. + return Constant(li - int(li / ri) * ri) + + if isinstance(lhs, Constant): if self.operator in ('+', '|') and lhs.value == '0': return rhs @@ -395,11 +418,16 @@ class Function(Expression): lhs = self.lhs.Simplify() rhs = self.rhs.Simplify() if self.rhs else None if isinstance(lhs, Constant) and isinstance(rhs, Constant): + l = decimal.Decimal(lhs.value) + r = decimal.Decimal(rhs.value) if self.fn == 'd_ratio': - if rhs.value == '0': + if r == 0: return Constant(0) - Constant(ast.literal_eval(f'{lhs} / {rhs}')) - return Constant(ast.literal_eval(f'{self.fn}({lhs}, {rhs})')) + return Constant(l / r) + if self.fn == 'min': + return lhs if l <= r else rhs + if self.fn == 'max': + return lhs if l >= r else rhs return Function(self.fn, lhs, rhs) @@ -410,9 +438,9 @@ class Function(Expression): def Equals(self, other: Expression) -> bool: if isinstance(other, Function): result = self.fn == other.fn and self.lhs.Equals(other.lhs) - if self.rhs: - result = result and self.rhs.Equals(other.rhs) - return result + if self.rhs is None or other.rhs is None: + return result and self.rhs is other.rhs + return result and self.rhs.Equals(other.rhs) return False def Substitute(self, name: str, expression: Expression) -> Expression: @@ -494,10 +522,12 @@ class MetricRef(Expression): class Constant(Expression): """A constant within the expression tree.""" - def __init__(self, value: Union[float, str]): + def __init__(self, value: Union[float, str, decimal.Decimal]): ctx = decimal.Context() ctx.prec = 20 dec = ctx.create_decimal(repr(value) if isinstance(value, float) else value) + if dec == 0: + dec = decimal.Decimal(0) self.value = dec.normalize().to_eng_string() self.value = self.value.replace('+', '') self.value = self.value.replace('E', 'e') diff --git a/tools/perf/pmu-events/metric_test.py b/tools/perf/pmu-events/metric_test.py index 8acfe4652b55..0221ac746ec2 100755 --- a/tools/perf/pmu-events/metric_test.py +++ b/tools/perf/pmu-events/metric_test.py @@ -4,6 +4,7 @@ import unittest from metric import Constant from metric import Event from metric import Expression +from metric import Function from metric import ParsePerfJson from metric import RewriteMetricsInTermsOfOthers @@ -65,6 +66,16 @@ class TestMetricExpressions(unittest.TestCase): after = before self.assertEqual(ParsePerfJson(before).ToPerfJson(), after) + def test_ParseAggrNr(self): + before = 'aggr_nr(UNC_CHA_CLOCKTICKS)' + self.assertEqual(ParsePerfJson(before).ToPerfJson(), before) + + before = 'a / pcu_0@UNC_P_CLOCKTICKS@ * aggr_nr(pcu_0@UNC_P_CLOCKTICKS@)' + self.assertEqual(ParsePerfJson(before).ToPerfJson(), before) + + before = 'a / (b / aggr_nr(c))' + self.assertEqual(ParsePerfJson(before).ToPerfJson(), before) + def test_IfElseTests(self): # if-else needs rewriting to Select and back. before = r'Event1 if #smt_on else Event2' @@ -160,6 +171,35 @@ class TestMetricExpressions(unittest.TestCase): after = '0 * SLOTS' self.assertEqual(ParsePerfJson(before).Simplify().ToPerfJson(), after) + # Constant folding for non-add/sub operators and simplified lhs. + self.assertEqual((Constant(2) * Constant(3)).Simplify().ToPerfJson(), '6') + self.assertEqual((Constant(6) / Constant(4)).Simplify().ToPerfJson(), '1.5') + self.assertEqual((Constant(7) % Constant(4)).Simplify().ToPerfJson(), '3') + self.assertEqual((Constant(1) < Constant(2)).Simplify().ToPerfJson(), '1') + self.assertEqual((Constant(1) > Constant(2)).Simplify().ToPerfJson(), '0') + self.assertEqual((Constant(2) & Constant(3)).Simplify().ToPerfJson(), '1') + self.assertEqual((Constant(2) & Constant(0)).Simplify().ToPerfJson(), '0') + self.assertEqual((Constant(0) | Constant(5)).Simplify().ToPerfJson(), '1') + self.assertEqual((Constant(2) ^ Constant(3)).Simplify().ToPerfJson(), '0') + self.assertEqual((Constant(2) ^ Constant(0)).Simplify().ToPerfJson(), '1') + self.assertEqual((Constant(1) / Constant(0)).Simplify().ToPerfJson(), '1 / 0') + self.assertEqual(ParsePerfJson('(0 if 1 else b) + a').Simplify().ToPerfJson(), 'a') + self.assertEqual(ParsePerfJson('(1 if 1 else b) * a').Simplify().ToPerfJson(), 'a') + + # Constant folding in Function.Simplify(). + self.assertEqual(ParsePerfJson('d_ratio(6, 4)').Simplify().ToPerfJson(), '1.5') + self.assertEqual(ParsePerfJson('d_ratio(6, 0)').Simplify().ToPerfJson(), '0') + self.assertEqual(ParsePerfJson('min(3, 5)').Simplify().ToPerfJson(), '3') + self.assertEqual(ParsePerfJson('max(3, 5)').Simplify().ToPerfJson(), '5') + + def test_FunctionEquals(self): + f1 = Function('f', Event('a')) + f2 = Function('f', Event('a'), Event('b')) + self.assertFalse(f1.Equals(f2)) + self.assertFalse(f2.Equals(f1)) + self.assertTrue(f1.Equals(Function('f', Event('a')))) + self.assertTrue(f2.Equals(Function('f', Event('a'), Event('b')))) + def test_RewriteMetricsInTermsOfOthers(self): Expression.__eq__ = lambda e1, e2: e1.Equals(e2) before = [('cpu', 'm1', ParsePerfJson('a + b + c + d')), -- 2.56.1.915.g69d5ec7298-goog