Skip to main content

rustc_codegen_llvm/
asm.rs

1use std::assert_matches;
2
3use rustc_abi::{BackendRepr, Float, Integer, Primitive, Scalar};
4use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
5use rustc_codegen_ssa::mir::operand::OperandValue;
6use rustc_codegen_ssa::traits::*;
7use rustc_data_structures::fx::FxHashMap;
8use rustc_middle::ty::Instance;
9use rustc_middle::ty::layout::TyAndLayout;
10use rustc_middle::{bug, span_bug};
11use rustc_span::{Pos, Span, Symbol, sym};
12use rustc_target::asm::*;
13use smallvec::SmallVec;
14use tracing::debug;
15
16use crate::attributes;
17use crate::builder::Builder;
18use crate::common::Funclet;
19use crate::context::CodegenCx;
20use crate::llvm::{self, ToLlvmBool, Type, Value};
21use crate::type_of::LayoutLlvmExt;
22
23impl<'ll, 'tcx> AsmBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
24    fn codegen_inline_asm(
25        &mut self,
26        template: &[InlineAsmTemplatePiece],
27        operands: &[InlineAsmOperandRef<'tcx, Self>],
28        options: InlineAsmOptions,
29        line_spans: &[Span],
30        instance: Instance<'_>,
31        dest: Option<Self::BasicBlock>,
32        catch_funclet: Option<(Self::BasicBlock, Option<&Self::Funclet>)>,
33    ) {
34        let asm_arch = self.tcx.sess.asm_arch.unwrap();
35
36        // Collect the types of output operands
37        let mut constraints = ::alloc::vec::Vec::new()vec![];
38        let mut clobbers = ::alloc::vec::Vec::new()vec![];
39        let mut output_types = ::alloc::vec::Vec::new()vec![];
40        let mut op_idx = FxHashMap::default();
41        let mut clobbered_x87 = false;
42        for (idx, op) in operands.iter().enumerate() {
43            match *op {
44                InlineAsmOperandRef::Out { reg, late, place } => {
45                    let is_target_supported = |reg_class: InlineAsmRegClass| {
46                        for &(_, feature) in reg_class.supported_types(asm_arch, true).as_ref() {
47                            if let Some(feature) = feature {
48                                if self
49                                    .tcx
50                                    .asm_target_features(instance.def_id())
51                                    .contains(&feature)
52                                {
53                                    return true;
54                                }
55                            } else {
56                                // Register class is unconditionally supported
57                                return true;
58                            }
59                        }
60                        false
61                    };
62
63                    let mut layout = None;
64                    let ty = if let Some(ref place) = place {
65                        layout = Some(&place.layout);
66                        llvm_fixup_output_type(self.cx, reg.reg_class(), &place.layout, instance)
67                    } else if #[allow(non_exhaustive_omitted_patterns)] match reg.reg_class() {
    InlineAsmRegClass::X86(X86InlineAsmRegClass::mmx_reg |
        X86InlineAsmRegClass::x87_reg) => true,
    _ => false,
}matches!(
68                        reg.reg_class(),
69                        InlineAsmRegClass::X86(
70                            X86InlineAsmRegClass::mmx_reg | X86InlineAsmRegClass::x87_reg
71                        )
72                    ) {
73                        // Special handling for x87/mmx registers: we always
74                        // clobber the whole set if one register is marked as
75                        // clobbered. This is due to the way LLVM handles the
76                        // FP stack in inline assembly.
77                        if !clobbered_x87 {
78                            clobbered_x87 = true;
79                            clobbers.push("~{st}".to_string());
80                            for i in 1..=7 {
81                                clobbers.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("~{{st({0})}}", i))
    })format!("~{{st({})}}", i));
82                            }
83                        }
84                        continue;
85                    } else if !is_target_supported(reg.reg_class())
86                        || reg.reg_class().is_clobber_only(asm_arch, true)
87                    {
88                        // We turn discarded outputs into clobber constraints
89                        // if the target feature needed by the register class is
90                        // disabled. This is necessary otherwise LLVM will try
91                        // to actually allocate a register for the dummy output.
92                        {
    match reg {
        InlineAsmRegOrRegClass::Reg(_) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "InlineAsmRegOrRegClass::Reg(_)",
                ::core::option::Option::None);
        }
    }
};assert_matches!(reg, InlineAsmRegOrRegClass::Reg(_));
93                        clobbers.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("~{0}", reg_to_llvm(reg, None)))
    })format!("~{}", reg_to_llvm(reg, None)));
94                        continue;
95                    } else {
96                        // If the output is discarded, we don't really care what
97                        // type is used. We're just using this to tell LLVM to
98                        // reserve the register.
99                        dummy_output_type(self.cx, reg.reg_class())
100                    };
101                    output_types.push(ty);
102                    op_idx.insert(idx, constraints.len());
103                    let prefix = if late { "=" } else { "=&" };
104                    constraints.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", prefix,
                reg_to_llvm(reg, layout)))
    })format!("{}{}", prefix, reg_to_llvm(reg, layout)));
105                }
106                InlineAsmOperandRef::InOut { reg, late, in_value, out_place } => {
107                    let layout = if let Some(ref out_place) = out_place {
108                        &out_place.layout
109                    } else {
110                        // LLVM required tied operands to have the same type,
111                        // so we just use the type of the input.
112                        &in_value.layout
113                    };
114                    let ty = llvm_fixup_output_type(self.cx, reg.reg_class(), layout, instance);
115                    output_types.push(ty);
116                    op_idx.insert(idx, constraints.len());
117                    let prefix = if late { "=" } else { "=&" };
118                    constraints.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", prefix,
                reg_to_llvm(reg, Some(layout))))
    })format!("{}{}", prefix, reg_to_llvm(reg, Some(layout))));
119                }
120                _ => {}
121            }
122        }
123
124        // Collect input operands
125        let mut inputs = ::alloc::vec::Vec::new()vec![];
126        for (idx, op) in operands.iter().enumerate() {
127            match *op {
128                InlineAsmOperandRef::In { reg, value } => {
129                    let llval = llvm_fixup_input(
130                        self,
131                        value.immediate(),
132                        reg.reg_class(),
133                        &value.layout,
134                        instance,
135                    );
136                    inputs.push(llval);
137                    op_idx.insert(idx, constraints.len());
138                    constraints.push(reg_to_llvm(reg, Some(&value.layout)));
139                }
140                InlineAsmOperandRef::InOut { reg, late, in_value, out_place: _ } => {
141                    let value = llvm_fixup_input(
142                        self,
143                        in_value.immediate(),
144                        reg.reg_class(),
145                        &in_value.layout,
146                        instance,
147                    );
148                    inputs.push(value);
149
150                    // In the case of fixed registers, we have the choice of
151                    // either using a tied operand or duplicating the constraint.
152                    // We prefer the latter because it matches the behavior of
153                    // Clang.
154                    if late && #[allow(non_exhaustive_omitted_patterns)] match reg {
    InlineAsmRegOrRegClass::Reg(_) => true,
    _ => false,
}matches!(reg, InlineAsmRegOrRegClass::Reg(_)) {
155                        constraints.push(reg_to_llvm(reg, Some(&in_value.layout)));
156                    } else {
157                        constraints.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", op_idx[&idx]))
    })format!("{}", op_idx[&idx]));
158                    }
159                }
160                InlineAsmOperandRef::SymFn { instance } => {
161                    inputs.push(self.cx.get_fn(instance));
162                    op_idx.insert(idx, constraints.len());
163                    constraints.push("s".to_string());
164                }
165                InlineAsmOperandRef::SymStatic { def_id } => {
166                    inputs.push(self.cx.get_static(def_id));
167                    op_idx.insert(idx, constraints.len());
168                    constraints.push("s".to_string());
169                }
170                _ => {}
171            }
172        }
173
174        // Build the template string
175        let mut labels = ::alloc::vec::Vec::new()vec![];
176        let mut template_str = String::new();
177        for piece in template {
178            match *piece {
179                InlineAsmTemplatePiece::String(ref s) => {
180                    if s.contains('$') {
181                        for c in s.chars() {
182                            if c == '$' {
183                                template_str.push_str("$$");
184                            } else {
185                                template_str.push(c);
186                            }
187                        }
188                    } else {
189                        template_str.push_str(s)
190                    }
191                }
192                InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => {
193                    match operands[operand_idx] {
194                        InlineAsmOperandRef::In { reg, .. }
195                        | InlineAsmOperandRef::Out { reg, .. }
196                        | InlineAsmOperandRef::InOut { reg, .. } => {
197                            let modifier = modifier_to_llvm(asm_arch, reg.reg_class(), modifier);
198                            if let Some(modifier) = modifier {
199                                template_str.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${{{0}:{1}}}",
                op_idx[&operand_idx], modifier))
    })format!(
200                                    "${{{}:{}}}",
201                                    op_idx[&operand_idx], modifier
202                                ));
203                            } else {
204                                template_str.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${{{0}}}", op_idx[&operand_idx]))
    })format!("${{{}}}", op_idx[&operand_idx]));
205                            }
206                        }
207                        InlineAsmOperandRef::Const { ref string } => {
208                            // Const operands get injected directly into the template
209                            template_str.push_str(string);
210                        }
211                        InlineAsmOperandRef::SymFn { .. }
212                        | InlineAsmOperandRef::SymStatic { .. } => {
213                            // Only emit the raw symbol name
214                            template_str.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${{{0}:c}}", op_idx[&operand_idx]))
    })format!("${{{}:c}}", op_idx[&operand_idx]));
215                        }
216                        InlineAsmOperandRef::Label { label } => {
217                            template_str.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${{{0}:l}}", constraints.len()))
    })format!("${{{}:l}}", constraints.len()));
218                            constraints.push("!i".to_owned());
219                            labels.push(label);
220                        }
221                    }
222                }
223            }
224        }
225
226        constraints.append(&mut clobbers);
227        if !options.contains(InlineAsmOptions::PRESERVES_FLAGS) {
228            match asm_arch {
229                InlineAsmArch::AArch64 | InlineAsmArch::Arm64EC | InlineAsmArch::Arm => {
230                    constraints.push("~{cc}".to_string());
231                }
232                InlineAsmArch::Amdgpu => {}
233                InlineAsmArch::X86 | InlineAsmArch::X86_64 => {
234                    constraints.extend_from_slice(&[
235                        "~{dirflag}".to_string(),
236                        "~{fpsr}".to_string(),
237                        "~{flags}".to_string(),
238                    ]);
239                }
240                InlineAsmArch::RiscV32 | InlineAsmArch::RiscV64 => {
241                    constraints.extend_from_slice(&[
242                        "~{fflags}".to_string(),
243                        "~{vtype}".to_string(),
244                        "~{vl}".to_string(),
245                        "~{vxsat}".to_string(),
246                        "~{vxrm}".to_string(),
247                    ]);
248                }
249                InlineAsmArch::Avr => {
250                    constraints.push("~{sreg}".to_string());
251                }
252                InlineAsmArch::Nvptx64 => {}
253                InlineAsmArch::PowerPC | InlineAsmArch::PowerPC64 => {}
254                InlineAsmArch::Hexagon => {}
255                InlineAsmArch::LoongArch32 | InlineAsmArch::LoongArch64 => {
256                    constraints.extend_from_slice(&[
257                        "~{$fcc0}".to_string(),
258                        "~{$fcc1}".to_string(),
259                        "~{$fcc2}".to_string(),
260                        "~{$fcc3}".to_string(),
261                        "~{$fcc4}".to_string(),
262                        "~{$fcc5}".to_string(),
263                        "~{$fcc6}".to_string(),
264                        "~{$fcc7}".to_string(),
265                    ]);
266                }
267                InlineAsmArch::Mips | InlineAsmArch::Mips64 => {}
268                InlineAsmArch::S390x => {
269                    constraints.push("~{cc}".to_string());
270                }
271                InlineAsmArch::Sparc | InlineAsmArch::Sparc64 => {
272                    // In LLVM, ~{icc} represents icc and xcc in 64-bit code.
273                    // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/Sparc/SparcRegisterInfo.td#L64
274                    constraints.push("~{icc}".to_string());
275                    constraints.push("~{fcc0}".to_string());
276                    constraints.push("~{fcc1}".to_string());
277                    constraints.push("~{fcc2}".to_string());
278                    constraints.push("~{fcc3}".to_string());
279                }
280                InlineAsmArch::SpirV => {}
281                InlineAsmArch::Wasm32 | InlineAsmArch::Wasm64 => {}
282                InlineAsmArch::Xtensa => {}
283                InlineAsmArch::Bpf => {}
284                InlineAsmArch::Msp430 => {
285                    constraints.push("~{sr}".to_string());
286                }
287                InlineAsmArch::M68k => {
288                    constraints.push("~{ccr}".to_string());
289                }
290                InlineAsmArch::CSKY => {
291                    constraints.push("~{psr}".to_string());
292                }
293            }
294        }
295        if !options.contains(InlineAsmOptions::NOMEM) {
296            // This is actually ignored by LLVM, but it's probably best to keep
297            // it just in case. LLVM instead uses the ReadOnly/ReadNone
298            // attributes on the call instruction to optimize.
299            constraints.push("~{memory}".to_string());
300        }
301        let volatile = !options.contains(InlineAsmOptions::PURE);
302        let alignstack = !options.contains(InlineAsmOptions::NOSTACK);
303        let output_type = match &output_types[..] {
304            [] => self.type_void(),
305            [ty] => ty,
306            tys => self.type_struct(tys, false),
307        };
308        let dialect = match asm_arch {
309            InlineAsmArch::X86 | InlineAsmArch::X86_64
310                if !options.contains(InlineAsmOptions::ATT_SYNTAX) =>
311            {
312                llvm::AsmDialect::Intel
313            }
314            _ => llvm::AsmDialect::Att,
315        };
316        let result = inline_asm_call(
317            self,
318            &template_str,
319            &constraints.join(","),
320            &inputs,
321            output_type,
322            &labels,
323            volatile,
324            alignstack,
325            dialect,
326            line_spans,
327            options.contains(InlineAsmOptions::MAY_UNWIND),
328            dest,
329            catch_funclet,
330        )
331        .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(line_spans[0],
    format_args!("LLVM asm constraint validation failed"))span_bug!(line_spans[0], "LLVM asm constraint validation failed"));
332
333        let mut attrs = SmallVec::<[_; 2]>::new();
334        if options.contains(InlineAsmOptions::PURE) {
335            if options.contains(InlineAsmOptions::NOMEM) {
336                attrs.push(llvm::MemoryEffects::None.create_attr(self.cx.llcx));
337            } else if options.contains(InlineAsmOptions::READONLY) {
338                attrs.push(llvm::MemoryEffects::ReadOnly.create_attr(self.cx.llcx));
339            }
340            attrs.push(llvm::AttributeKind::WillReturn.create_attr(self.cx.llcx));
341        } else if options.contains(InlineAsmOptions::NOMEM) {
342            attrs.push(llvm::MemoryEffects::InaccessibleMemOnly.create_attr(self.cx.llcx));
343        } else if options.contains(InlineAsmOptions::READONLY) {
344            attrs.push(llvm::MemoryEffects::ReadOnlyNotPure.create_attr(self.cx.llcx));
345        }
346        attributes::apply_to_callsite(result, llvm::AttributePlace::Function, &{ attrs });
347
348        // Write results to outputs. We need to do this for all possible control flow.
349        //
350        // Note that `dest` maybe populated with unreachable_block when asm goto with outputs
351        // is used (because we need to codegen callbr which always needs a destination), so
352        // here we use the NORETURN option to determine if `dest` should be used.
353        for block in (if options.contains(InlineAsmOptions::NORETURN) { None } else { Some(dest) })
354            .into_iter()
355            .chain(labels.iter().copied().map(Some))
356        {
357            if let Some(block) = block {
358                self.switch_to_block(block);
359            }
360
361            for (idx, op) in operands.iter().enumerate() {
362                if let InlineAsmOperandRef::Out { reg, place: Some(place), .. }
363                | InlineAsmOperandRef::InOut { reg, out_place: Some(place), .. } = *op
364                {
365                    let value = if output_types.len() == 1 {
366                        result
367                    } else {
368                        self.extract_value(result, op_idx[&idx] as u64)
369                    };
370                    let value =
371                        llvm_fixup_output(self, value, reg.reg_class(), &place.layout, instance);
372                    OperandValue::Immediate(value).store(self, place);
373                }
374            }
375        }
376    }
377}
378
379impl<'tcx> AsmCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> {
380    fn codegen_global_asm(
381        &mut self,
382        template: &[InlineAsmTemplatePiece],
383        operands: &[GlobalAsmOperandRef<'tcx>],
384        options: InlineAsmOptions,
385        _line_spans: &[Span],
386    ) {
387        let asm_arch = self.tcx.sess.asm_arch.unwrap();
388
389        // Build the template string
390        let mut template_str = String::new();
391
392        // On X86 platforms there are two assembly syntaxes. Rust uses intel by default,
393        // but AT&T can be specified explicitly.
394        if #[allow(non_exhaustive_omitted_patterns)] match asm_arch {
    InlineAsmArch::X86 | InlineAsmArch::X86_64 => true,
    _ => false,
}matches!(asm_arch, InlineAsmArch::X86 | InlineAsmArch::X86_64) {
395            if options.contains(InlineAsmOptions::ATT_SYNTAX) {
396                template_str.push_str(".att_syntax\n")
397            } else {
398                template_str.push_str(".intel_syntax\n")
399            }
400        }
401
402        for piece in template {
403            match *piece {
404                InlineAsmTemplatePiece::String(ref s) => template_str.push_str(s),
405                InlineAsmTemplatePiece::Placeholder { operand_idx, modifier: _, span } => {
406                    use rustc_codegen_ssa::back::symbol_export::escape_symbol_name;
407                    match operands[operand_idx] {
408                        GlobalAsmOperandRef::Const { ref string } => {
409                            // Const operands get injected directly into the
410                            // template. Note that we don't need to escape $
411                            // here unlike normal inline assembly.
412                            template_str.push_str(string);
413                        }
414                        GlobalAsmOperandRef::SymFn { instance } => {
415                            let llval = self.get_fn(instance);
416                            self.add_compiler_used_global(llval);
417                            let symbol = llvm::build_string(|s| unsafe {
418                                llvm::LLVMRustGetMangledName(llval, s);
419                            })
420                            .expect("symbol is not valid UTF-8");
421                            template_str.push_str(&escape_symbol_name(self.tcx, &symbol, span));
422                        }
423                        GlobalAsmOperandRef::SymStatic { def_id } => {
424                            let llval = self
425                                .renamed_statics
426                                .borrow()
427                                .get(&def_id)
428                                .copied()
429                                .unwrap_or_else(|| self.get_static(def_id));
430                            self.add_compiler_used_global(llval);
431                            let symbol = llvm::build_string(|s| unsafe {
432                                llvm::LLVMRustGetMangledName(llval, s);
433                            })
434                            .expect("symbol is not valid UTF-8");
435                            template_str.push_str(&escape_symbol_name(self.tcx, &symbol, span));
436                        }
437                    }
438                }
439            }
440        }
441
442        // Just to play it safe, if intel was used, reset the assembly syntax to att.
443        if #[allow(non_exhaustive_omitted_patterns)] match asm_arch {
    InlineAsmArch::X86 | InlineAsmArch::X86_64 => true,
    _ => false,
}matches!(asm_arch, InlineAsmArch::X86 | InlineAsmArch::X86_64)
444            && !options.contains(InlineAsmOptions::ATT_SYNTAX)
445        {
446            template_str.push_str("\n.att_syntax\n");
447        }
448
449        llvm::append_module_inline_asm(self.llmod, template_str.as_bytes());
450    }
451
452    fn mangled_name(&self, instance: Instance<'tcx>) -> String {
453        let llval = self.get_fn(instance);
454        llvm::build_string(|s| unsafe {
455            llvm::LLVMRustGetMangledName(llval, s);
456        })
457        .expect("symbol is not valid UTF-8")
458    }
459}
460
461pub(crate) fn inline_asm_call<'ll>(
462    bx: &mut Builder<'_, 'll, '_>,
463    asm: &str,
464    cons: &str,
465    inputs: &[&'ll Value],
466    output: &'ll llvm::Type,
467    labels: &[&'ll llvm::BasicBlock],
468    volatile: bool,
469    alignstack: bool,
470    dia: llvm::AsmDialect,
471    line_spans: &[Span],
472    unwind: bool,
473    dest: Option<&'ll llvm::BasicBlock>,
474    catch_funclet: Option<(&'ll llvm::BasicBlock, Option<&Funclet<'ll>>)>,
475) -> Option<&'ll Value> {
476    let argtys = inputs
477        .iter()
478        .map(|v| {
479            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/asm.rs:479",
                        "rustc_codegen_llvm::asm", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/asm.rs"),
                        ::tracing_core::__macro_support::Option::Some(479u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::asm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Asm Input Type: {0:?}",
                                                    *v) as &dyn Value))])
            });
    } else { ; }
};debug!("Asm Input Type: {:?}", *v);
480            bx.cx.val_ty(*v)
481        })
482        .collect::<Vec<_>>();
483
484    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/asm.rs:484",
                        "rustc_codegen_llvm::asm", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/asm.rs"),
                        ::tracing_core::__macro_support::Option::Some(484u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::asm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Asm Output Type: {0:?}",
                                                    output) as &dyn Value))])
            });
    } else { ; }
};debug!("Asm Output Type: {:?}", output);
485    let fty = bx.cx.type_func(&argtys, output);
486
487    // Ask LLVM to verify that the constraints are well-formed.
488    let constraints_ok = unsafe { llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr(), cons.len()) };
489    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/asm.rs:489",
                        "rustc_codegen_llvm::asm", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/asm.rs"),
                        ::tracing_core::__macro_support::Option::Some(489u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::asm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("constraint verification result: {0:?}",
                                                    constraints_ok) as &dyn Value))])
            });
    } else { ; }
};debug!("constraint verification result: {:?}", constraints_ok);
490    if !constraints_ok {
491        // LLVM has detected an issue with our constraints, so bail out.
492        return None;
493    }
494
495    let v = unsafe {
496        llvm::LLVMGetInlineAsm(
497            fty,
498            asm.as_ptr(),
499            asm.len(),
500            cons.as_ptr(),
501            cons.len(),
502            volatile.to_llvm_bool(),
503            alignstack.to_llvm_bool(),
504            dia,
505            unwind.to_llvm_bool(),
506        )
507    };
508
509    let call = if !labels.is_empty() {
510        if !catch_funclet.is_none() {
    ::core::panicking::panic("assertion failed: catch_funclet.is_none()")
};assert!(catch_funclet.is_none());
511        bx.callbr(fty, None, None, v, inputs, dest.unwrap(), labels, None, None)
512    } else if let Some((catch, funclet)) = catch_funclet {
513        bx.invoke(fty, None, None, v, inputs, dest.unwrap(), catch, funclet, None)
514    } else {
515        bx.call(fty, None, None, v, inputs, None, None)
516    };
517
518    // Store mark in a metadata node so we can map LLVM errors
519    // back to source locations. See #17552.
520    let key = "srcloc";
521    let kind = bx.get_md_kind_id(key);
522
523    // `srcloc` contains one 64-bit integer for each line of assembly code,
524    // where the lower 32 bits hold the lo byte position and the upper 32 bits
525    // hold the hi byte position.
526    let mut srcloc = ::alloc::vec::Vec::new()vec![];
527    if dia == llvm::AsmDialect::Intel && line_spans.len() > 1 {
528        // LLVM inserts an extra line to add the ".intel_syntax", so add
529        // a dummy srcloc entry for it.
530        //
531        // Don't do this if we only have 1 line span since that may be
532        // due to the asm template string coming from a macro. LLVM will
533        // default to the first srcloc for lines that don't have an
534        // associated srcloc.
535        srcloc.push(llvm::LLVMValueAsMetadata(bx.const_u64(0)));
536    }
537    srcloc.extend(line_spans.iter().map(|span| {
538        llvm::LLVMValueAsMetadata(
539            bx.const_u64(u64::from(span.lo().to_u32()) | (u64::from(span.hi().to_u32()) << 32)),
540        )
541    }));
542    bx.cx.set_metadata_node(call, kind, &srcloc);
543
544    Some(call)
545}
546
547/// If the register is an xmm/ymm/zmm register then return its index.
548fn xmm_reg_index(reg: InlineAsmReg) -> Option<u32> {
549    use X86InlineAsmReg::*;
550    match reg {
551        InlineAsmReg::X86(reg) if reg as u32 >= xmm0 as u32 && reg as u32 <= xmm15 as u32 => {
552            Some(reg as u32 - xmm0 as u32)
553        }
554        InlineAsmReg::X86(reg) if reg as u32 >= ymm0 as u32 && reg as u32 <= ymm15 as u32 => {
555            Some(reg as u32 - ymm0 as u32)
556        }
557        InlineAsmReg::X86(reg) if reg as u32 >= zmm0 as u32 && reg as u32 <= zmm31 as u32 => {
558            Some(reg as u32 - zmm0 as u32)
559        }
560        _ => None,
561    }
562}
563
564/// If the register is an AArch64 integer register then return its index.
565fn a64_reg_index(reg: InlineAsmReg) -> Option<u32> {
566    match reg {
567        InlineAsmReg::AArch64(r) => r.reg_index(),
568        _ => None,
569    }
570}
571
572/// If the register is an AArch64 vector register then return its index.
573fn a64_vreg_index(reg: InlineAsmReg) -> Option<u32> {
574    match reg {
575        InlineAsmReg::AArch64(reg) => reg.vreg_index(),
576        _ => None,
577    }
578}
579
580/// If the register is a Hexagon register pair then return its LLVM double register index.
581/// LLVM uses `d0`, `d1`, ... for Hexagon double registers in inline asm constraints,
582/// not the assembly-printed `r1:0`, `r3:2`, ... format.
583fn hexagon_reg_pair_index(reg: InlineAsmReg) -> Option<u32> {
584    match reg {
585        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r1_0) => Some(0),
586        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r3_2) => Some(1),
587        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r5_4) => Some(2),
588        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r7_6) => Some(3),
589        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r9_8) => Some(4),
590        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r11_10) => Some(5),
591        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r13_12) => Some(6),
592        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r15_14) => Some(7),
593        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r17_16) => Some(8),
594        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r21_20) => Some(10),
595        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r23_22) => Some(11),
596        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r25_24) => Some(12),
597        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r27_26) => Some(13),
598        _ => None,
599    }
600}
601
602/// If the register is a Hexagon HVX vector pair then return its LLVM W-register index.
603/// LLVM uses `w0`, `w1`, ... for Hexagon vector pair registers in inline asm constraints.
604fn hexagon_vreg_pair_index(reg: InlineAsmReg) -> Option<u32> {
605    match reg {
606        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v1_0) => Some(0),
607        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v3_2) => Some(1),
608        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v5_4) => Some(2),
609        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v7_6) => Some(3),
610        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v9_8) => Some(4),
611        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v11_10) => Some(5),
612        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v13_12) => Some(6),
613        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v15_14) => Some(7),
614        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v17_16) => Some(8),
615        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v19_18) => Some(9),
616        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v21_20) => Some(10),
617        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v23_22) => Some(11),
618        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v25_24) => Some(12),
619        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v27_26) => Some(13),
620        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v29_28) => Some(14),
621        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v31_30) => Some(15),
622        _ => None,
623    }
624}
625
626/// Converts a register class to an LLVM constraint code.
627fn reg_to_llvm(reg: InlineAsmRegOrRegClass, layout: Option<&TyAndLayout<'_>>) -> String {
628    use InlineAsmRegClass::*;
629    match reg {
630        // For vector registers LLVM wants the register name to match the type size.
631        InlineAsmRegOrRegClass::Reg(reg) => {
632            if let Some(idx) = xmm_reg_index(reg) {
633                let class = if let Some(layout) = layout {
634                    match layout.size.bytes() {
635                        64 => 'z',
636                        32 => 'y',
637                        _ => 'x',
638                    }
639                } else {
640                    // We use f32 as the type for discarded outputs
641                    'x'
642                };
643                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}mm{1}}}", class, idx))
    })format!("{{{}mm{}}}", class, idx)
644            } else if let Some(idx) = a64_reg_index(reg) {
645                let class = if let Some(layout) = layout {
646                    match layout.size.bytes() {
647                        8 => 'x',
648                        _ => 'w',
649                    }
650                } else {
651                    // We use i32 as the type for discarded outputs
652                    'w'
653                };
654                if class == 'x' && reg == InlineAsmReg::AArch64(AArch64InlineAsmReg::x30) {
655                    // LLVM doesn't recognize x30. use lr instead.
656                    "{lr}".to_string()
657                } else {
658                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}{1}}}", class, idx))
    })format!("{{{}{}}}", class, idx)
659                }
660            } else if let Some(idx) = a64_vreg_index(reg) {
661                let class = if let Some(layout) = layout {
662                    match layout.size.bytes() {
663                        16 => 'q',
664                        8 => 'd',
665                        4 => 's',
666                        2 => 'h',
667                        1 => 'd', // We fixup i8 to i8x8
668                        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
669                    }
670                } else {
671                    // We use i64x2 as the type for discarded outputs
672                    'q'
673                };
674                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}{1}}}", class, idx))
    })format!("{{{}{}}}", class, idx)
675            } else if let Some(idx) = hexagon_reg_pair_index(reg) {
676                // LLVM uses `dN` for Hexagon double registers, not the `rN+1:N` asm syntax.
677                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{d{0}}}", idx))
    })format!("{{d{}}}", idx)
678            } else if let Some(idx) = hexagon_vreg_pair_index(reg) {
679                // LLVM uses `wN` for Hexagon HVX vector pair registers.
680                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{w{0}}}", idx))
    })format!("{{w{}}}", idx)
681            } else if reg == InlineAsmReg::Arm(ArmInlineAsmReg::r14) {
682                // LLVM doesn't recognize r14
683                "{lr}".to_string()
684            } else {
685                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}}}", reg.name()))
    })format!("{{{}}}", reg.name())
686            }
687        }
688        // The constraints can be retrieved from
689        // https://llvm.org/docs/LangRef.html#supported-constraint-code-list
690        InlineAsmRegOrRegClass::RegClass(reg) => match reg {
691            AArch64(AArch64InlineAsmRegClass::reg) => "r",
692            AArch64(AArch64InlineAsmRegClass::vreg) => "w",
693            AArch64(AArch64InlineAsmRegClass::vreg_low16) => "x",
694            AArch64(AArch64InlineAsmRegClass::preg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
695            Arm(ArmInlineAsmRegClass::reg) => "r",
696            Arm(ArmInlineAsmRegClass::sreg)
697            | Arm(ArmInlineAsmRegClass::dreg_low16)
698            | Arm(ArmInlineAsmRegClass::qreg_low8) => "t",
699            Arm(ArmInlineAsmRegClass::sreg_low16)
700            | Arm(ArmInlineAsmRegClass::dreg_low8)
701            | Arm(ArmInlineAsmRegClass::qreg_low4) => "x",
702            Arm(ArmInlineAsmRegClass::dreg) | Arm(ArmInlineAsmRegClass::qreg) => "w",
703            Amdgpu(AmdgpuInlineAsmRegClass::Sgpr(_)) => "s",
704            Amdgpu(AmdgpuInlineAsmRegClass::Vgpr(_)) => "v",
705            Hexagon(HexagonInlineAsmRegClass::reg) => "r",
706            Hexagon(HexagonInlineAsmRegClass::reg_pair) => "r",
707            Hexagon(HexagonInlineAsmRegClass::preg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
708            Hexagon(HexagonInlineAsmRegClass::vreg) => "v",
709            Hexagon(HexagonInlineAsmRegClass::vreg_pair) => "v",
710            Hexagon(HexagonInlineAsmRegClass::qreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
711            LoongArch(LoongArchInlineAsmRegClass::reg) => "r",
712            LoongArch(LoongArchInlineAsmRegClass::freg)
713            | LoongArch(LoongArchInlineAsmRegClass::vreg)
714            | LoongArch(LoongArchInlineAsmRegClass::xreg) => "f",
715            Mips(MipsInlineAsmRegClass::reg) => "r",
716            Mips(MipsInlineAsmRegClass::freg) => "f",
717            Nvptx(NvptxInlineAsmRegClass::reg16) => "h",
718            Nvptx(NvptxInlineAsmRegClass::reg32) => "r",
719            Nvptx(NvptxInlineAsmRegClass::reg64) => "l",
720            PowerPC(PowerPCInlineAsmRegClass::reg) => "r",
721            PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => "b",
722            PowerPC(PowerPCInlineAsmRegClass::freg) => "f",
723            PowerPC(PowerPCInlineAsmRegClass::vreg) => "v",
724            PowerPC(PowerPCInlineAsmRegClass::vsreg) => "^wa",
725            PowerPC(
726                PowerPCInlineAsmRegClass::cr
727                | PowerPCInlineAsmRegClass::ctr
728                | PowerPCInlineAsmRegClass::lr
729                | PowerPCInlineAsmRegClass::xer
730                | PowerPCInlineAsmRegClass::spe_acc,
731            ) => {
732                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
733            }
734            RiscV(RiscVInlineAsmRegClass::reg) => "r",
735            RiscV(RiscVInlineAsmRegClass::freg) => "f",
736            RiscV(RiscVInlineAsmRegClass::vreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
737            X86(X86InlineAsmRegClass::reg) => "r",
738            X86(X86InlineAsmRegClass::reg_abcd) => "Q",
739            X86(X86InlineAsmRegClass::reg_byte) => "q",
740            X86(X86InlineAsmRegClass::xmm_reg) | X86(X86InlineAsmRegClass::ymm_reg) => "x",
741            X86(X86InlineAsmRegClass::zmm_reg) => "v",
742            X86(X86InlineAsmRegClass::kreg) => "^Yk",
743            X86(
744                X86InlineAsmRegClass::x87_reg
745                | X86InlineAsmRegClass::mmx_reg
746                | X86InlineAsmRegClass::kreg0
747                | X86InlineAsmRegClass::tmm_reg,
748            ) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
749            Xtensa(XtensaInlineAsmRegClass::freg) => "f",
750            Xtensa(XtensaInlineAsmRegClass::reg) => "r",
751            Xtensa(XtensaInlineAsmRegClass::sreg | XtensaInlineAsmRegClass::breg) => {
752                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
753            }
754            Wasm(WasmInlineAsmRegClass::local) => "r",
755            Bpf(BpfInlineAsmRegClass::reg) => "r",
756            Bpf(BpfInlineAsmRegClass::wreg) => "w",
757            Avr(AvrInlineAsmRegClass::reg) => "r",
758            Avr(AvrInlineAsmRegClass::reg_upper) => "d",
759            Avr(AvrInlineAsmRegClass::reg_pair) => "r",
760            Avr(AvrInlineAsmRegClass::reg_iw) => "w",
761            Avr(AvrInlineAsmRegClass::reg_ptr) => "e",
762            S390x(S390xInlineAsmRegClass::reg) => "r",
763            S390x(S390xInlineAsmRegClass::reg_addr) => "a",
764            S390x(S390xInlineAsmRegClass::freg) => "f",
765            S390x(S390xInlineAsmRegClass::vreg) => "v",
766            S390x(S390xInlineAsmRegClass::areg) => {
767                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
768            }
769            Sparc(SparcInlineAsmRegClass::reg) => "r",
770            Sparc(SparcInlineAsmRegClass::yreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
771            Msp430(Msp430InlineAsmRegClass::reg) => "r",
772            M68k(M68kInlineAsmRegClass::reg) => "r",
773            M68k(M68kInlineAsmRegClass::reg_addr) => "a",
774            M68k(M68kInlineAsmRegClass::reg_data) => "d",
775            CSKY(CSKYInlineAsmRegClass::reg) => "r",
776            CSKY(CSKYInlineAsmRegClass::freg) => "f",
777            SpirV(SpirVInlineAsmRegClass::reg) => ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM backend does not support SPIR-V"))bug!("LLVM backend does not support SPIR-V"),
778            Err => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
779        }
780        .to_string(),
781    }
782}
783
784/// Converts a modifier into LLVM's equivalent modifier.
785fn modifier_to_llvm(
786    arch: InlineAsmArch,
787    reg: InlineAsmRegClass,
788    modifier: Option<char>,
789) -> Option<char> {
790    use InlineAsmRegClass::*;
791    // The modifiers can be retrieved from
792    // https://llvm.org/docs/LangRef.html#asm-template-argument-modifiers
793    match reg {
794        AArch64(AArch64InlineAsmRegClass::reg) => modifier,
795        AArch64(AArch64InlineAsmRegClass::vreg) | AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
796            if modifier == Some('v') {
797                None
798            } else {
799                modifier
800            }
801        }
802        AArch64(AArch64InlineAsmRegClass::preg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
803        Arm(ArmInlineAsmRegClass::reg) => None,
804        Arm(ArmInlineAsmRegClass::sreg) | Arm(ArmInlineAsmRegClass::sreg_low16) => None,
805        Arm(ArmInlineAsmRegClass::dreg)
806        | Arm(ArmInlineAsmRegClass::dreg_low16)
807        | Arm(ArmInlineAsmRegClass::dreg_low8) => Some('P'),
808        Arm(ArmInlineAsmRegClass::qreg)
809        | Arm(ArmInlineAsmRegClass::qreg_low8)
810        | Arm(ArmInlineAsmRegClass::qreg_low4) => {
811            if modifier.is_none() {
812                Some('q')
813            } else {
814                modifier
815            }
816        }
817        Amdgpu(_) => None,
818        Hexagon(_) => None,
819        LoongArch(LoongArchInlineAsmRegClass::reg) => None,
820        LoongArch(LoongArchInlineAsmRegClass::freg) => modifier,
821        LoongArch(LoongArchInlineAsmRegClass::vreg) => {
822            if modifier.is_none() {
823                Some('w')
824            } else {
825                modifier
826            }
827        }
828        LoongArch(LoongArchInlineAsmRegClass::xreg) => {
829            if modifier.is_none() {
830                Some('u')
831            } else {
832                modifier
833            }
834        }
835        Mips(_) => None,
836        Nvptx(_) => None,
837        PowerPC(PowerPCInlineAsmRegClass::vsreg) => {
838            // The documentation for the 'x' modifier is missing for llvm, and the gcc
839            // documentation is simply "use this for any vsx argument". It is needed
840            // to ensure the correct vsx register number is used.
841            if modifier.is_none() { Some('x') } else { modifier }
842        }
843        PowerPC(_) => None,
844        RiscV(RiscVInlineAsmRegClass::reg) | RiscV(RiscVInlineAsmRegClass::freg) => None,
845        RiscV(RiscVInlineAsmRegClass::vreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
846        X86(X86InlineAsmRegClass::reg) | X86(X86InlineAsmRegClass::reg_abcd) => match modifier {
847            None if arch == InlineAsmArch::X86_64 => Some('q'),
848            None => Some('k'),
849            Some('l') => Some('b'),
850            Some('h') => Some('h'),
851            Some('x') => Some('w'),
852            Some('e') => Some('k'),
853            Some('r') => Some('q'),
854            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
855        },
856        X86(X86InlineAsmRegClass::reg_byte) => None,
857        X86(reg @ X86InlineAsmRegClass::xmm_reg)
858        | X86(reg @ X86InlineAsmRegClass::ymm_reg)
859        | X86(reg @ X86InlineAsmRegClass::zmm_reg) => match (reg, modifier) {
860            (X86InlineAsmRegClass::xmm_reg, None) => Some('x'),
861            (X86InlineAsmRegClass::ymm_reg, None) => Some('t'),
862            (X86InlineAsmRegClass::zmm_reg, None) => Some('g'),
863            (_, Some('x')) => Some('x'),
864            (_, Some('y')) => Some('t'),
865            (_, Some('z')) => Some('g'),
866            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
867        },
868        X86(X86InlineAsmRegClass::kreg) => None,
869        X86(
870            X86InlineAsmRegClass::x87_reg
871            | X86InlineAsmRegClass::mmx_reg
872            | X86InlineAsmRegClass::kreg0
873            | X86InlineAsmRegClass::tmm_reg,
874        ) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
875        Xtensa(_) => None,
876        Wasm(WasmInlineAsmRegClass::local) => None,
877        Bpf(_) => None,
878        Avr(AvrInlineAsmRegClass::reg_pair)
879        | Avr(AvrInlineAsmRegClass::reg_iw)
880        | Avr(AvrInlineAsmRegClass::reg_ptr) => match modifier {
881            Some('h') => Some('B'),
882            Some('l') => Some('A'),
883            _ => None,
884        },
885        Avr(_) => None,
886        S390x(_) => None,
887        Sparc(_) => None,
888        Msp430(_) => None,
889        SpirV(SpirVInlineAsmRegClass::reg) => ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM backend does not support SPIR-V"))bug!("LLVM backend does not support SPIR-V"),
890        M68k(_) => None,
891        CSKY(_) => None,
892        Err => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
893    }
894}
895
896/// Type to use for outputs that are discarded. It doesn't really matter what
897/// the type is, as long as it is valid for the constraint code.
898fn dummy_output_type<'ll>(cx: &CodegenCx<'ll, '_>, reg: InlineAsmRegClass) -> &'ll Type {
899    use InlineAsmRegClass::*;
900    match reg {
901        AArch64(AArch64InlineAsmRegClass::reg) => cx.type_i32(),
902        AArch64(AArch64InlineAsmRegClass::vreg) | AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
903            cx.type_vector(cx.type_i64(), 2)
904        }
905        AArch64(AArch64InlineAsmRegClass::preg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
906        Arm(ArmInlineAsmRegClass::reg) => cx.type_i32(),
907        Arm(ArmInlineAsmRegClass::sreg) | Arm(ArmInlineAsmRegClass::sreg_low16) => cx.type_f32(),
908        Arm(ArmInlineAsmRegClass::dreg)
909        | Arm(ArmInlineAsmRegClass::dreg_low16)
910        | Arm(ArmInlineAsmRegClass::dreg_low8) => cx.type_f64(),
911        Arm(ArmInlineAsmRegClass::qreg)
912        | Arm(ArmInlineAsmRegClass::qreg_low8)
913        | Arm(ArmInlineAsmRegClass::qreg_low4) => cx.type_vector(cx.type_i64(), 2),
914        Amdgpu(_) => cx.type_i32(),
915        Hexagon(HexagonInlineAsmRegClass::reg) => cx.type_i32(),
916        Hexagon(HexagonInlineAsmRegClass::reg_pair) => cx.type_i64(),
917        Hexagon(HexagonInlineAsmRegClass::preg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
918        Hexagon(HexagonInlineAsmRegClass::vreg) => {
919            // HVX vector register size depends on the HVX mode.
920            // LLVM's "v" constraint requires the exact vector width.
921            if cx.tcx.sess.unstable_target_features.contains(&sym::hvx_length128b) {
922                cx.type_vector(cx.type_i32(), 32) // 1024-bit for 128B mode
923            } else {
924                cx.type_vector(cx.type_i32(), 16) // 512-bit for 64B mode
925            }
926        }
927        Hexagon(HexagonInlineAsmRegClass::vreg_pair) => {
928            if cx.tcx.sess.unstable_target_features.contains(&sym::hvx_length128b) {
929                cx.type_vector(cx.type_i32(), 64) // 2048-bit for 128B mode
930            } else {
931                cx.type_vector(cx.type_i32(), 32) // 1024-bit for 64B mode
932            }
933        }
934        Hexagon(HexagonInlineAsmRegClass::qreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
935        LoongArch(LoongArchInlineAsmRegClass::reg) => cx.type_i32(),
936        LoongArch(LoongArchInlineAsmRegClass::freg) => cx.type_f32(),
937        LoongArch(LoongArchInlineAsmRegClass::vreg) => cx.type_vector(cx.type_i32(), 4),
938        LoongArch(LoongArchInlineAsmRegClass::xreg) => cx.type_vector(cx.type_i32(), 8),
939        Mips(MipsInlineAsmRegClass::reg) => cx.type_i32(),
940        Mips(MipsInlineAsmRegClass::freg) => cx.type_f32(),
941        Nvptx(NvptxInlineAsmRegClass::reg16) => cx.type_i16(),
942        Nvptx(NvptxInlineAsmRegClass::reg32) => cx.type_i32(),
943        Nvptx(NvptxInlineAsmRegClass::reg64) => cx.type_i64(),
944        PowerPC(PowerPCInlineAsmRegClass::reg) => cx.type_i32(),
945        PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => cx.type_i32(),
946        PowerPC(PowerPCInlineAsmRegClass::freg) => cx.type_f64(),
947        PowerPC(PowerPCInlineAsmRegClass::vreg) => cx.type_vector(cx.type_i32(), 4),
948        PowerPC(PowerPCInlineAsmRegClass::vsreg) => cx.type_vector(cx.type_i32(), 4),
949        PowerPC(
950            PowerPCInlineAsmRegClass::cr
951            | PowerPCInlineAsmRegClass::ctr
952            | PowerPCInlineAsmRegClass::lr
953            | PowerPCInlineAsmRegClass::xer
954            | PowerPCInlineAsmRegClass::spe_acc,
955        ) => {
956            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
957        }
958        RiscV(RiscVInlineAsmRegClass::reg) => cx.type_i32(),
959        RiscV(RiscVInlineAsmRegClass::freg) => cx.type_f32(),
960        RiscV(RiscVInlineAsmRegClass::vreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
961        X86(X86InlineAsmRegClass::reg) | X86(X86InlineAsmRegClass::reg_abcd) => cx.type_i32(),
962        X86(X86InlineAsmRegClass::reg_byte) => cx.type_i8(),
963        X86(X86InlineAsmRegClass::xmm_reg)
964        | X86(X86InlineAsmRegClass::ymm_reg)
965        | X86(X86InlineAsmRegClass::zmm_reg) => cx.type_f32(),
966        X86(X86InlineAsmRegClass::kreg) => cx.type_i16(),
967        X86(
968            X86InlineAsmRegClass::x87_reg
969            | X86InlineAsmRegClass::mmx_reg
970            | X86InlineAsmRegClass::kreg0
971            | X86InlineAsmRegClass::tmm_reg,
972        ) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
973        Xtensa(XtensaInlineAsmRegClass::reg) => cx.type_i32(),
974        Xtensa(XtensaInlineAsmRegClass::freg) => cx.type_f32(),
975        Xtensa(XtensaInlineAsmRegClass::sreg | XtensaInlineAsmRegClass::breg) => {
976            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
977        }
978        Wasm(WasmInlineAsmRegClass::local) => cx.type_i32(),
979        Bpf(BpfInlineAsmRegClass::reg) => cx.type_i64(),
980        Bpf(BpfInlineAsmRegClass::wreg) => cx.type_i32(),
981        Avr(AvrInlineAsmRegClass::reg) => cx.type_i8(),
982        Avr(AvrInlineAsmRegClass::reg_upper) => cx.type_i8(),
983        Avr(AvrInlineAsmRegClass::reg_pair) => cx.type_i16(),
984        Avr(AvrInlineAsmRegClass::reg_iw) => cx.type_i16(),
985        Avr(AvrInlineAsmRegClass::reg_ptr) => cx.type_i16(),
986        S390x(S390xInlineAsmRegClass::reg | S390xInlineAsmRegClass::reg_addr) => cx.type_i32(),
987        S390x(S390xInlineAsmRegClass::freg) => cx.type_f64(),
988        S390x(S390xInlineAsmRegClass::vreg) => cx.type_vector(cx.type_i64(), 2),
989        S390x(S390xInlineAsmRegClass::areg) => {
990            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
991        }
992        Sparc(SparcInlineAsmRegClass::reg) => cx.type_i32(),
993        Sparc(SparcInlineAsmRegClass::yreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
994        Msp430(Msp430InlineAsmRegClass::reg) => cx.type_i16(),
995        M68k(M68kInlineAsmRegClass::reg) => cx.type_i32(),
996        M68k(M68kInlineAsmRegClass::reg_addr) => cx.type_i32(),
997        M68k(M68kInlineAsmRegClass::reg_data) => cx.type_i32(),
998        CSKY(CSKYInlineAsmRegClass::reg) => cx.type_i32(),
999        CSKY(CSKYInlineAsmRegClass::freg) => cx.type_f32(),
1000        SpirV(SpirVInlineAsmRegClass::reg) => ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM backend does not support SPIR-V"))bug!("LLVM backend does not support SPIR-V"),
1001        Err => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1002    }
1003}
1004
1005/// Helper function to get the LLVM type for a Scalar. Pointers are returned as
1006/// the equivalent integer type.
1007fn llvm_asm_scalar_type<'ll>(cx: &CodegenCx<'ll, '_>, scalar: Scalar) -> &'ll Type {
1008    let dl = &cx.tcx.data_layout;
1009    match scalar.primitive() {
1010        Primitive::Int(Integer::I8, _) => cx.type_i8(),
1011        Primitive::Int(Integer::I16, _) => cx.type_i16(),
1012        Primitive::Int(Integer::I32, _) => cx.type_i32(),
1013        Primitive::Int(Integer::I64, _) => cx.type_i64(),
1014        Primitive::Float(Float::F16) => cx.type_f16(),
1015        Primitive::Float(Float::F32) => cx.type_f32(),
1016        Primitive::Float(Float::F64) => cx.type_f64(),
1017        Primitive::Float(Float::F128) => cx.type_f128(),
1018        // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
1019        Primitive::Pointer(_) => cx.type_from_integer(dl.ptr_sized_integer()),
1020        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1021    }
1022}
1023
1024fn any_target_feature_enabled(
1025    cx: &CodegenCx<'_, '_>,
1026    instance: Instance<'_>,
1027    features: &[Symbol],
1028) -> bool {
1029    let enabled = cx.tcx.asm_target_features(instance.def_id());
1030    features.iter().any(|feat| enabled.contains(feat))
1031}
1032
1033/// Fix up an input value to work around LLVM bugs.
1034fn llvm_fixup_input<'ll, 'tcx>(
1035    bx: &mut Builder<'_, 'll, 'tcx>,
1036    mut value: &'ll Value,
1037    reg: InlineAsmRegClass,
1038    layout: &TyAndLayout<'tcx>,
1039    instance: Instance<'_>,
1040) -> &'ll Value {
1041    use InlineAsmRegClass::*;
1042    let dl = &bx.tcx.data_layout;
1043    match (reg, layout.backend_repr) {
1044        (AArch64(AArch64InlineAsmRegClass::vreg), BackendRepr::Scalar(s)) => {
1045            if let Primitive::Int(Integer::I8, _) = s.primitive() {
1046                let vec_ty = bx.cx.type_vector(bx.cx.type_i8(), 8);
1047                bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
1048            } else {
1049                value
1050            }
1051        }
1052        (AArch64(AArch64InlineAsmRegClass::vreg_low16), BackendRepr::Scalar(s))
1053            if s.primitive() != Primitive::Float(Float::F128) =>
1054        {
1055            let elem_ty = llvm_asm_scalar_type(bx.cx, s);
1056            let count = 16 / layout.size.bytes();
1057            let vec_ty = bx.cx.type_vector(elem_ty, count);
1058            // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
1059            if let Primitive::Pointer(_) = s.primitive() {
1060                let t = bx.type_from_integer(dl.ptr_sized_integer());
1061                value = bx.ptrtoint(value, t);
1062            }
1063            bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
1064        }
1065        (
1066            AArch64(AArch64InlineAsmRegClass::vreg_low16),
1067            BackendRepr::SimdVector { element, count },
1068        ) if layout.size.bytes() == 8 => {
1069            let elem_ty = llvm_asm_scalar_type(bx.cx, element);
1070            let vec_ty = bx.cx.type_vector(elem_ty, count);
1071            let indices: Vec<_> = (0..count * 2).map(|x| bx.const_i32(x as i32)).collect();
1072            bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
1073        }
1074        (X86(X86InlineAsmRegClass::reg_abcd), BackendRepr::Scalar(s))
1075            if s.primitive() == Primitive::Float(Float::F64) =>
1076        {
1077            bx.bitcast(value, bx.cx.type_i64())
1078        }
1079        (
1080            X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
1081            BackendRepr::SimdVector { .. },
1082        ) if layout.size.bytes() == 64 => bx.bitcast(value, bx.cx.type_vector(bx.cx.type_f64(), 8)),
1083        (
1084            X86(
1085                X86InlineAsmRegClass::xmm_reg
1086                | X86InlineAsmRegClass::ymm_reg
1087                | X86InlineAsmRegClass::zmm_reg,
1088            ),
1089            BackendRepr::Scalar(s),
1090        ) if bx.sess().asm_arch == Some(InlineAsmArch::X86)
1091            && s.primitive() == Primitive::Float(Float::F128) =>
1092        {
1093            bx.bitcast(value, bx.type_vector(bx.type_i32(), 4))
1094        }
1095        (
1096            X86(
1097                X86InlineAsmRegClass::xmm_reg
1098                | X86InlineAsmRegClass::ymm_reg
1099                | X86InlineAsmRegClass::zmm_reg,
1100            ),
1101            BackendRepr::Scalar(s),
1102        ) if s.primitive() == Primitive::Float(Float::F16) => {
1103            let value = bx.insert_element(
1104                bx.const_undef(bx.type_vector(bx.type_f16(), 8)),
1105                value,
1106                bx.const_usize(0),
1107            );
1108            bx.bitcast(value, bx.type_vector(bx.type_i16(), 8))
1109        }
1110        (
1111            X86(
1112                X86InlineAsmRegClass::xmm_reg
1113                | X86InlineAsmRegClass::ymm_reg
1114                | X86InlineAsmRegClass::zmm_reg,
1115            ),
1116            BackendRepr::SimdVector { element, count: count @ (8 | 16) },
1117        ) if element.primitive() == Primitive::Float(Float::F16) => {
1118            bx.bitcast(value, bx.type_vector(bx.type_i16(), count))
1119        }
1120        (
1121            Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
1122            BackendRepr::Scalar(s),
1123        ) => {
1124            if let Primitive::Int(Integer::I32, _) = s.primitive() {
1125                bx.bitcast(value, bx.cx.type_f32())
1126            } else {
1127                value
1128            }
1129        }
1130        (
1131            Arm(
1132                ArmInlineAsmRegClass::dreg
1133                | ArmInlineAsmRegClass::dreg_low8
1134                | ArmInlineAsmRegClass::dreg_low16,
1135            ),
1136            BackendRepr::Scalar(s),
1137        ) => {
1138            if let Primitive::Int(Integer::I64, _) = s.primitive() {
1139                bx.bitcast(value, bx.cx.type_f64())
1140            } else {
1141                value
1142            }
1143        }
1144        (
1145            Arm(
1146                ArmInlineAsmRegClass::dreg
1147                | ArmInlineAsmRegClass::dreg_low8
1148                | ArmInlineAsmRegClass::dreg_low16
1149                | ArmInlineAsmRegClass::qreg
1150                | ArmInlineAsmRegClass::qreg_low4
1151                | ArmInlineAsmRegClass::qreg_low8,
1152            ),
1153            BackendRepr::SimdVector { element, count: count @ (4 | 8) },
1154        ) if element.primitive() == Primitive::Float(Float::F16) => {
1155            bx.bitcast(value, bx.type_vector(bx.type_i16(), count))
1156        }
1157        (LoongArch(LoongArchInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1158            if s.primitive() == Primitive::Float(Float::F16) =>
1159        {
1160            // Smaller floats are always "NaN-boxed" inside larger floats on LoongArch.
1161            let value = bx.bitcast(value, bx.type_i16());
1162            let value = bx.zext(value, bx.type_i32());
1163            let value = bx.or(value, bx.const_u32(0xFFFF_0000));
1164            bx.bitcast(value, bx.type_f32())
1165        }
1166        (Mips(MipsInlineAsmRegClass::reg), BackendRepr::Scalar(s)) => {
1167            match s.primitive() {
1168                // MIPS only supports register-length arithmetics.
1169                Primitive::Int(Integer::I8 | Integer::I16, _) => bx.zext(value, bx.cx.type_i32()),
1170                Primitive::Float(Float::F32) => bx.bitcast(value, bx.cx.type_i32()),
1171                Primitive::Float(Float::F64) => bx.bitcast(value, bx.cx.type_i64()),
1172                _ => value,
1173            }
1174        }
1175        (RiscV(RiscVInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1176            if s.primitive() == Primitive::Float(Float::F16)
1177                && !any_target_feature_enabled(bx, instance, &[sym::zfhmin, sym::zfh]) =>
1178        {
1179            // Smaller floats are always "NaN-boxed" inside larger floats on RISC-V.
1180            let value = bx.bitcast(value, bx.type_i16());
1181            let value = bx.zext(value, bx.type_i32());
1182            let value = bx.or(value, bx.const_u32(0xFFFF_0000));
1183            bx.bitcast(value, bx.type_f32())
1184        }
1185        (
1186            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1187            BackendRepr::Scalar(s),
1188        ) if s.primitive() == Primitive::Float(Float::F32) => {
1189            let value = bx.insert_element(
1190                bx.const_undef(bx.type_vector(bx.type_f32(), 4)),
1191                value,
1192                bx.const_usize(0),
1193            );
1194            bx.bitcast(value, bx.type_vector(bx.type_f32(), 4))
1195        }
1196        (
1197            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1198            BackendRepr::Scalar(s),
1199        ) if s.primitive() == Primitive::Float(Float::F64) => {
1200            let value = bx.insert_element(
1201                bx.const_undef(bx.type_vector(bx.type_f64(), 2)),
1202                value,
1203                bx.const_usize(0),
1204            );
1205            bx.bitcast(value, bx.type_vector(bx.type_f64(), 2))
1206        }
1207        _ => value,
1208    }
1209}
1210
1211/// Fix up an output value to work around LLVM bugs.
1212fn llvm_fixup_output<'ll, 'tcx>(
1213    bx: &mut Builder<'_, 'll, 'tcx>,
1214    mut value: &'ll Value,
1215    reg: InlineAsmRegClass,
1216    layout: &TyAndLayout<'tcx>,
1217    instance: Instance<'_>,
1218) -> &'ll Value {
1219    use InlineAsmRegClass::*;
1220    match (reg, layout.backend_repr) {
1221        (AArch64(AArch64InlineAsmRegClass::vreg), BackendRepr::Scalar(s)) => {
1222            if let Primitive::Int(Integer::I8, _) = s.primitive() {
1223                bx.extract_element(value, bx.const_i32(0))
1224            } else {
1225                value
1226            }
1227        }
1228        (AArch64(AArch64InlineAsmRegClass::vreg_low16), BackendRepr::Scalar(s))
1229            if s.primitive() != Primitive::Float(Float::F128) =>
1230        {
1231            value = bx.extract_element(value, bx.const_i32(0));
1232            if let Primitive::Pointer(_) = s.primitive() {
1233                value = bx.inttoptr(value, layout.llvm_type(bx.cx));
1234            }
1235            value
1236        }
1237        (
1238            AArch64(AArch64InlineAsmRegClass::vreg_low16),
1239            BackendRepr::SimdVector { element, count },
1240        ) if layout.size.bytes() == 8 => {
1241            let elem_ty = llvm_asm_scalar_type(bx.cx, element);
1242            let vec_ty = bx.cx.type_vector(elem_ty, count * 2);
1243            let indices: Vec<_> = (0..count).map(|x| bx.const_i32(x as i32)).collect();
1244            bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
1245        }
1246        (X86(X86InlineAsmRegClass::reg_abcd), BackendRepr::Scalar(s))
1247            if s.primitive() == Primitive::Float(Float::F64) =>
1248        {
1249            bx.bitcast(value, bx.cx.type_f64())
1250        }
1251        (
1252            X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
1253            BackendRepr::SimdVector { .. },
1254        ) if layout.size.bytes() == 64 => bx.bitcast(value, layout.llvm_type(bx.cx)),
1255        (
1256            X86(
1257                X86InlineAsmRegClass::xmm_reg
1258                | X86InlineAsmRegClass::ymm_reg
1259                | X86InlineAsmRegClass::zmm_reg,
1260            ),
1261            BackendRepr::Scalar(s),
1262        ) if bx.sess().asm_arch == Some(InlineAsmArch::X86)
1263            && s.primitive() == Primitive::Float(Float::F128) =>
1264        {
1265            bx.bitcast(value, bx.type_f128())
1266        }
1267        (
1268            X86(
1269                X86InlineAsmRegClass::xmm_reg
1270                | X86InlineAsmRegClass::ymm_reg
1271                | X86InlineAsmRegClass::zmm_reg,
1272            ),
1273            BackendRepr::Scalar(s),
1274        ) if s.primitive() == Primitive::Float(Float::F16) => {
1275            let value = bx.bitcast(value, bx.type_vector(bx.type_f16(), 8));
1276            bx.extract_element(value, bx.const_usize(0))
1277        }
1278        (
1279            X86(
1280                X86InlineAsmRegClass::xmm_reg
1281                | X86InlineAsmRegClass::ymm_reg
1282                | X86InlineAsmRegClass::zmm_reg,
1283            ),
1284            BackendRepr::SimdVector { element, count: count @ (8 | 16) },
1285        ) if element.primitive() == Primitive::Float(Float::F16) => {
1286            bx.bitcast(value, bx.type_vector(bx.type_f16(), count))
1287        }
1288        (
1289            Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
1290            BackendRepr::Scalar(s),
1291        ) => {
1292            if let Primitive::Int(Integer::I32, _) = s.primitive() {
1293                bx.bitcast(value, bx.cx.type_i32())
1294            } else {
1295                value
1296            }
1297        }
1298        (
1299            Arm(
1300                ArmInlineAsmRegClass::dreg
1301                | ArmInlineAsmRegClass::dreg_low8
1302                | ArmInlineAsmRegClass::dreg_low16,
1303            ),
1304            BackendRepr::Scalar(s),
1305        ) => {
1306            if let Primitive::Int(Integer::I64, _) = s.primitive() {
1307                bx.bitcast(value, bx.cx.type_i64())
1308            } else {
1309                value
1310            }
1311        }
1312        (
1313            Arm(
1314                ArmInlineAsmRegClass::dreg
1315                | ArmInlineAsmRegClass::dreg_low8
1316                | ArmInlineAsmRegClass::dreg_low16
1317                | ArmInlineAsmRegClass::qreg
1318                | ArmInlineAsmRegClass::qreg_low4
1319                | ArmInlineAsmRegClass::qreg_low8,
1320            ),
1321            BackendRepr::SimdVector { element, count: count @ (4 | 8) },
1322        ) if element.primitive() == Primitive::Float(Float::F16) => {
1323            bx.bitcast(value, bx.type_vector(bx.type_f16(), count))
1324        }
1325        (LoongArch(LoongArchInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1326            if s.primitive() == Primitive::Float(Float::F16) =>
1327        {
1328            let value = bx.bitcast(value, bx.type_i32());
1329            let value = bx.trunc(value, bx.type_i16());
1330            bx.bitcast(value, bx.type_f16())
1331        }
1332        (Mips(MipsInlineAsmRegClass::reg), BackendRepr::Scalar(s)) => {
1333            match s.primitive() {
1334                // MIPS only supports register-length arithmetics.
1335                Primitive::Int(Integer::I8, _) => bx.trunc(value, bx.cx.type_i8()),
1336                Primitive::Int(Integer::I16, _) => bx.trunc(value, bx.cx.type_i16()),
1337                Primitive::Float(Float::F32) => bx.bitcast(value, bx.cx.type_f32()),
1338                Primitive::Float(Float::F64) => bx.bitcast(value, bx.cx.type_f64()),
1339                _ => value,
1340            }
1341        }
1342        (RiscV(RiscVInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1343            if s.primitive() == Primitive::Float(Float::F16)
1344                && !any_target_feature_enabled(bx, instance, &[sym::zfhmin, sym::zfh]) =>
1345        {
1346            let value = bx.bitcast(value, bx.type_i32());
1347            let value = bx.trunc(value, bx.type_i16());
1348            bx.bitcast(value, bx.type_f16())
1349        }
1350        (
1351            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1352            BackendRepr::Scalar(s),
1353        ) if s.primitive() == Primitive::Float(Float::F32) => {
1354            let value = bx.bitcast(value, bx.type_vector(bx.type_f32(), 4));
1355            bx.extract_element(value, bx.const_usize(0))
1356        }
1357        (
1358            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1359            BackendRepr::Scalar(s),
1360        ) if s.primitive() == Primitive::Float(Float::F64) => {
1361            let value = bx.bitcast(value, bx.type_vector(bx.type_f64(), 2));
1362            bx.extract_element(value, bx.const_usize(0))
1363        }
1364        _ => value,
1365    }
1366}
1367
1368/// Output type to use for llvm_fixup_output.
1369fn llvm_fixup_output_type<'ll, 'tcx>(
1370    cx: &CodegenCx<'ll, 'tcx>,
1371    reg: InlineAsmRegClass,
1372    layout: &TyAndLayout<'tcx>,
1373    instance: Instance<'_>,
1374) -> &'ll Type {
1375    use InlineAsmRegClass::*;
1376    match (reg, layout.backend_repr) {
1377        (AArch64(AArch64InlineAsmRegClass::vreg), BackendRepr::Scalar(s)) => {
1378            if let Primitive::Int(Integer::I8, _) = s.primitive() {
1379                cx.type_vector(cx.type_i8(), 8)
1380            } else {
1381                layout.llvm_type(cx)
1382            }
1383        }
1384        (AArch64(AArch64InlineAsmRegClass::vreg_low16), BackendRepr::Scalar(s))
1385            if s.primitive() != Primitive::Float(Float::F128) =>
1386        {
1387            let elem_ty = llvm_asm_scalar_type(cx, s);
1388            let count = 16 / layout.size.bytes();
1389            cx.type_vector(elem_ty, count)
1390        }
1391        (
1392            AArch64(AArch64InlineAsmRegClass::vreg_low16),
1393            BackendRepr::SimdVector { element, count },
1394        ) if layout.size.bytes() == 8 => {
1395            let elem_ty = llvm_asm_scalar_type(cx, element);
1396            cx.type_vector(elem_ty, count * 2)
1397        }
1398        (X86(X86InlineAsmRegClass::reg_abcd), BackendRepr::Scalar(s))
1399            if s.primitive() == Primitive::Float(Float::F64) =>
1400        {
1401            cx.type_i64()
1402        }
1403        (
1404            X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
1405            BackendRepr::SimdVector { .. },
1406        ) if layout.size.bytes() == 64 => cx.type_vector(cx.type_f64(), 8),
1407        (
1408            X86(
1409                X86InlineAsmRegClass::xmm_reg
1410                | X86InlineAsmRegClass::ymm_reg
1411                | X86InlineAsmRegClass::zmm_reg,
1412            ),
1413            BackendRepr::Scalar(s),
1414        ) if cx.sess().asm_arch == Some(InlineAsmArch::X86)
1415            && s.primitive() == Primitive::Float(Float::F128) =>
1416        {
1417            cx.type_vector(cx.type_i32(), 4)
1418        }
1419        (
1420            X86(
1421                X86InlineAsmRegClass::xmm_reg
1422                | X86InlineAsmRegClass::ymm_reg
1423                | X86InlineAsmRegClass::zmm_reg,
1424            ),
1425            BackendRepr::Scalar(s),
1426        ) if s.primitive() == Primitive::Float(Float::F16) => cx.type_vector(cx.type_i16(), 8),
1427        (
1428            X86(
1429                X86InlineAsmRegClass::xmm_reg
1430                | X86InlineAsmRegClass::ymm_reg
1431                | X86InlineAsmRegClass::zmm_reg,
1432            ),
1433            BackendRepr::SimdVector { element, count: count @ (8 | 16) },
1434        ) if element.primitive() == Primitive::Float(Float::F16) => {
1435            cx.type_vector(cx.type_i16(), count)
1436        }
1437        (
1438            Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
1439            BackendRepr::Scalar(s),
1440        ) => {
1441            if let Primitive::Int(Integer::I32, _) = s.primitive() {
1442                cx.type_f32()
1443            } else {
1444                layout.llvm_type(cx)
1445            }
1446        }
1447        (
1448            Arm(
1449                ArmInlineAsmRegClass::dreg
1450                | ArmInlineAsmRegClass::dreg_low8
1451                | ArmInlineAsmRegClass::dreg_low16,
1452            ),
1453            BackendRepr::Scalar(s),
1454        ) => {
1455            if let Primitive::Int(Integer::I64, _) = s.primitive() {
1456                cx.type_f64()
1457            } else {
1458                layout.llvm_type(cx)
1459            }
1460        }
1461        (
1462            Arm(
1463                ArmInlineAsmRegClass::dreg
1464                | ArmInlineAsmRegClass::dreg_low8
1465                | ArmInlineAsmRegClass::dreg_low16
1466                | ArmInlineAsmRegClass::qreg
1467                | ArmInlineAsmRegClass::qreg_low4
1468                | ArmInlineAsmRegClass::qreg_low8,
1469            ),
1470            BackendRepr::SimdVector { element, count: count @ (4 | 8) },
1471        ) if element.primitive() == Primitive::Float(Float::F16) => {
1472            cx.type_vector(cx.type_i16(), count)
1473        }
1474        (LoongArch(LoongArchInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1475            if s.primitive() == Primitive::Float(Float::F16) =>
1476        {
1477            cx.type_f32()
1478        }
1479        (Mips(MipsInlineAsmRegClass::reg), BackendRepr::Scalar(s)) => {
1480            match s.primitive() {
1481                // MIPS only supports register-length arithmetics.
1482                Primitive::Int(Integer::I8 | Integer::I16, _) => cx.type_i32(),
1483                Primitive::Float(Float::F32) => cx.type_i32(),
1484                Primitive::Float(Float::F64) => cx.type_i64(),
1485                _ => layout.llvm_type(cx),
1486            }
1487        }
1488        (RiscV(RiscVInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1489            if s.primitive() == Primitive::Float(Float::F16)
1490                && !any_target_feature_enabled(cx, instance, &[sym::zfhmin, sym::zfh]) =>
1491        {
1492            cx.type_f32()
1493        }
1494        (
1495            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1496            BackendRepr::Scalar(s),
1497        ) if s.primitive() == Primitive::Float(Float::F32) => cx.type_vector(cx.type_f32(), 4),
1498        (
1499            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1500            BackendRepr::Scalar(s),
1501        ) if s.primitive() == Primitive::Float(Float::F64) => cx.type_vector(cx.type_f64(), 2),
1502        _ => layout.llvm_type(cx),
1503    }
1504}