|
| 1 | +# Copyright (C) 2024 Intel Corporation |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +"""Module for loop interchange optimization in P-ISA operations""" |
| 5 | + |
| 6 | +import re |
| 7 | +from const.options import LoopKey |
| 8 | +from high_parser.pisa_operations import PIsaOp, Comment |
| 9 | + |
| 10 | + |
| 11 | +def loop_interchange( |
| 12 | + pisa_list: list[PIsaOp], |
| 13 | + primary_key: LoopKey | None = LoopKey.PART, |
| 14 | + secondary_key: LoopKey | None = LoopKey.RNS, |
| 15 | +) -> list[PIsaOp]: |
| 16 | + """Batch pisa_list into groups and sort them by primary and optional secondary keys. |
| 17 | +
|
| 18 | + Args: |
| 19 | + pisa_list: List of PIsaOp instructions |
| 20 | + primary_key: Primary sort criterion from SortKey enum |
| 21 | + secondary_key: Optional secondary sort criterion from SortKey enum |
| 22 | +
|
| 23 | + Returns: |
| 24 | + List of processed PIsaOp instructions |
| 25 | +
|
| 26 | + Raises: |
| 27 | + ValueError: If invalid sort key values provided |
| 28 | + """ |
| 29 | + if primary_key is None and secondary_key is None: |
| 30 | + return pisa_list |
| 31 | + |
| 32 | + def get_sort_value(pisa: PIsaOp, key: LoopKey) -> int: |
| 33 | + match key: |
| 34 | + case LoopKey.RNS: |
| 35 | + return pisa.q |
| 36 | + case LoopKey.PART: |
| 37 | + match = re.search(r"_(\d+)_", str(pisa)) |
| 38 | + return int(match[1]) if match else 0 |
| 39 | + case LoopKey.UNIT: |
| 40 | + match = re.search(r"_(\d+),", str(pisa)) |
| 41 | + return int(match[1]) if match else 0 |
| 42 | + case _: |
| 43 | + raise ValueError(f"Invalid sort key value: {key}") |
| 44 | + |
| 45 | + def get_sort_key(pisa: PIsaOp) -> tuple: |
| 46 | + primary_value = get_sort_value(pisa, primary_key) |
| 47 | + if secondary_key: |
| 48 | + secondary_value = get_sort_value(pisa, secondary_key) |
| 49 | + return (primary_value, secondary_value) |
| 50 | + return (primary_value,) |
| 51 | + |
| 52 | + # Filter out comments |
| 53 | + pisa_list_wo_comments = [p for p in pisa_list if not isinstance(p, Comment)] |
| 54 | + # Sort based on primary and optional secondary keys |
| 55 | + pisa_list_wo_comments.sort(key=get_sort_key) |
| 56 | + return pisa_list_wo_comments |
0 commit comments