Skip to content

Unnecessary alloca Without Optimization Flags  #129282

Closed
@CJacob314

Description

@CJacob314

The following code, when compiled without optimization flags (or with -Copt-level=0) emits LLVM IR for an 8192-byte alloca, which can easily cause 100% unnecessary stack overflow errors in a running executable.

fn test<const SIZE: usize>() {
  if SIZE < 4096 {
    let arr = [0u8; SIZE];
    std::hint::black_box(&arr);
  } else {
    let vec = vec![0u8; SIZE];
    std::hint::black_box(&vec);
  }
}

fn main() {
    test::<8192>();
}

The following is the relevant LLVM IR:

define internal void @example::test::hb882c86c9d7a582d() unnamed_addr #1 personality ptr @rust_eh_personality !dbg !546 {
start:
  %0 = alloca [16 x i8], align 8
  %vec = alloca [24 x i8], align 8
  %arr = alloca [8192 x i8], align 1
  br label %bb2, !dbg !548

%arr only ends up being used by bb1 below, but bb1 has no predecessors:

bb1:                                              ; No predecessors!
  call void @llvm.memset.p0.i64(ptr align 1 %arr, i8 0, i64 8192, i1 false), !dbg !555
; call core::hint::black_box
  %_3 = call align 1 ptr @core::hint::black_box::h61dc8dd57d9b7993(ptr align 1 %arr), !dbg !556
  br label %bb5, !dbg !556
}

Here's a Godbolt Compiler Explorer link with all of the IR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-codegenArea: Code generationC-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions