Skip to content

Commit ceded6a

Browse files
committed
Auto merge of #27210 - vadimcn:win64-eh-pers, r=alexcrichton
After this change, the only remaining symbol we are pulling from libgcc on Win64 is `__chkstk_ms` - the stack probing routine.
2 parents d877e65 + 96d1db2 commit ceded6a

File tree

25 files changed

+667
-237
lines changed

25 files changed

+667
-237
lines changed

src/doc/trpl/lang-items.md

+1
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ fn main(argc: isize, argv: *const *const u8) -> isize {
5454
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
5555
#[lang = "eh_personality"] extern fn eh_personality() {}
5656
#[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
57+
# #[lang = "eh_unwind_resume"] extern fn rust_eh_unwind_resume() {}
5758
```
5859

5960
Note the use of `abort`: the `exchange_malloc` lang item is assumed to

src/doc/trpl/no-stdlib.md

+3
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ fn start(_argc: isize, _argv: *const *const u8) -> isize {
3939
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
4040
#[lang = "eh_personality"] extern fn eh_personality() {}
4141
#[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
42+
# #[lang = "eh_unwind_resume"] extern fn rust_eh_unwind_resume() {}
4243
# // fn main() {} tricked you, rustdoc!
4344
```
4445

@@ -63,6 +64,7 @@ pub extern fn main(argc: i32, argv: *const *const u8) -> i32 {
6364
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
6465
#[lang = "eh_personality"] extern fn eh_personality() {}
6566
#[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
67+
# #[lang = "eh_unwind_resume"] extern fn rust_eh_unwind_resume() {}
6668
# // fn main() {} tricked you, rustdoc!
6769
```
6870

@@ -150,6 +152,7 @@ extern fn panic_fmt(args: &core::fmt::Arguments,
150152
151153
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
152154
#[lang = "eh_personality"] extern fn eh_personality() {}
155+
# #[lang = "eh_unwind_resume"] extern fn rust_eh_unwind_resume() {}
153156
# #[start] fn start(argc: isize, argv: *const *const u8) -> isize { 0 }
154157
# fn main() {}
155158
```

src/librustc/middle/lang_items.rs

+1
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,7 @@ lets_do_this! {
327327

328328
EhPersonalityLangItem, "eh_personality", eh_personality;
329329
EhPersonalityCatchLangItem, "eh_personality_catch", eh_personality_catch;
330+
EhUnwindResumeLangItem, "eh_unwind_resume", eh_unwind_resume;
330331
MSVCTryFilterLangItem, "msvc_try_filter", msvc_try_filter;
331332

332333
ExchangeHeapLangItem, "exchange_heap", exchange_heap;

src/librustc/middle/weak_lang_items.rs

+5
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ pub fn check_crate(krate: &ast::Crate,
4545
if items.eh_personality().is_none() {
4646
items.missing.push(lang_items::EhPersonalityLangItem);
4747
}
48+
if sess.target.target.options.custom_unwind_resume &
49+
items.eh_unwind_resume().is_none() {
50+
items.missing.push(lang_items::EhUnwindResumeLangItem);
51+
}
4852

4953
{
5054
let mut cx = Context { sess: sess, items: items };
@@ -122,4 +126,5 @@ weak_lang_items! {
122126
panic_fmt, PanicFmtLangItem, rust_begin_unwind;
123127
stack_exhausted, StackExhaustedLangItem, rust_stack_exhausted;
124128
eh_personality, EhPersonalityLangItem, rust_eh_personality;
129+
eh_unwind_resume, EhUnwindResumeLangItem, rust_eh_unwind_resume;
125130
}

src/librustc_back/target/mod.rs

+6
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,11 @@ pub struct TargetOptions {
171171
/// currently only "gnu" is used to fall into LLVM. Unknown strings cause
172172
/// the system linker to be used.
173173
pub archive_format: String,
174+
/// Whether the target uses a custom unwind resumption routine.
175+
/// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
176+
/// defined in libgcc. If this option is enabled, the target must provide
177+
/// `eh_unwind_resume` lang item.
178+
pub custom_unwind_resume: bool,
174179
}
175180

176181
impl Default for TargetOptions {
@@ -209,6 +214,7 @@ impl Default for TargetOptions {
209214
pre_link_objects: Vec::new(),
210215
post_link_objects: Vec::new(),
211216
archive_format: String::new(),
217+
custom_unwind_resume: false,
212218
}
213219
}
214220
}

src/librustc_back/target/x86_64_pc_windows_gnu.rs

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ pub fn target() -> Target {
1616
// On Win64 unwinding is handled by the OS, so we can link libgcc statically.
1717
base.pre_link_args.push("-static-libgcc".to_string());
1818
base.pre_link_args.push("-m64".to_string());
19+
base.custom_unwind_resume = true;
1920

2021
Target {
2122
llvm_target: "x86_64-pc-windows-gnu".to_string(),

src/librustc_trans/trans/base.rs

+6
Original file line numberDiff line numberDiff line change
@@ -2171,6 +2171,12 @@ fn finish_register_fn(ccx: &CrateContext, sym: String, node_id: ast::NodeId,
21712171
llvm::SetDLLStorageClass(llfn, llvm::DLLExportStorageClass);
21722172
}
21732173
}
2174+
if ccx.tcx().lang_items.eh_unwind_resume() == Some(def) {
2175+
llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2176+
if ccx.use_dll_storage_attrs() {
2177+
llvm::SetDLLStorageClass(llfn, llvm::DLLExportStorageClass);
2178+
}
2179+
}
21742180
}
21752181

21762182
fn register_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,

src/librustc_trans/trans/cleanup.rs

+2
Original file line numberDiff line numberDiff line change
@@ -846,6 +846,8 @@ impl<'blk, 'tcx> CleanupHelperMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx
846846

847847
debug!("get_or_create_landing_pad");
848848

849+
self.inject_unwind_resume_hook();
850+
849851
// Check if a landing pad block exists; if not, create one.
850852
{
851853
let mut scopes = self.scopes.borrow_mut();

src/librustc_trans/trans/common.rs

+49
Original file line numberDiff line numberDiff line change
@@ -561,6 +561,55 @@ impl<'a, 'tcx> FunctionContext<'a, 'tcx> {
561561
}
562562
}
563563
}
564+
565+
/// By default, LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
566+
/// defined in libgcc, however, unlike personality routines, there is no easy way to
567+
/// override that symbol. This method injects a local-scoped `_Unwind_Resume` function
568+
/// which immediately defers to the user-defined `eh_unwind_resume` lang item.
569+
pub fn inject_unwind_resume_hook(&self) {
570+
let ccx = self.ccx;
571+
if !ccx.sess().target.target.options.custom_unwind_resume ||
572+
ccx.unwind_resume_hooked().get() {
573+
return;
574+
}
575+
576+
let new_resume = match ccx.tcx().lang_items.eh_unwind_resume() {
577+
Some(did) => callee::trans_fn_ref(ccx, did, ExprId(0), &self.param_substs).val,
578+
None => {
579+
let fty = Type::variadic_func(&[], &Type::void(self.ccx));
580+
declare::declare_cfn(self.ccx, "rust_eh_unwind_resume", fty,
581+
self.ccx.tcx().mk_nil())
582+
}
583+
};
584+
585+
unsafe {
586+
let resume_type = Type::func(&[Type::i8(ccx).ptr_to()], &Type::void(ccx));
587+
let old_resume = llvm::LLVMAddFunction(ccx.llmod(),
588+
"_Unwind_Resume\0".as_ptr() as *const _,
589+
resume_type.to_ref());
590+
llvm::SetLinkage(old_resume, llvm::InternalLinkage);
591+
let llbb = llvm::LLVMAppendBasicBlockInContext(ccx.llcx(),
592+
old_resume,
593+
"\0".as_ptr() as *const _);
594+
let builder = ccx.builder();
595+
builder.position_at_end(llbb);
596+
builder.call(new_resume, &[llvm::LLVMGetFirstParam(old_resume)], None);
597+
builder.unreachable(); // it should never return
598+
599+
// Until DwarfEHPrepare pass has run, _Unwind_Resume is not referenced by any live code
600+
// and is subject to dead code elimination. Here we add _Unwind_Resume to @llvm.globals
601+
// to prevent that.
602+
let i8p_ty = Type::i8p(ccx);
603+
let used_ty = Type::array(&i8p_ty, 1);
604+
let used = llvm::LLVMAddGlobal(ccx.llmod(), used_ty.to_ref(),
605+
"llvm.used\0".as_ptr() as *const _);
606+
let old_resume = llvm::LLVMConstBitCast(old_resume, i8p_ty.to_ref());
607+
llvm::LLVMSetInitializer(used, C_array(i8p_ty, &[old_resume]));
608+
llvm::SetLinkage(used, llvm::AppendingLinkage);
609+
llvm::LLVMSetSection(used, "llvm.metadata\0".as_ptr() as *const _)
610+
}
611+
ccx.unwind_resume_hooked().set(true);
612+
}
564613
}
565614

566615
// Basic block context. We create a block context for each basic block

src/librustc_trans/trans/context.rs

+6
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ pub struct LocalCrateContext<'tcx> {
146146

147147
eh_personality: RefCell<Option<ValueRef>>,
148148
rust_try_fn: RefCell<Option<ValueRef>>,
149+
unwind_resume_hooked: Cell<bool>,
149150

150151
intrinsics: RefCell<FnvHashMap<&'static str, ValueRef>>,
151152

@@ -466,6 +467,7 @@ impl<'tcx> LocalCrateContext<'tcx> {
466467
dbg_cx: dbg_cx,
467468
eh_personality: RefCell::new(None),
468469
rust_try_fn: RefCell::new(None),
470+
unwind_resume_hooked: Cell::new(false),
469471
intrinsics: RefCell::new(FnvHashMap()),
470472
n_llvm_insns: Cell::new(0),
471473
trait_cache: RefCell::new(FnvHashMap()),
@@ -735,6 +737,10 @@ impl<'b, 'tcx> CrateContext<'b, 'tcx> {
735737
&self.local.rust_try_fn
736738
}
737739

740+
pub fn unwind_resume_hooked<'a>(&'a self) -> &'a Cell<bool> {
741+
&self.local.unwind_resume_hooked
742+
}
743+
738744
fn intrinsics<'a>(&'a self) -> &'a RefCell<FnvHashMap<&'static str, ValueRef>> {
739745
&self.local.intrinsics
740746
}

src/librustc_trans/trans/intrinsic.rs

+47-104
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use llvm::{SequentiallyConsistent, Acquire, Release, AtomicXchg, ValueRef, TypeK
1616
use middle::subst;
1717
use middle::subst::FnSpace;
1818
use trans::adt;
19+
use trans::attributes;
1920
use trans::base::*;
2021
use trans::build::*;
2122
use trans::callee;
@@ -1159,26 +1160,14 @@ fn trans_msvc_try<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
11591160
// of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
11601161
// instructions).
11611162
//
1162-
// This translation is a little surprising for two reasons:
1163+
// This translation is a little surprising because
1164+
// we always call a shim function instead of inlining the call to `invoke`
1165+
// manually here. This is done because in LLVM we're only allowed to have one
1166+
// personality per function definition. The call to the `try` intrinsic is
1167+
// being inlined into the function calling it, and that function may already
1168+
// have other personality functions in play. By calling a shim we're
1169+
// guaranteed that our shim will have the right personality function.
11631170
//
1164-
// 1. We always call a shim function instead of inlining the call to `invoke`
1165-
// manually here. This is done because in LLVM we're only allowed to have one
1166-
// personality per function definition. The call to the `try` intrinsic is
1167-
// being inlined into the function calling it, and that function may already
1168-
// have other personality functions in play. By calling a shim we're
1169-
// guaranteed that our shim will have the right personality function.
1170-
//
1171-
// 2. Instead of making one shim (explained above), we make two shims! The
1172-
// reason for this has to do with the technical details about the
1173-
// implementation of unwinding in the runtime, but the tl;dr; is that the
1174-
// outer shim's personality function says "catch rust exceptions" and the
1175-
// inner shim's landing pad will not `resume` the exception being thrown.
1176-
// This means that the outer shim's landing pad is never run and the inner
1177-
// shim's return value is the return value of the whole call.
1178-
//
1179-
// The double-shim aspect is currently done for implementation ease on the
1180-
// runtime side of things, and more info can be found in
1181-
// src/libstd/rt/unwind/gcc.rs.
11821171
fn trans_gnu_try<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
11831172
func: ValueRef,
11841173
data: ValueRef,
@@ -1188,108 +1177,63 @@ fn trans_gnu_try<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
11881177
let ccx = bcx.ccx();
11891178
let dloc = DebugLoc::None;
11901179

1191-
// Type indicator for the exception being thrown, not entirely sure
1192-
// what's going on here but it's what all the examples in LLVM use.
1193-
let lpad_ty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)],
1194-
false);
1180+
// Translates the shims described above:
1181+
//
1182+
// bcx:
1183+
// invoke %func(%args...) normal %normal unwind %catch
1184+
//
1185+
// normal:
1186+
// ret null
1187+
//
1188+
// catch:
1189+
// (ptr, _) = landingpad
1190+
// ret ptr
11951191

1196-
// Define the "inner try" shim
1197-
let rust_try_inner = declare::define_internal_rust_fn(ccx,
1198-
"__rust_try_inner",
1199-
try_fn_ty);
1200-
trans_rust_try(ccx, rust_try_inner, lpad_ty, bcx.fcx.eh_personality(),
1201-
output, dloc, &mut |bcx, then, catch| {
1202-
let func = llvm::get_param(rust_try_inner, 0);
1203-
let data = llvm::get_param(rust_try_inner, 1);
1204-
Invoke(bcx, func, &[data], then.llbb, catch.llbb, None, dloc);
1205-
C_null(Type::i8p(ccx))
1206-
});
1207-
1208-
// Define the "outer try" shim.
1209-
let rust_try = declare::define_internal_rust_fn(ccx, "__rust_try",
1210-
try_fn_ty);
1192+
let rust_try = declare::define_internal_rust_fn(ccx, "__rust_try", try_fn_ty);
1193+
attributes::emit_uwtable(rust_try, true);
12111194
let catch_pers = match bcx.tcx().lang_items.eh_personality_catch() {
12121195
Some(did) => callee::trans_fn_ref(ccx, did, ExprId(0),
12131196
bcx.fcx.param_substs).val,
12141197
None => bcx.tcx().sess.bug("eh_personality_catch not defined"),
12151198
};
1216-
trans_rust_try(ccx, rust_try, lpad_ty, catch_pers, output, dloc,
1217-
&mut |bcx, then, catch| {
1218-
let func = llvm::get_param(rust_try, 0);
1219-
let data = llvm::get_param(rust_try, 1);
1220-
Invoke(bcx, rust_try_inner, &[func, data], then.llbb, catch.llbb,
1221-
None, dloc)
1222-
});
1223-
return rust_try
1224-
});
12251199

1226-
// Note that no invoke is used here because by definition this function
1227-
// can't panic (that's what it's catching).
1228-
let ret = Call(bcx, llfn, &[func, data], None, dloc);
1229-
Store(bcx, ret, dest);
1230-
return bcx;
1231-
1232-
// Translates both the inner and outer shims described above. The only
1233-
// difference between these two is the function invoked and the personality
1234-
// involved, so a common routine is shared.
1235-
//
1236-
// bcx:
1237-
// invoke %func(%args...) normal %normal unwind %unwind
1238-
//
1239-
// normal:
1240-
// ret null
1241-
//
1242-
// unwind:
1243-
// (ptr, _) = landingpad
1244-
// br (ptr != null), done, reraise
1245-
//
1246-
// done:
1247-
// ret ptr
1248-
//
1249-
// reraise:
1250-
// resume
1251-
//
1252-
// Note that the branch checking for `null` here isn't actually necessary,
1253-
// it's just an unfortunate hack to make sure that LLVM doesn't optimize too
1254-
// much. If this were not present, then LLVM would correctly deduce that our
1255-
// inner shim should be tagged with `nounwind` (as it catches all
1256-
// exceptions) and then the outer shim's `invoke` will be translated to just
1257-
// a simple call, destroying that entry for the personality function.
1258-
//
1259-
// To ensure that both shims always have an `invoke` this check against null
1260-
// confuses LLVM enough to the point that it won't infer `nounwind` and
1261-
// we'll proceed as normal.
1262-
fn trans_rust_try<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1263-
llfn: ValueRef,
1264-
lpad_ty: Type,
1265-
personality: ValueRef,
1266-
output: ty::FnOutput<'tcx>,
1267-
dloc: DebugLoc,
1268-
invoke: &mut FnMut(Block, Block, Block) -> ValueRef) {
12691200
let (fcx, block_arena);
12701201
block_arena = TypedArena::new();
1271-
fcx = new_fn_ctxt(ccx, llfn, ast::DUMMY_NODE_ID, false,
1202+
fcx = new_fn_ctxt(ccx, rust_try, ast::DUMMY_NODE_ID, false,
12721203
output, ccx.tcx().mk_substs(Substs::trans_empty()),
12731204
None, &block_arena);
12741205
let bcx = init_function(&fcx, true, output);
12751206
let then = bcx.fcx.new_temp_block("then");
12761207
let catch = bcx.fcx.new_temp_block("catch");
1277-
let reraise = bcx.fcx.new_temp_block("reraise");
1278-
let catch_return = bcx.fcx.new_temp_block("catch-return");
12791208

1280-
let invoke_ret = invoke(bcx, then, catch);
1281-
Ret(then, invoke_ret, dloc);
1282-
let vals = LandingPad(catch, lpad_ty, personality, 1);
1209+
let func = llvm::get_param(rust_try, 0);
1210+
let data = llvm::get_param(rust_try, 1);
1211+
Invoke(bcx, func, &[data], then.llbb, catch.llbb, None, dloc);
1212+
Ret(then, C_null(Type::i8p(ccx)), dloc);
1213+
1214+
// Type indicator for the exception being thrown.
1215+
// The first value in this tuple is a pointer to the exception object being thrown.
1216+
// The second value is a "selector" indicating which of the landing pad clauses
1217+
// the exception's type had been matched to. rust_try ignores the selector.
1218+
let lpad_ty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)],
1219+
false);
1220+
let vals = LandingPad(catch, lpad_ty, catch_pers, 1);
12831221
AddClause(catch, vals, C_null(Type::i8p(ccx)));
12841222
let ptr = ExtractValue(catch, vals, 0);
1285-
let valid = ICmp(catch, llvm::IntNE, ptr, C_null(Type::i8p(ccx)), dloc);
1286-
CondBr(catch, valid, catch_return.llbb, reraise.llbb, dloc);
1287-
Ret(catch_return, ptr, dloc);
1288-
Resume(reraise, vals);
1289-
}
1223+
Ret(catch, ptr, dloc);
1224+
fcx.cleanup();
1225+
1226+
return rust_try
1227+
});
1228+
1229+
// Note that no invoke is used here because by definition this function
1230+
// can't panic (that's what it's catching).
1231+
let ret = Call(bcx, llfn, &[func, data], None, dloc);
1232+
Store(bcx, ret, dest);
1233+
return bcx;
12901234
}
12911235

1292-
// Helper to generate the `Ty` associated with `rust_Try`
1236+
// Helper to generate the `Ty` associated with `rust_try`
12931237
fn get_rust_try_fn<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
12941238
f: &mut FnMut(Ty<'tcx>,
12951239
ty::FnOutput<'tcx>) -> ValueRef)
@@ -1299,8 +1243,7 @@ fn get_rust_try_fn<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
12991243
return llfn
13001244
}
13011245

1302-
// Define the types up front for the signatures of the rust_try and
1303-
// rust_try_inner functions.
1246+
// Define the type up front for the signature of the rust_try function.
13041247
let tcx = ccx.tcx();
13051248
let i8p = tcx.mk_mut_ptr(tcx.types.i8);
13061249
let fn_ty = tcx.mk_bare_fn(ty::BareFnTy {

0 commit comments

Comments
 (0)