问题
I found it hard to understand the LLVM C++ API.
Is there any relationship between LLVM C++ API and LLVM IR? Also, how could one use the LLVM C++ API?
回答1:
To (greatly) simplify, LLVM is a C++ library for writing compilers. Its C++ API is the external interface users of the library employ to implement their compiler.
There's a degree of symmetry between LLVM IR and part of the LLVM C++ API - the part used to build IR. A very good resource for getting a feel for this symmetry is http://llvm.org/demo/. For example, you can compile this C code:
int factorial(int X) {
if (X == 0) return 1;
return X*factorial(X-1);
}
Into LLVM IR:
define i32 @factorial(i32 %X) nounwind uwtable readnone {
%1 = icmp eq i32 %X, 0
br i1 %1, label %tailrecurse._crit_edge, label %tailrecurse
tailrecurse: ; preds = %tailrecurse, %0
%X.tr2 = phi i32 [ %2, %tailrecurse ], [ %X, %0 ]
%accumulator.tr1 = phi i32 [ %3, %tailrecurse ], [ 1, %0 ]
%2 = add nsw i32 %X.tr2, -1
%3 = mul nsw i32 %X.tr2, %accumulator.tr1
%4 = icmp eq i32 %2, 0
br i1 %4, label %tailrecurse._crit_edge, label %tailrecurse
tailrecurse._crit_edge: ; preds = %tailrecurse, %0
%accumulator.tr.lcssa = phi i32 [ 1, %0 ], [ %3, %tailrecurse ]
ret i32 %accumulator.tr.lcssa
}
As well as to C++ API calls (I won't paste it here because the output is long, but you can try it yourself). Doing this, you'll see, for example the icmp
instruction from the IR code above done as:
ICmpInst* int1_5 = new ICmpInst(*label_4, ICmpInst::ICMP_EQ, int32_X, const_int32_1, "");
ICmpInst
is a class that's part of the C++ API used to create icmp
instructions. A good reference for the C++ API is the Programmer's manual.
回答2:
You can use the CPP backend (llc -march=cpp
) to find out the mapping from any given IR to the C++ API.
来源:https://stackoverflow.com/questions/10675661/what-exactly-is-the-llvm-c-api