I am generating LLVM IR (.ll files) from a source language. This language doesn't have any mutable local variables and I don't use any alloca
s yet, everything so far is in LLVM registers. It does have immutable local values, though. Currently, they work fine unless the initializer part is a constant or another identifier. For example:
def fun(a: Int, b: Int) = {
val n = a + b
n + 2
}
This compiles fine, because a + b
compiles to the instruction add i32 %a, %b
and instructions can be optionally assigned to local values, so the line becomes: %n = add i32 %a, %b
.
On the other hand, I have trouble generating code for the following:
def fun() = {
val n = 1
n
}
I could generate %n = bitcast i32 1 to i32
but bitcast doesn't work with all types and is not really intended for this. Well, I guess in LLVM there is really nothing specifically intended for this, otherwise I wouldn't have the ques开发者_StackOverflow社区tion.
But is there a good solution without generating tons of different no-op instructions depending on the type of the value? bitcast will not work with tuples for example:
error: invalid cast opcode for cast from '{ i32, i32 }' to '{ i32, i32 }'
%n = bitcast {i32, i32} {i32 1, i32 2} to {i32, i32}
Then again, maybe because there are no 'copy' instructions in the IR, I shouldn't be trying to do this and should be replacing %n with the value everywhere it is used?
You have two possibilities:
- Generate the code using alloca's, load and stores (check e.g. clang's or llvm-gcc's output at -O0) and then use -mem2reg optimization pass to raise all this stuff to LLVM registers
- Use 1 instead of %n everywhere.
精彩评论