Interoperating with Verilog

It is easy to create magma Circuits from existing Verilog modules.


In [1]:
import magma as m

Defining a Circuit with a Verilog body


In [2]:
HalfAdder = m.DefineCircuit('HalfAdder', 
   'A', m.In(m.Bit), 
   'B', m.In(m.Bit),
   'S', m.Out(m.Bit),
   'C', m.Out(m.Bit))
HalfAdder.verilog  = '''\
    assign S = A ^ B;
    assign C = A & B;\
'''
m.EndCircuit()

In [3]:
print(HalfAdder)


HalfAdder(A: In(Bit), B: In(Bit), S: Out(Bit), C: Out(Bit))

Defining a Circuit from Verilog.

If we have verilog source, we can declare a magma circuit from that source. Magma uses the verilog parser pyverilog to parse the source and return a list of Circuits, one for each module in the file.


In [4]:
verilog_source = '''
module _HalfAdder(a, b, c);
    input a;
    output b;
    inout c;
    assign a = b & c;
endmodule'''

HalfAdder = m.DefineFromVerilog(verilog_source)[0]

print(HalfAdder)


Generating LALR tables
WARNING: 177 shift/reduce conflicts
_HalfAdder(a: In(Bit), b: Out(Bit), c: InOut(Bit))

The functions:

DeclareFromVerilogFile(filename)
DefineFromVerilogFile(filename)

can be used to declare and define Magma circuits from verilog files. The declare versions declare a Magma circuit, but does not include the verilog source code. The define versions define a Magma circuit which includes the verilog source code.

Defining a Circuit from Templated Verilog

It is also possible to run a text templating engine on the verilog source.

Here is an example using mako, a simple python templating engine. The expressions contained with ${...} are python.


In [5]:
mako_source = '''module CSA${N} ( input [${N-1}:0] a,b,c, output [${N-1}:0] s, co );
   assign s = a ^ b ^c;
   assign co = a&b | b&c | a&c;
endmodule'''

In [6]:
from mako.template import Template

template = Template(mako_source)
verilog = template.render(N=4)

print(verilog)


module CSA4 ( input [3:0] a,b,c, output [3:0] s, co );
   assign s = a ^ b ^c;
   assign co = a&b | b&c | a&c;
endmodule

The functions:

DeclareFromTemplatedVerilogFile(filename, **args)
DefineFromTemplatedVerilogFile(filename, **args)

can be used to declare and define Magma circuits from templated verilog files. The keyword args are passed to the templating engine and can be used to control the generation of verilog.


In [7]:
CSA4 = m.DefineFromTemplatedVerilog(mako_source, N=4)[0]
print(CSA4)


Generating LALR tables
WARNING: 177 shift/reduce conflicts
CSA4(a: In(Bits[4]), b: In(Bits[4]), c: In(Bits[4]), s: Out(Bits[4]), co: Out(Bits[4]))

Genesis3

See the repo https://github.com/phanrahan/genesis3 for a simple verilog generator similar to Genesis2.


In [ ]: