generateLLVMConstant function

String generateLLVMConstant(
  1. String variableName,
  2. String content
)

Generates an LLVM constant string definition from a Dart string.

This utility function converts a Dart string into the LLVM IR format for string constants. LLVM requires special encoding for certain characters and needs explicit null termination.

The conversion process:

  1. Escapes null characters (\0\00)
  2. Escapes newlines (\n\0A)
  3. Escapes quotes ("\22)
  4. Adds null terminator (\00) at the end
  5. Calculates array size including null terminator
  6. Formats as LLVM constant array declaration

Parameters:

  • variableName: The LLVM variable name for the constant (e.g., "@str.0")
  • content: The original string content to be converted

Returns: LLVM IR constant declaration string in the format: @variable = private constant [size x i8] c"escaped_content\\00"

Example:

final llvmConst = generateLLVMConstant("@str.0", "Hello\nWorld");
// Results in: @str.0 = private constant [12 x i8] c"Hello\0AWorld\00"

Implementation

String generateLLVMConstant(String variableName, String content) {
  // Convert the content into a format suitable for LLVM constant
  final escapedContent = content
      .replaceAll('\0', '\\00') // Ensure null terminators are represented
      .replaceAll('\n', '\\0A')
      .replaceAll("\"", "\\22"); // Replace newlines with LLVM encoding

  // Add null terminator to the end of the string
  final llvmContent = '$escapedContent\\00';

  // Calculate the size of the array
  final size = content.runes.length+1;

  // Format as LLVM constant string
  return '$variableName = private constant [$size x i8] c"$llvmContent"';
}