forked from llvm/circt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExportVerilog.cpp
More file actions
7427 lines (6499 loc) · 258 KB
/
ExportVerilog.cpp
File metadata and controls
7427 lines (6499 loc) · 258 KB
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
//===- ExportVerilog.cpp - Verilog Emitter --------------------------------===//
//
// 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 Verilog emitter implementation.
//
// CAREFUL: This file covers the emission phase of `ExportVerilog` which mainly
// walks the IR and produces output. Do NOT modify the IR during this walk, as
// emission occurs in a highly parallel fashion. If you need to modify the IR,
// do so during the preparation phase which lives in `PrepareForEmission.cpp`.
//
//===----------------------------------------------------------------------===//
#include "circt/Conversion/ExportVerilog.h"
#include "ExportVerilogInternals.h"
#include "circt/Dialect/Comb/CombDialect.h"
#include "circt/Dialect/Comb/CombVisitors.h"
#include "circt/Dialect/Debug/DebugDialect.h"
#include "circt/Dialect/Emit/EmitOps.h"
#include "circt/Dialect/HW/HWAttributes.h"
#include "circt/Dialect/HW/HWOps.h"
#include "circt/Dialect/HW/HWTypes.h"
#include "circt/Dialect/HW/HWVisitors.h"
#include "circt/Dialect/LTL/LTLVisitors.h"
#include "circt/Dialect/OM/OMOps.h"
#include "circt/Dialect/SV/SVAttributes.h"
#include "circt/Dialect/SV/SVOps.h"
#include "circt/Dialect/SV/SVVisitors.h"
#include "circt/Dialect/Verif/VerifVisitors.h"
#include "circt/Support/LLVM.h"
#include "circt/Support/LoweringOptions.h"
#include "circt/Support/Path.h"
#include "circt/Support/PrettyPrinter.h"
#include "circt/Support/PrettyPrinterHelpers.h"
#include "circt/Support/Version.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/ImplicitLocOpBuilder.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/Threading.h"
#include "mlir/Interfaces/FunctionImplementation.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Support/FileUtilities.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/raw_ostream.h"
namespace circt {
#define GEN_PASS_DEF_EXPORTSPLITVERILOG
#define GEN_PASS_DEF_EXPORTVERILOG
#include "circt/Conversion/Passes.h.inc"
} // namespace circt
using namespace circt;
using namespace comb;
using namespace hw;
using namespace sv;
using namespace ExportVerilog;
using namespace pretty;
#define DEBUG_TYPE "export-verilog"
StringRef circtHeader = "circt_header.svh";
StringRef circtHeaderInclude = "`include \"circt_header.svh\"\n";
namespace {
/// This enum keeps track of the precedence level of various binary operators,
/// where a lower number binds tighter.
enum VerilogPrecedence {
// Normal precedence levels.
Symbol, // Atomic symbol like "foo" and {a,b}
Selection, // () , [] , :: , ., $signed()
Unary, // Unary operators like ~foo
Multiply, // * , / , %
Addition, // + , -
Shift, // << , >>, <<<, >>>
Comparison, // > , >= , < , <=
Equality, // == , !=
And, // &
Xor, // ^ , ^~
Or, // |
AndShortCircuit, // &&
Conditional, // ? :
LowestPrecedence, // Sentinel which is always the lowest precedence.
};
/// This enum keeps track of whether the emitted subexpression is signed or
/// unsigned as seen from the Verilog language perspective.
enum SubExprSignResult { IsSigned, IsUnsigned };
/// This is information precomputed about each subexpression in the tree we
/// are emitting as a unit.
struct SubExprInfo {
/// The precedence of this expression.
VerilogPrecedence precedence;
/// The signedness of the expression.
SubExprSignResult signedness;
SubExprInfo(VerilogPrecedence precedence, SubExprSignResult signedness)
: precedence(precedence), signedness(signedness) {}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Helper routines
//===----------------------------------------------------------------------===//
static TypedAttr getInt32Attr(MLIRContext *ctx, uint32_t value) {
return Builder(ctx).getI32IntegerAttr(value);
}
static TypedAttr getIntAttr(MLIRContext *ctx, Type t, const APInt &value) {
return Builder(ctx).getIntegerAttr(t, value);
}
/// Return true for nullary operations that are better emitted multiple
/// times as inline expression (when they have multiple uses) rather than having
/// a temporary wire.
///
/// This can only handle nullary expressions, because we don't want to replicate
/// subtrees arbitrarily.
static bool isDuplicatableNullaryExpression(Operation *op) {
// We don't want wires that are just constants aesthetically.
if (isConstantExpression(op))
return true;
// If this is a small verbatim expression with no side effects, duplicate it
// inline.
if (isa<VerbatimExprOp>(op)) {
if (op->getNumOperands() == 0 &&
op->getAttrOfType<StringAttr>("format_string").getValue().size() <= 32)
return true;
}
// Always duplicate XMRs into their use site.
if (isa<XMRRefOp>(op))
return true;
// If this is a macro reference without side effects, allow duplication.
if (isa<MacroRefExprOp>(op))
return true;
return false;
}
// Return true if the expression can be inlined even when the op has multiple
// uses. Be careful to add operations here since it might cause exponential
// emission without proper restrictions.
static bool isDuplicatableExpression(Operation *op) {
if (op->getNumOperands() == 0)
return isDuplicatableNullaryExpression(op);
// It is cheap to inline extract op.
if (isa<comb::ExtractOp, hw::StructExtractOp, hw::UnionExtractOp>(op))
return true;
// We only inline array_get with a constant, port or wire index.
if (auto array = dyn_cast<hw::ArrayGetOp>(op)) {
auto *indexOp = array.getIndex().getDefiningOp();
if (!indexOp || isa<ConstantOp>(indexOp))
return true;
if (auto read = dyn_cast<ReadInOutOp>(indexOp)) {
auto *readSrc = read.getInput().getDefiningOp();
// A port or wire is ok to duplicate reads.
return !readSrc || isa<sv::WireOp, LogicOp>(readSrc);
}
return false;
}
return false;
}
/// Return the verilog name of the operations that can define a symbol.
/// Legalized names are added to "hw.verilogName" so look up it when the
/// attribute already exists.
StringRef ExportVerilog::getSymOpName(Operation *symOp) {
// Typeswitch of operation types which can define a symbol.
// If legalizeNames has renamed it, then the attribute must be set.
if (auto attr = symOp->getAttrOfType<StringAttr>("hw.verilogName"))
return attr.getValue();
return TypeSwitch<Operation *, StringRef>(symOp)
.Case<HWModuleOp, HWModuleExternOp, HWModuleGeneratedOp,
sv::SVVerbatimModuleOp, FuncOp>(
[](Operation *op) { return getVerilogModuleName(op); })
.Case<SVVerbatimSourceOp>([](SVVerbatimSourceOp op) {
return op.getVerilogNameAttr().getValue();
})
.Case<InterfaceOp>([&](InterfaceOp op) {
return getVerilogModuleNameAttr(op).getValue();
})
.Case<InterfaceSignalOp>(
[&](InterfaceSignalOp op) { return op.getSymName(); })
.Case<InterfaceModportOp>(
[&](InterfaceModportOp op) { return op.getSymName(); })
.Default([&](Operation *op) {
if (auto attr = op->getAttrOfType<StringAttr>("name"))
return attr.getValue();
if (auto attr = op->getAttrOfType<StringAttr>("instanceName"))
return attr.getValue();
if (auto attr = op->getAttrOfType<StringAttr>("sv.namehint"))
return attr.getValue();
if (auto attr =
op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName()))
return attr.getValue();
return StringRef("");
});
}
/// Emits a known-safe token that is legal when indexing into singleton arrays.
template <typename PPS>
static void emitZeroWidthIndexingValue(PPS &os) {
os << "/*Zero width*/ 1\'b0";
}
/// Return the verilog name of the port for the module.
static StringRef getPortVerilogName(Operation *module, size_t portArgNum) {
auto hml = cast<HWModuleLike>(module);
return hml.getPort(portArgNum).getVerilogName();
}
/// Return the verilog name of the port for the module.
static StringRef getInputPortVerilogName(Operation *module, size_t portArgNum) {
auto hml = cast<HWModuleLike>(module);
auto pId = hml.getHWModuleType().getPortIdForInputId(portArgNum);
if (auto attrs = dyn_cast_or_null<DictionaryAttr>(hml.getPortAttrs(pId)))
if (auto updatedName = attrs.getAs<StringAttr>("hw.verilogName"))
return updatedName.getValue();
return hml.getHWModuleType().getPortName(pId);
}
/// This predicate returns true if the specified operation is considered a
/// potentially inlinable Verilog expression. These nodes always have a single
/// result, but may have side effects (e.g. `sv.verbatim.expr.se`).
/// MemoryEffects should be checked if a client cares.
bool ExportVerilog::isVerilogExpression(Operation *op) {
// These are SV dialect expressions.
if (isa<ReadInOutOp, AggregateConstantOp, ArrayIndexInOutOp,
IndexedPartSelectInOutOp, StructFieldInOutOp, IndexedPartSelectOp,
ParamValueOp, XMROp, XMRRefOp, SampledOp, EnumConstantOp, SFormatFOp,
SystemFunctionOp, STimeOp, TimeOp, UnpackedArrayCreateOp,
UnpackedOpenArrayCastOp>(op))
return true;
// These are Verif dialect expressions.
if (isa<verif::ContractOp>(op))
return true;
// All HW combinational logic ops and SV expression ops are Verilog
// expressions.
return isCombinational(op) || isExpression(op);
}
// NOLINTBEGIN(misc-no-recursion)
/// Push this type's dimension into a vector.
static void getTypeDims(SmallVectorImpl<Attribute> &dims, Type type,
Location loc) {
if (auto integer = hw::type_dyn_cast<IntegerType>(type)) {
if (integer.getWidth() != 1)
dims.push_back(getInt32Attr(type.getContext(), integer.getWidth()));
return;
}
if (auto array = hw::type_dyn_cast<ArrayType>(type)) {
dims.push_back(getInt32Attr(type.getContext(), array.getNumElements()));
getTypeDims(dims, array.getElementType(), loc);
return;
}
if (auto intType = hw::type_dyn_cast<IntType>(type)) {
dims.push_back(intType.getWidth());
return;
}
if (auto inout = hw::type_dyn_cast<InOutType>(type))
return getTypeDims(dims, inout.getElementType(), loc);
if (auto uarray = hw::type_dyn_cast<hw::UnpackedArrayType>(type))
return getTypeDims(dims, uarray.getElementType(), loc);
if (auto uarray = hw::type_dyn_cast<sv::UnpackedOpenArrayType>(type))
return getTypeDims(dims, uarray.getElementType(), loc);
if (hw::type_isa<InterfaceType, StructType, EnumType, UnionType>(type))
return;
mlir::emitError(loc, "value has an unsupported verilog type ") << type;
}
// NOLINTEND(misc-no-recursion)
/// True iff 'a' and 'b' have the same wire dims.
static bool haveMatchingDims(Type a, Type b, Location loc) {
SmallVector<Attribute, 4> aDims;
getTypeDims(aDims, a, loc);
SmallVector<Attribute, 4> bDims;
getTypeDims(bDims, b, loc);
return aDims == bDims;
}
// NOLINTBEGIN(misc-no-recursion)
bool ExportVerilog::isZeroBitType(Type type) {
type = getCanonicalType(type);
if (auto intType = dyn_cast<IntegerType>(type))
return intType.getWidth() == 0;
if (auto inout = dyn_cast<hw::InOutType>(type))
return isZeroBitType(inout.getElementType());
if (auto uarray = dyn_cast<hw::UnpackedArrayType>(type))
return uarray.getNumElements() == 0 ||
isZeroBitType(uarray.getElementType());
if (auto array = dyn_cast<hw::ArrayType>(type))
return array.getNumElements() == 0 || isZeroBitType(array.getElementType());
if (auto structType = dyn_cast<hw::StructType>(type))
return llvm::all_of(structType.getElements(),
[](auto elem) { return isZeroBitType(elem.type); });
if (auto enumType = dyn_cast<hw::EnumType>(type))
return enumType.getFields().empty();
if (auto unionType = dyn_cast<hw::UnionType>(type))
return hw::getBitWidth(unionType) == 0;
// We have an open type system, so assume it is ok.
return false;
}
// NOLINTEND(misc-no-recursion)
/// Given a set of known nested types (those supported by this pass), strip off
/// leading unpacked types. This strips off portions of the type that are
/// printed to the right of the name in verilog.
// NOLINTBEGIN(misc-no-recursion)
static Type stripUnpackedTypes(Type type) {
return TypeSwitch<Type, Type>(type)
.Case<InOutType>([](InOutType inoutType) {
return stripUnpackedTypes(inoutType.getElementType());
})
.Case<UnpackedArrayType, sv::UnpackedOpenArrayType>([](auto arrayType) {
return stripUnpackedTypes(arrayType.getElementType());
})
.Default([](Type type) { return type; });
}
/// Return true if the type has a leading unpacked type.
static bool hasLeadingUnpackedType(Type type) {
assert(isa<hw::InOutType>(type) && "inout type is expected");
auto elementType = cast<hw::InOutType>(type).getElementType();
return stripUnpackedTypes(elementType) != elementType;
}
/// Return true if type has a struct type as a subtype.
static bool hasStructType(Type type) {
return TypeSwitch<Type, bool>(type)
.Case<InOutType, UnpackedArrayType, ArrayType>([](auto parentType) {
return hasStructType(parentType.getElementType());
})
.Case<StructType>([](auto) { return true; })
.Default([](auto) { return false; });
}
// NOLINTEND(misc-no-recursion)
//===----------------------------------------------------------------------===//
// Location comparison
//===----------------------------------------------------------------------===//
// NOLINTBEGIN(misc-no-recursion)
static int compareLocs(Location lhs, Location rhs);
// NameLoc comparator - compare names, then child locations.
static int compareLocsImpl(mlir::NameLoc lhs, mlir::NameLoc rhs) {
if (auto name = lhs.getName().compare(rhs.getName()))
return name;
return compareLocs(lhs.getChildLoc(), rhs.getChildLoc());
}
// FileLineColLoc comparator.
static int compareLocsImpl(mlir::FileLineColLoc lhs, mlir::FileLineColLoc rhs) {
if (auto fn = lhs.getFilename().compare(rhs.getFilename()))
return fn;
if (lhs.getLine() != rhs.getLine())
return lhs.getLine() < rhs.getLine() ? -1 : 1;
return lhs.getColumn() < rhs.getColumn() ? -1 : 1;
}
// CallSiteLoc comparator. Compare first on the callee, then on the caller.
static int compareLocsImpl(mlir::CallSiteLoc lhs, mlir::CallSiteLoc rhs) {
Location lhsCallee = lhs.getCallee();
Location rhsCallee = rhs.getCallee();
if (auto res = compareLocs(lhsCallee, rhsCallee))
return res;
Location lhsCaller = lhs.getCaller();
Location rhsCaller = rhs.getCaller();
return compareLocs(lhsCaller, rhsCaller);
}
template <typename TTargetLoc>
FailureOr<int> dispatchCompareLocations(Location lhs, Location rhs) {
auto lhsT = dyn_cast<TTargetLoc>(lhs);
auto rhsT = dyn_cast<TTargetLoc>(rhs);
if (lhsT && rhsT) {
// Both are of the target location type, compare them directly.
return compareLocsImpl(lhsT, rhsT);
}
if (lhsT) {
// lhs is TTargetLoc => it comes before rhs.
return -1;
}
if (rhsT) {
// rhs is TTargetLoc => it comes before lhs.
return 1;
}
return failure();
}
// Top-level comparator for two arbitrarily typed locations.
// First order comparison by location type:
// 1. FileLineColLoc
// 2. NameLoc
// 3. CallSiteLoc
// 4. Anything else...
// Intra-location type comparison is delegated to the corresponding
// compareLocsImpl() function.
static int compareLocs(Location lhs, Location rhs) {
// FileLineColLoc
if (auto res = dispatchCompareLocations<mlir::FileLineColLoc>(lhs, rhs);
succeeded(res))
return *res;
// NameLoc
if (auto res = dispatchCompareLocations<mlir::NameLoc>(lhs, rhs);
succeeded(res))
return *res;
// CallSiteLoc
if (auto res = dispatchCompareLocations<mlir::CallSiteLoc>(lhs, rhs);
succeeded(res))
return *res;
// Anything else...
return 0;
}
// NOLINTEND(misc-no-recursion)
//===----------------------------------------------------------------------===//
// Location printing
//===----------------------------------------------------------------------===//
/// Pull apart any fused locations into the location set, such that they are
/// uniqued. Any other location type will be added as-is.
static void collectAndUniqueLocations(Location loc,
SmallPtrSetImpl<Attribute> &locationSet) {
llvm::TypeSwitch<Location, void>(loc)
.Case<FusedLoc>([&](auto fusedLoc) {
for (auto subLoc : fusedLoc.getLocations())
collectAndUniqueLocations(subLoc, locationSet);
})
.Default([&](auto loc) { locationSet.insert(loc); });
}
// Sorts a vector of locations in-place.
template <typename TVector>
static void sortLocationVector(TVector &vec) {
llvm::array_pod_sort(
vec.begin(), vec.end(), [](const auto *lhs, const auto *rhs) -> int {
return compareLocs(cast<Location>(*lhs), cast<Location>(*rhs));
});
}
class LocationEmitter {
public:
// Generates location info for a single location in the specified style.
LocationEmitter(LoweringOptions::LocationInfoStyle style, Location loc) {
SmallPtrSet<Attribute, 8> locationSet;
locationSet.insert(loc);
llvm::raw_string_ostream os(output);
emitLocationSetInfo(os, style, locationSet);
}
// Generates location info for a set of operations in the specified style.
LocationEmitter(LoweringOptions::LocationInfoStyle style,
const SmallPtrSetImpl<Operation *> &ops) {
// Multiple operations may come from the same location or may not have
// useful
// location info. Unique it now.
SmallPtrSet<Attribute, 8> locationSet;
for (auto *op : ops)
collectAndUniqueLocations(op->getLoc(), locationSet);
llvm::raw_string_ostream os(output);
emitLocationSetInfo(os, style, locationSet);
}
StringRef strref() { return output; }
private:
void emitLocationSetInfo(llvm::raw_string_ostream &os,
LoweringOptions::LocationInfoStyle style,
const SmallPtrSetImpl<Attribute> &locationSet) {
if (style == LoweringOptions::LocationInfoStyle::None)
return;
std::string resstr;
llvm::raw_string_ostream sstr(resstr);
LocationEmitter::Impl(sstr, style, locationSet);
if (resstr.empty() || style == LoweringOptions::LocationInfoStyle::Plain) {
os << resstr;
return;
}
assert(style == LoweringOptions::LocationInfoStyle::WrapInAtSquareBracket &&
"other styles must be already handled");
os << "@[" << resstr << "]";
}
std::string output;
struct Impl {
// NOLINTBEGIN(misc-no-recursion)
Impl(llvm::raw_string_ostream &os, LoweringOptions::LocationInfoStyle style,
const SmallPtrSetImpl<Attribute> &locationSet)
: os(os), style(style) {
emitLocationSetInfoImpl(locationSet);
}
// Emit CallSiteLocs.
void emitLocationInfo(mlir::CallSiteLoc loc) {
os << "{";
emitLocationInfo(loc.getCallee());
os << " <- ";
emitLocationInfo(loc.getCaller());
os << "}";
}
// Emit NameLocs.
void emitLocationInfo(mlir::NameLoc loc) {
bool withName = !loc.getName().empty();
if (withName)
os << "'" << loc.getName().strref() << "'(";
emitLocationInfo(loc.getChildLoc());
if (withName)
os << ")";
}
// Emit FileLineColLocs.
void emitLocationInfo(FileLineColLoc loc) {
os << loc.getFilename().getValue();
if (auto line = loc.getLine()) {
os << ':' << line;
if (auto col = loc.getColumn())
os << ':' << col;
}
}
// Generates a string representation of a set of FileLineColLocs.
// The entries are sorted by filename, line, col. Try to merge together
// entries to reduce verbosity on the column info.
void
printFileLineColSetInfo(llvm::SmallVector<FileLineColLoc, 8> locVector) {
// The entries are sorted by filename, line, col. Try to merge together
// entries to reduce verbosity on the column info.
StringRef lastFileName;
for (size_t i = 0, e = locVector.size(); i != e;) {
if (i != 0)
os << ", ";
// Print the filename if it changed.
auto first = locVector[i];
if (first.getFilename() != lastFileName) {
lastFileName = first.getFilename();
os << lastFileName;
}
// Scan for entries with the same file/line.
size_t end = i + 1;
while (end != e &&
first.getFilename() == locVector[end].getFilename() &&
first.getLine() == locVector[end].getLine())
++end;
// If we have one entry, print it normally.
if (end == i + 1) {
if (auto line = first.getLine()) {
os << ':' << line;
if (auto col = first.getColumn())
os << ':' << col;
}
++i;
continue;
}
// Otherwise print a brace enclosed list.
os << ':' << first.getLine() << ":{";
while (i != end) {
os << locVector[i++].getColumn();
if (i != end)
os << ',';
}
os << '}';
}
}
/// Return the location information in the specified style. This is the main
/// dispatch function for calling the location-specific routines.
void emitLocationInfo(Location loc) {
llvm::TypeSwitch<Location, void>(loc)
.Case<mlir::CallSiteLoc, mlir::NameLoc, mlir::FileLineColLoc>(
[&](auto loc) { emitLocationInfo(loc); })
.Case<mlir::FusedLoc>([&](auto loc) {
SmallPtrSet<Attribute, 8> locationSet;
collectAndUniqueLocations(loc, locationSet);
emitLocationSetInfoImpl(locationSet);
})
.Default([&](auto loc) {
// Don't print anything for unhandled locations.
});
}
/// Emit the location information of `locationSet` to `sstr`. The emitted
/// string
/// may potentially be an empty string given the contents of the
/// `locationSet`.
void
emitLocationSetInfoImpl(const SmallPtrSetImpl<Attribute> &locationSet) {
// Fast pass some common cases.
switch (locationSet.size()) {
case 1:
emitLocationInfo(cast<LocationAttr>(*locationSet.begin()));
[[fallthrough]];
case 0:
return;
default:
break;
}
// Sort the entries into distinct location printing kinds.
SmallVector<FileLineColLoc, 8> flcLocs;
SmallVector<Attribute, 8> otherLocs;
flcLocs.reserve(locationSet.size());
otherLocs.reserve(locationSet.size());
for (Attribute loc : locationSet) {
if (auto flcLoc = dyn_cast<FileLineColLoc>(loc))
flcLocs.push_back(flcLoc);
else
otherLocs.push_back(loc);
}
// SmallPtrSet iteration is non-deterministic, so sort the location
// vectors to ensure deterministic output.
sortLocationVector(otherLocs);
sortLocationVector(flcLocs);
// To detect whether something actually got emitted, we inspect the stream
// for size changes. This is due to the possiblity of locations which are
// not supposed to be emitted (e.g. `loc("")`).
size_t sstrSize = os.tell();
bool emittedAnything = false;
auto recheckEmittedSomething = [&]() {
size_t currSize = os.tell();
bool emittedSomethingSinceLastCheck = currSize != sstrSize;
emittedAnything |= emittedSomethingSinceLastCheck;
sstrSize = currSize;
return emittedSomethingSinceLastCheck;
};
// First, emit the other locations through the generic location dispatch
// function.
llvm::interleave(
otherLocs,
[&](Attribute loc) { emitLocationInfo(cast<LocationAttr>(loc)); },
[&] {
if (recheckEmittedSomething()) {
os << ", ";
recheckEmittedSomething(); // reset detector to reflect the comma.
}
});
// If we emitted anything, and we have FileLineColLocs, then emit a
// location-separating comma.
if (emittedAnything && !flcLocs.empty())
os << ", ";
// Then, emit the FileLineColLocs.
printFileLineColSetInfo(flcLocs);
}
llvm::raw_string_ostream &os;
LoweringOptions::LocationInfoStyle style;
// NOLINTEND(misc-no-recursion)
};
};
/// Most expressions are invalid to bit-select from in Verilog, but some
/// things are ok. Return true if it is ok to inline bitselect from the
/// result of this expression. It is conservatively correct to return false.
static bool isOkToBitSelectFrom(Value v) {
// Module ports are always ok to bit select from.
if (isa<BlockArgument>(v))
return true;
// Read_inout is valid to inline for bit-select. See `select` syntax on
// SV spec A.8.4 (P1174).
if (auto read = v.getDefiningOp<ReadInOutOp>())
return true;
// Aggregate access can be inlined.
if (isa_and_nonnull<StructExtractOp, UnionExtractOp, ArrayGetOp>(
v.getDefiningOp()))
return true;
// Interface signal can be inlined.
if (v.getDefiningOp<ReadInterfaceSignalOp>())
return true;
// TODO: We could handle concat and other operators here.
return false;
}
/// Return true if we are unable to ever inline the specified operation. This
/// happens because not all Verilog expressions are composable, notably you
/// can only use bit selects like x[4:6] on simple expressions, you cannot use
/// expressions in the sensitivity list of always blocks, etc.
static bool isExpressionUnableToInline(Operation *op,
const LoweringOptions &options) {
if (auto cast = dyn_cast<BitcastOp>(op))
if (!haveMatchingDims(cast.getInput().getType(), cast.getResult().getType(),
op->getLoc())) {
// Even if dimentions don't match, we can inline when its user doesn't
// rely on the type.
if (op->hasOneUse() &&
isa<comb::ConcatOp, hw::ArrayConcatOp>(*op->getUsers().begin()))
return false;
// Bitcasts rely on the type being assigned to, so we cannot inline.
return true;
}
// StructCreateOp needs to be assigning to a named temporary so that types
// are inferred properly by verilog
if (isa<StructCreateOp, UnionCreateOp, UnpackedArrayCreateOp, ArrayInjectOp>(
op))
return true;
// Aggregate literal syntax only works in an assignment expression, where
// the Verilog expression's type is determined by the LHS.
if (auto aggConstantOp = dyn_cast<AggregateConstantOp>(op))
return true;
// Verbatim with a long string should be emitted as an out-of-line declration.
if (auto verbatim = dyn_cast<VerbatimExprOp>(op))
if (verbatim.getFormatString().size() > 32)
return true;
// Scan the users of the operation to see if any of them need this to be
// emitted out-of-line.
for (auto &use : op->getUses()) {
auto *user = use.getOwner();
// Verilog bit selection is required by the standard to be:
// "a vector, packed array, packed structure, parameter or concatenation".
//
// It cannot be an arbitrary expression, e.g. this is invalid:
// assign bar = {{a}, {b}, {c}, {d}}[idx];
//
// To handle these, we push the subexpression into a temporary.
if (isa<ExtractOp, ArraySliceOp, ArrayGetOp, ArrayInjectOp, StructExtractOp,
UnionExtractOp, IndexedPartSelectOp>(user))
if (use.getOperandNumber() == 0 && // ignore index operands.
!isOkToBitSelectFrom(use.get()))
return true;
// Handle option disallowing expressions in event control.
if (!options.allowExprInEventControl) {
// Check operations used for event control, anything other than
// a read of a wire must be out of line.
// Helper to determine if the use will be part of "event control",
// based on what the operation using it is and as which operand.
auto usedInExprControl = [user, &use]() {
return TypeSwitch<Operation *, bool>(user)
.Case<ltl::ClockOp>([&](auto clockOp) {
// LTL Clock op's clock operand must be a name.
return clockOp.getClock() == use.get();
})
.Case<sv::AssertConcurrentOp, sv::AssumeConcurrentOp,
sv::CoverConcurrentOp>(
[&](auto op) { return op.getClock() == use.get(); })
.Case<sv::AssertPropertyOp, sv::AssumePropertyOp,
sv::CoverPropertyOp>([&](auto op) {
return op.getDisable() == use.get() || op.getClock() == use.get();
})
.Case<AlwaysOp, AlwaysFFOp>([](auto) {
// Always blocks must have a name in their sensitivity list.
// (all operands)
return true;
})
.Default([](auto) { return false; });
};
if (!usedInExprControl())
continue;
// Otherwise, this can only be inlined if is (already) a read of a wire.
auto read = dyn_cast<ReadInOutOp>(op);
if (!read)
return true;
if (!isa_and_nonnull<sv::WireOp, RegOp>(read.getInput().getDefiningOp()))
return true;
}
}
return false;
}
enum class BlockStatementCount { Zero, One, TwoOrMore };
/// Compute how many statements are within this block, for begin/end markers.
static BlockStatementCount countStatements(Block &block) {
unsigned numStatements = 0;
block.walk([&](Operation *op) {
if (isVerilogExpression(op) ||
isa_and_nonnull<ltl::LTLDialect>(op->getDialect()))
return WalkResult::advance();
numStatements +=
TypeSwitch<Operation *, unsigned>(op)
.Case<VerbatimOp>([&](auto) {
// We don't know how many statements we emitted, so assume
// conservatively that a lot got put out. This will make sure we
// get a begin/end block around this.
return 3;
})
.Case<IfOp>([&](auto) {
// We count if as multiple statements to make sure it is always
// surrounded by a begin/end so we don't get if/else confusion in
// cases like this:
// if (cond)
// if (otherCond) // This should force a begin!
// stmt
// else // Goes with the outer if!
// thing;
return 2;
})
.Case<IfDefOp, IfDefProceduralOp>([&](auto) { return 3; })
.Case<OutputOp>([&](OutputOp oop) {
// Skip single-use instance outputs, they don't get statements.
// Keep this synchronized with visitStmt(InstanceOp,OutputOp).
return llvm::count_if(oop->getOperands(), [&](auto operand) {
Operation *op = operand.getDefiningOp();
return !operand.hasOneUse() || !op || !isa<HWInstanceLike>(op);
});
})
.Default([](auto) { return 1; });
if (numStatements > 1)
return WalkResult::interrupt();
return WalkResult::advance();
});
if (numStatements == 0)
return BlockStatementCount::Zero;
if (numStatements == 1)
return BlockStatementCount::One;
return BlockStatementCount::TwoOrMore;
}
/// Return true if this expression should be emitted inline into any statement
/// that uses it.
bool ExportVerilog::isExpressionEmittedInline(Operation *op,
const LoweringOptions &options) {
// Never create a temporary for a dead expression.
if (op->getResult(0).use_empty())
return true;
// Never create a temporary which is only going to be assigned to an output
// port, wire, or reg.
if (op->hasOneUse() &&
isa<hw::OutputOp, sv::AssignOp, sv::BPAssignOp, sv::PAssignOp>(
*op->getUsers().begin()))
return true;
// If mux inlining is dissallowed, we cannot inline muxes.
if (options.disallowMuxInlining && isa<MuxOp>(op))
return false;
// If this operation has multiple uses, we can't generally inline it unless
// the op is duplicatable.
if (!op->getResult(0).hasOneUse() && !isDuplicatableExpression(op))
return false;
// If it isn't structurally possible to inline this expression, emit it out
// of line.
return !isExpressionUnableToInline(op, options);
}
/// Find a nested IfOp in an else block that can be printed as `else if`
/// instead of nesting it into a new `begin` - `end` block. The block must
/// contain a single IfOp and optionally expressions which can be hoisted out.
static IfOp findNestedElseIf(Block *elseBlock) {
IfOp ifOp;
for (auto &op : *elseBlock) {
if (auto opIf = dyn_cast<IfOp>(op)) {
if (ifOp)
return {};
ifOp = opIf;
continue;
}
if (!isVerilogExpression(&op))
return {};
}
// SV attributes cannot be attached to `else if` so reject when ifOp has SV
// attributes.
if (ifOp && hasSVAttributes(ifOp))
return {};
return ifOp;
}
/// Emit SystemVerilog attributes.
template <typename PPS>
static void emitSVAttributesImpl(PPS &ps, ArrayAttr attrs, bool mayBreak) {
enum Container { NoContainer, InComment, InAttr };
Container currentContainer = NoContainer;
auto closeContainer = [&] {
if (currentContainer == NoContainer)
return;
if (currentContainer == InComment)
ps << " */";
else if (currentContainer == InAttr)
ps << " *)";
ps << PP::end << PP::end;
currentContainer = NoContainer;
};
bool isFirstContainer = true;
auto openContainer = [&](Container newContainer) {
assert(newContainer != NoContainer);
if (currentContainer == newContainer)
return false;
closeContainer();
// If not first container, insert break point but no space.
if (!isFirstContainer)
ps << (mayBreak ? PP::space : PP::nbsp);
isFirstContainer = false;
// fit container on one line if possible, break if needed.
ps << PP::ibox0;
if (newContainer == InComment)
ps << "/* ";
else if (newContainer == InAttr)
ps << "(* ";
currentContainer = newContainer;
// Pack attributes within to fit, align to current column when breaking.
ps << PP::ibox0;
return true;
};
// Break containers to starting column (0), put all on same line OR
// put each on their own line (cbox).
ps.scopedBox(PP::cbox0, [&]() {
for (auto attr : attrs.getAsRange<SVAttributeAttr>()) {
if (!openContainer(attr.getEmitAsComment().getValue() ? InComment
: InAttr))
ps << "," << (mayBreak ? PP::space : PP::nbsp);
ps << PPExtString(attr.getName().getValue());
if (attr.getExpression())
ps << " = " << PPExtString(attr.getExpression().getValue());
}
closeContainer();
});
}
/// Retrieve value's verilog name from IR. The name must already have been
/// added in pre-pass and passed through "hw.verilogName" attr.
StringRef getVerilogValueName(Value val) {
if (auto *op = val.getDefiningOp())
return getSymOpName(op);
if (auto port = dyn_cast<BlockArgument>(val)) {
// If the value is defined by for op, use its associated verilog name.
if (auto forOp = dyn_cast<ForOp>(port.getParentBlock()->getParentOp()))
return forOp->getAttrOfType<StringAttr>("hw.verilogName");
return getInputPortVerilogName(port.getParentBlock()->getParentOp(),
port.getArgNumber());
}
assert(false && "unhandled value");
return {};
}
//===----------------------------------------------------------------------===//
// VerilogEmitterState
//===----------------------------------------------------------------------===//
namespace {