Home:ALL Converter>How to compile nvptx in Rust

How to compile nvptx in Rust

Ask Time:2021-05-20T01:57:49         Author:BoKuToTsuZenU

Json Formatter

I have tried to compile nvptx in Rust with the help of this site. Here is the code I wrote.

use std::time::Duration;
use std::thread::sleep;

#[cfg(target_arch="nvptx")]
fn foo() {
    println!("call");
    use std::arch::nvptx::*;
    unsafe {
        let c = malloc(10);
        sleep(Duration::from_millis(100000));
        free(c);
    }
}


fn main() {
    #[cfg(target_arch="nvptx")]
    foo();
    println!("Hello, world!");
}

I've done my research. I thought it might be possible to compile to nvptx by doing cargo run --target nvptx64-nvidia-cuda. However, when I tried to run it, I received the following error.

error[E0463]: can't find crate for `std`.
  |.
  = note: the `nvptx64-nvidia-cuda` target may not be installed

error: aborting due to previous error

For more information about this error, try `rustc --explain E0463`.
error: could not compile `core_nvptx`.

To learn more, run the command again with --verbose.

So, I set rust to nightly and added a target for nvptx. rustup target add nvptx64-nvidia-cuda. So we added cargo run --target nvptx64-nvidia-cuda. I received the same error as above when I did

postscript

I have created a separate nvptx crate with the following file structure.

├─ Cargo.lock
├─ Cargo.toml
├─ nvptx
│ ├─ Cargo.lock
│ ├─ Cargo.toml
└─ src
└─ lib.rs
r└─ src
    r└─ main.rs

I created a .cargo/config file in the nvptx crate. In it, I wrote the following

[build].
target = "nvptx64-nvidia-cuda".

And here is how the contents of nvptx/src/lib.rs looks

#! [feature(stdsimd)]
#! [no_std] #!

use core::arch::nvptx;
use core::ffi::c_void;

unsafe fn cuda_alloc(size: usize) -> *mut c_void {
    nvptx::malloc(size)
}

unsafe fn cuda_free(ptr: *mut c_void) {
    nvptx::free(ptr);
}

Also, the code in src/main.rs is as follows.

use std::time::Duration;
use std::thread::sleep;

use nvptx::*;

fn foo() {

    println!("call");
    unsafe {
        let ptr = cuda_alloc(10 as usize);
        cuda_free(ptr);
    }
    
}


fn main() {
    foo();
    println!("Hello, world!");
}

When I compiled this, I received the following error.

error[E0432]: unresolved import `core::arch::nvptx`
 --> nvptx/src/lib.rs:4:5
  | use core::arch::nvptx
4 | use core::arch::nvptx;
  | ^^^^^^^^^^^^^^^^^ no `nvptx` in `arch`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0432`.
error: could not compile `nvptx`.

To learn more, run the command again with --verbose.

Rust version: nightly-x86_64-unknown-linux-gnu (default) rustc 1.54.0-nightly (f94942d84 2021-05-19)

Author:BoKuToTsuZenU,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/67608507/how-to-compile-nvptx-in-rust
yy