risc0-zkvm-circuit 0.4.0

RISC Zero zero-knowledge VM circuit crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
// Copyright 2022 Risc0, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "risc0/zkvm/circuit/poly_context.h"

#include "risc0/core/log.h"
#include "risc0/core/util.h"
#include "risc0/zkvm/circuit/constants.h"

#include <map>
#include <set>
#include <sstream>

namespace risc0::circuit {

namespace {

struct PolyOpInterface : public ValueImplBase,
                         public std::enable_shared_from_this<PolyOpInterface> {
  virtual int getTypeID() const = 0;
  virtual bool isConstraint() const = 0;
  virtual bool lessThan(const PolyOpInterface& rhs) const = 0;
  virtual int degree() const = 0;
  virtual void computeTaps(PolyContext::Impl& impl) = 0;
  virtual std::string output(PolyContext::Impl& impl, const std::string& out) = 0;
  virtual void findCriticalPath(PolyContext::Impl& impl) = 0;
};

template <typename Derived, int TypeID, bool isCons> struct PolyOpBase : PolyOpInterface {
  mutable int cachedDegree = -1;
  int getTypeID() const override { return TypeID; }
  bool isConstraint() const override { return isCons; }
  bool lessThan(const PolyOpInterface& rhs) const override {
    if (rhs.getTypeID() != TypeID) {
      return TypeID < rhs.getTypeID();
    }
    return static_cast<const Derived*>(this)->key() < static_cast<const Derived&>(rhs).key();
  }
  int degree() const override {
    if (cachedDegree < 0) {
      cachedDegree = static_cast<const Derived*>(this)->getDegree();
    }
    return cachedDegree;
  }
};

using PolyOp = std::shared_ptr<PolyOpInterface>;

struct OpConstant : public PolyOpBase<OpConstant, 0, false> {
  Fp value;
  OpConstant(Fp value) : value(value) {}
  int getDegree() const { return 0; }
  Fp key() const { return value; }
  void computeTaps(PolyContext::Impl& impl) override {}
  std::string output(PolyContext::Impl& impl, const std::string& out) override;
  void findCriticalPath(PolyContext::Impl& impl) override;
};

struct OpGet : public PolyOpBase<OpGet, 1, false> {
  std::string base;
  size_t offset;
  size_t back;
  OpGet(const std::string& base, size_t offset, size_t back)
      : base(base), offset(offset), back(back) {}
  int getDegree() const { return 1; }
  std::tuple<std::string, size_t, size_t> key() const {
    return std::make_tuple(base, offset, back);
  }
  void computeTaps(PolyContext::Impl& impl) override;
  std::string output(PolyContext::Impl& impl, const std::string& out) override;
  void findCriticalPath(PolyContext::Impl& impl) override;
};

struct OpAdd : public PolyOpBase<OpAdd, 2, false> {
  PolyOp lhs;
  PolyOp rhs;
  OpAdd(PolyOp lhs, PolyOp rhs) : lhs(lhs), rhs(rhs) {}
  int getDegree() const { return std::max(lhs->degree(), rhs->degree()); }
  std::pair<PolyOp, PolyOp> key() const { return std::make_pair(lhs, rhs); }
  void computeTaps(PolyContext::Impl& impl) override {
    lhs->computeTaps(impl);
    rhs->computeTaps(impl);
  }
  std::string output(PolyContext::Impl& impl, const std::string& out) override;
  void findCriticalPath(PolyContext::Impl& impl) override;
};

struct OpSub : public PolyOpBase<OpSub, 3, false> {
  PolyOp lhs;
  PolyOp rhs;
  OpSub(PolyOp lhs, PolyOp rhs) : lhs(lhs), rhs(rhs) {}
  int getDegree() const { return std::max(lhs->degree(), rhs->degree()); }
  std::pair<PolyOp, PolyOp> key() const { return std::make_pair(lhs, rhs); }
  void computeTaps(PolyContext::Impl& impl) override {
    lhs->computeTaps(impl);
    rhs->computeTaps(impl);
  }
  std::string output(PolyContext::Impl& impl, const std::string& out) override;
  void findCriticalPath(PolyContext::Impl& impl) override;
};

struct OpMul : public PolyOpBase<OpMul, 4, false> {
  PolyOp lhs;
  PolyOp rhs;
  OpMul(PolyOp lhs, PolyOp rhs) : lhs(lhs), rhs(rhs) {}
  int getDegree() const { return lhs->degree() + rhs->degree(); }
  std::pair<PolyOp, PolyOp> key() const { return std::make_pair(lhs, rhs); }
  void computeTaps(PolyContext::Impl& impl) override {
    lhs->computeTaps(impl);
    rhs->computeTaps(impl);
  }
  std::string output(PolyContext::Impl& impl, const std::string& out) override;
  void findCriticalPath(PolyContext::Impl& impl) override;
};

struct OpBegin : public PolyOpBase<OpBegin, 5, true> {
  int getDegree() const { return 0; }
  int key() const { return 0; }
  void computeTaps(PolyContext::Impl& impl) override {}
  std::string output(PolyContext::Impl& impl, const std::string& out) override;
  void findCriticalPath(PolyContext::Impl& impl) override;
};

struct OpAssertZero : public PolyOpBase<OpAssertZero, 6, true> {
  PolyOp prev;
  PolyOp zero;
  OpAssertZero(PolyOp prev, PolyOp zero) : prev(prev), zero(zero) {}
  int getDegree() const { return std::max(prev->degree(), zero->degree()); }
  std::pair<PolyOp, PolyOp> key() const { return std::make_pair(prev, zero); }
  void computeTaps(PolyContext::Impl& impl) override {
    prev->computeTaps(impl);
    zero->computeTaps(impl);
  }
  std::string output(PolyContext::Impl& impl, const std::string& out) override;
  void findCriticalPath(PolyContext::Impl& impl) override;
};

struct OpCombine : public PolyOpBase<OpCombine, 7, true> {
  PolyOp prev;
  PolyOp mul;
  PolyOp inner;
  OpCombine(PolyOp prev, PolyOp mul, PolyOp inner) : prev(prev), mul(mul), inner(inner) {}
  int getDegree() const { return std::max(prev->degree(), mul->degree() + inner->degree()); }
  std::tuple<PolyOp, PolyOp, PolyOp> key() const { return std::make_tuple(prev, mul, inner); }
  void computeTaps(PolyContext::Impl& impl) override {
    prev->computeTaps(impl);
    mul->computeTaps(impl);
    inner->computeTaps(impl);
  }
  std::string output(PolyContext::Impl& impl, const std::string& out) override;
  void findCriticalPath(PolyContext::Impl& impl) override;
};

struct OpGetGlobal : public PolyOpBase<OpGetGlobal, 8, false> {
  size_t offset;
  OpGetGlobal(size_t offset) : offset(offset) {}
  int getDegree() const { return 0; }
  size_t key() const { return offset; }
  void computeTaps(PolyContext::Impl& impl) override {}
  std::string output(PolyContext::Impl& impl, const std::string& out) override;
  void findCriticalPath(PolyContext::Impl& impl) override;
};

struct PolyBuffer : public BufferImplBase {
  std::string param;
};

PolyOp asPoly(Context::ValPtr ptr) {
  return std::static_pointer_cast<PolyOpInterface>(ptr);
}

struct InternLessThan {
  bool operator()(PolyOp a, PolyOp b) const { return a->lessThan(*b); }
};

} // namespace

struct PolyContext::Impl {
  std::set<PolyOp, InternLessThan> interned;
  std::vector<PolyOp> condStack;
  std::vector<SourceLoc> locStack;
  std::vector<PolyOp> resultStack;
  std::map<PolyOp, SourceLoc> opToLoc;
  size_t totFp4s = 0;
  size_t totCons = 0;
  std::map<PolyOp, std::string> opToName;
  std::stringstream outs;
  struct Tap {
    std::string base;
    size_t offset;
    size_t back;
    Tap(const std::string& base, size_t offset, size_t back)
        : base(base), offset(offset), back(back) {}
    bool operator<(const Tap& rhs) const {
      return std::make_tuple(base, offset, back) < std::make_tuple(rhs.base, rhs.offset, rhs.back);
    }
  };
  std::set<Tap> taps;
  std::map<Tap, size_t> tapToID;

  template <typename OpClass, typename... Args> PolyOp intern(SourceLoc loc, Args... args) {
    PolyOp newOp = std::make_shared<OpClass>(args...);
    auto it = interned.find(newOp);
    if (it != interned.end()) {
      return *it;
    }
    interned.emplace(newOp);
    opToLoc[newOp] = loc;
    return newOp;
  }
  Impl() { resultStack.push_back(intern<OpBegin>(SourceLoc::current())); }
  bool isConst(PolyOp a) { return static_cast<bool>(std::dynamic_pointer_cast<OpConstant>(a)); }
  Fp getConst(PolyOp a) { return std::dynamic_pointer_cast<OpConstant>(a)->value; }
  PolyOp constant(Fp val, SourceLoc loc) { return intern<OpConstant>(loc, val); }
  PolyOp get(const std::string& name, size_t offset, size_t back, SourceLoc loc) {
    return intern<OpGet>(loc, name, offset, back);
  }
  PolyOp getGlobal(size_t offset, SourceLoc loc) { return intern<OpGetGlobal>(loc, offset); }
  PolyOp add(PolyOp a, PolyOp b, SourceLoc loc) {
    if (isConst(a) && !isConst(b)) {
      std::swap(a, b);
    }
    if (isConst(b) && getConst(b) == 0) {
      return a;
    }
    if (isConst(a) && isConst(b)) {
      return constant(getConst(a) + getConst(b), loc);
    }
    return intern<OpAdd>(loc, a, b);
  }
  PolyOp sub(PolyOp a, PolyOp b, SourceLoc loc) {
    if (isConst(b) && getConst(b) == 0) {
      return a;
    }
    if (isConst(a) && isConst(b)) {
      return constant(getConst(a) - getConst(b), loc);
    }
    if (a == b) {
      return constant(0, loc);
    }
    return intern<OpSub>(loc, a, b);
  }
  PolyOp mul(PolyOp a, PolyOp b, SourceLoc loc) {
    if (isConst(a) && !isConst(b)) {
      std::swap(a, b);
    }
    if (isConst(b) && getConst(b) == 0) {
      return constant(0, loc);
    }
    if (isConst(b) && getConst(b) == 1) {
      return a;
    }
    if (isConst(a) && isConst(b)) {
      return constant(getConst(a) * getConst(b), loc);
    }
    return intern<OpMul>(loc, a, b);
  }
  void assertZero(PolyOp a, SourceLoc loc) {
    resultStack.back() = intern<OpAssertZero>(loc, resultStack.back(), a);
  }
  void beginGroup(SourceLoc loc) {
    locStack.push_back(loc);
    resultStack.push_back(intern<OpBegin>(loc));
  }
  void endGroup() {
    PolyOp inner = resultStack.back();
    auto cond = constant(1, locStack.back());
    resultStack.pop_back();
    resultStack.back() = intern<OpCombine>(locStack.back(), resultStack.back(), cond, inner);
    locStack.pop_back();
  }
  void beginIf(PolyOp a, SourceLoc loc) {
    condStack.push_back(a);
    locStack.push_back(loc);
    resultStack.push_back(intern<OpBegin>(loc));
  }
  void endIf() {
    PolyOp cond = condStack.back();
    condStack.pop_back();
    PolyOp inner = resultStack.back();
    resultStack.pop_back();
    resultStack.back() = intern<OpCombine>(locStack.back(), resultStack.back(), cond, inner);
    locStack.pop_back();
  }
  std::string eval(PolyOp op) {
    auto it = opToName.find(op);
    if (it != opToName.end()) {
      return it->second;
    }
    std::string opName;
    if (op->isConstraint()) {
      opName = std::to_string(totCons++);
    } else {
      opName = std::to_string(totFp4s++);
    }
    opToName[op] = opName;
    std::string expr = op->output(*this, opName);
    outs << expr << " // deg=" << op->degree() << ", " << opToLoc[op].filename << ":"
         << opToLoc[op].line << "\n";
    return opName;
  }
  void onCriticalPath(PolyOp op) {
    LOG(0,
        "  name=" << opToName[op] << ", deg=" << op->degree() << " " << opToLoc[op].filename << ":"
                  << opToLoc[op].line);
  }
};

std::string OpConstant::output(PolyContext::Impl& impl, const std::string& out) {
  return "do_const(" + out + ", " + value.str() + ")";
}

void OpConstant::findCriticalPath(PolyContext::Impl& impl) {}

void OpGet::computeTaps(PolyContext::Impl& impl) {
  impl.taps.emplace(base, offset, back);
}

std::string OpGet::output(PolyContext::Impl& impl, const std::string& out) {
  using Tap = PolyContext::Impl::Tap;
  Tap myTap = {base, offset, back};
  size_t myID = impl.tapToID[myTap];
  return "do_get(" + out + ", " + base + ", " + std::to_string(offset) + ", " +
         std::to_string(back) + ", " + std::to_string(myID) + ")";
}

void OpGet::findCriticalPath(PolyContext::Impl& impl) {
  impl.onCriticalPath(shared_from_this());
}

std::string OpGetGlobal::output(PolyContext::Impl& impl, const std::string& out) {
  return "do_get_global(" + out + ", " + std::to_string(offset) + ")";
}

void OpGetGlobal::findCriticalPath(PolyContext::Impl& impl) {}

std::string OpAdd::output(PolyContext::Impl& impl, const std::string& out) {
  return "do_add(" + out + ", " + impl.eval(lhs) + ", " + impl.eval(rhs) + ")";
}

void OpAdd::findCriticalPath(PolyContext::Impl& impl) {
  if (lhs->degree() < rhs->degree()) {
    rhs->findCriticalPath(impl);
  } else {
    lhs->findCriticalPath(impl);
  }
}

std::string OpSub::output(PolyContext::Impl& impl, const std::string& out) {
  return "do_sub(" + out + ", " + impl.eval(lhs) + ", " + impl.eval(rhs) + ")";
}

void OpSub::findCriticalPath(PolyContext::Impl& impl) {
  if (lhs->degree() < rhs->degree()) {
    rhs->findCriticalPath(impl);
  } else {
    lhs->findCriticalPath(impl);
  }
}

std::string OpMul::output(PolyContext::Impl& impl, const std::string& out) {
  return "do_mul(" + out + ", " + impl.eval(lhs) + ", " + impl.eval(rhs) + ")";
}

void OpMul::findCriticalPath(PolyContext::Impl& impl) {
  impl.onCriticalPath(shared_from_this());
  rhs->findCriticalPath(impl);
  lhs->findCriticalPath(impl);
}

std::string OpBegin::output(PolyContext::Impl& impl, const std::string& out) {
  return "do_begin(" + out + ")";
}

void OpBegin::findCriticalPath(PolyContext::Impl& impl) {}

std::string OpAssertZero::output(PolyContext::Impl& impl, const std::string& out) {
  auto opLoc = impl.opToLoc[shared_from_this()];
  return "do_assert_zero(" + out + ", " + impl.eval(prev) + ", " + impl.eval(zero) + ", \"" +
         opLoc.filename + ":" + std::to_string(opLoc.line) + "\")";
}

void OpAssertZero::findCriticalPath(PolyContext::Impl& impl) {
  if (prev->degree() == degree()) {
    prev->findCriticalPath(impl);
    return;
  }
  impl.onCriticalPath(shared_from_this());
  zero->findCriticalPath(impl);
}

std::string OpCombine::output(PolyContext::Impl& impl, const std::string& out) {
  auto opLoc = impl.opToLoc[shared_from_this()];
  return "do_combine(" + out + ", " + impl.eval(prev) + ", " + impl.eval(mul) + "," +
         impl.eval(inner) + ", \"" + opLoc.filename + ":" + std::to_string(opLoc.line) + "\")";
}

void OpCombine::findCriticalPath(PolyContext::Impl& impl) {
  if (prev->degree() == degree()) {
    prev->findCriticalPath(impl);
    return;
  }
  impl.onCriticalPath(shared_from_this());
  mul->findCriticalPath(impl);
  inner->findCriticalPath(impl);
}

PolyContext::PolyContext() : impl(std::make_unique<Impl>()) {}

PolyContext::~PolyContext() {}

Context::BufPtr PolyContext::addParam(const std::string& name, size_t size) {
  auto out = std::make_shared<PolyBuffer>();
  out->size = size;
  out->param = name;
  return out;
}

std::string PolyContext::done() {
  impl->outs << "#ifdef CHECK_EVAL\n";
  PolyOp result = impl->resultStack.back();
  impl->resultStack.pop_back();
  REQUIRE(impl->condStack.empty());
  REQUIRE(impl->resultStack.empty());
  result->computeTaps(*impl);
  size_t nextID = 0;
  for (const auto& tap : impl->taps) {
    impl->tapToID[tap] = nextID++;
  }
  std::string finalName = impl->eval(result);
  if ((unsigned)result->degree() > kMaxDegree) {
    result->findCriticalPath(*impl);
    throw std::runtime_error("Degree too large!");
  }
  std::map<std::set<size_t>, size_t> uniqCombos;
  std::vector<std::set<size_t>> comboById;
  std::set<size_t> simpleCombo = {0};
  comboById.push_back(simpleCombo);
  uniqCombos[simpleCombo] = 0;
  impl->outs << "do_result(" + finalName + ")\n";
  impl->outs << "#endif  // CHECK_EVAL\n";
  impl->outs << "#ifdef SIZES\n";
  impl->outs << "static constexpr size_t kNumStepFp4s = " << impl->totFp4s << ";\n";
  impl->outs << "static constexpr size_t kNumStepCons= " << impl->totCons << ";\n";
  impl->outs << "#endif  // SIZES\n";
  impl->outs << "#ifdef TAPS\n";
  impl->outs << R"**(
#ifndef base_begin
#define base_begin(base) /**/
#endif
#ifndef base_end
#define base_end(base) /**/
#endif
#ifndef offset_begin
#define offset_begin(base, offset) /**/
#endif
#ifndef offset_end
#define offset_end(base, offset, combo) /**/
#endif
#ifndef tap
#define tap(base, offset, back) /**/
#endif
)**";
  Impl::Tap prev("", 0, 0);
  bool first = true;
  std::set<size_t> curCombo;
  auto comboFinal = [&]() {
    size_t id;
    auto it = uniqCombos.find(curCombo);
    if (it != uniqCombos.end()) {
      id = it->second;
    } else {
      id = comboById.size();
      uniqCombos[curCombo] = id;
      comboById.push_back(curCombo);
    }
    curCombo.clear();
    return id;
  };
  for (const auto& tap : impl->taps) {
    if (first) {
      impl->outs << "base_begin(" << tap.base << ")\n";
      impl->outs << "  offset_begin(" << tap.base << ", " << tap.offset << ")\n";
    }
    if (!first && prev.base != tap.base) {
      size_t id = comboFinal();
      impl->outs << "  offset_end(" << prev.base << ", " << prev.offset << ", " << id << ")\n";
      impl->outs << "base_end(" << prev.base << ")\n";
      impl->outs << "base_begin(" << tap.base << ")\n";
      impl->outs << "  offset_begin(" << tap.base << ", " << tap.offset << ")\n";
    } else if (!first && prev.offset != tap.offset) {
      size_t id = comboFinal();
      impl->outs << "  offset_end(" << prev.base << ", " << prev.offset << ", " << id << ")\n";
      impl->outs << "  offset_begin(" << tap.base << ", " << tap.offset << ")\n";
    }
    impl->outs << "    tap(" << tap.base << ", " << tap.offset << ", " << tap.back << ")\n";
    curCombo.emplace(tap.back);
    first = false;
    prev = tap;
  }
  size_t id = comboFinal();
  impl->outs << "  offset_end(" << prev.base << ", " << prev.offset << ", " << id << ")\n";
  impl->outs << "base_end(" << prev.base << ")\n";
  impl->outs << R"**(
#undef base_begin
#undef base_end
#undef offset_begin
#undef offset_end
#undef tap
)**";
  impl->outs << "#endif  // TAPS\n";
  if (kComboCount != comboById.size()) {
    LOG(0, "Required " << comboById.size() << " combos");
  }
  REQUIRE(kComboCount == comboById.size());

  return impl->outs.str();
}

Context::ValPtr PolyContext::constant(Fp val, SourceLoc loc) {
  return impl->constant(val, loc);
}

Context::ValPtr PolyContext::getVal(BufPtr buf, size_t index, SourceLoc loc) {
  auto pbuf = std::static_pointer_cast<PolyBuffer>(buf);
  return impl->get(pbuf->param, pbuf->offset + index, pbuf->back, loc);
}

void PolyContext::setVal(BufPtr buf, size_t index, ValPtr val, SourceLoc loc) {
  auto pbuf = std::static_pointer_cast<PolyBuffer>(buf);
  auto lhs = impl->get(pbuf->param, pbuf->offset + index, pbuf->back, loc);
  impl->assertZero(impl->sub(lhs, asPoly(val), loc), loc);
}

Context::ValPtr PolyContext::getGlobal(size_t index, SourceLoc loc) {
  return impl->getGlobal(index, loc);
}

void PolyContext::setGlobal(size_t index, ValPtr val, SourceLoc loc) {
  auto lhs = impl->getGlobal(index, loc);
  impl->assertZero(impl->sub(lhs, asPoly(val), loc), loc);
}

bool PolyContext::beginNondet(SourceLoc loc) {
  return false;
}
void PolyContext::endNondet() {}

void PolyContext::beginGroup(SourceLoc loc) {
  impl->beginGroup(loc);
}

void PolyContext::endGroup() {
  impl->endGroup();
}

void PolyContext::beginIf(ValPtr a, SourceLoc loc) {
  impl->beginIf(asPoly(a), loc);
}

void PolyContext::endIf() {
  impl->endIf();
}

Context::BufPtr PolyContext::slice(BufPtr buf, size_t offset, size_t size, SourceLoc loc) {
  auto pbuf = std::static_pointer_cast<PolyBuffer>(buf);
  auto nbuf = std::make_shared<PolyBuffer>(*pbuf);
  if (offset + size > pbuf->size) {
    throw std::runtime_error("Slice out of bounds");
  }
  nbuf->offset += offset;
  nbuf->size = size;
  return nbuf;
}

Context::BufPtr PolyContext::back(BufPtr buf, size_t size, SourceLoc loc) {
  auto pbuf = std::static_pointer_cast<PolyBuffer>(buf);
  auto nbuf = std::make_shared<PolyBuffer>(*pbuf);
  nbuf->back += size;
  return nbuf;
}

Context::BufPtr PolyContext::requireDigits(BufPtr buf, size_t bits, SourceLoc loc) {
  auto pbuf = std::static_pointer_cast<PolyBuffer>(buf);
  if (pbuf->digits != 0 && pbuf->digits <= bits) {
    return pbuf;
  }
  auto nbuf = std::make_shared<PolyBuffer>(*pbuf);
  nbuf->digits = bits;
  if (pbuf->back == 0) {
    for (size_t i = 0; i < pbuf->size; i++) {
      PolyOp val = impl->get(pbuf->param, pbuf->offset + i, 0, loc);
      PolyOp cur = impl->constant(1, loc);
      for (int j = 0; j < (1 << bits); j++) {
        cur = impl->mul(cur, impl->sub(val, impl->constant(j, loc), loc), loc);
      }
      impl->assertZero(cur, loc);
    }
  }
  return nbuf;
}

Context::BufPtr PolyContext::requireMux(BufPtr buf, SourceLoc loc) {
  auto pbuf = std::static_pointer_cast<PolyBuffer>(buf);
  auto nbuf = std::make_shared<PolyBuffer>(*pbuf);
  nbuf->digits = 1;
  nbuf->isMux = true;
  if (pbuf->back == 0) {
    (void)requireDigits(buf, 1, loc);
    PolyOp tot = impl->constant(0, loc);
    for (size_t i = 0; i < pbuf->size; i++) {
      PolyOp val = impl->get(pbuf->param, pbuf->offset + i, 0, loc);
      tot = impl->add(tot, val, loc);
    }
    impl->assertZero(impl->sub(tot, impl->constant(1, loc), loc), loc);
  }
  return nbuf;
}

Context::ValPtr PolyContext::getDigits(BufPtr buf, size_t bits, SourceLoc loc) {
  auto pbuf = std::static_pointer_cast<PolyBuffer>(buf);
  PolyOp tot = impl->constant(0, loc);
  for (size_t i = 0; i < pbuf->size; i++) {
    PolyOp val = impl->get(pbuf->param, pbuf->offset + i, pbuf->back, loc);
    PolyOp bitMul = impl->constant(1 << (i * bits), loc);
    tot = impl->add(tot, impl->mul(bitMul, val, loc), loc);
  }
  return tot;
}

Context::ValPtr PolyContext::setDigits(BufPtr buf, size_t bits, ValPtr input, SourceLoc loc) {
  auto pbuf = std::static_pointer_cast<PolyBuffer>(buf);
  PolyOp getVal = asPoly(getDigits(buf, bits, loc));
  PolyOp subDigits = impl->sub(asPoly(input), getVal, loc);
  Fp shiftDiv = ::risc0::inv(Fp(1 << (pbuf->size * bits)));
  return impl->mul(subDigits, impl->constant(shiftDiv, loc), loc);
}

Context::ValPtr PolyContext::getMux(BufPtr buf, SourceLoc loc) {
  PolyOp tot = impl->constant(0, loc);
  auto pbuf = std::static_pointer_cast<PolyBuffer>(buf);
  for (size_t i = 0; i < pbuf->size; i++) {
    PolyOp val = impl->get(pbuf->param, pbuf->offset + i, pbuf->back, loc);
    tot = impl->add(tot, impl->mul(impl->constant(i, loc), val, loc), loc);
  }
  return tot;
}

void PolyContext::setMux(BufPtr buf, ValPtr input, SourceLoc loc) {
  PolyOp muxVal = asPoly(getMux(buf, loc));
  return impl->assertZero(impl->sub(muxVal, asPoly(input), loc), loc);
}

Context::ValPtr PolyContext::add(ValPtr a, ValPtr b, SourceLoc loc) {
  return impl->add(asPoly(a), asPoly(b), loc);
}

Context::ValPtr PolyContext::sub(ValPtr a, ValPtr b, SourceLoc loc) {
  return impl->sub(asPoly(a), asPoly(b), loc);
}

Context::ValPtr PolyContext::mul(ValPtr a, ValPtr b, SourceLoc loc) {
  return impl->mul(asPoly(a), asPoly(b), loc);
}

Context::ValPtr PolyContext::bitAnd(ValPtr a, ValPtr b, SourceLoc loc) {
  throw std::runtime_error("Unimplemented");
}

Context::ValPtr PolyContext::inv(ValPtr a, SourceLoc loc) {
  throw std::runtime_error("Unimplemented");
}

Context::ValPtr PolyContext::nonzero(ValPtr a, SourceLoc loc) {
  throw std::runtime_error("Unimplemented");
}

void PolyContext::assertZero(ValPtr a, SourceLoc loc) {
  impl->assertZero(asPoly(a), loc);
}

void PolyContext::log(const char* str, std::vector<ValPtr> vals) {
  // NO-OP
}

std::array<Context::ValPtr, 4> PolyContext::divide32(
    ValPtr numerLow, ValPtr numerHigh, ValPtr denomLow, ValPtr denomHigh, SourceLoc loc) {
  throw std::runtime_error("Unimplemented");
}

void PolyContext::memWrite(ValPtr cycle, ValPtr addr, ValPtr low, ValPtr high, SourceLoc loc) {
  throw std::runtime_error("Unimplemented");
}

std::array<Context::ValPtr, 2> PolyContext::memRead(ValPtr cycle, ValPtr addr, SourceLoc loc) {
  throw std::runtime_error("Unimplemented");
}

std::array<Context::ValPtr, 5> PolyContext::memCheck(SourceLoc loc) {
  throw std::runtime_error("Unimplemented");
}

} // namespace risc0::circuit