Must string literals be declared as a global variable in LLVM IR?

Hi,

#include <stdio.h>

int main(int argc, char *argv[]) {
    puts("Hello World!");
    return 0;
}

The above C code is converted to the following IR code. The string
literal "Hello World!" is defined as an unnamed global constant.

Does the IR language support the declaration of local values to store
the string literal? I don't this is supported as I am reading the
manual. But I would like to double check. Thanks.

@.str = private unnamed_addr constant [13 x i8] c"Hello World!\00", align 1

; Function Attrs: noinline nounwind optnone uwtable
define dso_local i32 @main(i32, i8**) #0 !dbg !7 {
  %3 = alloca i32, align 4
  %4 = alloca i32, align 4
  %5 = alloca i8**, align 8
  store i32 0, i32* %3, align 4
  store i32 %0, i32* %4, align 4
  call void @llvm.dbg.declare(metadata i32* %4, metadata !14, metadata
!DIExpression()), !dbg !15
  store i8** %1, i8*** %5, align 8
  call void @llvm.dbg.declare(metadata i8*** %5, metadata !16,
metadata !DIExpression()), !dbg !17
  %6 = call i32 @puts(i8* getelementptr inbounds ([13 x i8], [13 x
i8]* @.str, i32 0, i32 0)), !dbg !18
  ret i32 0, !dbg !19
}

If you want a pointer to a value, it has to be located somewhere in memory. There are basically three places memory can be allocated in a program: on the stack (alloca), on the heap (malloc), or in program memory (a global variable/constant).

-Eli

If you want a pointer to a value, it has to be located somewhere in
memory. There are basically three places memory can be allocated in a
program: on the stack (alloca),

Even I can alloca a chuck of memory, there is not a way to put the
string constant to it? Sounds likely there is not way to avoid the
initialization of the global variables. Is it?

You can always write a sequence of byte stores to store each character. Of course, that's not very efficient for long strings.

-Eli

Globals, especially ones as simple as strings, tend to be
"initialized" just by being mapped into memory by the kernel from the
executable file. It's the best possible initialization (no
computation, no explicit instructions, it's all just an mmap); all the
global variable is doing is giving you a handle to this string that
you've requested should be available.

Cheers.

Tim.