-
Notifications
You must be signed in to change notification settings - Fork 299
/
SCFToCalyx.cpp
2018 lines (1783 loc) · 86.6 KB
/
SCFToCalyx.cpp
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- SCFToCalyx.cpp - SCF to Calyx pass entry point -----------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This is the main SCF to Calyx conversion pass implementation.
//
//===----------------------------------------------------------------------===//
#include "circt/Conversion/SCFToCalyx.h"
#include "../PassDetail.h"
#include "circt/Dialect/Calyx/CalyxHelpers.h"
#include "circt/Dialect/Calyx/CalyxLoweringUtils.h"
#include "circt/Dialect/Calyx/CalyxOps.h"
#include "circt/Dialect/Comb/CombOps.h"
#include "circt/Dialect/HW/HWOps.h"
#include "mlir/Conversion/LLVMCommon/ConversionTarget.h"
#include "mlir/Conversion/LLVMCommon/Pattern.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/IR/AsmState.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "llvm/ADT/TypeSwitch.h"
#include <variant>
using namespace llvm;
using namespace mlir;
using namespace mlir::arith;
using namespace mlir::cf;
using namespace mlir::func;
namespace circt {
class ComponentLoweringStateInterface;
namespace scftocalyx {
//===----------------------------------------------------------------------===//
// Utility types
//===----------------------------------------------------------------------===//
class ScfWhileOp : public calyx::WhileOpInterface<scf::WhileOp> {
public:
explicit ScfWhileOp(scf::WhileOp op)
: calyx::WhileOpInterface<scf::WhileOp>(op) {}
Block::BlockArgListType getBodyArgs() override {
return getOperation().getAfterArguments();
}
Block *getBodyBlock() override { return &getOperation().getAfter().front(); }
Block *getConditionBlock() override {
return &getOperation().getBefore().front();
}
Value getConditionValue() override {
return getOperation().getConditionOp().getOperand(0);
}
std::optional<int64_t> getBound() override { return std::nullopt; }
};
class ScfForOp : public calyx::RepeatOpInterface<scf::ForOp> {
public:
explicit ScfForOp(scf::ForOp op) : calyx::RepeatOpInterface<scf::ForOp>(op) {}
Block::BlockArgListType getBodyArgs() override {
return getOperation().getRegion().getArguments();
}
Block *getBodyBlock() override {
return &getOperation().getRegion().getBlocks().front();
}
std::optional<int64_t> getBound() override {
return constantTripCount(getOperation().getLowerBound(),
getOperation().getUpperBound(),
getOperation().getStep());
}
};
//===----------------------------------------------------------------------===//
// Lowering state classes
//===----------------------------------------------------------------------===//
struct IfScheduleable {
scf::IfOp ifOp;
};
struct WhileScheduleable {
/// While operation to schedule.
ScfWhileOp whileOp;
};
struct ForScheduleable {
/// For operation to schedule.
ScfForOp forOp;
/// Bound
uint64_t bound;
};
struct CallScheduleable {
/// Instance for invoking.
calyx::InstanceOp instanceOp;
// CallOp for getting the arguments.
func::CallOp callOp;
};
/// A variant of types representing scheduleable operations.
using Scheduleable =
std::variant<calyx::GroupOp, IfScheduleable, WhileScheduleable,
ForScheduleable, CallScheduleable>;
class IfLoweringStateInterface {
public:
void addThenYieldRegs(scf::IfOp op, calyx::RegisterOp reg, unsigned idx) {
assert(
thenYieldRegs[op.getOperation()].count(idx) == 0 &&
"A register was already registered for the given then yield args.\n");
assert(idx < op->getNumOperands());
thenYieldRegs[op.getOperation()][idx] = reg;
}
const DenseMap<unsigned, calyx::RegisterOp> &getThenYieldRegs(scf::IfOp op) {
return thenYieldRegs[op.getOperation()];
}
calyx::RegisterOp getThenYieldRegs(scf::IfOp op, unsigned idx) {
auto regs = getThenYieldRegs(op);
auto it = regs.find(idx);
assert(it != regs.end() &&
"No then yield regs set for the provided index!");
return it->second;
}
void addElseYieldRegs(scf::IfOp op, calyx::RegisterOp reg, unsigned idx) {
assert(
elseYieldRegs[op.getOperation()].count(idx) == 0 &&
"A register was already registered for the given else yield args.\n");
assert(idx < op->getNumOperands());
elseYieldRegs[op.getOperation()][idx] = reg;
}
const DenseMap<unsigned, calyx::RegisterOp> &getElseYieldRegs(scf::IfOp op) {
return elseYieldRegs[op.getOperation()];
}
calyx::RegisterOp getElseYieldRegs(scf::IfOp op, unsigned idx) {
auto regs = getElseYieldRegs(op);
auto it = regs.find(idx);
assert(it != regs.end() &&
"No else yield regs set for the provided index!");
return it->second;
}
void setThenGroup(scf::IfOp op, calyx::GroupOp group) {
Operation *operation = op.getOperation();
assert(thenGroup.count(operation) == 0 &&
"A then group was already set for this scf::IfOp!\n");
thenGroup[operation] = group;
}
calyx::GroupOp getThenGroup(scf::IfOp op) {
auto it = thenGroup.find(op.getOperation());
assert(it != thenGroup.end() &&
"No then group was set for this scf::IfOp!\n");
return it->second;
}
void setElseGroup(scf::IfOp op, calyx::GroupOp group) {
Operation *operation = op.getOperation();
assert(elseGroup.count(operation) == 0 &&
"An else group was already set for this scf::IfOp!\n");
elseGroup[operation] = group;
}
calyx::GroupOp getElseGroup(scf::IfOp op) {
auto it = elseGroup.find(op.getOperation());
assert(it != elseGroup.end() &&
"No else group was set for this scf::IfOp!\n");
return it->second;
}
private:
DenseMap<Operation *, DenseMap<unsigned, calyx::RegisterOp>> thenYieldRegs;
DenseMap<Operation *, DenseMap<unsigned, calyx::RegisterOp>> elseYieldRegs;
DenseMap<Operation *, calyx::GroupOp> thenGroup;
DenseMap<Operation *, calyx::GroupOp> elseGroup;
};
class WhileLoopLoweringStateInterface
: calyx::LoopLoweringStateInterface<ScfWhileOp> {
public:
SmallVector<calyx::GroupOp> getWhileLoopInitGroups(ScfWhileOp op) {
return getLoopInitGroups(std::move(op));
}
calyx::GroupOp buildWhileLoopIterArgAssignments(
OpBuilder &builder, ScfWhileOp op, calyx::ComponentOp componentOp,
Twine uniqueSuffix, MutableArrayRef<OpOperand> ops) {
return buildLoopIterArgAssignments(builder, std::move(op), componentOp,
uniqueSuffix, ops);
}
void addWhileLoopIterReg(ScfWhileOp op, calyx::RegisterOp reg, unsigned idx) {
return addLoopIterReg(std::move(op), reg, idx);
}
const DenseMap<unsigned, calyx::RegisterOp> &
getWhileLoopIterRegs(ScfWhileOp op) {
return getLoopIterRegs(std::move(op));
}
void setWhileLoopLatchGroup(ScfWhileOp op, calyx::GroupOp group) {
return setLoopLatchGroup(std::move(op), group);
}
calyx::GroupOp getWhileLoopLatchGroup(ScfWhileOp op) {
return getLoopLatchGroup(std::move(op));
}
void setWhileLoopInitGroups(ScfWhileOp op,
SmallVector<calyx::GroupOp> groups) {
return setLoopInitGroups(std::move(op), std::move(groups));
}
};
class ForLoopLoweringStateInterface
: calyx::LoopLoweringStateInterface<ScfForOp> {
public:
SmallVector<calyx::GroupOp> getForLoopInitGroups(ScfForOp op) {
return getLoopInitGroups(std::move(op));
}
calyx::GroupOp buildForLoopIterArgAssignments(
OpBuilder &builder, ScfForOp op, calyx::ComponentOp componentOp,
Twine uniqueSuffix, MutableArrayRef<OpOperand> ops) {
return buildLoopIterArgAssignments(builder, std::move(op), componentOp,
uniqueSuffix, ops);
}
void addForLoopIterReg(ScfForOp op, calyx::RegisterOp reg, unsigned idx) {
return addLoopIterReg(std::move(op), reg, idx);
}
const DenseMap<unsigned, calyx::RegisterOp> &getForLoopIterRegs(ScfForOp op) {
return getLoopIterRegs(std::move(op));
}
calyx::RegisterOp getForLoopIterReg(ScfForOp op, unsigned idx) {
return getLoopIterReg(std::move(op), idx);
}
void setForLoopLatchGroup(ScfForOp op, calyx::GroupOp group) {
return setLoopLatchGroup(std::move(op), group);
}
calyx::GroupOp getForLoopLatchGroup(ScfForOp op) {
return getLoopLatchGroup(std::move(op));
}
void setForLoopInitGroups(ScfForOp op, SmallVector<calyx::GroupOp> groups) {
return setLoopInitGroups(std::move(op), std::move(groups));
}
};
/// Handles the current state of lowering of a Calyx component. It is mainly
/// used as a key/value store for recording information during partial lowering,
/// which is required at later lowering passes.
class ComponentLoweringState : public calyx::ComponentLoweringStateInterface,
public IfLoweringStateInterface,
public WhileLoopLoweringStateInterface,
public ForLoopLoweringStateInterface,
public calyx::SchedulerInterface<Scheduleable> {
public:
ComponentLoweringState(calyx::ComponentOp component)
: calyx::ComponentLoweringStateInterface(component) {}
};
//===----------------------------------------------------------------------===//
// Conversion patterns
//===----------------------------------------------------------------------===//
/// Iterate through the operations of a source function and instantiate
/// components or primitives based on the type of the operations.
class BuildOpGroups : public calyx::FuncOpPartialLoweringPattern {
using FuncOpPartialLoweringPattern::FuncOpPartialLoweringPattern;
LogicalResult
partiallyLowerFuncToComp(FuncOp funcOp,
PatternRewriter &rewriter) const override {
/// We walk the operations of the funcOp to ensure that all def's have
/// been visited before their uses.
bool opBuiltSuccessfully = true;
funcOp.walk([&](Operation *_op) {
opBuiltSuccessfully &=
TypeSwitch<mlir::Operation *, bool>(_op)
.template Case<arith::ConstantOp, ReturnOp, BranchOpInterface,
/// SCF
scf::YieldOp, scf::IfOp, scf::WhileOp, scf::ForOp,
/// memref
memref::AllocOp, memref::AllocaOp, memref::LoadOp,
memref::StoreOp,
/// standard arithmetic
AddIOp, SubIOp, CmpIOp, ShLIOp, ShRUIOp, ShRSIOp,
AndIOp, XOrIOp, OrIOp, ExtUIOp, ExtSIOp, TruncIOp,
MulIOp, DivUIOp, DivSIOp, RemUIOp, RemSIOp,
SelectOp, IndexCastOp, CallOp>(
[&](auto op) { return buildOp(rewriter, op).succeeded(); })
.template Case<FuncOp, scf::ConditionOp>([&](auto) {
/// Skip: these special cases will be handled separately.
return true;
})
.Default([&](auto op) {
op->emitError() << "Unhandled operation during BuildOpGroups()";
return false;
});
return opBuiltSuccessfully ? WalkResult::advance()
: WalkResult::interrupt();
});
return success(opBuiltSuccessfully);
}
private:
/// Op builder specializations.
LogicalResult buildOp(PatternRewriter &rewriter, scf::YieldOp yieldOp) const;
LogicalResult buildOp(PatternRewriter &rewriter,
BranchOpInterface brOp) const;
LogicalResult buildOp(PatternRewriter &rewriter,
arith::ConstantOp constOp) const;
LogicalResult buildOp(PatternRewriter &rewriter, SelectOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, AddIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, SubIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, MulIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, DivUIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, DivSIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, RemUIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, RemSIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, ShRUIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, ShRSIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, ShLIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, AndIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, OrIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, XOrIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, CmpIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, TruncIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, ExtUIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, ExtSIOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, ReturnOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, IndexCastOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, memref::AllocOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, memref::AllocaOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, memref::LoadOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, memref::StoreOp op) const;
LogicalResult buildOp(PatternRewriter &rewriter, scf::IfOp ifOp) const;
LogicalResult buildOp(PatternRewriter &rewriter, scf::WhileOp whileOp) const;
LogicalResult buildOp(PatternRewriter &rewriter, scf::ForOp forOp) const;
LogicalResult buildOp(PatternRewriter &rewriter, CallOp callOp) const;
/// buildLibraryOp will build a TCalyxLibOp inside a TGroupOp based on the
/// source operation TSrcOp.
template <typename TGroupOp, typename TCalyxLibOp, typename TSrcOp>
LogicalResult buildLibraryOp(PatternRewriter &rewriter, TSrcOp op,
TypeRange srcTypes, TypeRange dstTypes) const {
SmallVector<Type> types;
llvm::append_range(types, srcTypes);
llvm::append_range(types, dstTypes);
auto calyxOp =
getState<ComponentLoweringState>().getNewLibraryOpInstance<TCalyxLibOp>(
rewriter, op.getLoc(), types);
auto directions = calyxOp.portDirections();
SmallVector<Value, 4> opInputPorts;
SmallVector<Value, 4> opOutputPorts;
for (auto dir : enumerate(directions)) {
if (dir.value() == calyx::Direction::Input)
opInputPorts.push_back(calyxOp.getResult(dir.index()));
else
opOutputPorts.push_back(calyxOp.getResult(dir.index()));
}
assert(
opInputPorts.size() == op->getNumOperands() &&
opOutputPorts.size() == op->getNumResults() &&
"Expected an equal number of in/out ports in the Calyx library op with "
"respect to the number of operands/results of the source operation.");
/// Create assignments to the inputs of the library op.
auto group = createGroupForOp<TGroupOp>(rewriter, op);
rewriter.setInsertionPointToEnd(group.getBodyBlock());
for (auto dstOp : enumerate(opInputPorts))
rewriter.create<calyx::AssignOp>(op.getLoc(), dstOp.value(),
op->getOperand(dstOp.index()));
/// Replace the result values of the source operator with the new operator.
for (auto res : enumerate(opOutputPorts)) {
getState<ComponentLoweringState>().registerEvaluatingGroup(res.value(),
group);
op->getResult(res.index()).replaceAllUsesWith(res.value());
}
return success();
}
/// buildLibraryOp which provides in- and output types based on the operands
/// and results of the op argument.
template <typename TGroupOp, typename TCalyxLibOp, typename TSrcOp>
LogicalResult buildLibraryOp(PatternRewriter &rewriter, TSrcOp op) const {
return buildLibraryOp<TGroupOp, TCalyxLibOp, TSrcOp>(
rewriter, op, op.getOperandTypes(), op->getResultTypes());
}
/// Creates a group named by the basic block which the input op resides in.
template <typename TGroupOp>
TGroupOp createGroupForOp(PatternRewriter &rewriter, Operation *op) const {
Block *block = op->getBlock();
auto groupName = getState<ComponentLoweringState>().getUniqueName(
loweringState().blockName(block));
return calyx::createGroup<TGroupOp>(
rewriter, getState<ComponentLoweringState>().getComponentOp(),
op->getLoc(), groupName);
}
/// buildLibraryBinaryPipeOp will build a TCalyxLibBinaryPipeOp, to
/// deal with MulIOp, DivUIOp and RemUIOp.
template <typename TOpType, typename TSrcOp>
LogicalResult buildLibraryBinaryPipeOp(PatternRewriter &rewriter, TSrcOp op,
TOpType opPipe, Value out) const {
StringRef opName = TSrcOp::getOperationName().split(".").second;
Location loc = op.getLoc();
Type width = op.getResult().getType();
// Pass the result from the Operation to the Calyx primitive.
op.getResult().replaceAllUsesWith(out);
auto reg = createRegister(
op.getLoc(), rewriter, getComponent(), width.getIntOrFloatBitWidth(),
getState<ComponentLoweringState>().getUniqueName(opName));
// Operation pipelines are not combinational, so a GroupOp is required.
auto group = createGroupForOp<calyx::GroupOp>(rewriter, op);
OpBuilder builder(group->getRegion(0));
getState<ComponentLoweringState>().addBlockScheduleable(op->getBlock(),
group);
rewriter.setInsertionPointToEnd(group.getBodyBlock());
rewriter.create<calyx::AssignOp>(loc, opPipe.getLeft(), op.getLhs());
rewriter.create<calyx::AssignOp>(loc, opPipe.getRight(), op.getRhs());
// Write the output to this register.
rewriter.create<calyx::AssignOp>(loc, reg.getIn(), out);
// The write enable port is high when the pipeline is done.
rewriter.create<calyx::AssignOp>(loc, reg.getWriteEn(), opPipe.getDone());
// Set pipelineOp to high as long as its done signal is not high.
// This prevents the pipelineOP from executing for the cycle that we write
// to register. To get !(pipelineOp.done) we do 1 xor pipelineOp.done
hw::ConstantOp c1 = createConstant(loc, rewriter, getComponent(), 1, 1);
rewriter.create<calyx::AssignOp>(
loc, opPipe.getGo(), c1,
comb::createOrFoldNot(group.getLoc(), opPipe.getDone(), builder));
// The group is done when the register write is complete.
rewriter.create<calyx::GroupDoneOp>(loc, reg.getDone());
// Register the values for the pipeline.
getState<ComponentLoweringState>().registerEvaluatingGroup(out, group);
getState<ComponentLoweringState>().registerEvaluatingGroup(opPipe.getLeft(),
group);
getState<ComponentLoweringState>().registerEvaluatingGroup(
opPipe.getRight(), group);
return success();
}
/// Creates assignments within the provided group to the address ports of the
/// memoryOp based on the provided addressValues.
void assignAddressPorts(PatternRewriter &rewriter, Location loc,
calyx::GroupInterface group,
calyx::MemoryInterface memoryInterface,
Operation::operand_range addressValues) const {
IRRewriter::InsertionGuard guard(rewriter);
rewriter.setInsertionPointToEnd(group.getBody());
auto addrPorts = memoryInterface.addrPorts();
if (addressValues.empty()) {
assert(
addrPorts.size() == 1 &&
"We expected a 1 dimensional memory of size 1 because there were no "
"address assignment values");
// Assign to address 1'd0 in memory.
rewriter.create<calyx::AssignOp>(
loc, addrPorts[0],
createConstant(loc, rewriter, getComponent(), 1, 0));
} else {
assert(addrPorts.size() == addressValues.size() &&
"Mismatch between number of address ports of the provided memory "
"and address assignment values");
for (auto address : enumerate(addressValues))
rewriter.create<calyx::AssignOp>(loc, addrPorts[address.index()],
address.value());
}
}
};
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
memref::LoadOp loadOp) const {
Value memref = loadOp.getMemref();
auto memoryInterface =
getState<ComponentLoweringState>().getMemoryInterface(memref);
auto group = createGroupForOp<calyx::GroupOp>(rewriter, loadOp);
assignAddressPorts(rewriter, loadOp.getLoc(), group, memoryInterface,
loadOp.getIndices());
rewriter.setInsertionPointToEnd(group.getBodyBlock());
bool needReg = true;
Value res;
Value regWriteEn =
createConstant(loadOp.getLoc(), rewriter, getComponent(), 1, 1);
if (memoryInterface.readEnOpt().has_value()) {
auto oneI1 =
calyx::createConstant(loadOp.getLoc(), rewriter, getComponent(), 1, 1);
rewriter.create<calyx::AssignOp>(loadOp.getLoc(), memoryInterface.readEn(),
oneI1);
regWriteEn = memoryInterface.readDone();
if (calyx::noStoresToMemory(memref) &&
calyx::singleLoadFromMemory(memref)) {
// Single load from memory; we do not need to write the output to a
// register. The readData value will be held until readEn is asserted
// again
needReg = false;
rewriter.create<calyx::GroupDoneOp>(loadOp.getLoc(),
memoryInterface.readDone());
// We refrain from replacing the loadOp result with
// memoryInterface.readData, since multiple loadOp's need to be converted
// to a single memory's ReadData. If this replacement is done now, we lose
// the link between which SSA memref::LoadOp values map to which groups
// for loading a value from the Calyx memory. At this point of lowering,
// we keep the memref::LoadOp SSA value, and do value replacement _after_
// control has been generated (see LateSSAReplacement). This is *vital*
// for things such as calyx::InlineCombGroups to be able to properly track
// which memory assignment groups belong to which accesses.
res = loadOp.getResult();
}
}
if (needReg) {
// Multiple loads from the same memory; In this case, we _may_ have a
// structural hazard in the design we generate. To get around this, we
// conservatively place a register in front of each load operation, and
// replace all uses of the loaded value with the register output. Reading
// for sequential memories will cause a read to take at least 2 cycles,
// but it will usually be better because combinational reads on memories
// can significantly decrease the maximum achievable frequency.
auto reg = createRegister(
loadOp.getLoc(), rewriter, getComponent(),
loadOp.getMemRefType().getElementTypeBitWidth(),
getState<ComponentLoweringState>().getUniqueName("load"));
rewriter.setInsertionPointToEnd(group.getBodyBlock());
rewriter.create<calyx::AssignOp>(loadOp.getLoc(), reg.getIn(),
memoryInterface.readData());
rewriter.create<calyx::AssignOp>(loadOp.getLoc(), reg.getWriteEn(),
regWriteEn);
rewriter.create<calyx::GroupDoneOp>(loadOp.getLoc(), reg.getDone());
loadOp.getResult().replaceAllUsesWith(reg.getOut());
res = reg.getOut();
}
getState<ComponentLoweringState>().registerEvaluatingGroup(res, group);
getState<ComponentLoweringState>().addBlockScheduleable(loadOp->getBlock(),
group);
return success();
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
memref::StoreOp storeOp) const {
auto memoryInterface = getState<ComponentLoweringState>().getMemoryInterface(
storeOp.getMemref());
auto group = createGroupForOp<calyx::GroupOp>(rewriter, storeOp);
// This is a sequential group, so register it as being scheduleable for the
// block.
getState<ComponentLoweringState>().addBlockScheduleable(storeOp->getBlock(),
group);
assignAddressPorts(rewriter, storeOp.getLoc(), group, memoryInterface,
storeOp.getIndices());
rewriter.setInsertionPointToEnd(group.getBodyBlock());
rewriter.create<calyx::AssignOp>(
storeOp.getLoc(), memoryInterface.writeData(), storeOp.getValueToStore());
rewriter.create<calyx::AssignOp>(
storeOp.getLoc(), memoryInterface.writeEn(),
createConstant(storeOp.getLoc(), rewriter, getComponent(), 1, 1));
rewriter.create<calyx::GroupDoneOp>(storeOp.getLoc(),
memoryInterface.writeDone());
return success();
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
MulIOp mul) const {
Location loc = mul.getLoc();
Type width = mul.getResult().getType(), one = rewriter.getI1Type();
auto mulPipe =
getState<ComponentLoweringState>()
.getNewLibraryOpInstance<calyx::MultPipeLibOp>(
rewriter, loc, {one, one, one, width, width, width, one});
return buildLibraryBinaryPipeOp<calyx::MultPipeLibOp>(
rewriter, mul, mulPipe,
/*out=*/mulPipe.getOut());
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
DivUIOp div) const {
Location loc = div.getLoc();
Type width = div.getResult().getType(), one = rewriter.getI1Type();
auto divPipe =
getState<ComponentLoweringState>()
.getNewLibraryOpInstance<calyx::DivUPipeLibOp>(
rewriter, loc, {one, one, one, width, width, width, one});
return buildLibraryBinaryPipeOp<calyx::DivUPipeLibOp>(
rewriter, div, divPipe,
/*out=*/divPipe.getOut());
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
DivSIOp div) const {
Location loc = div.getLoc();
Type width = div.getResult().getType(), one = rewriter.getI1Type();
auto divPipe =
getState<ComponentLoweringState>()
.getNewLibraryOpInstance<calyx::DivSPipeLibOp>(
rewriter, loc, {one, one, one, width, width, width, one});
return buildLibraryBinaryPipeOp<calyx::DivSPipeLibOp>(
rewriter, div, divPipe,
/*out=*/divPipe.getOut());
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
RemUIOp rem) const {
Location loc = rem.getLoc();
Type width = rem.getResult().getType(), one = rewriter.getI1Type();
auto remPipe =
getState<ComponentLoweringState>()
.getNewLibraryOpInstance<calyx::RemUPipeLibOp>(
rewriter, loc, {one, one, one, width, width, width, one});
return buildLibraryBinaryPipeOp<calyx::RemUPipeLibOp>(
rewriter, rem, remPipe,
/*out=*/remPipe.getOut());
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
RemSIOp rem) const {
Location loc = rem.getLoc();
Type width = rem.getResult().getType(), one = rewriter.getI1Type();
auto remPipe =
getState<ComponentLoweringState>()
.getNewLibraryOpInstance<calyx::RemSPipeLibOp>(
rewriter, loc, {one, one, one, width, width, width, one});
return buildLibraryBinaryPipeOp<calyx::RemSPipeLibOp>(
rewriter, rem, remPipe,
/*out=*/remPipe.getOut());
}
template <typename TAllocOp>
static LogicalResult buildAllocOp(ComponentLoweringState &componentState,
PatternRewriter &rewriter, TAllocOp allocOp) {
rewriter.setInsertionPointToStart(
componentState.getComponentOp().getBodyBlock());
MemRefType memtype = allocOp.getType();
SmallVector<int64_t> addrSizes;
SmallVector<int64_t> sizes;
for (int64_t dim : memtype.getShape()) {
sizes.push_back(dim);
addrSizes.push_back(calyx::handleZeroWidth(dim));
}
// If memref has no size (e.g., memref<i32>) create a 1 dimensional memory of
// size 1.
if (sizes.empty() && addrSizes.empty()) {
sizes.push_back(1);
addrSizes.push_back(1);
}
auto memoryOp = rewriter.create<calyx::SeqMemoryOp>(
allocOp.getLoc(), componentState.getUniqueName("mem"),
memtype.getElementType().getIntOrFloatBitWidth(), sizes, addrSizes);
// Externalize memories by default. This makes it easier for the native
// compiler to provide initialized memories.
memoryOp->setAttr("external",
IntegerAttr::get(rewriter.getI1Type(), llvm::APInt(1, 1)));
componentState.registerMemoryInterface(allocOp.getResult(),
calyx::MemoryInterface(memoryOp));
return success();
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
memref::AllocOp allocOp) const {
return buildAllocOp(getState<ComponentLoweringState>(), rewriter, allocOp);
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
memref::AllocaOp allocOp) const {
return buildAllocOp(getState<ComponentLoweringState>(), rewriter, allocOp);
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
scf::YieldOp yieldOp) const {
if (yieldOp.getOperands().empty()) {
// If yield operands are empty, we assume we have a for loop.
auto forOp = dyn_cast<scf::ForOp>(yieldOp->getParentOp());
assert(forOp && "Empty yieldOps should only be located within ForOps");
ScfForOp forOpInterface(forOp);
// Get the ForLoop's Induction Register.
auto inductionReg =
getState<ComponentLoweringState>().getForLoopIterReg(forOpInterface, 0);
Type regWidth = inductionReg.getOut().getType();
// Adder should have same width as the inductionReg.
SmallVector<Type> types(3, regWidth);
auto addOp = getState<ComponentLoweringState>()
.getNewLibraryOpInstance<calyx::AddLibOp>(
rewriter, forOp.getLoc(), types);
auto directions = addOp.portDirections();
// For an add operation, we expect two input ports and one output port
SmallVector<Value, 2> opInputPorts;
Value opOutputPort;
for (auto dir : enumerate(directions)) {
switch (dir.value()) {
case calyx::Direction::Input: {
opInputPorts.push_back(addOp.getResult(dir.index()));
break;
}
case calyx::Direction::Output: {
opOutputPort = addOp.getResult(dir.index());
break;
}
}
}
// "Latch Group" increments inductionReg by forLoop's step value.
calyx::ComponentOp componentOp =
getState<ComponentLoweringState>().getComponentOp();
SmallVector<StringRef, 4> groupIdentifier = {
"incr", getState<ComponentLoweringState>().getUniqueName(forOp),
"induction", "var"};
auto groupOp = calyx::createGroup<calyx::GroupOp>(
rewriter, componentOp, forOp.getLoc(),
llvm::join(groupIdentifier, "_"));
rewriter.setInsertionPointToEnd(groupOp.getBodyBlock());
// Assign inductionReg.out to the left port of the adder.
Value leftOp = opInputPorts.front();
rewriter.create<calyx::AssignOp>(forOp.getLoc(), leftOp,
inductionReg.getOut());
// Assign forOp.getConstantStep to the right port of the adder.
Value rightOp = opInputPorts.back();
rewriter.create<calyx::AssignOp>(
forOp.getLoc(), rightOp,
createConstant(forOp->getLoc(), rewriter, componentOp,
regWidth.getIntOrFloatBitWidth(),
forOp.getConstantStep().value().getSExtValue()));
// Assign adder's output port to inductionReg.
buildAssignmentsForRegisterWrite(rewriter, groupOp, componentOp,
inductionReg, opOutputPort);
// Set group as For Loop's "latch" group.
getState<ComponentLoweringState>().setForLoopLatchGroup(forOpInterface,
groupOp);
getState<ComponentLoweringState>().registerEvaluatingGroup(opOutputPort,
groupOp);
return success();
}
// If yieldOp for a for loop is not empty, then we do not transform for loop.
if (dyn_cast<scf::ForOp>(yieldOp->getParentOp())) {
return yieldOp.getOperation()->emitError()
<< "Currently do not support non-empty yield operations inside for "
"loops. Run --scf-for-to-while before running --scf-to-calyx.";
}
if (auto whileOp = dyn_cast<scf::WhileOp>(yieldOp->getParentOp())) {
ScfWhileOp whileOpInterface(whileOp);
auto assignGroup =
getState<ComponentLoweringState>().buildWhileLoopIterArgAssignments(
rewriter, whileOpInterface,
getState<ComponentLoweringState>().getComponentOp(),
getState<ComponentLoweringState>().getUniqueName(whileOp) +
"_latch",
yieldOp->getOpOperands());
getState<ComponentLoweringState>().setWhileLoopLatchGroup(whileOpInterface,
assignGroup);
}
else if (auto ifOp = dyn_cast<scf::IfOp>(yieldOp->getParentOp())) {
bool isThenBranch = yieldOp->getParentRegion() == &ifOp.getThenRegion();
std::string branchName = isThenBranch ? "then" : "else";
std::string groupName = branchName + "_group";
auto ®ion = isThenBranch ? ifOp.getThenRegion() : ifOp.getElseRegion();
auto groupOp = calyx::createGroup<calyx::GroupOp>(
rewriter, getComponent(), region.getLoc(), groupName);
isThenBranch
? getState<ComponentLoweringState>().setThenGroup(ifOp, groupOp)
: getState<ComponentLoweringState>().setElseGroup(ifOp, groupOp);
for (auto operand : enumerate(yieldOp.getOperands())) {
std::string name =
branchName + "_yield_operand_" + std::to_string(operand.index());
auto reg = createRegister(
operand.value().getLoc(), rewriter, getComponent(),
operand.value().getType().getIntOrFloatBitWidth(), name);
isThenBranch ? getState<ComponentLoweringState>().addThenYieldRegs(
ifOp, reg, operand.index())
: getState<ComponentLoweringState>().addElseYieldRegs(
ifOp, reg, operand.index());
buildAssignmentsForRegisterWrite(
rewriter, groupOp,
getState<ComponentLoweringState>().getComponentOp(), reg,
operand.value());
getState<ComponentLoweringState>().registerEvaluatingGroup(
ifOp.getResult(operand.index()), groupOp);
}
}
return success();
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
scf::IfOp ifOp) const {
getState<ComponentLoweringState>().addBlockScheduleable(
ifOp.getOperation()->getBlock(), IfScheduleable{ifOp});
return success();
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
BranchOpInterface brOp) const {
/// Branch argument passing group creation
/// Branch operands are passed through registers. In BuildBasicBlockRegs we
/// created registers for all branch arguments of each block. We now
/// create groups for assigning values to these registers.
Block *srcBlock = brOp->getBlock();
for (auto succBlock : enumerate(brOp->getSuccessors())) {
auto succOperands = brOp.getSuccessorOperands(succBlock.index());
if (succOperands.empty())
continue;
// Create operand passing group
std::string groupName = loweringState().blockName(srcBlock) + "_to_" +
loweringState().blockName(succBlock.value());
auto groupOp = calyx::createGroup<calyx::GroupOp>(rewriter, getComponent(),
brOp.getLoc(), groupName);
// Fetch block argument registers associated with the basic block
auto dstBlockArgRegs =
getState<ComponentLoweringState>().getBlockArgRegs(succBlock.value());
// Create register assignment for each block argument
for (auto arg : enumerate(succOperands.getForwardedOperands())) {
auto reg = dstBlockArgRegs[arg.index()];
calyx::buildAssignmentsForRegisterWrite(
rewriter, groupOp,
getState<ComponentLoweringState>().getComponentOp(), reg,
arg.value());
}
/// Register the group as a block argument group, to be executed
/// when entering the successor block from this block (srcBlock).
getState<ComponentLoweringState>().addBlockArgGroup(
srcBlock, succBlock.value(), groupOp);
}
return success();
}
/// For each return statement, we create a new group for assigning to the
/// previously created return value registers.
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
ReturnOp retOp) const {
if (retOp.getNumOperands() == 0)
return success();
std::string groupName =
getState<ComponentLoweringState>().getUniqueName("ret_assign");
auto groupOp = calyx::createGroup<calyx::GroupOp>(rewriter, getComponent(),
retOp.getLoc(), groupName);
for (auto op : enumerate(retOp.getOperands())) {
auto reg = getState<ComponentLoweringState>().getReturnReg(op.index());
calyx::buildAssignmentsForRegisterWrite(
rewriter, groupOp, getState<ComponentLoweringState>().getComponentOp(),
reg, op.value());
}
/// Schedule group for execution for when executing the return op block.
getState<ComponentLoweringState>().addBlockScheduleable(retOp->getBlock(),
groupOp);
return success();
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
arith::ConstantOp constOp) const {
/// Move constant operations to the compOp body as hw::ConstantOp's.
APInt value;
calyx::matchConstantOp(constOp, value);
auto hwConstOp = rewriter.replaceOpWithNewOp<hw::ConstantOp>(constOp, value);
hwConstOp->moveAfter(getComponent().getBodyBlock(),
getComponent().getBodyBlock()->begin());
return success();
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
AddIOp op) const {
return buildLibraryOp<calyx::CombGroupOp, calyx::AddLibOp>(rewriter, op);
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
SubIOp op) const {
return buildLibraryOp<calyx::CombGroupOp, calyx::SubLibOp>(rewriter, op);
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
ShRUIOp op) const {
return buildLibraryOp<calyx::CombGroupOp, calyx::RshLibOp>(rewriter, op);
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
ShRSIOp op) const {
return buildLibraryOp<calyx::CombGroupOp, calyx::SrshLibOp>(rewriter, op);
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
ShLIOp op) const {
return buildLibraryOp<calyx::CombGroupOp, calyx::LshLibOp>(rewriter, op);
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
AndIOp op) const {
return buildLibraryOp<calyx::CombGroupOp, calyx::AndLibOp>(rewriter, op);
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
OrIOp op) const {
return buildLibraryOp<calyx::CombGroupOp, calyx::OrLibOp>(rewriter, op);
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
XOrIOp op) const {
return buildLibraryOp<calyx::CombGroupOp, calyx::XorLibOp>(rewriter, op);
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
SelectOp op) const {
return buildLibraryOp<calyx::CombGroupOp, calyx::MuxLibOp>(rewriter, op);
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
CmpIOp op) const {
switch (op.getPredicate()) {
case CmpIPredicate::eq:
return buildLibraryOp<calyx::CombGroupOp, calyx::EqLibOp>(rewriter, op);
case CmpIPredicate::ne:
return buildLibraryOp<calyx::CombGroupOp, calyx::NeqLibOp>(rewriter, op);
case CmpIPredicate::uge:
return buildLibraryOp<calyx::CombGroupOp, calyx::GeLibOp>(rewriter, op);
case CmpIPredicate::ult:
return buildLibraryOp<calyx::CombGroupOp, calyx::LtLibOp>(rewriter, op);
case CmpIPredicate::ugt:
return buildLibraryOp<calyx::CombGroupOp, calyx::GtLibOp>(rewriter, op);
case CmpIPredicate::ule:
return buildLibraryOp<calyx::CombGroupOp, calyx::LeLibOp>(rewriter, op);
case CmpIPredicate::sge:
return buildLibraryOp<calyx::CombGroupOp, calyx::SgeLibOp>(rewriter, op);
case CmpIPredicate::slt:
return buildLibraryOp<calyx::CombGroupOp, calyx::SltLibOp>(rewriter, op);
case CmpIPredicate::sgt:
return buildLibraryOp<calyx::CombGroupOp, calyx::SgtLibOp>(rewriter, op);
case CmpIPredicate::sle:
return buildLibraryOp<calyx::CombGroupOp, calyx::SleLibOp>(rewriter, op);
}
llvm_unreachable("unsupported comparison predicate");
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
TruncIOp op) const {
return buildLibraryOp<calyx::CombGroupOp, calyx::SliceLibOp>(
rewriter, op, {op.getOperand().getType()}, {op.getType()});
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
ExtUIOp op) const {
return buildLibraryOp<calyx::CombGroupOp, calyx::PadLibOp>(
rewriter, op, {op.getOperand().getType()}, {op.getType()});
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
ExtSIOp op) const {
return buildLibraryOp<calyx::CombGroupOp, calyx::ExtSILibOp>(
rewriter, op, {op.getOperand().getType()}, {op.getType()});
}
LogicalResult BuildOpGroups::buildOp(PatternRewriter &rewriter,
IndexCastOp op) const {
Type sourceType = calyx::convIndexType(rewriter, op.getOperand().getType());
Type targetType = calyx::convIndexType(rewriter, op.getResult().getType());
unsigned targetBits = targetType.getIntOrFloatBitWidth();
unsigned sourceBits = sourceType.getIntOrFloatBitWidth();
LogicalResult res = success();
if (targetBits == sourceBits) {
/// Drop the index cast and replace uses of the target value with the source
/// value.
op.getResult().replaceAllUsesWith(op.getOperand());
} else {
/// pad/slice the source operand.
if (sourceBits > targetBits)