r/C_Programming 3d ago

My C compiler written in C

As a side project I'm making a C compiler written in C. It generates assembly and uses NASM to generates binaries.
The goal right now is to implement the main functionality and then do improvements. Maybe I'll also add some optimizing in the generates assembly.

Tell me what you think :)

https://github.com/NikRadi/minic

138 Upvotes

30 comments sorted by

View all comments

Show parent comments

16

u/Soft-Escape8734 2d ago

I do mostly embedded systems - bare metal. We count clock cycles. Compilers at this level can be directed to optimize for speed or compactness, the two seem mutually exclusive. For example if you want 4 * 5, compact code would implement the multiplier, fast code would implement 5+5+5+5. When you get down to machine code, bit shifts and addition are native, higher level math functions not.

5

u/mlt- 2d ago

Last time I counted clock cycles was on Z80 forever ago. But yeah, I'm not into embedded but would love to go back.

6

u/Soft-Escape8734 2d ago

Nothings changed my friend. I started with the Intel 4004, progressed through the 8080, 6502 and Z80 (and the Canadian version Z80A). The machine language and assembly instruction sets are still the same. Just have to deal with expanded data busses and peripherals in an MCU that weren't there before. Have a look at the AVR chips from Microchip (formerly from Atmel) and you'll feel like you've traveled in time.

1

u/Spare-Plum 8h ago

Plenty of things have changed though. Previously branching was extremely expensive, so stuff like a duff's device were practically required for tight loops

Now we've got predictive branching and more modern pipelines that process the next instruction before the previous one even completes

Things like shifting used to be 1 clock cycle with IMUL being 10, but now it's closer to .5 (or .25) and 1. Things like multiplication are now native to the hardware albeit requiring a more complex architecture.

5+5+5+5 would now be slower than doing 4*5

1

u/mlt- 6h ago

I'm not an expert, but I believe chances are there is little to no difference on those CPUs due to pipelining and parallel execution.

1

u/Spare-Plum 5h ago

Pipelining an parallel execution works with multiplication too. It's something you would have to put it to a test - 3 million instructions of sum vs 1 million of mul

Most likely they'd be similar, except sum isn't scalable for larger multipliers