]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/asm.rs
Rollup merge of #92942 - Xaeroxe:raw_arg, r=dtolnay
[rust.git] / compiler / rustc_codegen_llvm / src / asm.rs
1 use crate::attributes;
2 use crate::builder::Builder;
3 use crate::common::Funclet;
4 use crate::context::CodegenCx;
5 use crate::llvm;
6 use crate::llvm_util;
7 use crate::type_::Type;
8 use crate::type_of::LayoutLlvmExt;
9 use crate::value::Value;
10
11 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
12 use rustc_codegen_ssa::mir::operand::OperandValue;
13 use rustc_codegen_ssa::traits::*;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_middle::ty::layout::TyAndLayout;
16 use rustc_middle::{bug, span_bug, ty::Instance};
17 use rustc_span::{Pos, Span};
18 use rustc_target::abi::*;
19 use rustc_target::asm::*;
20
21 use libc::{c_char, c_uint};
22 use smallvec::SmallVec;
23 use tracing::debug;
24
25 impl<'ll, 'tcx> AsmBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
26     fn codegen_inline_asm(
27         &mut self,
28         template: &[InlineAsmTemplatePiece],
29         operands: &[InlineAsmOperandRef<'tcx, Self>],
30         options: InlineAsmOptions,
31         line_spans: &[Span],
32         instance: Instance<'_>,
33         dest_catch_funclet: Option<(Self::BasicBlock, Self::BasicBlock, Option<&Self::Funclet>)>,
34     ) {
35         let asm_arch = self.tcx.sess.asm_arch.unwrap();
36
37         // Collect the types of output operands
38         let mut constraints = vec![];
39         let mut clobbers = vec![];
40         let mut output_types = vec![];
41         let mut op_idx = FxHashMap::default();
42         let mut clobbered_x87 = false;
43         for (idx, op) in operands.iter().enumerate() {
44             match *op {
45                 InlineAsmOperandRef::Out { reg, late, place } => {
46                     let is_target_supported = |reg_class: InlineAsmRegClass| {
47                         for &(_, feature) in reg_class.supported_types(asm_arch) {
48                             if let Some(feature) = feature {
49                                 let codegen_fn_attrs = self.tcx.codegen_fn_attrs(instance.def_id());
50                                 if self.tcx.sess.target_features.contains(&feature)
51                                     || codegen_fn_attrs.target_features.contains(&feature)
52                                 {
53                                     return true;
54                                 }
55                             } else {
56                                 // Register class is unconditionally supported
57                                 return true;
58                             }
59                         }
60                         false
61                     };
62
63                     let mut layout = None;
64                     let ty = if let Some(ref place) = place {
65                         layout = Some(&place.layout);
66                         llvm_fixup_output_type(self.cx, reg.reg_class(), &place.layout)
67                     } else if matches!(
68                         reg.reg_class(),
69                         InlineAsmRegClass::X86(
70                             X86InlineAsmRegClass::mmx_reg | X86InlineAsmRegClass::x87_reg
71                         )
72                     ) {
73                         // Special handling for x87/mmx registers: we always
74                         // clobber the whole set if one register is marked as
75                         // clobbered. This is due to the way LLVM handles the
76                         // FP stack in inline assembly.
77                         if !clobbered_x87 {
78                             clobbered_x87 = true;
79                             clobbers.push("~{st}".to_string());
80                             for i in 1..=7 {
81                                 clobbers.push(format!("~{{st({})}}", i));
82                             }
83                         }
84                         continue;
85                     } else if !is_target_supported(reg.reg_class())
86                         || reg.reg_class().is_clobber_only(asm_arch)
87                     {
88                         // We turn discarded outputs into clobber constraints
89                         // if the target feature needed by the register class is
90                         // disabled. This is necessary otherwise LLVM will try
91                         // to actually allocate a register for the dummy output.
92                         assert!(matches!(reg, InlineAsmRegOrRegClass::Reg(_)));
93                         clobbers.push(format!("~{}", reg_to_llvm(reg, None)));
94                         continue;
95                     } else {
96                         // If the output is discarded, we don't really care what
97                         // type is used. We're just using this to tell LLVM to
98                         // reserve the register.
99                         dummy_output_type(self.cx, reg.reg_class())
100                     };
101                     output_types.push(ty);
102                     op_idx.insert(idx, constraints.len());
103                     let prefix = if late { "=" } else { "=&" };
104                     constraints.push(format!("{}{}", prefix, reg_to_llvm(reg, layout)));
105                 }
106                 InlineAsmOperandRef::InOut { reg, late, in_value, out_place } => {
107                     let layout = if let Some(ref out_place) = out_place {
108                         &out_place.layout
109                     } else {
110                         // LLVM required tied operands to have the same type,
111                         // so we just use the type of the input.
112                         &in_value.layout
113                     };
114                     let ty = llvm_fixup_output_type(self.cx, reg.reg_class(), layout);
115                     output_types.push(ty);
116                     op_idx.insert(idx, constraints.len());
117                     let prefix = if late { "=" } else { "=&" };
118                     constraints.push(format!("{}{}", prefix, reg_to_llvm(reg, Some(layout))));
119                 }
120                 _ => {}
121             }
122         }
123
124         // Collect input operands
125         let mut inputs = vec![];
126         for (idx, op) in operands.iter().enumerate() {
127             match *op {
128                 InlineAsmOperandRef::In { reg, value } => {
129                     let llval =
130                         llvm_fixup_input(self, value.immediate(), reg.reg_class(), &value.layout);
131                     inputs.push(llval);
132                     op_idx.insert(idx, constraints.len());
133                     constraints.push(reg_to_llvm(reg, Some(&value.layout)));
134                 }
135                 InlineAsmOperandRef::InOut { reg, late: _, in_value, out_place: _ } => {
136                     let value = llvm_fixup_input(
137                         self,
138                         in_value.immediate(),
139                         reg.reg_class(),
140                         &in_value.layout,
141                     );
142                     inputs.push(value);
143                     constraints.push(format!("{}", op_idx[&idx]));
144                 }
145                 InlineAsmOperandRef::SymFn { instance } => {
146                     inputs.push(self.cx.get_fn(instance));
147                     op_idx.insert(idx, constraints.len());
148                     constraints.push("s".to_string());
149                 }
150                 InlineAsmOperandRef::SymStatic { def_id } => {
151                     inputs.push(self.cx.get_static(def_id));
152                     op_idx.insert(idx, constraints.len());
153                     constraints.push("s".to_string());
154                 }
155                 _ => {}
156             }
157         }
158
159         // Build the template string
160         let mut template_str = String::new();
161         for piece in template {
162             match *piece {
163                 InlineAsmTemplatePiece::String(ref s) => {
164                     if s.contains('$') {
165                         for c in s.chars() {
166                             if c == '$' {
167                                 template_str.push_str("$$");
168                             } else {
169                                 template_str.push(c);
170                             }
171                         }
172                     } else {
173                         template_str.push_str(s)
174                     }
175                 }
176                 InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => {
177                     match operands[operand_idx] {
178                         InlineAsmOperandRef::In { reg, .. }
179                         | InlineAsmOperandRef::Out { reg, .. }
180                         | InlineAsmOperandRef::InOut { reg, .. } => {
181                             let modifier = modifier_to_llvm(asm_arch, reg.reg_class(), modifier);
182                             if let Some(modifier) = modifier {
183                                 template_str.push_str(&format!(
184                                     "${{{}:{}}}",
185                                     op_idx[&operand_idx], modifier
186                                 ));
187                             } else {
188                                 template_str.push_str(&format!("${{{}}}", op_idx[&operand_idx]));
189                             }
190                         }
191                         InlineAsmOperandRef::Const { ref string } => {
192                             // Const operands get injected directly into the template
193                             template_str.push_str(string);
194                         }
195                         InlineAsmOperandRef::SymFn { .. }
196                         | InlineAsmOperandRef::SymStatic { .. } => {
197                             // Only emit the raw symbol name
198                             template_str.push_str(&format!("${{{}:c}}", op_idx[&operand_idx]));
199                         }
200                     }
201                 }
202             }
203         }
204
205         constraints.append(&mut clobbers);
206         if !options.contains(InlineAsmOptions::PRESERVES_FLAGS) {
207             match asm_arch {
208                 InlineAsmArch::AArch64 | InlineAsmArch::Arm => {
209                     constraints.push("~{cc}".to_string());
210                 }
211                 InlineAsmArch::X86 | InlineAsmArch::X86_64 => {
212                     constraints.extend_from_slice(&[
213                         "~{dirflag}".to_string(),
214                         "~{fpsr}".to_string(),
215                         "~{flags}".to_string(),
216                     ]);
217                 }
218                 InlineAsmArch::RiscV32 | InlineAsmArch::RiscV64 => {
219                     constraints.extend_from_slice(&[
220                         "~{vtype}".to_string(),
221                         "~{vl}".to_string(),
222                         "~{vxsat}".to_string(),
223                         "~{vxrm}".to_string(),
224                     ]);
225                 }
226                 InlineAsmArch::Avr => {
227                     constraints.push("~{sreg}".to_string());
228                 }
229                 InlineAsmArch::Nvptx64 => {}
230                 InlineAsmArch::PowerPC | InlineAsmArch::PowerPC64 => {}
231                 InlineAsmArch::Hexagon => {}
232                 InlineAsmArch::Mips | InlineAsmArch::Mips64 => {}
233                 InlineAsmArch::S390x => {}
234                 InlineAsmArch::SpirV => {}
235                 InlineAsmArch::Wasm32 | InlineAsmArch::Wasm64 => {}
236                 InlineAsmArch::Bpf => {}
237                 InlineAsmArch::Msp430 => {
238                     constraints.push("~{sr}".to_string());
239                 }
240             }
241         }
242         if !options.contains(InlineAsmOptions::NOMEM) {
243             // This is actually ignored by LLVM, but it's probably best to keep
244             // it just in case. LLVM instead uses the ReadOnly/ReadNone
245             // attributes on the call instruction to optimize.
246             constraints.push("~{memory}".to_string());
247         }
248         let volatile = !options.contains(InlineAsmOptions::PURE);
249         let alignstack = !options.contains(InlineAsmOptions::NOSTACK);
250         let output_type = match &output_types[..] {
251             [] => self.type_void(),
252             [ty] => ty,
253             tys => self.type_struct(tys, false),
254         };
255         let dialect = match asm_arch {
256             InlineAsmArch::X86 | InlineAsmArch::X86_64
257                 if !options.contains(InlineAsmOptions::ATT_SYNTAX) =>
258             {
259                 llvm::AsmDialect::Intel
260             }
261             _ => llvm::AsmDialect::Att,
262         };
263         let result = inline_asm_call(
264             self,
265             &template_str,
266             &constraints.join(","),
267             &inputs,
268             output_type,
269             volatile,
270             alignstack,
271             dialect,
272             line_spans,
273             options.contains(InlineAsmOptions::MAY_UNWIND),
274             dest_catch_funclet,
275         )
276         .unwrap_or_else(|| span_bug!(line_spans[0], "LLVM asm constraint validation failed"));
277
278         let mut attrs = SmallVec::<[_; 2]>::new();
279         if options.contains(InlineAsmOptions::PURE) {
280             if options.contains(InlineAsmOptions::NOMEM) {
281                 attrs.push(llvm::AttributeKind::ReadNone.create_attr(self.cx.llcx));
282             } else if options.contains(InlineAsmOptions::READONLY) {
283                 attrs.push(llvm::AttributeKind::ReadOnly.create_attr(self.cx.llcx));
284             }
285             attrs.push(llvm::AttributeKind::WillReturn.create_attr(self.cx.llcx));
286         } else if options.contains(InlineAsmOptions::NOMEM) {
287             attrs.push(llvm::AttributeKind::InaccessibleMemOnly.create_attr(self.cx.llcx));
288         } else {
289             // LLVM doesn't have an attribute to represent ReadOnly + SideEffect
290         }
291         attributes::apply_to_callsite(result, llvm::AttributePlace::Function, &{ attrs });
292
293         // Write results to outputs
294         for (idx, op) in operands.iter().enumerate() {
295             if let InlineAsmOperandRef::Out { reg, place: Some(place), .. }
296             | InlineAsmOperandRef::InOut { reg, out_place: Some(place), .. } = *op
297             {
298                 let value = if output_types.len() == 1 {
299                     result
300                 } else {
301                     self.extract_value(result, op_idx[&idx] as u64)
302                 };
303                 let value = llvm_fixup_output(self, value, reg.reg_class(), &place.layout);
304                 OperandValue::Immediate(value).store(self, place);
305             }
306         }
307     }
308 }
309
310 impl AsmMethods for CodegenCx<'_, '_> {
311     fn codegen_global_asm(
312         &self,
313         template: &[InlineAsmTemplatePiece],
314         operands: &[GlobalAsmOperandRef],
315         options: InlineAsmOptions,
316         _line_spans: &[Span],
317     ) {
318         let asm_arch = self.tcx.sess.asm_arch.unwrap();
319
320         // Default to Intel syntax on x86
321         let intel_syntax = matches!(asm_arch, InlineAsmArch::X86 | InlineAsmArch::X86_64)
322             && !options.contains(InlineAsmOptions::ATT_SYNTAX);
323
324         // Build the template string
325         let mut template_str = String::new();
326         if intel_syntax {
327             template_str.push_str(".intel_syntax\n");
328         }
329         for piece in template {
330             match *piece {
331                 InlineAsmTemplatePiece::String(ref s) => template_str.push_str(s),
332                 InlineAsmTemplatePiece::Placeholder { operand_idx, modifier: _, span: _ } => {
333                     match operands[operand_idx] {
334                         GlobalAsmOperandRef::Const { ref string } => {
335                             // Const operands get injected directly into the
336                             // template. Note that we don't need to escape $
337                             // here unlike normal inline assembly.
338                             template_str.push_str(string);
339                         }
340                     }
341                 }
342             }
343         }
344         if intel_syntax {
345             template_str.push_str("\n.att_syntax\n");
346         }
347
348         unsafe {
349             llvm::LLVMRustAppendModuleInlineAsm(
350                 self.llmod,
351                 template_str.as_ptr().cast(),
352                 template_str.len(),
353             );
354         }
355     }
356 }
357
358 pub(crate) fn inline_asm_call<'ll>(
359     bx: &mut Builder<'_, 'll, '_>,
360     asm: &str,
361     cons: &str,
362     inputs: &[&'ll Value],
363     output: &'ll llvm::Type,
364     volatile: bool,
365     alignstack: bool,
366     dia: llvm::AsmDialect,
367     line_spans: &[Span],
368     unwind: bool,
369     dest_catch_funclet: Option<(
370         &'ll llvm::BasicBlock,
371         &'ll llvm::BasicBlock,
372         Option<&Funclet<'ll>>,
373     )>,
374 ) -> Option<&'ll Value> {
375     let volatile = if volatile { llvm::True } else { llvm::False };
376     let alignstack = if alignstack { llvm::True } else { llvm::False };
377     let can_throw = if unwind { llvm::True } else { llvm::False };
378
379     let argtys = inputs
380         .iter()
381         .map(|v| {
382             debug!("Asm Input Type: {:?}", *v);
383             bx.cx.val_ty(*v)
384         })
385         .collect::<Vec<_>>();
386
387     debug!("Asm Output Type: {:?}", output);
388     let fty = bx.cx.type_func(&argtys, output);
389     unsafe {
390         // Ask LLVM to verify that the constraints are well-formed.
391         let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr().cast(), cons.len());
392         debug!("constraint verification result: {:?}", constraints_ok);
393         if constraints_ok {
394             if unwind && llvm_util::get_version() < (13, 0, 0) {
395                 bx.cx.sess().span_fatal(
396                     line_spans[0],
397                     "unwinding from inline assembly is only supported on llvm >= 13.",
398                 );
399             }
400
401             let v = llvm::LLVMRustInlineAsm(
402                 fty,
403                 asm.as_ptr().cast(),
404                 asm.len(),
405                 cons.as_ptr().cast(),
406                 cons.len(),
407                 volatile,
408                 alignstack,
409                 dia,
410                 can_throw,
411             );
412
413             let call = if let Some((dest, catch, funclet)) = dest_catch_funclet {
414                 bx.invoke(fty, v, inputs, dest, catch, funclet)
415             } else {
416                 bx.call(fty, v, inputs, None)
417             };
418
419             // Store mark in a metadata node so we can map LLVM errors
420             // back to source locations.  See #17552.
421             let key = "srcloc";
422             let kind = llvm::LLVMGetMDKindIDInContext(
423                 bx.llcx,
424                 key.as_ptr() as *const c_char,
425                 key.len() as c_uint,
426             );
427
428             // srcloc contains one integer for each line of assembly code.
429             // Unfortunately this isn't enough to encode a full span so instead
430             // we just encode the start position of each line.
431             // FIXME: Figure out a way to pass the entire line spans.
432             let mut srcloc = vec![];
433             if dia == llvm::AsmDialect::Intel && line_spans.len() > 1 {
434                 // LLVM inserts an extra line to add the ".intel_syntax", so add
435                 // a dummy srcloc entry for it.
436                 //
437                 // Don't do this if we only have 1 line span since that may be
438                 // due to the asm template string coming from a macro. LLVM will
439                 // default to the first srcloc for lines that don't have an
440                 // associated srcloc.
441                 srcloc.push(bx.const_i32(0));
442             }
443             srcloc.extend(line_spans.iter().map(|span| bx.const_i32(span.lo().to_u32() as i32)));
444             let md = llvm::LLVMMDNodeInContext(bx.llcx, srcloc.as_ptr(), srcloc.len() as u32);
445             llvm::LLVMSetMetadata(call, kind, md);
446
447             Some(call)
448         } else {
449             // LLVM has detected an issue with our constraints, bail out
450             None
451         }
452     }
453 }
454
455 /// If the register is an xmm/ymm/zmm register then return its index.
456 fn xmm_reg_index(reg: InlineAsmReg) -> Option<u32> {
457     match reg {
458         InlineAsmReg::X86(reg)
459             if reg as u32 >= X86InlineAsmReg::xmm0 as u32
460                 && reg as u32 <= X86InlineAsmReg::xmm15 as u32 =>
461         {
462             Some(reg as u32 - X86InlineAsmReg::xmm0 as u32)
463         }
464         InlineAsmReg::X86(reg)
465             if reg as u32 >= X86InlineAsmReg::ymm0 as u32
466                 && reg as u32 <= X86InlineAsmReg::ymm15 as u32 =>
467         {
468             Some(reg as u32 - X86InlineAsmReg::ymm0 as u32)
469         }
470         InlineAsmReg::X86(reg)
471             if reg as u32 >= X86InlineAsmReg::zmm0 as u32
472                 && reg as u32 <= X86InlineAsmReg::zmm31 as u32 =>
473         {
474             Some(reg as u32 - X86InlineAsmReg::zmm0 as u32)
475         }
476         _ => None,
477     }
478 }
479
480 /// If the register is an AArch64 vector register then return its index.
481 fn a64_vreg_index(reg: InlineAsmReg) -> Option<u32> {
482     match reg {
483         InlineAsmReg::AArch64(reg)
484             if reg as u32 >= AArch64InlineAsmReg::v0 as u32
485                 && reg as u32 <= AArch64InlineAsmReg::v31 as u32 =>
486         {
487             Some(reg as u32 - AArch64InlineAsmReg::v0 as u32)
488         }
489         _ => None,
490     }
491 }
492
493 /// Converts a register class to an LLVM constraint code.
494 fn reg_to_llvm(reg: InlineAsmRegOrRegClass, layout: Option<&TyAndLayout<'_>>) -> String {
495     match reg {
496         // For vector registers LLVM wants the register name to match the type size.
497         InlineAsmRegOrRegClass::Reg(reg) => {
498             if let Some(idx) = xmm_reg_index(reg) {
499                 let class = if let Some(layout) = layout {
500                     match layout.size.bytes() {
501                         64 => 'z',
502                         32 => 'y',
503                         _ => 'x',
504                     }
505                 } else {
506                     // We use f32 as the type for discarded outputs
507                     'x'
508                 };
509                 format!("{{{}mm{}}}", class, idx)
510             } else if let Some(idx) = a64_vreg_index(reg) {
511                 let class = if let Some(layout) = layout {
512                     match layout.size.bytes() {
513                         16 => 'q',
514                         8 => 'd',
515                         4 => 's',
516                         2 => 'h',
517                         1 => 'd', // We fixup i8 to i8x8
518                         _ => unreachable!(),
519                     }
520                 } else {
521                     // We use i64x2 as the type for discarded outputs
522                     'q'
523                 };
524                 format!("{{{}{}}}", class, idx)
525             } else if reg == InlineAsmReg::AArch64(AArch64InlineAsmReg::x30) {
526                 // LLVM doesn't recognize x30
527                 "{lr}".to_string()
528             } else if reg == InlineAsmReg::Arm(ArmInlineAsmReg::r14) {
529                 // LLVM doesn't recognize r14
530                 "{lr}".to_string()
531             } else {
532                 format!("{{{}}}", reg.name())
533             }
534         }
535         InlineAsmRegOrRegClass::RegClass(reg) => match reg {
536             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => "r",
537             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg) => "w",
538             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => "x",
539             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::preg) => {
540                 unreachable!("clobber-only")
541             }
542             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) => "r",
543             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
544             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
545             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8) => "t",
546             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16)
547             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8)
548             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => "x",
549             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
550             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg) => "w",
551             InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => "r",
552             InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg) => "r",
553             InlineAsmRegClass::Mips(MipsInlineAsmRegClass::freg) => "f",
554             InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => "h",
555             InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => "r",
556             InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => "l",
557             InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg) => "r",
558             InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => "b",
559             InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::freg) => "f",
560             InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::cr)
561             | InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::xer) => {
562                 unreachable!("clobber-only")
563             }
564             InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => "r",
565             InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => "f",
566             InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::vreg) => {
567                 unreachable!("clobber-only")
568             }
569             InlineAsmRegClass::X86(X86InlineAsmRegClass::reg) => "r",
570             InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => "Q",
571             InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => "q",
572             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg)
573             | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg) => "x",
574             InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => "v",
575             InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => "^Yk",
576             InlineAsmRegClass::X86(
577                 X86InlineAsmRegClass::x87_reg | X86InlineAsmRegClass::mmx_reg,
578             ) => unreachable!("clobber-only"),
579             InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => "r",
580             InlineAsmRegClass::Bpf(BpfInlineAsmRegClass::reg) => "r",
581             InlineAsmRegClass::Bpf(BpfInlineAsmRegClass::wreg) => "w",
582             InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg) => "r",
583             InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_upper) => "d",
584             InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_pair) => "r",
585             InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_iw) => "w",
586             InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_ptr) => "e",
587             InlineAsmRegClass::S390x(S390xInlineAsmRegClass::reg) => "r",
588             InlineAsmRegClass::S390x(S390xInlineAsmRegClass::freg) => "f",
589             InlineAsmRegClass::Msp430(Msp430InlineAsmRegClass::reg) => "r",
590             InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => {
591                 bug!("LLVM backend does not support SPIR-V")
592             }
593             InlineAsmRegClass::Err => unreachable!(),
594         }
595         .to_string(),
596     }
597 }
598
599 /// Converts a modifier into LLVM's equivalent modifier.
600 fn modifier_to_llvm(
601     arch: InlineAsmArch,
602     reg: InlineAsmRegClass,
603     modifier: Option<char>,
604 ) -> Option<char> {
605     match reg {
606         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => modifier,
607         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg)
608         | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
609             if modifier == Some('v') { None } else { modifier }
610         }
611         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::preg) => {
612             unreachable!("clobber-only")
613         }
614         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) => None,
615         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
616         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => None,
617         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
618         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
619         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => Some('P'),
620         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg)
621         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8)
622         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => {
623             if modifier.is_none() {
624                 Some('q')
625             } else {
626                 modifier
627             }
628         }
629         InlineAsmRegClass::Hexagon(_) => None,
630         InlineAsmRegClass::Mips(_) => None,
631         InlineAsmRegClass::Nvptx(_) => None,
632         InlineAsmRegClass::PowerPC(_) => None,
633         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg)
634         | InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => None,
635         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::vreg) => {
636             unreachable!("clobber-only")
637         }
638         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg)
639         | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => match modifier {
640             None if arch == InlineAsmArch::X86_64 => Some('q'),
641             None => Some('k'),
642             Some('l') => Some('b'),
643             Some('h') => Some('h'),
644             Some('x') => Some('w'),
645             Some('e') => Some('k'),
646             Some('r') => Some('q'),
647             _ => unreachable!(),
648         },
649         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => None,
650         InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::xmm_reg)
651         | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::ymm_reg)
652         | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::zmm_reg) => match (reg, modifier) {
653             (X86InlineAsmRegClass::xmm_reg, None) => Some('x'),
654             (X86InlineAsmRegClass::ymm_reg, None) => Some('t'),
655             (X86InlineAsmRegClass::zmm_reg, None) => Some('g'),
656             (_, Some('x')) => Some('x'),
657             (_, Some('y')) => Some('t'),
658             (_, Some('z')) => Some('g'),
659             _ => unreachable!(),
660         },
661         InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => None,
662         InlineAsmRegClass::X86(X86InlineAsmRegClass::x87_reg | X86InlineAsmRegClass::mmx_reg) => {
663             unreachable!("clobber-only")
664         }
665         InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => None,
666         InlineAsmRegClass::Bpf(_) => None,
667         InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_pair)
668         | InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_iw)
669         | InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_ptr) => match modifier {
670             Some('h') => Some('B'),
671             Some('l') => Some('A'),
672             _ => None,
673         },
674         InlineAsmRegClass::Avr(_) => None,
675         InlineAsmRegClass::S390x(_) => None,
676         InlineAsmRegClass::Msp430(_) => None,
677         InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => {
678             bug!("LLVM backend does not support SPIR-V")
679         }
680         InlineAsmRegClass::Err => unreachable!(),
681     }
682 }
683
684 /// Type to use for outputs that are discarded. It doesn't really matter what
685 /// the type is, as long as it is valid for the constraint code.
686 fn dummy_output_type<'ll>(cx: &CodegenCx<'ll, '_>, reg: InlineAsmRegClass) -> &'ll Type {
687     match reg {
688         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => cx.type_i32(),
689         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg)
690         | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
691             cx.type_vector(cx.type_i64(), 2)
692         }
693         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::preg) => {
694             unreachable!("clobber-only")
695         }
696         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) => cx.type_i32(),
697         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
698         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => cx.type_f32(),
699         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
700         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
701         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => cx.type_f64(),
702         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg)
703         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8)
704         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => {
705             cx.type_vector(cx.type_i64(), 2)
706         }
707         InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => cx.type_i32(),
708         InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg) => cx.type_i32(),
709         InlineAsmRegClass::Mips(MipsInlineAsmRegClass::freg) => cx.type_f32(),
710         InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => cx.type_i16(),
711         InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => cx.type_i32(),
712         InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => cx.type_i64(),
713         InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg) => cx.type_i32(),
714         InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => cx.type_i32(),
715         InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::freg) => cx.type_f64(),
716         InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::cr)
717         | InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::xer) => {
718             unreachable!("clobber-only")
719         }
720         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => cx.type_i32(),
721         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => cx.type_f32(),
722         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::vreg) => {
723             unreachable!("clobber-only")
724         }
725         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg)
726         | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => cx.type_i32(),
727         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => cx.type_i8(),
728         InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg)
729         | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg)
730         | InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => cx.type_f32(),
731         InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => cx.type_i16(),
732         InlineAsmRegClass::X86(X86InlineAsmRegClass::x87_reg | X86InlineAsmRegClass::mmx_reg) => {
733             unreachable!("clobber-only")
734         }
735         InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => cx.type_i32(),
736         InlineAsmRegClass::Bpf(BpfInlineAsmRegClass::reg) => cx.type_i64(),
737         InlineAsmRegClass::Bpf(BpfInlineAsmRegClass::wreg) => cx.type_i32(),
738         InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg) => cx.type_i8(),
739         InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_upper) => cx.type_i8(),
740         InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_pair) => cx.type_i16(),
741         InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_iw) => cx.type_i16(),
742         InlineAsmRegClass::Avr(AvrInlineAsmRegClass::reg_ptr) => cx.type_i16(),
743         InlineAsmRegClass::S390x(S390xInlineAsmRegClass::reg) => cx.type_i32(),
744         InlineAsmRegClass::S390x(S390xInlineAsmRegClass::freg) => cx.type_f64(),
745         InlineAsmRegClass::Msp430(Msp430InlineAsmRegClass::reg) => cx.type_i16(),
746         InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => {
747             bug!("LLVM backend does not support SPIR-V")
748         }
749         InlineAsmRegClass::Err => unreachable!(),
750     }
751 }
752
753 /// Helper function to get the LLVM type for a Scalar. Pointers are returned as
754 /// the equivalent integer type.
755 fn llvm_asm_scalar_type<'ll>(cx: &CodegenCx<'ll, '_>, scalar: Scalar) -> &'ll Type {
756     match scalar.value {
757         Primitive::Int(Integer::I8, _) => cx.type_i8(),
758         Primitive::Int(Integer::I16, _) => cx.type_i16(),
759         Primitive::Int(Integer::I32, _) => cx.type_i32(),
760         Primitive::Int(Integer::I64, _) => cx.type_i64(),
761         Primitive::F32 => cx.type_f32(),
762         Primitive::F64 => cx.type_f64(),
763         Primitive::Pointer => cx.type_isize(),
764         _ => unreachable!(),
765     }
766 }
767
768 /// Fix up an input value to work around LLVM bugs.
769 fn llvm_fixup_input<'ll, 'tcx>(
770     bx: &mut Builder<'_, 'll, 'tcx>,
771     mut value: &'ll Value,
772     reg: InlineAsmRegClass,
773     layout: &TyAndLayout<'tcx>,
774 ) -> &'ll Value {
775     match (reg, layout.abi) {
776         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
777             if let Primitive::Int(Integer::I8, _) = s.value {
778                 let vec_ty = bx.cx.type_vector(bx.cx.type_i8(), 8);
779                 bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
780             } else {
781                 value
782             }
783         }
784         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
785             let elem_ty = llvm_asm_scalar_type(bx.cx, s);
786             let count = 16 / layout.size.bytes();
787             let vec_ty = bx.cx.type_vector(elem_ty, count);
788             if let Primitive::Pointer = s.value {
789                 value = bx.ptrtoint(value, bx.cx.type_isize());
790             }
791             bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
792         }
793         (
794             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
795             Abi::Vector { element, count },
796         ) if layout.size.bytes() == 8 => {
797             let elem_ty = llvm_asm_scalar_type(bx.cx, element);
798             let vec_ty = bx.cx.type_vector(elem_ty, count);
799             let indices: Vec<_> = (0..count * 2).map(|x| bx.const_i32(x as i32)).collect();
800             bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
801         }
802         (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
803             if s.value == Primitive::F64 =>
804         {
805             bx.bitcast(value, bx.cx.type_i64())
806         }
807         (
808             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
809             Abi::Vector { .. },
810         ) if layout.size.bytes() == 64 => bx.bitcast(value, bx.cx.type_vector(bx.cx.type_f64(), 8)),
811         (
812             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
813             Abi::Scalar(s),
814         ) => {
815             if let Primitive::Int(Integer::I32, _) = s.value {
816                 bx.bitcast(value, bx.cx.type_f32())
817             } else {
818                 value
819             }
820         }
821         (
822             InlineAsmRegClass::Arm(
823                 ArmInlineAsmRegClass::dreg
824                 | ArmInlineAsmRegClass::dreg_low8
825                 | ArmInlineAsmRegClass::dreg_low16,
826             ),
827             Abi::Scalar(s),
828         ) => {
829             if let Primitive::Int(Integer::I64, _) = s.value {
830                 bx.bitcast(value, bx.cx.type_f64())
831             } else {
832                 value
833             }
834         }
835         (InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg), Abi::Scalar(s)) => match s.value {
836             // MIPS only supports register-length arithmetics.
837             Primitive::Int(Integer::I8 | Integer::I16, _) => bx.zext(value, bx.cx.type_i32()),
838             Primitive::F32 => bx.bitcast(value, bx.cx.type_i32()),
839             Primitive::F64 => bx.bitcast(value, bx.cx.type_i64()),
840             _ => value,
841         },
842         _ => value,
843     }
844 }
845
846 /// Fix up an output value to work around LLVM bugs.
847 fn llvm_fixup_output<'ll, 'tcx>(
848     bx: &mut Builder<'_, 'll, 'tcx>,
849     mut value: &'ll Value,
850     reg: InlineAsmRegClass,
851     layout: &TyAndLayout<'tcx>,
852 ) -> &'ll Value {
853     match (reg, layout.abi) {
854         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
855             if let Primitive::Int(Integer::I8, _) = s.value {
856                 bx.extract_element(value, bx.const_i32(0))
857             } else {
858                 value
859             }
860         }
861         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
862             value = bx.extract_element(value, bx.const_i32(0));
863             if let Primitive::Pointer = s.value {
864                 value = bx.inttoptr(value, layout.llvm_type(bx.cx));
865             }
866             value
867         }
868         (
869             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
870             Abi::Vector { element, count },
871         ) if layout.size.bytes() == 8 => {
872             let elem_ty = llvm_asm_scalar_type(bx.cx, element);
873             let vec_ty = bx.cx.type_vector(elem_ty, count * 2);
874             let indices: Vec<_> = (0..count).map(|x| bx.const_i32(x as i32)).collect();
875             bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
876         }
877         (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
878             if s.value == Primitive::F64 =>
879         {
880             bx.bitcast(value, bx.cx.type_f64())
881         }
882         (
883             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
884             Abi::Vector { .. },
885         ) if layout.size.bytes() == 64 => bx.bitcast(value, layout.llvm_type(bx.cx)),
886         (
887             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
888             Abi::Scalar(s),
889         ) => {
890             if let Primitive::Int(Integer::I32, _) = s.value {
891                 bx.bitcast(value, bx.cx.type_i32())
892             } else {
893                 value
894             }
895         }
896         (
897             InlineAsmRegClass::Arm(
898                 ArmInlineAsmRegClass::dreg
899                 | ArmInlineAsmRegClass::dreg_low8
900                 | ArmInlineAsmRegClass::dreg_low16,
901             ),
902             Abi::Scalar(s),
903         ) => {
904             if let Primitive::Int(Integer::I64, _) = s.value {
905                 bx.bitcast(value, bx.cx.type_i64())
906             } else {
907                 value
908             }
909         }
910         (InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg), Abi::Scalar(s)) => match s.value {
911             // MIPS only supports register-length arithmetics.
912             Primitive::Int(Integer::I8, _) => bx.trunc(value, bx.cx.type_i8()),
913             Primitive::Int(Integer::I16, _) => bx.trunc(value, bx.cx.type_i16()),
914             Primitive::F32 => bx.bitcast(value, bx.cx.type_f32()),
915             Primitive::F64 => bx.bitcast(value, bx.cx.type_f64()),
916             _ => value,
917         },
918         _ => value,
919     }
920 }
921
922 /// Output type to use for llvm_fixup_output.
923 fn llvm_fixup_output_type<'ll, 'tcx>(
924     cx: &CodegenCx<'ll, 'tcx>,
925     reg: InlineAsmRegClass,
926     layout: &TyAndLayout<'tcx>,
927 ) -> &'ll Type {
928     match (reg, layout.abi) {
929         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
930             if let Primitive::Int(Integer::I8, _) = s.value {
931                 cx.type_vector(cx.type_i8(), 8)
932             } else {
933                 layout.llvm_type(cx)
934             }
935         }
936         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
937             let elem_ty = llvm_asm_scalar_type(cx, s);
938             let count = 16 / layout.size.bytes();
939             cx.type_vector(elem_ty, count)
940         }
941         (
942             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
943             Abi::Vector { element, count },
944         ) if layout.size.bytes() == 8 => {
945             let elem_ty = llvm_asm_scalar_type(cx, element);
946             cx.type_vector(elem_ty, count * 2)
947         }
948         (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
949             if s.value == Primitive::F64 =>
950         {
951             cx.type_i64()
952         }
953         (
954             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
955             Abi::Vector { .. },
956         ) if layout.size.bytes() == 64 => cx.type_vector(cx.type_f64(), 8),
957         (
958             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
959             Abi::Scalar(s),
960         ) => {
961             if let Primitive::Int(Integer::I32, _) = s.value {
962                 cx.type_f32()
963             } else {
964                 layout.llvm_type(cx)
965             }
966         }
967         (
968             InlineAsmRegClass::Arm(
969                 ArmInlineAsmRegClass::dreg
970                 | ArmInlineAsmRegClass::dreg_low8
971                 | ArmInlineAsmRegClass::dreg_low16,
972             ),
973             Abi::Scalar(s),
974         ) => {
975             if let Primitive::Int(Integer::I64, _) = s.value {
976                 cx.type_f64()
977             } else {
978                 layout.llvm_type(cx)
979             }
980         }
981         (InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg), Abi::Scalar(s)) => match s.value {
982             // MIPS only supports register-length arithmetics.
983             Primitive::Int(Integer::I8 | Integer::I16, _) => cx.type_i32(),
984             Primitive::F32 => cx.type_i32(),
985             Primitive::F64 => cx.type_i64(),
986             _ => layout.llvm_type(cx),
987         },
988         _ => layout.llvm_type(cx),
989     }
990 }