0
\$\begingroup\$

In VHDL I can write (0 downto 1) and will generate a Vector with 0 elements.

I want to do this to "rightalign" a field in a union, if needed. Samplecode:

module example #(int ITEMS=3)(output logic[4:0] result);
union {
  logic [4:0] result;
  struct {
    logic systemstatus;
    logic [4-1-ITEMS-1:0] padding;
    logic [ITEMS-1:0] itemStatus;
  } bitfield;
} myStruct;
endmodule;

I want to generate a struct that looks roughly like this:

systemstatus | 0padder | item3 | item2 | item1 //ITEMS==3
systemstatus | item4   | item3 | item2 | item1 //ITEMS==4

As you can see the padding field disappears for 4 items. However the code above will not do what I want in system verilog since instead of creating a vector with 0 elements, I will always create a vector with at least one element ([0:0]), and when the expression becomes negative ([-1:0]]) I will create a vector with two elements.

Is there a way to let padding "decay/degenerate" to an empty vector? I know I could make myStruct.bitfield.itemStatus simply always the right size and always access a subvector. But the point is to do the magic once in the struct and not worry about it anymore in the rest of the code.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You want to use the let statement instead of a union. The let statement is like a macro, except it is limited to a scope, and limited by substituting expressions, not any arbitrary text.

module example #(int ITEMS=3)(output logic[4:0] result);
  let systemstatus = result[4];
  let itemStatus = result[ITEMS-1:0];
  ...
endmodule

If you still want do this using a union, you can get what you want by creating your union with two structs. Also note that you need to use a packed union and struct to guarantee bit alignment.

union packed {
  logic [4:0] result;
  struct packed {
    logic status;
    logic [3:0] padding;
  } system;
  struct packed {
    logic [4: 1+4-ITEMS] padding;
    logic [ITEMS-1:0] status;
  } item;
} myStruct; 

Now you can refer to mystruct.system.status and mystruct.item.status.

\$\endgroup\$
1
  • \$\begingroup\$ I actually want the union/struct bit, since i am trying o create a magic register. While the trick works if I have something infront of my padding, it does not work if there is no item infront of my padding, since padding ovelaps with result in your code. \$\endgroup\$
    – ted
    May 18, 2015 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.