Loading [MathJax]/extensions/tex2jax.js
CIRCT 21.0.0git
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Expressions.cpp
Go to the documentation of this file.
1//===- Expressions.cpp - Slang expression conversion ----------------------===//
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
10#include "slang/ast/SystemSubroutine.h"
11#include "slang/syntax/AllSyntax.h"
12
13using namespace circt;
14using namespace ImportVerilog;
15using moore::Domain;
16
17/// Convert a Slang `SVInt` to a CIRCT `FVInt`.
18static FVInt convertSVIntToFVInt(const slang::SVInt &svint) {
19 if (svint.hasUnknown()) {
20 unsigned numWords = svint.getNumWords() / 2;
21 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), numWords);
22 auto unknown = ArrayRef<uint64_t>(svint.getRawPtr() + numWords, numWords);
23 return FVInt(APInt(svint.getBitWidth(), value),
24 APInt(svint.getBitWidth(), unknown));
25 }
26 auto value = ArrayRef<uint64_t>(svint.getRawPtr(), svint.getNumWords());
27 return FVInt(APInt(svint.getBitWidth(), value));
28}
29
30// NOLINTBEGIN(misc-no-recursion)
31namespace {
32struct RvalueExprVisitor {
33 Context &context;
34 Location loc;
35 OpBuilder &builder;
36
37 RvalueExprVisitor(Context &context, Location loc)
38 : context(context), loc(loc), builder(context.builder) {}
39
40 // Handle references to the left-hand side of a parent assignment.
41 Value visit(const slang::ast::LValueReferenceExpression &expr) {
42 assert(!context.lvalueStack.empty() && "parent assignments push lvalue");
43 auto lvalue = context.lvalueStack.back();
44 return builder.create<moore::ReadOp>(loc, lvalue);
45 }
46
47 // Handle named values, such as references to declared variables.
48 Value visit(const slang::ast::NamedValueExpression &expr) {
49 if (auto value = context.valueSymbols.lookup(&expr.symbol)) {
50 if (isa<moore::RefType>(value.getType())) {
51 auto readOp = builder.create<moore::ReadOp>(loc, value);
52 if (context.rvalueReadCallback)
53 context.rvalueReadCallback(readOp);
54 value = readOp.getResult();
55 }
56 return value;
57 }
58
59 // Try to materialize constant values directly.
60 auto constant = context.evaluateConstant(expr);
61 if (auto value = context.materializeConstant(constant, *expr.type, loc))
62 return value;
63
64 // Otherwise some other part of ImportVerilog should have added an MLIR
65 // value for this expression's symbol to the `context.valueSymbols` table.
66 auto d = mlir::emitError(loc, "unknown name `") << expr.symbol.name << "`";
67 d.attachNote(context.convertLocation(expr.symbol.location))
68 << "no rvalue generated for " << slang::ast::toString(expr.symbol.kind);
69 return {};
70 }
71
72 // Handle hierarchical values, such as `x = Top.sub.var`.
73 Value visit(const slang::ast::HierarchicalValueExpression &expr) {
74 auto hierLoc = context.convertLocation(expr.symbol.location);
75 if (auto value = context.valueSymbols.lookup(&expr.symbol)) {
76 if (isa<moore::RefType>(value.getType())) {
77 auto readOp = builder.create<moore::ReadOp>(hierLoc, value);
78 if (context.rvalueReadCallback)
79 context.rvalueReadCallback(readOp);
80 value = readOp.getResult();
81 }
82 return value;
83 }
84
85 // Emit an error for those hierarchical values not recorded in the
86 // `valueSymbols`.
87 auto d = mlir::emitError(loc, "unknown hierarchical name `")
88 << expr.symbol.name << "`";
89 d.attachNote(hierLoc) << "no rvalue generated for "
90 << slang::ast::toString(expr.symbol.kind);
91 return {};
92 }
93
94 // Handle type conversions (explicit and implicit).
95 Value visit(const slang::ast::ConversionExpression &expr) {
96 auto type = context.convertType(*expr.type);
97 if (!type)
98 return {};
99 return context.convertRvalueExpression(expr.operand(), type);
100 }
101
102 // Handle blocking and non-blocking assignments.
103 Value visit(const slang::ast::AssignmentExpression &expr) {
104 auto lhs = context.convertLvalueExpression(expr.left());
105 if (!lhs)
106 return {};
107
108 context.lvalueStack.push_back(lhs);
109 auto rhs = context.convertRvalueExpression(
110 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
111 context.lvalueStack.pop_back();
112 if (!rhs)
113 return {};
114
115 if (expr.timingControl) {
116 auto loc = context.convertLocation(expr.timingControl->sourceRange);
117 mlir::emitError(loc, "delayed assignments not supported");
118 return {};
119 }
120
121 if (expr.isNonBlocking())
122 builder.create<moore::NonBlockingAssignOp>(loc, lhs, rhs);
123 else
124 builder.create<moore::BlockingAssignOp>(loc, lhs, rhs);
125 return rhs;
126 }
127
128 // Helper function to convert an argument to a simple bit vector type, pass it
129 // to a reduction op, and optionally invert the result.
130 template <class ConcreteOp>
131 Value createReduction(Value arg, bool invert) {
132 arg = context.convertToSimpleBitVector(arg);
133 if (!arg)
134 return {};
135 Value result = builder.create<ConcreteOp>(loc, arg);
136 if (invert)
137 result = builder.create<moore::NotOp>(loc, result);
138 return result;
139 }
140
141 // Helper function to create pre and post increments and decrements.
142 Value createIncrement(Value arg, bool isInc, bool isPost) {
143 auto preValue = builder.create<moore::ReadOp>(loc, arg);
144 auto one = builder.create<moore::ConstantOp>(
145 loc, cast<moore::IntType>(preValue.getType()), 1);
146 auto postValue =
147 isInc ? builder.create<moore::AddOp>(loc, preValue, one).getResult()
148 : builder.create<moore::SubOp>(loc, preValue, one).getResult();
149 builder.create<moore::BlockingAssignOp>(loc, arg, postValue);
150 if (isPost)
151 return preValue;
152 return postValue;
153 }
154
155 // Handle unary operators.
156 Value visit(const slang::ast::UnaryExpression &expr) {
157 using slang::ast::UnaryOperator;
158 Value arg;
159 if (expr.op == UnaryOperator::Preincrement ||
160 expr.op == UnaryOperator::Predecrement ||
161 expr.op == UnaryOperator::Postincrement ||
162 expr.op == UnaryOperator::Postdecrement)
163 arg = context.convertLvalueExpression(expr.operand());
164 else
165 arg = context.convertRvalueExpression(expr.operand());
166 if (!arg)
167 return {};
168
169 switch (expr.op) {
170 // `+a` is simply `a`, but converted to a simple bit vector type since
171 // this is technically an arithmetic operation.
172 case UnaryOperator::Plus:
173 return context.convertToSimpleBitVector(arg);
174
175 case UnaryOperator::Minus:
176 arg = context.convertToSimpleBitVector(arg);
177 if (!arg)
178 return {};
179 return builder.create<moore::NegOp>(loc, arg);
180
181 case UnaryOperator::BitwiseNot:
182 arg = context.convertToSimpleBitVector(arg);
183 if (!arg)
184 return {};
185 return builder.create<moore::NotOp>(loc, arg);
186
187 case UnaryOperator::BitwiseAnd:
188 return createReduction<moore::ReduceAndOp>(arg, false);
189 case UnaryOperator::BitwiseOr:
190 return createReduction<moore::ReduceOrOp>(arg, false);
191 case UnaryOperator::BitwiseXor:
192 return createReduction<moore::ReduceXorOp>(arg, false);
193 case UnaryOperator::BitwiseNand:
194 return createReduction<moore::ReduceAndOp>(arg, true);
195 case UnaryOperator::BitwiseNor:
196 return createReduction<moore::ReduceOrOp>(arg, true);
197 case UnaryOperator::BitwiseXnor:
198 return createReduction<moore::ReduceXorOp>(arg, true);
199
200 case UnaryOperator::LogicalNot:
201 arg = context.convertToBool(arg);
202 if (!arg)
203 return {};
204 return builder.create<moore::NotOp>(loc, arg);
205
206 case UnaryOperator::Preincrement:
207 return createIncrement(arg, true, false);
208 case UnaryOperator::Predecrement:
209 return createIncrement(arg, false, false);
210 case UnaryOperator::Postincrement:
211 return createIncrement(arg, true, true);
212 case UnaryOperator::Postdecrement:
213 return createIncrement(arg, false, true);
214 }
215
216 mlir::emitError(loc, "unsupported unary operator");
217 return {};
218 }
219
220 // Helper function to convert two arguments to a simple bit vector type and
221 // pass them into a binary op.
222 template <class ConcreteOp>
223 Value createBinary(Value lhs, Value rhs) {
224 lhs = context.convertToSimpleBitVector(lhs);
225 if (!lhs)
226 return {};
227 rhs = context.convertToSimpleBitVector(rhs);
228 if (!rhs)
229 return {};
230 return builder.create<ConcreteOp>(loc, lhs, rhs);
231 }
232
233 // Handle binary operators.
234 Value visit(const slang::ast::BinaryExpression &expr) {
235 auto lhs = context.convertRvalueExpression(expr.left());
236 if (!lhs)
237 return {};
238 auto rhs = context.convertRvalueExpression(expr.right());
239 if (!rhs)
240 return {};
241
242 // Determine the domain of the result.
243 Domain domain = Domain::TwoValued;
244 if (expr.type->isFourState() || expr.left().type->isFourState() ||
245 expr.right().type->isFourState())
246 domain = Domain::FourValued;
247
248 using slang::ast::BinaryOperator;
249 switch (expr.op) {
250 case BinaryOperator::Add:
251 return createBinary<moore::AddOp>(lhs, rhs);
252 case BinaryOperator::Subtract:
253 return createBinary<moore::SubOp>(lhs, rhs);
254 case BinaryOperator::Multiply:
255 return createBinary<moore::MulOp>(lhs, rhs);
256 case BinaryOperator::Divide:
257 if (expr.type->isSigned())
258 return createBinary<moore::DivSOp>(lhs, rhs);
259 else
260 return createBinary<moore::DivUOp>(lhs, rhs);
261 case BinaryOperator::Mod:
262 if (expr.type->isSigned())
263 return createBinary<moore::ModSOp>(lhs, rhs);
264 else
265 return createBinary<moore::ModUOp>(lhs, rhs);
266 case BinaryOperator::Power: {
267 // Slang casts the LHS and result of the `**` operator to a four-valued
268 // type, since the operator can return X even for two-valued inputs. To
269 // maintain uniform types across operands and results, cast the RHS to
270 // that four-valued type as well.
271 auto rhsCast =
272 builder.create<moore::ConversionOp>(loc, lhs.getType(), rhs);
273 if (expr.type->isSigned())
274 return createBinary<moore::PowSOp>(lhs, rhsCast);
275 else
276 return createBinary<moore::PowUOp>(lhs, rhsCast);
277 }
278
279 case BinaryOperator::BinaryAnd:
280 return createBinary<moore::AndOp>(lhs, rhs);
281 case BinaryOperator::BinaryOr:
282 return createBinary<moore::OrOp>(lhs, rhs);
283 case BinaryOperator::BinaryXor:
284 return createBinary<moore::XorOp>(lhs, rhs);
285 case BinaryOperator::BinaryXnor: {
286 auto result = createBinary<moore::XorOp>(lhs, rhs);
287 if (!result)
288 return {};
289 return builder.create<moore::NotOp>(loc, result);
290 }
291
292 case BinaryOperator::Equality:
293 if (isa<moore::UnpackedArrayType>(lhs.getType()))
294 return builder.create<moore::UArrayCmpOp>(
295 loc, moore::UArrayCmpPredicate::eq, lhs, rhs);
296 else if (isa<moore::StringType>(lhs.getType()))
297 return builder.create<moore::StringCmpOp>(
298 loc, moore::StringCmpPredicate::eq, lhs, rhs);
299 else
300 return createBinary<moore::EqOp>(lhs, rhs);
301 case BinaryOperator::Inequality:
302 if (isa<moore::UnpackedArrayType>(lhs.getType()))
303 return builder.create<moore::UArrayCmpOp>(
304 loc, moore::UArrayCmpPredicate::ne, lhs, rhs);
305 else if (isa<moore::StringType>(lhs.getType()))
306 return builder.create<moore::StringCmpOp>(
307 loc, moore::StringCmpPredicate::ne, lhs, rhs);
308 else
309 return createBinary<moore::NeOp>(lhs, rhs);
310 case BinaryOperator::CaseEquality:
311 return createBinary<moore::CaseEqOp>(lhs, rhs);
312 case BinaryOperator::CaseInequality:
313 return createBinary<moore::CaseNeOp>(lhs, rhs);
314 case BinaryOperator::WildcardEquality:
315 return createBinary<moore::WildcardEqOp>(lhs, rhs);
316 case BinaryOperator::WildcardInequality:
317 return createBinary<moore::WildcardNeOp>(lhs, rhs);
318
319 case BinaryOperator::GreaterThanEqual:
320 if (expr.left().type->isSigned())
321 return createBinary<moore::SgeOp>(lhs, rhs);
322 else if (isa<moore::StringType>(lhs.getType()))
323 return builder.create<moore::StringCmpOp>(
324 loc, moore::StringCmpPredicate::ge, lhs, rhs);
325 else
326 return createBinary<moore::UgeOp>(lhs, rhs);
327 case BinaryOperator::GreaterThan:
328 if (expr.left().type->isSigned())
329 return createBinary<moore::SgtOp>(lhs, rhs);
330 else if (isa<moore::StringType>(lhs.getType()))
331 return builder.create<moore::StringCmpOp>(
332 loc, moore::StringCmpPredicate::gt, lhs, rhs);
333 else
334 return createBinary<moore::UgtOp>(lhs, rhs);
335 case BinaryOperator::LessThanEqual:
336 if (expr.left().type->isSigned())
337 return createBinary<moore::SleOp>(lhs, rhs);
338 else if (isa<moore::StringType>(lhs.getType()))
339 return builder.create<moore::StringCmpOp>(
340 loc, moore::StringCmpPredicate::le, lhs, rhs);
341 else
342 return createBinary<moore::UleOp>(lhs, rhs);
343 case BinaryOperator::LessThan:
344 if (expr.left().type->isSigned())
345 return createBinary<moore::SltOp>(lhs, rhs);
346 else if (isa<moore::StringType>(lhs.getType()))
347 return builder.create<moore::StringCmpOp>(
348 loc, moore::StringCmpPredicate::lt, lhs, rhs);
349 else
350 return createBinary<moore::UltOp>(lhs, rhs);
351
352 // See IEEE 1800-2017 § 11.4.7 "Logical operators".
353 case BinaryOperator::LogicalAnd: {
354 // TODO: This should short-circuit. Put the RHS code into a separate
355 // block.
356 lhs = context.convertToBool(lhs, domain);
357 if (!lhs)
358 return {};
359 rhs = context.convertToBool(rhs, domain);
360 if (!rhs)
361 return {};
362 return builder.create<moore::AndOp>(loc, lhs, rhs);
363 }
364 case BinaryOperator::LogicalOr: {
365 // TODO: This should short-circuit. Put the RHS code into a separate
366 // block.
367 lhs = context.convertToBool(lhs, domain);
368 if (!lhs)
369 return {};
370 rhs = context.convertToBool(rhs, domain);
371 if (!rhs)
372 return {};
373 return builder.create<moore::OrOp>(loc, lhs, rhs);
374 }
375 case BinaryOperator::LogicalImplication: {
376 // `(lhs -> rhs)` equivalent to `(!lhs || rhs)`.
377 lhs = context.convertToBool(lhs, domain);
378 if (!lhs)
379 return {};
380 rhs = context.convertToBool(rhs, domain);
381 if (!rhs)
382 return {};
383 auto notLHS = builder.create<moore::NotOp>(loc, lhs);
384 return builder.create<moore::OrOp>(loc, notLHS, rhs);
385 }
386 case BinaryOperator::LogicalEquivalence: {
387 // `(lhs <-> rhs)` equivalent to `(lhs && rhs) || (!lhs && !rhs)`.
388 lhs = context.convertToBool(lhs, domain);
389 if (!lhs)
390 return {};
391 rhs = context.convertToBool(rhs, domain);
392 if (!rhs)
393 return {};
394 auto notLHS = builder.create<moore::NotOp>(loc, lhs);
395 auto notRHS = builder.create<moore::NotOp>(loc, rhs);
396 auto both = builder.create<moore::AndOp>(loc, lhs, rhs);
397 auto notBoth = builder.create<moore::AndOp>(loc, notLHS, notRHS);
398 return builder.create<moore::OrOp>(loc, both, notBoth);
399 }
400
401 case BinaryOperator::LogicalShiftLeft:
402 return createBinary<moore::ShlOp>(lhs, rhs);
403 case BinaryOperator::LogicalShiftRight:
404 return createBinary<moore::ShrOp>(lhs, rhs);
405 case BinaryOperator::ArithmeticShiftLeft:
406 return createBinary<moore::ShlOp>(lhs, rhs);
407 case BinaryOperator::ArithmeticShiftRight: {
408 // The `>>>` operator is an arithmetic right shift if the LHS operand is
409 // signed, or a logical right shift if the operand is unsigned.
410 lhs = context.convertToSimpleBitVector(lhs);
411 rhs = context.convertToSimpleBitVector(rhs);
412 if (!lhs || !rhs)
413 return {};
414 if (expr.type->isSigned())
415 return builder.create<moore::AShrOp>(loc, lhs, rhs);
416 return builder.create<moore::ShrOp>(loc, lhs, rhs);
417 }
418 }
419
420 mlir::emitError(loc, "unsupported binary operator");
421 return {};
422 }
423
424 // Handle `'0`, `'1`, `'x`, and `'z` literals.
425 Value visit(const slang::ast::UnbasedUnsizedIntegerLiteral &expr) {
426 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
427 }
428
429 // Handle integer literals.
430 Value visit(const slang::ast::IntegerLiteral &expr) {
431 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
432 }
433
434 // Handle concatenations.
435 Value visit(const slang::ast::ConcatenationExpression &expr) {
436 SmallVector<Value> operands;
437 for (auto *operand : expr.operands()) {
438 // Handle empty replications like `{0{...}}` which may occur within
439 // concatenations. Slang assigns them a `void` type which we can check for
440 // here.
441 if (operand->type->isVoid())
442 continue;
443 auto value = context.convertRvalueExpression(*operand);
444 value = context.convertToSimpleBitVector(value);
445 if (!value)
446 return {};
447 operands.push_back(value);
448 }
449 return builder.create<moore::ConcatOp>(loc, operands);
450 }
451
452 // Handle replications.
453 Value visit(const slang::ast::ReplicationExpression &expr) {
454 auto type = context.convertType(*expr.type);
455 auto value = context.convertRvalueExpression(expr.concat());
456 if (!value)
457 return {};
458 return builder.create<moore::ReplicateOp>(loc, type, value);
459 }
460
461 Value getSelectIndex(Value index, const slang::ConstantRange &range) const {
462 auto indexType = cast<moore::UnpackedType>(index.getType());
463 auto bw = std::max(llvm::Log2_32_Ceil(std::max(std::abs(range.lower()),
464 std::abs(range.upper()))),
465 indexType.getBitSize().value());
466 auto intType =
467 moore::IntType::get(index.getContext(), bw, indexType.getDomain());
468
469 if (range.isLittleEndian()) {
470 if (range.lower() == 0)
471 return index;
472
473 Value newIndex =
474 builder.createOrFold<moore::ConversionOp>(loc, intType, index);
475 Value offset = builder.create<moore::ConstantOp>(
476 loc, intType, range.lower(), /*isSigned = */ range.lower() < 0);
477 return builder.createOrFold<moore::SubOp>(loc, newIndex, offset);
478 }
479
480 if (range.upper() == 0)
481 return builder.createOrFold<moore::NegOp>(loc, index);
482
483 Value newIndex =
484 builder.createOrFold<moore::ConversionOp>(loc, intType, index);
485 Value offset = builder.create<moore::ConstantOp>(
486 loc, intType, range.upper(), /* isSigned = */ range.upper() < 0);
487 return builder.createOrFold<moore::SubOp>(loc, offset, newIndex);
488 }
489
490 // Handle single bit selections.
491 Value visit(const slang::ast::ElementSelectExpression &expr) {
492 auto type = context.convertType(*expr.type);
493 auto value = context.convertRvalueExpression(expr.value());
494 if (!type || !value)
495 return {};
496 auto range = expr.value().type->getFixedRange();
497 if (auto *constValue = expr.selector().constant) {
498 assert(!constValue->hasUnknown());
499 assert(constValue->size() <= 32);
500
501 auto lowBit = constValue->integer().as<uint32_t>().value();
502 return builder.create<moore::ExtractOp>(loc, type, value,
503 range.translateIndex(lowBit));
504 }
505 auto lowBit = context.convertRvalueExpression(expr.selector());
506 if (!lowBit)
507 return {};
508 return builder.create<moore::DynExtractOp>(loc, type, value,
509 getSelectIndex(lowBit, range));
510 }
511
512 // Handle range bits selections.
513 Value visit(const slang::ast::RangeSelectExpression &expr) {
514 auto type = context.convertType(*expr.type);
515 auto value = context.convertRvalueExpression(expr.value());
516 if (!type || !value)
517 return {};
518
519 Value dynLowBit;
520 uint32_t constLowBit;
521 auto *leftConst = expr.left().constant;
522 auto *rightConst = expr.right().constant;
523 if (leftConst) {
524 assert(!leftConst->hasUnknown());
525 assert(leftConst->size() <= 32);
526 }
527 if (rightConst) {
528 assert(!rightConst->hasUnknown());
529 assert(rightConst->size() <= 32);
530 }
531
532 if (expr.getSelectionKind() == slang::ast::RangeSelectionKind::Simple) {
533 if (leftConst && rightConst) {
534 // Estimate whether is big endian or little endian.
535 auto lhs = leftConst->integer().as<uint32_t>().value();
536 auto rhs = rightConst->integer().as<uint32_t>().value();
537 constLowBit = lhs < rhs ? lhs : rhs;
538 } else {
539 mlir::emitError(loc, "unsupported a variable as the index in the")
540 << slang::ast::toString(expr.getSelectionKind()) << "kind";
541 return {};
542 }
543 } else if (expr.getSelectionKind() ==
544 slang::ast::RangeSelectionKind::IndexedDown) {
545 // IndexedDown: arr[7-:8]. It's equivalent to arr[7:0] or arr[0:7]
546 // depending on little endian or bit endian. No matter which situation,
547 // the low bit must be "0".
548 if (leftConst) {
549 auto subtrahend = leftConst->integer().as<uint32_t>().value();
550 auto sliceWidth =
551 expr.right().constant->integer().as<uint32_t>().value();
552 constLowBit = subtrahend - sliceWidth - 1;
553 } else {
554 auto subtrahend = context.convertRvalueExpression(expr.left());
555 auto subtrahendType = cast<moore::UnpackedType>(subtrahend.getType());
556 auto intType = moore::IntType::get(context.getContext(),
557 subtrahendType.getBitSize().value(),
558 subtrahendType.getDomain());
559 auto sliceWidth =
560 expr.right().constant->integer().as<uint32_t>().value() - 1;
561 auto minuend = builder.create<moore::ConstantOp>(
562 loc, intType, sliceWidth, expr.left().type->isSigned());
563 dynLowBit = builder.create<moore::SubOp>(loc, subtrahend, minuend);
564 }
565 } else {
566 // IndexedUp: arr[0+:8]. "0" is the low bit, "8" is the bits slice width.
567 if (leftConst)
568 constLowBit = leftConst->integer().as<uint32_t>().value();
569 else
570 dynLowBit = context.convertRvalueExpression(expr.left());
571 }
572 auto range = expr.value().type->getFixedRange();
573 if (leftConst && rightConst)
574 return builder.create<moore::ExtractOp>(
575 loc, type, value, range.translateIndex(constLowBit));
576 return builder.create<moore::DynExtractOp>(
577 loc, type, value, getSelectIndex(dynLowBit, range));
578 }
579
580 Value visit(const slang::ast::MemberAccessExpression &expr) {
581 auto type = context.convertType(*expr.type);
582 auto valueType = expr.value().type;
583 auto value = context.convertRvalueExpression(expr.value());
584 if (!type || !value)
585 return {};
586 if (valueType->isStruct()) {
587 return builder.create<moore::StructExtractOp>(
588 loc, type, builder.getStringAttr(expr.member.name), value);
589 }
590 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
591 return builder.create<moore::UnionExtractOp>(
592 loc, type, builder.getStringAttr(expr.member.name), value);
593 }
594 mlir::emitError(loc, "expression of type ")
595 << value.getType() << " cannot be accessed";
596 return {};
597 }
598
599 // Handle set membership operator.
600 Value visit(const slang::ast::InsideExpression &expr) {
601 auto lhs = context.convertToSimpleBitVector(
602 context.convertRvalueExpression(expr.left()));
603 if (!lhs)
604 return {};
605 // All conditions for determining whether it is inside.
606 SmallVector<Value> conditions;
607
608 // Traverse open range list.
609 for (const auto *listExpr : expr.rangeList()) {
610 Value cond;
611 // The open range list on the right-hand side of the inside operator is a
612 // comma-separated list of expressions or ranges.
613 if (const auto *openRange =
614 listExpr->as_if<slang::ast::OpenRangeExpression>()) {
615 // Handle ranges.
616 auto lowBound = context.convertToSimpleBitVector(
617 context.convertRvalueExpression(openRange->left()));
618 auto highBound = context.convertToSimpleBitVector(
619 context.convertRvalueExpression(openRange->right()));
620 if (!lowBound || !highBound)
621 return {};
622 Value leftValue, rightValue;
623 // Determine if the expression on the left-hand side is inclusively
624 // within the range.
625 if (openRange->left().type->isSigned() ||
626 expr.left().type->isSigned()) {
627 leftValue = builder.create<moore::SgeOp>(loc, lhs, lowBound);
628 } else {
629 leftValue = builder.create<moore::UgeOp>(loc, lhs, lowBound);
630 }
631 if (openRange->right().type->isSigned() ||
632 expr.left().type->isSigned()) {
633 rightValue = builder.create<moore::SleOp>(loc, lhs, highBound);
634 } else {
635 rightValue = builder.create<moore::UleOp>(loc, lhs, highBound);
636 }
637 cond = builder.create<moore::AndOp>(loc, leftValue, rightValue);
638 } else {
639 // Handle expressions.
640 if (!listExpr->type->isSimpleBitVector()) {
641 if (listExpr->type->isUnpackedArray()) {
642 mlir::emitError(
643 loc, "unpacked arrays in 'inside' expressions not supported");
644 return {};
645 }
646 mlir::emitError(
647 loc, "only simple bit vectors supported in 'inside' expressions");
648 return {};
649 }
650 auto value = context.convertToSimpleBitVector(
651 context.convertRvalueExpression(*listExpr));
652 if (!value)
653 return {};
654 cond = builder.create<moore::WildcardEqOp>(loc, lhs, value);
655 }
656 conditions.push_back(cond);
657 }
658
659 // Calculate the final result by `or` op.
660 auto result = conditions.back();
661 conditions.pop_back();
662 while (!conditions.empty()) {
663 result = builder.create<moore::OrOp>(loc, conditions.back(), result);
664 conditions.pop_back();
665 }
666 return result;
667 }
668
669 // Handle conditional operator `?:`.
670 Value visit(const slang::ast::ConditionalExpression &expr) {
671 auto type = context.convertType(*expr.type);
672
673 // Handle condition.
674 if (expr.conditions.size() > 1) {
675 mlir::emitError(loc)
676 << "unsupported conditional expression with more than one condition";
677 return {};
678 }
679 const auto &cond = expr.conditions[0];
680 if (cond.pattern) {
681 mlir::emitError(loc) << "unsupported conditional expression with pattern";
682 return {};
683 }
684 auto value =
685 context.convertToBool(context.convertRvalueExpression(*cond.expr));
686 if (!value)
687 return {};
688 auto conditionalOp = builder.create<moore::ConditionalOp>(loc, type, value);
689
690 // Create blocks for true region and false region.
691 auto &trueBlock = conditionalOp.getTrueRegion().emplaceBlock();
692 auto &falseBlock = conditionalOp.getFalseRegion().emplaceBlock();
693
694 OpBuilder::InsertionGuard g(builder);
695
696 // Handle left expression.
697 builder.setInsertionPointToStart(&trueBlock);
698 auto trueValue = context.convertRvalueExpression(expr.left(), type);
699 if (!trueValue)
700 return {};
701 builder.create<moore::YieldOp>(loc, trueValue);
702
703 // Handle right expression.
704 builder.setInsertionPointToStart(&falseBlock);
705 auto falseValue = context.convertRvalueExpression(expr.right(), type);
706 if (!falseValue)
707 return {};
708 builder.create<moore::YieldOp>(loc, falseValue);
709
710 return conditionalOp.getResult();
711 }
712
713 /// Handle calls.
714 Value visit(const slang::ast::CallExpression &expr) {
715 // Class method calls are currently not supported.
716 if (expr.thisClass()) {
717 mlir::emitError(loc, "unsupported class method call");
718 return {};
719 }
720
721 // Try to materialize constant values directly.
722 auto constant = context.evaluateConstant(expr);
723 if (auto value = context.materializeConstant(constant, *expr.type, loc))
724 return value;
725
726 return std::visit(
727 [&](auto &subroutine) { return visitCall(expr, subroutine); },
728 expr.subroutine);
729 }
730
731 /// Handle subroutine calls.
732 Value visitCall(const slang::ast::CallExpression &expr,
733 const slang::ast::SubroutineSymbol *subroutine) {
734 auto *lowering = context.declareFunction(*subroutine);
735 if (!lowering)
736 return {};
737
738 // Convert the call arguments. Input arguments are converted to an rvalue.
739 // All other arguments are converted to lvalues and passed into the function
740 // by reference.
741 SmallVector<Value> arguments;
742 for (auto [callArg, declArg] :
743 llvm::zip(expr.arguments(), subroutine->getArguments())) {
744
745 // Unpack the `<expr> = EmptyArgument` pattern emitted by Slang for output
746 // and inout arguments.
747 auto *expr = callArg;
748 if (const auto *assign = expr->as_if<slang::ast::AssignmentExpression>())
749 expr = &assign->left();
750
751 Value value;
752 if (declArg->direction == slang::ast::ArgumentDirection::In)
753 value = context.convertRvalueExpression(*expr);
754 else
755 value = context.convertLvalueExpression(*expr);
756 if (!value)
757 return {};
758 arguments.push_back(value);
759 }
760
761 // Create the call.
762 auto callOp =
763 builder.create<mlir::func::CallOp>(loc, lowering->op, arguments);
764
765 // For calls to void functions we need to have a value to return from this
766 // function. Create a dummy `unrealized_conversion_cast`, which will get
767 // deleted again later on.
768 if (callOp.getNumResults() == 0)
769 return builder
770 .create<mlir::UnrealizedConversionCastOp>(
771 loc, moore::VoidType::get(context.getContext()), ValueRange{})
772 .getResult(0);
773
774 return callOp.getResult(0);
775 }
776
777 /// Handle system calls.
778 Value visitCall(const slang::ast::CallExpression &expr,
779 const slang::ast::CallExpression::SystemCallInfo &info) {
780 const auto &subroutine = *info.subroutine;
781 auto args = expr.arguments();
782
783 if (args.size() == 1) {
784 auto value = context.convertRvalueExpression(*args[0]);
785 if (!value)
786 return {};
787 auto result = context.convertSystemCallArity1(subroutine, loc, value);
788 if (failed(result))
789 return {};
790 if (*result)
791 return *result;
792 }
793
794 mlir::emitError(loc) << "unsupported system call `" << subroutine.name
795 << "`";
796 return {};
797 }
798
799 /// Handle string literals.
800 Value visit(const slang::ast::StringLiteral &expr) {
801 auto type = context.convertType(*expr.type);
802 return builder.create<moore::StringConstantOp>(loc, type, expr.getValue());
803 }
804
805 /// Handle real literals.
806 Value visit(const slang::ast::RealLiteral &expr) {
807 return builder.create<moore::RealLiteralOp>(
808 loc, builder.getF64FloatAttr(expr.getValue()));
809 }
810
811 /// Handle assignment patterns.
812 Value visitAssignmentPattern(
813 const slang::ast::AssignmentPatternExpressionBase &expr,
814 unsigned replCount = 1) {
815 auto type = context.convertType(*expr.type);
816
817 // Convert the individual elements first.
818 auto elementCount = expr.elements().size();
819 SmallVector<Value> elements;
820 elements.reserve(replCount * elementCount);
821 for (auto elementExpr : expr.elements()) {
822 auto value = context.convertRvalueExpression(*elementExpr);
823 if (!value)
824 return {};
825 elements.push_back(value);
826 }
827 for (unsigned replIdx = 1; replIdx < replCount; ++replIdx)
828 for (unsigned elementIdx = 0; elementIdx < elementCount; ++elementIdx)
829 elements.push_back(elements[elementIdx]);
830
831 // Handle integers.
832 if (auto intType = dyn_cast<moore::IntType>(type)) {
833 assert(intType.getWidth() == elements.size());
834 std::reverse(elements.begin(), elements.end());
835 return builder.create<moore::ConcatOp>(loc, intType, elements);
836 }
837
838 // Handle packed structs.
839 if (auto structType = dyn_cast<moore::StructType>(type)) {
840 assert(structType.getMembers().size() == elements.size());
841 return builder.create<moore::StructCreateOp>(loc, structType, elements);
842 }
843
844 // Handle unpacked structs.
845 if (auto structType = dyn_cast<moore::UnpackedStructType>(type)) {
846 assert(structType.getMembers().size() == elements.size());
847 return builder.create<moore::StructCreateOp>(loc, structType, elements);
848 }
849
850 // Handle packed arrays.
851 if (auto arrayType = dyn_cast<moore::ArrayType>(type)) {
852 assert(arrayType.getSize() == elements.size());
853 return builder.create<moore::ArrayCreateOp>(loc, arrayType, elements);
854 }
855
856 // Handle unpacked arrays.
857 if (auto arrayType = dyn_cast<moore::UnpackedArrayType>(type)) {
858 assert(arrayType.getSize() == elements.size());
859 return builder.create<moore::ArrayCreateOp>(loc, arrayType, elements);
860 }
861
862 mlir::emitError(loc) << "unsupported assignment pattern with type " << type;
863 return {};
864 }
865
866 Value visit(const slang::ast::SimpleAssignmentPatternExpression &expr) {
867 return visitAssignmentPattern(expr);
868 }
869
870 Value visit(const slang::ast::StructuredAssignmentPatternExpression &expr) {
871 return visitAssignmentPattern(expr);
872 }
873
874 Value visit(const slang::ast::ReplicatedAssignmentPatternExpression &expr) {
875 auto count =
876 context.evaluateConstant(expr.count()).integer().as<unsigned>();
877 assert(count && "Slang guarantees constant non-zero replication count");
878 return visitAssignmentPattern(expr, *count);
879 }
880
881 Value visit(const slang::ast::StreamingConcatenationExpression &expr) {
882 SmallVector<Value> operands;
883 for (auto stream : expr.streams()) {
884 auto operandLoc = context.convertLocation(stream.operand->sourceRange);
885 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
886 mlir::emitError(operandLoc)
887 << "Moore only support streaming "
888 "concatenation with fixed size 'with expression'";
889 return {};
890 }
891 Value value;
892 if (stream.constantWithWidth.has_value()) {
893 value = context.convertRvalueExpression(*stream.withExpr);
894 auto type = cast<moore::UnpackedType>(value.getType());
895 auto intType = moore::IntType::get(
896 context.getContext(), type.getBitSize().value(), type.getDomain());
897 // Do not care if it's signed, because we will not do expansion.
898 value = context.materializeConversion(intType, value, false, loc);
899 } else {
900 value = context.convertRvalueExpression(*stream.operand);
901 }
902
903 value = context.convertToSimpleBitVector(value);
904 if (!value)
905 return {};
906 operands.push_back(value);
907 }
908 Value value;
909
910 if (operands.size() == 1) {
911 // There must be at least one element, otherwise slang will report an
912 // error.
913 value = operands.front();
914 } else {
915 value = builder.create<moore::ConcatOp>(loc, operands).getResult();
916 }
917
918 if (expr.sliceSize == 0) {
919 return value;
920 }
921
922 auto type = cast<moore::IntType>(value.getType());
923 SmallVector<Value> slicedOperands;
924 auto iterMax = type.getWidth() / expr.sliceSize;
925 auto remainSize = type.getWidth() % expr.sliceSize;
926
927 for (size_t i = 0; i < iterMax; i++) {
928 auto extractResultType = moore::IntType::get(
929 context.getContext(), expr.sliceSize, type.getDomain());
930
931 auto extracted = builder.create<moore::ExtractOp>(
932 loc, extractResultType, value, i * expr.sliceSize);
933 slicedOperands.push_back(extracted);
934 }
935 // Handle other wire
936 if (remainSize) {
937 auto extractResultType = moore::IntType::get(
938 context.getContext(), remainSize, type.getDomain());
939
940 auto extracted = builder.create<moore::ExtractOp>(
941 loc, extractResultType, value, iterMax * expr.sliceSize);
942 slicedOperands.push_back(extracted);
943 }
944
945 return builder.create<moore::ConcatOp>(loc, slicedOperands);
946 }
947
948 /// Emit an error for all other expressions.
949 template <typename T>
950 Value visit(T &&node) {
951 mlir::emitError(loc, "unsupported expression: ")
952 << slang::ast::toString(node.kind);
953 return {};
954 }
955
956 Value visitInvalid(const slang::ast::Expression &expr) {
957 mlir::emitError(loc, "invalid expression");
958 return {};
959 }
960};
961} // namespace
962
963namespace {
964struct LvalueExprVisitor {
965 Context &context;
966 Location loc;
967 OpBuilder &builder;
968
969 LvalueExprVisitor(Context &context, Location loc)
970 : context(context), loc(loc), builder(context.builder) {}
971
972 // Handle named values, such as references to declared variables.
973 Value visit(const slang::ast::NamedValueExpression &expr) {
974 if (auto value = context.valueSymbols.lookup(&expr.symbol))
975 return value;
976 auto d = mlir::emitError(loc, "unknown name `") << expr.symbol.name << "`";
977 d.attachNote(context.convertLocation(expr.symbol.location))
978 << "no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
979 return {};
980 }
981
982 // Handle hierarchical values, such as `Top.sub.var = x`.
983 Value visit(const slang::ast::HierarchicalValueExpression &expr) {
984 if (auto value = context.valueSymbols.lookup(&expr.symbol))
985 return value;
986
987 // Emit an error for those hierarchical values not recorded in the
988 // `valueSymbols`.
989 auto d = mlir::emitError(loc, "unknown hierarchical name `")
990 << expr.symbol.name << "`";
991 d.attachNote(context.convertLocation(expr.symbol.location))
992 << "no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
993 return {};
994 }
995
996 // Handle concatenations.
997 Value visit(const slang::ast::ConcatenationExpression &expr) {
998 SmallVector<Value> operands;
999 for (auto *operand : expr.operands()) {
1000 auto value = context.convertLvalueExpression(*operand);
1001 if (!value)
1002 return {};
1003 operands.push_back(value);
1004 }
1005 return builder.create<moore::ConcatRefOp>(loc, operands);
1006 }
1007
1008 // Handle single bit selections.
1009 Value visit(const slang::ast::ElementSelectExpression &expr) {
1010 auto type = context.convertType(*expr.type);
1011 auto value = context.convertLvalueExpression(expr.value());
1012 if (!type || !value)
1013 return {};
1014 if (auto *constValue = expr.selector().constant) {
1015 assert(!constValue->hasUnknown());
1016 assert(constValue->size() <= 32);
1017
1018 auto lowBit = constValue->integer().as<uint32_t>().value();
1019 return builder.create<moore::ExtractRefOp>(
1020 loc, moore::RefType::get(cast<moore::UnpackedType>(type)), value,
1021 lowBit);
1022 }
1023 auto lowBit = context.convertRvalueExpression(expr.selector());
1024 if (!lowBit)
1025 return {};
1026 return builder.create<moore::DynExtractRefOp>(
1027 loc, moore::RefType::get(cast<moore::UnpackedType>(type)), value,
1028 lowBit);
1029 }
1030
1031 // Handle range bits selections.
1032 Value visit(const slang::ast::RangeSelectExpression &expr) {
1033 auto type = context.convertType(*expr.type);
1034 auto value = context.convertLvalueExpression(expr.value());
1035 if (!type || !value)
1036 return {};
1037
1038 Value dynLowBit;
1039 uint32_t constLowBit;
1040 auto *leftConst = expr.left().constant;
1041 auto *rightConst = expr.right().constant;
1042 if (leftConst) {
1043 assert(!leftConst->hasUnknown());
1044 assert(leftConst->size() <= 32);
1045 }
1046 if (rightConst) {
1047 assert(!rightConst->hasUnknown());
1048 assert(rightConst->size() <= 32);
1049 }
1050
1051 if (expr.getSelectionKind() == slang::ast::RangeSelectionKind::Simple) {
1052 if (leftConst && rightConst) {
1053 // Estimate whether is big endian or little endian.
1054 auto lhs = leftConst->integer().as<uint32_t>().value();
1055 auto rhs = rightConst->integer().as<uint32_t>().value();
1056 constLowBit = lhs < rhs ? lhs : rhs;
1057 } else {
1058 mlir::emitError(loc, "unsupported a variable as the index in the")
1059 << slang::ast::toString(expr.getSelectionKind()) << "kind";
1060 return {};
1061 }
1062 } else if (expr.getSelectionKind() ==
1063 slang::ast::RangeSelectionKind::IndexedDown) {
1064 // IndexedDown: arr[7-:8]. It's equivalent to arr[7:0] or arr[0:7]
1065 // depending on little endian or bit endian. No matter which situation,
1066 // the low bit must be "0".
1067 if (leftConst) {
1068 auto subtrahend = leftConst->integer().as<uint32_t>().value();
1069 auto sliceWidth =
1070 expr.right().constant->integer().as<uint32_t>().value();
1071 constLowBit = subtrahend - sliceWidth - 1;
1072 } else {
1073 auto subtrahend = context.convertRvalueExpression(expr.left());
1074 auto subtrahendType = cast<moore::UnpackedType>(subtrahend.getType());
1075 auto intType = moore::IntType::get(context.getContext(),
1076 subtrahendType.getBitSize().value(),
1077 subtrahendType.getDomain());
1078 auto sliceWidth =
1079 expr.right().constant->integer().as<uint32_t>().value() - 1;
1080 auto minuend =
1081 builder.create<moore::ConstantOp>(loc, intType, sliceWidth);
1082 dynLowBit = builder.create<moore::SubOp>(loc, subtrahend, minuend);
1083 }
1084 } else {
1085 // IndexedUp: arr[0+:8]. "0" is the low bit, "8" is the bits slice width.
1086 if (leftConst)
1087 constLowBit = leftConst->integer().as<uint32_t>().value();
1088 else
1089 dynLowBit = context.convertRvalueExpression(expr.left());
1090 }
1091 if (leftConst && rightConst)
1092 return builder.create<moore::ExtractRefOp>(
1093 loc, moore::RefType::get(cast<moore::UnpackedType>(type)), value,
1094 constLowBit);
1095 return builder.create<moore::DynExtractRefOp>(
1096 loc, moore::RefType::get(cast<moore::UnpackedType>(type)), value,
1097 dynLowBit);
1098 }
1099
1100 Value visit(const slang::ast::StreamingConcatenationExpression &expr) {
1101 SmallVector<Value> operands;
1102 for (auto stream : expr.streams()) {
1103 auto operandLoc = context.convertLocation(stream.operand->sourceRange);
1104 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
1105 mlir::emitError(operandLoc)
1106 << "Moore only support streaming "
1107 "concatenation with fixed size 'with expression'";
1108 return {};
1109 }
1110 Value value;
1111 if (stream.constantWithWidth.has_value()) {
1112 value = context.convertLvalueExpression(*stream.withExpr);
1113 auto type = cast<moore::UnpackedType>(
1114 cast<moore::RefType>(value.getType()).getNestedType());
1115 auto intType = moore::RefType::get(moore::IntType::get(
1116 context.getContext(), type.getBitSize().value(), type.getDomain()));
1117 // Do not care if it's signed, because we will not do expansion.
1118 value = context.materializeConversion(intType, value, false, loc);
1119 } else {
1120 value = context.convertLvalueExpression(*stream.operand);
1121 }
1122
1123 if (!value)
1124 return {};
1125 operands.push_back(value);
1126 }
1127 Value value;
1128 if (operands.size() == 1) {
1129 // There must be at least one element, otherwise slang will report an
1130 // error.
1131 value = operands.front();
1132 } else {
1133 value = builder.create<moore::ConcatRefOp>(loc, operands).getResult();
1134 }
1135
1136 if (expr.sliceSize == 0) {
1137 return value;
1138 }
1139
1140 auto type = cast<moore::IntType>(
1141 cast<moore::RefType>(value.getType()).getNestedType());
1142 SmallVector<Value> slicedOperands;
1143 auto widthSum = type.getWidth();
1144 auto domain = type.getDomain();
1145 auto iterMax = widthSum / expr.sliceSize;
1146 auto remainSize = widthSum % expr.sliceSize;
1147
1148 for (size_t i = 0; i < iterMax; i++) {
1149 auto extractResultType = moore::RefType::get(
1150 moore::IntType::get(context.getContext(), expr.sliceSize, domain));
1151
1152 auto extracted = builder.create<moore::ExtractRefOp>(
1153 loc, extractResultType, value, i * expr.sliceSize);
1154 slicedOperands.push_back(extracted);
1155 }
1156 // Handle other wire
1157 if (remainSize) {
1158 auto extractResultType = moore::RefType::get(
1159 moore::IntType::get(context.getContext(), remainSize, domain));
1160
1161 auto extracted = builder.create<moore::ExtractRefOp>(
1162 loc, extractResultType, value, iterMax * expr.sliceSize);
1163 slicedOperands.push_back(extracted);
1164 }
1165
1166 return builder.create<moore::ConcatRefOp>(loc, slicedOperands);
1167 }
1168
1169 Value visit(const slang::ast::MemberAccessExpression &expr) {
1170 auto type = context.convertType(*expr.type);
1171 auto valueType = expr.value().type;
1172 auto value = context.convertLvalueExpression(expr.value());
1173 if (!type || !value)
1174 return {};
1175 if (valueType->isStruct()) {
1176 return builder.create<moore::StructExtractRefOp>(
1177 loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
1178 builder.getStringAttr(expr.member.name), value);
1179 }
1180 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
1181 return builder.create<moore::UnionExtractRefOp>(
1182 loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
1183 builder.getStringAttr(expr.member.name), value);
1184 }
1185 mlir::emitError(loc, "expression of type ")
1186 << value.getType() << " cannot be accessed";
1187 return {};
1188 }
1189
1190 /// Emit an error for all other expressions.
1191 template <typename T>
1192 Value visit(T &&node) {
1193 return context.convertRvalueExpression(node);
1194 }
1195
1196 Value visitInvalid(const slang::ast::Expression &expr) {
1197 mlir::emitError(loc, "invalid expression");
1198 return {};
1199 }
1200};
1201} // namespace
1202
1203Value Context::convertRvalueExpression(const slang::ast::Expression &expr,
1204 Type requiredType) {
1205 auto loc = convertLocation(expr.sourceRange);
1206 auto value = expr.visit(RvalueExprVisitor(*this, loc));
1207 if (value && requiredType)
1208 value =
1209 materializeConversion(requiredType, value, expr.type->isSigned(), loc);
1210 return value;
1211}
1212
1213Value Context::convertLvalueExpression(const slang::ast::Expression &expr) {
1214 auto loc = convertLocation(expr.sourceRange);
1215 return expr.visit(LvalueExprVisitor(*this, loc));
1216}
1217// NOLINTEND(misc-no-recursion)
1218
1219/// Helper function to convert a value to its "truthy" boolean value.
1220Value Context::convertToBool(Value value) {
1221 if (!value)
1222 return {};
1223 if (auto type = dyn_cast_or_null<moore::IntType>(value.getType()))
1224 if (type.getBitSize() == 1)
1225 return value;
1226 if (auto type = dyn_cast_or_null<moore::UnpackedType>(value.getType()))
1227 return builder.create<moore::BoolCastOp>(value.getLoc(), value);
1228 mlir::emitError(value.getLoc(), "expression of type ")
1229 << value.getType() << " cannot be cast to a boolean";
1230 return {};
1231}
1232
1233/// Materialize a Slang integer literal as a constant op.
1234Value Context::materializeSVInt(const slang::SVInt &svint,
1235 const slang::ast::Type &astType, Location loc) {
1236 auto type = convertType(astType);
1237 if (!type)
1238 return {};
1239
1240 bool typeIsFourValued = false;
1241 if (auto unpackedType = dyn_cast<moore::UnpackedType>(type))
1242 typeIsFourValued = unpackedType.getDomain() == moore::Domain::FourValued;
1243
1244 auto fvint = convertSVIntToFVInt(svint);
1245 auto intType = moore::IntType::get(getContext(), fvint.getBitWidth(),
1246 fvint.hasUnknown() || typeIsFourValued
1249 Value result = builder.create<moore::ConstantOp>(loc, intType, fvint);
1250 if (result.getType() != type)
1251 result = builder.create<moore::ConversionOp>(loc, type, result);
1252 return result;
1253}
1254
1255Value Context::materializeConstant(const slang::ConstantValue &constant,
1256 const slang::ast::Type &type, Location loc) {
1257 if (constant.isInteger())
1258 return materializeSVInt(constant.integer(), type, loc);
1259 return {};
1260}
1261
1262slang::ConstantValue
1263Context::evaluateConstant(const slang::ast::Expression &expr) {
1264 using slang::ast::EvalFlags;
1265 slang::ast::EvalContext evalContext(
1266 compilation, EvalFlags::CacheResults | EvalFlags::SpecparamsAllowed);
1267 return expr.eval(evalContext);
1268}
1269
1270/// Helper function to convert a value to its "truthy" boolean value and
1271/// convert it to the given domain.
1272Value Context::convertToBool(Value value, Domain domain) {
1273 value = convertToBool(value);
1274 if (!value)
1275 return {};
1276 auto type = moore::IntType::get(getContext(), 1, domain);
1277 if (value.getType() == type)
1278 return value;
1279 return builder.create<moore::ConversionOp>(value.getLoc(), type, value);
1280}
1281
1283 if (!value)
1284 return {};
1285 if (isa<moore::IntType>(value.getType()))
1286 return value;
1287
1288 // Some operations in Slang's AST, for example bitwise or `|`, don't cast
1289 // packed struct/array operands to simple bit vectors but directly operate
1290 // on the struct/array. Since the corresponding IR ops operate only on
1291 // simple bit vectors, insert a conversion in this case.
1292 if (auto packed = dyn_cast<moore::PackedType>(value.getType())) {
1293 if (auto bits = packed.getBitSize()) {
1294 auto sbvType =
1295 moore::IntType::get(value.getContext(), *bits, packed.getDomain());
1296 return builder.create<moore::ConversionOp>(value.getLoc(), sbvType,
1297 value);
1298 }
1299 }
1300
1301 mlir::emitError(value.getLoc()) << "expression of type " << value.getType()
1302 << " cannot be cast to a simple bit vector";
1303 return {};
1304}
1305
1306Value Context::materializeConversion(Type type, Value value, bool isSigned,
1307 Location loc) {
1308 if (type == value.getType())
1309 return value;
1310 auto dstPacked = dyn_cast<moore::PackedType>(type);
1311 auto srcPacked = dyn_cast<moore::PackedType>(value.getType());
1312
1313 // Resize the value if needed.
1314 if (dstPacked && srcPacked && dstPacked.getBitSize() &&
1315 srcPacked.getBitSize() &&
1316 *dstPacked.getBitSize() != *srcPacked.getBitSize()) {
1317 auto dstWidth = *dstPacked.getBitSize();
1318 auto srcWidth = *srcPacked.getBitSize();
1319
1320 // Convert the value to a simple bit vector which we can extend or truncate.
1321 auto srcWidthType = moore::IntType::get(value.getContext(), srcWidth,
1322 srcPacked.getDomain());
1323 if (value.getType() != srcWidthType)
1324 value = builder.create<moore::ConversionOp>(value.getLoc(), srcWidthType,
1325 value);
1326
1327 // Create truncation or sign/zero extension ops depending on the source and
1328 // destination width.
1329 auto dstWidthType = moore::IntType::get(value.getContext(), dstWidth,
1330 srcPacked.getDomain());
1331 if (dstWidth < srcWidth) {
1332 value = builder.create<moore::TruncOp>(loc, dstWidthType, value);
1333 } else if (dstWidth > srcWidth) {
1334 if (isSigned)
1335 value = builder.create<moore::SExtOp>(loc, dstWidthType, value);
1336 else
1337 value = builder.create<moore::ZExtOp>(loc, dstWidthType, value);
1338 }
1339 }
1340
1341 if (value.getType() != type)
1342 value = builder.create<moore::ConversionOp>(loc, type, value);
1343 return value;
1344}
1345
1346FailureOr<Value>
1347Context::convertSystemCallArity1(const slang::ast::SystemSubroutine &subroutine,
1348 Location loc, Value value) {
1349 auto systemCallRes =
1350 llvm::StringSwitch<std::function<FailureOr<Value>()>>(subroutine.name)
1351 // Signed and unsigned system functions.
1352 .Case("$signed", [&]() { return value; })
1353 .Case("$unsigned", [&]() { return value; })
1354
1355 // Math functions in SystemVerilog.
1356 .Case("$clog2",
1357 [&]() -> FailureOr<Value> {
1358 value = convertToSimpleBitVector(value);
1359 if (!value)
1360 return failure();
1361 return (Value)builder.create<moore::Clog2BIOp>(loc, value);
1362 })
1363 .Case("$ln",
1364 [&]() -> Value {
1365 return builder.create<moore::LnBIOp>(loc, value);
1366 })
1367 .Case("$log10",
1368 [&]() -> Value {
1369 return builder.create<moore::Log10BIOp>(loc, value);
1370 })
1371 .Case("$sin",
1372 [&]() -> Value {
1373 return builder.create<moore::SinBIOp>(loc, value);
1374 })
1375 .Case("$cos",
1376 [&]() -> Value {
1377 return builder.create<moore::CosBIOp>(loc, value);
1378 })
1379 .Case("$tan",
1380 [&]() -> Value {
1381 return builder.create<moore::TanBIOp>(loc, value);
1382 })
1383 .Case("$exp",
1384 [&]() -> Value {
1385 return builder.create<moore::ExpBIOp>(loc, value);
1386 })
1387 .Case("$sqrt",
1388 [&]() -> Value {
1389 return builder.create<moore::SqrtBIOp>(loc, value);
1390 })
1391 .Case("$floor",
1392 [&]() -> Value {
1393 return builder.create<moore::FloorBIOp>(loc, value);
1394 })
1395 .Case("$ceil",
1396 [&]() -> Value {
1397 return builder.create<moore::CeilBIOp>(loc, value);
1398 })
1399 .Case("$asin",
1400 [&]() -> Value {
1401 return builder.create<moore::AsinBIOp>(loc, value);
1402 })
1403 .Case("$acos",
1404 [&]() -> Value {
1405 return builder.create<moore::AcosBIOp>(loc, value);
1406 })
1407 .Case("$atan",
1408 [&]() -> Value {
1409 return builder.create<moore::AtanBIOp>(loc, value);
1410 })
1411 .Case("$sinh",
1412 [&]() -> Value {
1413 return builder.create<moore::SinhBIOp>(loc, value);
1414 })
1415 .Case("$cosh",
1416 [&]() -> Value {
1417 return builder.create<moore::CoshBIOp>(loc, value);
1418 })
1419 .Case("$tanh",
1420 [&]() -> Value {
1421 return builder.create<moore::TanhBIOp>(loc, value);
1422 })
1423 .Case("$asinh",
1424 [&]() -> Value {
1425 return builder.create<moore::AsinhBIOp>(loc, value);
1426 })
1427 .Case("$acosh",
1428 [&]() -> Value {
1429 return builder.create<moore::AcoshBIOp>(loc, value);
1430 })
1431 .Case("$atanh",
1432 [&]() -> Value {
1433 return builder.create<moore::AtanhBIOp>(loc, value);
1434 })
1435 .Default([&]() -> Value { return {}; });
1436 return systemCallRes();
1437}
assert(baseType &&"element must be base type")
static FVInt convertSVIntToFVInt(const slang::SVInt &svint)
Convert a Slang SVInt to a CIRCT FVInt.
Four-valued arbitrary precision integers.
Definition FVInt.h:37
void info(Twine message)
Definition LSPUtils.cpp:20
Domain
The number of values each bit of a type can assume.
Definition MooreTypes.h:47
@ FourValued
Four-valued types such as logic or integer.
@ TwoValued
Two-valued types such as bit or int.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
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.
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.
slang::ConstantValue evaluateConstant(const slang::ast::Expression &expr)
Evaluate the constant value of an expression.
slang::ast::Compilation & compilation
OpBuilder builder
The builder used to create IR operations.
std::function< void(moore::ReadOp)> rvalueReadCallback
A listener called for every variable or net being read.
Type convertType(const slang::ast::Type &type, LocationAttr loc={})
Convert a slang type into an MLIR type.
Definition Types.cpp:167
Value materializeSVInt(const slang::SVInt &svint, const slang::ast::Type &type, Location loc)
Helper function to materialize an SVInt as an SSA value.
Value convertToBool(Value value)
Helper function to convert a value to its "truthy" boolean value.
Value convertRvalueExpression(const slang::ast::Expression &expr, Type requiredType={})
Value convertToSimpleBitVector(Value value)
Helper function to convert a value to its simple bit vector representation, if it has one.
FailureOr< Value > convertSystemCallArity1(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value)
Convert system function calls only have arity-1.
FunctionLowering * declareFunction(const slang::ast::SubroutineSymbol &subroutine)
Convert a function and its arguments to a function declaration in the IR.
MLIRContext * getContext()
Return the MLIR context.
SmallVector< Value > lvalueStack
A stack of assignment left-hand side values.
Location convertLocation(slang::SourceLocation loc)
Convert a slang SourceLocation into an MLIR Location.