/
ExportVerilog.cpp
4709 lines (4071 loc) · 163 KB
/
ExportVerilog.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
//===- 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 "../PassDetail.h"
#include "ExportVerilogInternals.h"
#include "RearrangableOStream.h"
#include "circt/Dialect/Comb/CombDialect.h"
#include "circt/Dialect/Comb/CombVisitors.h"
#include "circt/Dialect/HW/HWAttributes.h"
#include "circt/Dialect/HW/HWTypes.h"
#include "circt/Dialect/HW/HWVisitors.h"
#include "circt/Dialect/SV/SVOps.h"
#include "circt/Dialect/SV/SVVisitors.h"
#include "circt/Support/LLVM.h"
#include "circt/Support/LoweringOptions.h"
#include "circt/Support/Path.h"
#include "circt/Support/Version.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/ImplicitLocOpBuilder.h"
#include "mlir/IR/Threading.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/Path.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/raw_ostream.h"
using namespace circt;
using namespace comb;
using namespace hw;
using namespace sv;
using namespace ExportVerilog;
#define DEBUG_TYPE "export-verilog"
constexpr int INDENT_AMOUNT = 2;
constexpr int SPACE_PER_INDENT_IN_EXPRESSION_FORMATTING = 8;
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.
ForceEmitMultiUse, // Sentinel saying to recursively emit a multi-used expr.
};
/// 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 Attribute getInt32Attr(MLIRContext *ctx, uint32_t value) {
return Builder(ctx).getI32IntegerAttr(value);
}
static Attribute 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>("string").getValue().size() <= 32)
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>(op))
return true;
// We only inline array_get with a constant index.
if (auto array = dyn_cast<hw::ArrayGetOp>(op))
return array.index().getDefiningOp<ConstantOp>();
return false;
}
/// Return the verilog name of the operations that can define a symbol.
/// Except for <WireOp, RegOp, LocalParamOp, InstanceOp>, check global state
/// `getDeclarationVerilogName` for them.
static StringRef 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>(
[](Operation *op) { return getVerilogModuleName(op); })
.Case<InterfaceOp>([&](InterfaceOp op) {
return getVerilogModuleNameAttr(op).getValue();
})
.Case<InterfaceSignalOp>(
[&](InterfaceSignalOp op) { return op.sym_name(); })
.Case<InterfaceModportOp>(
[&](InterfaceModportOp op) { return op.sym_name(); })
.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>(SymbolTable::getSymbolAttrName()))
return attr.getValue();
return StringRef("");
});
}
/// Return the verilog name of the port for the module.
StringRef getPortVerilogName(Operation *module, ssize_t portArgNum) {
auto numInputs = hw::getModuleNumInputs(module);
// portArgNum is the index into the result of getAllModulePortInfos.
// Also ensure the correct index into the input/output list is computed.
ssize_t portId = portArgNum;
char verilogNameAttr[] = "hw.verilogName";
// Check for input ports.
if (portArgNum < numInputs) {
if (auto argAttr = module->getAttrOfType<ArrayAttr>(
mlir::function_interface_impl::getArgDictAttrName()))
if (auto argDict = argAttr[portArgNum].cast<DictionaryAttr>())
if (auto updatedName = argDict.get(verilogNameAttr))
return updatedName.cast<StringAttr>().getValue();
// Get the original name of input port if no renaming.
return module->getAttrOfType<ArrayAttr>("argNames")[portArgNum]
.cast<StringAttr>()
.getValue();
}
// If its an output port, get the index into the output port array.
portId = portArgNum - numInputs;
if (auto argAttr = module->getAttrOfType<ArrayAttr>(
mlir::function_interface_impl::getResultDictAttrName()))
if (auto argDict = argAttr[portId].cast<DictionaryAttr>())
if (auto updatedName = argDict.get(verilogNameAttr))
return updatedName.cast<StringAttr>().getValue();
// Get the original name of output port if no renaming.
return module->getAttrOfType<ArrayAttr>("resultNames")[portId]
.cast<StringAttr>()
.getValue();
}
StringRef getPortVerilogName(Operation *module, PortInfo port) {
return getPortVerilogName(
module, port.isOutput() ? port.argNum + hw::getModuleNumInputs(module)
: port.argNum);
}
/// 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, ArrayIndexInOutOp, IndexedPartSelectInOutOp,
StructFieldInOutOp, IndexedPartSelectOp, ParamValueOp, XMROp,
SampledOp>(op))
return true;
// All HW combinational logic ops and SV expression ops are Verilog
// expressions.
return isCombinational(op) || isExpression(op);
}
/// Return the width of the specified type in bits or -1 if it isn't
/// supported.
static int getBitWidthOrSentinel(Type type) {
return TypeSwitch<Type, int>(type)
.Case<IntegerType>([](IntegerType integerType) {
// Verilog doesn't support zero bit integers. We only support them in
// limited cases.
return integerType.getWidth();
})
.Case<InOutType>([](InOutType inoutType) {
return getBitWidthOrSentinel(inoutType.getElementType());
})
.Case<TypeAliasType>([](TypeAliasType alias) {
return getBitWidthOrSentinel(alias.getInnerType());
})
.Default([](Type) { return -1; });
}
/// 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.getSize()));
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 (hw::type_isa<InterfaceType>(type) || hw::type_isa<StructType>(type))
return;
mlir::emitError(loc, "value has an unsupported verilog type ") << type;
}
/// 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;
}
/// Return true if this is a zero bit type, e.g. a zero bit integer or array
/// thereof.
static bool isZeroBitType(Type type) {
if (auto intType = type.dyn_cast<IntegerType>())
return intType.getWidth() == 0;
if (auto inout = type.dyn_cast<hw::InOutType>())
return isZeroBitType(inout.getElementType());
if (auto uarray = type.dyn_cast<hw::UnpackedArrayType>())
return isZeroBitType(uarray.getElementType());
if (auto array = type.dyn_cast<hw::ArrayType>())
return isZeroBitType(array.getElementType());
if (auto structType = type.dyn_cast<hw::StructType>())
return llvm::all_of(structType.getElements(),
[](auto elem) { return isZeroBitType(elem.type); });
// We have an open type system, so assume it is ok.
return false;
}
/// 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.
static Type stripUnpackedTypes(Type type) {
return TypeSwitch<Type, Type>(type)
.Case<InOutType>([](InOutType inoutType) {
return stripUnpackedTypes(inoutType.getElementType());
})
.Case<UnpackedArrayType>([](UnpackedArrayType arrayType) {
return stripUnpackedTypes(arrayType.getElementType());
})
.Default([](Type type) { return type; });
}
/// 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; });
}
/// Return the word (e.g. "reg") in Verilog to declare the specified thing.
static StringRef getVerilogDeclWord(Operation *op,
const LoweringOptions &options) {
if (isa<RegOp>(op)) {
// Check if the type stored in this register is a struct or array of
// structs. In this case, according to spec section 6.8, the "reg" prefix
// should be left off.
auto elementType =
op->getResult(0).getType().cast<InOutType>().getElementType();
if (elementType.isa<StructType>())
return "";
if (auto innerType = elementType.dyn_cast<ArrayType>()) {
while (innerType.getElementType().isa<ArrayType>())
innerType = innerType.getElementType().cast<ArrayType>();
if (innerType.getElementType().isa<StructType>() ||
innerType.getElementType().isa<TypeAliasType>())
return "";
}
if (elementType.isa<TypeAliasType>())
return "";
return "reg";
}
if (isa<WireOp>(op))
return "wire";
if (isa<ConstantOp, LocalParamOp, ParamValueOp>(op))
return "localparam";
// Interfaces instances use the name of the declared interface.
if (auto interface = dyn_cast<InterfaceInstanceOp>(op))
return interface.getInterfaceType().getInterface().getValue();
// If 'op' is in a module, output 'wire'. If 'op' is in a procedural block,
// fall through to default.
bool isProcedural = op->getParentOp()->hasTrait<ProceduralRegion>();
if (!isProcedural)
return "wire";
// "automatic" values aren't allowed in disallowLocalVariables mode.
assert(!options.disallowLocalVariables && "automatic variables not allowed");
// If the type contains a struct type, we have to use only "automatic" because
// "automatic struct" is syntactically correct.
return hasStructType(op->getResult(0).getType()) ? "automatic"
: "automatic logic";
}
/// Pull any FileLineCol locs out of the specified location and add it to the
/// specified set.
static void collectFileLineColLocs(Location loc,
SmallPtrSet<Attribute, 8> &locationSet) {
if (auto fileLoc = loc.dyn_cast<FileLineColLoc>())
locationSet.insert(fileLoc);
if (auto fusedLoc = loc.dyn_cast<FusedLoc>())
for (auto loc : fusedLoc.getLocations())
collectFileLineColLocs(loc, locationSet);
}
/// Return the location information as a (potentially empty) string.
static std::string
getLocationInfoAsStringImpl(const SmallPtrSet<Operation *, 8> &ops) {
std::string resultStr;
llvm::raw_string_ostream sstr(resultStr);
// 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)
collectFileLineColLocs(op->getLoc(), locationSet);
auto printLoc = [&](FileLineColLoc loc) {
sstr << loc.getFilename().getValue();
if (auto line = loc.getLine()) {
sstr << ':' << line;
if (auto col = loc.getColumn())
sstr << ':' << col;
}
};
// Fast pass some common cases.
switch (locationSet.size()) {
case 1:
printLoc((*locationSet.begin()).cast<FileLineColLoc>());
LLVM_FALLTHROUGH;
case 0:
return sstr.str();
default:
break;
}
// Sort the entries.
SmallVector<FileLineColLoc, 8> locVector;
locVector.reserve(locationSet.size());
for (auto loc : locationSet)
locVector.push_back(loc.cast<FileLineColLoc>());
llvm::array_pod_sort(
locVector.begin(), locVector.end(),
[](const FileLineColLoc *lhs, const FileLineColLoc *rhs) -> int {
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;
});
// 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)
sstr << ", ";
// Print the filename if it changed.
auto first = locVector[i];
if (first.getFilename() != lastFileName) {
lastFileName = first.getFilename();
sstr << 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()) {
sstr << ':' << line;
if (auto col = first.getColumn())
sstr << ':' << col;
}
++i;
continue;
}
// Otherwise print a brace enclosed list.
sstr << ':' << first.getLine() << ":{";
while (i != end) {
sstr << locVector[i++].getColumn();
if (i != end)
sstr << ',';
}
sstr << '}';
}
return sstr.str();
}
/// Return the location information in the specified style.
static std::string
getLocationInfoAsString(const SmallPtrSet<Operation *, 8> &ops,
LoweringOptions::LocationInfoStyle style) {
auto str = getLocationInfoAsStringImpl(ops);
// If the location information is empty, just return an empty string.
if (str.empty())
return str;
switch (style) {
case LoweringOptions::LocationInfoStyle::Plain:
return str;
case LoweringOptions::LocationInfoStyle::WrapInAtSquareBracket:
return "@[" + str + ']';
}
llvm_unreachable("all styles must be handled");
}
/// 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 (v.isa<BlockArgument>())
return true;
// Uses of a wire or register can be done inline.
if (auto read = v.getDefiningOp<ReadInOutOp>()) {
if (read.input().getDefiningOp<WireOp>() ||
read.input().getDefiningOp<RegOp>())
return true;
}
// Aggregate access can be inlined.
if (v.getDefiningOp<StructExtractOp>())
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) {
if (auto cast = dyn_cast<BitcastOp>(op))
if (!haveMatchingDims(cast.input().getType(), cast.result().getType(),
op->getLoc()))
// 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>(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.string().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 *user : op->getUsers()) {
// 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, StructExtractOp>(user))
if (op->getResult(0) == user->getOperand(0) && // ignore index operands.
!isOkToBitSelectFrom(op->getResult(0)))
return true;
// Always blocks must have a name in their sensitivity list, not an expr.
if (isa<AlwaysOp>(user) || isa<AlwaysFFOp>(user)) {
// Anything other than a read of a wire must be out of line.
if (auto read = dyn_cast<ReadInOutOp>(op))
if (read.input().getDefiningOp<WireOp>() ||
read.input().getDefiningOp<RegOp>())
continue;
return true;
}
}
return false;
}
/// Return true if this expression should be emitted inline into any statement
/// that uses it.
static bool isExpressionEmittedInline(Operation *op) {
// Never create a temporary which is only going to be assigned to an output
// port.
if (op->hasOneUse() && isa<hw::OutputOp>(*op->getUsers().begin()))
return true;
// 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);
}
/// 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 {};
}
return ifOp;
}
//===----------------------------------------------------------------------===//
// ModuleNameManager Implementation
//===----------------------------------------------------------------------===//
namespace {
/// This class keeps track of names for values within a module.
struct ModuleNameManager {
ModuleNameManager() {}
StringRef addName(Value value, StringRef name) {
return addName(ValueOrOp(value), name);
}
StringRef addName(Operation *op, StringRef name) {
return addName(ValueOrOp(op), name);
}
StringRef addName(Value value, StringAttr name) {
return addName(ValueOrOp(value), name);
}
StringRef addName(Operation *op, StringAttr name) {
return addName(ValueOrOp(op), name);
}
StringRef getName(Value value) { return getName(ValueOrOp(value)); }
StringRef getName(Operation *op) {
// If RegOp or WireOp, then result has the name.
if (isa<sv::WireOp, sv::RegOp>(op))
return getName(op->getResult(0));
return getName(ValueOrOp(op));
}
bool hasName(Value value) { return nameTable.count(ValueOrOp(value)); }
bool hasName(Operation *op) {
// If RegOp or WireOp, then result has the name.
if (isa<sv::WireOp, sv::RegOp>(op))
return nameTable.count(op->getResult(0));
return nameTable.count(ValueOrOp(op));
}
private:
using ValueOrOp = PointerUnion<Value, Operation *>;
/// Retrieve a name from the name table. The name must already have been
/// added.
StringRef getName(ValueOrOp valueOrOp) {
auto entry = nameTable.find(valueOrOp);
assert(entry != nameTable.end() &&
"value expected a name but doesn't have one");
return entry->getSecond();
}
/// Add the specified name to the name table, auto-uniquing the name if
/// required. If the name is empty, then this creates a unique temp name.
///
/// "valueOrOp" is typically the Value for an intermediate wire etc, but it
/// can also be an op for an instance, since we want the instances op uniqued
/// and tracked. It can also be null for things like outputs which are not
/// tracked in the nameTable.
StringRef addName(ValueOrOp valueOrOp, StringRef name);
StringRef addName(ValueOrOp valueOrOp, StringAttr nameAttr) {
return addName(valueOrOp, nameAttr ? nameAttr.getValue() : "");
}
/// nameTable keeps track of mappings from Value's and operations (for
/// instances) to their string table entry.
llvm::DenseMap<ValueOrOp, StringRef> nameTable;
NameCollisionResolver nameResolver;
};
} // end anonymous namespace
/// Add the specified name to the name table, auto-uniquing the name if
/// required. If the name is empty, then this creates a unique temp name.
///
/// "valueOrOp" is typically the Value for an intermediate wire etc, but it
/// can also be an op for an instance, since we want the instances op uniqued
/// and tracked. It can also be null for things like outputs which are not
/// tracked in the nameTable.
StringRef ModuleNameManager::addName(ValueOrOp valueOrOp, StringRef name) {
auto updatedName = nameResolver.getLegalName(name);
if (valueOrOp)
nameTable[valueOrOp] = updatedName;
return updatedName;
}
//===----------------------------------------------------------------------===//
// VerilogEmitterState
//===----------------------------------------------------------------------===//
namespace {
/// This class maintains the mutable state that cross-cuts and is shared by the
/// various emitters.
class VerilogEmitterState {
public:
explicit VerilogEmitterState(ModuleOp designOp,
const SharedEmitterState &shared,
const LoweringOptions &options,
const HWSymbolCache &symbolCache,
const GlobalNameTable &globalNames,
raw_ostream &os)
: designOp(designOp), shared(shared), options(options),
symbolCache(symbolCache), globalNames(globalNames), os(os) {}
/// This is the root mlir::ModuleOp that holds the whole design being emitted.
ModuleOp designOp;
const SharedEmitterState &shared;
/// The emitter options which control verilog emission.
const LoweringOptions &options;
/// This is a cache of various information about the IR, in frozen state.
const HWSymbolCache &symbolCache;
/// This tracks global names where the Verilog name needs to be different than
/// the IR name.
const GlobalNameTable &globalNames;
/// The stream to emit to.
raw_ostream &os;
bool encounteredError = false;
unsigned currentIndent = 0;
private:
VerilogEmitterState(const VerilogEmitterState &) = delete;
void operator=(const VerilogEmitterState &) = delete;
};
} // namespace
//===----------------------------------------------------------------------===//
// EmitterBase
//===----------------------------------------------------------------------===//
namespace {
class EmitterBase {
public:
// All of the mutable state we are maintaining.
VerilogEmitterState &state;
/// The stream to emit to.
raw_ostream &os;
EmitterBase(VerilogEmitterState &state, raw_ostream &os)
: state(state), os(os) {}
explicit EmitterBase(VerilogEmitterState &state)
: EmitterBase(state, state.os) {}
InFlightDiagnostic emitError(Operation *op, const Twine &message) {
state.encounteredError = true;
return op->emitError(message);
}
InFlightDiagnostic emitOpError(Operation *op, const Twine &message) {
state.encounteredError = true;
return op->emitOpError(message);
}
raw_ostream &indent() { return os.indent(state.currentIndent); }
void addIndent() { state.currentIndent += INDENT_AMOUNT; }
void reduceIndent() {
assert(state.currentIndent >= INDENT_AMOUNT &&
"Unintended indent wrap-around.");
state.currentIndent -= INDENT_AMOUNT;
}
/// If we have location information for any of the specified operations,
/// aggregate it together and print a pretty comment specifying where the
/// operations came from. In any case, print a newline.
void emitLocationInfoAndNewLine(const SmallPtrSet<Operation *, 8> &ops) {
auto locInfo =
getLocationInfoAsString(ops, state.options.locationInfoStyle);
if (!locInfo.empty())
os << "\t// " << locInfo;
os << '\n';
}
void emitTextWithSubstitutions(StringRef string, Operation *op,
std::function<void(Value)> operandEmitter,
ArrayAttr symAttrs, ModuleNameManager &names);
/// Emit the value of a StringAttr as one or more Verilog "one-line" comments
/// ("//"). Break the comment to respect the emittedLineLength and trim
/// whitespace after a line break. Do nothing if the StringAttr is null or
/// the value is empty.
void emitComment(StringAttr comment);
/// Given an expression that is spilled into a temporary wire, try to
/// synthesize a better name than "_T_42" based on the structure of the
/// expression.
StringAttr inferStructuralNameForTemporary(Value expr);
private:
void operator=(const EmitterBase &) = delete;
EmitterBase(const EmitterBase &) = delete;
};
} // end anonymous namespace
void EmitterBase::emitTextWithSubstitutions(
StringRef string, Operation *op, std::function<void(Value)> operandEmitter,
ArrayAttr symAttrs, ModuleNameManager &names) {
// Perform operand substitions as we emit the line string. We turn {{42}}
// into the value of operand 42.
auto namify = [&](Attribute sym, HWSymbolCache::Item item) {
// CAVEAT: These accesses can reach into other modules through inner name
// references, which are currently being processed. Do not add those remote
// operations to this module's `names`, which is reserved for things named
// *within* this module. Instead, you have to rely on those remote
// operations to have been named inside the global names table. If they
// haven't, take a look at name name legalization first.
if (auto itemOp = item.getOp()) {
if (item.hasPort()) {
return getPortVerilogName(itemOp, item.getPort());
}
StringRef symOpName = getSymOpName(itemOp);
if (!symOpName.empty())
return symOpName;
emitError(itemOp, "cannot get name for symbol ") << sym;
} else {
emitError(op, "cannot get name for symbol ") << sym;
}
return StringRef("<INVALID>");
};
// Scan 'line' for a substitution, emitting any non-substitution prefix,
// then the mentioned operand, chopping the relevant text off 'line' and
// returning true. This returns false if no substitution is found.
unsigned numSymOps = symAttrs.size();
auto emitUntilSubstitution = [&](size_t next = 0) -> bool {
size_t start = 0;
while (1) {
next = string.find("{{", next);
if (next == StringRef::npos)
return false;
// Check to make sure we have a number followed by }}. If not, we
// ignore the {{ sequence as something that could happen in Verilog.
next += 2;
start = next;
while (next < string.size() && isdigit(string[next]))
++next;
// We need at least one digit.
if (start == next) {
next--;
continue;
}
// We must have a }} right after the digits.
if (!string.substr(next).startswith("}}"))
continue;
// We must be able to decode the integer into an unsigned.
unsigned operandNo = 0;
if (string.drop_front(start)
.take_front(next - start)
.getAsInteger(10, operandNo)) {
emitError(op, "operand substitution too large");
continue;
}
next += 2;
// Emit any text before the substitution.
os << string.take_front(start - 2);
// operandNo can either refer to Operands or symOps. symOps are
// numbered after the operands.
if (operandNo < op->getNumOperands())
// Emit the operand.
operandEmitter(op->getOperand(operandNo));
else if ((operandNo - op->getNumOperands()) < numSymOps) {
unsigned symOpNum = operandNo - op->getNumOperands();
auto sym = symAttrs[symOpNum];
StringRef symVerilogName;
if (auto fsym = sym.dyn_cast<FlatSymbolRefAttr>()) {
if (auto *symOp = state.symbolCache.getDefinition(fsym))
symVerilogName = namify(sym, symOp);
} else if (auto isym = sym.dyn_cast<InnerRefAttr>()) {
auto symOp = state.symbolCache.getInnerDefinition(isym.getModule(),
isym.getName());
symVerilogName = namify(sym, symOp);
}
os << symVerilogName;
} else {
emitError(op, "operand " + llvm::utostr(operandNo) + " isn't valid");
continue;
}
// Forget about the part we emitted.
string = string.drop_front(next);
return true;
}
};
// Emit all the substitutions.
while (emitUntilSubstitution())
;
// Emit any text after the last substitution.
os << string;
}
void EmitterBase::emitComment(StringAttr comment) {
if (!comment)
return;
// Set a line length for the comment. Subtract off the leading comment and
// space ("// ") as well as the current indent level to simplify later
// arithmetic. Ensure that this line length doesn't go below zero.
auto lineLength = state.options.emittedLineLength - state.currentIndent - 3;
if (lineLength > state.options.emittedLineLength)
lineLength = 0;
// Process the comment in line chunks extracted from manually specified line
// breaks. This is done to preserve user-specified line breaking if used.
auto ref = comment.getValue();
StringRef line;
while (!ref.empty()) {
std::tie(line, ref) = ref.split("\n");
// Emit each comment line breaking it if it exceeds the emittedLineLength.
for (;;) {
indent();
os << "// ";
// Base case 1: the entire comment fits on one line.
if (line.size() <= lineLength) {
os << line << "\n";
break;
}
// The comment does NOT fit on one line. Use a simple algorithm to find
// a position to break the line:
// 1) Search backwards for whitespace and break there if you find it.
// 2) If no whitespace exists in (1), search forward for whitespace
// and break there.
// This algorithm violates the emittedLineLength if (2) ever occurrs,
// but it's dead simple.
auto breakPos = line.rfind(' ', lineLength);
// No whitespace exists looking backwards.
if (breakPos == StringRef::npos) {
breakPos = line.find(' ', lineLength);
// No whitespace exists looking forward (you hit the end of the
// string).
if (breakPos == StringRef::npos)
breakPos = line.size();
}
// Emit up to the break position. Trim any whitespace after the break
// position. Exit if nothing is left to emit. Otherwise, update the
// comment ref and continue;
os << line.take_front(breakPos) << "\n";
breakPos = line.find_first_not_of(' ', breakPos);
// Base Case 2: nothing left except whitespace.
if (breakPos == StringRef::npos)
break;
line = line.drop_front(breakPos);
}
}
}
/// Given an expression that is spilled into a temporary wire, try to synthesize
/// a better name than "_T_42" based on the structure of the expression.
StringAttr EmitterBase::inferStructuralNameForTemporary(Value expr) {
StringAttr result;
bool addPrefixUnderScore = true;
// Look through read_inout.
if (auto read = expr.getDefiningOp<ReadInOutOp>())
return inferStructuralNameForTemporary(read.input());