From c830096d461cdfd47ba16a91da27051c9870ae13 Mon Sep 17 00:00:00 2001 From: Antoni Boucher Date: Thu, 12 Oct 2023 16:55:49 -0400 Subject: [PATCH] WIP: fix endianness of non-native 128-bit integers --- .github/workflows/m68k.yml | 15 ++-- build_sysroot/build_sysroot.sh | 4 +- build_system/src/build.rs | 26 ++++-- build_system/src/config.rs | 27 ++++-- config.sh | 9 +- src/base.rs | 5 +- src/context.rs | 23 +++-- src/int.rs | 150 ++++++++++++++++++++++----------- src/intrinsic/mod.rs | 20 +---- src/lib.rs | 5 +- tests/lang_tests_common.rs | 68 +++++++++------ tests/run/asm.rs | 14 ++- tests/run/int_overflow.rs | 138 +++--------------------------- 13 files changed, 247 insertions(+), 257 deletions(-) diff --git a/.github/workflows/m68k.yml b/.github/workflows/m68k.yml index f643c6849d3..848072af3c2 100644 --- a/.github/workflows/m68k.yml +++ b/.github/workflows/m68k.yml @@ -15,6 +15,8 @@ permissions: env: # Enable backtraces for easier debugging RUST_BACKTRACE: 1 + # TODO: remove when confish.sh is removed. + OVERWRITE_TARGET_TRIPLE: m68k-unknown-linux-gnu jobs: build: @@ -122,6 +124,7 @@ jobs: } EOF mkdir vm + pwd # TODO: remove sudo mount debian-m68k.img vm m68k-unknown-linux-gnu-gcc main.c -o main sudo cp main vm/home/main @@ -140,20 +143,16 @@ jobs: - name: Build run: | - ./y.sh prepare --only-libcore - # TODO: move into prepare command under a flag --cross-patches? - pushd build_sysroot/sysroot_src - git am ../../cross_patches/*.patch - popd - ./build.sh - cargo test + ./y.sh prepare --only-libcore --cross + ./y.sh build --target-triple m68k-unknown-linux-gnu + CG_GCC_TEST_TARGET=m68k-unknown-linux-gnu cargo test ./clean_all.sh - name: Prepare dependencies run: | git config --global user.email "user@example.com" git config --global user.name "User" - ./y.sh prepare + ./y.sh prepare --cross # Compile is a separate step, as the actions-rs/cargo action supports error annotations - name: Compile diff --git a/build_sysroot/build_sysroot.sh b/build_sysroot/build_sysroot.sh index bd5647fe329..c093206f5a1 100755 --- a/build_sysroot/build_sysroot.sh +++ b/build_sysroot/build_sysroot.sh @@ -23,7 +23,9 @@ if [[ "$1" == "--release" ]]; then else sysroot_channel='debug' # TODO: add flags to simplify the case for cross-compilation. - AR="m68k-unknown-linux-gnu-ar" CC="m68k-unknown-linux-gnu-gcc" cargo build --target $TARGET_TRIPLE + # TODO: or remove them completely if not needed. + #AR="m68k-unknown-linux-gnu-ar" CC="m68k-unknown-linux-gnu-gcc" + cargo build --target $TARGET_TRIPLE fi # Copy files to sysroot diff --git a/build_system/src/build.rs b/build_system/src/build.rs index 0428c6b2cda..6dd75f75313 100644 --- a/build_system/src/build.rs +++ b/build_system/src/build.rs @@ -11,7 +11,7 @@ use std::path::Path; struct BuildArg { codegen_release_channel: bool, sysroot_release_channel: bool, - features: Vec, + flags: Vec, gcc_path: String, } @@ -30,12 +30,12 @@ impl BuildArg { "--release" => build_arg.codegen_release_channel = true, "--release-sysroot" => build_arg.sysroot_release_channel = true, "--no-default-features" => { - build_arg.features.push("--no-default-features".to_string()); + build_arg.flags.push("--no-default-features".to_string()); } "--features" => { if let Some(arg) = args.next() { - build_arg.features.push("--features".to_string()); - build_arg.features.push(arg.as_str().into()); + build_arg.flags.push("--features".to_string()); + build_arg.flags.push(arg.as_str().into()); } else { return Err( "Expected a value after `--features`, found nothing".to_string() @@ -46,6 +46,15 @@ impl BuildArg { Self::usage(); return Ok(None); } + "--target-triple" => { + if args.next().is_some() { + // Handled in config.rs. + } else { + return Err( + "Expected a value after `--target-triple`, found nothing".to_string() + ); + } + } arg => return Err(format!("Unknown argument `{}`", arg)), } } @@ -61,6 +70,7 @@ impl BuildArg { --release-sysroot : Build sysroot in release mode --no-default-features : Add `--no-default-features` flag --features [arg] : Add a new feature [arg] + --target-triple [arg] : Set the target triple to [arg] --help : Show this help "# ) @@ -147,8 +157,6 @@ fn build_sysroot( &"build", &"--target", &target_triple, - &"--features", - &"compiler_builtins/c", ], None, Some(env), @@ -196,9 +204,9 @@ fn build_codegen(args: &BuildArg) -> Result<(), String> { } else { env.insert("CHANNEL".to_string(), "debug".to_string()); } - let ref_features = args.features.iter().map(|s| s.as_str()).collect::>(); - for feature in &ref_features { - command.push(feature); + let flags = args.flags.iter().map(|s| s.as_str()).collect::>(); + for flag in &flags { + command.push(flag); } run_command_with_output_and_env(&command, None, Some(&env))?; diff --git a/build_system/src/config.rs b/build_system/src/config.rs index 4f2e33f0f99..e44aee1d101 100644 --- a/build_system/src/config.rs +++ b/build_system/src/config.rs @@ -30,15 +30,32 @@ pub fn set_config( }; let host_triple = get_rustc_host_triple()?; let mut linker = None; - let mut target_triple = host_triple.as_str(); + let mut target_triple = host_triple.clone(); let mut run_wrapper = None; - // FIXME: handle this with a command line flag? - // let mut target_triple = "m68k-unknown-linux-gnu"; + + // We skip binary name and the command. + let mut args = std::env::args().skip(2); + + while let Some(arg) = args.next() { + match arg.as_str() { + "--target-triple" => { + if let Some(arg) = args.next() { + target_triple = arg; + } else { + return Err( + "Expected a value after `--target-triple`, found nothing".to_string() + ); + } + }, + _ => (), + } + } if host_triple != target_triple { if target_triple == "m68k-unknown-linux-gnu" { - target_triple = "mips-unknown-linux-gnu"; - linker = Some("-Clinker=m68k-linux-gcc"); + //target_triple = "mips-unknown-linux-gnu"; + // TODO: only add "-gcc" to the target triple instead of having these conditions? + linker = Some("-Clinker=m68k-unknown-linux-gnu-gcc"); } else if target_triple == "aarch64-unknown-linux-gnu" { // We are cross-compiling for aarch64. Use the correct linker and run tests in qemu. linker = Some("-Clinker=aarch64-linux-gnu-gcc"); diff --git a/config.sh b/config.sh index 8f5676f853a..967ed658b04 100644 --- a/config.sh +++ b/config.sh @@ -20,15 +20,13 @@ else fi HOST_TRIPLE=$(rustc -vV | grep host | cut -d: -f2 | tr -d " ") -#TARGET_TRIPLE=$HOST_TRIPLE -TARGET_TRIPLE="m68k-unknown-linux-gnu" +# TODO: remove $OVERWRITE_TARGET_TRIPLE when config.sh is removed. +TARGET_TRIPLE="${OVERWRITE_TARGET_TRIPLE:-$HOST_TRIPLE}" linker='' RUN_WRAPPER='' if [[ "$HOST_TRIPLE" != "$TARGET_TRIPLE" ]]; then if [[ "$TARGET_TRIPLE" == "m68k-unknown-linux-gnu" ]]; then - #TARGET_TRIPLE="mips-unknown-linux-gnu" - # TODO: figure a better way for the user to do that automatically for any target. linker='-Clinker=m68k-unknown-linux-gnu-gcc' elif [[ "$TARGET_TRIPLE" == "aarch64-unknown-linux-gnu" ]]; then # We are cross-compiling for aarch64. Use the correct linker and run tests in qemu. @@ -61,5 +59,6 @@ export DYLD_LIBRARY_PATH=$LD_LIBRARY_PATH # NOTE: To avoid the -fno-inline errors, use /opt/gcc/bin/gcc instead of cc. # To do so, add a symlink for cc to /opt/gcc/bin/gcc in our PATH. # Another option would be to add the following Rust flag: -Clinker=/opt/gcc/bin/gcc +# TODO: Revert to /opt/gcc/bin +# TODO: seems like this is necessary to build locally. export PATH="/opt/m68k-unknown-linux-gnu/bin:$PATH" -#export TARGET=$TARGET_TRIPLE diff --git a/src/base.rs b/src/base.rs index 201aa1c588f..3152357fe49 100644 --- a/src/base.rs +++ b/src/base.rs @@ -98,8 +98,9 @@ pub fn compile_codegen_unit(tcx: TyCtxt<'_>, cgu_name: Symbol, target_info: Lock .map(|string| &string[1..]) .collect(); - // TODO(antoyo): only set on x86 platforms. - //context.add_command_line_option("-masm=intel"); + if tcx.sess.target.arch == "x86" || tcx.sess.target.arch == "x86_64" { + context.add_command_line_option("-masm=intel"); + } if !disabled_features.contains("avx") && tcx.sess.target.arch == "x86_64" { // NOTE: we always enable AVX because the equivalent of llvm.x86.sse2.cmp.pd in GCC for diff --git a/src/context.rs b/src/context.rs index 1e0a83e67fb..a35ab40bf20 100644 --- a/src/context.rs +++ b/src/context.rs @@ -20,6 +20,7 @@ use rustc_target::abi::{call::FnAbi, HasDataLayout, PointeeInfo, Size, TargetDat use rustc_target::spec::{HasTargetSpec, Target, TlsModel}; use crate::callee::get_fn; +use crate::common::SignType; #[derive(Clone)] pub struct FuncSig<'gcc> { @@ -165,8 +166,15 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { (i128_type, u128_type) } else { - let i128_type = context.new_array_type(None, i64_type, 2); - let u128_type = context.new_array_type(None, u64_type, 2); + let layout = tcx.layout_of(ParamEnv::reveal_all().and(tcx.types.i128)).unwrap(); + let i128_align = layout.align.abi.bytes(); + let layout = tcx.layout_of(ParamEnv::reveal_all().and(tcx.types.u128)).unwrap(); + let u128_align = layout.align.abi.bytes(); + + // TODO(antoyo): re-enable the alignment when libgccjit fixed the issue in + // gcc_jit_context_new_array_constructor (it should not use reinterpret_cast). + let i128_type = context.new_array_type(None, i64_type, 2)/*.get_aligned(i128_align)*/; + let u128_type = context.new_array_type(None, u64_type, 2)/*.get_aligned(u128_align)*/; (i128_type, u128_type) }; @@ -187,8 +195,8 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { let ulonglong_type = context.new_c_type(CType::ULongLong); let sizet_type = context.new_c_type(CType::SizeT); - let isize_type = context.new_c_type(CType::Int); - let usize_type = context.new_c_type(CType::UInt); + let usize_type = sizet_type; + let isize_type = usize_type; let bool_type = context.new_type::(); // TODO(antoyo): only have those assertions on x86_64. @@ -212,7 +220,7 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { functions.insert(builtin.to_string(), context.get_builtin_function(builtin)); } - Self { + let mut cx = Self { check_overflow, codegen_unit, context, @@ -274,7 +282,10 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { pointee_infos: Default::default(), structs_as_pointer: Default::default(), cleanup_blocks: Default::default(), - } + }; + // TODO(antoyo): instead of doing this, add SsizeT to libgccjit. + cx.isize_type = usize_type.to_signed(&cx); + cx } pub fn rvalue_as_function(&self, value: RValue<'gcc>) -> Function<'gcc> { diff --git a/src/int.rs b/src/int.rs index 5719f6a8cf5..e6481d6bfc9 100644 --- a/src/int.rs +++ b/src/int.rs @@ -7,7 +7,9 @@ use std::convert::TryFrom; use gccjit::{ComparisonOp, FunctionType, RValue, ToRValue, Type, UnaryOp, BinaryOp}; use rustc_codegen_ssa::common::{IntPredicate, TypeKind}; use rustc_codegen_ssa::traits::{BackendTypes, BaseTypeMethods, BuilderMethods, OverflowOp}; -use rustc_middle::ty::Ty; +use rustc_middle::ty::{ParamEnv, Ty}; +use rustc_target::abi::{Endian, call::{ArgAbi, ArgAttributes, Conv, FnAbi, PassMode}}; +use rustc_target::spec; use crate::builder::ToGccComp; use crate::{builder::Builder, common::{SignType, TypeReflection}, context::CodegenCx}; @@ -37,11 +39,10 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { } else { let element_type = typ.dyncast_array().expect("element type"); - let values = [ + self.from_low_high_rvalues(typ, self.cx.context.new_unary_op(None, UnaryOp::BitwiseNegate, element_type, self.low(a)), self.cx.context.new_unary_op(None, UnaryOp::BitwiseNegate, element_type, self.high(a)), - ]; - self.cx.context.new_array_constructor(None, typ, &values) + ) } } @@ -110,11 +111,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { else { zero }; - let values = [ - high >> shift_value, - sign, - ]; - let array_value = self.context.new_array_constructor(None, a_type, &values); + let array_value = self.from_low_high_rvalues(a_type, high >> shift_value, sign); then_block.add_assignment(None, result, array_value); then_block.end_with_jump(None, after_block); @@ -130,11 +127,10 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let casted_low = self.context.new_cast(None, self.low(a), unsigned_type); let shifted_low = casted_low >> self.context.new_cast(None, b, unsigned_type); let shifted_low = self.context.new_cast(None, shifted_low, native_int_type); - let values = [ + let array_value = self.from_low_high_rvalues(a_type, (high << shift_value) | shifted_low, high >> b, - ]; - let array_value = self.context.new_array_constructor(None, a_type, &values); + ); actual_else_block.add_assignment(None, result, array_value); actual_else_block.end_with_jump(None, after_block); @@ -314,18 +310,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { _ => unreachable!(), }, }; - let a_type = lhs.get_type(); - let b_type = rhs.get_type(); - let param_a = self.context.new_parameter(None, a_type, "a"); - let param_b = self.context.new_parameter(None, b_type, "b"); - let result_field = self.context.new_field(None, a_type, "result"); - let overflow_field = self.context.new_field(None, self.bool_type, "overflow"); - let return_type = self.context.new_struct_type(None, "result_overflow", &[result_field, overflow_field]); - let func = self.context.new_function(None, FunctionType::Extern, return_type.as_type(), &[param_a, param_b], func_name, false); - let result = self.context.new_call(None, func, &[lhs, rhs]); - let overflow = result.access_field(None, overflow_field); - let int_result = result.access_field(None, result_field); - return (int_result, overflow); + return self.operation_with_overflow(func_name, lhs, rhs); }, _ => { match oop { @@ -350,6 +335,54 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { (res.dereference(None).to_rvalue(), overflow) } + pub fn operation_with_overflow(&self, func_name: &str, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> (RValue<'gcc>, RValue<'gcc>) { + let a_type = lhs.get_type(); + let b_type = rhs.get_type(); + let param_a = self.context.new_parameter(None, a_type, "a"); + let param_b = self.context.new_parameter(None, b_type, "b"); + let result_field = self.context.new_field(None, a_type, "result"); + let overflow_field = self.context.new_field(None, self.bool_type, "overflow"); + + let ret_ty = Ty::new_tup(self.tcx, &[self.tcx.types.i128, self.tcx.types.bool]); + let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ret_ty)).unwrap(); + + let arg_abi = ArgAbi { + layout, + mode: PassMode::Direct(ArgAttributes::new()), + }; + let mut fn_abi = FnAbi { + args: vec![arg_abi.clone(), arg_abi.clone()].into_boxed_slice(), + ret: arg_abi, + c_variadic: false, + fixed_count: 2, + conv: Conv::C, + can_unwind: false, // TODO: not sure about this one. + }; + fn_abi.adjust_for_foreign_abi(self.cx, spec::abi::Abi::C { + unwind: false, // TODO: not sure about this one. + }).unwrap(); + + let indirect = matches!(fn_abi.ret.mode, PassMode::Indirect { .. }); + + let return_type = self.context.new_struct_type(None, "result_overflow", &[result_field, overflow_field]); + let result = + if indirect { + let return_value = self.current_func().new_local(None, return_type.as_type(), "return_value"); + let return_param_type = return_type.as_type().make_pointer(); + let return_param = self.context.new_parameter(None, return_param_type, "return_value"); + let func = self.context.new_function(None, FunctionType::Extern, self.type_void(), &[return_param, param_a, param_b], func_name, false); + self.llbb().add_eval(None, self.context.new_call(None, func, &[return_value.get_address(None), lhs, rhs])); + return_value.to_rvalue() + } + else { + let func = self.context.new_function(None, FunctionType::Extern, return_type.as_type(), &[param_a, param_b], func_name, false); + self.context.new_call(None, func, &[lhs, rhs]) + }; + let overflow = result.access_field(None, overflow_field); + let int_result = result.access_field(None, result_field); + return (int_result, overflow); + } + pub fn gcc_icmp(&mut self, op: IntPredicate, mut lhs: RValue<'gcc>, mut rhs: RValue<'gcc>) -> RValue<'gcc> { let a_type = lhs.get_type(); let b_type = rhs.get_type(); @@ -468,11 +501,10 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { a ^ b } else { - let values = [ + self.from_low_high_rvalues(a_type, self.low(a) ^ self.low(b), self.high(a) ^ self.high(b), - ]; - self.context.new_array_constructor(None, a_type, &values) + ) } } @@ -519,11 +551,10 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { self.llbb().end_with_conditional(None, condition, then_block, else_block); // TODO(antoyo): take endianness into account. - let values = [ + let array_value = self.from_low_high_rvalues(a_type, zero, self.low(a) << (b - sixty_four), - ]; - let array_value = self.context.new_array_constructor(None, a_type, &values); + ); then_block.add_assignment(None, result, array_value); then_block.end_with_jump(None, after_block); @@ -534,16 +565,16 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { b0_block.end_with_jump(None, after_block); // NOTE: cast low to its unsigned type in order to perform a logical right shift. + // TODO: adjust this ^ comment. let unsigned_type = native_int_type.to_unsigned(&self.cx); let casted_low = self.context.new_cast(None, self.low(a), unsigned_type); let shift_value = self.context.new_cast(None, sixty_four - b, unsigned_type); let high_low = self.context.new_cast(None, casted_low >> shift_value, native_int_type); - let values = [ + + let array_value = self.from_low_high_rvalues(a_type, self.low(a) << b, (self.high(a) << b) | high_low, - ]; - - let array_value = self.context.new_array_constructor(None, a_type, &values); + ); actual_else_block.add_assignment(None, result, array_value); actual_else_block.end_with_jump(None, after_block); @@ -559,16 +590,16 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let arg_type = arg.get_type(); if !self.is_native_int_type(arg_type) { let native_int_type = arg_type.dyncast_array().expect("get element type"); - let lsb = self.context.new_array_access(None, arg, self.context.new_rvalue_from_int(self.int_type, 0)).to_rvalue(); + let lsb = self.low(arg); let swapped_lsb = self.gcc_bswap(lsb, width / 2); let swapped_lsb = self.context.new_cast(None, swapped_lsb, native_int_type); - let msb = self.context.new_array_access(None, arg, self.context.new_rvalue_from_int(self.int_type, 1)).to_rvalue(); + let msb = self.high(arg); let swapped_msb = self.gcc_bswap(msb, width / 2); let swapped_msb = self.context.new_cast(None, swapped_msb, native_int_type); // NOTE: we also need to swap the two elements here, in addition to swapping inside // the elements themselves like done above. - return self.context.new_array_constructor(None, arg_type, &[swapped_msb, swapped_lsb]); + return self.from_low_high_rvalues(arg_type, swapped_msb, swapped_lsb); } // TODO(antoyo): check if it's faster to use string literals and a @@ -672,11 +703,10 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { else { assert!(!a_native && !b_native, "both types should either be native or non-native for or operation"); let native_int_type = a_type.dyncast_array().expect("get element type"); - let values = [ + self.from_low_high_rvalues(a_type, self.context.new_binary_op(None, operation, native_int_type, self.low(a), self.low(b)), self.context.new_binary_op(None, operation, native_int_type, self.high(a), self.high(b)), - ]; - self.context.new_array_constructor(None, a_type, &values) + ) } } @@ -700,11 +730,10 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { let zero = self.context.new_rvalue_zero(value_type); let is_negative = self.context.new_comparison(None, ComparisonOp::LessThan, value, zero); let is_negative = self.gcc_int_cast(is_negative, dest_element_type); - let values = [ + self.from_low_high_rvalues(dest_typ, self.context.new_cast(None, value, dest_element_type), self.context.new_unary_op(None, UnaryOp::Minus, dest_element_type, is_negative), - ]; - self.context.new_array_constructor(None, dest_typ, &values) + ) } else { // Since u128 and i128 are the only types that can be unsupported, we know the type of @@ -782,20 +811,47 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { } fn high(&self, value: RValue<'gcc>) -> RValue<'gcc> { - self.context.new_array_access(None, value, self.context.new_rvalue_from_int(self.int_type, 1)) + let index = + match self.sess().target.options.endian { + Endian::Little => 1, + Endian::Big => 0, + }; + self.context.new_array_access(None, value, self.context.new_rvalue_from_int(self.int_type, index)) .to_rvalue() } fn low(&self, value: RValue<'gcc>) -> RValue<'gcc> { - self.context.new_array_access(None, value, self.context.new_rvalue_from_int(self.int_type, 0)) + let index = + match self.sess().target.options.endian { + Endian::Little => 0, + Endian::Big => 1, + }; + self.context.new_array_access(None, value, self.context.new_rvalue_from_int(self.int_type, index)) .to_rvalue() } + fn from_low_high_rvalues(&self, typ: Type<'gcc>, low: RValue<'gcc>, high: RValue<'gcc>) -> RValue<'gcc> { + let (first, last) = + match self.sess().target.options.endian { + Endian::Little => (low, high), + Endian::Big => (high, low), + }; + + let values = [first, last]; + self.context.new_array_constructor(None, typ, &values) + } + fn from_low_high(&self, typ: Type<'gcc>, low: i64, high: i64) -> RValue<'gcc> { + let (first, last) = + match self.sess().target.options.endian { + Endian::Little => (low, high), + Endian::Big => (high, low), + }; + let native_int_type = typ.dyncast_array().expect("get element type"); let values = [ - self.context.new_rvalue_from_long(native_int_type, low), - self.context.new_rvalue_from_long(native_int_type, high), + self.context.new_rvalue_from_long(native_int_type, first), + self.context.new_rvalue_from_long(native_int_type, last), ]; self.context.new_array_constructor(None, typ, &values) } diff --git a/src/intrinsic/mod.rs b/src/intrinsic/mod.rs index 69927b28cd5..bfe27c0552f 100644 --- a/src/intrinsic/mod.rs +++ b/src/intrinsic/mod.rs @@ -930,15 +930,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { 128 => "__rust_i128_addo", _ => unreachable!(), }; - let param_a = self.context.new_parameter(None, result_type, "a"); - let param_b = self.context.new_parameter(None, result_type, "b"); - let result_field = self.context.new_field(None, result_type, "result"); - let overflow_field = self.context.new_field(None, self.bool_type, "overflow"); - let return_type = self.context.new_struct_type(None, "result_overflow", &[result_field, overflow_field]); - let func = self.context.new_function(None, FunctionType::Extern, return_type.as_type(), &[param_a, param_b], func_name, false); - let result = self.context.new_call(None, func, &[lhs, rhs]); - let overflow = result.access_field(None, overflow_field); - let int_result = result.access_field(None, result_field); + let (int_result, overflow) = self.operation_with_overflow(func_name, lhs, rhs); self.llbb().add_assignment(None, res, int_result); overflow }; @@ -1000,15 +992,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { 128 => "__rust_i128_subo", _ => unreachable!(), }; - let param_a = self.context.new_parameter(None, result_type, "a"); - let param_b = self.context.new_parameter(None, result_type, "b"); - let result_field = self.context.new_field(None, result_type, "result"); - let overflow_field = self.context.new_field(None, self.bool_type, "overflow"); - let return_type = self.context.new_struct_type(None, "result_overflow", &[result_field, overflow_field]); - let func = self.context.new_function(None, FunctionType::Extern, return_type.as_type(), &[param_a, param_b], func_name, false); - let result = self.context.new_call(None, func, &[lhs, rhs]); - let overflow = result.access_field(None, overflow_field); - let int_result = result.access_field(None, result_field); + let (int_result, overflow) = self.operation_with_overflow(func_name, lhs, rhs); self.llbb().add_assignment(None, res, int_result); overflow }; diff --git a/src/lib.rs b/src/lib.rs index 3f35746182c..2355cd1f696 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -241,8 +241,9 @@ impl ExtraBackendMethods for GccCodegenBackend { temp_dir: None, }; - // TODO(antoyo): only set for x86. - //mods.context.add_command_line_option("-masm=intel"); + if tcx.sess.target.arch == "x86" || tcx.sess.target.arch == "x86_64" { + mods.context.add_command_line_option("-masm=intel"); + } unsafe { allocator::codegen(tcx, &mut mods, module_name, kind, alloc_error_handler_kind); } mods } diff --git a/tests/lang_tests_common.rs b/tests/lang_tests_common.rs index 275dd4a4536..4dcf7c0008d 100644 --- a/tests/lang_tests_common.rs +++ b/tests/lang_tests_common.rs @@ -2,7 +2,7 @@ use std::{ env::{self, current_dir}, path::PathBuf, - process::Command, + process::{self, Command}, }; use lang_tester::LangTester; @@ -51,12 +51,17 @@ pub fn main_inner(profile: Profile) { path.to_str().expect("to_str"), ]); - // TODO: allow setting this with a CLI arg (or environment variable if not possible). - compiler.args(&["--target", "m68k-unknown-linux-gnu"]); - compiler.args(&["-Clinker=m68k-unknown-linux-gnu-gcc"]); - let mut env_path = std::env::var("PATH").unwrap_or_default(); - env_path = format!("/opt/m68k-unknown-linux-gnu/bin:{}", env_path); - compiler.env("PATH", env_path); + // TODO(antoyo): find a way to send this via a cli argument. + let test_target = std::env::var("CG_GCC_TEST_TARGET"); + if let Ok(ref target) = test_target { + compiler.args(&["--target", &target]); + let linker = format!("{}-gcc", target); + compiler.args(&[format!("-Clinker={}", linker)]); + let mut env_path = std::env::var("PATH").unwrap_or_default(); + // TODO(antoyo): find a better way to add the PATH necessary locally. + env_path = format!("/opt/m68k-unknown-linux-gnu/bin:{}", env_path); + compiler.env("PATH", env_path); + } if let Some(flags) = option_env!("TEST_FLAGS") { for flag in flags.split_whitespace() { @@ -73,25 +78,38 @@ pub fn main_inner(profile: Profile) { } } // Test command 2: run `tempdir/x`. - let vm_parent_dir = "/home/bouanto/Ordinateur/VirtualMachines"; - let vm_dir = "debian-m68k-root-img/"; - let exe_filename = exe.file_name().unwrap(); - let vm_exe_path = PathBuf::from(vm_parent_dir).join(vm_dir).join("home").join(exe_filename); - // FIXME: panicking here makes the test pass. - let inside_vm_exe_path = PathBuf::from("/home").join(&exe_filename); - let mut copy = Command::new("sudo"); - copy.arg("cp"); - copy.args(&[&exe, &vm_exe_path]); + if test_target.is_ok() { + let vm_parent_dir = std::env::var("CG_GCC_VM_DIR") + .map(|dir| PathBuf::from(dir)) + .unwrap_or_else(|_| std::env::current_dir().unwrap()); + let vm_dir = "vm"; + let exe_filename = exe.file_name().unwrap(); + let vm_home_dir = vm_parent_dir.join(vm_dir).join("home"); + //std::fs::create_dir_all(&vm_home_dir).expect("create home directory"); + let vm_exe_path = vm_home_dir.join(exe_filename); + // FIXME: panicking here makes the test pass. + let inside_vm_exe_path = PathBuf::from("/home").join(&exe_filename); + let mut copy = Command::new("sudo"); + copy.arg("cp"); + copy.args(&[&exe, &vm_exe_path]); - let mut runtime = Command::new("sudo"); - runtime.args(&["chroot", vm_dir, "qemu-m68k-static"]); - runtime.arg(inside_vm_exe_path); - runtime.current_dir(vm_parent_dir); - vec![ - ("Compiler", compiler), - ("Copy", copy), - ("Run-time", runtime), - ] + let mut runtime = Command::new("sudo"); + runtime.args(&["chroot", vm_dir, "qemu-m68k-static"]); + runtime.arg(inside_vm_exe_path); + runtime.current_dir(vm_parent_dir); + vec![ + ("Compiler", compiler), + ("Copy", copy), + ("Run-time", runtime), + ] + } + else { + let runtime = Command::new(exe); + vec![ + ("Compiler", compiler), + ("Run-time", runtime), + ] + } }) .run(); } diff --git a/tests/run/asm.rs b/tests/run/asm.rs index 507b65ca049..56f2aac3d0a 100644 --- a/tests/run/asm.rs +++ b/tests/run/asm.rs @@ -5,8 +5,10 @@ #![feature(asm_const)] +#[cfg(target_arch="x86_64")] use std::arch::{asm, global_asm}; +#[cfg(target_arch="x86_64")] global_asm!( " .global add_asm @@ -20,6 +22,7 @@ extern "C" { fn add_asm(a: i64, b: i64) -> i64; } +#[cfg(target_arch="x86_64")] pub unsafe fn mem_cpy(dst: *mut u8, src: *const u8, len: usize) { asm!( "rep movsb", @@ -30,7 +33,8 @@ pub unsafe fn mem_cpy(dst: *mut u8, src: *const u8, len: usize) { ); } -fn main() { +#[cfg(target_arch="x86_64")] +fn asm() { unsafe { asm!("nop"); } @@ -173,3 +177,11 @@ fn main() { } assert_eq!(array1, array2); } + +#[cfg(not(target_arch="x86_64"))] +fn asm() { +} + +fn main() { + asm(); +} diff --git a/tests/run/int_overflow.rs b/tests/run/int_overflow.rs index 08fa087fccd..78872159f62 100644 --- a/tests/run/int_overflow.rs +++ b/tests/run/int_overflow.rs @@ -4,138 +4,20 @@ // stdout: Success // status: signal -#![allow(internal_features, unused_attributes)] -#![feature(auto_traits, lang_items, no_core, start, intrinsics, rustc_attrs)] +fn main() { + std::panic::set_hook(Box::new(|_| { + println!("Success"); + std::process::abort(); + })); -#![no_std] -#![no_core] - -/* - * Core - */ - -// Because we don't have core yet. -#[lang = "sized"] -pub trait Sized {} - -#[lang = "copy"] -trait Copy { -} - -impl Copy for isize {} -impl Copy for *mut i32 {} -impl Copy for usize {} -impl Copy for i32 {} -impl Copy for u8 {} -impl Copy for i8 {} - -#[lang = "receiver"] -trait Receiver { -} - -#[lang = "freeze"] -pub(crate) unsafe auto trait Freeze {} - -#[lang = "panic_location"] -struct PanicLocation { - file: &'static str, - line: u32, - column: u32, -} - -mod libc { - #[link(name = "c")] - extern "C" { - pub fn puts(s: *const u8) -> i32; - pub fn fflush(stream: *mut i32) -> i32; - - pub static stdout: *mut i32; - } -} - -mod intrinsics { - extern "rust-intrinsic" { - #[rustc_safe_intrinsic] - pub fn abort() -> !; - } -} - -#[lang = "panic"] -#[track_caller] -#[no_mangle] -pub fn panic(_msg: &'static str) -> ! { - unsafe { - // Panicking is expected iff overflow checking is enabled. - #[cfg(debug_assertions)] - libc::puts("Success\0" as *const str as *const u8); - libc::fflush(libc::stdout); - intrinsics::abort(); - } -} - -#[lang = "add"] -trait Add { - type Output; - - fn add(self, rhs: RHS) -> Self::Output; -} - -impl Add for u8 { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for i8 { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for i32 { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for usize { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -impl Add for isize { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - self + rhs - } -} - -/* - * Code - */ - -#[start] -fn main(mut argc: isize, _argv: *const *const u8) -> isize { - let int = 9223372036854775807isize; - let int = int + argc; // overflow + let arg_count = std::env::args().count(); + let int = isize::MAX; + let _int = int + arg_count as isize; // overflow // If overflow checking is disabled, we should reach here. #[cfg(not(debug_assertions))] unsafe { - libc::puts("Success\0" as *const str as *const u8); - libc::fflush(libc::stdout); - intrinsics::abort(); + println!("Success"); + std::process::abort(); } - - int }