]> git.lizzy.rs Git - rust.git/blob - src/inline_asm.rs
Skip registers saved by calling convention
[rust.git] / src / inline_asm.rs
1 //! Codegen of [`asm!`] invocations.
2
3 use crate::prelude::*;
4
5 use std::fmt::Write;
6
7 use rustc_ast::ast::{InlineAsmOptions, InlineAsmTemplatePiece};
8 use rustc_middle::mir::InlineAsmOperand;
9 use rustc_span::Symbol;
10 use rustc_target::asm::*;
11
12 pub(crate) fn codegen_inline_asm<'tcx>(
13     fx: &mut FunctionCx<'_, '_, 'tcx>,
14     _span: Span,
15     template: &[InlineAsmTemplatePiece],
16     operands: &[InlineAsmOperand<'tcx>],
17     options: InlineAsmOptions,
18 ) {
19     // FIXME add .eh_frame unwind info directives
20
21     if template.is_empty() {
22         // Black box
23         return;
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));
27         return;
28     } else if template[0] == InlineAsmTemplatePiece::String("movq %rbx, ".to_string())
29         && matches!(
30             template[1],
31             InlineAsmTemplatePiece::Placeholder { operand_idx: 0, modifier: Some('r'), span: _ }
32         )
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())
37         && matches!(
38             template[6],
39             InlineAsmTemplatePiece::Placeholder { operand_idx: 0, modifier: Some('r'), span: _ }
40         )
41     {
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 } => {
45                 assert_eq!(
46                     reg,
47                     InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::ax))
48                 );
49                 (
50                     crate::base::codegen_operand(fx, in_value).load_scalar(fx),
51                     crate::base::codegen_place(fx, out_place.unwrap()),
52                 )
53             }
54             _ => unreachable!(),
55         };
56         let ebx_place = match operands[0] {
57             InlineAsmOperand::Out { reg, late: true, place } => {
58                 assert_eq!(
59                     reg,
60                     InlineAsmRegOrRegClass::RegClass(InlineAsmRegClass::X86(
61                         X86InlineAsmRegClass::reg
62                     ))
63                 );
64                 crate::base::codegen_place(fx, place.unwrap())
65             }
66             _ => unreachable!(),
67         };
68         let (sub_leaf, ecx_place) = match operands[2] {
69             InlineAsmOperand::InOut { reg, late: true, ref in_value, out_place } => {
70                 assert_eq!(
71                     reg,
72                     InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::cx))
73                 );
74                 (
75                     crate::base::codegen_operand(fx, in_value).load_scalar(fx),
76                     crate::base::codegen_place(fx, out_place.unwrap()),
77                 )
78             }
79             _ => unreachable!(),
80         };
81         let edx_place = match operands[3] {
82             InlineAsmOperand::Out { reg, late: true, place } => {
83                 assert_eq!(
84                     reg,
85                     InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::dx))
86                 );
87                 crate::base::codegen_place(fx, place.unwrap())
88             }
89             _ => unreachable!(),
90         };
91
92         let (eax, ebx, ecx, edx) = crate::intrinsics::codegen_cpuid_call(fx, leaf, sub_leaf);
93
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)));
98         return;
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");
104     }
105
106     let mut inputs = Vec::new();
107     let mut outputs = Vec::new();
108
109     let mut asm_gen = InlineAssemblyGenerator {
110         tcx: fx.tcx,
111         arch: InlineAsmArch::X86_64,
112         template,
113         operands,
114         options,
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),
120     };
121     asm_gen.allocate_registers();
122     asm_gen.allocate_stack_slots();
123
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);
127
128     let generated_asm = asm_gen.generate_asm_wrapper(&asm_name);
129     fx.cx.global_asm.push_str(&generated_asm);
130
131     // FIXME overlap input and output slots to save stack space
132     for (i, operand) in operands.iter().enumerate() {
133         match *operand {
134             InlineAsmOperand::In { reg: _, ref value } => {
135                 inputs.push((
136                     asm_gen.stack_slots_input[i].unwrap(),
137                     crate::base::codegen_operand(fx, value).load_scalar(fx),
138                 ));
139             }
140             InlineAsmOperand::Out { reg: _, late: _, place } => {
141                 if let Some(place) = place {
142                     outputs.push((
143                         asm_gen.stack_slots_output[i].unwrap(),
144                         crate::base::codegen_place(fx, place),
145                     ));
146                 }
147             }
148             InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
149                 inputs.push((
150                     asm_gen.stack_slots_input[i].unwrap(),
151                     crate::base::codegen_operand(fx, in_value).load_scalar(fx),
152                 ));
153                 if let Some(out_place) = out_place {
154                     outputs.push((
155                         asm_gen.stack_slots_output[i].unwrap(),
156                         crate::base::codegen_place(fx, out_place),
157                     ));
158                 }
159             }
160             InlineAsmOperand::Const { value: _ } => todo!(),
161             InlineAsmOperand::SymFn { value: _ } => todo!(),
162             InlineAsmOperand::SymStatic { def_id: _ } => todo!(),
163         }
164     }
165
166     call_inline_asm(fx, &asm_name, asm_gen.stack_slot_size, inputs, outputs);
167 }
168
169 struct InlineAssemblyGenerator<'a, 'tcx> {
170     tcx: TyCtxt<'tcx>,
171     arch: InlineAsmArch,
172     template: &'a [InlineAsmTemplatePiece],
173     operands: &'a [InlineAsmOperand<'tcx>],
174     options: InlineAsmOptions,
175     registers: Vec<Option<InlineAsmReg>>,
176     stack_slots_clobber: Vec<Option<Size>>,
177     stack_slots_input: Vec<Option<Size>>,
178     stack_slots_output: Vec<Option<Size>>,
179     stack_slot_size: Size,
180 }
181
182 impl<'tcx> InlineAssemblyGenerator<'_, 'tcx> {
183     fn allocate_registers(&mut self) {
184         let sess = self.tcx.sess;
185         let map = allocatable_registers(
186             self.arch,
187             |feature| sess.target_features.contains(&Symbol::intern(feature)),
188             &sess.target,
189         );
190         let mut allocated = FxHashMap::<_, (bool, bool)>::default();
191         let mut regs = vec![None; self.operands.len()];
192
193         // Add explicit registers to the allocated set.
194         for (i, operand) in self.operands.iter().enumerate() {
195             match *operand {
196                 InlineAsmOperand::In { reg: InlineAsmRegOrRegClass::Reg(reg), .. } => {
197                     regs[i] = Some(reg);
198                     allocated.entry(reg).or_default().0 = true;
199                 }
200                 InlineAsmOperand::Out {
201                     reg: InlineAsmRegOrRegClass::Reg(reg), late: true, ..
202                 } => {
203                     regs[i] = Some(reg);
204                     allocated.entry(reg).or_default().1 = true;
205                 }
206                 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(reg), .. }
207                 | InlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(reg), .. } => {
208                     regs[i] = Some(reg);
209                     allocated.insert(reg, (true, true));
210                 }
211                 _ => (),
212             }
213         }
214
215         // Allocate out/inout/inlateout registers first because they are more constrained.
216         for (i, operand) in self.operands.iter().enumerate() {
217             match *operand {
218                 InlineAsmOperand::Out {
219                     reg: InlineAsmRegOrRegClass::RegClass(class),
220                     late: false,
221                     ..
222                 }
223                 | InlineAsmOperand::InOut {
224                     reg: InlineAsmRegOrRegClass::RegClass(class), ..
225                 } => {
226                     let mut alloc_reg = None;
227                     for &reg in &map[&class] {
228                         let mut used = false;
229                         reg.overlapping_regs(|r| {
230                             if allocated.contains_key(&r) {
231                                 used = true;
232                             }
233                         });
234
235                         if !used {
236                             alloc_reg = Some(reg);
237                             break;
238                         }
239                     }
240
241                     let reg = alloc_reg.expect("cannot allocate registers");
242                     regs[i] = Some(reg);
243                     allocated.insert(reg, (true, true));
244                 }
245                 _ => (),
246             }
247         }
248
249         // Allocate in/lateout.
250         for (i, operand) in self.operands.iter().enumerate() {
251             match *operand {
252                 InlineAsmOperand::In { reg: InlineAsmRegOrRegClass::RegClass(class), .. } => {
253                     let mut alloc_reg = None;
254                     for &reg in &map[&class] {
255                         let mut used = false;
256                         reg.overlapping_regs(|r| {
257                             if allocated.get(&r).copied().unwrap_or_default().0 {
258                                 used = true;
259                             }
260                         });
261
262                         if !used {
263                             alloc_reg = Some(reg);
264                             break;
265                         }
266                     }
267
268                     let reg = alloc_reg.expect("cannot allocate registers");
269                     regs[i] = Some(reg);
270                     allocated.entry(reg).or_default().0 = true;
271                 }
272                 InlineAsmOperand::Out {
273                     reg: InlineAsmRegOrRegClass::RegClass(class),
274                     late: true,
275                     ..
276                 } => {
277                     let mut alloc_reg = None;
278                     for &reg in &map[&class] {
279                         let mut used = false;
280                         reg.overlapping_regs(|r| {
281                             if allocated.get(&r).copied().unwrap_or_default().1 {
282                                 used = true;
283                             }
284                         });
285
286                         if !used {
287                             alloc_reg = Some(reg);
288                             break;
289                         }
290                     }
291
292                     let reg = alloc_reg.expect("cannot allocate registers");
293                     regs[i] = Some(reg);
294                     allocated.entry(reg).or_default().1 = true;
295                 }
296                 _ => (),
297             }
298         }
299
300         self.registers = regs;
301     }
302
303     fn allocate_stack_slots(&mut self) {
304         let mut slot_size = Size::from_bytes(0);
305         let mut slots_clobber = vec![None; self.operands.len()];
306         let mut slots_input = vec![None; self.operands.len()];
307         let mut slots_output = vec![None; self.operands.len()];
308
309         let mut new_slot = |reg_class: InlineAsmRegClass| {
310             let reg_size = reg_class
311                 .supported_types(InlineAsmArch::X86_64)
312                 .iter()
313                 .map(|(ty, _)| ty.size())
314                 .max()
315                 .unwrap();
316             let align = rustc_target::abi::Align::from_bytes(reg_size.bytes()).unwrap();
317             slot_size = slot_size.align_to(align);
318             let offset = slot_size;
319             slot_size += reg_size;
320             offset
321         };
322
323         // Allocate stack slots for saving clobbered registers
324         let abi_clobber =
325             InlineAsmClobberAbi::parse(self.arch, &self.tcx.sess.target, Symbol::intern("C"))
326                 .unwrap()
327                 .clobbered_regs();
328         for (i, reg) in self.registers.iter().enumerate().filter_map(|(i, r)| r.map(|r| (i, r))) {
329             let mut need_save = true;
330             // If the register overlaps with a register clobbered by function call, then
331             // we don't need to save it.
332             for r in abi_clobber {
333                 r.overlapping_regs(|r| {
334                     if r == reg {
335                         need_save = false;
336                     }
337                 });
338
339                 if !need_save {
340                     break;
341                 }
342             }
343
344             if need_save {
345                 slots_clobber[i] = Some(new_slot(reg.reg_class()));
346             }
347         }
348
349         // FIXME overlap input and output slots to save stack space
350         for (i, operand) in self.operands.iter().enumerate() {
351             match *operand {
352                 InlineAsmOperand::In { reg, .. } => {
353                     slots_input[i] = Some(new_slot(reg.reg_class()));
354                 }
355                 InlineAsmOperand::Out { reg, place, .. } => {
356                     if place.is_some() {
357                         slots_output[i] = Some(new_slot(reg.reg_class()));
358                     }
359                 }
360                 InlineAsmOperand::InOut { reg, out_place, .. } => {
361                     let slot = new_slot(reg.reg_class());
362                     slots_input[i] = Some(slot);
363                     if out_place.is_some() {
364                         slots_output[i] = Some(slot);
365                     }
366                 }
367                 InlineAsmOperand::Const { value: _ } => (),
368                 InlineAsmOperand::SymFn { value: _ } => (),
369                 InlineAsmOperand::SymStatic { def_id: _ } => (),
370             }
371         }
372
373         self.stack_slots_clobber = slots_clobber;
374         self.stack_slots_input = slots_input;
375         self.stack_slots_output = slots_output;
376         self.stack_slot_size = slot_size;
377     }
378
379     fn generate_asm_wrapper(&self, asm_name: &str) -> String {
380         let mut generated_asm = String::new();
381         writeln!(generated_asm, ".globl {}", asm_name).unwrap();
382         writeln!(generated_asm, ".type {},@function", asm_name).unwrap();
383         writeln!(generated_asm, ".section .text.{},\"ax\",@progbits", asm_name).unwrap();
384         writeln!(generated_asm, "{}:", asm_name).unwrap();
385
386         generated_asm.push_str(".intel_syntax noprefix\n");
387         generated_asm.push_str("    push rbp\n");
388         generated_asm.push_str("    mov rbp,rdi\n");
389
390         // Save clobbered registers
391         if !self.options.contains(InlineAsmOptions::NORETURN) {
392             for (reg, slot) in self
393                 .registers
394                 .iter()
395                 .zip(self.stack_slots_clobber.iter().copied())
396                 .filter_map(|(r, s)| r.zip(s))
397             {
398                 save_register(&mut generated_asm, self.arch, reg, slot);
399             }
400         }
401
402         // Write input registers
403         for (reg, slot) in self
404             .registers
405             .iter()
406             .zip(self.stack_slots_input.iter().copied())
407             .filter_map(|(r, s)| r.zip(s))
408         {
409             restore_register(&mut generated_asm, self.arch, reg, slot);
410         }
411
412         if self.options.contains(InlineAsmOptions::ATT_SYNTAX) {
413             generated_asm.push_str(".att_syntax\n");
414         }
415
416         // The actual inline asm
417         for piece in self.template {
418             match piece {
419                 InlineAsmTemplatePiece::String(s) => {
420                     generated_asm.push_str(s);
421                 }
422                 InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => {
423                     self.registers[*operand_idx]
424                         .unwrap()
425                         .emit(&mut generated_asm, self.arch, *modifier)
426                         .unwrap();
427                 }
428             }
429         }
430         generated_asm.push('\n');
431
432         if is_x86 && self.options.contains(InlineAsmOptions::ATT_SYNTAX) {
433             generated_asm.push_str(".intel_syntax noprefix\n");
434         }
435
436         if !self.options.contains(InlineAsmOptions::NORETURN) {
437             // Read output registers
438             for (reg, slot) in self
439                 .registers
440                 .iter()
441                 .zip(self.stack_slots_output.iter().copied())
442                 .filter_map(|(r, s)| r.zip(s))
443             {
444                 save_register(&mut generated_asm, self.arch, reg, slot);
445             }
446
447             // Restore clobbered registers
448             for (reg, slot) in self
449                 .registers
450                 .iter()
451                 .zip(self.stack_slots_clobber.iter().copied())
452                 .filter_map(|(r, s)| r.zip(s))
453             {
454                 restore_register(&mut generated_asm, self.arch, reg, slot);
455             }
456
457             generated_asm.push_str("    pop rbp\n");
458             generated_asm.push_str("    ret\n");
459         } else {
460             generated_asm.push_str("    ud2\n");
461         }
462
463         generated_asm.push_str(".att_syntax\n");
464         writeln!(generated_asm, ".size {name}, .-{name}", name = asm_name).unwrap();
465         generated_asm.push_str(".text\n");
466         generated_asm.push_str("\n\n");
467
468         generated_asm
469     }
470 }
471
472 fn call_inline_asm<'tcx>(
473     fx: &mut FunctionCx<'_, '_, 'tcx>,
474     asm_name: &str,
475     slot_size: Size,
476     inputs: Vec<(Size, Value)>,
477     outputs: Vec<(Size, CPlace<'tcx>)>,
478 ) {
479     let stack_slot = fx.bcx.func.create_stack_slot(StackSlotData {
480         kind: StackSlotKind::ExplicitSlot,
481         size: u32::try_from(slot_size.bytes()).unwrap(),
482     });
483     if fx.clif_comments.enabled() {
484         fx.add_comment(stack_slot, "inline asm scratch slot");
485     }
486
487     let inline_asm_func = fx
488         .module
489         .declare_function(
490             asm_name,
491             Linkage::Import,
492             &Signature {
493                 call_conv: CallConv::SystemV,
494                 params: vec![AbiParam::new(fx.pointer_type)],
495                 returns: vec![],
496             },
497         )
498         .unwrap();
499     let inline_asm_func = fx.module.declare_func_in_func(inline_asm_func, &mut fx.bcx.func);
500     if fx.clif_comments.enabled() {
501         fx.add_comment(inline_asm_func, asm_name);
502     }
503
504     for (offset, value) in inputs {
505         fx.bcx.ins().stack_store(value, stack_slot, i32::try_from(offset.bytes()).unwrap());
506     }
507
508     let stack_slot_addr = fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0);
509     fx.bcx.ins().call(inline_asm_func, &[stack_slot_addr]);
510
511     for (offset, place) in outputs {
512         let ty = fx.clif_type(place.layout().ty).unwrap();
513         let value = fx.bcx.ins().stack_load(ty, stack_slot, i32::try_from(offset.bytes()).unwrap());
514         place.write_cvalue(fx, CValue::by_val(value, place.layout()));
515     }
516 }
517
518 fn save_register(generated_asm: &mut String, arch: InlineAsmArch, reg: InlineAsmReg, offset: Size) {
519     match arch {
520         InlineAsmArch::X86_64 => {
521             write!(generated_asm, "    mov [rbp+0x{:x}], ", offset.bytes()).unwrap();
522             reg.emit(generated_asm, InlineAsmArch::X86_64, None).unwrap();
523             generated_asm.push('\n');
524         }
525         _ => unimplemented!("save_register for {:?}", arch),
526     }
527 }
528
529 fn restore_register(
530     generated_asm: &mut String,
531     arch: InlineAsmArch,
532     reg: InlineAsmReg,
533     offset: Size,
534 ) {
535     match arch {
536         InlineAsmArch::X86_64 => {
537             generated_asm.push_str("    mov ");
538             reg.emit(generated_asm, InlineAsmArch::X86_64, None).unwrap();
539             writeln!(generated_asm, ", [rbp+0x{:x}]", offset.bytes()).unwrap();
540         }
541         _ => unimplemented!("restore_register for {:?}", arch),
542     }
543 }