Bill Peet
Bill Peet

Reputation: 477

LLVM inconsistent numbering scheme

I've been playing around with compilers and have been working on my own toy C compiler. Currently I'm attempting to target LLVM IR, but I'm having trouble wrapping my head around the syntax.

My current current issue: why is this valid IR syntax:

define i32 @main() {
    %1 = alloca i32, align 4
    %2 = add i32 0, 0
    store i32 %2, i32* %1, align 4
    %3 = alloca i32, align 4
    %4 = add i32 0, 1
    store i32 %4, i32* %3, align 4
    %5 = load i32, i32* %1, align 4
    %6 = icmp ne i32 %5, 0
    br i1 %6, label %true0, label %else0
true0:                          ; preds %0
    %7 = add i32 0, 1
    store i32 %7, i32* %3, align 4
    br label %end0
else0:                          ; preds %0
    %8 = load i32, i32* %3, align 4
    %9 = icmp ne i32 %8, 0
    br i1 %9, label %true1, label %end1
true1:                      ; preds %else0
    %10 = add i32 0, 2
    store i32 %10, i32* %3, align 4
    br label %end1
end1:                       ; preds %true1, %else0
    br label %end0
end0:                           ; preds %true0, %else1
    %11 = load i32, i32* %3, align 4
    ret i32 %11
}

but this is not:

define i32 @main() {
    %1 = alloca i32, align 4
    %2 = add i32 0, 0
    store i32 %2, i32* %1, align 4 ; variable a
    %3 = load i32, i32* %1, align 4
    %4 = icmp ne i32 %3, 0
    br i1 %4, label %true0, label %else0
true0: ; preds %0
    %5 = add i32 0, 1
    ret i32 %5
    br label %end0
else0: ; preds %0
    %6 = add i32 0, 2
    ret i32 %6
    br label %end0
end0: ; % preds %true0, %else0
    ret i32 0
}

I get the error:

llc-6.0: test2.ll:13:1: error: instruction expected to be numbered '%7'
%6 = add i32 0, 2
^

I don't understand why that block needs to be %7, given the previously used number was %6. Compare the %else0 label of the first example, that's very similar syntax and works fine.

And yes, my compiler needs a lot of optimization, but I'm not finished yet :)

Upvotes: 1

Views: 283

Answers (1)

Eraklon
Eraklon

Reputation: 4288

Your code is invalid because there is actually another basic block you did not labeled:

true0: ; preds %0
    %5 = add i32 0, 1
    ret i32 %5
hidden_bb: ; this will named as %6 by default
    br label %end0
else0: ; preds %0

If it has a label than the error will gone. Note that all terminator instructions, like br and ret will create their own basic block.

Upvotes: 3

Related Questions