Skip to main content

rustc_codegen_llvm/
asm.rs

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