Search code examples
templatesllvmllvm-clang

Extract Function Template Declarations from LLVM Module?


Extracting Functions from an LLVM module is simple:

for(auto FF = My_Module.begin(); FF != My_Module.end(): ++FF)
    llvm::Function *F = dyn_cast<llvm::Function>(FF);

But this only gives me already defined functions. If I have a program like below:

template <class T> __attribute__((noinline)) T load(T *ptr){
   return *ptr;
}

int main(){
   int a = 4;
   int b = 5;
   char c = 6;
   long d = 8;
   return load<int>(&a) + load<int>(&b) + load<char>(&c) + load<long>(&d);
}

So if I wanted to, for instance, create another function in the IR of a function declaration of load for an unsigned long, how do I extract the FunctionTemplateDecl that I could use to create the function for that type?

Is that even the correct way to create a function for my desired type?


Solution

  • Function templates at that point are already materialized depending on the types used for their instantiation. The LLVM IR has no notion of templates; you're just a bit further up from actual machine code.

    You need to go the front-end (i.e. Clang) as this is where the FunctionTemplateDecl and friends reside (this means manipulating the AST, etc.).