This repository has been archived by the owner on May 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
EmitHLSPy.cpp
1663 lines (1458 loc) · 50.1 KB
/
EmitHLSPy.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
//===----------------------------------------------------------------------===//
//
// Adapated from ScaleHLS https://github.com/hanchenye/scalehls
//
//===----------------------------------------------------------------------===//
#include "EmitHLSPy.h"
#include "llvm/ADT/APFloat.h"
#include "Utils.h"
#include "Visitor.h"
#include "mlir/IR/AffineExprVisitor.h"
#include "mlir/IR/AsmState.h"
#include "mlir/IR/IntegerSet.h"
#include "mlir/Tools/mlir-translate/Translation.h"
#include "llvm/Support/raw_ostream.h"
#include <iostream>
using namespace mlir;
using namespace openhls;
//===----------------------------------------------------------------------===//
// Utils
//===----------------------------------------------------------------------===//
static SmallString<16> getTypeName(Value val) {
// Handle memref, tensor, and vector types.
auto valType = val.getType();
if (auto arrayType = val.getType().dyn_cast<ShapedType>())
valType = arrayType.getElementType();
// Handle float types.
if (valType.isa<Float32Type>())
return SmallString<16>("float");
else if (valType.isa<Float64Type>())
return SmallString<16>("double");
// Handle integer types.
else if (valType.isa<IndexType>())
return SmallString<16>("int");
else if (auto intType = valType.dyn_cast<IntegerType>()) {
if (intType.getWidth() == 1)
return SmallString<16>("bool");
else {
std::string signedness = "";
if (intType.getSignedness() == IntegerType::SignednessSemantics::Unsigned)
signedness = "u";
switch (intType.getWidth()) {
case 8:
case 16:
case 32:
case 64:
return SmallString<16>(signedness + "int" +
std::to_string(intType.getWidth()) + "_t");
default:
return SmallString<16>("ap_" + signedness + "int<" +
std::to_string(intType.getWidth()) + ">");
}
}
} else
val.getDefiningOp()->emitError("has unsupported type.");
return SmallString<16>();
}
//===----------------------------------------------------------------------===//
// Some Base Classes
//===----------------------------------------------------------------------===//
namespace {
/// This class maintains the mutable state that cross-cuts and is shared by the
/// various emitters.
class OpenHLSEmitterState {
public:
explicit OpenHLSEmitterState(raw_ostream &os) : os(os) {}
// The stream to emit to.
raw_ostream &os;
bool encounteredError = false;
unsigned currentIndent = 0;
// This table contains all declared values.
DenseMap<Value, SmallString<8>> nameTable;
private:
OpenHLSEmitterState(const OpenHLSEmitterState &) = delete;
void operator=(const OpenHLSEmitterState &) = delete;
};
} // namespace
namespace {
/// This is the base class for all of the HLSPy Emitter components.
class OpenHLSEmitterBase {
public:
explicit OpenHLSEmitterBase(OpenHLSEmitterState &state)
: state(state), os(state.os) {}
InFlightDiagnostic emitError(Operation *op, const Twine &message) {
state.encounteredError = true;
return op->emitError(message);
}
raw_ostream &indent() { return os.indent(state.currentIndent); }
void addIndent() { state.currentIndent += 2; }
void reduceIndent() { state.currentIndent -= 2; }
// All of the mutable state we are maintaining.
OpenHLSEmitterState &state;
// The stream to emit to.
raw_ostream &os;
/// Value name management methods.
SmallString<8> addName(Value val, bool isPtr = false);
void removeName(Value val);
SmallString<8> addAlias(Value val, Value alias);
SmallString<8> getName(Value val);
bool isDeclared(Value val) {
if (getName(val).empty()) {
return false;
} else
return true;
}
private:
OpenHLSEmitterBase(const OpenHLSEmitterBase &) = delete;
void operator=(const OpenHLSEmitterBase &) = delete;
};
} // namespace
// TODO: update naming rule.
SmallString<8> OpenHLSEmitterBase::addName(Value val, bool isPtr) {
assert(!isDeclared(val) && "has been declared before.");
SmallString<8> valName;
std::string s;
llvm::raw_string_ostream rs{s};
AsmState asmState(val.getParentRegion()->getParentOfType<FuncOp>());
val.printAsOperand(rs, asmState);
std::replace(s.begin(), s.end(), '%', '_');
valName = llvm::StringRef(s);
state.nameTable[val] = valName;
return valName;
}
SmallString<8> OpenHLSEmitterBase::addAlias(Value val, Value alias) {
assert(!isDeclared(alias) && "has been declared before.");
assert(isDeclared(val) && "hasn't been declared before.");
auto valName = getName(val);
state.nameTable[alias] = valName;
return valName;
}
void OpenHLSEmitterBase::removeName(Value val) {
assert(isDeclared(val) && "has not been declared before.");
val.dump();
state.nameTable.erase(val);
}
SmallString<8> OpenHLSEmitterBase::getName(Value val) {
// For constant scalar operations, the constant number will be returned rather
// than the value name.
// if (val.getType().dyn_cast<ShapedType>()) {
// return {"arr_" + state.nameTable.lookup(val).str().str()};
// }
if (auto defOp = val.getDefiningOp()) {
if (auto constOp = dyn_cast<arith::ConstantOp>(defOp)) {
auto constAttr = constOp.getValue();
if (auto floatAttr = constAttr.dyn_cast<FloatAttr>()) {
auto value = floatAttr.getValueAsDouble();
if (std::isfinite(value))
return SmallString<8>(std::to_string(value));
else if (value > 0)
return SmallString<8>("INFINITY");
else
return SmallString<8>("-INFINITY");
} else if (auto intAttr = constAttr.dyn_cast<IntegerAttr>()) {
auto value = intAttr.getInt();
return SmallString<8>(std::to_string(value));
} else if (auto boolAttr = constAttr.dyn_cast<BoolAttr>())
return SmallString<8>(std::to_string(boolAttr.getValue()));
}
}
return state.nameTable.lookup(val);
}
//===----------------------------------------------------------------------===//
// ModuleEmitter Class Declaration
//===----------------------------------------------------------------------===//
namespace {
class ModuleEmitter : public OpenHLSEmitterBase {
public:
using operand_range = Operation::operand_range;
explicit ModuleEmitter(OpenHLSEmitterState &state)
: OpenHLSEmitterBase(state) {}
/// SCF statement emitters.
void emitScfFor(scf::ForOp op);
void emitScfIf(scf::IfOp op);
void emitScfYield(scf::YieldOp op);
/// Affine statement emitters.
void emitAffineFor(AffineForOp op);
void emitAffineIf(AffineIfOp op);
void emitAffineParallel(AffineParallelOp op);
void emitAffineApply(AffineApplyOp op);
template <typename OpType>
void emitAffineMaxMin(OpType op, const char *syntax);
void emitAffineLoad(AffineLoadOp op);
void emitAffineStore(AffineStoreOp op);
void emitAffineYield(AffineYieldOp op);
/// Vector-related statement emitters.
void emitTransferRead(vector::TransferReadOp op);
void emitTransferWrite(vector::TransferWriteOp op);
void emitBroadcast(vector::BroadcastOp);
/// Memref-related statement emitters.
template <typename OpType> void emitAlloc(OpType op);
void emitLoad(memref::LoadOp op);
void emitStore(memref::StoreOp op);
void emitMemCpy(memref::CopyOp op);
void emitMemSubview(memref::SubViewOp op);
void emitGlobal(memref::GlobalOp op);
void emitGetGlobal(memref::GetGlobalOp op);
void emitTensorStore(memref::TensorStoreOp op);
template <typename OpType> void emitReshape(OpType op);
void emitTensorToMemref(bufferization::ToMemrefOp op);
void emitMemrefToTensor(bufferization::ToTensorOp op);
/// HLS dialect operation emitters.
// void emitStreamChannel(StreamChannelOp op);
// void emitStreamRead(StreamReadOp op);
// void emitStreamWrite(StreamWriteOp op);
// void emitPrimMul(PrimMulOp op);
template <typename AssignOpType> void emitAssign(AssignOpType op);
int apply_counter = 0;
/// Control flow operation emitters.
void emitCall(func::CallOp op);
/// Standard expression emitters.
void emitUnary(Operation *op, const char *syntax);
void emitBinary(Operation *op, const char *syntax);
template <typename OpType> void emitMaxMin(OpType op, const char *syntax);
/// Special expression emitters.
void emitSelect(arith::SelectOp op);
void emitConstant(arith::ConstantOp op);
/// Top-level MLIR module emitter.
void emitModule(ModuleOp module);
private:
/// Helper to get the string indices of TransferRead/Write operations.
template <typename TransferOpType>
SmallVector<SmallString<8>, 4> getTransferIndices(TransferOpType op);
/// C++ component emitters.
void emitValue(Value val, unsigned rank = 0, bool isPtr = false,
bool isRef = false);
void emitArrayDecl(Value array, bool input = false, bool output = false);
unsigned emitNestedLoopHeader(Value val);
void emitNestedLoopFooter(unsigned rank);
void emitInfoAndNewLine(Operation *op);
/// MLIR component and HLS C++ pragma emitters.
void emitBlock(Block &block);
void emitFunction(FuncOp func);
};
} // namespace
//===----------------------------------------------------------------------===//
// AffineEmitter Class
//===----------------------------------------------------------------------===//
namespace {
class AffineExprEmitter : public OpenHLSEmitterBase,
public AffineExprVisitor<AffineExprEmitter> {
public:
using operand_range = Operation::operand_range;
explicit AffineExprEmitter(OpenHLSEmitterState &state, unsigned numDim,
operand_range operands)
: OpenHLSEmitterBase(state), numDim(numDim), operands(operands) {}
void visitAddExpr(AffineBinaryOpExpr expr) { emitAffineBinary(expr, "+"); }
void visitMulExpr(AffineBinaryOpExpr expr) { emitAffineBinary(expr, "*"); }
void visitModExpr(AffineBinaryOpExpr expr) { emitAffineBinary(expr, "%"); }
void visitFloorDivExpr(AffineBinaryOpExpr expr) {
emitAffineBinary(expr, "//");
}
void visitCeilDivExpr(AffineBinaryOpExpr expr) {
// This is super inefficient.
os << "(";
visit(expr.getLHS());
os << " + ";
visit(expr.getRHS());
os << " - 1) // ";
visit(expr.getRHS());
os << ")";
}
void visitConstantExpr(AffineConstantExpr expr) { os << expr.getValue(); }
void visitDimExpr(AffineDimExpr expr) {
os << getName(operands[expr.getPosition()]);
}
void visitSymbolExpr(AffineSymbolExpr expr) {
os << getName(operands[numDim + expr.getPosition()]);
}
/// Affine expression emitters.
void emitAffineBinary(AffineBinaryOpExpr expr, const char *syntax) {
os << "(";
if (auto constRHS = expr.getRHS().dyn_cast<AffineConstantExpr>()) {
if ((unsigned)*syntax == (unsigned)*"*" && constRHS.getValue() == -1) {
os << "-";
visit(expr.getLHS());
os << ")";
return;
}
if ((unsigned)*syntax == (unsigned)*"+" && constRHS.getValue() < 0) {
visit(expr.getLHS());
os << " - ";
os << -constRHS.getValue();
os << ")";
return;
}
}
if (auto binaryRHS = expr.getRHS().dyn_cast<AffineBinaryOpExpr>()) {
if (auto constRHS = binaryRHS.getRHS().dyn_cast<AffineConstantExpr>()) {
if ((unsigned)*syntax == (unsigned)*"+" && constRHS.getValue() == -1 &&
binaryRHS.getKind() == AffineExprKind::Mul) {
visit(expr.getLHS());
os << " - ";
visit(binaryRHS.getLHS());
os << ")";
return;
}
}
}
visit(expr.getLHS());
os << " " << syntax << " ";
visit(expr.getRHS());
os << ")";
}
void emitAffineExpr(AffineExpr expr) { visit(expr); }
private:
unsigned numDim;
operand_range operands;
};
} // namespace
//===----------------------------------------------------------------------===//
// StmtVisitor, ExprVisitor, and PragmaVisitor Classes
//===----------------------------------------------------------------------===//
namespace {
class StmtVisitor : public HLSVisitorBase<StmtVisitor, bool> {
public:
StmtVisitor(ModuleEmitter &emitter) : emitter(emitter) {}
using HLSVisitorBase::visitOp;
/// SCF statements.
bool visitOp(scf::ForOp op) { return emitter.emitScfFor(op), true; };
bool visitOp(scf::IfOp op) { return emitter.emitScfIf(op), true; };
bool visitOp(scf::ParallelOp op) { return false; };
bool visitOp(scf::ReduceOp op) { return false; };
bool visitOp(scf::ReduceReturnOp op) { return false; };
bool visitOp(scf::YieldOp op) { return emitter.emitScfYield(op), true; };
/// Affine statements.
bool visitOp(AffineForOp op) { return emitter.emitAffineFor(op), true; }
bool visitOp(AffineIfOp op) { return emitter.emitAffineIf(op), true; }
bool visitOp(AffineParallelOp op) {
return emitter.emitAffineParallel(op), true;
}
bool visitOp(AffineApplyOp op) { return emitter.emitAffineApply(op), true; }
bool visitOp(AffineMaxOp op) {
return emitter.emitAffineMaxMin(op, "max"), true;
}
bool visitOp(AffineMinOp op) {
return emitter.emitAffineMaxMin(op, "min"), true;
}
bool visitOp(AffineLoadOp op) { return emitter.emitAffineLoad(op), true; }
bool visitOp(AffineStoreOp op) { return emitter.emitAffineStore(op), true; }
bool visitOp(AffineVectorLoadOp op) { return false; }
bool visitOp(AffineVectorStoreOp op) { return false; }
bool visitOp(AffineYieldOp op) { return emitter.emitAffineYield(op), true; }
/// Vector-related statements.
bool visitOp(vector::TransferReadOp op) {
return emitter.emitTransferRead(op), true;
};
bool visitOp(vector::TransferWriteOp op) {
return emitter.emitTransferWrite(op), true;
};
bool visitOp(vector::BroadcastOp op) {
return emitter.emitBroadcast(op), true;
};
/// Memref-related statements.
bool visitOp(memref::AllocOp op) { return emitter.emitAlloc(op), true; }
bool visitOp(memref::AllocaOp op) { return emitter.emitAlloc(op), true; }
bool visitOp(memref::LoadOp op) { return emitter.emitLoad(op), true; }
bool visitOp(memref::StoreOp op) { return emitter.emitStore(op), true; }
bool visitOp(memref::DeallocOp op) { return true; }
bool visitOp(memref::CopyOp op) { return emitter.emitMemCpy(op), true; }
bool visitOp(memref::SubViewOp op) { return emitter.emitMemSubview(op), true; }
bool visitOp(memref::GlobalOp op) { return emitter.emitGlobal(op), true; }
bool visitOp(memref::GetGlobalOp op) {
return emitter.emitGetGlobal(op), true;
}
bool visitOp(memref::TensorStoreOp op) {
return emitter.emitTensorStore(op), true;
}
bool visitOp(tensor::ReshapeOp op) { return emitter.emitReshape(op), true; }
bool visitOp(memref::ReshapeOp op) { return emitter.emitReshape(op), true; }
bool visitOp(memref::CollapseShapeOp op) {
return emitter.emitReshape(op), true;
}
bool visitOp(memref::ExpandShapeOp op) {
return emitter.emitReshape(op), true;
}
bool visitOp(memref::ReinterpretCastOp op) {
return emitter.emitReshape(op), true;
}
bool visitOp(bufferization::ToMemrefOp op) {
return emitter.emitTensorToMemref(op), true;
}
bool visitOp(bufferization::ToTensorOp op) {
return emitter.emitMemrefToTensor(op), true;
}
/// Control flow operations.
bool visitOp(func::CallOp op) { return emitter.emitCall(op), true; }
bool visitOp(func::ReturnOp op) { return true; }
private:
ModuleEmitter &emitter;
};
} // namespace
namespace {
class ExprVisitor : public HLSVisitorBase<ExprVisitor, bool> {
public:
ExprVisitor(ModuleEmitter &emitter) : emitter(emitter) {}
using HLSVisitorBase::visitOp;
/// Unary expressions.
bool visitOp(math::AbsOp op) { return emitter.emitUnary(op, "Abs"), true; }
bool visitOp(math::CeilOp op) { return emitter.emitUnary(op, "Ceil"), true; }
bool visitOp(math::CosOp op) { return emitter.emitUnary(op, "Cos"), true; }
bool visitOp(math::SinOp op) { return emitter.emitUnary(op, "Sin"), true; }
bool visitOp(math::TanhOp op) { return emitter.emitUnary(op, "Tanh"), true; }
bool visitOp(math::SqrtOp op) { return emitter.emitUnary(op, "Sqrt"), true; }
bool visitOp(math::RsqrtOp op) {
return emitter.emitUnary(op, "1.0 / Sqrt"), true;
}
bool visitOp(math::ExpOp op) { return emitter.emitUnary(op, "Exp"), true; }
bool visitOp(math::Exp2Op op) { return emitter.emitUnary(op, "Exp2"), true; }
bool visitOp(math::LogOp op) { return emitter.emitUnary(op, "Log"), true; }
bool visitOp(math::Log2Op op) { return emitter.emitUnary(op, "Log2"), true; }
bool visitOp(math::Log10Op op) {
return emitter.emitUnary(op, "log10"), true;
}
bool visitOp(arith::NegFOp op) { return emitter.emitUnary(op, "-"), true; }
/// Float binary expressions.
bool visitOp(arith::CmpFOp op);
bool visitOp(arith::AddFOp op) { return emitter.emitBinary(op, "+"), true; }
bool visitOp(arith::SubFOp op) { return emitter.emitBinary(op, "-"), true; }
bool visitOp(arith::MulFOp op) { return emitter.emitBinary(op, "*"), true; }
bool visitOp(arith::DivFOp op) { return emitter.emitBinary(op, "/"), true; }
bool visitOp(arith::RemFOp op) { return emitter.emitBinary(op, "%"), true; }
bool visitOp(arith::MaxFOp op) { return emitter.emitMaxMin(op, "max"), true; }
bool visitOp(arith::MinFOp op) { return emitter.emitMaxMin(op, "min"), true; }
/// Integer binary expressions.
bool visitOp(arith::CmpIOp op);
bool visitOp(arith::AddIOp op) { return emitter.emitBinary(op, "+"), true; }
bool visitOp(arith::SubIOp op) { return emitter.emitBinary(op, "-"), true; }
bool visitOp(arith::MulIOp op) { return emitter.emitBinary(op, "*"), true; }
bool visitOp(arith::DivSIOp op) { return emitter.emitBinary(op, "/"), true; }
bool visitOp(arith::RemSIOp op) { return emitter.emitBinary(op, "%"), true; }
bool visitOp(arith::DivUIOp op) { return emitter.emitBinary(op, "/"), true; }
bool visitOp(arith::RemUIOp op) { return emitter.emitBinary(op, "%"), true; }
bool visitOp(arith::XOrIOp op) { return emitter.emitBinary(op, "^"), true; }
bool visitOp(arith::AndIOp op) { return emitter.emitBinary(op, "&"), true; }
bool visitOp(arith::OrIOp op) { return emitter.emitBinary(op, "|"), true; }
bool visitOp(arith::ShLIOp op) { return emitter.emitBinary(op, "<<"), true; }
bool visitOp(arith::ShRSIOp op) { return emitter.emitBinary(op, ">>"), true; }
bool visitOp(arith::ShRUIOp op) { return emitter.emitBinary(op, ">>"), true; }
bool visitOp(arith::MaxSIOp op) {
return emitter.emitMaxMin(op, "max"), true;
}
bool visitOp(arith::MinSIOp op) {
return emitter.emitMaxMin(op, "min"), true;
}
bool visitOp(arith::MaxUIOp op) {
return emitter.emitMaxMin(op, "max"), true;
}
bool visitOp(arith::MinUIOp op) {
return emitter.emitMaxMin(op, "min"), true;
}
/// Special expressions.
bool visitOp(arith::SelectOp op) { return emitter.emitSelect(op), true; }
bool visitOp(arith::ConstantOp op) { return emitter.emitConstant(op), true; }
bool visitOp(arith::IndexCastOp op) { return emitter.emitAssign(op), true; }
bool visitOp(arith::UIToFPOp op) { return emitter.emitAssign(op), true; }
bool visitOp(arith::SIToFPOp op) { return emitter.emitAssign(op), true; }
bool visitOp(arith::FPToUIOp op) { return emitter.emitAssign(op), true; }
bool visitOp(arith::FPToSIOp op) { return emitter.emitAssign(op), true; }
/// TODO: Figure out whether these ops need to be separately handled.
bool visitOp(arith::TruncIOp op) { return emitter.emitAssign(op), true; }
bool visitOp(arith::TruncFOp op) { return emitter.emitAssign(op), true; }
bool visitOp(arith::ExtUIOp op) { return emitter.emitAssign(op), true; }
bool visitOp(arith::ExtSIOp op) { return emitter.emitAssign(op), true; }
private:
ModuleEmitter &emitter;
};
} // namespace
bool ExprVisitor::visitOp(arith::CmpFOp op) {
switch (op.getPredicate()) {
case arith::CmpFPredicate::OEQ:
case arith::CmpFPredicate::UEQ:
return emitter.emitBinary(op, "=="), true;
case arith::CmpFPredicate::ONE:
case arith::CmpFPredicate::UNE:
return emitter.emitBinary(op, "!="), true;
case arith::CmpFPredicate::OLT:
case arith::CmpFPredicate::ULT:
return emitter.emitBinary(op, "<"), true;
case arith::CmpFPredicate::OLE:
case arith::CmpFPredicate::ULE:
return emitter.emitBinary(op, "<="), true;
case arith::CmpFPredicate::OGT:
case arith::CmpFPredicate::UGT:
return emitter.emitBinary(op, ">"), true;
case arith::CmpFPredicate::OGE:
case arith::CmpFPredicate::UGE:
return emitter.emitBinary(op, ">="), true;
default:
op.emitError("has unsupported compare type.");
return false;
}
}
bool ExprVisitor::visitOp(arith::CmpIOp op) {
switch (op.getPredicate()) {
case arith::CmpIPredicate::eq:
return emitter.emitBinary(op, "=="), true;
case arith::CmpIPredicate::ne:
return emitter.emitBinary(op, "!="), true;
case arith::CmpIPredicate::slt:
case arith::CmpIPredicate::ult:
return emitter.emitBinary(op, "<"), true;
case arith::CmpIPredicate::sle:
case arith::CmpIPredicate::ule:
return emitter.emitBinary(op, "<="), true;
case arith::CmpIPredicate::sgt:
case arith::CmpIPredicate::ugt:
return emitter.emitBinary(op, ">"), true;
case arith::CmpIPredicate::sge:
case arith::CmpIPredicate::uge:
return emitter.emitBinary(op, ">="), true;
}
}
//===----------------------------------------------------------------------===//
// ModuleEmitter Class Definition
//===----------------------------------------------------------------------===//
/// SCF statement emitters.
void ModuleEmitter::emitScfFor(scf::ForOp op) {
indent() << "for ";
auto iterVar = op.getInductionVar();
std::string s;
llvm::raw_string_ostream rs{s};
AsmState asmState(op->getParentOfType<FuncOp>());
iterVar.printAsOperand(rs, asmState);
std::replace(s.begin(), s.end(), '%', '_');
state.nameTable[iterVar] = s;
os << s;
// emitValue(iterVar);
os << " in range(";
emitValue(op.getLowerBound());
os << ", ";
emitValue(op.getUpperBound());
os << ", ";
emitValue(op.getStep());
os << "):";
os << "\n";
addIndent();
emitBlock(*op.getBody());
state.nameTable.erase(iterVar);
reduceIndent();
indent() << "\n";
}
void ModuleEmitter::emitScfIf(scf::IfOp op) {
// Declare all values returned by scf::YieldOp. They will be further handled
// by the scf::YieldOp emitter.
for (auto result : op.getResults()) {
if (!isDeclared(result)) {
indent();
if (result.getType().isa<ShapedType>())
emitArrayDecl(result);
else
emitValue(result);
os << "\n";
}
}
indent() << "if (";
emitValue(op.getCondition());
os << "):";
os << "\n";
addIndent();
emitBlock(op.getThenRegion().front());
reduceIndent();
if (!op.getElseRegion().empty()) {
indent() << "else:\n";
addIndent();
emitBlock(op.getElseRegion().front());
reduceIndent();
}
indent() << "\n";
}
void ModuleEmitter::emitScfYield(scf::YieldOp op) {
if (op.getNumOperands() == 0)
return;
// For now, only and scf::If operations will use scf::Yield to return
// generated values.
if (auto parentOp = dyn_cast<scf::IfOp>(op->getParentOp())) {
unsigned resultIdx = 0;
for (auto result : parentOp.getResults()) {
unsigned rank = emitNestedLoopHeader(result);
indent();
emitValue(result, rank);
os << " = ";
emitValue(op.getOperand(resultIdx++), rank);
os << "\n";
emitNestedLoopFooter(rank);
}
}
}
/// Affine statement emitters.
void ModuleEmitter::emitAffineFor(AffineForOp op) {
indent() << "for ";
auto iterVar = op.getInductionVar();
// Emit lower bound.
emitValue(iterVar);
os << " in range(";
auto lowerMap = op.getLowerBoundMap();
AffineExprEmitter lowerEmitter(state, lowerMap.getNumDims(),
op.getLowerBoundOperands());
if (lowerMap.getNumResults() == 1)
lowerEmitter.emitAffineExpr(lowerMap.getResult(0));
else {
for (unsigned i = 0, e = lowerMap.getNumResults() - 1; i < e; ++i)
os << "max(";
lowerEmitter.emitAffineExpr(lowerMap.getResult(0));
for (auto &expr : llvm::drop_begin(lowerMap.getResults(), 1)) {
os << ", ";
lowerEmitter.emitAffineExpr(expr);
os << ")";
}
}
os << ", ";
// Emit upper bound.
auto upperMap = op.getUpperBoundMap();
AffineExprEmitter upperEmitter(state, upperMap.getNumDims(),
op.getUpperBoundOperands());
if (upperMap.getNumResults() == 1)
upperEmitter.emitAffineExpr(upperMap.getResult(0));
else {
for (unsigned i = 0, e = upperMap.getNumResults() - 1; i < e; ++i)
os << "min(";
upperEmitter.emitAffineExpr(upperMap.getResult(0));
for (auto &expr : llvm::drop_begin(upperMap.getResults(), 1)) {
os << ", ";
upperEmitter.emitAffineExpr(expr);
os << ")";
}
}
os << ", " << op.getStep() << "):";
os << "\n";
addIndent();
emitBlock(*op.getBody());
reduceIndent();
indent() << "\n";
}
void ModuleEmitter::emitAffineIf(AffineIfOp op) {
// Declare all values returned by AffineYieldOp. They will be further
// handled by the AffineYieldOp emitter.
for (auto result : op.getResults()) {
if (!isDeclared(result)) {
indent();
if (result.getType().isa<ShapedType>())
emitArrayDecl(result);
else
emitValue(result);
os << "\n";
}
}
indent() << "if (";
auto constrSet = op.getIntegerSet();
AffineExprEmitter constrEmitter(state, constrSet.getNumDims(),
op.getOperands());
// Emit all constraints.
unsigned constrIdx = 0;
for (auto &expr : constrSet.getConstraints()) {
constrEmitter.emitAffineExpr(expr);
if (constrSet.isEq(constrIdx))
os << " == 0";
else
os << " >= 0";
if (constrIdx++ != constrSet.getNumConstraints() - 1)
os << " and ";
}
os << "):";
os << "\n";
addIndent();
emitBlock(*op.getThenBlock());
reduceIndent();
if (op.hasElse()) {
indent() << "else:\n";
addIndent();
emitBlock(*op.getElseBlock());
reduceIndent();
}
indent() << "\n";
}
void ModuleEmitter::emitAffineParallel(AffineParallelOp op) {
// Declare all values returned by AffineParallelOp. They will be further
// handled by the AffineYieldOp emitter.
for (auto result : op.getResults()) {
if (!isDeclared(result)) {
indent();
if (result.getType().isa<ShapedType>())
emitArrayDecl(result);
else
emitValue(result);
os << "\n";
}
}
os << "\n";
indent() << "@parfor(";
auto steps = getIntArrayAttrValue(op, op.getStepsAttrName());
for (unsigned i = 0, e = op.getNumDims(); i < e; ++i) {
auto iterVar = op.getBody()->getArgument(i);
emitValue(iterVar);
os << "=(";
auto lowerMap = op.getLowerBoundsValueMap().getAffineMap();
AffineExprEmitter lowerEmitter(state, lowerMap.getNumDims(),
op.getLowerBoundsOperands());
lowerEmitter.emitAffineExpr(lowerMap.getResult(i));
os << ", ";
auto upperMap = op.getUpperBoundsValueMap().getAffineMap();
AffineExprEmitter upperEmitter(state, upperMap.getNumDims(),
op.getUpperBoundsOperands());
upperEmitter.emitAffineExpr(upperMap.getResult(i));
os << ", ";
os << steps[i] << ")";
if (i < op.getNumDims()-1)
os << ", ";
}
os << ")\n";
indent() << "def body(";
for (unsigned i = 0, e = op.getNumDims(); i < e; ++i) {
auto iterVar = op.getBody()->getArgument(i);
emitValue(iterVar);
if (i < op.getNumDims()-1)
os << ", ";
}
os << "):";
os << "\n";
addIndent();
emitBlock(*op.getBody());
reduceIndent();
os << "\n\n";
}
void ModuleEmitter::emitAffineApply(AffineApplyOp op) {
indent();
emitValue(op.getResult());
os << " = ";
auto affineMap = op.getAffineMap();
AffineExprEmitter(state, affineMap.getNumDims(), op.getOperands())
.emitAffineExpr(affineMap.getResult(0));
os << "\n";
}
template <typename OpType>
void ModuleEmitter::emitAffineMaxMin(OpType op, const char *syntax) {
indent();
emitValue(op.getResult());
os << " = ";
auto affineMap = op.getAffineMap();
AffineExprEmitter affineEmitter(state, affineMap.getNumDims(),
op.getOperands());
for (unsigned i = 0, e = affineMap.getNumResults() - 1; i < e; ++i)
os << syntax << "(";
affineEmitter.emitAffineExpr(affineMap.getResult(0));
for (auto &expr : llvm::drop_begin(affineMap.getResults(), 1)) {
os << ", ";
affineEmitter.emitAffineExpr(expr);
os << ")";
}
os << "\n";
}
void ModuleEmitter::emitAffineLoad(AffineLoadOp op) {
indent();
emitValue(op.getResult());
os << " = ";
emitValue(op.getMemRef());
auto affineMap = op.getAffineMap();
AffineExprEmitter affineEmitter(state, affineMap.getNumDims(),
op.getMapOperands());
os << "[";
for (auto index : affineMap.getResults()) {
affineEmitter.emitAffineExpr(index);
}
os << "]\n";
}
void ModuleEmitter::emitAffineStore(AffineStoreOp op) {
indent();
emitValue(op.getMemRef());
auto affineMap = op.getAffineMap();
AffineExprEmitter affineEmitter(state, affineMap.getNumDims(),
op.getMapOperands());
os << "[";
for (auto index : affineMap.getResults()) {
affineEmitter.emitAffineExpr(index);
os << ",";
}
os << "]";
os << " = ";
emitValue(op.getValueToStore());
}
// TODO: For now, all values created in the AffineIf region will be declared
// in the generated C++. However, values which will be returned by affine
// yield operation should not be declared again. How to "bind" the pair of
// values inside/outside of AffineIf region needs to be considered.
void ModuleEmitter::emitAffineYield(AffineYieldOp op) {
if (op.getNumOperands() == 0)
return;
// For now, only AffineParallel and AffineIf operations will use
// AffineYield to return generated values.
if (auto parentOp = dyn_cast<AffineIfOp>(op->getParentOp())) {
unsigned resultIdx = 0;
for (auto result : parentOp.getResults()) {
unsigned rank = emitNestedLoopHeader(result);
indent();
emitValue(result, rank);
os << " = ";
emitValue(op.getOperand(resultIdx++), rank);
// os << "\n";
emitNestedLoopFooter(rank);
}
} else if (auto parentOp = dyn_cast<AffineParallelOp>(op->getParentOp())) {
indent() << "if (";
unsigned ivIdx = 0;
for (auto iv : parentOp.getBody()->getArguments()) {
emitValue(iv);
os << " == 0";
if (ivIdx++ != parentOp.getBody()->getNumArguments() - 1)
os << " and ";
}
os << "):\n";
// When all induction values are 0, generated values will be directly
// assigned to the current results, correspondingly.
addIndent();
unsigned resultIdx = 0;
for (auto result : parentOp.getResults()) {
unsigned rank = emitNestedLoopHeader(result);
indent();
emitValue(result, rank);
os << " = ";
emitValue(op.getOperand(resultIdx++), rank);
os << "\n";
emitNestedLoopFooter(rank);
}
reduceIndent();
indent() << "else:\n";
// Otherwise, generated values will be accumulated/reduced to the
// current results with corresponding arith::AtomicRMWKind operations.
addIndent();
auto RMWAttrs =
getIntArrayAttrValue(parentOp, parentOp.getReductionsAttrName());
resultIdx = 0;
for (auto result : parentOp.getResults()) {
unsigned rank = emitNestedLoopHeader(result);
indent();
emitValue(result, rank);
switch ((arith::AtomicRMWKind)RMWAttrs[resultIdx]) {
case (arith::AtomicRMWKind::addf):
case (arith::AtomicRMWKind::addi):
os << " += ";
emitValue(op.getOperand(resultIdx++), rank);
break;
case (arith::AtomicRMWKind::assign):
os << " = ";
emitValue(op.getOperand(resultIdx++), rank);
break;
case (arith::AtomicRMWKind::maxf):
case (arith::AtomicRMWKind::maxs):
case (arith::AtomicRMWKind::maxu):
os << " = max(";
emitValue(result, rank);
os << ", ";
emitValue(op.getOperand(resultIdx++), rank);
os << ")";
break;
case (arith::AtomicRMWKind::minf):
case (arith::AtomicRMWKind::mins):
case (arith::AtomicRMWKind::minu):
os << " = min(";
emitValue(result, rank);
os << ", ";
emitValue(op.getOperand(resultIdx++), rank);
os << ")";
break;
case (arith::AtomicRMWKind::mulf):
case (arith::AtomicRMWKind::muli):
os << " *= ";
emitValue(op.getOperand(resultIdx++), rank);
break;
case (arith::AtomicRMWKind::ori):
os << " |= ";
emitValue(op.getOperand(resultIdx++), rank);
break;
case (arith::AtomicRMWKind::andi):
os << " &= ";
emitValue(op.getOperand(resultIdx++), rank);
break;
}
os << "\n";
emitNestedLoopFooter(rank);
}
reduceIndent();
indent() << "\n";
}
}