Skip to main content

rustc_codegen_ssa/mir/
naked_asm.rs

1use rustc_abi::{BackendRepr, Float, Integer, Primitive, RegKind};
2use rustc_hir::attrs::{InstructionSetAttr, Linkage};
3use rustc_hir::def_id::LOCAL_CRATE;
4use rustc_middle::mir::{InlineAsmOperand, START_BLOCK};
5use rustc_middle::mono::{MonoItemData, Visibility};
6use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout};
7use rustc_middle::ty::{Instance, Ty, TyCtxt, TypeVisitableExt};
8use rustc_middle::{bug, ty};
9use rustc_span::sym;
10use rustc_target::callconv::{ArgAbi, FnAbi, PassMode};
11use rustc_target::spec::{Arch, BinaryFormat};
12
13use crate::common;
14use crate::mir::AsmCodegenMethods;
15use crate::traits::GlobalAsmOperandRef;
16
17pub fn codegen_naked_asm<
18    'a,
19    'tcx,
20    Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>>
21        + FnAbiOf<'tcx, FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>>
22        + AsmCodegenMethods<'tcx>,
23>(
24    cx: &'a mut Cx,
25    instance: Instance<'tcx>,
26    item_data: MonoItemData,
27) {
28    if !!instance.args.has_infer() {
    ::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};assert!(!instance.args.has_infer());
29    let mir = cx.tcx().instance_mir(instance.def);
30
31    let rustc_middle::mir::TerminatorKind::InlineAsm {
32        asm_macro: _,
33        template,
34        ref operands,
35        options,
36        line_spans,
37        targets: _,
38        unwind: _,
39    } = mir.basic_blocks[START_BLOCK].terminator().kind
40    else {
41        ::rustc_middle::util::bug::bug_fmt(format_args!("#[naked] functions should always terminate with an asm! block"))bug!("#[naked] functions should always terminate with an asm! block")
42    };
43
44    let operands: Vec<_> =
45        operands.iter().map(|op| inline_to_global_operand::<Cx>(cx, instance, op)).collect();
46
47    let name = cx.mangled_name(instance);
48    let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
49    let (begin, end) = prefix_and_suffix(cx.tcx(), instance, &name, item_data, fn_abi);
50
51    let mut template_vec = Vec::new();
52    template_vec.push(rustc_ast::ast::InlineAsmTemplatePiece::String(begin.into()));
53    template_vec.extend(template.iter().cloned());
54    template_vec.push(rustc_ast::ast::InlineAsmTemplatePiece::String(end.into()));
55
56    cx.codegen_global_asm(&template_vec, &operands, options, line_spans);
57}
58
59fn inline_to_global_operand<'a, 'tcx, Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>>>(
60    cx: &'a Cx,
61    instance: Instance<'tcx>,
62    op: &InlineAsmOperand<'tcx>,
63) -> GlobalAsmOperandRef<'tcx> {
64    match op {
65        InlineAsmOperand::Const { value } => {
66            let const_value = instance
67                .instantiate_mir_and_normalize_erasing_regions(
68                    cx.tcx(),
69                    cx.typing_env(),
70                    ty::EarlyBinder::bind(value.const_),
71                )
72                .eval(cx.tcx(), cx.typing_env(), value.span)
73                .expect("erroneous constant missed by mono item collection");
74
75            let mono_type = instance.instantiate_mir_and_normalize_erasing_regions(
76                cx.tcx(),
77                cx.typing_env(),
78                ty::EarlyBinder::bind(value.ty()),
79            );
80
81            let string = common::asm_const_to_str(
82                cx.tcx(),
83                value.span,
84                const_value,
85                cx.layout_of(mono_type),
86            );
87
88            GlobalAsmOperandRef::Const { string }
89        }
90        InlineAsmOperand::SymFn { value } => {
91            let mono_type = instance.instantiate_mir_and_normalize_erasing_regions(
92                cx.tcx(),
93                cx.typing_env(),
94                ty::EarlyBinder::bind(value.ty()),
95            );
96
97            let instance = match mono_type.kind() {
98                &ty::FnDef(def_id, args) => {
99                    Instance::expect_resolve(cx.tcx(), cx.typing_env(), def_id, args, value.span)
100                }
101                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("asm sym is not a function"))bug!("asm sym is not a function"),
102            };
103
104            GlobalAsmOperandRef::SymFn { instance }
105        }
106        InlineAsmOperand::SymStatic { def_id } => {
107            GlobalAsmOperandRef::SymStatic { def_id: *def_id }
108        }
109        InlineAsmOperand::In { .. }
110        | InlineAsmOperand::Out { .. }
111        | InlineAsmOperand::InOut { .. }
112        | InlineAsmOperand::Label { .. } => {
113            ::rustc_middle::util::bug::bug_fmt(format_args!("invalid operand type for naked_asm!"))bug!("invalid operand type for naked_asm!")
114        }
115    }
116}
117
118fn prefix_and_suffix<'tcx>(
119    tcx: TyCtxt<'tcx>,
120    instance: Instance<'tcx>,
121    asm_name: &str,
122    item_data: MonoItemData,
123    fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
124) -> (String, String) {
125    use std::fmt::Write;
126
127    let asm_binary_format = &tcx.sess.target.binary_format;
128
129    let is_arm = tcx.sess.target.arch == Arch::Arm;
130    let is_thumb = tcx.sess.unstable_target_features.contains(&sym::thumb_mode);
131
132    // If we're compiling the compiler-builtins crate, e.g., the equivalent of
133    // compiler-rt, then we want to implicitly compile everything with hidden
134    // visibility as we're going to link this object all over the place but
135    // don't want the symbols to get exported. For naked asm we set the visibility here.
136    let mut visibility = item_data.visibility;
137    if item_data.linkage != Linkage::Internal && tcx.is_compiler_builtins(LOCAL_CRATE) {
138        visibility = Visibility::Hidden;
139    }
140
141    let attrs = tcx.codegen_instance_attrs(instance.def);
142    let link_section = attrs.link_section.map(|symbol| symbol.as_str().to_string());
143
144    // Pick a default alignment when the alignment is not explicitly specified.
145    let align_bytes = match attrs.alignment {
146        Some(align) => align.bytes(),
147        None => match asm_binary_format {
148            BinaryFormat::Coff => 16,
149            _ => 4,
150        },
151    };
152
153    // In particular, `.arm` can also be written `.code 32` and `.thumb` as `.code 16`.
154    let (arch_prefix, arch_suffix) = if is_arm {
155        (
156            match attrs.instruction_set {
157                None => match is_thumb {
158                    true => ".thumb\n.thumb_func",
159                    false => ".arm",
160                },
161                Some(InstructionSetAttr::ArmT32) => ".thumb\n.thumb_func",
162                Some(InstructionSetAttr::ArmA32) => ".arm",
163            },
164            match is_thumb {
165                true => ".thumb",
166                false => ".arm",
167            },
168        )
169    } else {
170        ("", "")
171    };
172
173    let emit_fatal = |msg| tcx.dcx().span_fatal(tcx.def_span(instance.def_id()), msg);
174
175    // see https://godbolt.org/z/cPK4sxKor.
176    let write_linkage = |w: &mut String| -> std::fmt::Result {
177        match item_data.linkage {
178            Linkage::External => {
179                w.write_fmt(format_args!(".globl {0}\n", asm_name))writeln!(w, ".globl {asm_name}")?;
180            }
181            Linkage::LinkOnceAny | Linkage::LinkOnceODR | Linkage::WeakAny | Linkage::WeakODR => {
182                match asm_binary_format {
183                    BinaryFormat::Elf | BinaryFormat::Coff | BinaryFormat::Wasm => {
184                        w.write_fmt(format_args!(".weak {0}\n", asm_name))writeln!(w, ".weak {asm_name}")?;
185                    }
186                    BinaryFormat::Xcoff => {
187                        // FIXME: there is currently no way of defining a weak symbol in inline assembly
188                        // for AIX. See https://github.com/llvm/llvm-project/issues/130269
189                        emit_fatal(
190                            "cannot create weak symbols from inline assembly for this target",
191                        )
192                    }
193                    BinaryFormat::MachO => {
194                        w.write_fmt(format_args!(".globl {0}\n", asm_name))writeln!(w, ".globl {asm_name}")?;
195                        w.write_fmt(format_args!(".weak_definition {0}\n", asm_name))writeln!(w, ".weak_definition {asm_name}")?;
196                    }
197                }
198            }
199            Linkage::Internal => {
200                // LTO can fail when internal linkage is used.
201                emit_fatal("naked functions may not have internal linkage")
202            }
203            Linkage::Common => emit_fatal("Functions may not have common linkage"),
204            Linkage::AvailableExternally => {
205                // this would make the function equal an extern definition
206                emit_fatal("Functions may not have available_externally linkage")
207            }
208            Linkage::ExternalWeak => {
209                // FIXME: actually this causes a SIGILL in LLVM
210                emit_fatal("Functions may not have external weak linkage")
211            }
212        }
213
214        Ok(())
215    };
216
217    let mut begin = String::new();
218    let mut end = String::new();
219    match asm_binary_format {
220        BinaryFormat::Elf => {
221            let section = link_section.unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".text.{0}", asm_name))
    })format!(".text.{asm_name}"));
222
223            let progbits = match is_arm {
224                true => "%progbits",
225                false => "@progbits",
226            };
227
228            let function = match is_arm {
229                true => "%function",
230                false => "@function",
231            };
232
233            begin.write_fmt(format_args!(".pushsection {0},\"ax\", {1}\n", section,
        progbits))writeln!(begin, ".pushsection {section},\"ax\", {progbits}").unwrap();
234            begin.write_fmt(format_args!(".balign {0}\n", align_bytes))writeln!(begin, ".balign {align_bytes}").unwrap();
235            write_linkage(&mut begin).unwrap();
236            match visibility {
237                Visibility::Default => {}
238                Visibility::Protected => begin.write_fmt(format_args!(".protected {0}\n", asm_name))writeln!(begin, ".protected {asm_name}").unwrap(),
239                Visibility::Hidden => begin.write_fmt(format_args!(".hidden {0}\n", asm_name))writeln!(begin, ".hidden {asm_name}").unwrap(),
240            }
241            begin.write_fmt(format_args!(".type {0}, {1}\n", asm_name, function))writeln!(begin, ".type {asm_name}, {function}").unwrap();
242            if !arch_prefix.is_empty() {
243                begin.write_fmt(format_args!("{0}\n", arch_prefix))writeln!(begin, "{}", arch_prefix).unwrap();
244            }
245            begin.write_fmt(format_args!("{0}:\n", asm_name))writeln!(begin, "{asm_name}:").unwrap();
246
247            end.write_fmt(format_args!("\n"))writeln!(end).unwrap();
248            // emit a label starting with `func_end` for `cargo asm` and other tooling that might
249            // pattern match on assembly generated by LLVM.
250            end.write_fmt(format_args!(".Lfunc_end_{0}:\n", asm_name))writeln!(end, ".Lfunc_end_{asm_name}:").unwrap();
251            end.write_fmt(format_args!(".size {0}, . - {0}\n", asm_name))writeln!(end, ".size {asm_name}, . - {asm_name}").unwrap();
252            end.write_fmt(format_args!(".popsection\n"))writeln!(end, ".popsection").unwrap();
253            if !arch_suffix.is_empty() {
254                end.write_fmt(format_args!("{0}\n", arch_suffix))writeln!(end, "{}", arch_suffix).unwrap();
255            }
256        }
257        BinaryFormat::MachO => {
258            let section = link_section.unwrap_or_else(|| "__TEXT,__text".to_string());
259            begin.write_fmt(format_args!(".pushsection {0},regular,pure_instructions\n",
        section))writeln!(begin, ".pushsection {},regular,pure_instructions", section).unwrap();
260            begin.write_fmt(format_args!(".balign {0}\n", align_bytes))writeln!(begin, ".balign {align_bytes}").unwrap();
261            write_linkage(&mut begin).unwrap();
262            match visibility {
263                Visibility::Default | Visibility::Protected => {}
264                Visibility::Hidden => begin.write_fmt(format_args!(".private_extern {0}\n", asm_name))writeln!(begin, ".private_extern {asm_name}").unwrap(),
265            }
266            begin.write_fmt(format_args!("{0}:\n", asm_name))writeln!(begin, "{asm_name}:").unwrap();
267
268            end.write_fmt(format_args!("\n"))writeln!(end).unwrap();
269            end.write_fmt(format_args!(".Lfunc_end_{0}:\n", asm_name))writeln!(end, ".Lfunc_end_{asm_name}:").unwrap();
270            end.write_fmt(format_args!(".popsection\n"))writeln!(end, ".popsection").unwrap();
271            if !arch_suffix.is_empty() {
272                end.write_fmt(format_args!("{0}\n", arch_suffix))writeln!(end, "{}", arch_suffix).unwrap();
273            }
274        }
275        BinaryFormat::Coff => {
276            begin.write_fmt(format_args!(".def {0}\n", asm_name))writeln!(begin, ".def {asm_name}").unwrap();
277            begin.write_fmt(format_args!(".scl 2\n"))writeln!(begin, ".scl 2").unwrap();
278            begin.write_fmt(format_args!(".type 32\n"))writeln!(begin, ".type 32").unwrap();
279            begin.write_fmt(format_args!(".endef\n"))writeln!(begin, ".endef").unwrap();
280
281            let section = link_section.unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".text.{0}", asm_name))
    })format!(".text.{asm_name}"));
282            begin.write_fmt(format_args!(".pushsection {0},\"xr\"\n", section))writeln!(begin, ".pushsection {},\"xr\"", section).unwrap();
283            write_linkage(&mut begin).unwrap();
284            begin.write_fmt(format_args!(".balign {0}\n", align_bytes))writeln!(begin, ".balign {align_bytes}").unwrap();
285            begin.write_fmt(format_args!("{0}:\n", asm_name))writeln!(begin, "{asm_name}:").unwrap();
286
287            end.write_fmt(format_args!("\n"))writeln!(end).unwrap();
288            if !arch_suffix.is_empty() {
289                end.write_fmt(format_args!("{0}\n", arch_suffix))writeln!(end, "{}", arch_suffix).unwrap();
290            }
291        }
292        BinaryFormat::Wasm => {
293            let section = link_section.unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".text.{0}", asm_name))
    })format!(".text.{asm_name}"));
294
295            begin.write_fmt(format_args!(".section {0},\"\",@\n", section))writeln!(begin, ".section {section},\"\",@").unwrap();
296            // wasm functions cannot be aligned, so skip
297            write_linkage(&mut begin).unwrap();
298            if let Visibility::Hidden = visibility {
299                begin.write_fmt(format_args!(".hidden {0}\n", asm_name))writeln!(begin, ".hidden {asm_name}").unwrap();
300            }
301            begin.write_fmt(format_args!(".type {0}, @function\n", asm_name))writeln!(begin, ".type {asm_name}, @function").unwrap();
302            if !arch_prefix.is_empty() {
303                begin.write_fmt(format_args!("{0}\n", arch_prefix))writeln!(begin, "{}", arch_prefix).unwrap();
304            }
305            begin.write_fmt(format_args!("{0}:\n", asm_name))writeln!(begin, "{asm_name}:").unwrap();
306            begin.write_fmt(format_args!(".functype {1} {0}\n",
        wasm_functype(tcx, fn_abi), asm_name))writeln!(begin, ".functype {asm_name} {}", wasm_functype(tcx, fn_abi)).unwrap();
307
308            end.write_fmt(format_args!("\n"))writeln!(end).unwrap();
309            // .size is ignored for function symbols, so we can skip it
310            end.write_fmt(format_args!("end_function\n"))writeln!(end, "end_function").unwrap();
311            end.write_fmt(format_args!(".Lfunc_end_{0}:\n", asm_name))writeln!(end, ".Lfunc_end_{asm_name}:").unwrap();
312        }
313        BinaryFormat::Xcoff => {
314            // the LLVM XCOFFAsmParser is extremely incomplete and does not implement many of the
315            // documented directives.
316            //
317            // - https://github.com/llvm/llvm-project/blob/1b25c0c4da968fe78921ce77736e5baef4db75e3/llvm/lib/MC/MCParser/XCOFFAsmParser.cpp
318            // - https://www.ibm.com/docs/en/ssw_aix_71/assembler/assembler_pdf.pdf
319            //
320            // Consequently, we try our best here but cannot do as good a job as for other binary
321            // formats.
322
323            // FIXME: start a section. `.csect` is not currently implemented in LLVM
324
325            // fun fact: according to the assembler documentation, .align takes an exponent,
326            // but LLVM only accepts powers of 2 (but does emit the exponent)
327            // so when we hand `.align 32` to LLVM, the assembly output will contain `.align 5`
328            begin.write_fmt(format_args!(".align {0}\n", align_bytes))writeln!(begin, ".align {}", align_bytes).unwrap();
329
330            write_linkage(&mut begin).unwrap();
331            if let Visibility::Hidden = visibility {
332                // FIXME apparently `.globl {asm_name}, hidden` is valid
333                // but due to limitations with `.weak` (see above) we can't really use that in general yet
334            }
335            begin.write_fmt(format_args!("{0}:\n", asm_name))writeln!(begin, "{asm_name}:").unwrap();
336
337            end.write_fmt(format_args!("\n"))writeln!(end).unwrap();
338            // FIXME: end the section?
339        }
340    }
341
342    (begin, end)
343}
344
345/// The webassembly type signature for the given function.
346///
347/// Used by the `.functype` directive on wasm targets.
348fn wasm_functype<'tcx>(tcx: TyCtxt<'tcx>, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> String {
349    let mut signature = String::with_capacity(64);
350
351    let ptr_type = match tcx.data_layout.pointer_size().bits() {
352        32 => "i32",
353        64 => "i64",
354        other => ::rustc_middle::util::bug::bug_fmt(format_args!("wasm pointer size cannot be {0} bits",
        other))bug!("wasm pointer size cannot be {other} bits"),
355    };
356
357    let hidden_return = #[allow(non_exhaustive_omitted_patterns)] match fn_abi.ret.mode {
    PassMode::Indirect { .. } => true,
    _ => false,
}matches!(fn_abi.ret.mode, PassMode::Indirect { .. });
358
359    signature.push('(');
360
361    if hidden_return {
362        signature.push_str(ptr_type);
363        if !fn_abi.args.is_empty() {
364            signature.push_str(", ");
365        }
366    }
367
368    let mut it = fn_abi.args.iter().peekable();
369    while let Some(arg_abi) = it.next() {
370        wasm_type(&mut signature, arg_abi, ptr_type);
371        if it.peek().is_some() {
372            signature.push_str(", ");
373        }
374    }
375
376    signature.push_str(") -> (");
377
378    if !hidden_return {
379        wasm_type(&mut signature, &fn_abi.ret, ptr_type);
380    }
381
382    signature.push(')');
383
384    signature
385}
386
387fn wasm_type<'tcx>(signature: &mut String, arg_abi: &ArgAbi<'_, Ty<'tcx>>, ptr_type: &'static str) {
388    match arg_abi.mode {
389        PassMode::Ignore => { /* do nothing */ }
390        PassMode::Direct(_) => {
391            let direct_type = match arg_abi.layout.backend_repr {
392                BackendRepr::Scalar(scalar) => wasm_primitive(scalar.primitive(), ptr_type),
393                BackendRepr::SimdVector { .. } => "v128",
394                other => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected BackendRepr: {0:?}", other)));
}unreachable!("unexpected BackendRepr: {:?}", other),
395            };
396
397            signature.push_str(direct_type);
398        }
399        PassMode::Pair(_, _) => match arg_abi.layout.backend_repr {
400            BackendRepr::ScalarPair(a, b) => {
401                signature.push_str(wasm_primitive(a.primitive(), ptr_type));
402                signature.push_str(", ");
403                signature.push_str(wasm_primitive(b.primitive(), ptr_type));
404            }
405            other => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("{0:?}", other)));
}unreachable!("{other:?}"),
406        },
407        PassMode::Cast { pad_i32, ref cast } => {
408            // For wasm, Cast is used for single-field primitive wrappers like `struct Wrapper(i64);`
409            if !!pad_i32 {
    {
        ::core::panicking::panic_fmt(format_args!("not currently used by wasm calling convention"));
    }
};assert!(!pad_i32, "not currently used by wasm calling convention");
410            if !cast.prefix[0].is_none() {
    { ::core::panicking::panic_fmt(format_args!("no prefix")); }
};assert!(cast.prefix[0].is_none(), "no prefix");
411            match (&cast.rest.total, &arg_abi.layout.size) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("single item")));
        }
    }
};assert_eq!(cast.rest.total, arg_abi.layout.size, "single item");
412
413            let wrapped_wasm_type = match cast.rest.unit.kind {
414                RegKind::Integer => match cast.rest.unit.size.bytes() {
415                    ..=4 => "i32",
416                    ..=8 => "i64",
417                    _ => ptr_type,
418                },
419                RegKind::Float => match cast.rest.unit.size.bytes() {
420                    ..=4 => "f32",
421                    ..=8 => "f64",
422                    _ => ptr_type,
423                },
424                RegKind::Vector { .. } => "v128",
425            };
426
427            signature.push_str(wrapped_wasm_type);
428        }
429        PassMode::Indirect { .. } => signature.push_str(ptr_type),
430    }
431}
432
433fn wasm_primitive(primitive: Primitive, ptr_type: &'static str) -> &'static str {
434    match primitive {
435        Primitive::Int(integer, _) => match integer {
436            Integer::I8 | Integer::I16 | Integer::I32 => "i32",
437            Integer::I64 => "i64",
438            Integer::I128 => "i64, i64",
439        },
440        Primitive::Float(float) => match float {
441            Float::F16 | Float::F32 => "f32",
442            Float::F64 => "f64",
443            Float::F128 => "i64, i64",
444        },
445        Primitive::Pointer(_) => ptr_type,
446    }
447}