Do Frontends need to care about alignment?


Meant to add more text, but somehow the email got sent.

Could you explain why for some of these cases? If I set the right target and only want to operate with the system C ABI, will LLVM not generate correct code if I want to pay say structs to a system defined function?

I see clang specifying alignment, but I’m not sure why.

I want to understand beyond alignment and function ABI (which for my case is also system’s C ABI) what makes my LLVM IR platform dependent.

LLVM will always generate correct code if you don’t specify alignment, but may generate inefficient code. For example, if you are targeting MIPS (or older ARM ISAs) then the hardware does not handle unaligned loads and stores, and so you will enter a trap-and-emulate path if you do a load or store with lower-than-natural alignment. To avoid this, LLVM will emit a slower sequence of loads, shifts and masks (or load-right + load-left on MIPS) for all cases where the load / store does not have a sufficiently high alignment in the IR.

The alignment is used to guarantee the alignment on allocas and globals, though in most cases this is unnecessary (most targets have a sufficiently high default alignment that they’ll be fine). It is also used to provide a contract to the back end saying ‘either this load/store has this alignment, or it is undefined behaviour’. This means that the back end is free to emit instructions that rely on that alignment (and mid-level optimisers are free to perform transforms that require that alignment). For x86, it doesn’t make much difference, as almost all instructions are alignment-independent. For MIPS, it can make a big difference.


The other case is that your ABI might require a particular alignment. While some of the details of calling conventions are handled by LLVM itself, some have to be specified by the frontend. There's been discussion on this divide on the mailing list before.

(p.s. I know you mentioned this in your question. Just mentioning it for completeness.)