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