The “automatic” keyword in Verilog HDL and System Verilog

It may be quite odd to use the “automatic” variables in your Verilog HDL test benches or System Verilog codes. Somehow, it is better to know when you must use it. Recently I have encountered two strange problems and I would like to share the solutions here.

Every registers, wires and variables defined in Verilog are treated as global static variables in simulators. The keyword “automatic” will change this default attribute into stack value, which means changing a variable from a global static value into a value defined and stored in stack. This problem originates from the very beginning of Verilog, when Verilog is only taken as a hardware description language that there is no need to use stack. However, along with the increasing scale of hardware design, Verilog HDL is involved into hardware verification. Stack is important for the correctness of behavorial description and the keyword “automatic” is introduced for this purpose.

The first scenario where “automatic” has been used is to write a recursive function in Verilog. eg:
  function automatic integer mcal;
      input integer VCN;
      begin
     if (VCN <2)
       mcal = 0;
     else if(VCN == 2)
       mcal = 1;
     else if(VCN == 3)
       mcal = 3;
     else
       mcal = 2*(VCN/2) + mcal(VCN/2) + mcal(VCN/2+VCN[0]);
      end
   endfunction // mcal

Here mcal(i) = 2*(i/2)+mcal(i/2)+mcal(i-i/2). If the return value mcal is not a automatic value, only one copy of mcal exists in all code copies of mcal functions and the recursive algorithm would definitely fail.

The second scenario is more delicate and weird than the first one. eg:
   for(i=0; i<PE.size(); i++)
   begin
    automatic int j = i;
      fork
         PE[j].run();        // start a sub-thread
       join_none
   end

You may think the code “automatic int j = i;” is totally nonsense but it is the key to solve the problem. Without it, only one copy of i exists and the finally excuted thread would be PE[PE.size()].run(), which does not exist. (i == PE.size() when the for loop is finished and this is the time threads run() would run).

BTW, System Verilog is fantastic!

Advertisements

关于 W. Song
Research Associate in the University of Cambridge

2 Responses to The “automatic” keyword in Verilog HDL and System Verilog

  1. 匿名 says:

    In your second example, Without it, only one copy of i exists should be one copy of “J”, right?

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: