From 4b3cf118b11ed5ecc623c4ae12213a5aadb10c39 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Wed, 9 Jun 2021 14:04:55 -0500 Subject: [PATCH] Temporarily externalize Julia globals --- src/driver.jl | 37 +++++++++++++++++++++++++++++++++++++ src/mcgen.jl | 4 ++++ 2 files changed, 41 insertions(+) diff --git a/src/driver.jl b/src/driver.jl index 9f36d720..2dd00514 100644 --- a/src/driver.jl +++ b/src/driver.jl @@ -219,8 +219,12 @@ const __llvm_initialized = Ref(false) internalize!(pm, exports) # eliminate all unused internal functions + add!(pm, ModulePass("ExternalizeJuliaGlobals", + externalize_julia_globals!)) global_optimizer!(pm) global_dce!(pm) + add!(pm, ModulePass("InternalizeJuliaGlobals", + internalize_julia_globals!)) strip_dead_prototypes!(pm) # merge constants (such as exception messages) from the runtime @@ -309,6 +313,39 @@ const __llvm_initialized = Ref(false) return ir, (; entry, compiled) end +# Protect null globals from being killed and inlined +function externalize_julia_globals!(mod::LLVM.Module) + changed = false + for gbl in LLVM.globals(mod) + if LLVM.linkage(gbl) == LLVM.API.LLVMInternalLinkage && + typeof(LLVM.initializer(gbl)) <: LLVM.PointerNull && + (startswith(LLVM.name(gbl), "jl_global") || + startswith(LLVM.name(gbl), "jl_sym")) + LLVM.linkage!(gbl, LLVM.API.LLVMExternalLinkage) + LLVM.initializer!(gbl, nothing) + LLVM.extinit!(gbl, true) + changed = true + end + end + changed +end +# And reset the back later +function internalize_julia_globals!(mod::LLVM.Module) + changed = false + for gbl in LLVM.globals(mod) + if LLVM.linkage(gbl) == LLVM.API.LLVMExternalLinkage && + LLVM.initializer(gbl) === nothing && + (startswith(LLVM.name(gbl), "jl_global") || + startswith(LLVM.name(gbl), "jl_sym")) + LLVM.extinit!(gbl, false) + LLVM.initializer!(gbl, null(eltype(llvmtype(gbl)))) + LLVM.linkage!(gbl, LLVM.API.LLVMInternalLinkage) + changed = true + end + end + changed +end + @locked function emit_asm(@nospecialize(job::CompilerJob), ir::LLVM.Module; strip::Bool=false, validate::Bool=true, format::LLVM.API.LLVMCodeGenFileType) finish_module!(job, ir) diff --git a/src/mcgen.jl b/src/mcgen.jl index ba28e787..404abb39 100644 --- a/src/mcgen.jl +++ b/src/mcgen.jl @@ -7,11 +7,15 @@ function prepare_execution!(@nospecialize(job::CompilerJob), mod::LLVM.Module) global current_job current_job = job + add!(pm, ModulePass("ExternalizeJuliaGlobals", + externalize_julia_globals!)) global_optimizer!(pm) add!(pm, ModulePass("ResolveCPUReferences", resolve_cpu_references!)) global_dce!(pm) + add!(pm, ModulePass("InternalizeJuliaGlobals", + internalize_julia_globals!)) strip_dead_prototypes!(pm) run!(pm, mod)