从LLVM中的不同文件内联代码

时间:2012-05-12 23:31:10

标签: c llvm clang

我需要在运行时使用LLVM内联几个函数。复杂的是,这些函数是在单独的bitcode文件中定义的。

在运行时,我需要为诸如

之类的函数生成代码
void snippet1();         //declaring that snippet1 and 2 are defined in snippet1.c and snippet2.c
void snippet2();

void combo12(){
    snippet1();
    snippet1();
    snippet2();
    snippet2();
}

从combo12.c,snippet1.c和snippet2.c编译的单独LLVM bitcode文件。问题是,我需要在combo12中内联对snippet1和snippet2的所有调用。我尝试使用以下代码(main.cpp)执行此操作:

OwningPtr<MemoryBuffer> MB, MB2, MB3;
Module *M1, *M2, *MC12, *MOUT;
LLVMContext Context;
std::string ErrorStr;

MemoryBuffer::getFile("snippet1.bc", MB);
M1 = ParseBitcodeFile(MB.get(), Context);

MemoryBuffer::getFile("snippet2.bc", MB2);
M2 = ParseBitcodeFile(MB2.get(), Context);    

MemoryBuffer::getFile("combo12.bc", MB3);
MC12 = ParseBitcodeFile(MB3.get(), Context);    

Linker* L;

L = new Linker("testprog", M1, 0);

L->setFlags(llvm::Linker::Verbose);

if (!(L->LinkInModule(M2, &ErrorStr)))
    std::cout << ErrorStr;

if (!(L->LinkInModule(MC12, &ErrorStr)))
    std::cout << ErrorStr;

MOUT = L->getModule();

MOUT->dump();

PassManager *PM;

PM = new PassManager();

PM->add(createInternalizePass(true));

PM->add(createAlwaysInlinerPass());

if (PM->run(*MOUT)){
    std::cout << "\n\n\nCode was altered!\n\n\n" << std::endl;
    MOUT->dump();
    std::cout << "\n\n ALTERED BEAST \n\n" << std::endl;
}

snippet1.c:

//What this function does is irrelevant
#include "post_opt.h"     //contains the struct exstr declaration
extern struct exstr a;
inline void snippet1() __attribute((always_inline));
void snippet1(){
    int x, y;
    a.b = 10;
    x = 2;
    if(x < a.a){
        y = x + 1;
    }
}

我使用

编译了snippet1.c,snippet2.c和combo12.c
clang -c -emit-llvm snippet1.c -o snippet1.bc -O0
clang -c -emit-llvm snippet2.c -o snippet2.bc -O0
clang -c -emit-llvm combo12.c -o combo12.bc -O0

和main.cpp一起

clang++ -g main.cpp `llvm-config --cppflags --ldflags --libs --cppflags --ldflags --libs core jit native linker transformutils ipo bitreader` -O0 -o main

当我运行./main时,虽然我使用always_inline属性明确标记了该函数,但它没有内联代码段代码,并使用AlwaysInline传递。它永远不会在屏幕上打印ALTERED BEAST。

为什么会这样?我认为,通过将所有模块链接在一起并应用IPO传递(AlwaysInline),这样就可以了。

感谢您的任何见解!

1 个答案:

答案 0 :(得分:2)

在编译期间进行内联而不进行链接和内联仅在编译时使用完全定义的函数。因此,不可能从其他文件内联函数(因为编译文件时会导致其他文件被忽略)。唯一的解决方案是在每个需要内联函数的文件中定义函数。