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/// Get the slang canonical body for the given `instance`, if there is one.
37/// If there isn't one, fall back to the normal body.
38inline const slang::ast::InstanceBodySymbol *
39getCanonicalBody(const slang::ast::InstanceSymbol &inst) {
40 const slang::ast::InstanceBodySymbol *body = inst.getCanonicalBody();
41 return body == nullptr ? &inst.body : body;
42}
43
44/// Port lowering information.
46 const slang::ast::PortSymbol &ast;
47 Location loc;
48 BlockArgument arg;
49 /// Slot index in the module signature. `outputIdx` is set for outputs;
50 /// `inputIdx` is set for inputs and inouts. Regular and expanded
51 /// interface-modport ports share one numbering per direction.
52 std::optional<unsigned> outputIdx;
53 std::optional<unsigned> inputIdx;
54};
55
56/// Lowering information for a single signal flattened from an interface port.
58 StringAttr name;
60 mlir::Type type;
61 Location loc;
62 BlockArgument arg;
63 /// the origin interface port symbol this was flattened from.
64 const slang::ast::InterfacePortSymbol *origin;
65 /// the interface body member (VariableSymbol , NetSymbol)
66 const slang::ast::Symbol *bodySym;
67 /// The connected interface instance backing this port (if any). This enables
68 /// materializing virtual interface handles from interface ports.
69 const slang::ast::InstanceSymbol *ifaceInstance = nullptr;
70 /// For modport-typed iface ports, the ModportPortSymbol this was flattened
71 /// from. Slang resolves in-body accesses like `bus.member` to a
72 /// `HierarchicalValueExpression` whose symbol is the `ModportPortSymbol`,
73 /// not the underlying interface body variable, so we register both keys in
74 /// `valueSymbols` to make the lookup find this port's `BlockArgument`.
75 const slang::ast::Symbol *modportPortSym = nullptr;
76 /// Slot index in the module signature; see `PortLowering::outputIdx`.
77 std::optional<unsigned> outputIdx;
78 std::optional<unsigned> inputIdx;
79};
80
81/// Lowering information for an expanded interface instance. Maps each interface
82/// body member to its expanded SSA value (moore.variable or moore.net).
84 DenseMap<const slang::ast::Symbol *, Value> expandedMembers;
85 DenseMap<StringAttr, Value> expandedMembersByName;
86};
87
88/// Cached lowering information for representing SystemVerilog `virtual
89/// interface` handles as Moore types (a struct of references to interface
90/// members).
92 moore::UnpackedStructType type;
93 SmallVector<StringAttr, 8> fieldNames;
94};
95
96/// A mapping entry for resolving Slang virtual interface member accesses.
97///
98/// Slang may resolve `vif.member` expressions (where `vif` has a
99/// `VirtualInterfaceType`) directly to a `NamedValueExpression` for `member`.
100/// This table records which virtual interface base symbol that member access is
101/// rooted in, so ImportVerilog can materialize the appropriate Moore IR.
103 const slang::ast::ValueSymbol *base = nullptr;
104 /// The name of the field in the lowered virtual interface handle struct that
105 /// should be accessed for this member.
106 StringAttr fieldName;
107};
108
109/// Module lowering information.
111 moore::SVModuleOp op;
112 SmallVector<PortLowering> ports;
113 SmallVector<FlattenedIfacePort> ifacePorts;
114 DenseMap<const slang::syntax::SyntaxNode *, const slang::ast::PortSymbol *>
116 /// Number of explicit-port slots per direction. Hierarchical-name ports
117 /// are appended after these in the module signature.
118 unsigned numExplicitOutputs = 0;
119 unsigned numExplicitInputs = 0;
120};
121
122/// Function lowering information. The `op` field holds either a `func::FuncOp`
123/// (for SystemVerilog functions), a `moore::CoroutineOp` (for tasks), or a
124/// `moore::DPIFuncOp` (for DPI-imported functions), all accessed through the
125/// `FunctionOpInterface`.
127 mlir::FunctionOpInterface op;
128
129 /// The AST symbols captured by this function, determined by the capture
130 /// analysis pre-pass. These are added as extra parameters to the function
131 /// during declaration.
132 SmallVector<const slang::ast::ValueSymbol *, 4> capturedSymbols;
133
134 explicit FunctionLowering(mlir::FunctionOpInterface op) : op(op) {}
135};
136
137// Class lowering information.
139 circt::moore::ClassDeclOp op;
140 bool methodsFinalized = false;
141};
142
143/// Information about a loops continuation and exit blocks relevant while
144/// lowering the loop's body statements.
145struct LoopFrame {
146 /// The block to jump to from a `continue` statement.
148 /// The block to jump to from a `break` statement.
150};
151
152/// Hierarchical path information.
153/// The "hierName" means a different hierarchical name at different module
154/// levels.
155/// The "idx" means where the current hierarchical name is on the portlists.
156/// The "direction" means hierarchical names whether downward(In) or
157/// upward(Out).
159 mlir::StringAttr hierName;
160 std::optional<unsigned int> idx;
161 slang::ast::ArgumentDirection direction;
162
163 /// The symbols this path resolves to, each paired with the elaborated
164 /// instance body it was observed in. Sibling instances elaborate the same
165 /// logical variable to distinct symbol objects. The pairing lets instance
166 /// wiring bind each one to the right instance.
167 llvm::SmallVector<std::pair<const slang::ast::ValueSymbol *,
168 const slang::ast::InstanceBodySymbol *>,
169 2>
171};
172
173/// ImportVerilog Elaboration Phases for Hierarchical Names
174///
175/// Hierarchical name resolution is performed in four distinct phases:
176///
177/// 1. Collection: The `traverseInstanceBody` pass walks the Slang AST to
178/// identify all hierarchical references (e.g., `Top.sub.var`). It records
179/// these in `hierPaths` mapped by module body.
180///
181/// 2. Port Generation: In `convertModuleHeader`, we inspect `hierPaths` for
182/// the module and add corresponding input/output ports to the generated
183/// `moore.module` to allow cross-module communication.
184///
185/// 3. Wiring: In `Structure.cpp` during instance creation, we look up the
186/// canonical module body's `hierPaths` to determine which hierarchical
187/// values need to be passed as inputs or captured as outputs from the
188/// instance.
189///
190/// 4. Resolution: In `Expressions.cpp`, visitors for rvalues and lvalues
191/// resolve hierarchical names by first checking function captures (inside
192/// a function body the capture argument must be used to respect region
193/// isolation), then the instance-aware `hierValueSymbols` map, and finally
194/// standard scoped lookups.
195
196// A slang::SourceLocation for deterministic comparisons. Comparisons use the
197// buffer's sortKey rather than bufferId.
199 uint64_t sortKey;
200 size_t offset;
201
202 static LocationKey get(const slang::SourceLocation &loc,
203 const slang::SourceManager &mgr) {
204 return {
205 mgr.getSortKey(loc.buffer()),
206 loc.offset(),
207 };
208 }
209
210 std::strong_ordering operator<=>(const LocationKey &) const = default;
211 bool operator==(const LocationKey &) const = default;
212};
213
214/// A helper class to facilitate the conversion from a Slang AST to MLIR
215/// operations. Keeps track of the destination MLIR module, builders, and
216/// various worklists and utilities needed for conversion.
217struct Context {
219 slang::ast::Compilation &compilation, mlir::ModuleOp intoModuleOp,
220 const slang::SourceManager &sourceManager)
223 builder(OpBuilder::atBlockEnd(intoModuleOp.getBody())),
225 Context(const Context &) = delete;
226
227 /// Return the MLIR context.
228 MLIRContext *getContext() { return intoModuleOp.getContext(); }
229
230 /// Convert a slang `SourceLocation` into an MLIR `Location`.
231 Location convertLocation(slang::SourceLocation loc);
232 /// Convert a slang `SourceRange` into an MLIR `Location`.
233 Location convertLocation(slang::SourceRange range);
234
235 /// Convert a slang type into an MLIR type. Returns null on failure. Uses the
236 /// provided location for error reporting, or tries to guess one from the
237 /// given type. Types tend to have unreliable location information, so it's
238 /// generally a good idea to pass in a location.
239 Type convertType(const slang::ast::Type &type, LocationAttr loc = {});
240 Type convertType(const slang::ast::DeclaredType &type);
241
242 /// Convert hierarchy and structure AST nodes to MLIR ops.
243 LogicalResult convertCompilation();
244 /// Convert a module and its ports to an empty module op in the IR. Also adds
245 /// the op to the worklist of module bodies to be lowered. This acts like a
246 /// module "declaration", allowing instances to already refer to a module even
247 /// before its body has been lowered.
248 /// `module` must be the canonical module body if there is one.
249 ModuleLowering *
250 convertModuleHeader(const slang::ast::InstanceBodySymbol *module);
251 /// Convert a module's body to the corresponding IR ops. The module op must
252 /// have already been created earlier through a `convertModuleHeader` call.
253 /// `module` must be the canonical module body if there is one.
254 LogicalResult convertModuleBody(const slang::ast::InstanceBodySymbol *module);
255 LogicalResult convertPackage(const slang::ast::PackageSymbol &package);
256 FunctionLowering *
257 declareFunction(const slang::ast::SubroutineSymbol &subroutine);
258 LogicalResult defineFunction(const slang::ast::SubroutineSymbol &subroutine);
259 LogicalResult
260 convertPrimitiveInstance(const slang::ast::PrimitiveInstanceSymbol &prim);
261 ClassLowering *declareClass(const slang::ast::ClassType &cls);
262 LogicalResult buildClassProperties(const slang::ast::ClassType &classdecl);
263 LogicalResult materializeClassMethods(const slang::ast::ClassType &classdecl);
264 LogicalResult convertGlobalVariable(const slang::ast::VariableSymbol &var);
265
266 /// Convert a Slang virtual interface type into the Moore type used to
267 /// represent virtual interface handles. Populates internal caches so that
268 /// interface instance references can be materialized consistently.
269 FailureOr<moore::UnpackedStructType>
270 convertVirtualInterfaceType(const slang::ast::VirtualInterfaceType &type,
271 Location loc);
272
273 /// Materialize a Moore value representing a concrete interface instance as a
274 /// virtual interface handle. This only succeeds for the Slang
275 /// `VirtualInterfaceType` wrappers that refer to a real interface instance
276 /// (`isRealIface`).
277 FailureOr<Value>
278 materializeVirtualInterfaceValue(const slang::ast::VirtualInterfaceType &type,
279 Location loc);
280
281 /// Register the interface members of a virtual interface base symbol for use
282 /// in later expression conversion.
283 LogicalResult
284 registerVirtualInterfaceMembers(const slang::ast::ValueSymbol &base,
285 const slang::ast::VirtualInterfaceType &type,
286 Location loc);
287
288 /// Checks whether one class (actualTy) is derived from another class
289 /// (baseTy). True if it's a subclass, false otherwise.
290 bool isClassDerivedFrom(const moore::ClassHandleType &actualTy,
291 const moore::ClassHandleType &baseTy);
292
293 /// Tries to find the closest base class of actualTy that carries a property
294 /// with name fieldName. The location is used for error reporting.
295 moore::ClassHandleType
296 getAncestorClassWithProperty(const moore::ClassHandleType &actualTy,
297 StringRef fieldName, Location loc);
298
299 Value getImplicitThisRef() const {
300 return currentThisRef; // block arg added in declareFunction
301 }
302
303 /// Maps assertion system calls to their corresponding clocks
304 DenseMap<const slang::ast::CallExpression *,
305 const slang::ast::TimingControl *>
307
308 /// Generates a map from assertions to clocks using Slang's analysis
310
311 Value getIndexedQueue() const { return currentQueue; }
312
313 // Convert a statement AST node to MLIR ops.
314 LogicalResult convertStatement(const slang::ast::Statement &stmt);
315
316 // Convert an expression AST node to MLIR ops.
317 Value convertRvalueExpression(const slang::ast::Expression &expr,
318 Type requiredType = {});
319 Value convertLvalueExpression(const slang::ast::Expression &expr);
320
321 // Convert an assertion expression AST node to MLIR ops.
322 Value convertAssertionExpression(const slang::ast::AssertionExpr &expr,
323 Location loc);
324
325 // Convert an assertion expression AST node to MLIR ops.
327 const slang::ast::CallExpression &expr,
328 const slang::ast::CallExpression::SystemCallInfo &info, Location loc);
329
330 // Traverse the whole AST to collect hierarchical names.
331 void traverseInstanceBody(const slang::ast::InstanceSymbol &symbol);
332
333 /// Build a composite key for hierValueSymbols from a hierarchical value
334 /// expression. Returns {firstInstanceSymbol, dottedHierName} or std::nullopt
335 /// if the expression has no instance path.
336 std::optional<std::pair<const slang::ast::InstanceSymbol *, mlir::StringAttr>>
337 buildHierValueKey(const slang::ast::HierarchicalValueExpression &expr);
338
339 /// If `sym` is captured by the function currently being converted, return the
340 /// value it is bound to (the capture block argument); otherwise return null.
341 Value resolveCapturedValue(const slang::ast::ValueSymbol &sym);
342
343 // Convert timing controls into a corresponding set of ops that delay
344 // execution of the current block. Produces an error if the implicit event
345 // control `@*` or `@(*)` is used.
346 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl);
347 // Convert timing controls into a corresponding set of ops that delay
348 // execution of the current block. Then converts the given statement, taking
349 // note of the rvalues it reads and adding them to a wait op in case an
350 // implicit event control `@*` or `@(*)` is used.
351 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl,
352 const slang::ast::Statement &stmt);
353
354 /// Helper function to convert a value to a MLIR I1 value.
355 Value convertToI1(Value value);
356
357 // Convert a slang timing control for LTL
358 Value convertLTLTimingControl(const slang::ast::TimingControl &ctrl,
359 const Value &seqOrPro);
360
361 LogicalResult
362 convertNInputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
363
364 LogicalResult
365 convertNOutputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
366
367 LogicalResult
368 convertFixedPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
369
370 LogicalResult
371 convertPullGatePrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
372
373 /// Helper function to convert a value to its "truthy" boolean value.
374 Value convertToBool(Value value);
375
376 /// Helper function to convert a value to its "truthy" boolean value and
377 /// convert it to the given domain.
378 Value convertToBool(Value value, Domain domain);
379
380 /// Helper function to convert a value to its simple bit vector
381 /// representation, if it has one. Otherwise returns null. Also returns null
382 /// if the given value is null.
383 Value convertToSimpleBitVector(Value value);
384
385 /// Helper function to insert the necessary operations to cast a value from
386 /// one type to another. If `fallible` is true, conversion failures are
387 /// reported by returning a null value without emitting diagnostics.
388 Value materializeConversion(Type type, Value value, bool isSigned,
389 Location loc, bool fallible = false);
390
391 /// Helper function to materialize an `SVInt` as an SSA value.
392 Value materializeSVInt(const slang::SVInt &svint,
393 const slang::ast::Type &type, Location loc);
394
395 /// Helper function to materialize a real value as an SSA value.
396 Value materializeSVReal(const slang::ConstantValue &svreal,
397 const slang::ast::Type &type, Location loc);
398
399 /// Helper function to materialize a string as an SSA value.
400 Value materializeString(const slang::ConstantValue &string,
401 const slang::ast::Type &astType, Location loc);
402
403 /// Helper function to materialize an unpacked array of `SVInt`s as an SSA
404 /// value.
406 const slang::ConstantValue &constant,
407 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc);
408
409 /// Helper function to materialize a `ConstantValue` as an SSA value. Returns
410 /// null if the constant cannot be materialized.
411 Value materializeConstant(const slang::ConstantValue &constant,
412 const slang::ast::Type &type, Location loc);
413
414 /// Convert a list of string literal arguments with formatting specifiers and
415 /// arguments to be interpolated into a `!moore.format_string` value. Returns
416 /// failure if an error occurs. Returns a null value if the formatted string
417 /// is trivially empty. Otherwise returns the formatted string.
418 FailureOr<Value> convertFormatString(
419 std::span<const slang::ast::Expression *const> arguments, Location loc,
420 moore::IntFormat defaultFormat = moore::IntFormat::Decimal,
421 bool appendNewline = false);
422
423 /// Result of converting a scan format string. The final cursor of the
424 /// consuming chain and the list of (destination expression, scanned value,
425 /// matched flag) tuples to assign
428 SmallVector<std::tuple<const slang::ast::Expression *, Value, Value>>
430 };
431
432 /// Convert a scan format string into a consuming chain of `moore.scan.*`
433 /// operations starting from `initialCursor`. Each non-suppressed specifier
434 /// produces an entry in `assignments`; the caller is responsible for emitting
435 /// the corresponding `moore.blocking_assign` ops. Returns failur if an erro
436 /// occurs.
437 FailureOr<ScanStringResult>
438 convertScanString(StringRef formatStr, Value initialCursor,
439 std::span<const slang::ast::Expression *const> destinations,
440 Location loc);
441
442 /// Convert system function calls. Returns a null `Value` on failure after
443 /// emitting an error.
444 Value convertSystemCall(const slang::ast::SystemSubroutine &subroutine,
445 Location loc,
446 std::span<const slang::ast::Expression *const> args);
447
448 /// Convert system function calls within properties and assertion with a
449 /// single argument.
450 FailureOr<Value> convertAssertionSystemCallArity1(
451 const slang::ast::SystemSubroutine &subroutine, Location loc, Value value,
452 Type originalType, Value clockVal);
453
454 /// Evaluate the constant value of an expression.
455 slang::ConstantValue evaluateConstant(const slang::ast::Expression &expr);
456
457 /// Convert the inside/set-membership expression.
458 Value convertInsideCheck(Value insideLhs, Location loc,
459 const slang::ast::Expression &expr);
460
462 slang::ast::Compilation &compilation;
463 mlir::ModuleOp intoModuleOp;
464 const slang::SourceManager &sourceManager;
465
466 /// The builder used to create IR operations.
467 OpBuilder builder;
468 /// A symbol table of the MLIR module we are emitting into.
469 SymbolTable symbolTable;
470
471 /// The top-level operations ordered by their Slang source location. This is
472 /// used to produce IR that follows the source file order.
473 std::map<LocationKey, Operation *> orderedRootOps;
474
475 /// How we have lowered modules to MLIR.
476 /// The keys must be the slang canonical module bodies where they exist.
477 DenseMap<const slang::ast::InstanceBodySymbol *,
478 std::unique_ptr<ModuleLowering>>
480
481 /// Expanded interface instances, keyed by the InstanceSymbol pointer.
482 /// Each entry maps body members to their expanded SSA values. Scoped
483 /// per-module so entries are cleaned up when a module's conversion ends.
485 llvm::ScopedHashTable<const slang::ast::InstanceSymbol *,
487 using InterfaceInstanceScope = InterfaceInstances::ScopeTy;
489 /// Owning storage for InterfaceLowering objects
490 /// because ScopedHashTable stores values by copy.
491 SmallVector<std::unique_ptr<InterfaceLowering>> interfaceInstanceStorage;
492
493 /// Module instances already emitted by the predeclaration pass. These are
494 /// skipped during the later source-order module-body walk to avoid emitting
495 /// duplicate instances.
496 DenseSet<const slang::ast::InstanceSymbol *> predeclaredInstances;
497
498 /// Cached virtual interface layouts (type + field order).
499 DenseMap<const slang::ast::InstanceBodySymbol *, VirtualInterfaceLowering>
501 DenseMap<const slang::ast::ModportSymbol *, VirtualInterfaceLowering>
503 /// A list of modules for which the header has been created, but the body has
504 /// not been converted yet.
505 std::queue<const slang::ast::InstanceBodySymbol *> moduleWorklist;
506
507 /// A list of functions for which the declaration has been created, but the
508 /// body has not been defined yet.
509 std::queue<const slang::ast::SubroutineSymbol *> functionWorklist;
510
511 /// Functions that have already been converted.
512 DenseMap<const slang::ast::SubroutineSymbol *,
513 std::unique_ptr<FunctionLowering>>
515
516 /// DPI-C export directives keyed by the SystemVerilog subroutine they expose.
517 DenseMap<const slang::ast::SubroutineSymbol *, std::string> dpiExportCNames;
518
519 /// Classes that have already been converted.
520 DenseMap<const slang::ast::ClassType *, std::unique_ptr<ClassLowering>>
522
523 /// A table of defined values, such as variables, that may be referred to by
524 /// name in expressions. The expressions use this table to lookup the MLIR
525 /// value that was created for a given declaration in the Slang AST node.
527 llvm::ScopedHashTable<const slang::ast::ValueSymbol *, Value>;
528 using ValueSymbolScope = ValueSymbols::ScopeTy;
530
531 /// A table mapping symbols for interface members accessed through a virtual
532 /// interface to the virtual interface base value symbol.
534 llvm::ScopedHashTable<const slang::ast::ValueSymbol *,
536 using VirtualInterfaceMemberScope = VirtualInterfaceMembers::ScopeTy;
538
539 /// A table of defined global variables that may be referred to by name in
540 /// expressions.
541 DenseMap<const slang::ast::ValueSymbol *, moore::GlobalVariableOp>
543 /// A list of global variables that still need their initializers to be
544 /// converted.
545 SmallVector<const slang::ast::ValueSymbol *> globalVariableWorklist;
546
547 /// Pre-computed capture analysis: maps each function to the set of non-local,
548 /// non-global variables it captures (directly or transitively).
550
551 /// Collect all hierarchical names used for the per module/instance.
552 /// The keys are the slang canonical instance bodies (or the real instance
553 /// if slang's getCanonicalBody() returned null).
554 DenseMap<const slang::ast::InstanceBodySymbol *, SmallVector<HierPathInfo>>
556
557 /// Persistent map for hierarchical value lookups. Keyed by a composite
558 /// of the instance symbol (the specific instance being wired, e.g., p1 or
559 /// p2) and the hierarchical path name (e.g., "child.child_val"). This
560 /// ensures instance-specific resolution even when Slang shares or doesn't
561 /// share instance bodies across multiple instances of the same module.
562 DenseMap<std::pair<const slang::ast::InstanceSymbol *, mlir::StringAttr>,
563 Value>
565
566 /// A stack of assignment left-hand side values. Each assignment will push its
567 /// lowered left-hand side onto this stack before lowering its right-hand
568 /// side. This allows expressions to resolve the opaque
569 /// `LValueReferenceExpression`s in the AST.
570 SmallVector<Value> lvalueStack;
571
572 /// A stack of loop continuation and exit blocks. Each loop will push the
573 /// relevant info onto this stack, lower its loop body statements, and pop the
574 /// info off the stack again. Continue and break statements encountered as
575 /// part of the loop body statements will use this information to branch to
576 /// the correct block.
577 SmallVector<LoopFrame> loopStack;
578
579 /// A listener called for every variable or net being read. This can be used
580 /// to collect all variables read as part of an expression or statement, for
581 /// example to populate the list of observed signals in an implicit event
582 /// control `@*`.
583 std::function<void(moore::ReadOp)> rvalueReadCallback;
584 /// A listener called for every variable or net being assigned. This can be
585 /// used to collect all variables assigned in a task scope.
586 std::function<void(mlir::Operation *)> variableAssignCallback;
587
588 /// Whether we are currently converting expressions inside a timing control,
589 /// such as `@(posedge clk)`. This is used by the implicit event control
590 /// callback to avoid adding reads from explicit event controls to the
591 /// implicit sensitivity list.
593
594 /// The time scale currently in effect.
595 slang::TimeScale timeScale;
596
597 /// Variable to track the value of the current function's implicit `this`
598 /// reference
599 Value currentThisRef = {};
600
601 /// The function currently being converted, if any. Used to give captured
602 /// symbols priority over module-level hierarchical values inside function
603 /// bodies.
605
606 /// Variable that tracks the queue which we are currently converting the index
607 /// expression for. This is necessary to implement the `$` operator, which
608 /// returns the index of the last element of the queue.
609 Value currentQueue = {};
610
611 /// The definition symbol of the module body currently being converted.
612 /// Used to resolve the `%l`/`%L` library binding format specifier.
613 const slang::ast::DefinitionSymbol *currentDefinition = nullptr;
614
615 /// Ensure that the global variables for `$monitor` state exist. This creates
616 /// the `__monitor_active_id` and `__monitor_enabled` globals on first call.
618
619 /// Ensure that the global variable for `$timeformat` state exists.
620 /// This creates the `__timeformat_state` global on first call.
622
623 /// Process any pending `$monitor` calls and generate the monitoring
624 /// procedures at module level.
625 LogicalResult flushPendingMonitors();
626
627 /// Global variable ops for `$monitor` state management. These are created on
628 /// demand by `ensureMonitorGlobals()`.
629 moore::GlobalVariableOp monitorActiveIdGlobal = nullptr;
630 moore::GlobalVariableOp monitorEnabledGlobal = nullptr;
631
632 /// Global variable ops for `$timeformat` state management. These are created
633 /// on demand by `ensureTimeFormatGlobal()`.
634 moore::GlobalVariableOp timeFormatGlobal = nullptr;
635
636 /// The next monitor ID to allocate. ID 0 is reserved for "no monitor active".
637 unsigned nextMonitorId = 1;
638
639 /// Information about a pending `$monitor` call that needs to be converted
640 /// after the current module's body has been processed.
642 unsigned id;
643 Location loc;
644 const slang::ast::CallExpression *call;
645 };
646
647 /// Pending `$monitor` calls that need to be converted at module level.
648 SmallVector<PendingMonitor> pendingMonitors;
649
650private:
651 /// Helper function to extract the commonalities in lowering of functions and
652 /// methods
654 declareCallableImpl(const slang::ast::SubroutineSymbol &subroutine,
655 mlir::StringRef qualifiedName,
656 llvm::SmallVectorImpl<Type> &extraParams);
657};
658
659} // namespace ImportVerilog
660} // namespace circt
661#endif // CONVERSION_IMPORTVERILOG_IMPORTVERILOGINTERNALS_H
const slang::ast::InstanceBodySymbol * getCanonicalBody(const slang::ast::InstanceSymbol &inst)
Get the slang canonical body for the given instance, if there is one.
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 ...
Result of converting a scan format string.
SmallVector< std::tuple< const slang::ast::Expression *, Value, Value > > assignments
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.
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.
FailureOr< ScanStringResult > convertScanString(StringRef formatStr, Value initialCursor, std::span< const slang::ast::Expression *const > destinations, Location loc)
Convert a scan format string into a consuming chain of moore.scan.
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.
const slang::ast::DefinitionSymbol * currentDefinition
The definition symbol of the module body currently being converted.
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)
FailureOr< Value > convertAssertionSystemCallArity1(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value, Type originalType, Value clockVal)
Convert system function calls within properties and assertion with a single argument.
DenseSet< const slang::ast::InstanceSymbol * > predeclaredInstances
Module instances already emitted by the predeclaration pass.
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
void ensureTimeFormatGlobal()
Ensure that the global variable for $timeformat state exists.
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 resolveCapturedValue(const slang::ast::ValueSymbol &sym)
If sym is captured by the function currently being converted, return the value it is bound to (the ca...
DenseMap< std::pair< const slang::ast::InstanceSymbol *, mlir::StringAttr >, Value > hierValueSymbols
Persistent map for hierarchical value lookups.
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.
DenseMap< const slang::ast::SubroutineSymbol *, std::string > dpiExportCNames
DPI-C export directives keyed by the SystemVerilog subroutine they expose.
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
Value materializeConversion(Type type, Value value, bool isSigned, Location loc, bool fallible=false)
Helper function to insert the necessary operations to cast a value from one type to another.
void traverseInstanceBody(const slang::ast::InstanceSymbol &symbol)
void populateAssertionClocks()
Generates a map from assertions to clocks using Slang's analysis.
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.
DenseMap< const slang::ast::CallExpression *, const slang::ast::TimingControl * > assertionCallClocks
Maps assertion system calls to their corresponding clocks.
FunctionLowering * currentFunctionLowering
The function currently being converted, if any.
InterfaceInstances::ScopeTy InterfaceInstanceScope
moore::GlobalVariableOp timeFormatGlobal
Global variable ops for $timeformat state management.
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)
std::optional< std::pair< const slang::ast::InstanceSymbol *, mlir::StringAttr > > buildHierValueKey(const slang::ast::HierarchicalValueExpression &expr)
Build a composite key for hierValueSymbols from a hierarchical value expression.
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.
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.
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 * modportPortSym
For modport-typed iface ports, the ModportPortSymbol this was flattened from.
const slang::ast::Symbol * bodySym
the interface body member (VariableSymbol , NetSymbol)
std::optional< unsigned > outputIdx
Slot index in the module signature; see PortLowering::outputIdx.
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
llvm::SmallVector< std::pair< const slang::ast::ValueSymbol *, const slang::ast::InstanceBodySymbol * >, 2 > valueSyms
The symbols this path resolves to, each paired with the elaborated instance body it was observed in.
Lowering information for an expanded interface instance.
DenseMap< const slang::ast::Symbol *, Value > expandedMembers
DenseMap< StringAttr, Value > expandedMembersByName
ImportVerilog Elaboration Phases for Hierarchical Names.
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
unsigned numExplicitOutputs
Number of explicit-port slots per direction.
std::optional< unsigned > outputIdx
Slot index in the module signature.
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...