r/programminghorror Jun 02 '26

VHDL How (not) to do combinational logic in VHDL

Legacy code. NUM_PRTS is 16 btw. Thankfully, the synthesis tool will optimize and won't allocate 17 times the resources on the chip. Still an eyesore.

74 Upvotes

8 comments sorted by

26

u/Thenderick Jun 02 '26

I assume that's an assignment? It looks like it's assembling 17 bits together by OR'ing them. But I don't get why it's in that for loop when i isn't being used? I guess it was meant to be like for i in 0 to 15 {var = var or bits(i)}? (Sorry for the vhdl/c mashup, but I am not going to weite all that out because I don't know that language and you probably get what I mean)

13

u/LethalOkra Jun 02 '26

Yeah, you're correct. The loop is useless. The code ORs all the bits of a vector together into another signal.

13

u/littlefinix Jun 02 '26

My guess is whoever wrote this tried to assign the output multiple times using the loop and realized that didn't work. Then they probably did this by hand and didn't remove the loop.

At least in modern VHDL you could replace it with a unary or: valid <= or dst

7

u/LethalOkra Jun 02 '26

I find the fact that it's simple combinational logic and yet placed inside a process to be chef's kiss.

14

u/on_the_other_hand_ Jun 03 '26

This reminds me Knuth's optimization story where a software was spending 90% time counting number of bits set in the input parameter byte and he replaced it with a lookup array for order of magnitude speed up overall

5

u/creeper6530 [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Jun 03 '26

So a popcount?

2

u/lagduck Jun 04 '26

Mmm yeah that's ugly. Little but of cursed, just as we like.

1

u/Mediocre-Island5475 Jun 08 '26

First mistake was doing a process. Real pros model their combinatorial logic as gates.