LLZK 3.0.0
An open-source IR for Zero Knowledge (ZK) circuits
Loading...
Searching...
No Matches
OverflowSemantics.cpp
Go to the documentation of this file.
1//===-- OverflowSemantics.cpp - Cast overflow helpers -----------*- C++ -*-===//
2//
3// Part of the LLZK Project, under the Apache License v2.0.
4// See LICENSE.txt for license information.
5// Copyright 2026 Project LLZK
6// SPDX-License-Identifier: Apache-2.0
7//
8//===----------------------------------------------------------------------===//
9
11
12#include <llvm/Support/ErrorHandling.h>
13
14using namespace llvm;
15
16namespace llzk::cast {
17namespace {
18
19static DynamicAPInt positiveModulo(const DynamicAPInt &value, const DynamicAPInt &modulus) {
20 DynamicAPInt result = value % modulus;
21 return result < 0 ? result + modulus : result;
22}
23
24} // namespace
25
26std::optional<DynamicAPInt>
27applyIntToFeltOverflow(const DynamicAPInt &value, const Field &field, OverflowSemantics overflow) {
28 switch (overflow) {
30 return value < 0 || value >= field.prime() ? std::nullopt : std::optional(value);
32 return value < 0 ? field.zero() : (value < field.maxVal() ? value : field.maxVal());
34 return field.reduce(value);
36 return field.reduce(positiveModulo(value, DynamicAPInt(1) << field.bitWidth()));
37 }
38 llvm_unreachable("unknown overflow semantics");
39}
40
41std::optional<DynamicAPInt> applyFeltToIndexOverflow(
42 const DynamicAPInt &value, unsigned indexBitWidth, OverflowSemantics overflow
43) {
44 const DynamicAPInt safeUpperBound = (DynamicAPInt(1) << (indexBitWidth - 1)) - 1;
45 switch (overflow) {
47 return value < 0 || value > safeUpperBound ? std::nullopt : std::optional(value);
49 return value < 0 ? DynamicAPInt(0) : (value < safeUpperBound ? value : safeUpperBound);
52 return positiveModulo(value, safeUpperBound + 1);
53 }
54 llvm_unreachable("unknown overflow semantics");
55}
56
57} // namespace llzk::cast
Information about the prime finite field used for the interval analysis.
Definition Field.h:36
llvm::DynamicAPInt zero() const
Returns the zero field element.
Definition Field.h:79
llvm::DynamicAPInt prime() const
For the prime field p, returns p.
Definition Field.h:70
llvm::DynamicAPInt reduce(const llvm::DynamicAPInt &i) const
Returns the canonical representative of i mod p in [0, p).
unsigned bitWidth() const
Width sufficient for the modulus and its representatives, independent of literal storage.
Definition Field.h:103
llvm::DynamicAPInt maxVal() const
Returns p - 1, which is the max value possible in a prime field described by p.
Definition Field.h:85
std::optional< DynamicAPInt > applyIntToFeltOverflow(const DynamicAPInt &value, const Field &field, OverflowSemantics overflow)
std::optional< DynamicAPInt > applyFeltToIndexOverflow(const DynamicAPInt &value, unsigned indexBitWidth, OverflowSemantics overflow)