simulating c style unions in LLVM

I am trying to create a boxed tagged datatype for a language where it is necessary to resolve the type at runtime. If I were writing an interpreter in C- it would most likely look something like this-

    unsigned tag;
    union { long Int; double Float; .... }

Is there a standard way for constructing a type like this in LLVM?

Thanks again.

You have to write it using bitcasts. Try looking at llvm-gcc or clang
output for a rough outline.


Well, you can always ask bitter melon, who translates this:

struct foo
   unsigned tag;
   union { long Int; double Float; } data;

void bar(struct foo *x) {
    x->data.Int = x->tag;

into this:

  %struct.anon = type { double } = type { i32, %struct.anon }

define void @bar(* nocapture %x) nounwind {
  %0 = getelementptr* %x, i32 0, i32 0 ; <i32*> [#uses=1]
  %1 = load i32* %0, align 4 ; <i32> [#uses=1]
  %2 = getelementptr* %x, i32 0, i32 1 ; <%struct.anon*> [#uses=1]
  %3 = bitcast %struct.anon* %2 to i32* ; <i32*> [#uses=1]
  store i32 %1, i32* %3, align 4
  ret void

So essentially the union just turns into bitcasts.

I know there was some discussion about adding a first-order union to
LLVM a bit back, but IIRC disagreement over semantics prevented it
from going anywhere.

Thanks both. I looked over the getelementptr and bitcast documentation but I am still a bit confused by one point. lets say i have something like this.

    long Int; double float; long* IntRef;

Since pointer sizes are platform dependent if I am trying to use the union in question with an extern C function is it possible to make write the single definition in a platform independent way?

Thanks in advance.

Not really; there's some discussion of that in the thread starting at .


Eli Friedman wrote:

Initial implementation discussions began with a patch I posted here: