How to get Opaque Pointers from the C++ API of LLVM?

I’m working on a pass where I insert code which check whether a pointer-struct-field in null or not. I’m currently switching to LLVM 17 (coming from LLVM 12) and opaque pointers are the way to go. But I’m unable to find the function and LLVM type in the C++ API which I now have to use to generate a load-statement of getelementptr.

I compiled the following C++ code to IR:

struct A {
    float i;
};

struct T {
    A *base;
    int i;
};

float f(T *t) {
    if (t->base == nullptr)
        return -1;
    else
        return t->base->i;
}

and I get something like this (extract)

  %base = getelementptr inbounds %struct.T, ptr %0, i32 0, i32 0
  %1 = load ptr, ptr %base, align 8
  %cmp = icmp eq ptr %1, null

%1 is the base-pointer-field and then there is the comparison with the nullptr. Great.

How do I create this IR from the C++ API?

More precisely.

Is there a way to get the type of the field from the getelemtptr-instr indices? (In the Opaque Pointer-document it’s said to use getSourceElementType(), I’m unable to find, createInboundsGEP() returns a Value).

How to get the opaque ptr-type from C++ API?

How to get the typeless null-value from the C++ API?

Am I asking the right questions to solve my problem?

Is there a way to get the type of the field from the getelemtptr-instr indices? (In the Opaque Pointer-document it’s said to use getSourceElementType(), I’m unable to find, createInboundsGEP() returns a Value).

Not entirely sure I understand the question correctly, but GEP->getResultElementType() will essentially return what the pointer element type of a getelementptr would have been in typed pointer mode.

How to get the opaque ptr-type from C++ API?

PointerType::get(Ctx, AS). Ctx is the LLVMContext instance.

How to get the typeless null-value from the C++ API?

Constant::getNullValue(PTy). There are still different null values, since you can have pointers with different address spaces.

1 Like

I guess what would help here is:

llc -march=cpp -o code.cpp code.ll

What has happened to the “cpp” target?
llc -version does not seem to list it here.

The cpp backend was removed in ⚙ D19942 Remove bit-rotten CppBackend. (May 2016), on the basis that it didn’t produce working code anymore and was effectively unmaintained for several years by that point.