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