]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/asm.rs
Rollup merge of #74353 - pierwill:pierwill-edit-dep-node, r=jonas-schievink
[rust.git] / src / librustc_codegen_llvm / 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::ast::LlvmAsmDialect;
9 use rustc_ast::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::span_bug;
16 use rustc_middle::ty::layout::TyAndLayout;
17 use rustc_span::{Pos, Span};
18 use rustc_target::abi::*;
19 use rustc_target::asm::*;
20
21 use libc::{c_char, c_uint};
22 use log::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.target.arch[..] {
64             "x86" | "x86_64" => vec!["~{dirflag}", "~{fpsr}", "~{flags}"],
65             "mips" | "mips64" => vec!["~{$1}"],
66             _ => Vec::new(),
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 output_types = vec![];
129         let mut op_idx = FxHashMap::default();
130         for (idx, op) in operands.iter().enumerate() {
131             match *op {
132                 InlineAsmOperandRef::Out { reg, late, place } => {
133                     let ty = if let Some(place) = place {
134                         llvm_fixup_output_type(self.cx, reg.reg_class(), &place.layout)
135                     } else {
136                         // If the output is discarded, we don't really care what
137                         // type is used. We're just using this to tell LLVM to
138                         // reserve the register.
139                         dummy_output_type(self.cx, reg.reg_class())
140                     };
141                     output_types.push(ty);
142                     op_idx.insert(idx, constraints.len());
143                     let prefix = if late { "=" } else { "=&" };
144                     constraints.push(format!("{}{}", prefix, reg_to_llvm(reg)));
145                 }
146                 InlineAsmOperandRef::InOut { reg, late, in_value, out_place } => {
147                     let ty = if let Some(ref out_place) = out_place {
148                         llvm_fixup_output_type(self.cx, reg.reg_class(), &out_place.layout)
149                     } else {
150                         // LLVM required tied operands to have the same type,
151                         // so we just use the type of the input.
152                         llvm_fixup_output_type(self.cx, reg.reg_class(), &in_value.layout)
153                     };
154                     output_types.push(ty);
155                     op_idx.insert(idx, constraints.len());
156                     let prefix = if late { "=" } else { "=&" };
157                     constraints.push(format!("{}{}", prefix, reg_to_llvm(reg)));
158                 }
159                 _ => {}
160             }
161         }
162
163         // Collect input operands
164         let mut inputs = vec![];
165         for (idx, op) in operands.iter().enumerate() {
166             match *op {
167                 InlineAsmOperandRef::In { reg, value } => {
168                     let value =
169                         llvm_fixup_input(self, value.immediate(), reg.reg_class(), &value.layout);
170                     inputs.push(value);
171                     op_idx.insert(idx, constraints.len());
172                     constraints.push(reg_to_llvm(reg));
173                 }
174                 InlineAsmOperandRef::InOut { reg, late: _, in_value, out_place: _ } => {
175                     let value = llvm_fixup_input(
176                         self,
177                         in_value.immediate(),
178                         reg.reg_class(),
179                         &in_value.layout,
180                     );
181                     inputs.push(value);
182                     constraints.push(format!("{}", op_idx[&idx]));
183                 }
184                 InlineAsmOperandRef::SymFn { instance } => {
185                     inputs.push(self.cx.get_fn(instance));
186                     op_idx.insert(idx, constraints.len());
187                     constraints.push("s".to_string());
188                 }
189                 InlineAsmOperandRef::SymStatic { def_id } => {
190                     inputs.push(self.cx.get_static(def_id));
191                     op_idx.insert(idx, constraints.len());
192                     constraints.push("s".to_string());
193                 }
194                 _ => {}
195             }
196         }
197
198         // Build the template string
199         let mut template_str = String::new();
200         for piece in template {
201             match *piece {
202                 InlineAsmTemplatePiece::String(ref s) => {
203                     if s.contains('$') {
204                         for c in s.chars() {
205                             if c == '$' {
206                                 template_str.push_str("$$");
207                             } else {
208                                 template_str.push(c);
209                             }
210                         }
211                     } else {
212                         template_str.push_str(s)
213                     }
214                 }
215                 InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => {
216                     match operands[operand_idx] {
217                         InlineAsmOperandRef::In { reg, .. }
218                         | InlineAsmOperandRef::Out { reg, .. }
219                         | InlineAsmOperandRef::InOut { reg, .. } => {
220                             let modifier = modifier_to_llvm(asm_arch, reg.reg_class(), modifier);
221                             if let Some(modifier) = modifier {
222                                 template_str.push_str(&format!(
223                                     "${{{}:{}}}",
224                                     op_idx[&operand_idx], modifier
225                                 ));
226                             } else {
227                                 template_str.push_str(&format!("${{{}}}", op_idx[&operand_idx]));
228                             }
229                         }
230                         InlineAsmOperandRef::Const { ref string } => {
231                             // Const operands get injected directly into the template
232                             template_str.push_str(string);
233                         }
234                         InlineAsmOperandRef::SymFn { .. }
235                         | InlineAsmOperandRef::SymStatic { .. } => {
236                             // Only emit the raw symbol name
237                             template_str.push_str(&format!("${{{}:c}}", op_idx[&operand_idx]));
238                         }
239                     }
240                 }
241             }
242         }
243
244         if !options.contains(InlineAsmOptions::PRESERVES_FLAGS) {
245             match asm_arch {
246                 InlineAsmArch::AArch64 | InlineAsmArch::Arm => {
247                     constraints.push("~{cc}".to_string());
248                 }
249                 InlineAsmArch::X86 | InlineAsmArch::X86_64 => {
250                     constraints.extend_from_slice(&[
251                         "~{dirflag}".to_string(),
252                         "~{fpsr}".to_string(),
253                         "~{flags}".to_string(),
254                     ]);
255                 }
256                 InlineAsmArch::RiscV32 | InlineAsmArch::RiscV64 => {}
257                 InlineAsmArch::Nvptx64 => {}
258                 InlineAsmArch::Hexagon => {}
259             }
260         }
261         if !options.contains(InlineAsmOptions::NOMEM) {
262             // This is actually ignored by LLVM, but it's probably best to keep
263             // it just in case. LLVM instead uses the ReadOnly/ReadNone
264             // attributes on the call instruction to optimize.
265             constraints.push("~{memory}".to_string());
266         }
267         let volatile = !options.contains(InlineAsmOptions::PURE);
268         let alignstack = !options.contains(InlineAsmOptions::NOSTACK);
269         let output_type = match &output_types[..] {
270             [] => self.type_void(),
271             [ty] => ty,
272             tys => self.type_struct(&tys, false),
273         };
274         let dialect = match asm_arch {
275             InlineAsmArch::X86 | InlineAsmArch::X86_64
276                 if !options.contains(InlineAsmOptions::ATT_SYNTAX) =>
277             {
278                 LlvmAsmDialect::Intel
279             }
280             _ => LlvmAsmDialect::Att,
281         };
282         let result = inline_asm_call(
283             self,
284             &template_str,
285             &constraints.join(","),
286             &inputs,
287             output_type,
288             volatile,
289             alignstack,
290             dialect,
291             line_spans,
292         )
293         .unwrap_or_else(|| span_bug!(line_spans[0], "LLVM asm constraint validation failed"));
294
295         if options.contains(InlineAsmOptions::PURE) {
296             if options.contains(InlineAsmOptions::NOMEM) {
297                 llvm::Attribute::ReadNone.apply_callsite(llvm::AttributePlace::Function, result);
298             } else if options.contains(InlineAsmOptions::READONLY) {
299                 llvm::Attribute::ReadOnly.apply_callsite(llvm::AttributePlace::Function, result);
300             }
301         } else {
302             if options.contains(InlineAsmOptions::NOMEM) {
303                 llvm::Attribute::InaccessibleMemOnly
304                     .apply_callsite(llvm::AttributePlace::Function, result);
305             } else {
306                 // LLVM doesn't have an attribute to represent ReadOnly + SideEffect
307             }
308         }
309
310         // Write results to outputs
311         for (idx, op) in operands.iter().enumerate() {
312             if let InlineAsmOperandRef::Out { reg, place: Some(place), .. }
313             | InlineAsmOperandRef::InOut { reg, out_place: Some(place), .. } = *op
314             {
315                 let value = if output_types.len() == 1 {
316                     result
317                 } else {
318                     self.extract_value(result, op_idx[&idx] as u64)
319                 };
320                 let value = llvm_fixup_output(self, value, reg.reg_class(), &place.layout);
321                 OperandValue::Immediate(value).store(self, place);
322             }
323         }
324     }
325 }
326
327 impl AsmMethods for CodegenCx<'ll, 'tcx> {
328     fn codegen_global_asm(&self, ga: &hir::GlobalAsm) {
329         let asm = ga.asm.as_str();
330         unsafe {
331             llvm::LLVMRustAppendModuleInlineAsm(self.llmod, asm.as_ptr().cast(), asm.len());
332         }
333     }
334 }
335
336 fn inline_asm_call(
337     bx: &mut Builder<'a, 'll, 'tcx>,
338     asm: &str,
339     cons: &str,
340     inputs: &[&'ll Value],
341     output: &'ll llvm::Type,
342     volatile: bool,
343     alignstack: bool,
344     dia: LlvmAsmDialect,
345     line_spans: &[Span],
346 ) -> Option<&'ll Value> {
347     let volatile = if volatile { llvm::True } else { llvm::False };
348     let alignstack = if alignstack { llvm::True } else { llvm::False };
349
350     let argtys = inputs
351         .iter()
352         .map(|v| {
353             debug!("Asm Input Type: {:?}", *v);
354             bx.cx.val_ty(*v)
355         })
356         .collect::<Vec<_>>();
357
358     debug!("Asm Output Type: {:?}", output);
359     let fty = bx.cx.type_func(&argtys[..], output);
360     unsafe {
361         // Ask LLVM to verify that the constraints are well-formed.
362         let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr().cast(), cons.len());
363         debug!("constraint verification result: {:?}", constraints_ok);
364         if constraints_ok {
365             let v = llvm::LLVMRustInlineAsm(
366                 fty,
367                 asm.as_ptr().cast(),
368                 asm.len(),
369                 cons.as_ptr().cast(),
370                 cons.len(),
371                 volatile,
372                 alignstack,
373                 llvm::AsmDialect::from_generic(dia),
374             );
375             let call = bx.call(v, inputs, None);
376
377             // Store mark in a metadata node so we can map LLVM errors
378             // back to source locations.  See #17552.
379             let key = "srcloc";
380             let kind = llvm::LLVMGetMDKindIDInContext(
381                 bx.llcx,
382                 key.as_ptr() as *const c_char,
383                 key.len() as c_uint,
384             );
385
386             // srcloc contains one integer for each line of assembly code.
387             // Unfortunately this isn't enough to encode a full span so instead
388             // we just encode the start position of each line.
389             // FIXME: Figure out a way to pass the entire line spans.
390             let mut srcloc = vec![];
391             if dia == LlvmAsmDialect::Intel && line_spans.len() > 1 {
392                 // LLVM inserts an extra line to add the ".intel_syntax", so add
393                 // a dummy srcloc entry for it.
394                 //
395                 // Don't do this if we only have 1 line span since that may be
396                 // due to the asm template string coming from a macro. LLVM will
397                 // default to the first srcloc for lines that don't have an
398                 // associated srcloc.
399                 srcloc.push(bx.const_i32(0));
400             }
401             srcloc.extend(line_spans.iter().map(|span| bx.const_i32(span.lo().to_u32() as i32)));
402             let md = llvm::LLVMMDNodeInContext(bx.llcx, srcloc.as_ptr(), srcloc.len() as u32);
403             llvm::LLVMSetMetadata(call, kind, md);
404
405             Some(call)
406         } else {
407             // LLVM has detected an issue with our constraints, bail out
408             None
409         }
410     }
411 }
412
413 /// Converts a register class to an LLVM constraint code.
414 fn reg_to_llvm(reg: InlineAsmRegOrRegClass) -> String {
415     match reg {
416         InlineAsmRegOrRegClass::Reg(reg) => format!("{{{}}}", reg.name()),
417         InlineAsmRegOrRegClass::RegClass(reg) => match reg {
418             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => "r",
419             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg) => "w",
420             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => "x",
421             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) => "r",
422             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => "l",
423             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
424             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
425             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8) => "t",
426             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16)
427             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8)
428             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => "x",
429             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
430             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg) => "w",
431             InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => "r",
432             InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => "h",
433             InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => "r",
434             InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => "l",
435             InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => "r",
436             InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => "f",
437             InlineAsmRegClass::X86(X86InlineAsmRegClass::reg) => "r",
438             InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => "Q",
439             InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => "q",
440             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg)
441             | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg) => "x",
442             InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => "v",
443             InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => "^Yk",
444         }
445         .to_string(),
446     }
447 }
448
449 /// Converts a modifier into LLVM's equivalent modifier.
450 fn modifier_to_llvm(
451     arch: InlineAsmArch,
452     reg: InlineAsmRegClass,
453     modifier: Option<char>,
454 ) -> Option<char> {
455     match reg {
456         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => modifier,
457         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg)
458         | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
459             if modifier == Some('v') { None } else { modifier }
460         }
461         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg)
462         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => None,
463         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
464         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => None,
465         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
466         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
467         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => Some('P'),
468         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg)
469         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8)
470         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => {
471             if modifier.is_none() {
472                 Some('q')
473             } else {
474                 modifier
475             }
476         }
477         InlineAsmRegClass::Hexagon(_) => None,
478         InlineAsmRegClass::Nvptx(_) => None,
479         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg)
480         | InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => None,
481         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg)
482         | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => match modifier {
483             None if arch == InlineAsmArch::X86_64 => Some('q'),
484             None => Some('k'),
485             Some('l') => Some('b'),
486             Some('h') => Some('h'),
487             Some('x') => Some('w'),
488             Some('e') => Some('k'),
489             Some('r') => Some('q'),
490             _ => unreachable!(),
491         },
492         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => None,
493         InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::xmm_reg)
494         | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::ymm_reg)
495         | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::zmm_reg) => match (reg, modifier) {
496             (X86InlineAsmRegClass::xmm_reg, None) => Some('x'),
497             (X86InlineAsmRegClass::ymm_reg, None) => Some('t'),
498             (X86InlineAsmRegClass::zmm_reg, None) => Some('g'),
499             (_, Some('x')) => Some('x'),
500             (_, Some('y')) => Some('t'),
501             (_, Some('z')) => Some('g'),
502             _ => unreachable!(),
503         },
504         InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => None,
505     }
506 }
507
508 /// Type to use for outputs that are discarded. It doesn't really matter what
509 /// the type is, as long as it is valid for the constraint code.
510 fn dummy_output_type(cx: &CodegenCx<'ll, 'tcx>, reg: InlineAsmRegClass) -> &'ll Type {
511     match reg {
512         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => cx.type_i32(),
513         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg)
514         | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
515             cx.type_vector(cx.type_i64(), 2)
516         }
517         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg)
518         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => cx.type_i32(),
519         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
520         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => cx.type_f32(),
521         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
522         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
523         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => cx.type_f64(),
524         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg)
525         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8)
526         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => {
527             cx.type_vector(cx.type_i64(), 2)
528         }
529         InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => cx.type_i32(),
530         InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => cx.type_i16(),
531         InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => cx.type_i32(),
532         InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => cx.type_i64(),
533         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => cx.type_i32(),
534         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => cx.type_f32(),
535         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg)
536         | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => cx.type_i32(),
537         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => cx.type_i8(),
538         InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg)
539         | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg)
540         | InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => cx.type_f32(),
541         InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => cx.type_i16(),
542     }
543 }
544
545 /// Helper function to get the LLVM type for a Scalar. Pointers are returned as
546 /// the equivalent integer type.
547 fn llvm_asm_scalar_type(cx: &CodegenCx<'ll, 'tcx>, scalar: &Scalar) -> &'ll Type {
548     match scalar.value {
549         Primitive::Int(Integer::I8, _) => cx.type_i8(),
550         Primitive::Int(Integer::I16, _) => cx.type_i16(),
551         Primitive::Int(Integer::I32, _) => cx.type_i32(),
552         Primitive::Int(Integer::I64, _) => cx.type_i64(),
553         Primitive::F32 => cx.type_f32(),
554         Primitive::F64 => cx.type_f64(),
555         Primitive::Pointer => cx.type_isize(),
556         _ => unreachable!(),
557     }
558 }
559
560 /// Fix up an input value to work around LLVM bugs.
561 fn llvm_fixup_input(
562     bx: &mut Builder<'a, 'll, 'tcx>,
563     mut value: &'ll Value,
564     reg: InlineAsmRegClass,
565     layout: &TyAndLayout<'tcx>,
566 ) -> &'ll Value {
567     match (reg, &layout.abi) {
568         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
569             if let Primitive::Int(Integer::I8, _) = s.value {
570                 let vec_ty = bx.cx.type_vector(bx.cx.type_i8(), 8);
571                 bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
572             } else {
573                 value
574             }
575         }
576         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
577             let elem_ty = llvm_asm_scalar_type(bx.cx, s);
578             let count = 16 / layout.size.bytes();
579             let vec_ty = bx.cx.type_vector(elem_ty, count);
580             if let Primitive::Pointer = s.value {
581                 value = bx.ptrtoint(value, bx.cx.type_isize());
582             }
583             bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
584         }
585         (
586             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
587             Abi::Vector { element, count },
588         ) if layout.size.bytes() == 8 => {
589             let elem_ty = llvm_asm_scalar_type(bx.cx, element);
590             let vec_ty = bx.cx.type_vector(elem_ty, *count);
591             let indices: Vec<_> = (0..count * 2).map(|x| bx.const_i32(x as i32)).collect();
592             bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
593         }
594         (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
595             if s.value == Primitive::F64 =>
596         {
597             bx.bitcast(value, bx.cx.type_i64())
598         }
599         (
600             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
601             Abi::Vector { .. },
602         ) if layout.size.bytes() == 64 => bx.bitcast(value, bx.cx.type_vector(bx.cx.type_f64(), 8)),
603         (
604             InlineAsmRegClass::Arm(
605                 ArmInlineAsmRegClass::sreg_low16
606                 | ArmInlineAsmRegClass::dreg_low8
607                 | ArmInlineAsmRegClass::qreg_low4
608                 | ArmInlineAsmRegClass::dreg
609                 | ArmInlineAsmRegClass::qreg,
610             ),
611             Abi::Scalar(s),
612         ) => {
613             if let Primitive::Int(Integer::I32, _) = s.value {
614                 bx.bitcast(value, bx.cx.type_f32())
615             } else {
616                 value
617             }
618         }
619         _ => value,
620     }
621 }
622
623 /// Fix up an output value to work around LLVM bugs.
624 fn llvm_fixup_output(
625     bx: &mut Builder<'a, 'll, 'tcx>,
626     mut value: &'ll Value,
627     reg: InlineAsmRegClass,
628     layout: &TyAndLayout<'tcx>,
629 ) -> &'ll Value {
630     match (reg, &layout.abi) {
631         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
632             if let Primitive::Int(Integer::I8, _) = s.value {
633                 bx.extract_element(value, bx.const_i32(0))
634             } else {
635                 value
636             }
637         }
638         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
639             value = bx.extract_element(value, bx.const_i32(0));
640             if let Primitive::Pointer = s.value {
641                 value = bx.inttoptr(value, layout.llvm_type(bx.cx));
642             }
643             value
644         }
645         (
646             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
647             Abi::Vector { element, count },
648         ) if layout.size.bytes() == 8 => {
649             let elem_ty = llvm_asm_scalar_type(bx.cx, element);
650             let vec_ty = bx.cx.type_vector(elem_ty, *count * 2);
651             let indices: Vec<_> = (0..*count).map(|x| bx.const_i32(x as i32)).collect();
652             bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
653         }
654         (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
655             if s.value == Primitive::F64 =>
656         {
657             bx.bitcast(value, bx.cx.type_f64())
658         }
659         (
660             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
661             Abi::Vector { .. },
662         ) if layout.size.bytes() == 64 => bx.bitcast(value, layout.llvm_type(bx.cx)),
663         (
664             InlineAsmRegClass::Arm(
665                 ArmInlineAsmRegClass::sreg_low16
666                 | ArmInlineAsmRegClass::dreg_low8
667                 | ArmInlineAsmRegClass::qreg_low4
668                 | ArmInlineAsmRegClass::dreg
669                 | ArmInlineAsmRegClass::qreg,
670             ),
671             Abi::Scalar(s),
672         ) => {
673             if let Primitive::Int(Integer::I32, _) = s.value {
674                 bx.bitcast(value, bx.cx.type_i32())
675             } else {
676                 value
677             }
678         }
679         _ => value,
680     }
681 }
682
683 /// Output type to use for llvm_fixup_output.
684 fn llvm_fixup_output_type(
685     cx: &CodegenCx<'ll, 'tcx>,
686     reg: InlineAsmRegClass,
687     layout: &TyAndLayout<'tcx>,
688 ) -> &'ll Type {
689     match (reg, &layout.abi) {
690         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
691             if let Primitive::Int(Integer::I8, _) = s.value {
692                 cx.type_vector(cx.type_i8(), 8)
693             } else {
694                 layout.llvm_type(cx)
695             }
696         }
697         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
698             let elem_ty = llvm_asm_scalar_type(cx, s);
699             let count = 16 / layout.size.bytes();
700             cx.type_vector(elem_ty, count)
701         }
702         (
703             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
704             Abi::Vector { element, count },
705         ) if layout.size.bytes() == 8 => {
706             let elem_ty = llvm_asm_scalar_type(cx, element);
707             cx.type_vector(elem_ty, count * 2)
708         }
709         (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
710             if s.value == Primitive::F64 =>
711         {
712             cx.type_i64()
713         }
714         (
715             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
716             Abi::Vector { .. },
717         ) if layout.size.bytes() == 64 => cx.type_vector(cx.type_f64(), 8),
718         (
719             InlineAsmRegClass::Arm(
720                 ArmInlineAsmRegClass::sreg_low16
721                 | ArmInlineAsmRegClass::dreg_low8
722                 | ArmInlineAsmRegClass::qreg_low4
723                 | ArmInlineAsmRegClass::dreg
724                 | ArmInlineAsmRegClass::qreg,
725             ),
726             Abi::Scalar(s),
727         ) => {
728             if let Primitive::Int(Integer::I32, _) = s.value {
729                 cx.type_f32()
730             } else {
731                 layout.llvm_type(cx)
732             }
733         }
734         _ => layout.llvm_type(cx),
735     }
736 }