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::mono::{MonoItemData, Visibility};
5use rustc_middle::mir::{InlineAsmOperand, START_BLOCK};
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    // If no alignment is specified, an alignment of 4 bytes is used.
145    let align_bytes = attrs.alignment.map(|a| a.bytes()).unwrap_or(4);
146
147    // In particular, `.arm` can also be written `.code 32` and `.thumb` as `.code 16`.
148    let (arch_prefix, arch_suffix) = if is_arm {
149        (
150            match attrs.instruction_set {
151                None => match is_thumb {
152                    true => ".thumb\n.thumb_func",
153                    false => ".arm",
154                },
155                Some(InstructionSetAttr::ArmT32) => ".thumb\n.thumb_func",
156                Some(InstructionSetAttr::ArmA32) => ".arm",
157            },
158            match is_thumb {
159                true => ".thumb",
160                false => ".arm",
161            },
162        )
163    } else {
164        ("", "")
165    };
166
167    let emit_fatal = |msg| tcx.dcx().span_fatal(tcx.def_span(instance.def_id()), msg);
168
169    // see https://godbolt.org/z/cPK4sxKor.
170    let write_linkage = |w: &mut String| -> std::fmt::Result {
171        match item_data.linkage {
172            Linkage::External => {
173                w.write_fmt(format_args!(".globl {0}\n", asm_name))writeln!(w, ".globl {asm_name}")?;
174            }
175            Linkage::LinkOnceAny | Linkage::LinkOnceODR | Linkage::WeakAny | Linkage::WeakODR => {
176                match asm_binary_format {
177                    BinaryFormat::Elf | BinaryFormat::Coff | BinaryFormat::Wasm => {
178                        w.write_fmt(format_args!(".weak {0}\n", asm_name))writeln!(w, ".weak {asm_name}")?;
179                    }
180                    BinaryFormat::Xcoff => {
181                        // FIXME: there is currently no way of defining a weak symbol in inline assembly
182                        // for AIX. See https://github.com/llvm/llvm-project/issues/130269
183                        emit_fatal(
184                            "cannot create weak symbols from inline assembly for this target",
185                        )
186                    }
187                    BinaryFormat::MachO => {
188                        w.write_fmt(format_args!(".globl {0}\n", asm_name))writeln!(w, ".globl {asm_name}")?;
189                        w.write_fmt(format_args!(".weak_definition {0}\n", asm_name))writeln!(w, ".weak_definition {asm_name}")?;
190                    }
191                }
192            }
193            Linkage::Internal => {
194                // LTO can fail when internal linkage is used.
195                emit_fatal("naked functions may not have internal linkage")
196            }
197            Linkage::Common => emit_fatal("Functions may not have common linkage"),
198            Linkage::AvailableExternally => {
199                // this would make the function equal an extern definition
200                emit_fatal("Functions may not have available_externally linkage")
201            }
202            Linkage::ExternalWeak => {
203                // FIXME: actually this causes a SIGILL in LLVM
204                emit_fatal("Functions may not have external weak linkage")
205            }
206        }
207
208        Ok(())
209    };
210
211    let mut begin = String::new();
212    let mut end = String::new();
213    match asm_binary_format {
214        BinaryFormat::Elf => {
215            let section = link_section.unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".text.{0}", asm_name))
    })format!(".text.{asm_name}"));
216
217            let progbits = match is_arm {
218                true => "%progbits",
219                false => "@progbits",
220            };
221
222            let function = match is_arm {
223                true => "%function",
224                false => "@function",
225            };
226
227            begin.write_fmt(format_args!(".pushsection {0},\"ax\", {1}\n", section,
        progbits))writeln!(begin, ".pushsection {section},\"ax\", {progbits}").unwrap();
228            begin.write_fmt(format_args!(".balign {0}\n", align_bytes))writeln!(begin, ".balign {align_bytes}").unwrap();
229            write_linkage(&mut begin).unwrap();
230            match visibility {
231                Visibility::Default => {}
232                Visibility::Protected => begin.write_fmt(format_args!(".protected {0}\n", asm_name))writeln!(begin, ".protected {asm_name}").unwrap(),
233                Visibility::Hidden => begin.write_fmt(format_args!(".hidden {0}\n", asm_name))writeln!(begin, ".hidden {asm_name}").unwrap(),
234            }
235            begin.write_fmt(format_args!(".type {0}, {1}\n", asm_name, function))writeln!(begin, ".type {asm_name}, {function}").unwrap();
236            if !arch_prefix.is_empty() {
237                begin.write_fmt(format_args!("{0}\n", arch_prefix))writeln!(begin, "{}", arch_prefix).unwrap();
238            }
239            begin.write_fmt(format_args!("{0}:\n", asm_name))writeln!(begin, "{asm_name}:").unwrap();
240
241            end.write_fmt(format_args!("\n"))writeln!(end).unwrap();
242            // emit a label starting with `func_end` for `cargo asm` and other tooling that might
243            // pattern match on assembly generated by LLVM.
244            end.write_fmt(format_args!(".Lfunc_end_{0}:\n", asm_name))writeln!(end, ".Lfunc_end_{asm_name}:").unwrap();
245            end.write_fmt(format_args!(".size {0}, . - {0}\n", asm_name))writeln!(end, ".size {asm_name}, . - {asm_name}").unwrap();
246            end.write_fmt(format_args!(".popsection\n"))writeln!(end, ".popsection").unwrap();
247            if !arch_suffix.is_empty() {
248                end.write_fmt(format_args!("{0}\n", arch_suffix))writeln!(end, "{}", arch_suffix).unwrap();
249            }
250        }
251        BinaryFormat::MachO => {
252            let section = link_section.unwrap_or_else(|| "__TEXT,__text".to_string());
253            begin.write_fmt(format_args!(".pushsection {0},regular,pure_instructions\n",
        section))writeln!(begin, ".pushsection {},regular,pure_instructions", section).unwrap();
254            begin.write_fmt(format_args!(".balign {0}\n", align_bytes))writeln!(begin, ".balign {align_bytes}").unwrap();
255            write_linkage(&mut begin).unwrap();
256            match visibility {
257                Visibility::Default | Visibility::Protected => {}
258                Visibility::Hidden => begin.write_fmt(format_args!(".private_extern {0}\n", asm_name))writeln!(begin, ".private_extern {asm_name}").unwrap(),
259            }
260            begin.write_fmt(format_args!("{0}:\n", asm_name))writeln!(begin, "{asm_name}:").unwrap();
261
262            end.write_fmt(format_args!("\n"))writeln!(end).unwrap();
263            end.write_fmt(format_args!(".Lfunc_end_{0}:\n", asm_name))writeln!(end, ".Lfunc_end_{asm_name}:").unwrap();
264            end.write_fmt(format_args!(".popsection\n"))writeln!(end, ".popsection").unwrap();
265            if !arch_suffix.is_empty() {
266                end.write_fmt(format_args!("{0}\n", arch_suffix))writeln!(end, "{}", arch_suffix).unwrap();
267            }
268        }
269        BinaryFormat::Coff => {
270            let section = link_section.unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".text.{0}", asm_name))
    })format!(".text.{asm_name}"));
271            begin.write_fmt(format_args!(".pushsection {0},\"xr\"\n", section))writeln!(begin, ".pushsection {},\"xr\"", section).unwrap();
272            begin.write_fmt(format_args!(".balign {0}\n", align_bytes))writeln!(begin, ".balign {align_bytes}").unwrap();
273            write_linkage(&mut begin).unwrap();
274            begin.write_fmt(format_args!(".def {0}\n", asm_name))writeln!(begin, ".def {asm_name}").unwrap();
275            begin.write_fmt(format_args!(".scl 2\n"))writeln!(begin, ".scl 2").unwrap();
276            begin.write_fmt(format_args!(".type 32\n"))writeln!(begin, ".type 32").unwrap();
277            begin.write_fmt(format_args!(".endef\n"))writeln!(begin, ".endef").unwrap();
278            begin.write_fmt(format_args!("{0}:\n", asm_name))writeln!(begin, "{asm_name}:").unwrap();
279
280            end.write_fmt(format_args!("\n"))writeln!(end).unwrap();
281            end.write_fmt(format_args!(".Lfunc_end_{0}:\n", asm_name))writeln!(end, ".Lfunc_end_{asm_name}:").unwrap();
282            end.write_fmt(format_args!(".popsection\n"))writeln!(end, ".popsection").unwrap();
283            if !arch_suffix.is_empty() {
284                end.write_fmt(format_args!("{0}\n", arch_suffix))writeln!(end, "{}", arch_suffix).unwrap();
285            }
286        }
287        BinaryFormat::Wasm => {
288            let section = link_section.unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".text.{0}", asm_name))
    })format!(".text.{asm_name}"));
289
290            begin.write_fmt(format_args!(".section {0},\"\",@\n", section))writeln!(begin, ".section {section},\"\",@").unwrap();
291            // wasm functions cannot be aligned, so skip
292            write_linkage(&mut begin).unwrap();
293            if let Visibility::Hidden = visibility {
294                begin.write_fmt(format_args!(".hidden {0}\n", asm_name))writeln!(begin, ".hidden {asm_name}").unwrap();
295            }
296            begin.write_fmt(format_args!(".type {0}, @function\n", asm_name))writeln!(begin, ".type {asm_name}, @function").unwrap();
297            if !arch_prefix.is_empty() {
298                begin.write_fmt(format_args!("{0}\n", arch_prefix))writeln!(begin, "{}", arch_prefix).unwrap();
299            }
300            begin.write_fmt(format_args!("{0}:\n", asm_name))writeln!(begin, "{asm_name}:").unwrap();
301            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();
302
303            end.write_fmt(format_args!("\n"))writeln!(end).unwrap();
304            // .size is ignored for function symbols, so we can skip it
305            end.write_fmt(format_args!("end_function\n"))writeln!(end, "end_function").unwrap();
306            end.write_fmt(format_args!(".Lfunc_end_{0}:\n", asm_name))writeln!(end, ".Lfunc_end_{asm_name}:").unwrap();
307        }
308        BinaryFormat::Xcoff => {
309            // the LLVM XCOFFAsmParser is extremely incomplete and does not implement many of the
310            // documented directives.
311            //
312            // - https://github.com/llvm/llvm-project/blob/1b25c0c4da968fe78921ce77736e5baef4db75e3/llvm/lib/MC/MCParser/XCOFFAsmParser.cpp
313            // - https://www.ibm.com/docs/en/ssw_aix_71/assembler/assembler_pdf.pdf
314            //
315            // Consequently, we try our best here but cannot do as good a job as for other binary
316            // formats.
317
318            // FIXME: start a section. `.csect` is not currently implemented in LLVM
319
320            // fun fact: according to the assembler documentation, .align takes an exponent,
321            // but LLVM only accepts powers of 2 (but does emit the exponent)
322            // so when we hand `.align 32` to LLVM, the assembly output will contain `.align 5`
323            begin.write_fmt(format_args!(".align {0}\n", align_bytes))writeln!(begin, ".align {}", align_bytes).unwrap();
324
325            write_linkage(&mut begin).unwrap();
326            if let Visibility::Hidden = visibility {
327                // FIXME apparently `.globl {asm_name}, hidden` is valid
328                // but due to limitations with `.weak` (see above) we can't really use that in general yet
329            }
330            begin.write_fmt(format_args!("{0}:\n", asm_name))writeln!(begin, "{asm_name}:").unwrap();
331
332            end.write_fmt(format_args!("\n"))writeln!(end).unwrap();
333            // FIXME: end the section?
334        }
335    }
336
337    (begin, end)
338}
339
340/// The webassembly type signature for the given function.
341///
342/// Used by the `.functype` directive on wasm targets.
343fn wasm_functype<'tcx>(tcx: TyCtxt<'tcx>, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> String {
344    let mut signature = String::with_capacity(64);
345
346    let ptr_type = match tcx.data_layout.pointer_size().bits() {
347        32 => "i32",
348        64 => "i64",
349        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"),
350    };
351
352    let hidden_return = #[allow(non_exhaustive_omitted_patterns)] match fn_abi.ret.mode {
    PassMode::Indirect { .. } => true,
    _ => false,
}matches!(fn_abi.ret.mode, PassMode::Indirect { .. });
353
354    signature.push('(');
355
356    if hidden_return {
357        signature.push_str(ptr_type);
358        if !fn_abi.args.is_empty() {
359            signature.push_str(", ");
360        }
361    }
362
363    let mut it = fn_abi.args.iter().peekable();
364    while let Some(arg_abi) = it.next() {
365        wasm_type(&mut signature, arg_abi, ptr_type);
366        if it.peek().is_some() {
367            signature.push_str(", ");
368        }
369    }
370
371    signature.push_str(") -> (");
372
373    if !hidden_return {
374        wasm_type(&mut signature, &fn_abi.ret, ptr_type);
375    }
376
377    signature.push(')');
378
379    signature
380}
381
382fn wasm_type<'tcx>(signature: &mut String, arg_abi: &ArgAbi<'_, Ty<'tcx>>, ptr_type: &'static str) {
383    match arg_abi.mode {
384        PassMode::Ignore => { /* do nothing */ }
385        PassMode::Direct(_) => {
386            let direct_type = match arg_abi.layout.backend_repr {
387                BackendRepr::Scalar(scalar) => wasm_primitive(scalar.primitive(), ptr_type),
388                BackendRepr::SimdVector { .. } => "v128",
389                other => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected BackendRepr: {0:?}", other)));
}unreachable!("unexpected BackendRepr: {:?}", other),
390            };
391
392            signature.push_str(direct_type);
393        }
394        PassMode::Pair(_, _) => match arg_abi.layout.backend_repr {
395            BackendRepr::ScalarPair(a, b) => {
396                signature.push_str(wasm_primitive(a.primitive(), ptr_type));
397                signature.push_str(", ");
398                signature.push_str(wasm_primitive(b.primitive(), ptr_type));
399            }
400            other => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("{0:?}", other)));
}unreachable!("{other:?}"),
401        },
402        PassMode::Cast { pad_i32, ref cast } => {
403            // For wasm, Cast is used for single-field primitive wrappers like `struct Wrapper(i64);`
404            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");
405            if !cast.prefix[0].is_none() {
    { ::core::panicking::panic_fmt(format_args!("no prefix")); }
};assert!(cast.prefix[0].is_none(), "no prefix");
406            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");
407
408            let wrapped_wasm_type = match cast.rest.unit.kind {
409                RegKind::Integer => match cast.rest.unit.size.bytes() {
410                    ..=4 => "i32",
411                    ..=8 => "i64",
412                    _ => ptr_type,
413                },
414                RegKind::Float => match cast.rest.unit.size.bytes() {
415                    ..=4 => "f32",
416                    ..=8 => "f64",
417                    _ => ptr_type,
418                },
419                RegKind::Vector => "v128",
420            };
421
422            signature.push_str(wrapped_wasm_type);
423        }
424        PassMode::Indirect { .. } => signature.push_str(ptr_type),
425    }
426}
427
428fn wasm_primitive(primitive: Primitive, ptr_type: &'static str) -> &'static str {
429    match primitive {
430        Primitive::Int(integer, _) => match integer {
431            Integer::I8 | Integer::I16 | Integer::I32 => "i32",
432            Integer::I64 => "i64",
433            Integer::I128 => "i64, i64",
434        },
435        Primitive::Float(float) => match float {
436            Float::F16 | Float::F32 => "f32",
437            Float::F64 => "f64",
438            Float::F128 => "i64, i64",
439        },
440        Primitive::Pointer(_) => ptr_type,
441    }
442}