Skip to content

Commit 4808561

Browse files
committed
Fix misoptimizations when matching against strings/slices
When matching against strings/slices, we call the comparison function for strings, which takes two string slices by value. The slices are passed in memory, and currently we just pass in a pointer to the original slice. That can cause misoptimizations because we emit a call to llvm.lifetime.end for all by-value arguments at the end of a function, which in this case marks the original slice as dead. So we need to properly create copies of the slices to pass them to the comparison function. Fixes #22008
1 parent 342ab53 commit 4808561

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/librustc_trans/trans/_match.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -828,7 +828,19 @@ fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
828828
&format!("comparison of `{}`",
829829
cx.ty_to_string(rhs_t))[],
830830
StrEqFnLangItem);
831-
callee::trans_lang_call(cx, did, &[lhs, rhs], None, debug_loc)
831+
let t = ty::mk_str_slice(cx.tcx(), cx.tcx().mk_region(ty::ReStatic), ast::MutImmutable);
832+
// The comparison function gets the slices by value, so we have to make copies here. Even
833+
// if the function doesn't write through the pointer, things like lifetime intrinsics
834+
// require that we do this properly
835+
let lhs_arg = alloc_ty(cx, t, "lhs");
836+
let rhs_arg = alloc_ty(cx, t, "rhs");
837+
memcpy_ty(cx, lhs_arg, lhs, t);
838+
memcpy_ty(cx, rhs_arg, rhs, t);
839+
let res = callee::trans_lang_call(cx, did, &[lhs_arg, rhs_arg], None, debug_loc);
840+
call_lifetime_end(res.bcx, lhs_arg);
841+
call_lifetime_end(res.bcx, rhs_arg);
842+
843+
res
832844
}
833845

834846
let _icx = push_ctxt("compare_values");

src/test/run-pass/issue22008.rs

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
pub fn main() {
12+
let command = "a";
13+
14+
match command {
15+
"foo" => println!("foo"),
16+
_ => println!("{}", command),
17+
}
18+
}

0 commit comments

Comments
 (0)