CIRCT 23.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
13#include "CaptureAnalysis.h"
20#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
21#include "mlir/Dialect/Func/IR/FuncOps.h"
22#include "slang/ast/ASTVisitor.h"
23#include "slang/text/SourceManager.h"
24#include "llvm/ADT/ScopedHashTable.h"
25#include "llvm/Support/Debug.h"
26#include <map>
27#include <queue>
28
29#define DEBUG_TYPE "import-verilog"
30
31namespace circt {
32namespace ImportVerilog {
33
34using moore::Domain;
35
36/// Port lowering information.
38 const slang::ast::PortSymbol &ast;
39 Location loc;
40 BlockArgument arg;
41};
42
43/// Lowering information for a single signal flattened from an interface port.
45 StringAttr name;
47 mlir::Type type;
48 Location loc;
49 BlockArgument arg;
50 /// the origin interface port symbol this was flattened from.
51 const slang::ast::InterfacePortSymbol *origin;
52 /// the interface body member (VariableSymbol , NetSymbol)
53 const slang::ast::Symbol *bodySym;
54 /// The connected interface instance backing this port (if any). This enables
55 /// materializing virtual interface handles from interface ports.
56 const slang::ast::InstanceSymbol *ifaceInstance = nullptr;
57};
58
59/// Lowering information for an expanded interface instance. Maps each interface
60/// body member to its expanded SSA value (moore.variable or moore.net).
62 DenseMap<const slang::ast::Symbol *, Value> expandedMembers;
63 DenseMap<StringAttr, Value> expandedMembersByName;
64};
65
66/// Cached lowering information for representing SystemVerilog `virtual
67/// interface` handles as Moore types (a struct of references to interface
68/// members).
70 moore::UnpackedStructType type;
71 SmallVector<StringAttr, 8> fieldNames;
72};
73
74/// A mapping entry for resolving Slang virtual interface member accesses.
75///
76/// Slang may resolve `vif.member` expressions (where `vif` has a
77/// `VirtualInterfaceType`) directly to a `NamedValueExpression` for `member`.
78/// This table records which virtual interface base symbol that member access is
79/// rooted in, so ImportVerilog can materialize the appropriate Moore IR.
81 const slang::ast::ValueSymbol *base = nullptr;
82 /// The name of the field in the lowered virtual interface handle struct that
83 /// should be accessed for this member.
84 StringAttr fieldName;
85};
86
87/// Module lowering information.
89 moore::SVModuleOp op;
90 SmallVector<PortLowering> ports;
91 SmallVector<FlattenedIfacePort> ifacePorts;
92 DenseMap<const slang::syntax::SyntaxNode *, const slang::ast::PortSymbol *>
94};
95
96/// Function lowering information. The `op` field holds either a `func::FuncOp`
97/// (for SystemVerilog functions), a `moore::CoroutineOp` (for tasks), or a
98/// `moore::DPIFuncOp` (for DPI-imported functions), all accessed through the
99/// `FunctionOpInterface`.
101 mlir::FunctionOpInterface op;
102
103 /// The AST symbols captured by this function, determined by the capture
104 /// analysis pre-pass. These are added as extra parameters to the function
105 /// during declaration.
106 SmallVector<const slang::ast::ValueSymbol *, 4> capturedSymbols;
107
108 explicit FunctionLowering(mlir::FunctionOpInterface op) : op(op) {}
109};
110
111// Class lowering information.
113 circt::moore::ClassDeclOp op;
114 bool methodsFinalized = false;
115};
116
117/// Information about a loops continuation and exit blocks relevant while
118/// lowering the loop's body statements.
119struct LoopFrame {
120 /// The block to jump to from a `continue` statement.
122 /// The block to jump to from a `break` statement.
124};
125
126/// Hierarchical path information.
127/// The "hierName" means a different hierarchical name at different module
128/// levels.
129/// The "idx" means where the current hierarchical name is on the portlists.
130/// The "direction" means hierarchical names whether downward(In) or
131/// upward(Out).
133 mlir::StringAttr hierName;
134 std::optional<unsigned int> idx;
135 slang::ast::ArgumentDirection direction;
136 const slang::ast::ValueSymbol *valueSym;
137};
138
139// A slang::SourceLocation for deterministic comparisons. Comparisons use the
140// buffer's sortKey rather than bufferId.
142 uint64_t sortKey;
143 size_t offset;
144
145 static LocationKey get(const slang::SourceLocation &loc,
146 const slang::SourceManager &mgr) {
147 return {
148 mgr.getSortKey(loc.buffer()),
149 loc.offset(),
150 };
151 }
152
153 std::strong_ordering operator<=>(const LocationKey &) const = default;
154 bool operator==(const LocationKey &) const = default;
155};
156
157/// A helper class to facilitate the conversion from a Slang AST to MLIR
158/// operations. Keeps track of the destination MLIR module, builders, and
159/// various worklists and utilities needed for conversion.
160struct Context {
162 slang::ast::Compilation &compilation, mlir::ModuleOp intoModuleOp,
163 const slang::SourceManager &sourceManager)
166 builder(OpBuilder::atBlockEnd(intoModuleOp.getBody())),
168 Context(const Context &) = delete;
169
170 /// Return the MLIR context.
171 MLIRContext *getContext() { return intoModuleOp.getContext(); }
172
173 /// Convert a slang `SourceLocation` into an MLIR `Location`.
174 Location convertLocation(slang::SourceLocation loc);
175 /// Convert a slang `SourceRange` into an MLIR `Location`.
176 Location convertLocation(slang::SourceRange range);
177
178 /// Convert a slang type into an MLIR type. Returns null on failure. Uses the
179 /// provided location for error reporting, or tries to guess one from the
180 /// given type. Types tend to have unreliable location information, so it's
181 /// generally a good idea to pass in a location.
182 Type convertType(const slang::ast::Type &type, LocationAttr loc = {});
183 Type convertType(const slang::ast::DeclaredType &type);
184
185 /// Convert hierarchy and structure AST nodes to MLIR ops.
186 LogicalResult convertCompilation();
187 ModuleLowering *
188 convertModuleHeader(const slang::ast::InstanceBodySymbol *module);
189 LogicalResult convertModuleBody(const slang::ast::InstanceBodySymbol *module);
190 LogicalResult convertPackage(const slang::ast::PackageSymbol &package);
191 FunctionLowering *
192 declareFunction(const slang::ast::SubroutineSymbol &subroutine);
193 LogicalResult defineFunction(const slang::ast::SubroutineSymbol &subroutine);
194 LogicalResult
195 convertPrimitiveInstance(const slang::ast::PrimitiveInstanceSymbol &prim);
196 ClassLowering *declareClass(const slang::ast::ClassType &cls);
197 LogicalResult buildClassProperties(const slang::ast::ClassType &classdecl);
198 LogicalResult materializeClassMethods(const slang::ast::ClassType &classdecl);
199 LogicalResult convertGlobalVariable(const slang::ast::VariableSymbol &var);
200
201 /// Convert a Slang virtual interface type into the Moore type used to
202 /// represent virtual interface handles. Populates internal caches so that
203 /// interface instance references can be materialized consistently.
204 FailureOr<moore::UnpackedStructType>
205 convertVirtualInterfaceType(const slang::ast::VirtualInterfaceType &type,
206 Location loc);
207
208 /// Materialize a Moore value representing a concrete interface instance as a
209 /// virtual interface handle. This only succeeds for the Slang
210 /// `VirtualInterfaceType` wrappers that refer to a real interface instance
211 /// (`isRealIface`).
212 FailureOr<Value>
213 materializeVirtualInterfaceValue(const slang::ast::VirtualInterfaceType &type,
214 Location loc);
215
216 /// Register the interface members of a virtual interface base symbol for use
217 /// in later expression conversion.
218 LogicalResult
219 registerVirtualInterfaceMembers(const slang::ast::ValueSymbol &base,
220 const slang::ast::VirtualInterfaceType &type,
221 Location loc);
222
223 /// Checks whether one class (actualTy) is derived from another class
224 /// (baseTy). True if it's a subclass, false otherwise.
225 bool isClassDerivedFrom(const moore::ClassHandleType &actualTy,
226 const moore::ClassHandleType &baseTy);
227
228 /// Tries to find the closest base class of actualTy that carries a property
229 /// with name fieldName. The location is used for error reporting.
230 moore::ClassHandleType
231 getAncestorClassWithProperty(const moore::ClassHandleType &actualTy,
232 StringRef fieldName, Location loc);
233
234 Value getImplicitThisRef() const {
235 return currentThisRef; // block arg added in declareFunction
236 }
237
238 Value getIndexedQueue() const { return currentQueue; }
239
240 // Convert a statement AST node to MLIR ops.
241 LogicalResult convertStatement(const slang::ast::Statement &stmt);
242
243 // Convert an expression AST node to MLIR ops.
244 Value convertRvalueExpression(const slang::ast::Expression &expr,
245 Type requiredType = {});
246 Value convertLvalueExpression(const slang::ast::Expression &expr);
247
248 // Convert an assertion expression AST node to MLIR ops.
249 Value convertAssertionExpression(const slang::ast::AssertionExpr &expr,
250 Location loc);
251
252 // Convert an assertion expression AST node to MLIR ops.
254 const slang::ast::CallExpression &expr,
255 const slang::ast::CallExpression::SystemCallInfo &info, Location loc);
256
257 // Traverse the whole AST to collect hierarchical names.
258 void traverseInstanceBody(const slang::ast::Symbol &symbol);
259
260 // Convert timing controls into a corresponding set of ops that delay
261 // execution of the current block. Produces an error if the implicit event
262 // control `@*` or `@(*)` is used.
263 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl);
264 // Convert timing controls into a corresponding set of ops that delay
265 // execution of the current block. Then converts the given statement, taking
266 // note of the rvalues it reads and adding them to a wait op in case an
267 // implicit event control `@*` or `@(*)` is used.
268 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl,
269 const slang::ast::Statement &stmt);
270
271 /// Helper function to convert a value to a MLIR I1 value.
272 Value convertToI1(Value value);
273
274 // Convert a slang timing control for LTL
275 Value convertLTLTimingControl(const slang::ast::TimingControl &ctrl,
276 const Value &seqOrPro);
277
278 LogicalResult
279 convertNInputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
280
281 LogicalResult
282 convertNOutputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
283
284 LogicalResult
285 convertFixedPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
286
287 LogicalResult
288 convertPullGatePrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
289
290 /// Helper function to convert a value to its "truthy" boolean value.
291 Value convertToBool(Value value);
292
293 /// Helper function to convert a value to its "truthy" boolean value and
294 /// convert it to the given domain.
295 Value convertToBool(Value value, Domain domain);
296
297 /// Helper function to convert a value to its simple bit vector
298 /// representation, if it has one. Otherwise returns null. Also returns null
299 /// if the given value is null.
300 Value convertToSimpleBitVector(Value value);
301
302 /// Helper function to insert the necessary operations to cast a value from
303 /// one type to another.
304 Value materializeConversion(Type type, Value value, bool isSigned,
305 Location loc);
306
307 /// Helper function to materialize an `SVInt` as an SSA value.
308 Value materializeSVInt(const slang::SVInt &svint,
309 const slang::ast::Type &type, Location loc);
310
311 /// Helper function to materialize a real value as an SSA value.
312 Value materializeSVReal(const slang::ConstantValue &svreal,
313 const slang::ast::Type &type, Location loc);
314
315 /// Helper function to materialize a string as an SSA value.
316 Value materializeString(const slang::ConstantValue &string,
317 const slang::ast::Type &astType, Location loc);
318
319 /// Helper function to materialize an unpacked array of `SVInt`s as an SSA
320 /// value.
322 const slang::ConstantValue &constant,
323 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc);
324
325 /// Helper function to materialize a `ConstantValue` as an SSA value. Returns
326 /// null if the constant cannot be materialized.
327 Value materializeConstant(const slang::ConstantValue &constant,
328 const slang::ast::Type &type, Location loc);
329
330 /// Convert a list of string literal arguments with formatting specifiers and
331 /// arguments to be interpolated into a `!moore.format_string` value. Returns
332 /// failure if an error occurs. Returns a null value if the formatted string
333 /// is trivially empty. Otherwise returns the formatted string.
334 FailureOr<Value> convertFormatString(
335 std::span<const slang::ast::Expression *const> arguments, Location loc,
336 moore::IntFormat defaultFormat = moore::IntFormat::Decimal,
337 bool appendNewline = false);
338
339 /// Convert system function calls. Returns a null `Value` on failure after
340 /// emitting an error.
341 Value convertSystemCall(const slang::ast::SystemSubroutine &subroutine,
342 Location loc,
343 std::span<const slang::ast::Expression *const> args);
344
345 /// Convert system function calls within properties and assertion with a
346 /// single argument.
347 FailureOr<Value> convertAssertionSystemCallArity1(
348 const slang::ast::SystemSubroutine &subroutine, Location loc, Value value,
349 Type originalType);
350
351 /// Evaluate the constant value of an expression.
352 slang::ConstantValue evaluateConstant(const slang::ast::Expression &expr);
353
354 /// Convert the inside/set-membership expression.
355 Value convertInsideCheck(Value insideLhs, Location loc,
356 const slang::ast::Expression &expr);
357
359 slang::ast::Compilation &compilation;
360 mlir::ModuleOp intoModuleOp;
361 const slang::SourceManager &sourceManager;
362
363 /// The builder used to create IR operations.
364 OpBuilder builder;
365 /// A symbol table of the MLIR module we are emitting into.
366 SymbolTable symbolTable;
367
368 /// The top-level operations ordered by their Slang source location. This is
369 /// used to produce IR that follows the source file order.
370 std::map<LocationKey, Operation *> orderedRootOps;
371
372 /// How we have lowered modules to MLIR.
373 DenseMap<const slang::ast::InstanceBodySymbol *,
374 std::unique_ptr<ModuleLowering>>
376
377 /// Expanded interface instances, keyed by the InstanceSymbol pointer.
378 /// Each entry maps body members to their expanded SSA values. Scoped
379 /// per-module so entries are cleaned up when a module's conversion ends.
381 llvm::ScopedHashTable<const slang::ast::InstanceSymbol *,
383 using InterfaceInstanceScope = InterfaceInstances::ScopeTy;
385 /// Owning storage for InterfaceLowering objects
386 /// because ScopedHashTable stores values by copy.
387 SmallVector<std::unique_ptr<InterfaceLowering>> interfaceInstanceStorage;
388
389 /// Cached virtual interface layouts (type + field order).
390 DenseMap<const slang::ast::InstanceBodySymbol *, VirtualInterfaceLowering>
392 DenseMap<const slang::ast::ModportSymbol *, VirtualInterfaceLowering>
394 /// A list of modules for which the header has been created, but the body has
395 /// not been converted yet.
396 std::queue<const slang::ast::InstanceBodySymbol *> moduleWorklist;
397
398 /// A list of functions for which the declaration has been created, but the
399 /// body has not been defined yet.
400 std::queue<const slang::ast::SubroutineSymbol *> functionWorklist;
401
402 /// Functions that have already been converted.
403 DenseMap<const slang::ast::SubroutineSymbol *,
404 std::unique_ptr<FunctionLowering>>
406
407 /// Classes that have already been converted.
408 DenseMap<const slang::ast::ClassType *, std::unique_ptr<ClassLowering>>
410
411 /// A table of defined values, such as variables, that may be referred to by
412 /// name in expressions. The expressions use this table to lookup the MLIR
413 /// value that was created for a given declaration in the Slang AST node.
415 llvm::ScopedHashTable<const slang::ast::ValueSymbol *, Value>;
416 using ValueSymbolScope = ValueSymbols::ScopeTy;
418
419 /// A table mapping symbols for interface members accessed through a virtual
420 /// interface to the virtual interface base value symbol.
422 llvm::ScopedHashTable<const slang::ast::ValueSymbol *,
424 using VirtualInterfaceMemberScope = VirtualInterfaceMembers::ScopeTy;
426
427 /// A table of defined global variables that may be referred to by name in
428 /// expressions.
429 DenseMap<const slang::ast::ValueSymbol *, moore::GlobalVariableOp>
431 /// A list of global variables that still need their initializers to be
432 /// converted.
433 SmallVector<const slang::ast::ValueSymbol *> globalVariableWorklist;
434
435 /// Pre-computed capture analysis: maps each function to the set of non-local,
436 /// non-global variables it captures (directly or transitively).
438
439 /// Collect all hierarchical names used for the per module/instance.
440 DenseMap<const slang::ast::InstanceBodySymbol *, SmallVector<HierPathInfo>>
442
443 /// It's used to collect the repeat hierarchical names on the same path.
444 /// Such as `Top.sub.a` and `sub.a`, they are equivalent. The variable "a"
445 /// will be added to the port list. But we only record once. If we don't do
446 /// that. We will view the strange IR, such as `module @Sub(out y, out y)`;
447 DenseSet<StringAttr> sameHierPaths;
448
449 /// A stack of assignment left-hand side values. Each assignment will push its
450 /// lowered left-hand side onto this stack before lowering its right-hand
451 /// side. This allows expressions to resolve the opaque
452 /// `LValueReferenceExpression`s in the AST.
453 SmallVector<Value> lvalueStack;
454
455 /// A stack of loop continuation and exit blocks. Each loop will push the
456 /// relevant info onto this stack, lower its loop body statements, and pop the
457 /// info off the stack again. Continue and break statements encountered as
458 /// part of the loop body statements will use this information to branch to
459 /// the correct block.
460 SmallVector<LoopFrame> loopStack;
461
462 /// A listener called for every variable or net being read. This can be used
463 /// to collect all variables read as part of an expression or statement, for
464 /// example to populate the list of observed signals in an implicit event
465 /// control `@*`.
466 std::function<void(moore::ReadOp)> rvalueReadCallback;
467 /// A listener called for every variable or net being assigned. This can be
468 /// used to collect all variables assigned in a task scope.
469 std::function<void(mlir::Operation *)> variableAssignCallback;
470
471 /// Whether we are currently converting expressions inside a timing control,
472 /// such as `@(posedge clk)`. This is used by the implicit event control
473 /// callback to avoid adding reads from explicit event controls to the
474 /// implicit sensitivity list.
476
477 /// The time scale currently in effect.
478 slang::TimeScale timeScale;
479
480 /// Variable to track the value of the current function's implicit `this`
481 /// reference
482 Value currentThisRef = {};
483
484 /// Variable that tracks the queue which we are currently converting the index
485 /// expression for. This is necessary to implement the `$` operator, which
486 /// returns the index of the last element of the queue.
487 Value currentQueue = {};
488
489 /// Ensure that the global variables for `$monitor` state exist. This creates
490 /// the `__monitor_active_id` and `__monitor_enabled` globals on first call.
492
493 /// Process any pending `$monitor` calls and generate the monitoring
494 /// procedures at module level.
495 LogicalResult flushPendingMonitors();
496
497 /// Global variable ops for `$monitor` state management. These are created on
498 /// demand by `ensureMonitorGlobals()`.
499 moore::GlobalVariableOp monitorActiveIdGlobal = nullptr;
500 moore::GlobalVariableOp monitorEnabledGlobal = nullptr;
501
502 /// The next monitor ID to allocate. ID 0 is reserved for "no monitor active".
503 unsigned nextMonitorId = 1;
504
505 /// Information about a pending `$monitor` call that needs to be converted
506 /// after the current module's body has been processed.
508 unsigned id;
509 Location loc;
510 const slang::ast::CallExpression *call;
511 };
512
513 /// Pending `$monitor` calls that need to be converted at module level.
514 SmallVector<PendingMonitor> pendingMonitors;
515
516private:
517 /// Helper function to extract the commonalities in lowering of functions and
518 /// methods
520 declareCallableImpl(const slang::ast::SubroutineSymbol &subroutine,
521 mlir::StringRef qualifiedName,
522 llvm::SmallVectorImpl<Type> &extraParams);
523};
524
525} // namespace ImportVerilog
526} // namespace circt
527#endif // CONVERSION_IMPORTVERILOG_IMPORTVERILOGINTERNALS_H
DenseMap< const slang::ast::SubroutineSymbol *, SmallSetVector< const slang::ast::ValueSymbol *, 4 > > CaptureMap
The result of capture analysis: for each function, the set of non-local, non-global variable symbols ...
Domain
The number of values each bit of a type can assume.
Definition MooreTypes.h:50
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Options that control how Verilog input files are parsed and processed.
Information about a pending $monitor call that needs to be converted after the current module's body ...
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
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.
llvm::ScopedHashTable< const slang::ast::InstanceSymbol *, InterfaceLowering * > InterfaceInstances
Expanded interface instances, keyed by the InstanceSymbol pointer.
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.
std::queue< const slang::ast::SubroutineSymbol * > functionWorklist
A list of functions for which the declaration has been created, but the body has not been defined yet...
Value convertLvalueExpression(const slang::ast::Expression &expr)
LogicalResult registerVirtualInterfaceMembers(const slang::ast::ValueSymbol &base, const slang::ast::VirtualInterfaceType &type, Location loc)
Register the interface members of a virtual interface base symbol for use in later expression convers...
Definition Types.cpp:474
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.
SmallVector< PendingMonitor > pendingMonitors
Pending $monitor calls that need to be converted at module level.
Value convertInsideCheck(Value insideLhs, Location loc, const slang::ast::Expression &expr)
Convert the inside/set-membership expression.
Value convertLTLTimingControl(const slang::ast::TimingControl &ctrl, const Value &seqOrPro)
LogicalResult materializeClassMethods(const slang::ast::ClassType &classdecl)
DenseMap< const slang::ast::ValueSymbol *, moore::GlobalVariableOp > globalVariables
A table of defined global variables that may be referred to by name in expressions.
slang::ast::Compilation & compilation
LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl)
DenseMap< const slang::ast::InstanceBodySymbol *, VirtualInterfaceLowering > virtualIfaceLowerings
Cached virtual interface layouts (type + field order).
LogicalResult flushPendingMonitors()
Process any pending $monitor calls and generate the monitoring procedures at module level.
LogicalResult convertNInputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
llvm::ScopedHashTable< const slang::ast::ValueSymbol *, VirtualInterfaceMemberAccess > VirtualInterfaceMembers
A table mapping symbols for interface members accessed through a virtual interface to the virtual int...
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.
LogicalResult convertGlobalVariable(const slang::ast::VariableSymbol &var)
Convert a variable to a moore.global_variable operation.
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)
CaptureMap functionCaptures
Pre-computed capture analysis: maps each function to the set of non-local, non-global variables it ca...
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
Value convertSystemCall(const slang::ast::SystemSubroutine &subroutine, Location loc, std::span< const slang::ast::Expression *const > args)
Convert system function calls.
Type convertType(const slang::ast::Type &type, LocationAttr loc={})
Convert a slang type into an MLIR type.
Definition Types.cpp:224
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 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)
VirtualInterfaceMembers::ScopeTy VirtualInterfaceMemberScope
Value convertToBool(Value value)
Helper function to convert a value to its "truthy" boolean value.
LogicalResult convertFixedPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
std::function< void(mlir::Operation *)> variableAssignCallback
A listener called for every variable or net being assigned.
moore::ClassHandleType getAncestorClassWithProperty(const moore::ClassHandleType &actualTy, StringRef fieldName, Location loc)
Tries to find the closest base class of actualTy that carries a property with name fieldName.
void ensureMonitorGlobals()
Ensure that the global variables for $monitor state exist.
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={})
SmallVector< std::unique_ptr< InterfaceLowering > > interfaceInstanceStorage
Owning storage for InterfaceLowering objects because ScopedHashTable stores values by copy.
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::GlobalVariableOp monitorActiveIdGlobal
Global variable ops for $monitor state management.
VirtualInterfaceMembers virtualIfaceMembers
Value materializeString(const slang::ConstantValue &string, const slang::ast::Type &astType, Location loc)
Helper function to materialize a string as an SSA value.
moore::GlobalVariableOp monitorEnabledGlobal
DenseMap< const slang::ast::ModportSymbol *, VirtualInterfaceLowering > virtualIfaceModportLowerings
Value currentThisRef
Variable to track the value of the current function's implicit this reference.
const slang::SourceManager & sourceManager
DenseSet< StringAttr > sameHierPaths
It's used to collect the repeat hierarchical names on the same path.
Value currentQueue
Variable that tracks the queue which we are currently converting the index expression for.
std::map< LocationKey, Operation * > orderedRootOps
The top-level operations ordered by their Slang source location.
InterfaceInstances::ScopeTy InterfaceInstanceScope
FailureOr< Value > materializeVirtualInterfaceValue(const slang::ast::VirtualInterfaceType &type, Location loc)
Materialize a Moore value representing a concrete interface instance as a virtual interface handle.
Definition Types.cpp:357
LogicalResult convertPrimitiveInstance(const slang::ast::PrimitiveInstanceSymbol &prim)
Convert a primitive instance.
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.
bool isInsideTimingControl
Whether we are currently converting expressions inside a timing control, such as @(posedge clk).
FunctionLowering * declareFunction(const slang::ast::SubroutineSymbol &subroutine)
Convert a function and its arguments to a function declaration in the IR.
LogicalResult convertNOutputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
Value convertAssertionExpression(const slang::ast::AssertionExpr &expr, Location loc)
LogicalResult buildClassProperties(const slang::ast::ClassType &classdecl)
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 defineFunction(const slang::ast::SubroutineSymbol &subroutine)
Define a function’s body.
FailureOr< Value > convertAssertionSystemCallArity1(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value, Type originalType)
Convert system function calls within properties and assertion with a single argument.
unsigned nextMonitorId
The next monitor ID to allocate. ID 0 is reserved for "no monitor active".
LogicalResult convertPullGatePrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
LogicalResult convertStatement(const slang::ast::Statement &stmt)
SmallVector< const slang::ast::ValueSymbol * > globalVariableWorklist
A list of global variables that still need their initializers to be converted.
void traverseInstanceBody(const slang::ast::Symbol &symbol)
FailureOr< moore::UnpackedStructType > convertVirtualInterfaceType(const slang::ast::VirtualInterfaceType &type, Location loc)
Convert a Slang virtual interface type into the Moore type used to represent virtual interface handle...
Definition Types.cpp:238
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.
Lowering information for a single signal flattened from an interface port.
const slang::ast::InterfacePortSymbol * origin
the origin interface port symbol this was flattened from.
const slang::ast::Symbol * bodySym
the interface body member (VariableSymbol , NetSymbol)
const slang::ast::InstanceSymbol * ifaceInstance
The connected interface instance backing this port (if any).
SmallVector< const slang::ast::ValueSymbol *, 4 > capturedSymbols
The AST symbols captured by this function, determined by the capture analysis pre-pass.
FunctionLowering(mlir::FunctionOpInterface op)
slang::ast::ArgumentDirection direction
const slang::ast::ValueSymbol * valueSym
Lowering information for an expanded interface instance.
DenseMap< const slang::ast::Symbol *, Value > expandedMembers
DenseMap< StringAttr, Value > expandedMembersByName
bool operator==(const LocationKey &) const =default
static LocationKey get(const slang::SourceLocation &loc, const slang::SourceManager &mgr)
std::strong_ordering operator<=>(const LocationKey &) const =default
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
SmallVector< FlattenedIfacePort > ifacePorts
const slang::ast::PortSymbol & ast
Cached lowering information for representing SystemVerilog virtual interface handles as Moore types (...
A mapping entry for resolving Slang virtual interface member accesses.
StringAttr fieldName
The name of the field in the lowered virtual interface handle struct that should be accessed for this...