1
votes

I wanted to use __attribute__((bitwidth(N))) to define custom-sized integer types when generating LLVM IR code with clang. I found some information that there is no plan to support this attribute. However, supporting such an attribute for IR generation (i.e. assembly representation) would be very helpful.

My use-case: I want to write a compiler for a custom micro-architecture with smallest possible effort*. The architecture only supports a very specific/unusual bitwidth. "Programs" for the micro-architecture are supposed to be written in a limited subset of C. In this context it is promising to use clang in order to generate LLVM IR and use this as basis for further processing. It would be great if the bitwidth attribute could be used to pass additional information about datatypes on to the next step as in the following example:

C-Code:

typedef int __attribute__((bitwidth(22))) int22;
int22 myVar = 0;

LLVM IR Assembly:

@myVar = global i22 0, align 3
; note that the align information is not relevant
; in my case, i.e. "align 4" would also be fine

Maybe there is some trick to "enable" this attribute for IR (wouldn't be too difficult to implement IMHO), or someone has more recent information than I could find (the llvm bugzilla entry is rather old now).

If not, maybe there is some alternative approach how I could "attach" additional information about the datatypes defined in C.


*) Adding a custom micro-architecture to clang (so that the -target option can be used) is regraded as very complex. True?

1

1 Answers

1
votes

Adding a new target to clang isn't that hard. Take an existing target look where it is included into clang and "clone" the approach. However, targets "commonly" define a strict data-layout that controls the generation of assembly by a back-end.

The bitwidth attribute would require back-ends to handle arbitrary sizes of types (e.g., int with 22bit as you showed). AFAIK, non of the back-ends in LLVM can handle this (may someone correct me if i'm wrong).

So if you want bitwidth support you can add this attribute to clang with a distinct target and limit it to this target only.

An alternative approach: If you just need LLVM IR, and from this point on you do your own stuff, maybe all you need is to add some metadata to the generated IR, i.e., you bring a custom attribute to clang that tells clang to add metadata to a destinct type (e.g., you say i32 should be 22 bit wide). You can look a the clang code and search for the align attribute, clone it for a bitwidth attribute and in code generation you handle your attribute to add metadata to the module.