xref: /linux/tools/perf/pmu-events/metric.py (revision db5a60750133d1789c1254fcae55dbf542ef0aa6)
1# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2"""Parse or generate representations of perf metrics."""
3import ast
4import decimal
5import json
6import os
7import re
8from enum import Enum
9from typing import Dict, List, Optional, Sequence, Set, Tuple, Union
10
11all_pmus: Set[str] = set()
12all_events: Set[str] = set()
13experimental_events: Set[str] = set()
14all_events_all_models: Set[str] = set()
15
16def LoadEvents(directory: str) -> None:
17  """Populate a global set of all known events for the purpose of validating Event names"""
18  global all_events
19  global all_events_all_models
20  all_events = {
21      "context\\-switches",
22      "cpu\\-cycles",
23      "cycles",
24      "duration_time",
25      "instructions",
26  }
27  for file in os.listdir(os.fsencode(directory)):
28    filename = os.fsdecode(file)
29    if filename.endswith(".json"):
30      try:
31        with open(f"{directory}/{filename}", encoding="utf-8") as f:
32          for x in json.load(f):
33            if "Unit" in x:
34              all_pmus.add(x["Unit"])
35            if "EventName" in x:
36              all_events.add(x["EventName"])
37              if "Experimental" in x and x["Experimental"] == "1":
38                experimental_events.add(x["EventName"])
39            elif "ArchStdEvent" in x:
40              all_events.add(x["ArchStdEvent"])
41      except json.decoder.JSONDecodeError:
42        # The generated directory may be the same as the input, which
43        # causes partial json files. Ignore errors.
44        pass
45  all_events_all_models = all_events.copy()
46  for root, _, files in os.walk(directory + ".."):
47    for filename in files:
48      if filename.endswith(".json"):
49        try:
50          with open(f"{root}/{filename}", encoding="utf-8") as f:
51            for x in json.load(f):
52              if "EventName" in x:
53                all_events_all_models.add(x["EventName"])
54              elif "ArchStdEvent" in x:
55                all_events_all_models.add(x["ArchStdEvent"])
56        except json.decoder.JSONDecodeError:
57          # The generated directory may be the same as the input, which
58          # causes partial json files. Ignore errors.
59          pass
60
61
62def CheckPmu(name: str) -> bool:
63  return name in all_pmus
64
65
66def CheckEvent(name: str) -> bool:
67  """Check the event name exists in the set of all loaded events"""
68  if len(all_events) == 0:
69    # No events loaded so assume any event is good.
70    return True
71
72  if ':' in name:
73    # Remove trailing modifier.
74    name = name[:name.find(':')]
75  elif '/' in name:
76    # Name could begin with a PMU or an event, for now assume it is good.
77    return True
78
79  return name in all_events
80
81def CheckEveryEvent(*names: str) -> None:
82  """Check all the events exist in at least one json file"""
83  if len(all_events_all_models) == 0:
84    assert len(names) == 1, f"Cannot determine valid events in {names}"
85    # No events loaded so assume any event is good.
86    return
87
88  for name in names:
89    # Remove trailing modifier.
90    if ':' in name:
91      name = name[:name.find(':')]
92    elif '/' in name:
93      name = name[:name.find('/')]
94      if any([name.startswith(x) for x in ['amd', 'arm', 'cpu', 'msr', 'power', 'cha', 'uncore']]):
95        continue
96    if name not in all_events_all_models:
97      raise ValueError(f"Is {name} a named json event?")
98
99
100def IsExperimentalEvent(name: str) -> bool:
101  if ':' in name:
102    # Remove trailing modifier.
103    name = name[:name.find(':')]
104  elif '/' in name:
105    # Name could begin with a PMU or an event, for now assume it is not experimental.
106    return False
107
108  return name in experimental_events
109
110
111class MetricConstraint(Enum):
112  GROUPED_EVENTS = 0
113  NO_GROUP_EVENTS = 1
114  NO_GROUP_EVENTS_NMI = 2
115  NO_GROUP_EVENTS_SMT = 3
116
117class Expression:
118  """Abstract base class of elements in a metric expression."""
119
120  def ToPerfJson(self) -> str:
121    """Returns a perf json file encoded representation."""
122    raise NotImplementedError()
123
124  def ToPython(self) -> str:
125    """Returns a python expr parseable representation."""
126    raise NotImplementedError()
127
128  def Simplify(self):
129    """Returns a simplified version of self."""
130    raise NotImplementedError()
131
132  def HasExperimentalEvents(self) -> bool:
133    """Are experimental events used in the expression?"""
134    raise NotImplementedError()
135
136  def Equals(self, other) -> bool:
137    """Returns true when two expressions are the same."""
138    raise NotImplementedError()
139
140  def Substitute(self, name: str, expression: 'Expression') -> 'Expression':
141    raise NotImplementedError()
142
143  def __str__(self) -> str:
144    return self.ToPerfJson()
145
146  def __or__(self, other: Union[int, float, 'Expression']) -> 'Operator':
147    return Operator('|', self, other)
148
149  def __ror__(self, other: Union[int, float, 'Expression']) -> 'Operator':
150    return Operator('|', other, self)
151
152  def __xor__(self, other: Union[int, float, 'Expression']) -> 'Operator':
153    return Operator('^', self, other)
154
155  def __and__(self, other: Union[int, float, 'Expression']) -> 'Operator':
156    return Operator('&', self, other)
157
158  def __rand__(self, other: Union[int, float, 'Expression']) -> 'Operator':
159    return Operator('&', other, self)
160
161  def __lt__(self, other: Union[int, float, 'Expression']) -> 'Operator':
162    return Operator('<', self, other)
163
164  def __gt__(self, other: Union[int, float, 'Expression']) -> 'Operator':
165    return Operator('>', self, other)
166
167  def __add__(self, other: Union[int, float, 'Expression']) -> 'Operator':
168    return Operator('+', self, other)
169
170  def __radd__(self, other: Union[int, float, 'Expression']) -> 'Operator':
171    return Operator('+', other, self)
172
173  def __sub__(self, other: Union[int, float, 'Expression']) -> 'Operator':
174    return Operator('-', self, other)
175
176  def __rsub__(self, other: Union[int, float, 'Expression']) -> 'Operator':
177    return Operator('-', other, self)
178
179  def __mul__(self, other: Union[int, float, 'Expression']) -> 'Operator':
180    return Operator('*', self, other)
181
182  def __rmul__(self, other: Union[int, float, 'Expression']) -> 'Operator':
183    return Operator('*', other, self)
184
185  def __truediv__(self, other: Union[int, float, 'Expression']) -> 'Operator':
186    return Operator('/', self, other)
187
188  def __rtruediv__(self, other: Union[int, float, 'Expression']) -> 'Operator':
189    return Operator('/', other, self)
190
191  def __mod__(self, other: Union[int, float, 'Expression']) -> 'Operator':
192    return Operator('%', self, other)
193
194
195def _Constify(val: Union[bool, int, float, Expression]) -> Expression:
196  """Used to ensure that the nodes in the expression tree are all Expression."""
197  if isinstance(val, bool):
198    return Constant(1 if val else 0)
199  if isinstance(val, (int, float)):
200    return Constant(val)
201  return val
202
203
204# Simple lookup for operator precedence, used to avoid unnecessary
205# brackets. Precedence matches that of the simple expression parser
206# but differs from python where comparisons are lower precedence than
207# the bitwise &, ^, | but not the logical versions that the expression
208# parser doesn't have.
209_PRECEDENCE = {
210    '|': 0,
211    '^': 1,
212    '&': 2,
213    '<': 3,
214    '>': 3,
215    '+': 4,
216    '-': 4,
217    '*': 5,
218    '/': 5,
219    '%': 5,
220}
221
222
223class Operator(Expression):
224  """Represents a binary operator in the parse tree."""
225
226  def __init__(self, operator: str, lhs: Union[int, float, Expression],
227               rhs: Union[int, float, Expression]):
228    self.operator = operator
229    self.lhs = _Constify(lhs)
230    self.rhs = _Constify(rhs)
231
232  def Bracket(self,
233              other: Expression,
234              other_str: str,
235              rhs: bool = False) -> str:
236    """If necessary brackets the given other value.
237
238    If ``other`` is an operator then a bracket is necessary when
239    this/self operator has higher precedence. Consider: '(a + b) * c',
240    ``other_str`` will be 'a + b'. A bracket is necessary as without
241    the bracket 'a + b * c' will evaluate 'b * c' first. However, '(a
242    * b) + c' doesn't need a bracket as 'a * b' will always be
243    evaluated first. For 'a / (b * c)' (ie the same precedence level
244    operations) then we add the bracket to best match the original
245    input, but not for '(a / b) * c' where the bracket is unnecessary.
246
247    Args:
248      other (Expression): is a lhs or rhs operator
249      other_str (str): ``other`` in the appropriate string form
250      rhs (bool):  is ``other`` on the RHS
251
252    Returns:
253      str: possibly bracketed other_str
254    """
255    if isinstance(other, Operator):
256      if _PRECEDENCE.get(self.operator, -1) > _PRECEDENCE.get(
257          other.operator, -1):
258        return f'({other_str})'
259      if rhs and _PRECEDENCE.get(self.operator, -1) == _PRECEDENCE.get(
260          other.operator, -1):
261        return f'({other_str})'
262    return other_str
263
264  def ToPerfJson(self):
265    return (f'{self.Bracket(self.lhs, self.lhs.ToPerfJson())} {self.operator} '
266            f'{self.Bracket(self.rhs, self.rhs.ToPerfJson(), True)}')
267
268  def ToPython(self):
269    return (f'{self.Bracket(self.lhs, self.lhs.ToPython())} {self.operator} '
270            f'{self.Bracket(self.rhs, self.rhs.ToPython(), True)}')
271
272  def Simplify(self) -> Expression:
273    lhs = self.lhs.Simplify()
274    rhs = self.rhs.Simplify()
275    if isinstance(lhs, Constant) and isinstance(rhs, Constant):
276      return Constant(ast.literal_eval(lhs.value + self.operator + rhs.value))
277
278    if isinstance(self.lhs, Constant):
279      if self.operator in ('+', '|') and lhs.value == '0':
280        return rhs
281
282      # Simplify multiplication by 0 except for the slot event which
283      # is deliberately introduced using this pattern.
284      if self.operator == '*' and lhs.value == '0' and (
285          not isinstance(rhs, Event) or 'slots' not in rhs.name.lower()):
286        return Constant(0)
287
288      if self.operator == '*' and lhs.value == '1':
289        return rhs
290
291    if isinstance(rhs, Constant):
292      if self.operator in ('+', '|') and rhs.value == '0':
293        return lhs
294
295      if self.operator == '*' and rhs.value == '0':
296        return Constant(0)
297
298      if self.operator == '*' and rhs.value == '1':
299        return lhs
300
301    return Operator(self.operator, lhs, rhs)
302
303  def HasExperimentalEvents(self) -> bool:
304    return self.lhs.HasExperimentalEvents() or self.rhs.HasExperimentalEvents()
305
306  def Equals(self, other: Expression) -> bool:
307    if isinstance(other, Operator):
308      return self.operator == other.operator and self.lhs.Equals(
309          other.lhs) and self.rhs.Equals(other.rhs)
310    return False
311
312  def Substitute(self, name: str, expression: Expression) -> Expression:
313    if self.Equals(expression):
314      return Event(name)
315    lhs = self.lhs.Substitute(name, expression)
316    rhs = self.rhs.Substitute(name, expression)
317    return Operator(self.operator, lhs, rhs)
318
319
320class Select(Expression):
321  """Represents a select ternary in the parse tree."""
322
323  def __init__(self, true_val: Union[int, float, Expression],
324               cond: Union[int, float, Expression],
325               false_val: Union[int, float, Expression]):
326    self.true_val = _Constify(true_val)
327    self.cond = _Constify(cond)
328    self.false_val = _Constify(false_val)
329
330  def ToPerfJson(self):
331    true_str = self.true_val.ToPerfJson()
332    cond_str = self.cond.ToPerfJson()
333    false_str = self.false_val.ToPerfJson()
334    return f'({true_str} if {cond_str} else {false_str})'
335
336  def ToPython(self):
337    return (f'Select({self.true_val.ToPython()}, {self.cond.ToPython()}, '
338            f'{self.false_val.ToPython()})')
339
340  def Simplify(self) -> Expression:
341    cond = self.cond.Simplify()
342    true_val = self.true_val.Simplify()
343    false_val = self.false_val.Simplify()
344    if isinstance(cond, Constant):
345      return false_val if cond.value == '0' else true_val
346
347    if true_val.Equals(false_val):
348      return true_val
349
350    return Select(true_val, cond, false_val)
351
352  def HasExperimentalEvents(self) -> bool:
353    return (self.cond.HasExperimentalEvents() or self.true_val.HasExperimentalEvents() or
354            self.false_val.HasExperimentalEvents())
355
356  def Equals(self, other: Expression) -> bool:
357    if isinstance(other, Select):
358      return self.cond.Equals(other.cond) and self.false_val.Equals(
359          other.false_val) and self.true_val.Equals(other.true_val)
360    return False
361
362  def Substitute(self, name: str, expression: Expression) -> Expression:
363    if self.Equals(expression):
364      return Event(name)
365    true_val = self.true_val.Substitute(name, expression)
366    cond = self.cond.Substitute(name, expression)
367    false_val = self.false_val.Substitute(name, expression)
368    return Select(true_val, cond, false_val)
369
370
371class Function(Expression):
372  """A function in an expression like min, max, d_ratio."""
373
374  def __init__(self,
375               fn: str,
376               lhs: Union[int, float, Expression],
377               rhs: Optional[Union[int, float, Expression]] = None):
378    self.fn = fn
379    self.lhs = _Constify(lhs)
380    self.rhs = None
381    if rhs is not None:
382      self.rhs = _Constify(rhs)
383
384  def ToPerfJson(self):
385    if self.rhs:
386      return f'{self.fn}({self.lhs.ToPerfJson()}, {self.rhs.ToPerfJson()})'
387    return f'{self.fn}({self.lhs.ToPerfJson()})'
388
389  def ToPython(self):
390    if self.rhs:
391      return f'{self.fn}({self.lhs.ToPython()}, {self.rhs.ToPython()})'
392    return f'{self.fn}({self.lhs.ToPython()})'
393
394  def Simplify(self) -> Expression:
395    lhs = self.lhs.Simplify()
396    rhs = self.rhs.Simplify() if self.rhs else None
397    if isinstance(lhs, Constant) and isinstance(rhs, Constant):
398      if self.fn == 'd_ratio':
399        if rhs.value == '0':
400          return Constant(0)
401        Constant(ast.literal_eval(f'{lhs} / {rhs}'))
402      return Constant(ast.literal_eval(f'{self.fn}({lhs}, {rhs})'))
403
404    return Function(self.fn, lhs, rhs)
405
406  def HasExperimentalEvents(self) -> bool:
407    return (self.lhs.HasExperimentalEvents() or
408            (self.rhs is not None and self.rhs.HasExperimentalEvents()))
409
410  def Equals(self, other: Expression) -> bool:
411    if isinstance(other, Function):
412      result = self.fn == other.fn and self.lhs.Equals(other.lhs)
413      if self.rhs:
414        result = result and self.rhs.Equals(other.rhs)
415      return result
416    return False
417
418  def Substitute(self, name: str, expression: Expression) -> Expression:
419    if self.Equals(expression):
420      return Event(name)
421    lhs = self.lhs.Substitute(name, expression)
422    rhs = None
423    if self.rhs:
424      rhs = self.rhs.Substitute(name, expression)
425    return Function(self.fn, lhs, rhs)
426
427
428def _FixEscapes(s: str) -> str:
429  s = re.sub(r'([^\\]),', r'\1\\,', s)
430  return re.sub(r'([^\\])=', r'\1\\=', s)
431
432
433class Event(Expression):
434  """An event in an expression."""
435
436  def __init__(self, *args: str):
437    error = ""
438    CheckEveryEvent(*args)
439    for name in args:
440      if CheckEvent(name):
441        self.name = _FixEscapes(name)
442        return
443      if error:
444        error += " or " + name
445      else:
446        error = name
447    raise ValueError(f"No event {error} in:\n{all_events}")
448
449  def HasExperimentalEvents(self) -> bool:
450    return IsExperimentalEvent(self.name)
451
452  def ToPerfJson(self):
453    result = re.sub('/', '@', _FixEscapes(self.name))
454    return result
455
456  def ToPython(self):
457    return f'Event(r"{self.name}")'
458
459  def Simplify(self) -> Expression:
460    return self
461
462  def Equals(self, other: Expression) -> bool:
463    return isinstance(other, Event) and self.name == other.name
464
465  def Substitute(self, name: str, expression: Expression) -> Expression:
466    return self
467
468
469class MetricRef(Expression):
470  """A metric reference in an expression."""
471
472  def __init__(self, name: str):
473    self.name = _FixEscapes(name)
474
475  def ToPerfJson(self):
476    return self.name
477
478  def ToPython(self):
479    return f'MetricRef(r"{self.name}")'
480
481  def Simplify(self) -> Expression:
482    return self
483
484  def HasExperimentalEvents(self) -> bool:
485    return False
486
487  def Equals(self, other: Expression) -> bool:
488    return isinstance(other, MetricRef) and self.name == other.name
489
490  def Substitute(self, name: str, expression: Expression) -> Expression:
491    return self
492
493
494class Constant(Expression):
495  """A constant within the expression tree."""
496
497  def __init__(self, value: Union[float, str]):
498    ctx = decimal.Context()
499    ctx.prec = 20
500    dec = ctx.create_decimal(repr(value) if isinstance(value, float) else value)
501    self.value = dec.normalize().to_eng_string()
502    self.value = self.value.replace('+', '')
503    self.value = self.value.replace('E', 'e')
504
505  def ToPerfJson(self):
506    return self.value
507
508  def ToPython(self):
509    return f'Constant({self.value})'
510
511  def Simplify(self) -> Expression:
512    return self
513
514  def HasExperimentalEvents(self) -> bool:
515    return False
516
517  def Equals(self, other: Expression) -> bool:
518    return isinstance(other, Constant) and self.value == other.value
519
520  def Substitute(self, name: str, expression: Expression) -> Expression:
521    return self
522
523
524class Literal(Expression):
525  """A runtime literal within the expression tree."""
526
527  def __init__(self, value: str):
528    self.value = value
529
530  def ToPerfJson(self):
531    return self.value
532
533  def ToPython(self):
534    return f'Literal({self.value})'
535
536  def Simplify(self) -> Expression:
537    return self
538
539  def HasExperimentalEvents(self) -> bool:
540    return False
541
542  def Equals(self, other: Expression) -> bool:
543    return isinstance(other, Literal) and self.value == other.value
544
545  def Substitute(self, name: str, expression: Expression) -> Expression:
546    return self
547
548
549def min(lhs: Union[int, float, Expression], rhs: Union[int, float,
550                                                       Expression]) -> Function:
551  # pylint: disable=redefined-builtin
552  # pylint: disable=invalid-name
553  return Function('min', lhs, rhs)
554
555
556def max(lhs: Union[int, float, Expression], rhs: Union[int, float,
557                                                       Expression]) -> Function:
558  # pylint: disable=redefined-builtin
559  # pylint: disable=invalid-name
560  return Function('max', lhs, rhs)
561
562
563def d_ratio(lhs: Union[int, float, Expression],
564            rhs: Union[int, float, Expression]) -> Function:
565  # pylint: disable=redefined-builtin
566  # pylint: disable=invalid-name
567  return Function('d_ratio', lhs, rhs)
568
569
570def source_count(event: Event) -> Function:
571  # pylint: disable=redefined-builtin
572  # pylint: disable=invalid-name
573  return Function('source_count', event)
574
575
576def aggr_nr(event: Event) -> Function:
577  # pylint: disable=invalid-name
578  return Function('aggr_nr', event)
579
580
581def has_event(event: Event) -> Function:
582  # pylint: disable=redefined-builtin
583  # pylint: disable=invalid-name
584  return Function('has_event', event)
585
586def strcmp_cpuid_str(cpuid: Event) -> Function:
587  # pylint: disable=redefined-builtin
588  # pylint: disable=invalid-name
589  return Function('strcmp_cpuid_str', cpuid)
590
591class Metric:
592  """An individual metric that will specifiable on the perf command line."""
593  groups: Set[str]
594  expr: Expression
595  scale_unit: str
596  constraint: MetricConstraint
597  threshold: Optional[Expression]
598
599  def __init__(self,
600               name: str,
601               description: str,
602               expr: Expression,
603               scale_unit: str,
604               constraint: MetricConstraint = MetricConstraint.GROUPED_EVENTS,
605               threshold: Optional[Expression] = None):
606    self.name = name
607    self.description = description
608    self.expr = expr.Simplify()
609    if self.expr.HasExperimentalEvents():
610      self.description += " (metric should be considered experimental as it contains experimental events)."
611    # Workraound valid_only_metric hiding certain metrics based on unit.
612    scale_unit = scale_unit.replace('/sec', ' per sec')
613    if scale_unit[0].isdigit():
614      self.scale_unit = scale_unit
615    else:
616      self.scale_unit = f'1{scale_unit}'
617    self.constraint = constraint
618    self.threshold = threshold
619    self.groups = set()
620
621  def __lt__(self, other):
622    """Sort order."""
623    if self.name != other.name:
624      return self.name < other.name
625    if not self.expr.Equals(other.expr):
626      return self.expr.ToPerfJson() < other.expr.ToPerfJson()
627    return self.description < other.description
628
629  def AddToMetricGroup(self, group):
630    """Callback used when being added to a MetricGroup."""
631    if group.name:
632      self.groups.add(group.name)
633
634  def Flatten(self) -> Set['Metric']:
635    """Return a leaf metric."""
636    return set([self])
637
638  def ToPerfJson(self) -> Dict[str, str]:
639    """Return as dictionary for Json generation."""
640    result = {
641        'MetricName': self.name,
642        'MetricGroup': ';'.join(sorted(self.groups)),
643        'BriefDescription': self.description,
644        'MetricExpr': self.expr.ToPerfJson(),
645        'ScaleUnit': self.scale_unit
646    }
647    if self.constraint != MetricConstraint.GROUPED_EVENTS:
648      result['MetricConstraint'] = self.constraint.name
649    if self.threshold:
650      result['MetricThreshold'] = self.threshold.ToPerfJson()
651
652    return result
653
654  def ToMetricGroupDescriptions(self, _root: bool = True) -> Dict[str, str]:
655    return {}
656
657class MetricGroup:
658  """A group of metrics.
659
660  Metric groups may be specificd on the perf command line, but within
661  the json they aren't encoded. Metrics may be in multiple groups
662  which can facilitate arrangements similar to trees.
663  """
664
665  def __init__(self, name: str,
666               metric_list: Sequence[Union[Optional[Metric], Optional['MetricGroup']]],
667               description: Optional[str] = None):
668    self.name = name
669    self.metric_list = []
670    self.description = description
671    for metric in metric_list:
672      if metric:
673        self.metric_list.append(metric)
674        metric.AddToMetricGroup(self)
675
676  def AddToMetricGroup(self, group):
677    """Callback used when a MetricGroup is added into another."""
678    for metric in self.metric_list:
679      metric.AddToMetricGroup(group)
680
681  def Flatten(self) -> Set[Metric]:
682    """Returns a set of all leaf metrics."""
683    result: Set[Metric] = set()
684    for x in self.metric_list:
685      result = result.union(x.Flatten())
686
687    return result
688
689  def ToPerfJson(self) -> List[Dict[str, str]]:
690    result = []
691    for x in sorted(self.Flatten()):
692      result.append(x.ToPerfJson())
693    return result
694
695  def ToMetricGroupDescriptions(self, _root: bool = True) -> Dict[str, str]:
696    result = {self.name: self.description} if self.description else {}
697    for x in self.metric_list:
698      result.update(x.ToMetricGroupDescriptions(False))
699    return result
700
701  def __str__(self) -> str:
702    return str(self.ToPerfJson())
703
704
705def JsonEncodeMetric(x: MetricGroup):
706  class MetricJsonEncoder(json.JSONEncoder):
707    """Special handling for Metric objects."""
708
709    def default(self, o):
710      if isinstance(o, Metric) or isinstance(o, MetricGroup):
711        return o.ToPerfJson()
712      return json.JSONEncoder.default(self, o)
713
714  return json.dumps(x, indent=2, cls=MetricJsonEncoder)
715
716
717def JsonEncodeMetricGroupDescriptions(x: MetricGroup):
718  return json.dumps(x.ToMetricGroupDescriptions(), indent=2)
719
720
721class _RewriteIfExpToSelect(ast.NodeTransformer):
722  """Transformer to convert if-else nodes to Select expressions."""
723
724  def visit_IfExp(self, node):
725    # pylint: disable=invalid-name
726    self.generic_visit(node)
727    call = ast.Call(
728        func=ast.Name(id='Select', ctx=ast.Load()),
729        args=[node.body, node.test, node.orelse],
730        keywords=[])
731    ast.copy_location(call, node.test)
732    return call
733
734
735def ParsePerfJson(orig: str) -> Expression:
736  """A simple json metric expression decoder.
737
738  Converts a json encoded metric expression by way of python's ast and
739  eval routine. First tokens are mapped to Event calls, then
740  accidentally converted keywords or literals are mapped to their
741  appropriate calls. Python's ast is used to match if-else that can't
742  be handled via operator overloading. Finally the ast is evaluated.
743
744  Args:
745    orig (str): String to parse.
746
747  Returns:
748    Expression: The parsed string.
749  """
750  # pylint: disable=eval-used
751  py = orig.strip()
752  # First try to convert everything that looks like a string (event name) into Event(r"EVENT_NAME").
753  # This isn't very selective so is followed up by converting some unwanted conversions back again
754  py = re.sub(r'([a-zA-Z][^-+/\* \\\(\),]*(?:\\.[^-+/\* \\\(\),]*)*)',
755              r'Event(r"\1")', py)
756  # If it started with a # it should have been a literal, rather than an event name
757  py = re.sub(r'#Event\(r"([^"]*)"\)', r'Literal("#\1")', py)
758  # Fix events wrongly broken at a ','
759  while True:
760    prev_py = py
761    py = re.sub(r'Event\(r"([^"]*)"\),Event\(r"([^"]*)"\)', r'Event(r"\1,\2")', py)
762    if py == prev_py:
763      break
764  # Convert accidentally converted hex constants ("0Event(r"xDEADBEEF)"") back to a constant,
765  # but keep it wrapped in Event(), otherwise Python drops the 0x prefix and it gets interpreted as
766  # a double by the Bison parser
767  py = re.sub(r'0Event\(r"[xX]([0-9a-fA-F]*)"\)', r'Event("0x\1")', py)
768  # Convert accidentally converted scientific notation constants back
769  py = re.sub(r'([0-9]+)Event\(r"(e[0-9]*)"\)', r'\1\2', py)
770  # Convert all the known keywords back from events to just the keyword
771  keywords = ['if', 'else', 'min', 'max', 'd_ratio', 'source_count', 'aggr_nr', 'has_event', 'strcmp_cpuid_str']
772  for kw in keywords:
773    py = re.sub(rf'Event\(r"{kw}"\)', kw, py)
774  try:
775    parsed = ast.parse(py, mode='eval')
776  except SyntaxError as e:
777    raise SyntaxError(f'Parsing expression:\n{orig}') from e
778  _RewriteIfExpToSelect().visit(parsed)
779  parsed = ast.fix_missing_locations(parsed)
780  return _Constify(eval(compile(parsed, orig, 'eval')))
781
782def RewriteMetricsInTermsOfOthers(metrics: List[Tuple[str, str, Expression]]
783                                  )-> Dict[Tuple[str, str], Expression]:
784  """Shorten metrics by rewriting in terms of others.
785
786  Args:
787    metrics (list): pmus, metric names and their expressions.
788  Returns:
789    Dict: mapping from a pmu, metric name pair to a shortened expression.
790  """
791  updates: Dict[Tuple[str, str], Expression] = dict()
792  for outer_pmu, outer_name, outer_expression in metrics:
793    if outer_pmu is None:
794      outer_pmu = 'cpu'
795    updated = outer_expression
796    while True:
797      for inner_pmu, inner_name, inner_expression in metrics:
798        if inner_pmu is None:
799          inner_pmu = 'cpu'
800        if inner_pmu.lower() != outer_pmu.lower():
801          continue
802        if inner_name.lower() == outer_name.lower():
803          continue
804        if (inner_pmu, inner_name) in updates:
805          inner_expression = updates[(inner_pmu, inner_name)]
806        updated = updated.Substitute(inner_name, inner_expression)
807      if updated.Equals(outer_expression):
808        break
809      if (outer_pmu, outer_name) in updates and updated.Equals(updates[(outer_pmu, outer_name)]):
810        break
811      updates[(outer_pmu, outer_name)] = updated
812  return updates
813