LLZK 0.1.0
Veridise's ZK Language IR
Loading...
Searching...
No Matches
Compare.h
Go to the documentation of this file.
1//===-- Compare.h -----------------------------------------------*- C++ -*-===//
2//
3// Part of the LLZK Project, under the Apache License v2.0.
4// See LICENSE.txt for license information.
5// Copyright 2025 Veridise Inc.
6// SPDX-License-Identifier: Apache-2.0
7//
8//===----------------------------------------------------------------------===//
9
10#pragma once
11
12#include <mlir/IR/Operation.h>
13
14#include <concepts>
15
16namespace llzk {
17
18template <typename Op>
19concept OpComparable = requires(Op op) {
20 { op.getOperation() } -> std::convertible_to<mlir::Operation *>;
21};
22
23template <typename Op>
24concept NamedOpComparable = requires(Op op) {
26 { op.getName() } -> std::convertible_to<mlir::StringRef>;
27};
28
29template <OpComparable Op> mlir::FailureOr<bool> isLocationLess(const Op &l, const Op &r) {
30 Op &lhs = const_cast<Op &>(l);
31 Op &rhs = const_cast<Op &>(r);
32 mlir::Location lhsLoc = lhs.getOperation()->getLoc(), rhsLoc = rhs.getOperation()->getLoc();
33 auto unknownLoc = mlir::UnknownLoc::get(lhs.getOperation()->getContext());
34 // We cannot make judgments on unknown locations.
35 if (lhsLoc == unknownLoc || rhsLoc == unknownLoc) {
36 return mlir::failure();
37 }
38 // If we have full locations for both, then we can sort by file name, then line, then column.
39 auto lhsFileLoc = llvm::dyn_cast<mlir::FileLineColLoc>(lhsLoc);
40 auto rhsFileLoc = llvm::dyn_cast<mlir::FileLineColLoc>(rhsLoc);
41 if (lhsFileLoc && rhsFileLoc) {
42 auto filenameCmp = lhsFileLoc.getFilename().compare(rhsFileLoc.getFilename());
43 return filenameCmp < 0 || (filenameCmp == 0 && lhsFileLoc.getLine() < rhsFileLoc.getLine()) ||
44 (filenameCmp == 0 && lhsFileLoc.getLine() == rhsFileLoc.getLine() &&
45 lhsFileLoc.getColumn() < rhsFileLoc.getColumn());
46 }
47 return mlir::failure();
48}
49
50template <OpComparable Op> struct OpLocationLess {
51 bool operator()(const Op &l, const Op &r) const { return isLocationLess(l, r).value_or(false); }
52};
53
54template <NamedOpComparable Op> struct NamedOpLocationLess {
55 bool operator()(const Op &l, const Op &r) const {
56 auto res = isLocationLess(l, r);
57 if (mlir::succeeded(res)) {
58 return res.value();
59 }
60
61 Op &lhs = const_cast<Op &>(l);
62 Op &rhs = const_cast<Op &>(r);
63 return lhs.getName().compare(rhs.getName()) < 0;
64 }
65};
66
67} // namespace llzk
mlir::FailureOr< bool > isLocationLess(const Op &l, const Op &r)
Definition Compare.h:29
bool operator()(const Op &l, const Op &r) const
Definition Compare.h:55
bool operator()(const Op &l, const Op &r) const
Definition Compare.h:51