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