1 //! Codegen of [`asm!`] invocations.
7 use rustc_ast::ast::{InlineAsmOptions, InlineAsmTemplatePiece};
8 use rustc_middle::mir::InlineAsmOperand;
9 use rustc_span::Symbol;
10 use rustc_target::asm::*;
12 pub(crate) fn codegen_inline_asm<'tcx>(
13 fx: &mut FunctionCx<'_, '_, 'tcx>,
15 template: &[InlineAsmTemplatePiece],
16 operands: &[InlineAsmOperand<'tcx>],
17 options: InlineAsmOptions,
19 // FIXME add .eh_frame unwind info directives
21 if template.is_empty() {
24 } else if template[0] == InlineAsmTemplatePiece::String("int $$0x29".to_string()) {
25 let true_ = fx.bcx.ins().iconst(types::I32, 1);
26 fx.bcx.ins().trapnz(true_, TrapCode::User(1));
28 } else if template[0] == InlineAsmTemplatePiece::String("movq %rbx, ".to_string())
31 InlineAsmTemplatePiece::Placeholder { operand_idx: 0, modifier: Some('r'), span: _ }
33 && template[2] == InlineAsmTemplatePiece::String("\n".to_string())
34 && template[3] == InlineAsmTemplatePiece::String("cpuid".to_string())
35 && template[4] == InlineAsmTemplatePiece::String("\n".to_string())
36 && template[5] == InlineAsmTemplatePiece::String("xchgq %rbx, ".to_string())
39 InlineAsmTemplatePiece::Placeholder { operand_idx: 0, modifier: Some('r'), span: _ }
42 assert_eq!(operands.len(), 4);
43 let (leaf, eax_place) = match operands[1] {
44 InlineAsmOperand::InOut { reg, late: true, ref in_value, out_place } => {
47 InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::ax))
50 crate::base::codegen_operand(fx, in_value).load_scalar(fx),
51 crate::base::codegen_place(fx, out_place.unwrap()),
56 let ebx_place = match operands[0] {
57 InlineAsmOperand::Out { reg, late: true, place } => {
60 InlineAsmRegOrRegClass::RegClass(InlineAsmRegClass::X86(
61 X86InlineAsmRegClass::reg
64 crate::base::codegen_place(fx, place.unwrap())
68 let (sub_leaf, ecx_place) = match operands[2] {
69 InlineAsmOperand::InOut { reg, late: true, ref in_value, out_place } => {
72 InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::cx))
75 crate::base::codegen_operand(fx, in_value).load_scalar(fx),
76 crate::base::codegen_place(fx, out_place.unwrap()),
81 let edx_place = match operands[3] {
82 InlineAsmOperand::Out { reg, late: true, place } => {
85 InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::dx))
87 crate::base::codegen_place(fx, place.unwrap())
92 let (eax, ebx, ecx, edx) = crate::intrinsics::codegen_cpuid_call(fx, leaf, sub_leaf);
94 eax_place.write_cvalue(fx, CValue::by_val(eax, fx.layout_of(fx.tcx.types.u32)));
95 ebx_place.write_cvalue(fx, CValue::by_val(ebx, fx.layout_of(fx.tcx.types.u32)));
96 ecx_place.write_cvalue(fx, CValue::by_val(ecx, fx.layout_of(fx.tcx.types.u32)));
97 edx_place.write_cvalue(fx, CValue::by_val(edx, fx.layout_of(fx.tcx.types.u32)));
99 } else if fx.tcx.symbol_name(fx.instance).name.starts_with("___chkstk") {
100 // ___chkstk, ___chkstk_ms and __alloca are only used on Windows
101 crate::trap::trap_unimplemented(fx, "Stack probes are not supported");
102 } else if fx.tcx.symbol_name(fx.instance).name == "__alloca" {
103 crate::trap::trap_unimplemented(fx, "Alloca is not supported");
106 let mut inputs = Vec::new();
107 let mut outputs = Vec::new();
109 let mut asm_gen = InlineAssemblyGenerator {
111 arch: InlineAsmArch::X86_64,
115 registers: Vec::new(),
116 stack_slots_clobber: Vec::new(),
117 stack_slots_input: Vec::new(),
118 stack_slots_output: Vec::new(),
119 stack_slot_size: Size::from_bytes(0),
121 asm_gen.allocate_registers();
122 asm_gen.allocate_stack_slots();
124 let inline_asm_index = fx.inline_asm_index;
125 fx.inline_asm_index += 1;
126 let asm_name = format!("{}__inline_asm_{}", fx.symbol_name, inline_asm_index);
128 let generated_asm = asm_gen.generate_asm_wrapper(&asm_name);
129 fx.cx.global_asm.push_str(&generated_asm);
131 for (i, operand) in operands.iter().enumerate() {
133 InlineAsmOperand::In { reg: _, ref value } => {
135 asm_gen.stack_slots_input[i].unwrap(),
136 crate::base::codegen_operand(fx, value).load_scalar(fx),
139 InlineAsmOperand::Out { reg: _, late: _, place } => {
140 if let Some(place) = place {
142 asm_gen.stack_slots_output[i].unwrap(),
143 crate::base::codegen_place(fx, place),
147 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
149 asm_gen.stack_slots_input[i].unwrap(),
150 crate::base::codegen_operand(fx, in_value).load_scalar(fx),
152 if let Some(out_place) = out_place {
154 asm_gen.stack_slots_output[i].unwrap(),
155 crate::base::codegen_place(fx, out_place),
159 InlineAsmOperand::Const { value: _ } => todo!(),
160 InlineAsmOperand::SymFn { value: _ } => todo!(),
161 InlineAsmOperand::SymStatic { def_id: _ } => todo!(),
165 call_inline_asm(fx, &asm_name, asm_gen.stack_slot_size, inputs, outputs);
168 struct InlineAssemblyGenerator<'a, 'tcx> {
171 template: &'a [InlineAsmTemplatePiece],
172 operands: &'a [InlineAsmOperand<'tcx>],
173 options: InlineAsmOptions,
174 registers: Vec<Option<InlineAsmReg>>,
175 stack_slots_clobber: Vec<Option<Size>>,
176 stack_slots_input: Vec<Option<Size>>,
177 stack_slots_output: Vec<Option<Size>>,
178 stack_slot_size: Size,
181 impl<'tcx> InlineAssemblyGenerator<'_, 'tcx> {
182 fn allocate_registers(&mut self) {
183 let sess = self.tcx.sess;
184 let map = allocatable_registers(
186 |feature| sess.target_features.contains(&Symbol::intern(feature)),
189 let mut allocated = FxHashMap::<_, (bool, bool)>::default();
190 let mut regs = vec![None; self.operands.len()];
192 // Add explicit registers to the allocated set.
193 for (i, operand) in self.operands.iter().enumerate() {
195 InlineAsmOperand::In { reg: InlineAsmRegOrRegClass::Reg(reg), .. } => {
197 allocated.entry(reg).or_default().0 = true;
199 InlineAsmOperand::Out {
200 reg: InlineAsmRegOrRegClass::Reg(reg), late: true, ..
203 allocated.entry(reg).or_default().1 = true;
205 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(reg), .. }
206 | InlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(reg), .. } => {
208 allocated.insert(reg, (true, true));
214 // Allocate out/inout/inlateout registers first because they are more constrained.
215 for (i, operand) in self.operands.iter().enumerate() {
217 InlineAsmOperand::Out {
218 reg: InlineAsmRegOrRegClass::RegClass(class),
222 | InlineAsmOperand::InOut {
223 reg: InlineAsmRegOrRegClass::RegClass(class), ..
225 let mut alloc_reg = None;
226 for ® in &map[&class] {
227 let mut used = false;
228 reg.overlapping_regs(|r| {
229 if allocated.contains_key(&r) {
235 alloc_reg = Some(reg);
240 let reg = alloc_reg.expect("cannot allocate registers");
242 allocated.insert(reg, (true, true));
248 // Allocate in/lateout.
249 for (i, operand) in self.operands.iter().enumerate() {
251 InlineAsmOperand::In { reg: InlineAsmRegOrRegClass::RegClass(class), .. } => {
252 let mut alloc_reg = None;
253 for ® in &map[&class] {
254 let mut used = false;
255 reg.overlapping_regs(|r| {
256 if allocated.get(&r).copied().unwrap_or_default().0 {
262 alloc_reg = Some(reg);
267 let reg = alloc_reg.expect("cannot allocate registers");
269 allocated.entry(reg).or_default().0 = true;
271 InlineAsmOperand::Out {
272 reg: InlineAsmRegOrRegClass::RegClass(class),
276 let mut alloc_reg = None;
277 for ® in &map[&class] {
278 let mut used = false;
279 reg.overlapping_regs(|r| {
280 if allocated.get(&r).copied().unwrap_or_default().1 {
286 alloc_reg = Some(reg);
291 let reg = alloc_reg.expect("cannot allocate registers");
293 allocated.entry(reg).or_default().1 = true;
299 self.registers = regs;
302 fn allocate_stack_slots(&mut self) {
303 let mut slot_size = Size::from_bytes(0);
304 let mut slots_clobber = vec![None; self.operands.len()];
305 let mut slots_input = vec![None; self.operands.len()];
306 let mut slots_output = vec![None; self.operands.len()];
308 let new_slot_fn = |slot_size: &mut Size, reg_class: InlineAsmRegClass| {
309 let reg_size = reg_class
310 .supported_types(InlineAsmArch::X86_64)
312 .map(|(ty, _)| ty.size())
315 let align = rustc_target::abi::Align::from_bytes(reg_size.bytes()).unwrap();
316 let offset = slot_size.align_to(align);
317 *slot_size = offset + reg_size;
320 let mut new_slot = |x| new_slot_fn(&mut slot_size, x);
322 // Allocate stack slots for saving clobbered registers
324 InlineAsmClobberAbi::parse(self.arch, &self.tcx.sess.target, Symbol::intern("C"))
327 for (i, reg) in self.registers.iter().enumerate().filter_map(|(i, r)| r.map(|r| (i, r))) {
328 let mut need_save = true;
329 // If the register overlaps with a register clobbered by function call, then
330 // we don't need to save it.
331 for r in abi_clobber {
332 r.overlapping_regs(|r| {
344 slots_clobber[i] = Some(new_slot(reg.reg_class()));
348 // Allocate stack slots for inout
349 for (i, operand) in self.operands.iter().enumerate() {
351 InlineAsmOperand::InOut { reg, out_place: Some(_), .. } => {
352 let slot = new_slot(reg.reg_class());
353 slots_input[i] = Some(slot);
354 slots_output[i] = Some(slot);
360 let slot_size_before_input = slot_size;
361 let mut new_slot = |x| new_slot_fn(&mut slot_size, x);
363 // Allocate stack slots for input
364 for (i, operand) in self.operands.iter().enumerate() {
366 InlineAsmOperand::In { reg, .. }
367 | InlineAsmOperand::InOut { reg, out_place: None, .. } => {
368 slots_input[i] = Some(new_slot(reg.reg_class()));
374 // Reset slot size to before input so that input and output operands can overlap
375 // and save some memory.
376 let slot_size_after_input = slot_size;
377 slot_size = slot_size_before_input;
378 let mut new_slot = |x| new_slot_fn(&mut slot_size, x);
380 // Allocate stack slots for output
381 for (i, operand) in self.operands.iter().enumerate() {
383 InlineAsmOperand::Out { reg, place: Some(_), .. } => {
384 slots_output[i] = Some(new_slot(reg.reg_class()));
390 slot_size = slot_size.max(slot_size_after_input);
392 self.stack_slots_clobber = slots_clobber;
393 self.stack_slots_input = slots_input;
394 self.stack_slots_output = slots_output;
395 self.stack_slot_size = slot_size;
398 fn generate_asm_wrapper(&self, asm_name: &str) -> String {
399 let mut generated_asm = String::new();
400 writeln!(generated_asm, ".globl {}", asm_name).unwrap();
401 writeln!(generated_asm, ".type {},@function", asm_name).unwrap();
402 writeln!(generated_asm, ".section .text.{},\"ax\",@progbits", asm_name).unwrap();
403 writeln!(generated_asm, "{}:", asm_name).unwrap();
405 generated_asm.push_str(".intel_syntax noprefix\n");
406 generated_asm.push_str(" push rbp\n");
407 generated_asm.push_str(" mov rbp,rdi\n");
409 // Save clobbered registers
410 if !self.options.contains(InlineAsmOptions::NORETURN) {
411 for (reg, slot) in self
414 .zip(self.stack_slots_clobber.iter().copied())
415 .filter_map(|(r, s)| r.zip(s))
417 save_register(&mut generated_asm, self.arch, reg, slot);
421 // Write input registers
422 for (reg, slot) in self
425 .zip(self.stack_slots_input.iter().copied())
426 .filter_map(|(r, s)| r.zip(s))
428 restore_register(&mut generated_asm, self.arch, reg, slot);
431 if self.options.contains(InlineAsmOptions::ATT_SYNTAX) {
432 generated_asm.push_str(".att_syntax\n");
435 // The actual inline asm
436 for piece in self.template {
438 InlineAsmTemplatePiece::String(s) => {
439 generated_asm.push_str(s);
441 InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => {
442 self.registers[*operand_idx]
444 .emit(&mut generated_asm, self.arch, *modifier)
449 generated_asm.push('\n');
451 if is_x86 && self.options.contains(InlineAsmOptions::ATT_SYNTAX) {
452 generated_asm.push_str(".intel_syntax noprefix\n");
455 if !self.options.contains(InlineAsmOptions::NORETURN) {
456 // Read output registers
457 for (reg, slot) in self
460 .zip(self.stack_slots_output.iter().copied())
461 .filter_map(|(r, s)| r.zip(s))
463 save_register(&mut generated_asm, self.arch, reg, slot);
466 // Restore clobbered registers
467 for (reg, slot) in self
470 .zip(self.stack_slots_clobber.iter().copied())
471 .filter_map(|(r, s)| r.zip(s))
473 restore_register(&mut generated_asm, self.arch, reg, slot);
476 generated_asm.push_str(" pop rbp\n");
477 generated_asm.push_str(" ret\n");
479 generated_asm.push_str(" ud2\n");
482 generated_asm.push_str(".att_syntax\n");
483 writeln!(generated_asm, ".size {name}, .-{name}", name = asm_name).unwrap();
484 generated_asm.push_str(".text\n");
485 generated_asm.push_str("\n\n");
491 fn call_inline_asm<'tcx>(
492 fx: &mut FunctionCx<'_, '_, 'tcx>,
495 inputs: Vec<(Size, Value)>,
496 outputs: Vec<(Size, CPlace<'tcx>)>,
498 let stack_slot = fx.bcx.func.create_stack_slot(StackSlotData {
499 kind: StackSlotKind::ExplicitSlot,
500 size: u32::try_from(slot_size.bytes()).unwrap(),
502 if fx.clif_comments.enabled() {
503 fx.add_comment(stack_slot, "inline asm scratch slot");
506 let inline_asm_func = fx
512 call_conv: CallConv::SystemV,
513 params: vec![AbiParam::new(fx.pointer_type)],
518 let inline_asm_func = fx.module.declare_func_in_func(inline_asm_func, &mut fx.bcx.func);
519 if fx.clif_comments.enabled() {
520 fx.add_comment(inline_asm_func, asm_name);
523 for (offset, value) in inputs {
524 fx.bcx.ins().stack_store(value, stack_slot, i32::try_from(offset.bytes()).unwrap());
527 let stack_slot_addr = fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0);
528 fx.bcx.ins().call(inline_asm_func, &[stack_slot_addr]);
530 for (offset, place) in outputs {
531 let ty = fx.clif_type(place.layout().ty).unwrap();
532 let value = fx.bcx.ins().stack_load(ty, stack_slot, i32::try_from(offset.bytes()).unwrap());
533 place.write_cvalue(fx, CValue::by_val(value, place.layout()));
537 fn save_register(generated_asm: &mut String, arch: InlineAsmArch, reg: InlineAsmReg, offset: Size) {
539 InlineAsmArch::X86_64 => {
540 write!(generated_asm, " mov [rbp+0x{:x}], ", offset.bytes()).unwrap();
541 reg.emit(generated_asm, InlineAsmArch::X86_64, None).unwrap();
542 generated_asm.push('\n');
544 _ => unimplemented!("save_register for {:?}", arch),
549 generated_asm: &mut String,
555 InlineAsmArch::X86_64 => {
556 generated_asm.push_str(" mov ");
557 reg.emit(generated_asm, InlineAsmArch::X86_64, None).unwrap();
558 writeln!(generated_asm, ", [rbp+0x{:x}]", offset.bytes()).unwrap();
560 _ => unimplemented!("restore_register for {:?}", arch),