CIRCT 21.0.0git
Loading...
Searching...
No Matches
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 return createBinary<moore::EqOp>(lhs, rhs);
294 case BinaryOperator::Inequality:
295 return createBinary<moore::NeOp>(lhs, rhs);
296 case BinaryOperator::CaseEquality:
297 return createBinary<moore::CaseEqOp>(lhs, rhs);
298 case BinaryOperator::CaseInequality:
299 return createBinary<moore::CaseNeOp>(lhs, rhs);
300 case BinaryOperator::WildcardEquality:
301 return createBinary<moore::WildcardEqOp>(lhs, rhs);
302 case BinaryOperator::WildcardInequality:
303 return createBinary<moore::WildcardNeOp>(lhs, rhs);
304
305 case BinaryOperator::GreaterThanEqual:
306 if (expr.left().type->isSigned())
307 return createBinary<moore::SgeOp>(lhs, rhs);
308 else
309 return createBinary<moore::UgeOp>(lhs, rhs);
310 case BinaryOperator::GreaterThan:
311 if (expr.left().type->isSigned())
312 return createBinary<moore::SgtOp>(lhs, rhs);
313 else
314 return createBinary<moore::UgtOp>(lhs, rhs);
315 case BinaryOperator::LessThanEqual:
316 if (expr.left().type->isSigned())
317 return createBinary<moore::SleOp>(lhs, rhs);
318 else
319 return createBinary<moore::UleOp>(lhs, rhs);
320 case BinaryOperator::LessThan:
321 if (expr.left().type->isSigned())
322 return createBinary<moore::SltOp>(lhs, rhs);
323 else
324 return createBinary<moore::UltOp>(lhs, rhs);
325
326 // See IEEE 1800-2017 ยง 11.4.7 "Logical operators".
327 case BinaryOperator::LogicalAnd: {
328 // TODO: This should short-circuit. Put the RHS code into a separate
329 // block.
330 lhs = context.convertToBool(lhs, domain);
331 if (!lhs)
332 return {};
333 rhs = context.convertToBool(rhs, domain);
334 if (!rhs)
335 return {};
336 return builder.create<moore::AndOp>(loc, lhs, rhs);
337 }
338 case BinaryOperator::LogicalOr: {
339 // TODO: This should short-circuit. Put the RHS code into a separate
340 // block.
341 lhs = context.convertToBool(lhs, domain);
342 if (!lhs)
343 return {};
344 rhs = context.convertToBool(rhs, domain);
345 if (!rhs)
346 return {};
347 return builder.create<moore::OrOp>(loc, lhs, rhs);
348 }
349 case BinaryOperator::LogicalImplication: {
350 // `(lhs -> rhs)` equivalent to `(!lhs || rhs)`.
351 lhs = context.convertToBool(lhs, domain);
352 if (!lhs)
353 return {};
354 rhs = context.convertToBool(rhs, domain);
355 if (!rhs)
356 return {};
357 auto notLHS = builder.create<moore::NotOp>(loc, lhs);
358 return builder.create<moore::OrOp>(loc, notLHS, rhs);
359 }
360 case BinaryOperator::LogicalEquivalence: {
361 // `(lhs <-> rhs)` equivalent to `(lhs && rhs) || (!lhs && !rhs)`.
362 lhs = context.convertToBool(lhs, domain);
363 if (!lhs)
364 return {};
365 rhs = context.convertToBool(rhs, domain);
366 if (!rhs)
367 return {};
368 auto notLHS = builder.create<moore::NotOp>(loc, lhs);
369 auto notRHS = builder.create<moore::NotOp>(loc, rhs);
370 auto both = builder.create<moore::AndOp>(loc, lhs, rhs);
371 auto notBoth = builder.create<moore::AndOp>(loc, notLHS, notRHS);
372 return builder.create<moore::OrOp>(loc, both, notBoth);
373 }
374
375 case BinaryOperator::LogicalShiftLeft:
376 return createBinary<moore::ShlOp>(lhs, rhs);
377 case BinaryOperator::LogicalShiftRight:
378 return createBinary<moore::ShrOp>(lhs, rhs);
379 case BinaryOperator::ArithmeticShiftLeft:
380 return createBinary<moore::ShlOp>(lhs, rhs);
381 case BinaryOperator::ArithmeticShiftRight: {
382 // The `>>>` operator is an arithmetic right shift if the LHS operand is
383 // signed, or a logical right shift if the operand is unsigned.
384 lhs = context.convertToSimpleBitVector(lhs);
385 rhs = context.convertToSimpleBitVector(rhs);
386 if (!lhs || !rhs)
387 return {};
388 if (expr.type->isSigned())
389 return builder.create<moore::AShrOp>(loc, lhs, rhs);
390 return builder.create<moore::ShrOp>(loc, lhs, rhs);
391 }
392 }
393
394 mlir::emitError(loc, "unsupported binary operator");
395 return {};
396 }
397
398 // Handle `'0`, `'1`, `'x`, and `'z` literals.
399 Value visit(const slang::ast::UnbasedUnsizedIntegerLiteral &expr) {
400 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
401 }
402
403 // Handle integer literals.
404 Value visit(const slang::ast::IntegerLiteral &expr) {
405 return context.materializeSVInt(expr.getValue(), *expr.type, loc);
406 }
407
408 // Handle concatenations.
409 Value visit(const slang::ast::ConcatenationExpression &expr) {
410 SmallVector<Value> operands;
411 for (auto *operand : expr.operands()) {
412 auto value = context.convertRvalueExpression(*operand);
413 if (!value)
414 continue;
415 value = context.convertToSimpleBitVector(value);
416 operands.push_back(value);
417 }
418 return builder.create<moore::ConcatOp>(loc, operands);
419 }
420
421 // Handle replications.
422 Value visit(const slang::ast::ReplicationExpression &expr) {
423 auto type = context.convertType(*expr.type);
424 if (isa<moore::VoidType>(type))
425 return {};
426
427 auto value = context.convertRvalueExpression(expr.concat());
428 if (!value)
429 return {};
430 return builder.create<moore::ReplicateOp>(loc, type, value);
431 }
432
433 Value getSelectIndex(Value index, const slang::ConstantRange &range) const {
434 auto indexType = cast<moore::UnpackedType>(index.getType());
435 auto bw = std::max(llvm::Log2_32_Ceil(std::max(std::abs(range.lower()),
436 std::abs(range.upper()))),
437 indexType.getBitSize().value());
438 auto intType =
439 moore::IntType::get(index.getContext(), bw, indexType.getDomain());
440
441 if (range.isLittleEndian()) {
442 if (range.lower() == 0)
443 return index;
444
445 Value newIndex =
446 builder.createOrFold<moore::ConversionOp>(loc, intType, index);
447 Value offset = builder.create<moore::ConstantOp>(
448 loc, intType, range.lower(), /*isSigned = */ range.lower() < 0);
449 return builder.createOrFold<moore::SubOp>(loc, newIndex, offset);
450 }
451
452 if (range.upper() == 0)
453 return builder.createOrFold<moore::NegOp>(loc, index);
454
455 Value newIndex =
456 builder.createOrFold<moore::ConversionOp>(loc, intType, index);
457 Value offset = builder.create<moore::ConstantOp>(
458 loc, intType, range.upper(), /* isSigned = */ range.upper() < 0);
459 return builder.createOrFold<moore::SubOp>(loc, offset, newIndex);
460 }
461
462 // Handle single bit selections.
463 Value visit(const slang::ast::ElementSelectExpression &expr) {
464 auto type = context.convertType(*expr.type);
465 auto value = context.convertRvalueExpression(expr.value());
466 if (!type || !value)
467 return {};
468 auto range = expr.value().type->getFixedRange();
469 if (auto *constValue = expr.selector().constant) {
470 assert(!constValue->hasUnknown());
471 assert(constValue->size() <= 32);
472
473 auto lowBit = constValue->integer().as<uint32_t>().value();
474 return builder.create<moore::ExtractOp>(loc, type, value,
475 range.translateIndex(lowBit));
476 }
477 auto lowBit = context.convertRvalueExpression(expr.selector());
478 if (!lowBit)
479 return {};
480 return builder.create<moore::DynExtractOp>(loc, type, value,
481 getSelectIndex(lowBit, range));
482 }
483
484 // Handle range bits selections.
485 Value visit(const slang::ast::RangeSelectExpression &expr) {
486 auto type = context.convertType(*expr.type);
487 auto value = context.convertRvalueExpression(expr.value());
488 if (!type || !value)
489 return {};
490
491 Value dynLowBit;
492 uint32_t constLowBit;
493 auto *leftConst = expr.left().constant;
494 auto *rightConst = expr.right().constant;
495 if (leftConst) {
496 assert(!leftConst->hasUnknown());
497 assert(leftConst->size() <= 32);
498 }
499 if (rightConst) {
500 assert(!rightConst->hasUnknown());
501 assert(rightConst->size() <= 32);
502 }
503
504 if (expr.getSelectionKind() == slang::ast::RangeSelectionKind::Simple) {
505 if (leftConst && rightConst) {
506 // Estimate whether is big endian or little endian.
507 auto lhs = leftConst->integer().as<uint32_t>().value();
508 auto rhs = rightConst->integer().as<uint32_t>().value();
509 constLowBit = lhs < rhs ? lhs : rhs;
510 } else {
511 mlir::emitError(loc, "unsupported a variable as the index in the")
512 << slang::ast::toString(expr.getSelectionKind()) << "kind";
513 return {};
514 }
515 } else if (expr.getSelectionKind() ==
516 slang::ast::RangeSelectionKind::IndexedDown) {
517 // IndexedDown: arr[7-:8]. It's equivalent to arr[7:0] or arr[0:7]
518 // depending on little endian or bit endian. No matter which situation,
519 // the low bit must be "0".
520 if (leftConst) {
521 auto subtrahend = leftConst->integer().as<uint32_t>().value();
522 auto sliceWidth =
523 expr.right().constant->integer().as<uint32_t>().value();
524 constLowBit = subtrahend - sliceWidth - 1;
525 } else {
526 auto subtrahend = context.convertRvalueExpression(expr.left());
527 auto subtrahendType = cast<moore::UnpackedType>(subtrahend.getType());
528 auto intType = moore::IntType::get(context.getContext(),
529 subtrahendType.getBitSize().value(),
530 subtrahendType.getDomain());
531 auto sliceWidth =
532 expr.right().constant->integer().as<uint32_t>().value() - 1;
533 auto minuend = builder.create<moore::ConstantOp>(
534 loc, intType, sliceWidth, expr.left().type->isSigned());
535 dynLowBit = builder.create<moore::SubOp>(loc, subtrahend, minuend);
536 }
537 } else {
538 // IndexedUp: arr[0+:8]. "0" is the low bit, "8" is the bits slice width.
539 if (leftConst)
540 constLowBit = leftConst->integer().as<uint32_t>().value();
541 else
542 dynLowBit = context.convertRvalueExpression(expr.left());
543 }
544 auto range = expr.value().type->getFixedRange();
545 if (leftConst && rightConst)
546 return builder.create<moore::ExtractOp>(
547 loc, type, value, range.translateIndex(constLowBit));
548 return builder.create<moore::DynExtractOp>(
549 loc, type, value, getSelectIndex(dynLowBit, range));
550 }
551
552 Value visit(const slang::ast::MemberAccessExpression &expr) {
553 auto type = context.convertType(*expr.type);
554 auto valueType = expr.value().type;
555 auto value = context.convertRvalueExpression(expr.value());
556 if (!type || !value)
557 return {};
558 if (valueType->isStruct()) {
559 return builder.create<moore::StructExtractOp>(
560 loc, type, builder.getStringAttr(expr.member.name), value);
561 }
562 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
563 return builder.create<moore::UnionExtractOp>(
564 loc, type, builder.getStringAttr(expr.member.name), value);
565 }
566 mlir::emitError(loc, "expression of type ")
567 << value.getType() << " cannot be accessed";
568 return {};
569 }
570
571 // Handle set membership operator.
572 Value visit(const slang::ast::InsideExpression &expr) {
573 auto lhs = context.convertToSimpleBitVector(
574 context.convertRvalueExpression(expr.left()));
575 if (!lhs)
576 return {};
577 // All conditions for determining whether it is inside.
578 SmallVector<Value> conditions;
579
580 // Traverse open range list.
581 for (const auto *listExpr : expr.rangeList()) {
582 Value cond;
583 // The open range list on the right-hand side of the inside operator is a
584 // comma-separated list of expressions or ranges.
585 if (const auto *openRange =
586 listExpr->as_if<slang::ast::OpenRangeExpression>()) {
587 // Handle ranges.
588 auto lowBound = context.convertToSimpleBitVector(
589 context.convertRvalueExpression(openRange->left()));
590 auto highBound = context.convertToSimpleBitVector(
591 context.convertRvalueExpression(openRange->right()));
592 if (!lowBound || !highBound)
593 return {};
594 Value leftValue, rightValue;
595 // Determine if the expression on the left-hand side is inclusively
596 // within the range.
597 if (openRange->left().type->isSigned() ||
598 expr.left().type->isSigned()) {
599 leftValue = builder.create<moore::SgeOp>(loc, lhs, lowBound);
600 } else {
601 leftValue = builder.create<moore::UgeOp>(loc, lhs, lowBound);
602 }
603 if (openRange->right().type->isSigned() ||
604 expr.left().type->isSigned()) {
605 rightValue = builder.create<moore::SleOp>(loc, lhs, highBound);
606 } else {
607 rightValue = builder.create<moore::UleOp>(loc, lhs, highBound);
608 }
609 cond = builder.create<moore::AndOp>(loc, leftValue, rightValue);
610 } else {
611 // Handle expressions.
612 if (!listExpr->type->isSimpleBitVector()) {
613 if (listExpr->type->isUnpackedArray()) {
614 mlir::emitError(
615 loc, "unpacked arrays in 'inside' expressions not supported");
616 return {};
617 }
618 mlir::emitError(
619 loc, "only simple bit vectors supported in 'inside' expressions");
620 return {};
621 }
622 auto value = context.convertToSimpleBitVector(
623 context.convertRvalueExpression(*listExpr));
624 if (!value)
625 return {};
626 cond = builder.create<moore::WildcardEqOp>(loc, lhs, value);
627 }
628 conditions.push_back(cond);
629 }
630
631 // Calculate the final result by `or` op.
632 auto result = conditions.back();
633 conditions.pop_back();
634 while (!conditions.empty()) {
635 result = builder.create<moore::OrOp>(loc, conditions.back(), result);
636 conditions.pop_back();
637 }
638 return result;
639 }
640
641 // Handle conditional operator `?:`.
642 Value visit(const slang::ast::ConditionalExpression &expr) {
643 auto type = context.convertType(*expr.type);
644
645 // Handle condition.
646 if (expr.conditions.size() > 1) {
647 mlir::emitError(loc)
648 << "unsupported conditional expression with more than one condition";
649 return {};
650 }
651 const auto &cond = expr.conditions[0];
652 if (cond.pattern) {
653 mlir::emitError(loc) << "unsupported conditional expression with pattern";
654 return {};
655 }
656 auto value =
657 context.convertToBool(context.convertRvalueExpression(*cond.expr));
658 if (!value)
659 return {};
660 auto conditionalOp = builder.create<moore::ConditionalOp>(loc, type, value);
661
662 // Create blocks for true region and false region.
663 auto &trueBlock = conditionalOp.getTrueRegion().emplaceBlock();
664 auto &falseBlock = conditionalOp.getFalseRegion().emplaceBlock();
665
666 OpBuilder::InsertionGuard g(builder);
667
668 // Handle left expression.
669 builder.setInsertionPointToStart(&trueBlock);
670 auto trueValue = context.convertRvalueExpression(expr.left(), type);
671 if (!trueValue)
672 return {};
673 builder.create<moore::YieldOp>(loc, trueValue);
674
675 // Handle right expression.
676 builder.setInsertionPointToStart(&falseBlock);
677 auto falseValue = context.convertRvalueExpression(expr.right(), type);
678 if (!falseValue)
679 return {};
680 builder.create<moore::YieldOp>(loc, falseValue);
681
682 return conditionalOp.getResult();
683 }
684
685 /// Handle calls.
686 Value visit(const slang::ast::CallExpression &expr) {
687 // Class method calls are currently not supported.
688 if (expr.thisClass()) {
689 mlir::emitError(loc, "unsupported class method call");
690 return {};
691 }
692
693 // Try to materialize constant values directly.
694 auto constant = context.evaluateConstant(expr);
695 if (auto value = context.materializeConstant(constant, *expr.type, loc))
696 return value;
697
698 return std::visit(
699 [&](auto &subroutine) { return visitCall(expr, subroutine); },
700 expr.subroutine);
701 }
702
703 /// Handle subroutine calls.
704 Value visitCall(const slang::ast::CallExpression &expr,
705 const slang::ast::SubroutineSymbol *subroutine) {
706 auto *lowering = context.declareFunction(*subroutine);
707 if (!lowering)
708 return {};
709
710 // Convert the call arguments. Input arguments are converted to an rvalue.
711 // All other arguments are converted to lvalues and passed into the function
712 // by reference.
713 SmallVector<Value> arguments;
714 for (auto [callArg, declArg] :
715 llvm::zip(expr.arguments(), subroutine->getArguments())) {
716
717 // Unpack the `<expr> = EmptyArgument` pattern emitted by Slang for output
718 // and inout arguments.
719 auto *expr = callArg;
720 if (const auto *assign = expr->as_if<slang::ast::AssignmentExpression>())
721 expr = &assign->left();
722
723 Value value;
724 if (declArg->direction == slang::ast::ArgumentDirection::In)
725 value = context.convertRvalueExpression(*expr);
726 else
727 value = context.convertLvalueExpression(*expr);
728 if (!value)
729 return {};
730 arguments.push_back(value);
731 }
732
733 // Create the call.
734 auto callOp =
735 builder.create<mlir::func::CallOp>(loc, lowering->op, arguments);
736
737 // For calls to void functions we need to have a value to return from this
738 // function. Create a dummy `unrealized_conversion_cast`, which will get
739 // deleted again later on.
740 if (callOp.getNumResults() == 0)
741 return builder
742 .create<mlir::UnrealizedConversionCastOp>(
743 loc, moore::VoidType::get(context.getContext()), ValueRange{})
744 .getResult(0);
745
746 return callOp.getResult(0);
747 }
748
749 /// Handle system calls.
750 Value visitCall(const slang::ast::CallExpression &expr,
751 const slang::ast::CallExpression::SystemCallInfo &info) {
752 const auto &subroutine = *info.subroutine;
753 auto args = expr.arguments();
754
755 if (args.size() == 1) {
756 auto value = context.convertRvalueExpression(*args[0]);
757 if (!value)
758 return {};
759 auto result = context.convertSystemCallArity1(subroutine, loc, value);
760 if (failed(result))
761 return {};
762 if (*result)
763 return *result;
764 }
765
766 mlir::emitError(loc) << "unsupported system call `" << subroutine.name
767 << "`";
768 return {};
769 }
770
771 /// Handle string literals.
772 Value visit(const slang::ast::StringLiteral &expr) {
773 auto type = context.convertType(*expr.type);
774 return builder.create<moore::StringConstantOp>(loc, type, expr.getValue());
775 }
776
777 /// Handle real literals.
778 Value visit(const slang::ast::RealLiteral &expr) {
779 return builder.create<moore::RealLiteralOp>(
780 loc, builder.getF64FloatAttr(expr.getValue()));
781 }
782
783 /// Handle assignment patterns.
784 Value visitAssignmentPattern(
785 const slang::ast::AssignmentPatternExpressionBase &expr,
786 unsigned replCount = 1) {
787 auto type = context.convertType(*expr.type);
788
789 // Convert the individual elements first.
790 auto elementCount = expr.elements().size();
791 SmallVector<Value> elements;
792 elements.reserve(replCount * elementCount);
793 for (auto elementExpr : expr.elements()) {
794 auto value = context.convertRvalueExpression(*elementExpr);
795 if (!value)
796 return {};
797 elements.push_back(value);
798 }
799 for (unsigned replIdx = 1; replIdx < replCount; ++replIdx)
800 for (unsigned elementIdx = 0; elementIdx < elementCount; ++elementIdx)
801 elements.push_back(elements[elementIdx]);
802
803 // Handle integers.
804 if (auto intType = dyn_cast<moore::IntType>(type)) {
805 assert(intType.getWidth() == elements.size());
806 std::reverse(elements.begin(), elements.end());
807 return builder.create<moore::ConcatOp>(loc, intType, elements);
808 }
809
810 // Handle packed structs.
811 if (auto structType = dyn_cast<moore::StructType>(type)) {
812 assert(structType.getMembers().size() == elements.size());
813 return builder.create<moore::StructCreateOp>(loc, structType, elements);
814 }
815
816 // Handle unpacked structs.
817 if (auto structType = dyn_cast<moore::UnpackedStructType>(type)) {
818 assert(structType.getMembers().size() == elements.size());
819 return builder.create<moore::StructCreateOp>(loc, structType, elements);
820 }
821
822 // Handle packed arrays.
823 if (auto arrayType = dyn_cast<moore::ArrayType>(type)) {
824 assert(arrayType.getSize() == elements.size());
825 return builder.create<moore::ArrayCreateOp>(loc, arrayType, elements);
826 }
827
828 // Handle unpacked arrays.
829 if (auto arrayType = dyn_cast<moore::UnpackedArrayType>(type)) {
830 assert(arrayType.getSize() == elements.size());
831 return builder.create<moore::ArrayCreateOp>(loc, arrayType, elements);
832 }
833
834 mlir::emitError(loc) << "unsupported assignment pattern with type " << type;
835 return {};
836 }
837
838 Value visit(const slang::ast::SimpleAssignmentPatternExpression &expr) {
839 return visitAssignmentPattern(expr);
840 }
841
842 Value visit(const slang::ast::StructuredAssignmentPatternExpression &expr) {
843 return visitAssignmentPattern(expr);
844 }
845
846 Value visit(const slang::ast::ReplicatedAssignmentPatternExpression &expr) {
847 auto count =
848 context.evaluateConstant(expr.count()).integer().as<unsigned>();
849 assert(count && "Slang guarantees constant non-zero replication count");
850 return visitAssignmentPattern(expr, *count);
851 }
852
853 Value visit(const slang::ast::StreamingConcatenationExpression &expr) {
854 SmallVector<Value> operands;
855 for (auto stream : expr.streams()) {
856 auto operandLoc = context.convertLocation(stream.operand->sourceRange);
857 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
858 mlir::emitError(operandLoc)
859 << "Moore only support streaming "
860 "concatenation with fixed size 'with expression'";
861 return {};
862 }
863 Value value;
864 if (stream.constantWithWidth.has_value()) {
865 value = context.convertRvalueExpression(*stream.withExpr);
866 auto type = cast<moore::UnpackedType>(value.getType());
867 auto intType = moore::IntType::get(
868 context.getContext(), type.getBitSize().value(), type.getDomain());
869 // Do not care if it's signed, because we will not do expansion.
870 value = context.materializeConversion(intType, value, false, loc);
871 } else {
872 value = context.convertRvalueExpression(*stream.operand);
873 }
874
875 if (!value)
876 return {};
877 value = context.convertToSimpleBitVector(value);
878 if (!value) {
879 return {};
880 }
881 operands.push_back(value);
882 }
883 Value value;
884
885 if (operands.size() == 1) {
886 // There must be at least one element, otherwise slang will report an
887 // error.
888 value = operands.front();
889 } else {
890 value = builder.create<moore::ConcatOp>(loc, operands).getResult();
891 }
892
893 if (expr.sliceSize == 0) {
894 return value;
895 }
896
897 auto type = cast<moore::IntType>(value.getType());
898 SmallVector<Value> slicedOperands;
899 auto iterMax = type.getWidth() / expr.sliceSize;
900 auto remainSize = type.getWidth() % expr.sliceSize;
901
902 for (size_t i = 0; i < iterMax; i++) {
903 auto extractResultType = moore::IntType::get(
904 context.getContext(), expr.sliceSize, type.getDomain());
905
906 auto extracted = builder.create<moore::ExtractOp>(
907 loc, extractResultType, value, i * expr.sliceSize);
908 slicedOperands.push_back(extracted);
909 }
910 // Handle other wire
911 if (remainSize) {
912 auto extractResultType = moore::IntType::get(
913 context.getContext(), remainSize, type.getDomain());
914
915 auto extracted = builder.create<moore::ExtractOp>(
916 loc, extractResultType, value, iterMax * expr.sliceSize);
917 slicedOperands.push_back(extracted);
918 }
919
920 return builder.create<moore::ConcatOp>(loc, slicedOperands);
921 }
922
923 /// Emit an error for all other expressions.
924 template <typename T>
925 Value visit(T &&node) {
926 mlir::emitError(loc, "unsupported expression: ")
927 << slang::ast::toString(node.kind);
928 return {};
929 }
930
931 Value visitInvalid(const slang::ast::Expression &expr) {
932 mlir::emitError(loc, "invalid expression");
933 return {};
934 }
935};
936} // namespace
937
938namespace {
939struct LvalueExprVisitor {
940 Context &context;
941 Location loc;
942 OpBuilder &builder;
943
944 LvalueExprVisitor(Context &context, Location loc)
945 : context(context), loc(loc), builder(context.builder) {}
946
947 // Handle named values, such as references to declared variables.
948 Value visit(const slang::ast::NamedValueExpression &expr) {
949 if (auto value = context.valueSymbols.lookup(&expr.symbol))
950 return value;
951 auto d = mlir::emitError(loc, "unknown name `") << expr.symbol.name << "`";
952 d.attachNote(context.convertLocation(expr.symbol.location))
953 << "no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
954 return {};
955 }
956
957 // Handle hierarchical values, such as `Top.sub.var = x`.
958 Value visit(const slang::ast::HierarchicalValueExpression &expr) {
959 if (auto value = context.valueSymbols.lookup(&expr.symbol))
960 return value;
961
962 // Emit an error for those hierarchical values not recorded in the
963 // `valueSymbols`.
964 auto d = mlir::emitError(loc, "unknown hierarchical name `")
965 << expr.symbol.name << "`";
966 d.attachNote(context.convertLocation(expr.symbol.location))
967 << "no lvalue generated for " << slang::ast::toString(expr.symbol.kind);
968 return {};
969 }
970
971 // Handle concatenations.
972 Value visit(const slang::ast::ConcatenationExpression &expr) {
973 SmallVector<Value> operands;
974 for (auto *operand : expr.operands()) {
975 auto value = context.convertLvalueExpression(*operand);
976 if (!value)
977 continue;
978 operands.push_back(value);
979 }
980 return builder.create<moore::ConcatRefOp>(loc, operands);
981 }
982
983 // Handle single bit selections.
984 Value visit(const slang::ast::ElementSelectExpression &expr) {
985 auto type = context.convertType(*expr.type);
986 auto value = context.convertLvalueExpression(expr.value());
987 if (!type || !value)
988 return {};
989 if (auto *constValue = expr.selector().constant) {
990 assert(!constValue->hasUnknown());
991 assert(constValue->size() <= 32);
992
993 auto lowBit = constValue->integer().as<uint32_t>().value();
994 return builder.create<moore::ExtractRefOp>(
995 loc, moore::RefType::get(cast<moore::UnpackedType>(type)), value,
996 lowBit);
997 }
998 auto lowBit = context.convertRvalueExpression(expr.selector());
999 if (!lowBit)
1000 return {};
1001 return builder.create<moore::DynExtractRefOp>(
1002 loc, moore::RefType::get(cast<moore::UnpackedType>(type)), value,
1003 lowBit);
1004 }
1005
1006 // Handle range bits selections.
1007 Value visit(const slang::ast::RangeSelectExpression &expr) {
1008 auto type = context.convertType(*expr.type);
1009 auto value = context.convertLvalueExpression(expr.value());
1010 if (!type || !value)
1011 return {};
1012
1013 Value dynLowBit;
1014 uint32_t constLowBit;
1015 auto *leftConst = expr.left().constant;
1016 auto *rightConst = expr.right().constant;
1017 if (leftConst) {
1018 assert(!leftConst->hasUnknown());
1019 assert(leftConst->size() <= 32);
1020 }
1021 if (rightConst) {
1022 assert(!rightConst->hasUnknown());
1023 assert(rightConst->size() <= 32);
1024 }
1025
1026 if (expr.getSelectionKind() == slang::ast::RangeSelectionKind::Simple) {
1027 if (leftConst && rightConst) {
1028 // Estimate whether is big endian or little endian.
1029 auto lhs = leftConst->integer().as<uint32_t>().value();
1030 auto rhs = rightConst->integer().as<uint32_t>().value();
1031 constLowBit = lhs < rhs ? lhs : rhs;
1032 } else {
1033 mlir::emitError(loc, "unsupported a variable as the index in the")
1034 << slang::ast::toString(expr.getSelectionKind()) << "kind";
1035 return {};
1036 }
1037 } else if (expr.getSelectionKind() ==
1038 slang::ast::RangeSelectionKind::IndexedDown) {
1039 // IndexedDown: arr[7-:8]. It's equivalent to arr[7:0] or arr[0:7]
1040 // depending on little endian or bit endian. No matter which situation,
1041 // the low bit must be "0".
1042 if (leftConst) {
1043 auto subtrahend = leftConst->integer().as<uint32_t>().value();
1044 auto sliceWidth =
1045 expr.right().constant->integer().as<uint32_t>().value();
1046 constLowBit = subtrahend - sliceWidth - 1;
1047 } else {
1048 auto subtrahend = context.convertRvalueExpression(expr.left());
1049 auto subtrahendType = cast<moore::UnpackedType>(subtrahend.getType());
1050 auto intType = moore::IntType::get(context.getContext(),
1051 subtrahendType.getBitSize().value(),
1052 subtrahendType.getDomain());
1053 auto sliceWidth =
1054 expr.right().constant->integer().as<uint32_t>().value() - 1;
1055 auto minuend =
1056 builder.create<moore::ConstantOp>(loc, intType, sliceWidth);
1057 dynLowBit = builder.create<moore::SubOp>(loc, subtrahend, minuend);
1058 }
1059 } else {
1060 // IndexedUp: arr[0+:8]. "0" is the low bit, "8" is the bits slice width.
1061 if (leftConst)
1062 constLowBit = leftConst->integer().as<uint32_t>().value();
1063 else
1064 dynLowBit = context.convertRvalueExpression(expr.left());
1065 }
1066 if (leftConst && rightConst)
1067 return builder.create<moore::ExtractRefOp>(
1068 loc, moore::RefType::get(cast<moore::UnpackedType>(type)), value,
1069 constLowBit);
1070 return builder.create<moore::DynExtractRefOp>(
1071 loc, moore::RefType::get(cast<moore::UnpackedType>(type)), value,
1072 dynLowBit);
1073 }
1074
1075 Value visit(const slang::ast::StreamingConcatenationExpression &expr) {
1076 SmallVector<Value> operands;
1077 for (auto stream : expr.streams()) {
1078 auto operandLoc = context.convertLocation(stream.operand->sourceRange);
1079 if (!stream.constantWithWidth.has_value() && stream.withExpr) {
1080 mlir::emitError(operandLoc)
1081 << "Moore only support streaming "
1082 "concatenation with fixed size 'with expression'";
1083 return {};
1084 }
1085 Value value;
1086 if (stream.constantWithWidth.has_value()) {
1087 value = context.convertLvalueExpression(*stream.withExpr);
1088 auto type = cast<moore::UnpackedType>(
1089 cast<moore::RefType>(value.getType()).getNestedType());
1090 auto intType = moore::RefType::get(moore::IntType::get(
1091 context.getContext(), type.getBitSize().value(), type.getDomain()));
1092 // Do not care if it's signed, because we will not do expansion.
1093 value = context.materializeConversion(intType, value, false, loc);
1094 } else {
1095 value = context.convertLvalueExpression(*stream.operand);
1096 }
1097
1098 if (!value)
1099 return {};
1100 operands.push_back(value);
1101 }
1102 Value value;
1103 if (operands.size() == 1) {
1104 // There must be at least one element, otherwise slang will report an
1105 // error.
1106 value = operands.front();
1107 } else {
1108 value = builder.create<moore::ConcatRefOp>(loc, operands).getResult();
1109 }
1110
1111 if (expr.sliceSize == 0) {
1112 return value;
1113 }
1114
1115 auto type = cast<moore::IntType>(
1116 cast<moore::RefType>(value.getType()).getNestedType());
1117 SmallVector<Value> slicedOperands;
1118 auto widthSum = type.getWidth();
1119 auto domain = type.getDomain();
1120 auto iterMax = widthSum / expr.sliceSize;
1121 auto remainSize = widthSum % expr.sliceSize;
1122
1123 for (size_t i = 0; i < iterMax; i++) {
1124 auto extractResultType = moore::RefType::get(
1125 moore::IntType::get(context.getContext(), expr.sliceSize, domain));
1126
1127 auto extracted = builder.create<moore::ExtractRefOp>(
1128 loc, extractResultType, value, i * expr.sliceSize);
1129 slicedOperands.push_back(extracted);
1130 }
1131 // Handle other wire
1132 if (remainSize) {
1133 auto extractResultType = moore::RefType::get(
1134 moore::IntType::get(context.getContext(), remainSize, domain));
1135
1136 auto extracted = builder.create<moore::ExtractRefOp>(
1137 loc, extractResultType, value, iterMax * expr.sliceSize);
1138 slicedOperands.push_back(extracted);
1139 }
1140
1141 return builder.create<moore::ConcatRefOp>(loc, slicedOperands);
1142 }
1143
1144 Value visit(const slang::ast::MemberAccessExpression &expr) {
1145 auto type = context.convertType(*expr.type);
1146 auto valueType = expr.value().type;
1147 auto value = context.convertLvalueExpression(expr.value());
1148 if (!type || !value)
1149 return {};
1150 if (valueType->isStruct()) {
1151 return builder.create<moore::StructExtractRefOp>(
1152 loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
1153 builder.getStringAttr(expr.member.name), value);
1154 }
1155 if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
1156 return builder.create<moore::UnionExtractRefOp>(
1157 loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
1158 builder.getStringAttr(expr.member.name), value);
1159 }
1160 mlir::emitError(loc, "expression of type ")
1161 << value.getType() << " cannot be accessed";
1162 return {};
1163 }
1164
1165 /// Emit an error for all other expressions.
1166 template <typename T>
1167 Value visit(T &&node) {
1168 return context.convertRvalueExpression(node);
1169 }
1170
1171 Value visitInvalid(const slang::ast::Expression &expr) {
1172 mlir::emitError(loc, "invalid expression");
1173 return {};
1174 }
1175};
1176} // namespace
1177
1178Value Context::convertRvalueExpression(const slang::ast::Expression &expr,
1179 Type requiredType) {
1180 auto loc = convertLocation(expr.sourceRange);
1181 auto value = expr.visit(RvalueExprVisitor(*this, loc));
1182 if (value && requiredType)
1183 value =
1184 materializeConversion(requiredType, value, expr.type->isSigned(), loc);
1185 return value;
1186}
1187
1188Value Context::convertLvalueExpression(const slang::ast::Expression &expr) {
1189 auto loc = convertLocation(expr.sourceRange);
1190 return expr.visit(LvalueExprVisitor(*this, loc));
1191}
1192// NOLINTEND(misc-no-recursion)
1193
1194/// Helper function to convert a value to its "truthy" boolean value.
1195Value Context::convertToBool(Value value) {
1196 if (!value)
1197 return {};
1198 if (auto type = dyn_cast_or_null<moore::IntType>(value.getType()))
1199 if (type.getBitSize() == 1)
1200 return value;
1201 if (auto type = dyn_cast_or_null<moore::UnpackedType>(value.getType()))
1202 return builder.create<moore::BoolCastOp>(value.getLoc(), value);
1203 mlir::emitError(value.getLoc(), "expression of type ")
1204 << value.getType() << " cannot be cast to a boolean";
1205 return {};
1206}
1207
1208/// Materialize a Slang integer literal as a constant op.
1209Value Context::materializeSVInt(const slang::SVInt &svint,
1210 const slang::ast::Type &astType, Location loc) {
1211 auto type = convertType(astType);
1212 if (!type)
1213 return {};
1214
1215 bool typeIsFourValued = false;
1216 if (auto unpackedType = dyn_cast<moore::UnpackedType>(type))
1217 typeIsFourValued = unpackedType.getDomain() == moore::Domain::FourValued;
1218
1219 auto fvint = convertSVIntToFVInt(svint);
1220 auto intType = moore::IntType::get(getContext(), fvint.getBitWidth(),
1221 fvint.hasUnknown() || typeIsFourValued
1224 Value result = builder.create<moore::ConstantOp>(loc, intType, fvint);
1225 if (result.getType() != type)
1226 result = builder.create<moore::ConversionOp>(loc, type, result);
1227 return result;
1228}
1229
1230Value Context::materializeConstant(const slang::ConstantValue &constant,
1231 const slang::ast::Type &type, Location loc) {
1232 if (constant.isInteger())
1233 return materializeSVInt(constant.integer(), type, loc);
1234 return {};
1235}
1236
1237slang::ConstantValue
1238Context::evaluateConstant(const slang::ast::Expression &expr) {
1239 using slang::ast::EvalFlags;
1240 slang::ast::EvalContext evalContext(
1241 compilation, EvalFlags::CacheResults | EvalFlags::SpecparamsAllowed);
1242 return expr.eval(evalContext);
1243}
1244
1245/// Helper function to convert a value to its "truthy" boolean value and
1246/// convert it to the given domain.
1247Value Context::convertToBool(Value value, Domain domain) {
1248 value = convertToBool(value);
1249 if (!value)
1250 return {};
1251 auto type = moore::IntType::get(getContext(), 1, domain);
1252 if (value.getType() == type)
1253 return value;
1254 return builder.create<moore::ConversionOp>(value.getLoc(), type, value);
1255}
1256
1258 if (!value)
1259 return {};
1260 if (isa<moore::IntType>(value.getType()))
1261 return value;
1262
1263 // Some operations in Slang's AST, for example bitwise or `|`, don't cast
1264 // packed struct/array operands to simple bit vectors but directly operate
1265 // on the struct/array. Since the corresponding IR ops operate only on
1266 // simple bit vectors, insert a conversion in this case.
1267 if (auto packed = dyn_cast<moore::PackedType>(value.getType())) {
1268 if (auto bits = packed.getBitSize()) {
1269 auto sbvType =
1270 moore::IntType::get(value.getContext(), *bits, packed.getDomain());
1271 return builder.create<moore::ConversionOp>(value.getLoc(), sbvType,
1272 value);
1273 }
1274 }
1275
1276 mlir::emitError(value.getLoc()) << "expression of type " << value.getType()
1277 << " cannot be cast to a simple bit vector";
1278 return {};
1279}
1280
1281Value Context::materializeConversion(Type type, Value value, bool isSigned,
1282 Location loc) {
1283 if (type == value.getType())
1284 return value;
1285 auto dstPacked = dyn_cast<moore::PackedType>(type);
1286 auto srcPacked = dyn_cast<moore::PackedType>(value.getType());
1287
1288 // Resize the value if needed.
1289 if (dstPacked && srcPacked && dstPacked.getBitSize() &&
1290 srcPacked.getBitSize() &&
1291 *dstPacked.getBitSize() != *srcPacked.getBitSize()) {
1292 auto dstWidth = *dstPacked.getBitSize();
1293 auto srcWidth = *srcPacked.getBitSize();
1294
1295 // Convert the value to a simple bit vector which we can extend or truncate.
1296 auto srcWidthType = moore::IntType::get(value.getContext(), srcWidth,
1297 srcPacked.getDomain());
1298 if (value.getType() != srcWidthType)
1299 value = builder.create<moore::ConversionOp>(value.getLoc(), srcWidthType,
1300 value);
1301
1302 // Create truncation or sign/zero extension ops depending on the source and
1303 // destination width.
1304 auto dstWidthType = moore::IntType::get(value.getContext(), dstWidth,
1305 srcPacked.getDomain());
1306 if (dstWidth < srcWidth) {
1307 value = builder.create<moore::TruncOp>(loc, dstWidthType, value);
1308 } else if (dstWidth > srcWidth) {
1309 if (isSigned)
1310 value = builder.create<moore::SExtOp>(loc, dstWidthType, value);
1311 else
1312 value = builder.create<moore::ZExtOp>(loc, dstWidthType, value);
1313 }
1314 }
1315
1316 if (value.getType() != type)
1317 value = builder.create<moore::ConversionOp>(loc, type, value);
1318 return value;
1319}
1320
1321FailureOr<Value>
1322Context::convertSystemCallArity1(const slang::ast::SystemSubroutine &subroutine,
1323 Location loc, Value value) {
1324 auto systemCallRes =
1325 llvm::StringSwitch<std::function<FailureOr<Value>()>>(subroutine.name)
1326 // Signed and unsigned system functions.
1327 .Case("$signed", [&]() { return value; })
1328 .Case("$unsigned", [&]() { return value; })
1329
1330 // Math functions in SystemVerilog.
1331 .Case("$clog2",
1332 [&]() -> FailureOr<Value> {
1333 value = convertToSimpleBitVector(value);
1334 if (!value)
1335 return failure();
1336 return (Value)builder.create<moore::Clog2BIOp>(loc, value);
1337 })
1338 .Case("$ln",
1339 [&]() -> Value {
1340 return builder.create<moore::LnBIOp>(loc, value);
1341 })
1342 .Case("$log10",
1343 [&]() -> Value {
1344 return builder.create<moore::Log10BIOp>(loc, value);
1345 })
1346 .Case("$sin",
1347 [&]() -> Value {
1348 return builder.create<moore::SinBIOp>(loc, value);
1349 })
1350 .Case("$cos",
1351 [&]() -> Value {
1352 return builder.create<moore::CosBIOp>(loc, value);
1353 })
1354 .Case("$tan",
1355 [&]() -> Value {
1356 return builder.create<moore::TanBIOp>(loc, value);
1357 })
1358 .Case("$exp",
1359 [&]() -> Value {
1360 return builder.create<moore::ExpBIOp>(loc, value);
1361 })
1362 .Case("$sqrt",
1363 [&]() -> Value {
1364 return builder.create<moore::SqrtBIOp>(loc, value);
1365 })
1366 .Case("$floor",
1367 [&]() -> Value {
1368 return builder.create<moore::FloorBIOp>(loc, value);
1369 })
1370 .Case("$ceil",
1371 [&]() -> Value {
1372 return builder.create<moore::CeilBIOp>(loc, value);
1373 })
1374 .Case("$asin",
1375 [&]() -> Value {
1376 return builder.create<moore::AsinBIOp>(loc, value);
1377 })
1378 .Case("$acos",
1379 [&]() -> Value {
1380 return builder.create<moore::AcosBIOp>(loc, value);
1381 })
1382 .Case("$atan",
1383 [&]() -> Value {
1384 return builder.create<moore::AtanBIOp>(loc, value);
1385 })
1386 .Case("$sinh",
1387 [&]() -> Value {
1388 return builder.create<moore::SinhBIOp>(loc, value);
1389 })
1390 .Case("$cosh",
1391 [&]() -> Value {
1392 return builder.create<moore::CoshBIOp>(loc, value);
1393 })
1394 .Case("$tanh",
1395 [&]() -> Value {
1396 return builder.create<moore::TanhBIOp>(loc, value);
1397 })
1398 .Case("$asinh",
1399 [&]() -> Value {
1400 return builder.create<moore::AsinhBIOp>(loc, value);
1401 })
1402 .Case("$acosh",
1403 [&]() -> Value {
1404 return builder.create<moore::AcoshBIOp>(loc, value);
1405 })
1406 .Case("$atanh",
1407 [&]() -> Value {
1408 return builder.create<moore::AtanhBIOp>(loc, value);
1409 })
1410 .Default([&]() -> Value { return {}; });
1411 return systemCallRes();
1412}
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.