Skip to main content

rustc_ast_lowering/
asm.rs

1use std::collections::hash_map::Entry;
2
3use rustc_ast::*;
4use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
5use rustc_errors::msg;
6use rustc_hir as hir;
7use rustc_hir::def::{DefKind, Res};
8use rustc_session::diagnostics::feature_err;
9use rustc_span::{Span, sym};
10use rustc_target::asm;
11
12use crate::diagnostics::{
13    AbiSpecifiedMultipleTimes, AttSyntaxOnlyX86, ClobberAbiNotSupported,
14    InlineAsmUnsupportedTarget, InvalidAbiClobberAbi, InvalidAsmTemplateModifierConst,
15    InvalidAsmTemplateModifierLabel, InvalidAsmTemplateModifierRegClass,
16    InvalidAsmTemplateModifierRegClassSub, InvalidAsmTemplateModifierSym, InvalidRegister,
17    InvalidRegisterClass, RegisterClassOnlyClobber, RegisterClassOnlyClobberStable,
18    RegisterConflict,
19};
20use crate::{
21    AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
22};
23
24impl<'hir> LoweringContext<'_, 'hir> {
25    pub(crate) fn lower_inline_asm(
26        &mut self,
27        sp: Span,
28        asm: &InlineAsm,
29    ) -> &'hir hir::InlineAsm<'hir> {
30        // Rustdoc needs to support asm! from foreign architectures: don't try
31        // lowering the register constraints in this case.
32        let asm_arch =
33            if self.tcx.sess.opts.actually_rustdoc { None } else { self.tcx.sess.asm_arch };
34        if asm_arch.is_none() && !self.tcx.sess.opts.actually_rustdoc {
35            self.dcx().emit_err(InlineAsmUnsupportedTarget { span: sp });
36        }
37        if let Some(asm_arch) = asm_arch {
38            // Inline assembly is currently only stable for these architectures.
39            // (See also compiletest's `has_asm_support`.)
40            let is_stable = #[allow(non_exhaustive_omitted_patterns)] match asm_arch {
    asm::InlineAsmArch::X86 | asm::InlineAsmArch::X86_64 |
        asm::InlineAsmArch::Arm | asm::InlineAsmArch::AArch64 |
        asm::InlineAsmArch::Arm64EC | asm::InlineAsmArch::RiscV32 |
        asm::InlineAsmArch::RiscV64 | asm::InlineAsmArch::LoongArch32 |
        asm::InlineAsmArch::LoongArch64 | asm::InlineAsmArch::S390x |
        asm::InlineAsmArch::PowerPC | asm::InlineAsmArch::PowerPC64 => true,
    _ => false,
}matches!(
41                asm_arch,
42                asm::InlineAsmArch::X86
43                    | asm::InlineAsmArch::X86_64
44                    | asm::InlineAsmArch::Arm
45                    | asm::InlineAsmArch::AArch64
46                    | asm::InlineAsmArch::Arm64EC
47                    | asm::InlineAsmArch::RiscV32
48                    | asm::InlineAsmArch::RiscV64
49                    | asm::InlineAsmArch::LoongArch32
50                    | asm::InlineAsmArch::LoongArch64
51                    | asm::InlineAsmArch::S390x
52                    | asm::InlineAsmArch::PowerPC
53                    | asm::InlineAsmArch::PowerPC64
54            );
55            if !is_stable
56                && !self.tcx.features().asm_experimental_arch()
57                && sp
58                    .ctxt()
59                    .outer_expn_data()
60                    .allow_internal_unstable
61                    .filter(|features| features.contains(&sym::asm_experimental_arch))
62                    .is_none()
63            {
64                feature_err(
65                    &self.tcx.sess,
66                    sym::asm_experimental_arch,
67                    sp,
68                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("inline assembly is not stable yet on this architecture"))msg!("inline assembly is not stable yet on this architecture"),
69                )
70                .emit();
71            }
72        }
73        let allow_experimental_reg = self.tcx.features().asm_experimental_reg();
74        if asm.options.contains(InlineAsmOptions::ATT_SYNTAX)
75            && !#[allow(non_exhaustive_omitted_patterns)] match asm_arch {
    Some(asm::InlineAsmArch::X86 | asm::InlineAsmArch::X86_64) => true,
    _ => false,
}matches!(asm_arch, Some(asm::InlineAsmArch::X86 | asm::InlineAsmArch::X86_64))
76            && !self.tcx.sess.opts.actually_rustdoc
77        {
78            self.dcx().emit_err(AttSyntaxOnlyX86 { span: sp });
79        }
80        if asm.options.contains(InlineAsmOptions::MAY_UNWIND) && !self.tcx.features().asm_unwind() {
81            feature_err(
82                &self.tcx.sess,
83                sym::asm_unwind,
84                sp,
85                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the `may_unwind` option is unstable"))msg!("the `may_unwind` option is unstable"),
86            )
87            .emit();
88        }
89
90        let mut clobber_abis = FxIndexMap::default();
91        if let Some(asm_arch) = asm_arch {
92            for (abi_name, abi_span) in &asm.clobber_abis {
93                match asm::InlineAsmClobberAbi::parse(
94                    asm_arch,
95                    &self.tcx.sess.target,
96                    &self.tcx.sess.internal_target_features,
97                    *abi_name,
98                ) {
99                    Ok(abi) => {
100                        // If the abi was already in the list, emit an error
101                        match clobber_abis.get(&abi) {
102                            Some((prev_name, prev_sp)) => {
103                                // Multiple different abi names may actually be the same ABI
104                                // If the specified ABIs are not the same name, alert the user that they resolve to the same ABI
105                                let source_map = self.tcx.sess.source_map();
106                                let equivalent = source_map.span_to_snippet(*prev_sp)
107                                    != source_map.span_to_snippet(*abi_span);
108
109                                self.dcx().emit_err(AbiSpecifiedMultipleTimes {
110                                    abi_span: *abi_span,
111                                    prev_name: *prev_name,
112                                    prev_span: *prev_sp,
113                                    equivalent,
114                                });
115                            }
116                            None => {
117                                clobber_abis.insert(abi, (*abi_name, *abi_span));
118                            }
119                        }
120                    }
121                    Err(&[]) => {
122                        self.dcx().emit_err(ClobberAbiNotSupported { abi_span: *abi_span });
123                    }
124                    Err(supported_abis) => {
125                        self.dcx().emit_err(InvalidAbiClobberAbi {
126                            abi_span: *abi_span,
127                            supported_abis: supported_abis.to_vec().into(),
128                        });
129                    }
130                }
131            }
132        }
133
134        // Lower operands to HIR. We use dummy register classes if an error
135        // occurs during lowering because we still need to be able to produce a
136        // valid HIR.
137        let sess = self.tcx.sess;
138        let mut operands: Vec<_> = asm
139            .operands
140            .iter()
141            .map(|(op, op_sp)| {
142                let lower_reg = |&reg: &_| match reg {
143                    InlineAsmRegOrRegClass::Reg(reg) => hir::InlineAsmRegOrRegClass::Reg {
144                        reg: if let Some(asm_arch) = asm_arch {
145                            asm::InlineAsmReg::parse(asm_arch, reg).unwrap_or_else(|error| {
146                                self.dcx().emit_err(InvalidRegister {
147                                    op_span: *op_sp,
148                                    reg,
149                                    error,
150                                });
151                                asm::InlineAsmReg::Err
152                            })
153                        } else {
154                            asm::InlineAsmReg::Err
155                        },
156                        source_name: Some(reg),
157                    },
158                    InlineAsmRegOrRegClass::RegClass(reg_class) => {
159                        hir::InlineAsmRegOrRegClass::RegClass(if let Some(asm_arch) = asm_arch {
160                            asm::InlineAsmRegClass::parse(asm_arch, reg_class).unwrap_or_else(
161                                |supported_register_classes| {
162                                    self.dcx().emit_err(InvalidRegisterClass {
163                                        op_span: *op_sp,
164                                        reg_class,
165                                        supported_register_classes: supported_register_classes
166                                            .to_vec()
167                                            .into(),
168                                    });
169                                    asm::InlineAsmRegClass::Err
170                                },
171                            )
172                        } else {
173                            asm::InlineAsmRegClass::Err
174                        })
175                    }
176                };
177
178                let op = match op {
179                    InlineAsmOperand::In { reg, expr } => hir::InlineAsmOperand::In {
180                        reg: lower_reg(reg),
181                        expr: self.lower_expr(expr),
182                    },
183                    InlineAsmOperand::Out { reg, late, expr } => hir::InlineAsmOperand::Out {
184                        reg: lower_reg(reg),
185                        late: *late,
186                        expr: expr.as_ref().map(|expr| self.lower_expr(expr)),
187                    },
188                    InlineAsmOperand::InOut { reg, late, expr } => hir::InlineAsmOperand::InOut {
189                        reg: lower_reg(reg),
190                        late: *late,
191                        expr: self.lower_expr(expr),
192                    },
193                    InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
194                        hir::InlineAsmOperand::SplitInOut {
195                            reg: lower_reg(reg),
196                            late: *late,
197                            in_expr: self.lower_expr(in_expr),
198                            out_expr: out_expr.as_ref().map(|expr| self.lower_expr(expr)),
199                        }
200                    }
201                    InlineAsmOperand::Const { anon_const } => hir::InlineAsmOperand::Const {
202                        anon_const: self.lower_const_block(anon_const),
203                    },
204                    InlineAsmOperand::Sym { sym } => {
205                        let static_def_id = self
206                            .get_partial_res(sym.id)
207                            .and_then(|res| res.full_res())
208                            .and_then(|res| match res {
209                                Res::Def(DefKind::Static { .. }, def_id) => Some(def_id),
210                                _ => None,
211                            });
212
213                        if let Some(def_id) = static_def_id {
214                            let path = self.lower_qpath(
215                                sym.id,
216                                &sym.qself,
217                                &sym.path,
218                                ParamMode::Optional,
219                                AllowReturnTypeNotation::No,
220                                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
221                                None,
222                            );
223                            hir::InlineAsmOperand::SymStatic { path, def_id }
224                        } else {
225                            // Replace the InlineAsmSym AST node with an
226                            // Expr using the name node id.
227                            let expr = Expr {
228                                id: sym.id,
229                                kind: ExprKind::Path(sym.qself.clone(), sym.path.clone()),
230                                span: *op_sp,
231                                attrs: AttrVec::new(),
232                                tokens: None,
233                            };
234
235                            hir::InlineAsmOperand::SymFn { expr: self.lower_expr(&expr) }
236                        }
237                    }
238                    InlineAsmOperand::Label { block } => {
239                        hir::InlineAsmOperand::Label { block: self.lower_block(block, false) }
240                    }
241                };
242                (op, self.lower_span(*op_sp))
243            })
244            .collect();
245
246        // Validate template modifiers against the register classes for the operands
247        for p in &asm.template {
248            if let InlineAsmTemplatePiece::Placeholder {
249                operand_idx,
250                modifier: Some(modifier),
251                span: placeholder_span,
252            } = *p
253            {
254                let op_sp = asm.operands[operand_idx].1;
255                match &operands[operand_idx].0 {
256                    hir::InlineAsmOperand::In { reg, .. }
257                    | hir::InlineAsmOperand::Out { reg, .. }
258                    | hir::InlineAsmOperand::InOut { reg, .. }
259                    | hir::InlineAsmOperand::SplitInOut { reg, .. } => {
260                        let class = reg.reg_class();
261                        if class == asm::InlineAsmRegClass::Err {
262                            continue;
263                        }
264                        let valid_modifiers =
265                            class.valid_modifiers(asm_arch.unwrap(), allow_experimental_reg);
266                        if !valid_modifiers.contains(&modifier) {
267                            // First check if the requested modifier is missing from the valid
268                            // values because experimental registers are disabled.
269                            let unstable_modifiers = class.valid_modifiers(asm_arch.unwrap(), true);
270                            if !allow_experimental_reg && unstable_modifiers.contains(&modifier) {
271                                self.tcx.sess.create_feature_err(
272                                    InvalidAsmTemplateModifierRegClass {
273                                        placeholder_span,
274                                        op_span: op_sp,
275                                        modifier: modifier.to_string(),
276                                        sub: InvalidAsmTemplateModifierRegClassSub::ModifierIsGated {
277                                            class_name: class.name(),
278                                            feature: sym::asm_experimental_reg,
279                                            stable_modifiers: valid_modifiers.to_vec().into(),
280                                            all_modifiers: unstable_modifiers.to_vec().into(),
281                                        },
282                                    },
283                                    sym::asm_experimental_reg,
284                                ).emit();
285                            } else {
286                                let sub = if valid_modifiers.is_empty() {
287                                    InvalidAsmTemplateModifierRegClassSub::DoesNotSupportModifier {
288                                        class_name: class.name(),
289                                    }
290                                } else {
291                                    InvalidAsmTemplateModifierRegClassSub::SupportModifier {
292                                        class_name: class.name(),
293                                        modifiers: valid_modifiers.to_vec().into(),
294                                    }
295                                };
296                                self.dcx().emit_err(InvalidAsmTemplateModifierRegClass {
297                                    placeholder_span,
298                                    op_span: op_sp,
299                                    modifier: modifier.to_string(),
300                                    sub,
301                                });
302                            }
303                        }
304                    }
305                    hir::InlineAsmOperand::Const { .. } => {
306                        self.dcx().emit_err(InvalidAsmTemplateModifierConst {
307                            placeholder_span,
308                            op_span: op_sp,
309                        });
310                    }
311                    hir::InlineAsmOperand::SymFn { .. }
312                    | hir::InlineAsmOperand::SymStatic { .. } => {
313                        self.dcx().emit_err(InvalidAsmTemplateModifierSym {
314                            placeholder_span,
315                            op_span: op_sp,
316                        });
317                    }
318                    hir::InlineAsmOperand::Label { .. } => {
319                        self.dcx().emit_err(InvalidAsmTemplateModifierLabel {
320                            placeholder_span,
321                            op_span: op_sp,
322                        });
323                    }
324                }
325            }
326        }
327
328        let mut used_input_regs = FxHashMap::default();
329        let mut used_output_regs = FxHashMap::default();
330
331        for (idx, &(ref op, op_sp)) in operands.iter().enumerate() {
332            if let Some(reg) = op.reg() {
333                let reg_class = reg.reg_class();
334                if reg_class == asm::InlineAsmRegClass::Err {
335                    continue;
336                }
337
338                // Some register classes can only be used as clobbers. This
339                // means that we disallow passing a value in/out of the asm and
340                // require that the operand name an explicit register, not a
341                // register class.
342                if reg_class.is_clobber_only(asm_arch.unwrap(), allow_experimental_reg)
343                    && !op.is_clobber()
344                {
345                    if allow_experimental_reg || reg_class.is_clobber_only(asm_arch.unwrap(), true)
346                    {
347                        // always clobber-only
348                        self.dcx().emit_err(RegisterClassOnlyClobber {
349                            op_span: op_sp,
350                            reg_class_name: reg_class.name(),
351                        });
352                    } else {
353                        // clobber-only in stable
354                        self.tcx
355                            .sess
356                            .create_feature_err(
357                                RegisterClassOnlyClobberStable {
358                                    op_span: op_sp,
359                                    reg_class_name: reg_class.name(),
360                                },
361                                sym::asm_experimental_reg,
362                            )
363                            .emit();
364                    }
365                    continue;
366                }
367
368                // Check for conflicts between explicit register operands.
369                if let hir::InlineAsmRegOrRegClass::Reg { reg, .. } = reg {
370                    let (input, output) = match op {
371                        hir::InlineAsmOperand::In { .. } => (true, false),
372
373                        // Late output do not conflict with inputs, but normal outputs do
374                        hir::InlineAsmOperand::Out { late, .. } => (!late, true),
375
376                        hir::InlineAsmOperand::InOut { .. }
377                        | hir::InlineAsmOperand::SplitInOut { .. } => (true, true),
378
379                        hir::InlineAsmOperand::Const { .. }
380                        | hir::InlineAsmOperand::SymFn { .. }
381                        | hir::InlineAsmOperand::SymStatic { .. }
382                        | hir::InlineAsmOperand::Label { .. } => {
383                            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("{0:?} is not a register operand", op)));
};unreachable!("{op:?} is not a register operand");
384                        }
385                    };
386
387                    // Flag to output the error only once per operand
388                    let mut skip = false;
389
390                    let mut check = |used_regs: &mut FxHashMap<asm::InlineAsmReg, usize>,
391                                     input,
392                                     r: asm::InlineAsmReg| {
393                        match used_regs.entry(r) {
394                            Entry::Occupied(o) => {
395                                if skip {
396                                    return;
397                                }
398                                skip = true;
399
400                                let idx2 = *o.get();
401                                let (ref op2, op_sp2) = operands[idx2];
402
403                                let in_out = match (op, op2) {
404                                    (
405                                        hir::InlineAsmOperand::In { .. },
406                                        hir::InlineAsmOperand::Out { late, .. },
407                                    )
408                                    | (
409                                        hir::InlineAsmOperand::Out { late, .. },
410                                        hir::InlineAsmOperand::In { .. },
411                                    ) => {
412                                        if !!*late { ::core::panicking::panic("assertion failed: !*late") };assert!(!*late);
413                                        let out_op_sp = if input { op_sp2 } else { op_sp };
414                                        Some(out_op_sp)
415                                    }
416                                    _ => None,
417                                };
418                                let reg1_name = op
419                                    .reg()
420                                    .and_then(|reg| reg.source_name())
421                                    .expect("{op:?} has no source register name");
422
423                                let reg2_name = op2
424                                    .reg()
425                                    .and_then(|reg| reg.source_name())
426                                    .expect("{op2:?} has no source register name");
427
428                                self.dcx().emit_err(RegisterConflict {
429                                    op_span1: op_sp,
430                                    op_span2: op_sp2,
431                                    reg1_name: reg1_name.as_str(),
432                                    reg2_name: reg2_name.as_str(),
433                                    in_out,
434                                });
435                            }
436                            Entry::Vacant(v) => {
437                                if r == reg {
438                                    v.insert(idx);
439                                }
440                            }
441                        }
442                    };
443                    let mut overlapping_with = ::alloc::vec::Vec::new()vec![];
444                    reg.overlapping_regs(|r| {
445                        overlapping_with.push(r);
446                    });
447                    for r in overlapping_with {
448                        if input {
449                            check(&mut used_input_regs, true, r);
450                        }
451                        if output {
452                            check(&mut used_output_regs, false, r);
453                        }
454                    }
455                }
456            }
457        }
458
459        // If a clobber_abi is specified, add the necessary clobbers to the
460        // operands list.
461        let mut clobbered = FxHashSet::default();
462        for (abi, (_, abi_span)) in clobber_abis {
463            for &clobber in abi.clobbered_regs() {
464                // Don't emit a clobber for a register already clobbered
465                if clobbered.contains(&clobber) {
466                    continue;
467                }
468
469                let mut overlapping_with = ::alloc::vec::Vec::new()vec![];
470                clobber.overlapping_regs(|reg| {
471                    overlapping_with.push(reg);
472                });
473                let output_used =
474                    overlapping_with.iter().any(|reg| used_output_regs.contains_key(&reg));
475
476                if !output_used {
477                    operands.push((
478                        hir::InlineAsmOperand::Out {
479                            reg: hir::InlineAsmRegOrRegClass::Reg {
480                                reg: clobber,
481                                source_name: None,
482                            },
483                            late: true,
484                            expr: None,
485                        },
486                        self.lower_span(abi_span),
487                    ));
488                    clobbered.insert(clobber);
489                }
490            }
491        }
492
493        // Feature gate checking for `asm_goto_with_outputs`.
494        if let Some((_, op_sp)) =
495            operands.iter().find(|(op, _)| #[allow(non_exhaustive_omitted_patterns)] match op {
    hir::InlineAsmOperand::Label { .. } => true,
    _ => false,
}matches!(op, hir::InlineAsmOperand::Label { .. }))
496        {
497            // Check if an output operand is used.
498            let output_operand_used = operands.iter().any(|(op, _)| {
499                #[allow(non_exhaustive_omitted_patterns)] match op {
    hir::InlineAsmOperand::Out { expr: Some(_), .. } |
        hir::InlineAsmOperand::InOut { .. } |
        hir::InlineAsmOperand::SplitInOut { out_expr: Some(_), .. } => true,
    _ => false,
}matches!(
500                    op,
501                    hir::InlineAsmOperand::Out { expr: Some(_), .. }
502                        | hir::InlineAsmOperand::InOut { .. }
503                        | hir::InlineAsmOperand::SplitInOut { out_expr: Some(_), .. }
504                )
505            });
506            if output_operand_used && !self.tcx.features().asm_goto_with_outputs() {
507                feature_err(
508                    sess,
509                    sym::asm_goto_with_outputs,
510                    *op_sp,
511                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("using both label and output operands for inline assembly is unstable"))msg!("using both label and output operands for inline assembly is unstable"),
512                )
513                .emit();
514            }
515        }
516
517        let operands = self.arena.alloc_from_iter(operands);
518        let template = self.arena.alloc_from_iter(asm.template.iter().cloned());
519        let template_strs = self.arena.alloc_from_iter(
520            asm.template_strs
521                .iter()
522                .map(|(sym, snippet, span)| (*sym, *snippet, self.lower_span(*span))),
523        );
524        let line_spans =
525            self.arena.alloc_from_iter(asm.line_spans.iter().map(|span| self.lower_span(*span)));
526        let hir_asm = hir::InlineAsm {
527            asm_macro: asm.asm_macro,
528            template,
529            template_strs,
530            operands,
531            options: asm.options,
532            line_spans,
533        };
534        self.arena.alloc(hir_asm)
535    }
536}