Skip to content

Implement unwinding #244

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jan 11, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ default = ["master"]
master = ["gccjit/master"]

[dependencies]
gccjit = { git = "https://github.com/antoyo/gccjit.rs" }
#gccjit = { git = "https://github.com/antoyo/gccjit.rs" }

# Local copy.
#gccjit = { path = "../gccjit.rs" }
gccjit = { path = "../gccjit.rs" }

smallvec = { version = "1.6.1", features = ["union", "may_dangle"] }
target-lexicon = "0.10.0"
Expand Down
18 changes: 18 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,26 @@ To print a debug representation of a tree:
debug_tree(expr);
```

(defined in print-tree.h)

To print a debug reprensentation of a gimple struct:

```c
debug_gimple_stmt(gimple_struct)
```

To get the `rustc` command to run in `gdb`, add the `--verbose` flag to `cargo build`.

To have the correct file paths in `gdb` instead of `/usr/src/debug/gcc/libstdc++-v3/libsupc++/eh_personality.cc`, TODO

Maybe by calling the following at the beginning of gdb:

```
set substitute-path /usr/src/debug/gcc /home/bouanto/Ordinateur/Programmation/Projets/gcc-repo/gcc
```

TODO: but that's not what I remember I was doing.

### How to use a custom-build rustc

* Build the stage2 compiler (`rustup toolchain link debug-current build/x86_64-unknown-linux-gnu/stage2`).
Expand Down
2 changes: 1 addition & 1 deletion build_sysroot/build_sysroot.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ rm Cargo.lock test_target/Cargo.lock 2>/dev/null || true
rm -r sysroot/ 2>/dev/null || true

# Build libs
export RUSTFLAGS="$RUSTFLAGS -Z force-unstable-if-unmarked -Cpanic=abort"
export RUSTFLAGS="$RUSTFLAGS -Z force-unstable-if-unmarked"
if [[ "$1" == "--release" ]]; then
sysroot_channel='release'
RUSTFLAGS="$RUSTFLAGS -Zmir-opt-level=3" cargo build --target $TARGET_TRIPLE --release
Expand Down
2 changes: 1 addition & 1 deletion config.sh
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ if [[ "$HOST_TRIPLE" != "$TARGET_TRIPLE" ]]; then
fi
fi

export RUSTFLAGS="$CG_RUSTFLAGS $linker -Cpanic=abort -Csymbol-mangling-version=v0 -Cdebuginfo=2 -Clto=off -Zpanic-abort-tests -Zcodegen-backend=$(pwd)/target/${CHANNEL:-debug}/librustc_codegen_gcc.$dylib_ext --sysroot $(pwd)/build_sysroot/sysroot"
export RUSTFLAGS="$CG_RUSTFLAGS $linker -Csymbol-mangling-version=v0 -Cdebuginfo=2 -Clto=off -Zcodegen-backend=$(pwd)/target/${CHANNEL:-debug}/librustc_codegen_gcc.$dylib_ext --sysroot $(pwd)/build_sysroot/sysroot"

# FIXME(antoyo): remove once the atomic shim is gone
if [[ `uname` == 'Darwin' ]]; then
Expand Down
5 changes: 2 additions & 3 deletions src/asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,8 +352,7 @@ impl<'a, 'gcc, 'tcx> AsmBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tcx> {
inputs.push(AsmInOperand {
constraint: "X".into(),
rust_idx,
val: self.cx.rvalue_as_function(get_fn(self.cx, instance))
.get_address(None),
val: get_fn(self.cx, instance, false).get_address(None),
});
}

Expand Down Expand Up @@ -739,7 +738,7 @@ impl<'gcc, 'tcx> AsmMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
}

GlobalAsmOperandRef::SymFn { instance } => {
let function = self.rvalue_as_function(get_fn(self, instance));
let function = get_fn(self, instance, false);
self.add_used_function(function);
// TODO(@Amanieu): Additional mangling is needed on
// some targets to add a leading underscore (Mach-O)
Expand Down
11 changes: 11 additions & 0 deletions src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ pub fn compile_codegen_unit<'tcx>(tcx: TyCtxt<'tcx>, cgu_name: Symbol, supports_
// Instantiate monomorphizations without filling out definitions yet...
//let llvm_module = ModuleLlvm::new(tcx, &cgu_name.as_str());
let context = Context::default();

context.add_command_line_option("-fexceptions");
context.add_driver_option("-fexceptions");

/*context.add_command_line_option("-fasynchronous-unwind-tables");
context.add_driver_option("-fasynchronous-unwind-tables");

context.add_command_line_option("-funwind-tables");
context.add_driver_option("-funwind-tables");*/

// TODO(antoyo): only set on x86 platforms.
context.add_command_line_option("-masm=intel");
// TODO(antoyo): only add the following cli argument if the feature is supported.
Expand Down Expand Up @@ -147,6 +157,7 @@ pub fn compile_codegen_unit<'tcx>(tcx: TyCtxt<'tcx>, cgu_name: Symbol, supports_
}

// TODO(bjorn3): Remove once unwinding is properly implemented
// TODO: remove.
context.set_allow_unreachable_blocks(true);

{
Expand Down
99 changes: 82 additions & 17 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use gccjit::{
RValue,
ToRValue,
Type,
UnaryOp,
UnaryOp, FunctionType,
};
use rustc_codegen_ssa::MemFlags;
use rustc_codegen_ssa::common::{AtomicOrdering, AtomicRmwBinOp, IntPredicate, RealPredicate, SynchronizationScope};
Expand Down Expand Up @@ -372,10 +372,11 @@ impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
}
}

impl<'gcc, 'tcx> Deref for Builder<'_, 'gcc, 'tcx> {
impl<'a, 'gcc, 'tcx> Deref for Builder<'a, 'gcc, 'tcx> {
type Target = CodegenCx<'gcc, 'tcx>;

fn deref(&self) -> &Self::Target {
fn deref<'b>(&'b self) -> &'a Self::Target
{
self.cx
}
}
Expand All @@ -393,7 +394,7 @@ impl<'gcc, 'tcx> BackendTypes for Builder<'_, 'gcc, 'tcx> {
}

impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> {
fn build(cx: &'a CodegenCx<'gcc, 'tcx>, block: Block<'gcc>) -> Self {
fn build(cx: &'a CodegenCx<'gcc, 'tcx>, block: Block<'gcc>) -> Builder<'a, 'gcc, 'tcx> {
Builder::with_cx(cx, block)
}

Expand Down Expand Up @@ -450,8 +451,43 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> {
self.block.end_with_switch(None, value, default_block, &gcc_cases);
}

#[cfg(feature="master")]
fn invoke(&mut self, typ: Type<'gcc>, func: RValue<'gcc>, args: &[RValue<'gcc>], then: Block<'gcc>, catch: Block<'gcc>, _funclet: Option<&Funclet>) -> RValue<'gcc> {
let try_block = self.current_func().new_block("try");

let current_block = self.block.clone();
self.block = try_block;
let call = self.call(typ, func, args, None); // TODO: use funclet here?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Funclets are only for implementing SEH unwinding on Windows. GCC may or may not generate them automatically behind the scenes (in which case cg_ssa should be changed to not use funclets with GCC), but LLVM requires explicitly using them instead of landing pads when using SEH. In case you didn't know, funclets are kind of functions, except that they share the stack frame with another function. In SEH a funclet is called by the unwinder for every frame that needs cleanup, unlike on Unix where the unwinder moves the IP to a landingpad and then returns, the landingpad then tail calls back into the unwinder to continue with the next frame.

self.block = current_block;

let return_value = self.current_func()
.new_local(None, call.get_type(), "invokeResult");

try_block.add_assignment(None, return_value, call);

try_block.end_with_jump(None, then);

if self.cleanup_blocks.borrow().contains(&catch) {
self.block.add_try_finally(None, try_block, catch);
}
else {
// FIXME: FIXME: FIXME: Seems like bad (_URC_NO_REASON) return code, perhaps because the cleanup pad was created properly.
println!("Try/catch in {:?}", self.current_func());
self.block.add_try_catch(None, try_block, catch);
}

self.block.end_with_jump(None, then);

// NOTE: since jumps were added in a place rustc does not expect, the current blocks in the
// state need to be updated.
// FIXME: not sure it's actually needed.
self.switch_to_block(then);

return_value.to_rvalue()
}

#[cfg(not(feature="master"))]
fn invoke(&mut self, typ: Type<'gcc>, func: RValue<'gcc>, args: &[RValue<'gcc>], then: Block<'gcc>, catch: Block<'gcc>, _funclet: Option<&Funclet>) -> RValue<'gcc> {
// TODO(bjorn3): Properly implement unwinding.
let call_site = self.call(typ, func, args, None);
let condition = self.context.new_rvalue_from_int(self.bool_type, 1);
self.llbb().end_with_conditional(None, condition, then, catch);
Expand Down Expand Up @@ -1160,23 +1196,52 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> {
aggregate_value
}

fn set_personality_fn(&mut self, _personality: RValue<'gcc>) {
// TODO(antoyo)
fn set_personality_fn(&mut self, personality: RValue<'gcc>) {
let personality = self.rvalue_as_function(personality); // FIXME: why calling
//rvalue_as_function doesn't work?
//let personality = unsafe { std::mem::transmute(personality) };
#[cfg(feature="master")]
self.current_func().set_personality_function(personality);
// FIXME: rustc manages to generate the symbol DW.ref.rust_eh_personality multiple times
// for the same asm file, which causes an assembler error.
}

fn cleanup_landing_pad(&mut self, _ty: Type<'gcc>, _pers_fn: RValue<'gcc>) -> RValue<'gcc> {
let field1 = self.context.new_field(None, self.u8_type.make_pointer(), "landing_pad_field_1");
let field2 = self.context.new_field(None, self.i32_type, "landing_pad_field_1");
fn cleanup_landing_pad(&mut self, _ty: Type<'gcc>, pers_fn: RValue<'gcc>) -> RValue<'gcc> {
self.set_personality_fn(pers_fn);

/*
* Matching GCC exception handling with LLVM:
*
* GCC LLVM
* CATCH_EXPR landing pad catch clause
* TRY_FINALLY_EXPR cleanup
*/

self.cleanup_blocks.borrow_mut().insert(self.block);

let eh_pointer_builtin = self.cx.context.get_target_builtin_function("__builtin_eh_pointer");
let zero = self.cx.context.new_rvalue_zero(self.int_type);
let ptr = self.cx.context.new_call(None, eh_pointer_builtin, &[zero]);

let field1_type = self.u8_type.make_pointer();
let field1 = self.context.new_field(None, field1_type, "landing_pad_field_1");
let field2 = self.context.new_field(None, self.i32_type, "landing_pad_field_2");
let struct_type = self.context.new_struct_type(None, "landing_pad", &[field1, field2]);
self.current_func().new_local(None, struct_type.as_type(), "landing_pad")
.to_rvalue()
// TODO(antoyo): Properly implement unwinding.
// the above is just to make the compilation work as it seems
// rustc_codegen_ssa now calls the unwinding builder methods even on panic=abort.
let value = self.current_func().new_local(None, struct_type.as_type(), "landing_pad");
let ptr = self.cx.context.new_cast(None, ptr, field1_type);
self.block.add_assignment(None, value.access_field(None, field1), ptr);
self.block.add_assignment(None, value.access_field(None, field2), zero); // TODO: set the proper value here (the type of exception?).

value.to_rvalue()
}

fn resume(&mut self, _exn: RValue<'gcc>) {
// TODO(bjorn3): Properly implement unwinding.
fn resume(&mut self, exn: RValue<'gcc>) {
// TODO: check if this is normal that we need to dereference the value.
let exn = exn.dereference(None).to_rvalue();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

exn here should be a struct forming a pair with the same values as the landing pad returned. By the way in the latest rustc I changed cleanup_landing_pad and resume to return/accept two separate values rather than a single pair value.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I haven't sync with rustc for a while because I was having issues. I'll try to do it soon.

let param = self.context.new_parameter(None, exn.get_type(), "exn");
// TODO(antoyo): should we call __builtin_unwind_resume instead? This might actually be the same.
let unwind_resume = self.context.new_function(None, FunctionType::Extern, self.type_void(), &[param], "_Unwind_Resume", false);
self.llbb().add_eval(None, self.context.new_call(None, unwind_resume, &[exn]));
self.unreachable();
}

Expand Down
24 changes: 15 additions & 9 deletions src/callee.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#[cfg(feature="master")]
use gccjit::{FnAttribute, Visibility};
use gccjit::{FunctionType, RValue};
use gccjit::{FunctionType, RValue, Function};
use rustc_codegen_ssa::traits::BaseTypeMethods;
use rustc_middle::ty::{self, Instance, TypeVisitable};
use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt};
Expand All @@ -16,22 +16,24 @@ use crate::context::CodegenCx;
///
/// - `cx`: the crate context
/// - `instance`: the instance to be instantiated
pub fn get_fn<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, instance: Instance<'tcx>) -> RValue<'gcc> {
pub fn get_fn<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, instance: Instance<'tcx>, dont_cache: bool) -> Function<'gcc> {
let tcx = cx.tcx();

assert!(!instance.substs.needs_infer());
assert!(!instance.substs.has_escaping_bound_vars());

let sym = tcx.symbol_name(instance).name;

if let Some(&func) = cx.function_instances.borrow().get(&instance) {
return func;
}

let sym = tcx.symbol_name(instance).name;

let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());

let func =
if let Some(func) = cx.get_declared_value(&sym) {
unreachable!();
/*
// Create a fn pointer with the new signature.
let ptrty = fn_abi.ptr_to_gcc_type(cx);

Expand Down Expand Up @@ -64,11 +66,14 @@ pub fn get_fn<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, instance: Instance<'tcx>)
}
else {
func
}
}*/
}
else {
cx.linkage.set(FunctionType::Extern);
let func = cx.declare_fn(&sym, &fn_abi);
/*if sym == "rust_eh_personality" {
panic!();
}*/
let func = cx.declare_fn(&sym, &fn_abi, dont_cache);

attributes::from_fn_attrs(cx, func, instance);

Expand Down Expand Up @@ -163,11 +168,12 @@ pub fn get_fn<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, instance: Instance<'tcx>)
}
}

// FIXME(antoyo): this is a wrong cast. That requires changing the compiler API.
unsafe { std::mem::transmute(func) }
func
};

cx.function_instances.borrow_mut().insert(instance, func);
//if !dont_cache {
cx.function_instances.borrow_mut().insert(instance, func);
//}

func
}
Loading