LLVM IR for nested arrays

Hey, I’m working on implementing simple nested arrays in LLVM, but I’m having some trouble doing so - here’s an example:

i32 main() {
	i32** matrix = new i32*[2];
	matrix[0] = new i32[2];
	matrix[1] = new i32[2];
	matrix[0][0] = 1;
	matrix[1][0] = 2;
	
	print("%i %i\n", matrix[0][0], matrix[1][0]);
}

The code above should print 1 2, but instead it prints 1 635240784. This is my IR for the program above:

@llvm.global_ctors = appending global [0 x { i32, ptr, ptr }] zeroinitializer

declare ptr @malloc(i64)
declare i32 @printf(ptr, ...)

define i32 @main() {
entry:
  %0 = call ptr @malloc(i64 16)
  %matrix = alloca ptr, align 8
  store ptr %0, ptr %matrix, align 8
  %1 = getelementptr ptr, ptr %matrix, i64 0
  %2 = call ptr @malloc(i64 8)
  store ptr %2, ptr %1, align 8
  %3 = getelementptr ptr, ptr %matrix, i64 1
  %4 = call ptr @malloc(i64 8)
  store ptr %4, ptr %3, align 8
  %5 = getelementptr ptr, ptr %matrix, i64 0
  %6 = load ptr, ptr %5, align 8
  %7 = getelementptr ptr, ptr %6, i64 0
  store i32 1, ptr %7, align 4
  %8 = getelementptr ptr, ptr %matrix, i64 1
  %9 = load ptr, ptr %8, align 8
  %10 = getelementptr ptr, ptr %9, i64 0
  store i32 2, ptr %10, align 4
  %11 = alloca [7 x i8], align 1
  store [7 x i8] c"%i %i\0A\00", ptr %11, align 1
  %12 = load ptr, ptr %matrix, align 8
  %13 = getelementptr ptr, ptr %12, i64 0
  %14 = load ptr, ptr %13, align 8
  %15 = getelementptr ptr, ptr %14, i64 0
  %16 = load ptr, ptr %matrix, align 8
  %17 = getelementptr ptr, ptr %16, i64 1
  %18 = load ptr, ptr %17, align 8
  %19 = getelementptr ptr, ptr %18, i64 0
  %call = call i32 (ptr, ...) @printf(ptr %11, ptr %15, ptr %19)
  ret i32 0
}

What do I need to do in order to fix this issue? Thanks :smiley:

This is clearly not equivalent to calling printf with two ints (ptr is not i32…).

Also why are you putting the string in a local buffer? Just pass a pointer to a string constant.

1 Like

I see, I’d missed this line. Turns out there were a couple more errors, which weren’t terribly difficult to fix. I’ve also moved my string into string constant. Thanks