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