Skip to content

Commit

Permalink
Add LLVM.init_native_target and LLVM.init_all_targets (#15466)
Browse files Browse the repository at this point in the history
LLVM's targets need to be initialized before they can be used. The Crystal compiler does this in `Crystal::Codegen::Target#to_target_machine`, but for external code that uses the LLVM wrappers directly, there is no simple way to do this. This PR adds two convenience methods which are more or less equivalent to LLVM's `LLVMInitializeNativeTarget` and `LLVMInitializeAllTargets`, both static line functions in `llvm-c/Target.h`, except the latter only initializes targets already supported by Crystal itself (e.g. no RISC-V or PowerPC at the moment even if `llvm-config` indicates their availability).
  • Loading branch information
HertzDevil authored Feb 21, 2025
1 parent debc74a commit 3af8697
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
24 changes: 24 additions & 0 deletions src/llvm.cr
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,30 @@ module LLVM
{% end %}
end

def self.init_native_target : Nil
{% if flag?(:i386) || flag?(:x86_64) %}
init_x86
{% elsif flag?(:aarch64) %}
init_aarch64
{% elsif flag?(:arm) %}
init_arm
{% elsif flag?(:wasm32) %}
init_webassembly
{% elsif flag?(:avr) %}
init_avr
{% else %}
{% raise "Unsupported platform" %}
{% end %}
end

def self.init_all_targets : Nil
{% for target in %i(x86 aarch64 arm avr webassembly) %}
{% if LibLLVM::BUILT_TARGETS.includes?(target) %}
init_{{ target.id }}
{% end %}
{% end %}
end

@[Deprecated("This method has no effect")]
def self.start_multithreaded : Bool
if multithreaded?
Expand Down
2 changes: 1 addition & 1 deletion src/llvm/target.cr
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ struct LLVM::Target
end

def self.first : self
first? || raise "No LLVM targets available (did you forget to invoke LLVM.init_x86?)"
first? || raise "No LLVM targets available (did you forget to invoke LLVM.init_native_target?)"
end

def self.first? : self?
Expand Down

0 comments on commit 3af8697

Please sign in to comment.