]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/asm.rs
Rollup merge of #69825 - lcnr:discriminant, r=oli-obk
[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_of::LayoutLlvmExt;
5 use crate::value::Value;
6
7 use rustc_codegen_ssa::mir::operand::OperandValue;
8 use rustc_codegen_ssa::mir::place::PlaceRef;
9 use rustc_codegen_ssa::traits::*;
10 use rustc_hir as hir;
11 use rustc_span::Span;
12
13 use libc::{c_char, c_uint};
14 use log::debug;
15 use std::ffi::{CStr, CString};
16
17 impl AsmBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
18     fn codegen_inline_asm(
19         &mut self,
20         ia: &hir::InlineAsmInner,
21         outputs: Vec<PlaceRef<'tcx, &'ll Value>>,
22         mut inputs: Vec<&'ll Value>,
23         span: Span,
24     ) -> bool {
25         let mut ext_constraints = vec![];
26         let mut output_types = vec![];
27
28         // Prepare the output operands
29         let mut indirect_outputs = vec![];
30         for (i, (out, &place)) in ia.outputs.iter().zip(&outputs).enumerate() {
31             if out.is_rw {
32                 let operand = self.load_operand(place);
33                 if let OperandValue::Immediate(_) = operand.val {
34                     inputs.push(operand.immediate());
35                 }
36                 ext_constraints.push(i.to_string());
37             }
38             if out.is_indirect {
39                 let operand = self.load_operand(place);
40                 if let OperandValue::Immediate(_) = operand.val {
41                     indirect_outputs.push(operand.immediate());
42                 }
43             } else {
44                 output_types.push(place.layout.llvm_type(self.cx()));
45             }
46         }
47         if !indirect_outputs.is_empty() {
48             indirect_outputs.extend_from_slice(&inputs);
49             inputs = indirect_outputs;
50         }
51
52         let clobbers = ia.clobbers.iter().map(|s| format!("~{{{}}}", &s));
53
54         // Default per-arch clobbers
55         // Basically what clang does
56         let arch_clobbers = match &self.sess().target.target.arch[..] {
57             "x86" | "x86_64" => vec!["~{dirflag}", "~{fpsr}", "~{flags}"],
58             "mips" | "mips64" => vec!["~{$1}"],
59             _ => Vec::new(),
60         };
61
62         let all_constraints = ia
63             .outputs
64             .iter()
65             .map(|out| out.constraint.to_string())
66             .chain(ia.inputs.iter().map(|s| s.to_string()))
67             .chain(ext_constraints)
68             .chain(clobbers)
69             .chain(arch_clobbers.iter().map(|s| (*s).to_string()))
70             .collect::<Vec<String>>()
71             .join(",");
72
73         debug!("Asm Constraints: {}", &all_constraints);
74
75         // Depending on how many outputs we have, the return type is different
76         let num_outputs = output_types.len();
77         let output_type = match num_outputs {
78             0 => self.type_void(),
79             1 => output_types[0],
80             _ => self.type_struct(&output_types, false),
81         };
82
83         let asm = CString::new(ia.asm.as_str().as_bytes()).unwrap();
84         let constraint_cstr = CString::new(all_constraints).unwrap();
85         let r = inline_asm_call(
86             self,
87             &asm,
88             &constraint_cstr,
89             &inputs,
90             output_type,
91             ia.volatile,
92             ia.alignstack,
93             ia.dialect,
94         );
95         if r.is_none() {
96             return false;
97         }
98         let r = r.unwrap();
99
100         // Again, based on how many outputs we have
101         let outputs = ia.outputs.iter().zip(&outputs).filter(|&(ref o, _)| !o.is_indirect);
102         for (i, (_, &place)) in outputs.enumerate() {
103             let v = if num_outputs == 1 { r } else { self.extract_value(r, i as u64) };
104             OperandValue::Immediate(v).store(self, place);
105         }
106
107         // Store mark in a metadata node so we can map LLVM errors
108         // back to source locations.  See #17552.
109         unsafe {
110             let key = "srcloc";
111             let kind = llvm::LLVMGetMDKindIDInContext(
112                 self.llcx,
113                 key.as_ptr() as *const c_char,
114                 key.len() as c_uint,
115             );
116
117             let val: &'ll Value = self.const_i32(span.ctxt().outer_expn().as_u32() as i32);
118
119             llvm::LLVMSetMetadata(r, kind, llvm::LLVMMDNodeInContext(self.llcx, &val, 1));
120         }
121
122         true
123     }
124 }
125
126 impl AsmMethods for CodegenCx<'ll, 'tcx> {
127     fn codegen_global_asm(&self, ga: &hir::GlobalAsm) {
128         let asm = CString::new(ga.asm.as_str().as_bytes()).unwrap();
129         unsafe {
130             llvm::LLVMRustAppendModuleInlineAsm(self.llmod, asm.as_ptr());
131         }
132     }
133 }
134
135 fn inline_asm_call(
136     bx: &mut Builder<'a, 'll, 'tcx>,
137     asm: &CStr,
138     cons: &CStr,
139     inputs: &[&'ll Value],
140     output: &'ll llvm::Type,
141     volatile: bool,
142     alignstack: bool,
143     dia: ::rustc_ast::ast::AsmDialect,
144 ) -> Option<&'ll Value> {
145     let volatile = if volatile { llvm::True } else { llvm::False };
146     let alignstack = if alignstack { llvm::True } else { llvm::False };
147
148     let argtys = inputs
149         .iter()
150         .map(|v| {
151             debug!("Asm Input Type: {:?}", *v);
152             bx.cx.val_ty(*v)
153         })
154         .collect::<Vec<_>>();
155
156     debug!("Asm Output Type: {:?}", output);
157     let fty = bx.cx.type_func(&argtys[..], output);
158     unsafe {
159         // Ask LLVM to verify that the constraints are well-formed.
160         let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr());
161         debug!("constraint verification result: {:?}", constraints_ok);
162         if constraints_ok {
163             let v = llvm::LLVMRustInlineAsm(
164                 fty,
165                 asm.as_ptr(),
166                 cons.as_ptr(),
167                 volatile,
168                 alignstack,
169                 llvm::AsmDialect::from_generic(dia),
170             );
171             Some(bx.call(v, inputs, None))
172         } else {
173             // LLVM has detected an issue with our constraints, bail out
174             None
175         }
176     }
177 }