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-

struct
{
    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.

-Eli

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 }
  %struct.foo = type { i32, %struct.anon }

define void @bar(%struct.foo* nocapture %x) nounwind {
entry:
  %0 = getelementptr %struct.foo* %x, i32 0, i32 0 ; <i32*> [#uses=1]
  %1 = load i32* %0, align 4 ; <i32> [#uses=1]
  %2 = getelementptr %struct.foo* %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.

union
{
    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
http://lists.cs.uiuc.edu/pipermail/llvmdev/2009-May/022132.html .

-Eli

Eli Friedman wrote:

Initial implementation discussions began with a patch I posted here:

http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-Mon-20090511/077443.html

Andrew