CIRCT 24.0.0git
Loading...
Searching...
No Matches
SVDialect.cpp
Go to the documentation of this file.
1//===- SVDialect.cpp - Implement the SV dialect ---------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the SV dialect.
10//
11//===----------------------------------------------------------------------===//
12
18
19#include "mlir/IR/DialectImplementation.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringSet.h"
23#include "llvm/ADT/TypeSwitch.h"
24#include "llvm/Support/ManagedStatic.h"
25
26using namespace circt;
27using namespace circt::sv;
28
29//===----------------------------------------------------------------------===//
30// Dialect specification.
31//===----------------------------------------------------------------------===//
32
33namespace {
34/// Reject NetType or VarType on output direction module ports. Handle types
35/// are only meaningful as an input direction block argument; a module result
36/// is always a pure SSA value.
37struct SVHandleModulePortTypeInterface : public hw::HWModulePortTypeInterface {
39
40 LogicalResult
41 verifyHWModulePortType(function_ref<InFlightDiagnostic()> emitError,
43 Type type) const override {
44 if (direction == hw::ModulePort::Output) {
45 if (isa<NetType>(type))
46 return emitError()
47 << "sv.net handles are not supported on output ports";
48 if (isa<VarType>(type))
49 return emitError()
50 << "sv.var handles are not supported on output ports";
51 }
52 return success();
53 }
54};
55} // namespace
56
57void SVDialect::initialize() {
58 // Register types and attributes.
59 registerTypes();
60 registerAttributes();
61
62 // Register interface implementations.
63 addInterfaces<SVHandleModulePortTypeInterface>();
64}
65
66#define GET_ATTRDEF_CLASSES
67#include "circt/Dialect/SV/SVDialect.cpp.inc"
68
69//===----------------------------------------------------------------------===//
70// Name conflict resolution
71//===----------------------------------------------------------------------===//
72
73/// Return a StringSet that contains all of the reserved names (e.g. Verilog
74/// keywords) that we need to avoid for fear of name conflicts.
76 static void *call() {
77 auto set = std::make_unique<StringSet<>>();
78 static const char *const reservedWords[] = {
79#include "ReservedWords.def"
80 };
81 for (auto *word : reservedWords)
82 set->insert(word);
83 return set.release();
84 }
85};
86
87/// A StringSet that contains all of the reserved names (e.g., Verilog and VHDL
88/// keywords) that we need to avoid to prevent naming conflicts.
89static llvm::ManagedStatic<StringSet<>, ReservedWordsCreator> reservedWords;
90
91/// Given string \p origName, generate a new name if it conflicts with any
92/// keyword or any other name in the set \p recordNames. Use the int \p
93/// nextGeneratedNameID as a counter for suffix. Update the \p recordNames with
94/// the generated name and return the StringRef.
95StringRef
96circt::sv::resolveKeywordConflict(StringRef origName,
97 llvm::StringMap<size_t> &nextGeneratedNameIDs,
98 bool caseInsensitiveKeywords) {
99 // Get the list of reserved words we need to avoid. We could prepopulate this
100 // into the used words cache, but it is large and immutable, so we just query
101 // it when needed.
102
103 // Fast path: name is valid
104 if (!reservedWords->contains(caseInsensitiveKeywords ? origName.lower()
105 : origName)) {
106 auto itAndInserted = nextGeneratedNameIDs.insert({origName, 0});
107 if (itAndInserted.second)
108 return itAndInserted.first->getKey();
109 }
110
111 // We need to mutate the name, get the copy ready.
112 SmallString<16> nameBuffer(origName.begin(), origName.end());
113 nameBuffer.push_back('_');
114 auto baseSize = nameBuffer.size();
115 auto &nextGeneratedNameID = nextGeneratedNameIDs[origName];
116
117 while (1) {
118 // We need to auto-unique it.
119 auto suffix = llvm::utostr(nextGeneratedNameID++);
120 nameBuffer.append(suffix.begin(), suffix.end());
121
122 // The name may be unique. No keywords have an underscore followed by a
123 // number, so don't check that again.
124 auto itAndInserted = nextGeneratedNameIDs.insert({nameBuffer, 0});
125 if (itAndInserted.second)
126 return itAndInserted.first->getKey();
127
128 // Chop off the suffix and try again until we get a unique name..
129 nameBuffer.resize(baseSize);
130 }
131}
132
133static bool isValidVerilogCharacterFirst(char ch) {
134 return llvm::isAlpha(ch) || ch == '_';
135}
136
137static bool isValidVerilogCharacter(char ch) {
138 return isValidVerilogCharacterFirst(ch) || llvm::isDigit(ch) || ch == '$';
139}
140
141/// Legalize the specified name for use in SV output. Auto-uniquifies the name
142/// through \c resolveKeywordConflict if required. If the name is empty, a
143/// unique temp name is created.
144StringRef circt::sv::legalizeName(StringRef name,
145 llvm::StringMap<size_t> &nextGeneratedNameIDs,
146 bool caseInsensitiveKeywords) {
147
148 // Fastest path: empty name.
149 if (name.empty())
150 return resolveKeywordConflict("_GEN", nextGeneratedNameIDs,
151 caseInsensitiveKeywords);
152
153 // Check that the name is valid as the semi-fast path.
154 if (llvm::all_of(name, isValidVerilogCharacter) &&
155 isValidVerilogCharacterFirst(name.front()))
156 return resolveKeywordConflict(name, nextGeneratedNameIDs,
157 caseInsensitiveKeywords);
158
159 // The name consists of at least one invalid character. Escape it.
160 SmallString<16> tmpName;
161 if (!isValidVerilogCharacterFirst(name.front()) && name.front() != ' ' &&
162 name.front() != '.')
163 tmpName += '_';
164 for (char ch : name) {
166 tmpName += ch;
167 else if (ch == ' ' || ch == '.')
168 tmpName += '_';
169 else {
170 tmpName += llvm::utohexstr((unsigned char)ch);
171 }
172 }
173
174 // Make sure the new valid name does not conflict with any existing names.
175 return resolveKeywordConflict(tmpName, nextGeneratedNameIDs,
176 caseInsensitiveKeywords);
177}
178
179/// Check if a name is valid for use in SV output by only containing characters
180/// allowed in SV identifiers.
181///
182/// Call \c legalizeName() to obtain a legalized version of the name.
183bool circt::sv::isNameValid(StringRef name, bool caseInsensitiveKeywords) {
184 if (name.empty())
185 return false;
186 if (name.front() == '\\') {
187 // Check if the name is a valid escaped name.
188 if (name.size() < 2)
189 return false;
190 for (auto ch : name.drop_front()) {
191 bool isValidChar = llvm::isPrint(ch) && !llvm::isSpace(ch);
192 if (!isValidChar)
193 return false;
194 }
195 } else {
196 if (!isValidVerilogCharacterFirst(name.front()))
197 return false;
198 for (char ch : name) {
200 return false;
201 }
202 }
203
204 return reservedWords->contains(caseInsensitiveKeywords ? name.lower()
205 : name) == 0;
206}
return success()
static bool isValidVerilogCharacterFirst(char ch)
static llvm::ManagedStatic< StringSet<>, ReservedWordsCreator > reservedWords
A StringSet that contains all of the reserved names (e.g., Verilog and VHDL keywords) that we need to...
Definition SVDialect.cpp:89
static bool isValidVerilogCharacter(char ch)
llvm::StringRef resolveKeywordConflict(llvm::StringRef origName, llvm::StringMap< size_t > &nextGeneratedNameIDs, bool caseInsensitiveKeywords)
Given string origName, generate a new name if it conflicts with any keyword or any other name in the ...
StringRef legalizeName(llvm::StringRef name, llvm::StringMap< size_t > &nextGeneratedNameIDs, bool caseInsensitiveKeywords)
Legalize the specified name for use in SV output.
bool isNameValid(llvm::StringRef name, bool caseInsensitiveKeywords)
Check if a name is valid for use in SV output by only containing characters allowed in SV identifiers...
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Return a StringSet that contains all of the reserved names (e.g.
Definition SVDialect.cpp:75
static void * call()
Definition SVDialect.cpp:76
HWModulePortTypeInterface(mlir::Dialect *dialect)
Definition HWTypes.h:40