CIRCT 22.0.0git
Loading...
Searching...
No Matches
ImportVerilogInternals.h
Go to the documentation of this file.
1//===- ImportVerilogInternals.h - Internal implementation details ---------===//
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// NOLINTNEXTLINE(llvm-header-guard)
10#ifndef CONVERSION_IMPORTVERILOG_IMPORTVERILOGINTERNALS_H
11#define CONVERSION_IMPORTVERILOG_IMPORTVERILOGINTERNALS_H
12
19#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
20#include "mlir/Dialect/Func/IR/FuncOps.h"
21#include "slang/ast/ASTVisitor.h"
22#include "llvm/ADT/ScopedHashTable.h"
23#include "llvm/Support/Debug.h"
24#include <map>
25#include <queue>
26
27#define DEBUG_TYPE "import-verilog"
28
29namespace circt {
30namespace ImportVerilog {
31
32using moore::Domain;
33
34/// Port lowering information.
36 const slang::ast::PortSymbol &ast;
37 Location loc;
38 BlockArgument arg;
39};
40
41/// Module lowering information.
43 moore::SVModuleOp op;
44 SmallVector<PortLowering> ports;
45 DenseMap<const slang::syntax::SyntaxNode *, const slang::ast::PortSymbol *>
47};
48
49/// Function lowering information.
51 mlir::func::FuncOp op;
52 llvm::SmallVector<Value, 4> captures;
53 llvm::DenseMap<Value, unsigned> captureIndex;
54 bool capturesFinalized = false;
55 bool isConverting = false;
56};
57
58// Class lowering information.
60 circt::moore::ClassDeclOp op;
61};
62
63/// Information about a loops continuation and exit blocks relevant while
64/// lowering the loop's body statements.
65struct LoopFrame {
66 /// The block to jump to from a `continue` statement.
68 /// The block to jump to from a `break` statement.
69 Block *breakBlock;
70};
71
72/// Hierarchical path information.
73/// The "hierName" means a different hierarchical name at different module
74/// levels.
75/// The "idx" means where the current hierarchical name is on the portlists.
76/// The "direction" means hierarchical names whether downward(In) or
77/// upward(Out).
79 mlir::StringAttr hierName;
80 std::optional<unsigned int> idx;
81 slang::ast::ArgumentDirection direction;
82 const slang::ast::ValueSymbol *valueSym;
83};
84
85/// A helper class to facilitate the conversion from a Slang AST to MLIR
86/// operations. Keeps track of the destination MLIR module, builders, and
87/// various worklists and utilities needed for conversion.
88struct Context {
90 slang::ast::Compilation &compilation, mlir::ModuleOp intoModuleOp,
91 const slang::SourceManager &sourceManager)
94 builder(OpBuilder::atBlockEnd(intoModuleOp.getBody())),
96 Context(const Context &) = delete;
97
98 /// Return the MLIR context.
99 MLIRContext *getContext() { return intoModuleOp.getContext(); }
100
101 /// Convert a slang `SourceLocation` into an MLIR `Location`.
102 Location convertLocation(slang::SourceLocation loc);
103 /// Convert a slang `SourceRange` into an MLIR `Location`.
104 Location convertLocation(slang::SourceRange range);
105
106 /// Convert a slang type into an MLIR type. Returns null on failure. Uses the
107 /// provided location for error reporting, or tries to guess one from the
108 /// given type. Types tend to have unreliable location information, so it's
109 /// generally a good idea to pass in a location.
110 Type convertType(const slang::ast::Type &type, LocationAttr loc = {});
111 Type convertType(const slang::ast::DeclaredType &type);
112
113 /// Convert hierarchy and structure AST nodes to MLIR ops.
114 LogicalResult convertCompilation();
115 ModuleLowering *
116 convertModuleHeader(const slang::ast::InstanceBodySymbol *module);
117 LogicalResult convertModuleBody(const slang::ast::InstanceBodySymbol *module);
118 LogicalResult convertPackage(const slang::ast::PackageSymbol &package);
119 FunctionLowering *
120 declareFunction(const slang::ast::SubroutineSymbol &subroutine);
121 LogicalResult convertFunction(const slang::ast::SubroutineSymbol &subroutine);
122 LogicalResult finalizeFunctionBodyCaptures(FunctionLowering &lowering);
123 LogicalResult convertClassDeclaration(const slang::ast::ClassType &classdecl);
124 ClassLowering *declareClass(const slang::ast::ClassType &cls);
125
126 /// Checks whether one class (actualTy) is derived from another class
127 /// (baseTy). True if it's a subclass, false otherwise.
128 bool isClassDerivedFrom(const moore::ClassHandleType &actualTy,
129 const moore::ClassHandleType &baseTy);
130
131 /// Tries to find the closest base class of actualTy that carries
132 /// a property with name fieldName.
133 moore::ClassHandleType
134 getAncestorClassWithProperty(const moore::ClassHandleType &actualTy,
135 StringRef fieldName);
136
137 Value getImplicitThisRef() const {
138 return currentThisRef; // block arg added in declareFunction
139 }
140 // Convert a statement AST node to MLIR ops.
141 LogicalResult convertStatement(const slang::ast::Statement &stmt);
142
143 // Convert an expression AST node to MLIR ops.
144 Value convertRvalueExpression(const slang::ast::Expression &expr,
145 Type requiredType = {});
146 Value convertLvalueExpression(const slang::ast::Expression &expr);
147
148 // Convert an assertion expression AST node to MLIR ops.
149 Value convertAssertionExpression(const slang::ast::AssertionExpr &expr,
150 Location loc);
151
152 // Convert an assertion expression AST node to MLIR ops.
154 const slang::ast::CallExpression &expr,
155 const slang::ast::CallExpression::SystemCallInfo &info, Location loc);
156
157 // Traverse the whole AST to collect hierarchical names.
158 LogicalResult
159 collectHierarchicalValues(const slang::ast::Expression &expr,
160 const slang::ast::Symbol &outermostModule);
161 LogicalResult traverseInstanceBody(const slang::ast::Symbol &symbol);
162
163 // Convert timing controls into a corresponding set of ops that delay
164 // execution of the current block. Produces an error if the implicit event
165 // control `@*` or `@(*)` is used.
166 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl);
167 // Convert timing controls into a corresponding set of ops that delay
168 // execution of the current block. Then converts the given statement, taking
169 // note of the rvalues it reads and adding them to a wait op in case an
170 // implicit event control `@*` or `@(*)` is used.
171 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl,
172 const slang::ast::Statement &stmt);
173
174 /// Helper function to convert a value to a MLIR I1 value.
175 Value convertToI1(Value value);
176
177 // Convert a slang timing control for LTL
178 Value convertLTLTimingControl(const slang::ast::TimingControl &ctrl,
179 const Value &seqOrPro);
180
181 /// Helper function to convert a value to its "truthy" boolean value.
182 Value convertToBool(Value value);
183
184 /// Helper function to convert a value to its "truthy" boolean value and
185 /// convert it to the given domain.
186 Value convertToBool(Value value, Domain domain);
187
188 /// Helper function to convert a value to its simple bit vector
189 /// representation, if it has one. Otherwise returns null. Also returns null
190 /// if the given value is null.
191 Value convertToSimpleBitVector(Value value);
192
193 /// Helper function to insert the necessary operations to cast a value from
194 /// one type to another.
195 Value materializeConversion(Type type, Value value, bool isSigned,
196 Location loc);
197
198 /// Helper function to materialize an `SVInt` as an SSA value.
199 Value materializeSVInt(const slang::SVInt &svint,
200 const slang::ast::Type &type, Location loc);
201
202 /// Helper function to materialize a real value as an SSA value.
203 Value materializeSVReal(const slang::ConstantValue &svreal,
204 const slang::ast::Type &type, Location loc);
205
206 /// Helper function to materialize a string as an SSA value.
207 Value materializeString(const slang::ConstantValue &string,
208 const slang::ast::Type &astType, Location loc);
209
210 /// Helper function to materialize an unpacked array of `SVInt`s as an SSA
211 /// value.
213 const slang::ConstantValue &constant,
214 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc);
215
216 /// Helper function to materialize a `ConstantValue` as an SSA value. Returns
217 /// null if the constant cannot be materialized.
218 Value materializeConstant(const slang::ConstantValue &constant,
219 const slang::ast::Type &type, Location loc);
220
221 /// Convert a list of string literal arguments with formatting specifiers and
222 /// arguments to be interpolated into a `!moore.format_string` value. Returns
223 /// failure if an error occurs. Returns a null value if the formatted string
224 /// is trivially empty. Otherwise returns the formatted string.
225 FailureOr<Value> convertFormatString(
226 std::span<const slang::ast::Expression *const> arguments, Location loc,
227 moore::IntFormat defaultFormat = moore::IntFormat::Decimal,
228 bool appendNewline = false);
229
230 /// Convert system function calls only have arity-0.
231 FailureOr<Value>
232 convertSystemCallArity0(const slang::ast::SystemSubroutine &subroutine,
233 Location loc);
234
235 /// Convert system function calls only have arity-1.
236 FailureOr<Value>
237 convertSystemCallArity1(const slang::ast::SystemSubroutine &subroutine,
238 Location loc, Value value);
239
240 /// Convert system function calls within properties and assertion with a
241 /// single argument.
242 FailureOr<Value> convertAssertionSystemCallArity1(
243 const slang::ast::SystemSubroutine &subroutine, Location loc,
244 Value value);
245
246 /// Evaluate the constant value of an expression.
247 slang::ConstantValue evaluateConstant(const slang::ast::Expression &expr);
248
250 slang::ast::Compilation &compilation;
251 mlir::ModuleOp intoModuleOp;
252 const slang::SourceManager &sourceManager;
253
254 /// The builder used to create IR operations.
255 OpBuilder builder;
256 /// A symbol table of the MLIR module we are emitting into.
257 SymbolTable symbolTable;
258
259 /// The top-level operations ordered by their Slang source location. This is
260 /// used to produce IR that follows the source file order.
261 std::map<slang::SourceLocation, Operation *> orderedRootOps;
262
263 /// How we have lowered modules to MLIR.
264 DenseMap<const slang::ast::InstanceBodySymbol *,
265 std::unique_ptr<ModuleLowering>>
267 /// A list of modules for which the header has been created, but the body has
268 /// not been converted yet.
269 std::queue<const slang::ast::InstanceBodySymbol *> moduleWorklist;
270
271 /// Functions that have already been converted.
272 DenseMap<const slang::ast::SubroutineSymbol *,
273 std::unique_ptr<FunctionLowering>>
275
276 /// Classes that have already been converted.
277 DenseMap<const slang::ast::ClassType *, std::unique_ptr<ClassLowering>>
279
280 /// A table of defined values, such as variables, that may be referred to by
281 /// name in expressions. The expressions use this table to lookup the MLIR
282 /// value that was created for a given declaration in the Slang AST node.
284 llvm::ScopedHashTable<const slang::ast::ValueSymbol *, Value>;
285 using ValueSymbolScope = ValueSymbols::ScopeTy;
287
288 /// Collect all hierarchical names used for the per module/instance.
289 DenseMap<const slang::ast::InstanceBodySymbol *, SmallVector<HierPathInfo>>
291
292 /// It's used to collect the repeat hierarchical names on the same path.
293 /// Such as `Top.sub.a` and `sub.a`, they are equivalent. The variable "a"
294 /// will be added to the port list. But we only record once. If we don't do
295 /// that. We will view the strange IR, such as `module @Sub(out y, out y)`;
296 DenseSet<StringAttr> sameHierPaths;
297
298 /// A stack of assignment left-hand side values. Each assignment will push its
299 /// lowered left-hand side onto this stack before lowering its right-hand
300 /// side. This allows expressions to resolve the opaque
301 /// `LValueReferenceExpression`s in the AST.
302 SmallVector<Value> lvalueStack;
303
304 /// A stack of loop continuation and exit blocks. Each loop will push the
305 /// relevant info onto this stack, lower its loop body statements, and pop the
306 /// info off the stack again. Continue and break statements encountered as
307 /// part of the loop body statements will use this information to branch to
308 /// the correct block.
309 SmallVector<LoopFrame> loopStack;
310
311 /// A listener called for every variable or net being read. This can be used
312 /// to collect all variables read as part of an expression or statement, for
313 /// example to populate the list of observed signals in an implicit event
314 /// control `@*`.
315 std::function<void(moore::ReadOp)> rvalueReadCallback;
316 /// A listener called for every variable or net being assigned. This can be
317 /// used to collect all variables assigned in a task scope.
318 std::function<void(mlir::Operation *)> variableAssignCallback;
319
320 /// The time scale currently in effect.
321 slang::TimeScale timeScale;
322
323private:
324 /// Helper function to extract the commonalities in lowering of functions and
325 /// methods
327 declareCallableImpl(const slang::ast::SubroutineSymbol &subroutine,
328 mlir::StringRef qualifiedName,
329 llvm::SmallVectorImpl<Type> &extraParams);
330 /// Variable to track the value of the current function's implicit `this`
331 /// reference
332 Value currentThisRef = {};
333};
334
335} // namespace ImportVerilog
336} // namespace circt
337#endif // CONVERSION_IMPORTVERILOG_IMPORTVERILOGINTERNALS_H
Domain
The number of values each bit of a type can assume.
Definition MooreTypes.h:49
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Options that control how Verilog input files are parsed and processed.
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
LogicalResult convertFunction(const slang::ast::SubroutineSymbol &subroutine)
Convert a function.
Value convertToI1(Value value)
Helper function to convert a value to a MLIR I1 value.
Value materializeConversion(Type type, Value value, bool isSigned, Location loc)
Helper function to insert the necessary operations to cast a value from one type to another.
FunctionLowering * declareCallableImpl(const slang::ast::SubroutineSymbol &subroutine, mlir::StringRef qualifiedName, llvm::SmallVectorImpl< Type > &extraParams)
Helper function to extract the commonalities in lowering of functions and methods.
ModuleLowering * convertModuleHeader(const slang::ast::InstanceBodySymbol *module)
Convert a module and its ports to an empty module op in the IR.
Value convertLvalueExpression(const slang::ast::Expression &expr)
Value materializeConstant(const slang::ConstantValue &constant, const slang::ast::Type &type, Location loc)
Helper function to materialize a ConstantValue as an SSA value.
SmallVector< LoopFrame > loopStack
A stack of loop continuation and exit blocks.
LogicalResult convertModuleBody(const slang::ast::InstanceBodySymbol *module)
Convert a module's body to the corresponding IR ops.
LogicalResult convertClassDeclaration(const slang::ast::ClassType &classdecl)
slang::ConstantValue evaluateConstant(const slang::ast::Expression &expr)
Evaluate the constant value of an expression.
Value convertLTLTimingControl(const slang::ast::TimingControl &ctrl, const Value &seqOrPro)
slang::ast::Compilation & compilation
LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl)
Context(const ImportVerilogOptions &options, slang::ast::Compilation &compilation, mlir::ModuleOp intoModuleOp, const slang::SourceManager &sourceManager)
OpBuilder builder
The builder used to create IR operations.
std::queue< const slang::ast::InstanceBodySymbol * > moduleWorklist
A list of modules for which the header has been created, but the body has not been converted yet.
Value materializeFixedSizeUnpackedArrayType(const slang::ConstantValue &constant, const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc)
Helper function to materialize an unpacked array of SVInts as an SSA value.
Value convertAssertionCallExpression(const slang::ast::CallExpression &expr, const slang::ast::CallExpression::SystemCallInfo &info, Location loc)
DenseMap< const slang::ast::ClassType *, std::unique_ptr< ClassLowering > > classes
Classes that have already been converted.
std::function< void(moore::ReadOp)> rvalueReadCallback
A listener called for every variable or net being read.
bool isClassDerivedFrom(const moore::ClassHandleType &actualTy, const moore::ClassHandleType &baseTy)
Checks whether one class (actualTy) is derived from another class (baseTy).
Context(const Context &)=delete
std::map< slang::SourceLocation, Operation * > orderedRootOps
The top-level operations ordered by their Slang source location.
Type convertType(const slang::ast::Type &type, LocationAttr loc={})
Convert a slang type into an MLIR type.
Definition Types.cpp:191
DenseMap< const slang::ast::SubroutineSymbol *, std::unique_ptr< FunctionLowering > > functions
Functions that have already been converted.
Value materializeSVInt(const slang::SVInt &svint, const slang::ast::Type &type, Location loc)
Helper function to materialize an SVInt as an SSA value.
slang::TimeScale timeScale
The time scale currently in effect.
LogicalResult finalizeFunctionBodyCaptures(FunctionLowering &lowering)
Value materializeSVReal(const slang::ConstantValue &svreal, const slang::ast::Type &type, Location loc)
Helper function to materialize a real value as an SSA value.
ClassLowering * declareClass(const slang::ast::ClassType &cls)
Value convertToBool(Value value)
Helper function to convert a value to its "truthy" boolean value.
std::function< void(mlir::Operation *)> variableAssignCallback
A listener called for every variable or net being assigned.
FailureOr< Value > convertFormatString(std::span< const slang::ast::Expression *const > arguments, Location loc, moore::IntFormat defaultFormat=moore::IntFormat::Decimal, bool appendNewline=false)
Convert a list of string literal arguments with formatting specifiers and arguments to be interpolate...
const ImportVerilogOptions & options
Value convertRvalueExpression(const slang::ast::Expression &expr, Type requiredType={})
FailureOr< Value > convertSystemCallArity0(const slang::ast::SystemSubroutine &subroutine, Location loc)
Convert system function calls only have arity-0.
llvm::ScopedHashTable< const slang::ast::ValueSymbol *, Value > ValueSymbols
A table of defined values, such as variables, that may be referred to by name in expressions.
Value convertToSimpleBitVector(Value value)
Helper function to convert a value to its simple bit vector representation, if it has one.
moore::ClassHandleType getAncestorClassWithProperty(const moore::ClassHandleType &actualTy, StringRef fieldName)
Tries to find the closest base class of actualTy that carries a property with name fieldName.
LogicalResult traverseInstanceBody(const slang::ast::Symbol &symbol)
Value materializeString(const slang::ConstantValue &string, const slang::ast::Type &astType, Location loc)
Helper function to materialize a string as an SSA value.
Value currentThisRef
Variable to track the value of the current function's implicit this reference.
FailureOr< Value > convertSystemCallArity1(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value)
Convert system function calls only have arity-1.
const slang::SourceManager & sourceManager
DenseSet< StringAttr > sameHierPaths
It's used to collect the repeat hierarchical names on the same path.
FailureOr< Value > convertAssertionSystemCallArity1(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value)
Convert system function calls within properties and assertion with a single argument.
SymbolTable symbolTable
A symbol table of the MLIR module we are emitting into.
DenseMap< const slang::ast::InstanceBodySymbol *, SmallVector< HierPathInfo > > hierPaths
Collect all hierarchical names used for the per module/instance.
FunctionLowering * declareFunction(const slang::ast::SubroutineSymbol &subroutine)
Convert a function and its arguments to a function declaration in the IR.
LogicalResult collectHierarchicalValues(const slang::ast::Expression &expr, const slang::ast::Symbol &outermostModule)
Value convertAssertionExpression(const slang::ast::AssertionExpr &expr, Location loc)
LogicalResult convertPackage(const slang::ast::PackageSymbol &package)
Convert a package and its contents.
LogicalResult convertCompilation()
Convert hierarchy and structure AST nodes to MLIR ops.
MLIRContext * getContext()
Return the MLIR context.
LogicalResult convertStatement(const slang::ast::Statement &stmt)
SmallVector< Value > lvalueStack
A stack of assignment left-hand side values.
DenseMap< const slang::ast::InstanceBodySymbol *, std::unique_ptr< ModuleLowering > > modules
How we have lowered modules to MLIR.
Location convertLocation(slang::SourceLocation loc)
Convert a slang SourceLocation into an MLIR Location.
llvm::DenseMap< Value, unsigned > captureIndex
Hierarchical path information.
slang::ast::ArgumentDirection direction
const slang::ast::ValueSymbol * valueSym
std::optional< unsigned int > idx
Information about a loops continuation and exit blocks relevant while lowering the loop's body statem...
Block * breakBlock
The block to jump to from a break statement.
Block * continueBlock
The block to jump to from a continue statement.
DenseMap< const slang::syntax::SyntaxNode *, const slang::ast::PortSymbol * > portsBySyntaxNode
const slang::ast::PortSymbol & ast