LLVM infinite program shuts down after a short while

Hi, I’ve compiled the following code using my custom compiler:

i32 main() {
	while(true) {
		for(i32 x = 0; x < 3; x++) {
			for(i32 y = 0; y < 3; y++) {
				print("%i %i\n", x, y);
			}
		}
	}
}

The code above should produce an endless loop, however, when I compile it into IR and emit an executable, which I then run via cmd the program runs correctly for 4-5 seconds, and then it just shuts down. Here is the IR I’m generating:

; ModuleID = 'channel'
source_filename = "channel"

@.str = private constant [7 x i8] c"%i %i\0A\00"
@llvm.global_ctors = appending global [0 x { i32, ptr, ptr }] zeroinitializer

declare i32 @printf(ptr, ...)

define i32 @main() {
  br label %2

1:                                                ; preds = %2
  ret i32 0

2:                                                ; preds = %5, %0
  br i1 true, label %3, label %1

3:                                                ; preds = %2
  %4 = alloca i32, align 4
  store i32 0, ptr %4, align 4
  br label %6

5:                                                ; preds = %6
  br label %2

6:                                                ; preds = %9, %3
  %7 = load i32, ptr %4, align 4
  %8 = icmp slt i32 %7, 3
  br i1 %8, label %12, label %5

9:                                                ; preds = %14
  %10 = load i32, ptr %4, align 4
  %11 = add i32 %10, 1
  store i32 %11, ptr %4, align 4
  br label %6

12:                                               ; preds = %6
  %13 = alloca i32, align 4
  store i32 0, ptr %13, align 4
  br label %15

14:                                               ; preds = %15
  br label %9

15:                                               ; preds = %18, %12
  %16 = load i32, ptr %13, align 4
  %17 = icmp slt i32 %16, 3
  br i1 %17, label %21, label %14

18:                                               ; preds = %21
  %19 = load i32, ptr %13, align 4
  %20 = add i32 %19, 1
  store i32 %20, ptr %13, align 4
  br label %15

21:                                               ; preds = %15
  %22 = load i32, ptr %4, align 4
  %23 = load i32, ptr %13, align 4
  %24 = call i32 (ptr, ...) @printf(ptr @.str, i32 %22, i32 %23)
  br label %18
}

I can’t see anything inherently wrong about it, but I may be missing something.

Any help is greatly appreciated.

You overflow your stack. Put the allocas in the entry block.

1 Like

Thanks! That was it, this would also explain why it worked just fine when I compiled it with -O3

Can you please send something as an answer, so I can accept your proposal as the solution, Thanks :smiley:

Can you please send something as an answer,

I do not know what that means. Don’t worry about it, happy it works now.

For some reason I can’t see the “accept as solution” button, that usually appears underneath answers :smiley:, maybe its bugged :person_shrugging: