Loading [MathJax]/extensions/tex2jax.js
CIRCT 22.0.0git
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
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};
53
54/// Information about a loops continuation and exit blocks relevant while
55/// lowering the loop's body statements.
56struct LoopFrame {
57 /// The block to jump to from a `continue` statement.
59 /// The block to jump to from a `break` statement.
60 Block *breakBlock;
61};
62
63/// Hierarchical path information.
64/// The "hierName" means a different hierarchical name at different module
65/// levels.
66/// The "idx" means where the current hierarchical name is on the portlists.
67/// The "direction" means hierarchical names whether downward(In) or
68/// upward(Out).
70 mlir::StringAttr hierName;
71 std::optional<unsigned int> idx;
72 slang::ast::ArgumentDirection direction;
73 const slang::ast::ValueSymbol *valueSym;
74};
75
76/// A helper class to facilitate the conversion from a Slang AST to MLIR
77/// operations. Keeps track of the destination MLIR module, builders, and
78/// various worklists and utilities needed for conversion.
79struct Context {
81 slang::ast::Compilation &compilation, mlir::ModuleOp intoModuleOp,
82 const slang::SourceManager &sourceManager)
85 builder(OpBuilder::atBlockEnd(intoModuleOp.getBody())),
87 Context(const Context &) = delete;
88
89 /// Return the MLIR context.
90 MLIRContext *getContext() { return intoModuleOp.getContext(); }
91
92 /// Convert a slang `SourceLocation` into an MLIR `Location`.
93 Location convertLocation(slang::SourceLocation loc);
94 /// Convert a slang `SourceRange` into an MLIR `Location`.
95 Location convertLocation(slang::SourceRange range);
96
97 /// Convert a slang type into an MLIR type. Returns null on failure. Uses the
98 /// provided location for error reporting, or tries to guess one from the
99 /// given type. Types tend to have unreliable location information, so it's
100 /// generally a good idea to pass in a location.
101 Type convertType(const slang::ast::Type &type, LocationAttr loc = {});
102 Type convertType(const slang::ast::DeclaredType &type);
103
104 /// Convert hierarchy and structure AST nodes to MLIR ops.
105 LogicalResult convertCompilation();
106 ModuleLowering *
107 convertModuleHeader(const slang::ast::InstanceBodySymbol *module);
108 LogicalResult convertModuleBody(const slang::ast::InstanceBodySymbol *module);
109 LogicalResult convertPackage(const slang::ast::PackageSymbol &package);
110 FunctionLowering *
111 declareFunction(const slang::ast::SubroutineSymbol &subroutine);
112 LogicalResult convertFunction(const slang::ast::SubroutineSymbol &subroutine);
113
114 // Convert a statement AST node to MLIR ops.
115 LogicalResult convertStatement(const slang::ast::Statement &stmt);
116
117 // Convert an expression AST node to MLIR ops.
118 Value convertRvalueExpression(const slang::ast::Expression &expr,
119 Type requiredType = {});
120 Value convertLvalueExpression(const slang::ast::Expression &expr);
121
122 // Convert an assertion expression AST node to MLIR ops.
123 Value convertAssertionExpression(const slang::ast::AssertionExpr &expr,
124 Location loc);
125
126 // Traverse the whole AST to collect hierarchical names.
127 LogicalResult
128 collectHierarchicalValues(const slang::ast::Expression &expr,
129 const slang::ast::Symbol &outermostModule);
130 LogicalResult traverseInstanceBody(const slang::ast::Symbol &symbol);
131
132 // Convert a slang timing control into an MLIR timing control.
133 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl,
134 const slang::ast::Statement &stmt);
135
136 /// Helper function to convert a value to a MLIR I1 value.
137 Value convertToI1(Value value);
138
139 // Convert a slang timing control for LTL
140 Value convertLTLTimingControl(const slang::ast::TimingControl &ctrl,
141 const Value &seqOrPro);
142
143 /// Helper function to convert a value to its "truthy" boolean value.
144 Value convertToBool(Value value);
145
146 /// Helper function to convert a value to its "truthy" boolean value and
147 /// convert it to the given domain.
148 Value convertToBool(Value value, Domain domain);
149
150 /// Helper function to convert a value to its simple bit vector
151 /// representation, if it has one. Otherwise returns null. Also returns null
152 /// if the given value is null.
153 Value convertToSimpleBitVector(Value value);
154
155 /// Helper function to insert the necessary operations to cast a value from
156 /// one type to another.
157 Value materializeConversion(Type type, Value value, bool isSigned,
158 Location loc);
159
160 /// Helper function to materialize an `SVInt` as an SSA value.
161 Value materializeSVInt(const slang::SVInt &svint,
162 const slang::ast::Type &type, Location loc);
163
164 /// Helper function to materialize a `ConstantValue` as an SSA value. Returns
165 /// null if the constant cannot be materialized.
166 Value materializeConstant(const slang::ConstantValue &constant,
167 const slang::ast::Type &type, Location loc);
168
169 /// Convert a list of string literal arguments with formatting specifiers and
170 /// arguments to be interpolated into a `!moore.format_string` value. Returns
171 /// failure if an error occurs. Returns a null value if the formatted string
172 /// is trivially empty. Otherwise returns the formatted string.
173 FailureOr<Value> convertFormatString(
174 std::span<const slang::ast::Expression *const> arguments, Location loc,
175 moore::IntFormat defaultFormat = moore::IntFormat::Decimal,
176 bool appendNewline = false);
177
178 /// Convert system function calls only have arity-1.
179 FailureOr<Value>
180 convertSystemCallArity1(const slang::ast::SystemSubroutine &subroutine,
181 Location loc, Value value);
182
183 /// Evaluate the constant value of an expression.
184 slang::ConstantValue evaluateConstant(const slang::ast::Expression &expr);
185
187 slang::ast::Compilation &compilation;
188 mlir::ModuleOp intoModuleOp;
189 const slang::SourceManager &sourceManager;
190
191 /// The builder used to create IR operations.
192 OpBuilder builder;
193 /// A symbol table of the MLIR module we are emitting into.
194 SymbolTable symbolTable;
195
196 /// The top-level operations ordered by their Slang source location. This is
197 /// used to produce IR that follows the source file order.
198 std::map<slang::SourceLocation, Operation *> orderedRootOps;
199
200 /// How we have lowered modules to MLIR.
201 DenseMap<const slang::ast::InstanceBodySymbol *,
202 std::unique_ptr<ModuleLowering>>
204 /// A list of modules for which the header has been created, but the body has
205 /// not been converted yet.
206 std::queue<const slang::ast::InstanceBodySymbol *> moduleWorklist;
207
208 /// Functions that have already been converted.
209 DenseMap<const slang::ast::SubroutineSymbol *,
210 std::unique_ptr<FunctionLowering>>
212
213 /// A table of defined values, such as variables, that may be referred to by
214 /// name in expressions. The expressions use this table to lookup the MLIR
215 /// value that was created for a given declaration in the Slang AST node.
217 llvm::ScopedHashTable<const slang::ast::ValueSymbol *, Value>;
218 using ValueSymbolScope = ValueSymbols::ScopeTy;
220
221 /// Collect all hierarchical names used for the per module/instance.
222 DenseMap<const slang::ast::InstanceBodySymbol *, SmallVector<HierPathInfo>>
224
225 /// It's used to collect the repeat hierarchical names on the same path.
226 /// Such as `Top.sub.a` and `sub.a`, they are equivalent. The variable "a"
227 /// will be added to the port list. But we only record once. If we don't do
228 /// that. We will view the strange IR, such as `module @Sub(out y, out y)`;
229 DenseSet<StringAttr> sameHierPaths;
230
231 /// A stack of assignment left-hand side values. Each assignment will push its
232 /// lowered left-hand side onto this stack before lowering its right-hand
233 /// side. This allows expressions to resolve the opaque
234 /// `LValueReferenceExpression`s in the AST.
235 SmallVector<Value> lvalueStack;
236
237 /// A stack of loop continuation and exit blocks. Each loop will push the
238 /// relevant info onto this stack, lower its loop body statements, and pop the
239 /// info off the stack again. Continue and break statements encountered as
240 /// part of the loop body statements will use this information to branch to
241 /// the correct block.
242 SmallVector<LoopFrame> loopStack;
243
244 /// A listener called for every variable or net being read. This can be used
245 /// to collect all variables read as part of an expression or statement, for
246 /// example to populate the list of observed signals in an implicit event
247 /// control `@*`.
248 std::function<void(moore::ReadOp)> rvalueReadCallback;
249
250 /// The time scale currently in effect.
251 slang::TimeScale timeScale;
252};
253
254} // namespace ImportVerilog
255} // namespace circt
256
257#endif // CONVERSION_IMPORTVERILOG_IMPORTVERILOGINTERNALS_H
Domain
The number of values each bit of a type can assume.
Definition MooreTypes.h:48
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.
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.
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, const slang::ast::Statement &stmt)
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.
std::function< void(moore::ReadOp)> rvalueReadCallback
A listener called for every variable or net being read.
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:176
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.
Value convertToBool(Value value)
Helper function to convert a value to its "truthy" boolean value.
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={})
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.
LogicalResult traverseInstanceBody(const slang::ast::Symbol &symbol)
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.
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.
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