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