LLZK 0.1.0
Veridise's ZK Language IR
Loading...
Searching...
No Matches
Field.cpp
Go to the documentation of this file.
1//===-- Field.cpp -----------------------------------------------*- 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#include "llzk/Analysis/Field.h"
12
13#include <llvm/ADT/APSInt.h>
14#include <llvm/ADT/SlowDynamicAPInt.h>
15#include <llvm/ADT/Twine.h>
16
17#include <mutex>
18
19using namespace llvm;
20
21namespace llzk {
22
23Field::Field(std::string_view primeStr) {
24 APSInt parsedInt(primeStr);
25
26 primeMod = toDynamicAPInt(parsedInt);
27 halfPrime = (primeMod + felt(1)) / felt(2);
28 bitwidth = parsedInt.getBitWidth();
29}
30
31const Field &Field::getField(const char *fieldName) {
32 static DenseMap<StringRef, Field> knownFields;
33 static std::once_flag fieldsInit;
34 std::call_once(fieldsInit, initKnownFields, knownFields);
35
36 if (auto it = knownFields.find(fieldName); it != knownFields.end()) {
37 return it->second;
38 }
39 report_fatal_error("field \"" + Twine(fieldName) + "\" is unsupported");
40}
41
42void Field::initKnownFields(DenseMap<StringRef, Field> &knownFields) {
43 // bn128/254, default for circom
44 knownFields.try_emplace(
45 "bn128",
46 Field("21888242871839275222246405745257275088696311157297823662689037894645226208583")
47 );
48 knownFields.try_emplace("bn254", knownFields.at("bn128"));
49 // 15 * 2^27 + 1, default for zirgen
50 knownFields.try_emplace("babybear", Field("2013265921"));
51 // 2^64 - 2^32 + 1, used for plonky2
52 knownFields.try_emplace("goldilocks", Field("18446744069414584321"));
53 // 2^31 - 1, used for Plonky3
54 knownFields.try_emplace("mersenne31", Field("2147483647"));
55}
56
57DynamicAPInt Field::reduce(const DynamicAPInt &i) const {
58 DynamicAPInt m = i % prime();
59 if (m < 0) {
60 return prime() + m;
61 }
62 return m;
63}
64
65DynamicAPInt Field::reduce(const APInt &i) const { return reduce(toDynamicAPInt(i)); }
66
67} // namespace llzk
This file implements helper methods for constructing DynamicAPInts.
Field()=delete
llvm::DynamicAPInt prime() const
For the prime field p, returns p.
Definition Field.h:37
llvm::DynamicAPInt reduce(const llvm::DynamicAPInt &i) const
Returns i mod p and reduces the result into the appropriate bitwidth.
llvm::DynamicAPInt felt(int i) const
Returns i as a signed field element.
Definition Field.h:43
static const Field & getField(const char *fieldName)
Get a Field from a given field name string.
Definition Field.cpp:31
DynamicAPInt toDynamicAPInt(StringRef str)