]> git.lizzy.rs Git - rust.git/blob - src/trap.rs
Codegen 128bit atomic loads and stores for compiler builtins as trap
[rust.git] / src / trap.rs
1 //! Helpers used to print a message and abort in case of certain panics and some detected UB.
2
3 use crate::prelude::*;
4
5 fn codegen_print(fx: &mut FunctionCx<'_, '_, '_>, msg: &str) {
6     let puts = fx
7         .module
8         .declare_function(
9             "puts",
10             Linkage::Import,
11             &Signature {
12                 call_conv: fx.target_config.default_call_conv,
13                 params: vec![AbiParam::new(fx.pointer_type)],
14                 returns: vec![AbiParam::new(types::I32)],
15             },
16         )
17         .unwrap();
18     let puts = fx.module.declare_func_in_func(puts, &mut fx.bcx.func);
19     if fx.clif_comments.enabled() {
20         fx.add_comment(puts, "puts");
21     }
22
23     let real_msg = format!("trap at {:?} ({}): {}\0", fx.instance, fx.symbol_name, msg);
24     let msg_ptr = fx.anonymous_str(&real_msg);
25     fx.bcx.ins().call(puts, &[msg_ptr]);
26 }
27
28 /// Use this for example when a function call should never return. This will fill the current block,
29 /// so you can **not** add instructions to it afterwards.
30 ///
31 /// Trap code: user65535
32 pub(crate) fn trap_unreachable(fx: &mut FunctionCx<'_, '_, '_>, msg: impl AsRef<str>) {
33     codegen_print(fx, msg.as_ref());
34     fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
35 }
36 /// Use this when something is unimplemented, but `libcore` or `libstd` requires it to codegen.
37 /// Unlike `trap_unreachable` this will not fill the current block, so you **must** add instructions
38 /// to it afterwards.
39 ///
40 /// Trap code: user65535
41 pub(crate) fn trap_unimplemented(fx: &mut FunctionCx<'_, '_, '_>, msg: impl AsRef<str>) {
42     codegen_print(fx, msg.as_ref());
43     let true_ = fx.bcx.ins().iconst(types::I32, 1);
44     fx.bcx.ins().trapnz(true_, TrapCode::User(!0));
45 }
46
47 /// Like `trap_unimplemented` but returns a fake value of the specified type.
48 ///
49 /// Trap code: user65535
50 pub(crate) fn trap_unimplemented_ret_value<'tcx>(
51     fx: &mut FunctionCx<'_, '_, 'tcx>,
52     dest_layout: TyAndLayout<'tcx>,
53     msg: impl AsRef<str>,
54 ) -> CValue<'tcx> {
55     trap_unimplemented(fx, msg);
56     CValue::by_ref(Pointer::const_addr(fx, 0), dest_layout)
57 }