]>
Commit | Line | Data |
---|---|---|
a2a8927a | 1 | //! Codegen of `asm!` invocations. |
29967ef6 XL |
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; | |
5099ac24 | 9 | use rustc_span::sym; |
29967ef6 XL |
10 | use rustc_target::asm::*; |
11 | ||
9ffffee4 FG |
12 | enum CInlineAsmOperand<'tcx> { |
13 | In { | |
14 | reg: InlineAsmRegOrRegClass, | |
15 | value: CValue<'tcx>, | |
16 | }, | |
17 | Out { | |
18 | reg: InlineAsmRegOrRegClass, | |
19 | late: bool, | |
20 | place: Option<CPlace<'tcx>>, | |
21 | }, | |
22 | InOut { | |
23 | reg: InlineAsmRegOrRegClass, | |
24 | _late: bool, | |
25 | in_value: CValue<'tcx>, | |
26 | out_place: Option<CPlace<'tcx>>, | |
27 | }, | |
28 | Const { | |
29 | value: String, | |
30 | }, | |
31 | Symbol { | |
32 | symbol: String, | |
33 | }, | |
34 | } | |
35 | ||
29967ef6 | 36 | pub(crate) fn codegen_inline_asm<'tcx>( |
6a06907d | 37 | fx: &mut FunctionCx<'_, '_, 'tcx>, |
9ffffee4 | 38 | span: Span, |
29967ef6 XL |
39 | template: &[InlineAsmTemplatePiece], |
40 | operands: &[InlineAsmOperand<'tcx>], | |
41 | options: InlineAsmOptions, | |
f2b60f7d | 42 | destination: Option<mir::BasicBlock>, |
29967ef6 XL |
43 | ) { |
44 | // FIXME add .eh_frame unwind info directives | |
45 | ||
064997fb | 46 | if !template.is_empty() { |
f2b60f7d | 47 | // Used by panic_abort |
064997fb | 48 | if template[0] == InlineAsmTemplatePiece::String("int $$0x29".to_string()) { |
f2b60f7d | 49 | fx.bcx.ins().trap(TrapCode::User(1)); |
064997fb | 50 | return; |
f2b60f7d FG |
51 | } |
52 | ||
53 | // Used by stdarch | |
2b03887a | 54 | if template[0] == InlineAsmTemplatePiece::String("mov ".to_string()) |
064997fb FG |
55 | && matches!( |
56 | template[1], | |
57 | InlineAsmTemplatePiece::Placeholder { | |
58 | operand_idx: 0, | |
59 | modifier: Some('r'), | |
60 | span: _ | |
61 | } | |
62 | ) | |
2b03887a FG |
63 | && template[2] == InlineAsmTemplatePiece::String(", rbx".to_string()) |
64 | && template[3] == InlineAsmTemplatePiece::String("\n".to_string()) | |
65 | && template[4] == InlineAsmTemplatePiece::String("cpuid".to_string()) | |
66 | && template[5] == InlineAsmTemplatePiece::String("\n".to_string()) | |
67 | && template[6] == InlineAsmTemplatePiece::String("xchg ".to_string()) | |
064997fb | 68 | && matches!( |
2b03887a | 69 | template[7], |
064997fb FG |
70 | InlineAsmTemplatePiece::Placeholder { |
71 | operand_idx: 0, | |
72 | modifier: Some('r'), | |
73 | span: _ | |
74 | } | |
75 | ) | |
2b03887a | 76 | && template[8] == InlineAsmTemplatePiece::String(", rbx".to_string()) |
064997fb FG |
77 | { |
78 | assert_eq!(operands.len(), 4); | |
79 | let (leaf, eax_place) = match operands[1] { | |
f2b60f7d FG |
80 | InlineAsmOperand::InOut { |
81 | reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::ax)), | |
2b03887a | 82 | late: _, |
f2b60f7d FG |
83 | ref in_value, |
84 | out_place: Some(out_place), | |
85 | } => ( | |
86 | crate::base::codegen_operand(fx, in_value).load_scalar(fx), | |
87 | crate::base::codegen_place(fx, out_place), | |
88 | ), | |
064997fb FG |
89 | _ => unreachable!(), |
90 | }; | |
91 | let ebx_place = match operands[0] { | |
f2b60f7d FG |
92 | InlineAsmOperand::Out { |
93 | reg: | |
064997fb | 94 | InlineAsmRegOrRegClass::RegClass(InlineAsmRegClass::X86( |
f2b60f7d FG |
95 | X86InlineAsmRegClass::reg, |
96 | )), | |
2b03887a | 97 | late: _, |
f2b60f7d FG |
98 | place: Some(place), |
99 | } => crate::base::codegen_place(fx, place), | |
064997fb FG |
100 | _ => unreachable!(), |
101 | }; | |
102 | let (sub_leaf, ecx_place) = match operands[2] { | |
f2b60f7d FG |
103 | InlineAsmOperand::InOut { |
104 | reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::cx)), | |
2b03887a | 105 | late: _, |
f2b60f7d FG |
106 | ref in_value, |
107 | out_place: Some(out_place), | |
108 | } => ( | |
109 | crate::base::codegen_operand(fx, in_value).load_scalar(fx), | |
110 | crate::base::codegen_place(fx, out_place), | |
111 | ), | |
064997fb FG |
112 | _ => unreachable!(), |
113 | }; | |
114 | let edx_place = match operands[3] { | |
f2b60f7d FG |
115 | InlineAsmOperand::Out { |
116 | reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::dx)), | |
2b03887a | 117 | late: _, |
f2b60f7d FG |
118 | place: Some(place), |
119 | } => crate::base::codegen_place(fx, place), | |
064997fb FG |
120 | _ => unreachable!(), |
121 | }; | |
17df50a5 | 122 | |
064997fb | 123 | let (eax, ebx, ecx, edx) = crate::intrinsics::codegen_cpuid_call(fx, leaf, sub_leaf); |
17df50a5 | 124 | |
064997fb FG |
125 | eax_place.write_cvalue(fx, CValue::by_val(eax, fx.layout_of(fx.tcx.types.u32))); |
126 | ebx_place.write_cvalue(fx, CValue::by_val(ebx, fx.layout_of(fx.tcx.types.u32))); | |
127 | ecx_place.write_cvalue(fx, CValue::by_val(ecx, fx.layout_of(fx.tcx.types.u32))); | |
128 | edx_place.write_cvalue(fx, CValue::by_val(edx, fx.layout_of(fx.tcx.types.u32))); | |
f2b60f7d FG |
129 | let destination_block = fx.get_block(destination.unwrap()); |
130 | fx.bcx.ins().jump(destination_block, &[]); | |
064997fb | 131 | return; |
f2b60f7d FG |
132 | } |
133 | ||
134 | // Used by compiler-builtins | |
135 | if fx.tcx.symbol_name(fx.instance).name.starts_with("___chkstk") { | |
064997fb FG |
136 | // ___chkstk, ___chkstk_ms and __alloca are only used on Windows |
137 | crate::trap::trap_unimplemented(fx, "Stack probes are not supported"); | |
f2b60f7d | 138 | return; |
064997fb FG |
139 | } else if fx.tcx.symbol_name(fx.instance).name == "__alloca" { |
140 | crate::trap::trap_unimplemented(fx, "Alloca is not supported"); | |
f2b60f7d FG |
141 | return; |
142 | } | |
143 | ||
144 | // Used by measureme | |
145 | if template[0] == InlineAsmTemplatePiece::String("xor %eax, %eax".to_string()) | |
146 | && template[1] == InlineAsmTemplatePiece::String("\n".to_string()) | |
147 | && template[2] == InlineAsmTemplatePiece::String("mov %rbx, ".to_string()) | |
148 | && matches!( | |
149 | template[3], | |
150 | InlineAsmTemplatePiece::Placeholder { | |
151 | operand_idx: 0, | |
152 | modifier: Some('r'), | |
153 | span: _ | |
154 | } | |
155 | ) | |
156 | && template[4] == InlineAsmTemplatePiece::String("\n".to_string()) | |
157 | && template[5] == InlineAsmTemplatePiece::String("cpuid".to_string()) | |
158 | && template[6] == InlineAsmTemplatePiece::String("\n".to_string()) | |
159 | && template[7] == InlineAsmTemplatePiece::String("mov ".to_string()) | |
160 | && matches!( | |
161 | template[8], | |
162 | InlineAsmTemplatePiece::Placeholder { | |
163 | operand_idx: 0, | |
164 | modifier: Some('r'), | |
165 | span: _ | |
166 | } | |
167 | ) | |
168 | && template[9] == InlineAsmTemplatePiece::String(", %rbx".to_string()) | |
169 | { | |
170 | let destination_block = fx.get_block(destination.unwrap()); | |
171 | fx.bcx.ins().jump(destination_block, &[]); | |
172 | return; | |
173 | } else if template[0] == InlineAsmTemplatePiece::String("rdpmc".to_string()) { | |
174 | // Return zero dummy values for all performance counters | |
175 | match operands[0] { | |
176 | InlineAsmOperand::In { | |
177 | reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::cx)), | |
178 | value: _, | |
179 | } => {} | |
180 | _ => unreachable!(), | |
181 | }; | |
182 | let lo = match operands[1] { | |
183 | InlineAsmOperand::Out { | |
184 | reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::ax)), | |
185 | late: true, | |
186 | place: Some(place), | |
187 | } => crate::base::codegen_place(fx, place), | |
188 | _ => unreachable!(), | |
189 | }; | |
190 | let hi = match operands[2] { | |
191 | InlineAsmOperand::Out { | |
192 | reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::dx)), | |
193 | late: true, | |
194 | place: Some(place), | |
195 | } => crate::base::codegen_place(fx, place), | |
196 | _ => unreachable!(), | |
197 | }; | |
198 | ||
199 | let u32_layout = fx.layout_of(fx.tcx.types.u32); | |
200 | let zero = fx.bcx.ins().iconst(types::I32, 0); | |
201 | lo.write_cvalue(fx, CValue::by_val(zero, u32_layout)); | |
202 | hi.write_cvalue(fx, CValue::by_val(zero, u32_layout)); | |
203 | ||
204 | let destination_block = fx.get_block(destination.unwrap()); | |
205 | fx.bcx.ins().jump(destination_block, &[]); | |
206 | return; | |
207 | } else if template[0] == InlineAsmTemplatePiece::String("lock xadd ".to_string()) | |
208 | && matches!( | |
209 | template[1], | |
210 | InlineAsmTemplatePiece::Placeholder { operand_idx: 1, modifier: None, span: _ } | |
211 | ) | |
212 | && template[2] == InlineAsmTemplatePiece::String(", (".to_string()) | |
213 | && matches!( | |
214 | template[3], | |
215 | InlineAsmTemplatePiece::Placeholder { operand_idx: 0, modifier: None, span: _ } | |
216 | ) | |
217 | && template[4] == InlineAsmTemplatePiece::String(")".to_string()) | |
218 | { | |
219 | let destination_block = fx.get_block(destination.unwrap()); | |
220 | fx.bcx.ins().jump(destination_block, &[]); | |
221 | return; | |
064997fb | 222 | } |
29967ef6 XL |
223 | } |
224 | ||
9ffffee4 FG |
225 | let operands = operands |
226 | .into_iter() | |
227 | .map(|operand| match *operand { | |
228 | InlineAsmOperand::In { reg, ref value } => { | |
229 | CInlineAsmOperand::In { reg, value: crate::base::codegen_operand(fx, value) } | |
230 | } | |
231 | InlineAsmOperand::Out { reg, late, ref place } => CInlineAsmOperand::Out { | |
232 | reg, | |
233 | late, | |
234 | place: place.map(|place| crate::base::codegen_place(fx, place)), | |
235 | }, | |
236 | InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => { | |
237 | CInlineAsmOperand::InOut { | |
238 | reg, | |
239 | _late: late, | |
240 | in_value: crate::base::codegen_operand(fx, in_value), | |
241 | out_place: out_place.map(|place| crate::base::codegen_place(fx, place)), | |
242 | } | |
243 | } | |
244 | InlineAsmOperand::Const { ref value } => { | |
245 | let (const_value, ty) = crate::constant::eval_mir_constant(fx, &*value) | |
246 | .unwrap_or_else(|| span_bug!(span, "asm const cannot be resolved")); | |
247 | let value = rustc_codegen_ssa::common::asm_const_to_str( | |
248 | fx.tcx, | |
249 | span, | |
250 | const_value, | |
251 | fx.layout_of(ty), | |
252 | ); | |
253 | CInlineAsmOperand::Const { value } | |
254 | } | |
255 | InlineAsmOperand::SymFn { ref value } => { | |
256 | let literal = fx.monomorphize(value.literal); | |
257 | if let ty::FnDef(def_id, substs) = *literal.ty().kind() { | |
258 | let instance = ty::Instance::resolve_for_fn_ptr( | |
259 | fx.tcx, | |
260 | ty::ParamEnv::reveal_all(), | |
261 | def_id, | |
262 | substs, | |
263 | ) | |
264 | .unwrap(); | |
265 | let symbol = fx.tcx.symbol_name(instance); | |
266 | ||
267 | // Pass a wrapper rather than the function itself as the function itself may not | |
268 | // be exported from the main codegen unit and may thus be unreachable from the | |
269 | // object file created by an external assembler. | |
270 | let inline_asm_index = fx.cx.inline_asm_index.get(); | |
271 | fx.cx.inline_asm_index.set(inline_asm_index + 1); | |
272 | let wrapper_name = format!( | |
273 | "__inline_asm_{}_wrapper_n{}", | |
274 | fx.cx.cgu_name.as_str().replace('.', "__").replace('-', "_"), | |
275 | inline_asm_index | |
276 | ); | |
277 | let sig = | |
278 | get_function_sig(fx.tcx, fx.target_config.default_call_conv, instance); | |
279 | create_wrapper_function( | |
280 | fx.module, | |
281 | &mut fx.cx.unwind_context, | |
282 | sig, | |
283 | &wrapper_name, | |
284 | symbol.name, | |
285 | ); | |
286 | ||
287 | CInlineAsmOperand::Symbol { symbol: wrapper_name } | |
288 | } else { | |
289 | span_bug!(span, "invalid type for asm sym (fn)"); | |
290 | } | |
291 | } | |
292 | InlineAsmOperand::SymStatic { def_id } => { | |
293 | assert!(fx.tcx.is_static(def_id)); | |
294 | let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx); | |
295 | CInlineAsmOperand::Symbol { symbol: fx.tcx.symbol_name(instance).name.to_owned() } | |
296 | } | |
297 | }) | |
298 | .collect::<Vec<_>>(); | |
299 | ||
29967ef6 XL |
300 | let mut inputs = Vec::new(); |
301 | let mut outputs = Vec::new(); | |
302 | ||
a2a8927a XL |
303 | let mut asm_gen = InlineAssemblyGenerator { |
304 | tcx: fx.tcx, | |
305 | arch: fx.tcx.sess.asm_arch.unwrap(), | |
5e7ed085 | 306 | enclosing_def_id: fx.instance.def_id(), |
a2a8927a | 307 | template, |
9ffffee4 | 308 | operands: &operands, |
a2a8927a XL |
309 | options, |
310 | registers: Vec::new(), | |
311 | stack_slots_clobber: Vec::new(), | |
312 | stack_slots_input: Vec::new(), | |
313 | stack_slots_output: Vec::new(), | |
314 | stack_slot_size: Size::from_bytes(0), | |
29967ef6 | 315 | }; |
a2a8927a XL |
316 | asm_gen.allocate_registers(); |
317 | asm_gen.allocate_stack_slots(); | |
318 | ||
319 | let inline_asm_index = fx.cx.inline_asm_index.get(); | |
320 | fx.cx.inline_asm_index.set(inline_asm_index + 1); | |
321 | let asm_name = format!( | |
322 | "__inline_asm_{}_n{}", | |
323 | fx.cx.cgu_name.as_str().replace('.', "__").replace('-', "_"), | |
324 | inline_asm_index | |
325 | ); | |
326 | ||
327 | let generated_asm = asm_gen.generate_asm_wrapper(&asm_name); | |
328 | fx.cx.global_asm.push_str(&generated_asm); | |
29967ef6 | 329 | |
a2a8927a | 330 | for (i, operand) in operands.iter().enumerate() { |
9ffffee4 FG |
331 | match operand { |
332 | CInlineAsmOperand::In { reg: _, value } => { | |
333 | inputs.push((asm_gen.stack_slots_input[i].unwrap(), value.load_scalar(fx))); | |
29967ef6 | 334 | } |
9ffffee4 | 335 | CInlineAsmOperand::Out { reg: _, late: _, place } => { |
29967ef6 | 336 | if let Some(place) = place { |
9ffffee4 | 337 | outputs.push((asm_gen.stack_slots_output[i].unwrap(), place.clone())); |
29967ef6 XL |
338 | } |
339 | } | |
9ffffee4 FG |
340 | CInlineAsmOperand::InOut { reg: _, _late: _, in_value, out_place } => { |
341 | inputs.push((asm_gen.stack_slots_input[i].unwrap(), in_value.load_scalar(fx))); | |
29967ef6 | 342 | if let Some(out_place) = out_place { |
9ffffee4 | 343 | outputs.push((asm_gen.stack_slots_output[i].unwrap(), out_place.clone())); |
29967ef6 XL |
344 | } |
345 | } | |
9ffffee4 | 346 | CInlineAsmOperand::Const { value: _ } | CInlineAsmOperand::Symbol { symbol: _ } => {} |
29967ef6 XL |
347 | } |
348 | } | |
349 | ||
a2a8927a | 350 | call_inline_asm(fx, &asm_name, asm_gen.stack_slot_size, inputs, outputs); |
f2b60f7d FG |
351 | |
352 | match destination { | |
353 | Some(destination) => { | |
354 | let destination_block = fx.get_block(destination); | |
355 | fx.bcx.ins().jump(destination_block, &[]); | |
356 | } | |
357 | None => { | |
358 | fx.bcx.ins().trap(TrapCode::UnreachableCodeReached); | |
359 | } | |
360 | } | |
29967ef6 XL |
361 | } |
362 | ||
a2a8927a XL |
363 | struct InlineAssemblyGenerator<'a, 'tcx> { |
364 | tcx: TyCtxt<'tcx>, | |
29967ef6 | 365 | arch: InlineAsmArch, |
5e7ed085 | 366 | enclosing_def_id: DefId, |
a2a8927a | 367 | template: &'a [InlineAsmTemplatePiece], |
9ffffee4 | 368 | operands: &'a [CInlineAsmOperand<'tcx>], |
29967ef6 | 369 | options: InlineAsmOptions, |
a2a8927a XL |
370 | registers: Vec<Option<InlineAsmReg>>, |
371 | stack_slots_clobber: Vec<Option<Size>>, | |
372 | stack_slots_input: Vec<Option<Size>>, | |
373 | stack_slots_output: Vec<Option<Size>>, | |
374 | stack_slot_size: Size, | |
375 | } | |
376 | ||
377 | impl<'tcx> InlineAssemblyGenerator<'_, 'tcx> { | |
378 | fn allocate_registers(&mut self) { | |
379 | let sess = self.tcx.sess; | |
5e7ed085 FG |
380 | let map = allocatable_registers( |
381 | self.arch, | |
382 | sess.relocation_model(), | |
383 | self.tcx.asm_target_features(self.enclosing_def_id), | |
384 | &sess.target, | |
385 | ); | |
a2a8927a XL |
386 | let mut allocated = FxHashMap::<_, (bool, bool)>::default(); |
387 | let mut regs = vec![None; self.operands.len()]; | |
388 | ||
389 | // Add explicit registers to the allocated set. | |
390 | for (i, operand) in self.operands.iter().enumerate() { | |
391 | match *operand { | |
9ffffee4 | 392 | CInlineAsmOperand::In { reg: InlineAsmRegOrRegClass::Reg(reg), .. } => { |
a2a8927a XL |
393 | regs[i] = Some(reg); |
394 | allocated.entry(reg).or_default().0 = true; | |
395 | } | |
9ffffee4 FG |
396 | CInlineAsmOperand::Out { |
397 | reg: InlineAsmRegOrRegClass::Reg(reg), | |
398 | late: true, | |
399 | .. | |
a2a8927a XL |
400 | } => { |
401 | regs[i] = Some(reg); | |
402 | allocated.entry(reg).or_default().1 = true; | |
403 | } | |
9ffffee4 FG |
404 | CInlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(reg), .. } |
405 | | CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(reg), .. } => { | |
a2a8927a XL |
406 | regs[i] = Some(reg); |
407 | allocated.insert(reg, (true, true)); | |
408 | } | |
409 | _ => (), | |
410 | } | |
29967ef6 | 411 | } |
29967ef6 | 412 | |
a2a8927a XL |
413 | // Allocate out/inout/inlateout registers first because they are more constrained. |
414 | for (i, operand) in self.operands.iter().enumerate() { | |
415 | match *operand { | |
9ffffee4 | 416 | CInlineAsmOperand::Out { |
a2a8927a XL |
417 | reg: InlineAsmRegOrRegClass::RegClass(class), |
418 | late: false, | |
419 | .. | |
420 | } | |
9ffffee4 | 421 | | CInlineAsmOperand::InOut { |
a2a8927a XL |
422 | reg: InlineAsmRegOrRegClass::RegClass(class), .. |
423 | } => { | |
424 | let mut alloc_reg = None; | |
425 | for ® in &map[&class] { | |
426 | let mut used = false; | |
427 | reg.overlapping_regs(|r| { | |
428 | if allocated.contains_key(&r) { | |
429 | used = true; | |
430 | } | |
431 | }); | |
432 | ||
433 | if !used { | |
434 | alloc_reg = Some(reg); | |
435 | break; | |
436 | } | |
437 | } | |
438 | ||
439 | let reg = alloc_reg.expect("cannot allocate registers"); | |
440 | regs[i] = Some(reg); | |
441 | allocated.insert(reg, (true, true)); | |
442 | } | |
443 | _ => (), | |
444 | } | |
445 | } | |
446 | ||
447 | // Allocate in/lateout. | |
448 | for (i, operand) in self.operands.iter().enumerate() { | |
449 | match *operand { | |
9ffffee4 | 450 | CInlineAsmOperand::In { reg: InlineAsmRegOrRegClass::RegClass(class), .. } => { |
a2a8927a XL |
451 | let mut alloc_reg = None; |
452 | for ® in &map[&class] { | |
453 | let mut used = false; | |
454 | reg.overlapping_regs(|r| { | |
455 | if allocated.get(&r).copied().unwrap_or_default().0 { | |
456 | used = true; | |
457 | } | |
458 | }); | |
459 | ||
460 | if !used { | |
461 | alloc_reg = Some(reg); | |
462 | break; | |
463 | } | |
464 | } | |
465 | ||
466 | let reg = alloc_reg.expect("cannot allocate registers"); | |
467 | regs[i] = Some(reg); | |
468 | allocated.entry(reg).or_default().0 = true; | |
469 | } | |
9ffffee4 | 470 | CInlineAsmOperand::Out { |
a2a8927a XL |
471 | reg: InlineAsmRegOrRegClass::RegClass(class), |
472 | late: true, | |
473 | .. | |
474 | } => { | |
475 | let mut alloc_reg = None; | |
476 | for ® in &map[&class] { | |
477 | let mut used = false; | |
478 | reg.overlapping_regs(|r| { | |
479 | if allocated.get(&r).copied().unwrap_or_default().1 { | |
480 | used = true; | |
481 | } | |
482 | }); | |
483 | ||
484 | if !used { | |
485 | alloc_reg = Some(reg); | |
486 | break; | |
487 | } | |
488 | } | |
489 | ||
490 | let reg = alloc_reg.expect("cannot allocate registers"); | |
491 | regs[i] = Some(reg); | |
492 | allocated.entry(reg).or_default().1 = true; | |
493 | } | |
494 | _ => (), | |
495 | } | |
496 | } | |
29967ef6 | 497 | |
a2a8927a | 498 | self.registers = regs; |
29967ef6 XL |
499 | } |
500 | ||
a2a8927a XL |
501 | fn allocate_stack_slots(&mut self) { |
502 | let mut slot_size = Size::from_bytes(0); | |
503 | let mut slots_clobber = vec![None; self.operands.len()]; | |
504 | let mut slots_input = vec![None; self.operands.len()]; | |
505 | let mut slots_output = vec![None; self.operands.len()]; | |
506 | ||
507 | let new_slot_fn = |slot_size: &mut Size, reg_class: InlineAsmRegClass| { | |
508 | let reg_size = | |
509 | reg_class.supported_types(self.arch).iter().map(|(ty, _)| ty.size()).max().unwrap(); | |
510 | let align = rustc_target::abi::Align::from_bytes(reg_size.bytes()).unwrap(); | |
511 | let offset = slot_size.align_to(align); | |
512 | *slot_size = offset + reg_size; | |
513 | offset | |
514 | }; | |
515 | let mut new_slot = |x| new_slot_fn(&mut slot_size, x); | |
516 | ||
517 | // Allocate stack slots for saving clobbered registers | |
5e7ed085 FG |
518 | let abi_clobber = InlineAsmClobberAbi::parse(self.arch, &self.tcx.sess.target, sym::C) |
519 | .unwrap() | |
520 | .clobbered_regs(); | |
a2a8927a XL |
521 | for (i, reg) in self.registers.iter().enumerate().filter_map(|(i, r)| r.map(|r| (i, r))) { |
522 | let mut need_save = true; | |
523 | // If the register overlaps with a register clobbered by function call, then | |
524 | // we don't need to save it. | |
525 | for r in abi_clobber { | |
526 | r.overlapping_regs(|r| { | |
527 | if r == reg { | |
528 | need_save = false; | |
529 | } | |
530 | }); | |
531 | ||
532 | if !need_save { | |
533 | break; | |
534 | } | |
535 | } | |
536 | ||
537 | if need_save { | |
538 | slots_clobber[i] = Some(new_slot(reg.reg_class())); | |
29967ef6 | 539 | } |
29967ef6 | 540 | } |
a2a8927a XL |
541 | |
542 | // Allocate stack slots for inout | |
543 | for (i, operand) in self.operands.iter().enumerate() { | |
544 | match *operand { | |
9ffffee4 | 545 | CInlineAsmOperand::InOut { reg, out_place: Some(_), .. } => { |
a2a8927a XL |
546 | let slot = new_slot(reg.reg_class()); |
547 | slots_input[i] = Some(slot); | |
548 | slots_output[i] = Some(slot); | |
549 | } | |
550 | _ => (), | |
551 | } | |
552 | } | |
553 | ||
554 | let slot_size_before_input = slot_size; | |
555 | let mut new_slot = |x| new_slot_fn(&mut slot_size, x); | |
556 | ||
557 | // Allocate stack slots for input | |
558 | for (i, operand) in self.operands.iter().enumerate() { | |
559 | match *operand { | |
9ffffee4 FG |
560 | CInlineAsmOperand::In { reg, .. } |
561 | | CInlineAsmOperand::InOut { reg, out_place: None, .. } => { | |
a2a8927a XL |
562 | slots_input[i] = Some(new_slot(reg.reg_class())); |
563 | } | |
564 | _ => (), | |
565 | } | |
566 | } | |
567 | ||
568 | // Reset slot size to before input so that input and output operands can overlap | |
569 | // and save some memory. | |
570 | let slot_size_after_input = slot_size; | |
571 | slot_size = slot_size_before_input; | |
572 | let mut new_slot = |x| new_slot_fn(&mut slot_size, x); | |
573 | ||
574 | // Allocate stack slots for output | |
575 | for (i, operand) in self.operands.iter().enumerate() { | |
576 | match *operand { | |
9ffffee4 | 577 | CInlineAsmOperand::Out { reg, place: Some(_), .. } => { |
a2a8927a XL |
578 | slots_output[i] = Some(new_slot(reg.reg_class())); |
579 | } | |
580 | _ => (), | |
581 | } | |
582 | } | |
583 | ||
584 | slot_size = slot_size.max(slot_size_after_input); | |
585 | ||
586 | self.stack_slots_clobber = slots_clobber; | |
587 | self.stack_slots_input = slots_input; | |
588 | self.stack_slots_output = slots_output; | |
589 | self.stack_slot_size = slot_size; | |
29967ef6 | 590 | } |
29967ef6 | 591 | |
a2a8927a XL |
592 | fn generate_asm_wrapper(&self, asm_name: &str) -> String { |
593 | let mut generated_asm = String::new(); | |
594 | writeln!(generated_asm, ".globl {}", asm_name).unwrap(); | |
595 | writeln!(generated_asm, ".type {},@function", asm_name).unwrap(); | |
596 | writeln!(generated_asm, ".section .text.{},\"ax\",@progbits", asm_name).unwrap(); | |
597 | writeln!(generated_asm, "{}:", asm_name).unwrap(); | |
598 | ||
599 | let is_x86 = matches!(self.arch, InlineAsmArch::X86 | InlineAsmArch::X86_64); | |
600 | ||
601 | if is_x86 { | |
602 | generated_asm.push_str(".intel_syntax noprefix\n"); | |
603 | } | |
604 | Self::prologue(&mut generated_asm, self.arch); | |
605 | ||
606 | // Save clobbered registers | |
607 | if !self.options.contains(InlineAsmOptions::NORETURN) { | |
608 | for (reg, slot) in self | |
609 | .registers | |
610 | .iter() | |
611 | .zip(self.stack_slots_clobber.iter().copied()) | |
612 | .filter_map(|(r, s)| r.zip(s)) | |
613 | { | |
614 | Self::save_register(&mut generated_asm, self.arch, reg, slot); | |
615 | } | |
616 | } | |
617 | ||
618 | // Write input registers | |
619 | for (reg, slot) in self | |
620 | .registers | |
621 | .iter() | |
622 | .zip(self.stack_slots_input.iter().copied()) | |
623 | .filter_map(|(r, s)| r.zip(s)) | |
624 | { | |
625 | Self::restore_register(&mut generated_asm, self.arch, reg, slot); | |
626 | } | |
627 | ||
628 | if is_x86 && self.options.contains(InlineAsmOptions::ATT_SYNTAX) { | |
629 | generated_asm.push_str(".att_syntax\n"); | |
630 | } | |
631 | ||
632 | // The actual inline asm | |
633 | for piece in self.template { | |
634 | match piece { | |
635 | InlineAsmTemplatePiece::String(s) => { | |
636 | generated_asm.push_str(s); | |
637 | } | |
638 | InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => { | |
9ffffee4 FG |
639 | match self.operands[*operand_idx] { |
640 | CInlineAsmOperand::In { .. } | |
641 | | CInlineAsmOperand::Out { .. } | |
642 | | CInlineAsmOperand::InOut { .. } => { | |
643 | if self.options.contains(InlineAsmOptions::ATT_SYNTAX) { | |
644 | generated_asm.push('%'); | |
645 | } | |
646 | self.registers[*operand_idx] | |
647 | .unwrap() | |
648 | .emit(&mut generated_asm, self.arch, *modifier) | |
649 | .unwrap(); | |
650 | } | |
651 | CInlineAsmOperand::Const { ref value } => { | |
652 | generated_asm.push_str(value); | |
653 | } | |
654 | CInlineAsmOperand::Symbol { ref symbol } => generated_asm.push_str(symbol), | |
a2a8927a | 655 | } |
a2a8927a XL |
656 | } |
657 | } | |
658 | } | |
659 | generated_asm.push('\n'); | |
660 | ||
661 | if is_x86 && self.options.contains(InlineAsmOptions::ATT_SYNTAX) { | |
662 | generated_asm.push_str(".intel_syntax noprefix\n"); | |
663 | } | |
664 | ||
665 | if !self.options.contains(InlineAsmOptions::NORETURN) { | |
666 | // Read output registers | |
667 | for (reg, slot) in self | |
668 | .registers | |
669 | .iter() | |
670 | .zip(self.stack_slots_output.iter().copied()) | |
671 | .filter_map(|(r, s)| r.zip(s)) | |
672 | { | |
673 | Self::save_register(&mut generated_asm, self.arch, reg, slot); | |
674 | } | |
675 | ||
676 | // Restore clobbered registers | |
677 | for (reg, slot) in self | |
678 | .registers | |
679 | .iter() | |
680 | .zip(self.stack_slots_clobber.iter().copied()) | |
681 | .filter_map(|(r, s)| r.zip(s)) | |
682 | { | |
683 | Self::restore_register(&mut generated_asm, self.arch, reg, slot); | |
684 | } | |
685 | ||
686 | Self::epilogue(&mut generated_asm, self.arch); | |
687 | } else { | |
688 | Self::epilogue_noreturn(&mut generated_asm, self.arch); | |
689 | } | |
690 | ||
691 | if is_x86 { | |
692 | generated_asm.push_str(".att_syntax\n"); | |
693 | } | |
694 | writeln!(generated_asm, ".size {name}, .-{name}", name = asm_name).unwrap(); | |
695 | generated_asm.push_str(".text\n"); | |
696 | generated_asm.push_str("\n\n"); | |
697 | ||
698 | generated_asm | |
29967ef6 XL |
699 | } |
700 | ||
a2a8927a XL |
701 | fn prologue(generated_asm: &mut String, arch: InlineAsmArch) { |
702 | match arch { | |
703 | InlineAsmArch::X86 => { | |
704 | generated_asm.push_str(" push ebp\n"); | |
705 | generated_asm.push_str(" mov ebp,[esp+8]\n"); | |
706 | } | |
707 | InlineAsmArch::X86_64 => { | |
708 | generated_asm.push_str(" push rbp\n"); | |
709 | generated_asm.push_str(" mov rbp,rdi\n"); | |
710 | } | |
711 | InlineAsmArch::RiscV32 => { | |
712 | generated_asm.push_str(" addi sp, sp, -8\n"); | |
713 | generated_asm.push_str(" sw ra, 4(sp)\n"); | |
714 | generated_asm.push_str(" sw s0, 0(sp)\n"); | |
715 | generated_asm.push_str(" mv s0, a0\n"); | |
716 | } | |
717 | InlineAsmArch::RiscV64 => { | |
718 | generated_asm.push_str(" addi sp, sp, -16\n"); | |
719 | generated_asm.push_str(" sd ra, 8(sp)\n"); | |
720 | generated_asm.push_str(" sd s0, 0(sp)\n"); | |
721 | generated_asm.push_str(" mv s0, a0\n"); | |
722 | } | |
723 | _ => unimplemented!("prologue for {:?}", arch), | |
29967ef6 | 724 | } |
a2a8927a | 725 | } |
29967ef6 | 726 | |
a2a8927a XL |
727 | fn epilogue(generated_asm: &mut String, arch: InlineAsmArch) { |
728 | match arch { | |
729 | InlineAsmArch::X86 => { | |
730 | generated_asm.push_str(" pop ebp\n"); | |
731 | generated_asm.push_str(" ret\n"); | |
732 | } | |
733 | InlineAsmArch::X86_64 => { | |
734 | generated_asm.push_str(" pop rbp\n"); | |
735 | generated_asm.push_str(" ret\n"); | |
736 | } | |
737 | InlineAsmArch::RiscV32 => { | |
738 | generated_asm.push_str(" lw s0, 0(sp)\n"); | |
739 | generated_asm.push_str(" lw ra, 4(sp)\n"); | |
740 | generated_asm.push_str(" addi sp, sp, 8\n"); | |
741 | generated_asm.push_str(" ret\n"); | |
742 | } | |
743 | InlineAsmArch::RiscV64 => { | |
744 | generated_asm.push_str(" ld s0, 0(sp)\n"); | |
745 | generated_asm.push_str(" ld ra, 8(sp)\n"); | |
746 | generated_asm.push_str(" addi sp, sp, 16\n"); | |
747 | generated_asm.push_str(" ret\n"); | |
748 | } | |
749 | _ => unimplemented!("epilogue for {:?}", arch), | |
29967ef6 | 750 | } |
a2a8927a | 751 | } |
29967ef6 | 752 | |
a2a8927a XL |
753 | fn epilogue_noreturn(generated_asm: &mut String, arch: InlineAsmArch) { |
754 | match arch { | |
755 | InlineAsmArch::X86 | InlineAsmArch::X86_64 => { | |
756 | generated_asm.push_str(" ud2\n"); | |
757 | } | |
758 | InlineAsmArch::RiscV32 | InlineAsmArch::RiscV64 => { | |
759 | generated_asm.push_str(" ebreak\n"); | |
760 | } | |
761 | _ => unimplemented!("epilogue_noreturn for {:?}", arch), | |
762 | } | |
29967ef6 XL |
763 | } |
764 | ||
a2a8927a XL |
765 | fn save_register( |
766 | generated_asm: &mut String, | |
767 | arch: InlineAsmArch, | |
768 | reg: InlineAsmReg, | |
769 | offset: Size, | |
770 | ) { | |
771 | match arch { | |
772 | InlineAsmArch::X86 => { | |
773 | write!(generated_asm, " mov [ebp+0x{:x}], ", offset.bytes()).unwrap(); | |
774 | reg.emit(generated_asm, InlineAsmArch::X86, None).unwrap(); | |
775 | generated_asm.push('\n'); | |
776 | } | |
777 | InlineAsmArch::X86_64 => { | |
778 | write!(generated_asm, " mov [rbp+0x{:x}], ", offset.bytes()).unwrap(); | |
779 | reg.emit(generated_asm, InlineAsmArch::X86_64, None).unwrap(); | |
780 | generated_asm.push('\n'); | |
781 | } | |
782 | InlineAsmArch::RiscV32 => { | |
783 | generated_asm.push_str(" sw "); | |
784 | reg.emit(generated_asm, InlineAsmArch::RiscV32, None).unwrap(); | |
785 | writeln!(generated_asm, ", 0x{:x}(s0)", offset.bytes()).unwrap(); | |
786 | } | |
787 | InlineAsmArch::RiscV64 => { | |
788 | generated_asm.push_str(" sd "); | |
789 | reg.emit(generated_asm, InlineAsmArch::RiscV64, None).unwrap(); | |
790 | writeln!(generated_asm, ", 0x{:x}(s0)", offset.bytes()).unwrap(); | |
791 | } | |
792 | _ => unimplemented!("save_register for {:?}", arch), | |
793 | } | |
794 | } | |
29967ef6 | 795 | |
a2a8927a XL |
796 | fn restore_register( |
797 | generated_asm: &mut String, | |
798 | arch: InlineAsmArch, | |
799 | reg: InlineAsmReg, | |
800 | offset: Size, | |
801 | ) { | |
802 | match arch { | |
803 | InlineAsmArch::X86 => { | |
804 | generated_asm.push_str(" mov "); | |
805 | reg.emit(generated_asm, InlineAsmArch::X86, None).unwrap(); | |
806 | writeln!(generated_asm, ", [ebp+0x{:x}]", offset.bytes()).unwrap(); | |
807 | } | |
808 | InlineAsmArch::X86_64 => { | |
809 | generated_asm.push_str(" mov "); | |
810 | reg.emit(generated_asm, InlineAsmArch::X86_64, None).unwrap(); | |
811 | writeln!(generated_asm, ", [rbp+0x{:x}]", offset.bytes()).unwrap(); | |
812 | } | |
813 | InlineAsmArch::RiscV32 => { | |
814 | generated_asm.push_str(" lw "); | |
815 | reg.emit(generated_asm, InlineAsmArch::RiscV32, None).unwrap(); | |
816 | writeln!(generated_asm, ", 0x{:x}(s0)", offset.bytes()).unwrap(); | |
817 | } | |
818 | InlineAsmArch::RiscV64 => { | |
819 | generated_asm.push_str(" ld "); | |
820 | reg.emit(generated_asm, InlineAsmArch::RiscV64, None).unwrap(); | |
821 | writeln!(generated_asm, ", 0x{:x}(s0)", offset.bytes()).unwrap(); | |
822 | } | |
823 | _ => unimplemented!("restore_register for {:?}", arch), | |
824 | } | |
825 | } | |
29967ef6 XL |
826 | } |
827 | ||
828 | fn call_inline_asm<'tcx>( | |
6a06907d | 829 | fx: &mut FunctionCx<'_, '_, 'tcx>, |
29967ef6 XL |
830 | asm_name: &str, |
831 | slot_size: Size, | |
a2a8927a XL |
832 | inputs: Vec<(Size, Value)>, |
833 | outputs: Vec<(Size, CPlace<'tcx>)>, | |
29967ef6 | 834 | ) { |
f2b60f7d | 835 | let stack_slot = fx.bcx.func.create_sized_stack_slot(StackSlotData { |
29967ef6 | 836 | kind: StackSlotKind::ExplicitSlot, |
29967ef6 XL |
837 | size: u32::try_from(slot_size.bytes()).unwrap(), |
838 | }); | |
cdc7bbd5 XL |
839 | if fx.clif_comments.enabled() { |
840 | fx.add_comment(stack_slot, "inline asm scratch slot"); | |
841 | } | |
29967ef6 XL |
842 | |
843 | let inline_asm_func = fx | |
29967ef6 XL |
844 | .module |
845 | .declare_function( | |
846 | asm_name, | |
847 | Linkage::Import, | |
848 | &Signature { | |
849 | call_conv: CallConv::SystemV, | |
850 | params: vec![AbiParam::new(fx.pointer_type)], | |
851 | returns: vec![], | |
852 | }, | |
853 | ) | |
854 | .unwrap(); | |
17df50a5 | 855 | let inline_asm_func = fx.module.declare_func_in_func(inline_asm_func, &mut fx.bcx.func); |
cdc7bbd5 XL |
856 | if fx.clif_comments.enabled() { |
857 | fx.add_comment(inline_asm_func, asm_name); | |
858 | } | |
29967ef6 | 859 | |
a2a8927a | 860 | for (offset, value) in inputs { |
6a06907d | 861 | fx.bcx.ins().stack_store(value, stack_slot, i32::try_from(offset.bytes()).unwrap()); |
29967ef6 XL |
862 | } |
863 | ||
864 | let stack_slot_addr = fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0); | |
865 | fx.bcx.ins().call(inline_asm_func, &[stack_slot_addr]); | |
866 | ||
a2a8927a | 867 | for (offset, place) in outputs { |
29967ef6 | 868 | let ty = fx.clif_type(place.layout().ty).unwrap(); |
6a06907d | 869 | let value = fx.bcx.ins().stack_load(ty, stack_slot, i32::try_from(offset.bytes()).unwrap()); |
29967ef6 XL |
870 | place.write_cvalue(fx, CValue::by_val(value, place.layout())); |
871 | } | |
872 | } |