How to convert a SystemVerilog interface to individual ports - fpga

I am looking into introducing interfaces into a code base that currently aren’t using interfaces.
For this I need to have adapters to turn the interface into individual signals again.
I was thinking of doing it like this:
interface foo();
logic a;
logic b;
logic c;
modport source(input a, c,
output b);
modport sink(input b, c,
output a);
endinterface // foo
module foo_source_to_ports
(
foo f,
input logic a,
input logic c,
output logic b);
assign f.a = a;
assign f.c = c;
assign b = f.b;
endmodule
module foo_ports_to_source
(
foo f,
output logic a,
output logic c,
input logic b);
assign a = f.a;
assign c = f.c;
assign f.b = b;
endmodule
module foo_sink_to_ports
(
foo f,
input logic b,
input logic c,
output logic a);
assign f.b = b;
assign f.c = c;
assign a = f.a;
endmodule
module foo_ports_to_sink
(
foo f,
output logic b,
output logic c,
input logic a);
assign b = f.b;
assign c = f.c;
assign f.a = a;
endmodule
I was wondering if someone knew of a better way of doing this. I guess I am not the only one with this problem.

I think you're overthinking it. Why don't you just instantiate your interface inside the RTL and connect its signals to the other signals directly using assign statements?
Even if you use an adapter that does these assigns for you you still have to specify all of the port connections for it at its instantiation, aside from the list of assigns that it contains. You'd have a lot of redundant information (hence a lot of places to edit in your code should changes be necessary).

This code looks very strange because:
The module port lists have both an interface and duplicate logic ports.
The interface ports do not have a modport indicating their role.
You're not showing how any of these modules would be instantiated and interconnected.
I know that vcs supports interface ports in the RTL, however mvsim does not.
This is what I would expect:
module source (
foo.source f
)
// Use interface
endmodule
module sink(
foo.sink f
);
module top();
foo f;
source u_source(.f(f));
sink u_sink(.f(f));
endmodule
Personally, I think that this is a terrific way to write the RTL and makes for much cleaner, more maintainable code. However, EDA support seems to be spotty.

Related

C++ std::move assignment from scratch - low maintainability

I like the new std::move but afraid that it reduces my program maintainability.
To my knowledge, if I create move constructor or move assignment operator=(), I have to write it from scratch. That is where the problem begins.
Code version 1
Here is a tiny class:-
class B{
M shouldBeMove; //if it is copied, it is still correct (but prefer move)
C shouldBeCopy; //can be copied or moved, both are equal and ok
//wow, I don't even have to write this line for operator=():-
// this->shouldBeCopy = that.shouldBeCopy
}
B b1;
B b2=b1;
Currently, B b2=b1 will copy both M and C. It is ok.
Code version 2
Now I want to use the power of std::move :-
class B{
M shouldBeMove; //now, the program is refactored that it must be moved
// M now has "M& operator=(M&& that)"
C shouldBeCopy;
B& operator=(B&& that){
this->shouldBeMove=std::move(that.shouldBeMove);
this->shouldBeCopy=that.shouldBeCopy; //<-- a bit tedious (1#)
// ... imagine that there are 10 variables to be copied ...
}
}
B b1;
B b2=std::move(b1);
It is still ok, but a bit tedious. (1#)
Code version 3
Then one month in the future, I may want to add a new field e.g. C shouldBeCopy2 to B, I also have to add a line into operator= :-
B& operator=(B&& that){
this->shouldBeMove=std::move(that.shouldBeMove);
this->shouldBeCopy=that.shouldBeCopy;
this->shouldBeCopy2=that.shouldBeCopy2; //<--- new line
}
I think I am a type that may forget to add that line. (2#)
Question:
1#. How to make it not tedious?
2#. How to foolproof my mistake?
You should follow rule of zero and let compiler generate the constructors and assign operators for you.
But when you need to implement a moveable type, make sure you implement both move assignment operator (T& operator=(T&&)) and move constructor (T(T&&)). Please follow rule of five and ensure the class have proper copy constructor/move constructor/copy assignment operator/move assignment operator/destructor
https://ideone.com/UVZNOM
#include <iostream>
using namespace std;
class M{
public: int database=0;
M& operator=(M&& other){
this->database=other.database;
other.database=0;
return *this;
}
M(M &&other) {
*this = std::move(other);
}
M (M& m)=default;
M ()=default;
~M() { /* free db */ }
};
class B{ // As rule of zero, you don't need to implement constructors and assignment operators
public: M shouldMove;
};
int main() {
B b;
b.shouldMove.database=5;
B b2=std::move(b);
std::cout<< b.shouldMove.database <<std::endl;
std::cout<< b2.shouldMove.database <<std::endl;
return 0;
}

Reimplement insert iterator to make easy work with "related types" to the one stored on the container

We have the following lightweight classes:
struct A {};
struct B { A get_a() const { return /* sth */; } };
And let's suppose I have an ordered container of type A, and I want to copy objects from another container of type B to it:
std::copy(b_cont.begin(), b_cont.end(),
std::make_insert_iterator(a_cont, a_cont.end())
);
Of course, it won't work because a_cont and b_cont have different types, and classes A and B don't provide conversion operators. The most obvious solution is to call the function get_a for each B object on the range [b_cont.begin(), b_cont.end()), so, lets write a custom insert iterator:
template<template<class...> class container>
struct ba_insert_iterator : public std::insert_iterator<container<A> >
{
using std::insert_iterator<container<A>>::insert_iterator;
ba_insert_iterator& operator=(B const& o)
{
std::insert_iterator<container<A>>::operator=(o.get_a());
return *this;
}
};
template<template<class...> class container>
ba_insert_iterator<container> make_a_inserter(container<A>& c)
{ return ba_insert_iterator<container>(c, c.end()); }
Just an iterator that receives an object of type B, instead of another one of type A, and a function to create them easily. But when instantiating the template:
std::copy(b_cont.begin(), b_cont.end(), make_a_inserter(a_cont));
It says that it doesn't find the operator= because the second operand is an A object (as expected), but the first operand is an std::insert_iterator<std::set<A> >!!, so the compiler is "casting" the iterator to its clase base, which of course lacks of a method for receiving B objects to insert.
Why does it happen?
You inherited operator* (and operator++ too, for that matter) from insert_iterator.
And those return insert_iterator&, not ba_insert_iterator&.
For obvious reasons, std::copy dereferences the output iterator before assigning to it.

Proper ways to initialize member variables with identical names as the parameters

I got a class that looks like this
class Rational{
public:
Rational(int p = 0, int q = 1) : p(p), q(q){};
private:
int p;
int q;
};
My question is about the initialization syntax where member variables and constructor parameters has identical names.
I now know it is legal to do so, but my question is:
If I want do have "clean", easy to grasp code I wonder if I can do as one normally would do in java:
//Legal Java Code
this.q = q;
this.p = p;
//Is any of these legal C++ code (if so, which one)?
this.q(q);
this.p(p);
//or
this->q(q);
this->p(p);
Even though I haven't tested it, and I can test it, I still want to know the C++ conventions of doing this.
In C++, you have to say:
this -> q = q;
this -> p = p;
or equivalently
(*this).q = q;
(*this).p = p;
But I think the member initializer list syntax
Rational(int p = 0, int q = 1) : p(p), q(q){}
is cleaner (note the lack of a semicolon!) Why don't you like it?

how to convert expression to string in z3

There are two expr_vector A,B, I am trying to compare the elements in them using
if(strcmp(A[i].ToString(),B[i].ToString()) == 1)
And the error ‘class z3::expr’ has no member named ‘ToString’,which is found on override string ToString ( ) .
Or could you please tell me how to compare the variables in the two expr_vector? Such as the variable q1 is in the vector<expr>A and B respectively.
The link you provided in your question is for the Z3 C# (.Net) API, and your question suggests you are using the C++ API (expr_vector is a class of the Z3 C++ API).
To test whether a and b are equal, where a and b are z3::expr, we should use eq(a, b).
The eq function is just a wrapper for Z3_is_eq_ast, and is defined at z3++.h
friend bool eq(ast const & a, ast const & b) { return Z3_is_eq_ast(a.ctx(), a, b) != 0; }

Class set method in Haskell using State-Monad

I've recently had a look at Haskell's Monad - State. I've been able to create functions that operate with this Monad, but I'm trying to encapsulate the behavior into a class, basically I'm trying to replicate in Haskell something like this:
class A {
public:
int x;
void setX(int newX) {
x = newX;
}
void getX() {
return x;
}
}
I would be very grateful if anyone can help with this. Thanks!
I would start off by noting that Haskell, to say the least, does not encourage traditional OO-style development; instead, it has features and characteristics that lend themselves well to the sort of 'pure functional' manipulation that you won't really find in many other languages; the short on this is that trying to 'bring over' concepts from other (traditional languages) can often be a very bad idea.
but I'm trying to encapsulate the behavior into a class
Hence, my first major question that comes to mind is why? Surely you must want to do something with this (traditional OO concept of a) class?
If an approximate answer to this question is: "I'd like to model some sort of data construct", then you'd be better off working with something like
data A = A { xval :: Int }
> let obj1 = A 5
> xval obj1
5
> let obj2 = obj1 { xval = 10 }
> xval obj2
10
Which demonstrates pure, immutable data structures, along with 'getter' functions and destructive updates (utilizing record syntax). This way, you'd do whatever work you need to do as some combination of functions mapping these 'data constructs' to new data constructs, as appropriate.
Now, if you absolutely needed some sort of model of State (and indeed, answering this question requires a bit of experience in knowing exactly what local versus global state is), only then would you delve into using the State Monad, with something like:
module StateGame where
import Control.Monad.State
-- Example use of State monad
-- Passes a string of dictionary {a,b,c}
-- Game is to produce a number from the string.
-- By default the game is off, a C toggles the
-- game on and off. A 'a' gives +1 and a b gives -1.
-- E.g
-- 'ab' = 0
-- 'ca' = 1
-- 'cabca' = 0
-- State = game is on or off & current score
-- = (Bool, Int)
type GameValue = Int
type GameState = (Bool, Int)
playGame :: String -> State GameState GameValue
playGame [] = do
(_, score) <- get
return score
playGame (x:xs) = do
(on, score) <- get
case x of
'a' | on -> put (on, score + 1)
'b' | on -> put (on, score - 1)
'c' -> put (not on, score)
_ -> put (on, score)
playGame xs
startState = (False, 0)
main = print $ evalState (playGame "abcaaacbbcabbab") startState
(shamelessly lifted from this tutorial). Note the use of the analogous 'pure immutable data structures' within the context of a state monad, in addition to 'put' and 'get' monadic functions, which facilitate access to the state contained within the State Monad.
Ultimately, I'd suggest you ask yourself: what is it that you really want to accomplish with this model of an (OO) class? Haskell is not your typical OO-language, and trying to map concepts over 1-to-1 will only frustrate you in the short (and possibly long) term. This should be a standard mantra, but I'd highly recommend learning from the book Real World Haskell, where the authors are able to delve into far more detailed 'motivation' for picking any one tool or abstraction over another. If you were adamant, you could model traditional OO constructs in Haskell, but I wouldn't suggest going about doing this - unless you have a really good reason for doing so.
It takes a bit of permuting to transform imperative code into a purely functional context.
A setter mutates an object. We're not allowed to do that directly in Haskell because of laziness and purity.
Perhaps, if we transcribe the State monad to another language it'll be more apparent. Your code is in C++, but because I at least want garbage collection I'll use java here.
Since Java never got around to defining anonymous functions, first, we'll define an interface for pure functions.
public interface Function<A,B> {
B apply(A a);
}
Then we can make up a pure immutable pair type.
public final class Pair<A,B> {
private final A a;
private final B b;
public Pair(A a, B b) {
this.a = a;
this.b = b;
}
public A getFst() { return a; }
public B getSnd() { return b; }
public static <A,B> Pair<A,B> make(A a, B b) {
return new Pair<A,B>(a, b);
}
public String toString() {
return "(" + a + ", " + b + ")";
}
}
With those in hand, we can actually define the State monad:
public abstract class State<S,A> implements Function<S, Pair<A, S> > {
// pure takes a value a and yields a state action, that takes a state s, leaves it untouched, and returns your a paired with it.
public static <S,A> State<S,A> pure(final A a) {
return new State<S,A>() {
public Pair<A,S> apply(S s) {
return new Pair<A,S>(a, s);
}
};
}
// we can also read the state as a state action.
public static <S> State<S,S> get() {
return new State<S,S>() {
public Pair<S,S> apply(S, s) {
return new Pair<S,S>(s, s);
}
}
}
// we can compose state actions
public <B> State<S,B> bind(final Function<A, State<S,B>> f) {
return new State<S,B>() {
public Pair<B,S> apply(S s0) {
Pair<A,S> p = State.this.apply(s0);
return f.apply(p.getFst()).apply(p.getSnd());
}
};
}
// we can also read the state as a state action.
public static <S> State<S,S> put(final S newS) {
return new State<S,S>() {
public Pair<S,S> apply(S, s) {
return new Pair<S,S>(s, newS);
}
}
}
}
Now, there does exist a notion of a getter and a setter inside of the state monad. These are called lenses. The basic presentation in Java would look like:
public abstract class Lens[A,B] {
public abstract B get(A a);
public abstract A set(B b, A a);
// .. followed by a whole bunch of concrete methods.
}
The idea is that a lens provides access to a getter that knows how to extract a B from an A, and a setter that knows how to take a B and some old A, and replace part of the A, yielding a new A. It can't mutate the old one, but it can construct a new one with one of the fields replaced.
I gave a talk on these at a recent Boston Area Scala Enthusiasts meeting. You can watch the presentation here.
To come back into Haskell, rather than talk about things in an imperative setting. We can import
import Data.Lens.Lazy
from comonad-transformers or one of the other lens libraries mentioned here. That link provides the laws that must be satisfied to be a valid lens.
And then what you are looking for is some data type like:
data A = A { x_ :: Int }
with a lens
x :: Lens A Int
x = lens x_ (\b a -> a { x_ = b })
Now you can write code that looks like
postIncrement :: State A Int
postIncrement = do
old_x <- access x
x ~= (old_x + 1)
return old_x
using the combinators from Data.Lens.Lazy.
The other lens libraries mentioned above provide similar combinators.
First of all, I agree with Raeez that this probably the wrong way to go, unless you really know why! If you want to increase some value by 42 (say), why not write a function that does that for you?
It's quite a change from the traditional OO mindset where you have boxes with values in them and you take them out, manipulate them and put them back in. I would say that until you start noticing the pattern "Hey! I always take some value as an argument, and at the end return it slightly modified, tupled with some other value and all the plumbing is getting messy!" you don't really need the State monad. Part of the fun of (learning) Haskell is finding new ways to get around the stateful OO thinking!
That said, if you absolutely want a box with an x of type Int in it, you could try making your own get and put variants, something like this:
import Control.Monad.State
data Point = Point { x :: Int, y :: Int } deriving Show
getX :: State Point Int
getX = get >>= return . x
putX :: Int -> State Point ()
putX newVal = do
pt <- get
put (pt { x = newVal })
increaseX :: State Point ()
increaseX = do
x <- getX
putX (x + 1)
test :: State Point Int
test = do
x1 <- getX
increaseX
x2 <- getX
putX 7
x3 <- getX
return $ x1 + x2 + x3
Now, if you evaluate runState test (Point 2 9) in ghci, you'll get back (12,Point {x = 7, y = 9}) (since 12 = 2 + (2+1) + 7 and the x in the state gets set to 7 at the end). If you don't care about the returned point, you can use evalState and you'll get just the 12.
There's also more advanced things to do here like abstracting out Point with a typeclass in case you have multiple datastructures which have something which behaves like x but that's better left for another question, in my opinion!

Resources