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