ldzm
ldzm

Reputation: 23

How to check if a target of an LLVM AllocaInst is a function pointer

%pointer = alloca void (i32)*, align 8 How to check if %pointer is a function pointer?Can I get the parameter list of the function pointer?

Upvotes: 2

Views: 1625

Answers (1)

Bernard Nongpoh
Bernard Nongpoh

Reputation: 1058

Let Create a function that check if an Alloca Instruction Type is a function pointer.

bool  isFunctionPointerType(Type *type){
      // Check the type here
     if(PointerType *pointerType=dyn_cast<PointerType>(type)){
        return isFunctionPointerType(pointerType->getElementType());
     }
        //Exit Condition
        else if(type->isFunctionTy()){
        return  true;
        }
       return false;
  }

In your runOnModule/runOnFunction Pass

if(AllocaInst *allocaInst=dyn_cast<AllocaInst>(inst)){
     if(isFunctionPointerType(allocaInst->getType())){
     errs()<<"Funtion Pointer Type\n";
     }
  }

The above pass are tested on the following source.c code

#include <stdio.h>

void fun(int a)
{
    printf("Value of a is %d\n", a);
}

int main()
{

    void (*fun_ptr)(int) = &fun;

    (*fun_ptr)(10);

    return 0;
}

Corresponding LLVM Bitcode without any optimization

entry:
%retval = alloca i32, align 4
%fun_ptr = alloca void (i32)*, align 8
store i32 0, i32* %retval, align 4
call void @llvm.dbg.declare(metadata void (i32)** %fun_ptr, metadata !11,
... metadata !15), !dbg !16
store void (i32)* @_Z3funi, void (i32)** %fun_ptr, align 8, !dbg !16
%0 = load void (i32)*, void (i32)** %fun_ptr, align 8, !dbg !17
call void %0(i32 10), !dbg !18
ret i32 0, !dbg !19

Successfully detect func_ptr as a function pointer.

Note that the code use recursion to find the type recursively

Another way is to track the used of func_ptr using def-use chain in LLVM, ie by tracking the StoreInst and check if the source operand is a pointer to function : haven't try yet.

Hope this helps... If it help please mark it as correct solution or upvote.. Thanks..

Upvotes: 3

Related Questions