VHDL For Generate
Quick Syntax
-- add 2 to an array of integers
GEN_EXAMPLE1: for n in 0 to 7 generate
begin
output(n) <= input(n) + 2;
end generate;
-- instantiate an entity 16 times
GEN_EXAMPLE2: for n in 0 to 15 generate
begin
GEN2_INST: entity work.my_entity
port map (
clk => clk,
reset => reset,
input => input(n),
output => output(n));
end generate;
Purpose
The purpose of for generate statements is to give you the ability to replace many lines of code with much fewer when you have to do multiples of something. It's very convenient for simple things or even instantiating multiple instances of the same entity.
In the above examples, you can see where having the same lines of code to do something 8 times or 16 times would be cumbersome and much harder to maintain for when there are changes. Imagine if you need to do something 100's of times?
By using for generate, you can do something as many times as you want. I often use natural generics and constants to determine the upper bound of the for generate instead of hard wiring in a number there. It gives you a lot of flexibility for making modular code.
Best Practices
1. Use for generate statements when you have to do the same code multiple times to save lines of code and make it easy to maintain.
2. Combine for generate statements with either generics or constants of type natural, which makes it easy to change the number of iterations in the for loop.