rustc_codegen_ssa/mir/
naked_asm.rs

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