Skip to main content

rustc_codegen_llvm/
asm.rs

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