]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/asm.rs
Auto merge of #89514 - davidtwco:polymorphize-shims-and-predicates, r=lcnr
[rust.git] / compiler / rustc_ast_lowering / src / asm.rs
1 use super::LoweringContext;
2
3 use rustc_ast::*;
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_errors::struct_span_err;
6 use rustc_hir as hir;
7 use rustc_span::{Span, Symbol};
8 use rustc_target::asm;
9 use std::collections::hash_map::Entry;
10 use std::fmt::Write;
11
12 impl<'a, 'hir> LoweringContext<'a, 'hir> {
13     crate fn lower_inline_asm(&mut self, sp: Span, asm: &InlineAsm) -> &'hir hir::InlineAsm<'hir> {
14         // Rustdoc needs to support asm! from foriegn architectures: don't try
15         // lowering the register contraints in this case.
16         let asm_arch = if self.sess.opts.actually_rustdoc { None } else { self.sess.asm_arch };
17         if asm_arch.is_none() && !self.sess.opts.actually_rustdoc {
18             struct_span_err!(self.sess, sp, E0472, "inline assembly is unsupported on this target")
19                 .emit();
20         }
21         if asm.options.contains(InlineAsmOptions::ATT_SYNTAX)
22             && !matches!(asm_arch, Some(asm::InlineAsmArch::X86 | asm::InlineAsmArch::X86_64))
23             && !self.sess.opts.actually_rustdoc
24         {
25             self.sess
26                 .struct_span_err(sp, "the `att_syntax` option is only supported on x86")
27                 .emit();
28         }
29
30         let mut clobber_abi = None;
31         if let Some(asm_arch) = asm_arch {
32             if let Some((abi_name, abi_span)) = asm.clobber_abi {
33                 match asm::InlineAsmClobberAbi::parse(asm_arch, &self.sess.target, abi_name) {
34                     Ok(abi) => clobber_abi = Some((abi, abi_span)),
35                     Err(&[]) => {
36                         self.sess
37                             .struct_span_err(
38                                 abi_span,
39                                 "`clobber_abi` is not supported on this target",
40                             )
41                             .emit();
42                     }
43                     Err(supported_abis) => {
44                         let mut err =
45                             self.sess.struct_span_err(abi_span, "invalid ABI for `clobber_abi`");
46                         let mut abis = format!("`{}`", supported_abis[0]);
47                         for m in &supported_abis[1..] {
48                             let _ = write!(abis, ", `{}`", m);
49                         }
50                         err.note(&format!(
51                             "the following ABIs are supported on this target: {}",
52                             abis
53                         ));
54                         err.emit();
55                     }
56                 }
57             }
58         }
59
60         // Lower operands to HIR. We use dummy register classes if an error
61         // occurs during lowering because we still need to be able to produce a
62         // valid HIR.
63         let sess = self.sess;
64         let mut operands: Vec<_> = asm
65             .operands
66             .iter()
67             .map(|(op, op_sp)| {
68                 let lower_reg = |reg| match reg {
69                     InlineAsmRegOrRegClass::Reg(s) => {
70                         asm::InlineAsmRegOrRegClass::Reg(if let Some(asm_arch) = asm_arch {
71                             asm::InlineAsmReg::parse(
72                                 asm_arch,
73                                 |feature| sess.target_features.contains(&Symbol::intern(feature)),
74                                 &sess.target,
75                                 s,
76                             )
77                             .unwrap_or_else(|e| {
78                                 let msg = format!("invalid register `{}`: {}", s.as_str(), e);
79                                 sess.struct_span_err(*op_sp, &msg).emit();
80                                 asm::InlineAsmReg::Err
81                             })
82                         } else {
83                             asm::InlineAsmReg::Err
84                         })
85                     }
86                     InlineAsmRegOrRegClass::RegClass(s) => {
87                         asm::InlineAsmRegOrRegClass::RegClass(if let Some(asm_arch) = asm_arch {
88                             asm::InlineAsmRegClass::parse(asm_arch, s).unwrap_or_else(|e| {
89                                 let msg = format!("invalid register class `{}`: {}", s.as_str(), e);
90                                 sess.struct_span_err(*op_sp, &msg).emit();
91                                 asm::InlineAsmRegClass::Err
92                             })
93                         } else {
94                             asm::InlineAsmRegClass::Err
95                         })
96                     }
97                 };
98
99                 let op = match *op {
100                     InlineAsmOperand::In { reg, ref expr } => hir::InlineAsmOperand::In {
101                         reg: lower_reg(reg),
102                         expr: self.lower_expr_mut(expr),
103                     },
104                     InlineAsmOperand::Out { reg, late, ref expr } => hir::InlineAsmOperand::Out {
105                         reg: lower_reg(reg),
106                         late,
107                         expr: expr.as_ref().map(|expr| self.lower_expr_mut(expr)),
108                     },
109                     InlineAsmOperand::InOut { reg, late, ref expr } => {
110                         hir::InlineAsmOperand::InOut {
111                             reg: lower_reg(reg),
112                             late,
113                             expr: self.lower_expr_mut(expr),
114                         }
115                     }
116                     InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => {
117                         hir::InlineAsmOperand::SplitInOut {
118                             reg: lower_reg(reg),
119                             late,
120                             in_expr: self.lower_expr_mut(in_expr),
121                             out_expr: out_expr.as_ref().map(|expr| self.lower_expr_mut(expr)),
122                         }
123                     }
124                     InlineAsmOperand::Const { ref anon_const } => hir::InlineAsmOperand::Const {
125                         anon_const: self.lower_anon_const(anon_const),
126                     },
127                     InlineAsmOperand::Sym { ref expr } => {
128                         hir::InlineAsmOperand::Sym { expr: self.lower_expr_mut(expr) }
129                     }
130                 };
131                 (op, self.lower_span(*op_sp))
132             })
133             .collect();
134
135         // Validate template modifiers against the register classes for the operands
136         for p in &asm.template {
137             if let InlineAsmTemplatePiece::Placeholder {
138                 operand_idx,
139                 modifier: Some(modifier),
140                 span: placeholder_span,
141             } = *p
142             {
143                 let op_sp = asm.operands[operand_idx].1;
144                 match &operands[operand_idx].0 {
145                     hir::InlineAsmOperand::In { reg, .. }
146                     | hir::InlineAsmOperand::Out { reg, .. }
147                     | hir::InlineAsmOperand::InOut { reg, .. }
148                     | hir::InlineAsmOperand::SplitInOut { reg, .. } => {
149                         let class = reg.reg_class();
150                         if class == asm::InlineAsmRegClass::Err {
151                             continue;
152                         }
153                         let valid_modifiers = class.valid_modifiers(asm_arch.unwrap());
154                         if !valid_modifiers.contains(&modifier) {
155                             let mut err = sess.struct_span_err(
156                                 placeholder_span,
157                                 "invalid asm template modifier for this register class",
158                             );
159                             err.span_label(placeholder_span, "template modifier");
160                             err.span_label(op_sp, "argument");
161                             if !valid_modifiers.is_empty() {
162                                 let mut mods = format!("`{}`", valid_modifiers[0]);
163                                 for m in &valid_modifiers[1..] {
164                                     let _ = write!(mods, ", `{}`", m);
165                                 }
166                                 err.note(&format!(
167                                     "the `{}` register class supports \
168                                      the following template modifiers: {}",
169                                     class.name(),
170                                     mods
171                                 ));
172                             } else {
173                                 err.note(&format!(
174                                     "the `{}` register class does not support template modifiers",
175                                     class.name()
176                                 ));
177                             }
178                             err.emit();
179                         }
180                     }
181                     hir::InlineAsmOperand::Const { .. } => {
182                         let mut err = sess.struct_span_err(
183                             placeholder_span,
184                             "asm template modifiers are not allowed for `const` arguments",
185                         );
186                         err.span_label(placeholder_span, "template modifier");
187                         err.span_label(op_sp, "argument");
188                         err.emit();
189                     }
190                     hir::InlineAsmOperand::Sym { .. } => {
191                         let mut err = sess.struct_span_err(
192                             placeholder_span,
193                             "asm template modifiers are not allowed for `sym` arguments",
194                         );
195                         err.span_label(placeholder_span, "template modifier");
196                         err.span_label(op_sp, "argument");
197                         err.emit();
198                     }
199                 }
200             }
201         }
202
203         let mut used_input_regs = FxHashMap::default();
204         let mut used_output_regs = FxHashMap::default();
205
206         for (idx, &(ref op, op_sp)) in operands.iter().enumerate() {
207             if let Some(reg) = op.reg() {
208                 let reg_class = reg.reg_class();
209                 if reg_class == asm::InlineAsmRegClass::Err {
210                     continue;
211                 }
212
213                 // Some register classes can only be used as clobbers. This
214                 // means that we disallow passing a value in/out of the asm and
215                 // require that the operand name an explicit register, not a
216                 // register class.
217                 if reg_class.is_clobber_only(asm_arch.unwrap())
218                     && !(op.is_clobber() && matches!(reg, asm::InlineAsmRegOrRegClass::Reg(_)))
219                 {
220                     let msg = format!(
221                         "register class `{}` can only be used as a clobber, \
222                              not as an input or output",
223                         reg_class.name()
224                     );
225                     sess.struct_span_err(op_sp, &msg).emit();
226                     continue;
227                 }
228
229                 // Check for conflicts between explicit register operands.
230                 if let asm::InlineAsmRegOrRegClass::Reg(reg) = reg {
231                     let (input, output) = match op {
232                         hir::InlineAsmOperand::In { .. } => (true, false),
233
234                         // Late output do not conflict with inputs, but normal outputs do
235                         hir::InlineAsmOperand::Out { late, .. } => (!late, true),
236
237                         hir::InlineAsmOperand::InOut { .. }
238                         | hir::InlineAsmOperand::SplitInOut { .. } => (true, true),
239
240                         hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::Sym { .. } => {
241                             unreachable!()
242                         }
243                     };
244
245                     // Flag to output the error only once per operand
246                     let mut skip = false;
247                     reg.overlapping_regs(|r| {
248                         let mut check = |used_regs: &mut FxHashMap<asm::InlineAsmReg, usize>,
249                                          input| {
250                             match used_regs.entry(r) {
251                                 Entry::Occupied(o) => {
252                                     if skip {
253                                         return;
254                                     }
255                                     skip = true;
256
257                                     let idx2 = *o.get();
258                                     let &(ref op2, op_sp2) = &operands[idx2];
259                                     let reg2 = match op2.reg() {
260                                         Some(asm::InlineAsmRegOrRegClass::Reg(r)) => r,
261                                         _ => unreachable!(),
262                                     };
263
264                                     let msg = format!(
265                                         "register `{}` conflicts with register `{}`",
266                                         reg.name(),
267                                         reg2.name()
268                                     );
269                                     let mut err = sess.struct_span_err(op_sp, &msg);
270                                     err.span_label(op_sp, &format!("register `{}`", reg.name()));
271                                     err.span_label(op_sp2, &format!("register `{}`", reg2.name()));
272
273                                     match (op, op2) {
274                                         (
275                                             hir::InlineAsmOperand::In { .. },
276                                             hir::InlineAsmOperand::Out { late, .. },
277                                         )
278                                         | (
279                                             hir::InlineAsmOperand::Out { late, .. },
280                                             hir::InlineAsmOperand::In { .. },
281                                         ) => {
282                                             assert!(!*late);
283                                             let out_op_sp = if input { op_sp2 } else { op_sp };
284                                             let msg = "use `lateout` instead of \
285                                                        `out` to avoid conflict";
286                                             err.span_help(out_op_sp, msg);
287                                         }
288                                         _ => {}
289                                     }
290
291                                     err.emit();
292                                 }
293                                 Entry::Vacant(v) => {
294                                     v.insert(idx);
295                                 }
296                             }
297                         };
298                         if input {
299                             check(&mut used_input_regs, true);
300                         }
301                         if output {
302                             check(&mut used_output_regs, false);
303                         }
304                     });
305                 }
306             }
307         }
308
309         // If a clobber_abi is specified, add the necessary clobbers to the
310         // operands list.
311         if let Some((abi, abi_span)) = clobber_abi {
312             for &clobber in abi.clobbered_regs() {
313                 let mut output_used = false;
314                 clobber.overlapping_regs(|reg| {
315                     if used_output_regs.contains_key(&reg) {
316                         output_used = true;
317                     }
318                 });
319
320                 if !output_used {
321                     operands.push((
322                         hir::InlineAsmOperand::Out {
323                             reg: asm::InlineAsmRegOrRegClass::Reg(clobber),
324                             late: true,
325                             expr: None,
326                         },
327                         self.lower_span(abi_span),
328                     ));
329                 }
330             }
331         }
332
333         let operands = self.arena.alloc_from_iter(operands);
334         let template = self.arena.alloc_from_iter(asm.template.iter().cloned());
335         let template_strs = self.arena.alloc_from_iter(
336             asm.template_strs
337                 .iter()
338                 .map(|(sym, snippet, span)| (*sym, *snippet, self.lower_span(*span))),
339         );
340         let line_spans =
341             self.arena.alloc_from_iter(asm.line_spans.iter().map(|span| self.lower_span(*span)));
342         let hir_asm =
343             hir::InlineAsm { template, template_strs, operands, options: asm.options, line_spans };
344         self.arena.alloc(hir_asm)
345     }
346 }