cranelift_ruby 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d1487b62468b109e4245cee90074f2372c2cb7abeecf33275bdce071fef1e220
4
+ data.tar.gz: 91d1a096961545faf0ba4da70a19a58b1a395c4b0419303ce6abafbd8ee49a80
5
+ SHA512:
6
+ metadata.gz: b56586435590db7e090b14b372bceeb32fd9c41955a4528dea99d6ce77413278d150b4c80e681a843c50d29cb7573e91f199ed2323f4611b5c92d13fc173b669
7
+ data.tar.gz: ce719fe18e79a14de52bab14745ceeae9cda0cadf9f9ac597cc8792dc729a7c059cc3039d93f7b92fc831abcf55b9406f2dbad2eabadfd789d059d28a7ec459c
@@ -0,0 +1,21 @@
1
+ name: Ruby
2
+
3
+ on: [push,pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+ - name: Install latest nightly
11
+ uses: actions-rs/toolchain@v1
12
+ with:
13
+ toolchain: stable
14
+ override: true
15
+ - name: Set up Ruby
16
+ uses: ruby/setup-ruby@v1
17
+ with:
18
+ ruby-version: 3.0
19
+ bundler-cache: true
20
+ - name: Run the default task
21
+ run: bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,15 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+
11
+ # Added by cargo
12
+
13
+ /target
14
+ Cargo.lock
15
+ Gemfile.lock
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.7
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2021-07-20
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at marco.rudilosso@shopify.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Cargo.toml ADDED
@@ -0,0 +1,19 @@
1
+ [package]
2
+ name = "cranelift_ruby"
3
+ version = "0.1.0"
4
+ edition = "2018"
5
+
6
+ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7
+
8
+ [dependencies]
9
+ rutie = "0.8"
10
+ cranelift-jit = "0.75.0"
11
+ cranelift = "0.75.0"
12
+ cranelift-module = "0.75.0"
13
+ cranelift-native = "0.75.0"
14
+ eyre = "0.6.5"
15
+ lazy_static = "1"
16
+
17
+ [lib]
18
+ name = "cranelift_ruby"
19
+ crate-type = ["cdylib"]
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in cranelift_ruby.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "minitest", "~> 5.0"
11
+
12
+ gem "rubocop", "~> 1.7"
data/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # Cranelift::Ruby
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/cranelift/ruby`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'cranelift_ruby'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install cranelift_ruby
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/cranelift_ruby. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/cranelift_ruby/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## Code of Conduct
38
+
39
+ Everyone interacting in the Cranelift::Ruby project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/cranelift_ruby/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rbconfig"
4
+ require "bundler/gem_tasks"
5
+ require "rake/testtask"
6
+
7
+ # Mac OS with rbenv users keep leaving behind build artifacts from
8
+ # when they tried to build against a statically linked Ruby and then
9
+ # try against a dynamically linked one causing errors in the build result.
10
+ desc "Preventative work"
11
+ task :tidy_up do
12
+ sh "cargo clean"
13
+ end
14
+
15
+ desc "Build Rust extension"
16
+ task :build_lib do
17
+ sh "cargo build --release"
18
+ end
19
+
20
+ desc "bundle install"
21
+ task :bundle_install do
22
+ sh "bundle install"
23
+ end
24
+
25
+ Rake::TestTask.new(test: %i[]) do |t|
26
+ t.libs << "test"
27
+ t.libs << "lib"
28
+ t.test_files = FileList["test/**/*_test.rb"]
29
+ end
30
+
31
+ Rake::TestTask.new(test_clean: %i[tidy_up bundle_install build_lib]) do |t|
32
+ t.libs << "test"
33
+ t.libs << "lib"
34
+ t.test_files = FileList["test/**/*_test.rb"]
35
+ end
36
+
37
+ task default: :test_clean
data/bin/console ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "cranelift_ruby"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ require "irb/completion"
16
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/cranelift_ruby/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "cranelift_ruby"
7
+ spec.version = CraneliftRuby::VERSION
8
+ spec.authors = ["Marco Concetto Rudilosso"]
9
+ spec.email = ["marco.rudilosso@shopify.com"]
10
+
11
+ spec.summary = "Allows using the cranelift compiler to get assembly from IR"
12
+ # spec.description = "TODO: Write a longer description or delete this line."
13
+ # spec.homepage = "TODO: Put your gem's website or public repo URL here."
14
+ spec.required_ruby_version = ">= 2.4.0"
15
+
16
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'https://mygemserver.com'"
17
+
18
+ # spec.metadata["homepage_uri"] = spec.homepage
19
+ # spec.metadata["source_code_uri"] = "TODO: Put your gem's public repo URL here."
20
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
21
+
22
+ # Specify which files should be added to the gem when it is released.
23
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
24
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
25
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
26
+ end
27
+ spec.bindir = "exe"
28
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
29
+ spec.require_paths = ["lib"]
30
+ spec.extensions = %w[Rakefile]
31
+ # Uncomment to register a new dependency of your gem
32
+ # spec.add_dependency "example-gem", "~> 1.0"
33
+ spec.add_dependency 'rutie', '~> 0.0.4'
34
+ # For more information and examples about making a new gem, checkout our
35
+ # guide at: https://bundler.io/guides/creating_gem.html
36
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cranelift_ruby/version"
4
+ require "rutie"
5
+
6
+ module CraneliftRuby
7
+ Rutie.new(:cranelift_ruby).init "Init_cranelift_ruby", __dir__
8
+ end
@@ -0,0 +1,3 @@
1
+ module CraneliftRuby
2
+ VERSION = "0.1.0"
3
+ end
data/src/lib.rs ADDED
@@ -0,0 +1,599 @@
1
+ #[macro_use]
2
+ extern crate rutie;
3
+
4
+ #[macro_use]
5
+ extern crate lazy_static;
6
+
7
+ use std::convert::TryInto;
8
+ use std::num::TryFromIntError;
9
+
10
+ use cranelift::codegen::binemit::{NullStackMapSink, NullTrapSink};
11
+ use cranelift::codegen::ir::{Inst, SigRef};
12
+ use cranelift::codegen::settings::{self, Configurable};
13
+ use cranelift::prelude::*;
14
+ use cranelift_jit::{JITBuilder, JITModule};
15
+ use cranelift_module::{default_libcall_names, FuncId, Linkage, Module};
16
+ use eyre::{eyre, Result};
17
+ use rutie::{
18
+ AnyException, AnyObject, Array, Class, Exception, Integer, NilClass, Object, Proc, RString,
19
+ Symbol, VM,
20
+ };
21
+ class!(Cranelift);
22
+
23
+ pub struct Builder {
24
+ pub module: JITModule,
25
+ }
26
+
27
+ impl Builder {
28
+ fn new() -> Result<Self> {
29
+ let mut flag_builder = settings::builder();
30
+ flag_builder.set("use_colocated_libcalls", "false")?;
31
+ // FIXME set back to true once the x64 backend supports it.
32
+ flag_builder.set("is_pic", "false")?;
33
+ let isa_builder = cranelift_native::builder()
34
+ .map_err(|e| eyre!("Host machine is not supported. Error: {}", e))?;
35
+ let isa = isa_builder.finish(settings::Flags::new(flag_builder));
36
+ Ok(Self {
37
+ module: JITModule::new(JITBuilder::with_isa(isa, default_libcall_names())),
38
+ })
39
+ }
40
+ }
41
+
42
+ wrappable_struct!(Builder, BuilderWrapper, BUILDER_WRAPPER);
43
+
44
+ class!(CraneliftBuilder);
45
+
46
+ methods!(
47
+ CraneliftBuilder,
48
+ itself,
49
+ fn make_signature(params: Array, returns: Array) -> AnyObject {
50
+ let builder = itself.get_data(&*BUILDER_WRAPPER);
51
+ let params = params.map_err(|e| VM::raise_ex(e)).unwrap();
52
+ let returns = returns.map_err(|e| VM::raise_ex(e)).unwrap();
53
+ let sig = make_signature_impl(params, returns, &builder.module)
54
+ .map_err(|e| VM::raise_ex(e))
55
+ .unwrap();
56
+
57
+ Class::from_existing("CraneliftRuby")
58
+ .get_nested_class("Signature")
59
+ .wrap_data(sig, &*SIGNATURE_WRAPPER)
60
+ },
61
+ fn cranelift_builder_new() -> AnyObject {
62
+ let builder = Builder::new()
63
+ .map_err(|e| VM::raise_ex(AnyException::new("StandardError", Some(&e.to_string()))))
64
+ .unwrap();
65
+ Class::from_existing("CraneliftRuby")
66
+ .get_nested_class("CraneliftBuilder")
67
+ .wrap_data(builder, &*BUILDER_WRAPPER)
68
+ },
69
+ fn make_function(name: RString, signature: AnyObject, callback: Proc) -> Integer {
70
+ let builder = itself.get_data_mut(&*BUILDER_WRAPPER);
71
+ let name = name.map_err(|e| VM::raise_ex(e)).unwrap();
72
+ let signature = signature.map_err(|e| VM::raise_ex(e)).unwrap();
73
+ let signature = signature.get_data(&*SIGNATURE_WRAPPER);
74
+ let callback = callback.map_err(|e| VM::raise_ex(e)).unwrap();
75
+ let func_id = make_function_impl(name.to_str(), signature, callback, builder)
76
+ .map_err(|e| VM::raise_ex(e))
77
+ .unwrap();
78
+ Integer::new(func_id.into())
79
+ },
80
+ fn finalize() -> NilClass {
81
+ let builder = itself.get_data_mut(&*BUILDER_WRAPPER);
82
+ builder.module.finalize_definitions();
83
+ NilClass::new()
84
+ },
85
+ fn get_function_pointer(func_id: Integer) -> Integer {
86
+ let builder = itself.get_data_mut(&*BUILDER_WRAPPER);
87
+ let func_id = func_id.map_err(|e| VM::raise_ex(e)).unwrap();
88
+ let func_id = func_id
89
+ .to_i64()
90
+ .try_into()
91
+ .map_err(|_e| {
92
+ VM::raise_ex(AnyException::new(
93
+ "StandardError",
94
+ Some("Could create function id due to bad conversion"),
95
+ ))
96
+ })
97
+ .unwrap();
98
+ let func_id = FuncId::new(func_id);
99
+ Integer::new(builder.module.get_finalized_function(func_id) as i64)
100
+ }
101
+ );
102
+
103
+ fn map_symbol_to_type(symbol: Symbol) -> Result<types::Type, AnyException> {
104
+ let s = symbol.to_str();
105
+ if s == "I8" {
106
+ Ok(types::I8)
107
+ } else if s == "I16" {
108
+ Ok(types::I16)
109
+ } else if s == "I32" {
110
+ Ok(types::I32)
111
+ } else if s == "I64" {
112
+ Ok(types::I64)
113
+ } else {
114
+ Err(AnyException::new(
115
+ "StandardError",
116
+ Some("The type for a param or a return is unknown"),
117
+ ))
118
+ }
119
+ }
120
+
121
+ fn make_signature_impl(
122
+ params: Array,
123
+ returns: Array,
124
+ module: &JITModule,
125
+ ) -> Result<Signature, AnyException> {
126
+ let mut sig = module.make_signature();
127
+ for param in params {
128
+ let param = param.try_convert_to::<Symbol>()?;
129
+ let ty = map_symbol_to_type(param)?;
130
+ sig.params.push(AbiParam::new(ty));
131
+ }
132
+
133
+ for ret in returns {
134
+ let ret = ret.try_convert_to::<Symbol>()?;
135
+ let ty = map_symbol_to_type(ret)?;
136
+ sig.returns.push(AbiParam::new(ty));
137
+ }
138
+ Ok(sig)
139
+ }
140
+
141
+ fn make_function_impl(
142
+ name: &str,
143
+ signature: &Signature,
144
+ callback: Proc,
145
+ builder: &mut Builder,
146
+ ) -> Result<u32, AnyException> {
147
+ let func = builder
148
+ .module
149
+ .declare_function(name, Linkage::Local, &signature)
150
+ .map_err(|e| AnyException::new("StandardError", Some(&e.to_string())))?;
151
+ let mut ctx = builder.module.make_context();
152
+ let mut func_ctx = FunctionBuilderContext::new();
153
+ ctx.func.signature = signature.clone();
154
+ ctx.func.name = ExternalName::user(0, func.as_u32());
155
+ // ctx.set_disasm(true);
156
+ let bcx: FunctionBuilder = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
157
+ let cranelift_bcx: AnyObject = Class::from_existing("CraneliftRuby")
158
+ .get_nested_class("CraneliftFunctionBuilder")
159
+ .wrap_data(bcx, &*FUNCTION_BUILDER_WRAPPER);
160
+ callback.call(&[cranelift_bcx]);
161
+ let mut trap_sink = NullTrapSink {};
162
+ let mut stack_map_sink = NullStackMapSink {};
163
+ // println!("{}", ctx.func.display(None).to_string());
164
+ builder
165
+ .module
166
+ .define_function(func, &mut ctx, &mut trap_sink, &mut stack_map_sink)
167
+ .map_err(|e| AnyException::new("StandardError", Some(&format!("{:?}", e))))?;
168
+ // println!("code: {}", ctx.mach_compile_result.unwrap().disasm.unwrap());
169
+ Ok(func.as_u32())
170
+ }
171
+
172
+ wrappable_struct!(Signature, SignatureWrapper, SIGNATURE_WRAPPER);
173
+ wrappable_struct!(Block, BlockWrapper, BLOCK_WRAPPER);
174
+
175
+ wrappable_struct!(
176
+ FunctionBuilder<'static>,
177
+ FunctionBuilderWrapper,
178
+ FUNCTION_BUILDER_WRAPPER
179
+ );
180
+
181
+ class!(CraneliftFunctionBuilder);
182
+
183
+ methods!(
184
+ CraneliftFunctionBuilder,
185
+ itself,
186
+ fn create_block() -> AnyObject {
187
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
188
+ let block = bcx.create_block();
189
+ Class::from_existing("CraneliftRuby")
190
+ .get_nested_class("Block")
191
+ .wrap_data(block, &*BLOCK_WRAPPER)
192
+ },
193
+ fn append_block_params_for_function_params(block: AnyObject) -> NilClass {
194
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
195
+ let block = block.map_err(|e| VM::raise_ex(e)).unwrap();
196
+ let block = block.get_data(&*BLOCK_WRAPPER);
197
+ bcx.append_block_params_for_function_params(*block);
198
+ NilClass::new()
199
+ },
200
+ fn switch_to_block(block: AnyObject) -> NilClass {
201
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
202
+ let block = block.map_err(|e| VM::raise_ex(e)).unwrap();
203
+ let block = block.get_data(&*BLOCK_WRAPPER);
204
+ bcx.switch_to_block(*block);
205
+ NilClass::new()
206
+ },
207
+ fn declare_var(variable: AnyObject, ty: Symbol) -> NilClass {
208
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
209
+ let variable = variable.map_err(|e| VM::raise_ex(e)).unwrap();
210
+ let variable = variable.get_data(&*VARIABLE_WRAPPER);
211
+ let ty = ty.map_err(|e| VM::raise_ex(e)).unwrap();
212
+ let ty = map_symbol_to_type(ty).map_err(|e| VM::raise_ex(e)).unwrap();
213
+ bcx.declare_var(*variable, ty);
214
+ NilClass::new()
215
+ },
216
+ fn use_var(variable: AnyObject) -> Integer {
217
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
218
+ let variable = variable.map_err(|e| VM::raise_ex(e)).unwrap();
219
+ let variable = variable.get_data(&*VARIABLE_WRAPPER);
220
+ let val = bcx.use_var(*variable);
221
+ Integer::new(val.as_u32().into())
222
+ },
223
+ fn def_var(variable: AnyObject, value: Integer) -> NilClass {
224
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
225
+ let variable = variable.map_err(|e| VM::raise_ex(e)).unwrap();
226
+ let variable = variable.get_data(&*VARIABLE_WRAPPER);
227
+ let value = value.map_err(|e| VM::raise_ex(e)).unwrap();
228
+ let value = from_integer_to_value(value)
229
+ .map_err(|e| VM::raise_ex(e))
230
+ .unwrap();
231
+ bcx.def_var(*variable, value);
232
+ NilClass::new()
233
+ },
234
+ fn block_param(block: AnyObject, index: Integer) -> Integer {
235
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
236
+ let block = block.map_err(|e| VM::raise_ex(e)).unwrap();
237
+ let index = index.map_err(|e| VM::raise_ex(e)).unwrap();
238
+
239
+ let block = block.get_data(&*BLOCK_WRAPPER);
240
+ let param = bcx.block_params(*block)[index.to_u64() as usize];
241
+ Integer::new(param.as_u32().into())
242
+ },
243
+ fn import_signature(signature: AnyObject) -> AnyObject {
244
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
245
+
246
+ let signature = signature.map_err(|e| VM::raise_ex(e)).unwrap();
247
+ let signature = signature.get_data(&*SIGNATURE_WRAPPER);
248
+ let sigref = bcx.import_signature(signature.clone());
249
+ Class::from_existing("CraneliftRuby")
250
+ .get_nested_class("SigRef")
251
+ .wrap_data(sigref, &*SIGREF_WRAPPER)
252
+ }
253
+ fn call_indirect(sigref: AnyObject, callee: Integer, args: Array) -> Integer {
254
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
255
+
256
+ let sigref = sigref.map_err(|e| VM::raise_ex(e)).unwrap();
257
+ let sigref = sigref.get_data(&*SIGREF_WRAPPER);
258
+ let callee = callee.map_err(|e| VM::raise_ex(e)).unwrap();
259
+ let callee = from_integer_to_value(callee).map_err(|e| VM::raise_ex(e)).unwrap();
260
+ let args = args.map_err(|e| VM::raise_ex(e)).unwrap();
261
+ let args = from_array_to_values(args).map_err(|e| VM::raise_ex(e)).unwrap();
262
+ let res = bcx.ins().call_indirect(*sigref, callee, &args);
263
+ Integer::new(res.as_u32().into())
264
+ }
265
+ fn inst_results(inst: Integer) -> Array {
266
+ let mut result = Array::new();
267
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
268
+ let inst = inst.map_err(|e| VM::raise_ex(e)).unwrap();
269
+ let inst = from_integer_to_inst(inst).map_err(|e| VM::raise_ex(e)).unwrap();
270
+ let values = bcx.inst_results(inst);
271
+ for value in values {
272
+ result.push(Integer::new(value.as_u32().into()));
273
+ }
274
+ result
275
+ }
276
+ fn iconst(ty: Symbol, value: Integer) -> Integer {
277
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
278
+ let ty = ty.map_err(|e| VM::raise_ex(e)).unwrap();
279
+ let ty = map_symbol_to_type(ty).map_err(|e| VM::raise_ex(e)).unwrap();
280
+ let value = value.map_err(|e| VM::raise_ex(e)).unwrap();
281
+ let res = bcx.ins().iconst(ty, value.to_i64());
282
+ Integer::new(res.as_u32().into())
283
+ },
284
+ fn load(ty: Symbol, addr: Integer, offset: Integer) -> Integer {
285
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
286
+ let ty = ty.map_err(|e| VM::raise_ex(e)).unwrap();
287
+ let ty = map_symbol_to_type(ty).map_err(|e| VM::raise_ex(e)).unwrap();
288
+ let addr = addr.map_err(|e| VM::raise_ex(e)).unwrap();
289
+ let addr = addr
290
+ .to_u64()
291
+ .try_into()
292
+ .map_err(|e: TryFromIntError| {
293
+ VM::raise_ex(AnyException::new("StandardError", Some(&e.to_string())))
294
+ })
295
+ .unwrap();
296
+ let offset = offset.map_err(|e| VM::raise_ex(e)).unwrap();
297
+ let res = bcx.ins().load(
298
+ ty,
299
+ MemFlags::trusted(),
300
+ Value::from_u32(addr),
301
+ offset.to_i32(),
302
+ );
303
+ Integer::new(res.as_u32().into())
304
+ },
305
+ fn store(value: Integer, addr: Integer, offset: Integer) -> NilClass {
306
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
307
+ let addr = addr.map_err(|e| VM::raise_ex(e)).unwrap();
308
+ let addr = addr
309
+ .to_u64()
310
+ .try_into()
311
+ .map_err(|e: TryFromIntError| {
312
+ VM::raise_ex(AnyException::new("StandardError", Some(&e.to_string())))
313
+ })
314
+ .unwrap();
315
+ let value = value.map_err(|e| VM::raise_ex(e)).unwrap();
316
+ let value = value
317
+ .to_u64()
318
+ .try_into()
319
+ .map_err(|e: TryFromIntError| {
320
+ VM::raise_ex(AnyException::new("StandardError", Some(&e.to_string())))
321
+ })
322
+ .unwrap();
323
+ let offset = offset.map_err(|e| VM::raise_ex(e)).unwrap();
324
+ bcx.ins().store(
325
+ MemFlags::trusted(),
326
+ Value::from_u32(value),
327
+ Value::from_u32(addr),
328
+ offset.to_i32(),
329
+ );
330
+ NilClass::new()
331
+ },
332
+ fn iadd(x: Integer, y: Integer) -> Integer {
333
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
334
+ let x = x.map_err(|e| VM::raise_ex(e)).unwrap();
335
+ let x = from_integer_to_value(x)
336
+ .map_err(|e| VM::raise_ex(e))
337
+ .unwrap();
338
+ let y = y.map_err(|e| VM::raise_ex(e)).unwrap();
339
+ let y = from_integer_to_value(y)
340
+ .map_err(|e| VM::raise_ex(e))
341
+ .unwrap();
342
+
343
+ let res = bcx.ins().iadd(x, y);
344
+ Integer::new(res.as_u32().into())
345
+ },
346
+ fn return_(values: Array) -> NilClass {
347
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
348
+ let values = values.map_err(|e| VM::raise_ex(e)).unwrap();
349
+ let mut return_value: Vec<Value> = from_array_to_values(values)
350
+ .map_err(|e| VM::raise_ex(e))
351
+ .unwrap();
352
+ bcx.ins().return_(&return_value);
353
+ NilClass::new()
354
+ },
355
+ fn jump(block: AnyObject, args: Array) -> NilClass {
356
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
357
+ let block = block.map_err(|e| VM::raise_ex(e)).unwrap();
358
+ let block = block.get_data(&*BLOCK_WRAPPER);
359
+ let args = args.map_err(|e| VM::raise_ex(e)).unwrap();
360
+ let args = from_array_to_values(args)
361
+ .map_err(|e| VM::raise_ex(e))
362
+ .unwrap();
363
+ bcx.ins().jump(*block, &args);
364
+ NilClass::new()
365
+ },
366
+ fn brz(value: Integer, block: AnyObject, args: Array) -> NilClass {
367
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
368
+ let block = block.map_err(|e| VM::raise_ex(e)).unwrap();
369
+ let block = block.get_data(&*BLOCK_WRAPPER);
370
+ let args = args.map_err(|e| VM::raise_ex(e)).unwrap();
371
+ let args = from_array_to_values(args)
372
+ .map_err(|e| VM::raise_ex(e))
373
+ .unwrap();
374
+ let value = value.map_err(|e| VM::raise_ex(e)).unwrap();
375
+ let value = from_integer_to_value(value)
376
+ .map_err(|e| VM::raise_ex(e))
377
+ .unwrap();
378
+ bcx.ins().brz(value, *block, &args);
379
+ NilClass::new()
380
+ },
381
+ fn brnz(value: Integer, block: AnyObject, args: Array) -> NilClass {
382
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
383
+ let block = block.map_err(|e| VM::raise_ex(e)).unwrap();
384
+ let block = block.get_data(&*BLOCK_WRAPPER);
385
+ let args = args.map_err(|e| VM::raise_ex(e)).unwrap();
386
+ let args = from_array_to_values(args)
387
+ .map_err(|e| VM::raise_ex(e))
388
+ .unwrap();
389
+ let value = value.map_err(|e| VM::raise_ex(e)).unwrap();
390
+ let value = from_integer_to_value(value)
391
+ .map_err(|e| VM::raise_ex(e))
392
+ .unwrap();
393
+ bcx.ins().brnz(value, *block, &args);
394
+ NilClass::new()
395
+ },
396
+ fn br_icmp(cond: Symbol, x: Integer, y: Integer, block: AnyObject, args: Array) -> NilClass {
397
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
398
+ let block = block.map_err(|e| VM::raise_ex(e)).unwrap();
399
+ let block = block.get_data(&*BLOCK_WRAPPER);
400
+ let args = args.map_err(|e| VM::raise_ex(e)).unwrap();
401
+ let args = from_array_to_values(args)
402
+ .map_err(|e| VM::raise_ex(e))
403
+ .unwrap();
404
+ let x = x.map_err(|e| VM::raise_ex(e)).unwrap();
405
+ let x = from_integer_to_value(x)
406
+ .map_err(|e| VM::raise_ex(e))
407
+ .unwrap();
408
+ let y = y.map_err(|e| VM::raise_ex(e)).unwrap();
409
+ let y = from_integer_to_value(y)
410
+ .map_err(|e| VM::raise_ex(e))
411
+ .unwrap();
412
+ let cond = cond.map_err(|e| VM::raise_ex(e)).unwrap();
413
+ let cond = from_symbol_to_icc(cond)
414
+ .map_err(|e| VM::raise_ex(e))
415
+ .unwrap();
416
+ bcx.ins().br_icmp(cond, x, y, *block, &args);
417
+ NilClass::new()
418
+ },
419
+ fn icmp(cond: Symbol, x: Integer, y: Integer) -> Integer {
420
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
421
+ let x = x.map_err(|e| VM::raise_ex(e)).unwrap();
422
+ let x = from_integer_to_value(x)
423
+ .map_err(|e| VM::raise_ex(e))
424
+ .unwrap();
425
+ let y = y.map_err(|e| VM::raise_ex(e)).unwrap();
426
+ let y = from_integer_to_value(y)
427
+ .map_err(|e| VM::raise_ex(e))
428
+ .unwrap();
429
+ let cond = cond.map_err(|e| VM::raise_ex(e)).unwrap();
430
+ let cond = from_symbol_to_icc(cond)
431
+ .map_err(|e| VM::raise_ex(e))
432
+ .unwrap();
433
+ let res = bcx.ins().icmp(cond, x, y);
434
+ Integer::new(res.as_u32().into())
435
+ },
436
+ fn select(cond: Integer, x: Integer, y: Integer) -> Integer {
437
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
438
+ let x = x.map_err(|e| VM::raise_ex(e)).unwrap();
439
+ let x = from_integer_to_value(x)
440
+ .map_err(|e| VM::raise_ex(e))
441
+ .unwrap();
442
+ let y = y.map_err(|e| VM::raise_ex(e)).unwrap();
443
+ let y = from_integer_to_value(y)
444
+ .map_err(|e| VM::raise_ex(e))
445
+ .unwrap();
446
+ let cond = cond.map_err(|e| VM::raise_ex(e)).unwrap();
447
+ let cond = from_integer_to_value(cond)
448
+ .map_err(|e| VM::raise_ex(e))
449
+ .unwrap();
450
+ let res = bcx.ins().select(cond, x, y);
451
+ Integer::new(res.as_u32().into())
452
+ },
453
+ fn finalize_function() -> NilClass {
454
+ let bcx = itself.get_data_mut(&*FUNCTION_BUILDER_WRAPPER);
455
+ bcx.seal_all_blocks();
456
+ bcx.finalize();
457
+ NilClass::new()
458
+ }
459
+ );
460
+
461
+ fn from_symbol_to_icc(symbol: Symbol) -> Result<IntCC, AnyException> {
462
+ let s = symbol.to_str();
463
+ if s == "e" {
464
+ Ok(IntCC::Equal)
465
+ } else if s == "ne" {
466
+ Ok(IntCC::NotEqual)
467
+ } else if s == "sg" {
468
+ Ok(IntCC::SignedGreaterThan)
469
+ } else if s == "sge" {
470
+ Ok(IntCC::SignedGreaterThanOrEqual)
471
+ } else if s == "sle" {
472
+ Ok(IntCC::SignedLessThanOrEqual)
473
+ } else if s == "sl" {
474
+ Ok(IntCC::SignedLessThan)
475
+ } else if s == "ug" {
476
+ Ok(IntCC::UnsignedGreaterThan)
477
+ } else if s == "uge" {
478
+ Ok(IntCC::UnsignedGreaterThanOrEqual)
479
+ } else if s == "ule" {
480
+ Ok(IntCC::UnsignedLessThanOrEqual)
481
+ } else if s == "ul" {
482
+ Ok(IntCC::UnsignedLessThan)
483
+ } else if s == "overflow" {
484
+ Ok(IntCC::Overflow)
485
+ } else if s == "not_overflow" {
486
+ Ok(IntCC::NotOverflow)
487
+ } else {
488
+ Err(AnyException::new(
489
+ "StandardError",
490
+ Some("The type for a param or a return is unknown"),
491
+ ))
492
+ }
493
+ }
494
+
495
+ fn from_integer_to_value(i: Integer) -> Result<Value, AnyException> {
496
+ Ok(Value::from_u32(i.to_i32().try_into().map_err(|_e| {
497
+ AnyException::new("StandardError", Some("Could not conver int to u32"))
498
+ })?))
499
+ }
500
+
501
+ fn from_integer_to_inst(i: Integer) -> Result<Inst, AnyException> {
502
+ Ok(Inst::from_u32(i.to_i32().try_into().map_err(|_e| {
503
+ AnyException::new("StandardError", Some("Could not conver int to u32"))
504
+ })?))
505
+ }
506
+
507
+ fn from_array_to_values(array: Array) -> Result<Vec<Value>, AnyException> {
508
+ let mut return_values: Vec<Value> = Vec::new();
509
+ for value in array {
510
+ let value = value.try_convert_to::<Integer>()?;
511
+ let value = value.to_i32().try_into().map_err(|_e| {
512
+ AnyException::new("StandardError", Some("Could not conver int to u32"))
513
+ })?;
514
+ return_values.push(Value::from_u32(value));
515
+ }
516
+ Ok(return_values)
517
+ }
518
+
519
+ wrappable_struct!(Variable, VariableWrapper, VARIABLE_WRAPPER);
520
+ wrappable_struct!(SigRef, SigRefWrapper, SIGREF_WRAPPER);
521
+
522
+
523
+ class!(CraneliftVariable);
524
+
525
+ methods!(
526
+ CraneliftVariable,
527
+ _itself,
528
+ fn new_cranelift_variable(index: Integer) -> AnyObject {
529
+ let index = index.map_err(|e| VM::raise_ex(e)).unwrap();
530
+ let var = Variable::new(
531
+ index
532
+ .to_i64()
533
+ .try_into()
534
+ .map_err(|_e| {
535
+ VM::raise_ex(AnyException::new(
536
+ "StandardError",
537
+ Some("Could not convert to usize"),
538
+ ))
539
+ })
540
+ .unwrap(),
541
+ );
542
+ Class::from_existing("CraneliftRuby")
543
+ .get_nested_class("Variable")
544
+ .wrap_data(var, &*VARIABLE_WRAPPER)
545
+ }
546
+ );
547
+
548
+ #[allow(non_snake_case)]
549
+ #[no_mangle]
550
+ pub extern "C" fn Init_cranelift_ruby() {
551
+ let data_class = Class::from_existing("Object");
552
+ rutie::Module::from_existing("CraneliftRuby").define(|itself| {
553
+ itself
554
+ .define_nested_class("CraneliftBuilder", Some(&data_class))
555
+ .define(|klass| {
556
+ klass.def_self("new", cranelift_builder_new);
557
+ klass.def("make_signature", make_signature);
558
+ klass.def("make_function", make_function);
559
+ klass.def("finalize", finalize);
560
+ klass.def("get_function_pointer", get_function_pointer);
561
+ });
562
+ itself.define_nested_class("Signature", Some(&data_class));
563
+ itself.define_nested_class("SigRef", Some(&data_class));
564
+ itself.define_nested_class("Block", Some(&data_class));
565
+ itself
566
+ .define_nested_class("Variable", Some(&data_class))
567
+ .define(|klass| {
568
+ klass.def_self("new", new_cranelift_variable);
569
+ });
570
+ itself
571
+ .define_nested_class("CraneliftFunctionBuilder", Some(&data_class))
572
+ .define(|klass| {
573
+ klass.def("create_block", create_block);
574
+ klass.def("switch_to_block", switch_to_block);
575
+ klass.def("block_param", block_param);
576
+ klass.def(
577
+ "append_block_params_for_function_params",
578
+ append_block_params_for_function_params,
579
+ );
580
+ klass.def("return", return_);
581
+ klass.def("iconst", iconst);
582
+ klass.def("iadd", iadd);
583
+ klass.def("load", load);
584
+ klass.def("store", store);
585
+ klass.def("jump", jump);
586
+ klass.def("brz", brz);
587
+ klass.def("brnz", brnz);
588
+ klass.def("br_icmp", br_icmp);
589
+ klass.def("finalize", finalize_function);
590
+ klass.def("declare_var", declare_var);
591
+ klass.def("def_var", def_var);
592
+ klass.def("use_var", use_var);
593
+ klass.def("icmp", icmp);
594
+ klass.def("import_signature", import_signature);
595
+ klass.def("call_indirect", call_indirect);
596
+ klass.def("inst_results", inst_results);
597
+ });
598
+ });
599
+ }
metadata ADDED
@@ -0,0 +1,72 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cranelift_ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Marco Concetto Rudilosso
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-07-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rutie
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.0.4
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.0.4
27
+ description:
28
+ email:
29
+ - marco.rudilosso@shopify.com
30
+ executables: []
31
+ extensions:
32
+ - Rakefile
33
+ extra_rdoc_files: []
34
+ files:
35
+ - ".github/workflows/main.yml"
36
+ - ".gitignore"
37
+ - ".rubocop.yml"
38
+ - CHANGELOG.md
39
+ - CODE_OF_CONDUCT.md
40
+ - Cargo.toml
41
+ - Gemfile
42
+ - README.md
43
+ - Rakefile
44
+ - bin/console
45
+ - bin/setup
46
+ - cranelift_ruby.gemspec
47
+ - lib/cranelift_ruby.rb
48
+ - lib/cranelift_ruby/version.rb
49
+ - src/lib.rs
50
+ homepage:
51
+ licenses: []
52
+ metadata: {}
53
+ post_install_message:
54
+ rdoc_options: []
55
+ require_paths:
56
+ - lib
57
+ required_ruby_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 2.4.0
62
+ required_rubygems_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ requirements: []
68
+ rubygems_version: 3.0.3
69
+ signing_key:
70
+ specification_version: 4
71
+ summary: Allows using the cranelift compiler to get assembly from IR
72
+ test_files: []