]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_codegen_llvm/src/asm.rs
New upstream version 1.53.0+dfsg1
[rustc.git] / compiler / rustc_codegen_llvm / src / asm.rs
1 use crate::builder::Builder;
2 use crate::context::CodegenCx;
3 use crate::llvm;
4 use crate::type_::Type;
5 use crate::type_of::LayoutLlvmExt;
6 use crate::value::Value;
7
8 use rustc_ast::LlvmAsmDialect;
9 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
10 use rustc_codegen_ssa::mir::operand::OperandValue;
11 use rustc_codegen_ssa::mir::place::PlaceRef;
12 use rustc_codegen_ssa::traits::*;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_hir as hir;
15 use rustc_middle::ty::layout::TyAndLayout;
16 use rustc_middle::{bug, span_bug};
17 use rustc_span::{Pos, Span, Symbol};
18 use rustc_target::abi::*;
19 use rustc_target::asm::*;
20
21 use libc::{c_char, c_uint};
22 use tracing::debug;
23
24 impl AsmBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
25 fn codegen_llvm_inline_asm(
26 &mut self,
27 ia: &hir::LlvmInlineAsmInner,
28 outputs: Vec<PlaceRef<'tcx, &'ll Value>>,
29 mut inputs: Vec<&'ll Value>,
30 span: Span,
31 ) -> bool {
32 let mut ext_constraints = vec![];
33 let mut output_types = vec![];
34
35 // Prepare the output operands
36 let mut indirect_outputs = vec![];
37 for (i, (out, &place)) in ia.outputs.iter().zip(&outputs).enumerate() {
38 if out.is_rw {
39 let operand = self.load_operand(place);
40 if let OperandValue::Immediate(_) = operand.val {
41 inputs.push(operand.immediate());
42 }
43 ext_constraints.push(i.to_string());
44 }
45 if out.is_indirect {
46 let operand = self.load_operand(place);
47 if let OperandValue::Immediate(_) = operand.val {
48 indirect_outputs.push(operand.immediate());
49 }
50 } else {
51 output_types.push(place.layout.llvm_type(self.cx));
52 }
53 }
54 if !indirect_outputs.is_empty() {
55 indirect_outputs.extend_from_slice(&inputs);
56 inputs = indirect_outputs;
57 }
58
59 let clobbers = ia.clobbers.iter().map(|s| format!("~{{{}}}", &s));
60
61 // Default per-arch clobbers
62 // Basically what clang does
63 let arch_clobbers = match &self.sess().target.arch[..] {
64 "x86" | "x86_64" => &["~{dirflag}", "~{fpsr}", "~{flags}"][..],
65 "mips" | "mips64" => &["~{$1}"],
66 _ => &[],
67 };
68
69 let all_constraints = ia
70 .outputs
71 .iter()
72 .map(|out| out.constraint.to_string())
73 .chain(ia.inputs.iter().map(|s| s.to_string()))
74 .chain(ext_constraints)
75 .chain(clobbers)
76 .chain(arch_clobbers.iter().map(|s| (*s).to_string()))
77 .collect::<Vec<String>>()
78 .join(",");
79
80 debug!("Asm Constraints: {}", &all_constraints);
81
82 // Depending on how many outputs we have, the return type is different
83 let num_outputs = output_types.len();
84 let output_type = match num_outputs {
85 0 => self.type_void(),
86 1 => output_types[0],
87 _ => self.type_struct(&output_types, false),
88 };
89
90 let asm = ia.asm.as_str();
91 let r = inline_asm_call(
92 self,
93 &asm,
94 &all_constraints,
95 &inputs,
96 output_type,
97 ia.volatile,
98 ia.alignstack,
99 ia.dialect,
100 &[span],
101 );
102 if r.is_none() {
103 return false;
104 }
105 let r = r.unwrap();
106
107 // Again, based on how many outputs we have
108 let outputs = ia.outputs.iter().zip(&outputs).filter(|&(ref o, _)| !o.is_indirect);
109 for (i, (_, &place)) in outputs.enumerate() {
110 let v = if num_outputs == 1 { r } else { self.extract_value(r, i as u64) };
111 OperandValue::Immediate(v).store(self, place);
112 }
113
114 true
115 }
116
117 fn codegen_inline_asm(
118 &mut self,
119 template: &[InlineAsmTemplatePiece],
120 operands: &[InlineAsmOperandRef<'tcx, Self>],
121 options: InlineAsmOptions,
122 line_spans: &[Span],
123 ) {
124 let asm_arch = self.tcx.sess.asm_arch.unwrap();
125
126 // Collect the types of output operands
127 let mut constraints = vec![];
128 let mut clobbers = vec![];
129 let mut output_types = vec![];
130 let mut op_idx = FxHashMap::default();
131 for (idx, op) in operands.iter().enumerate() {
132 match *op {
133 InlineAsmOperandRef::Out { reg, late, place } => {
134 let is_target_supported = |reg_class: InlineAsmRegClass| {
135 for &(_, feature) in reg_class.supported_types(asm_arch) {
136 if let Some(feature) = feature {
137 if self.tcx.sess.target_features.contains(&Symbol::intern(feature))
138 {
139 return true;
140 }
141 } else {
142 // Register class is unconditionally supported
143 return true;
144 }
145 }
146 false
147 };
148
149 let mut layout = None;
150 let ty = if let Some(ref place) = place {
151 layout = Some(&place.layout);
152 llvm_fixup_output_type(self.cx, reg.reg_class(), &place.layout)
153 } else if !is_target_supported(reg.reg_class()) {
154 // We turn discarded outputs into clobber constraints
155 // if the target feature needed by the register class is
156 // disabled. This is necessary otherwise LLVM will try
157 // to actually allocate a register for the dummy output.
158 assert!(matches!(reg, InlineAsmRegOrRegClass::Reg(_)));
159 clobbers.push(format!("~{}", reg_to_llvm(reg, None)));
160 continue;
161 } else {
162 // If the output is discarded, we don't really care what
163 // type is used. We're just using this to tell LLVM to
164 // reserve the register.
165 dummy_output_type(self.cx, reg.reg_class())
166 };
167 output_types.push(ty);
168 op_idx.insert(idx, constraints.len());
169 let prefix = if late { "=" } else { "=&" };
170 constraints.push(format!("{}{}", prefix, reg_to_llvm(reg, layout)));
171 }
172 InlineAsmOperandRef::InOut { reg, late, in_value, out_place } => {
173 let layout = if let Some(ref out_place) = out_place {
174 &out_place.layout
175 } else {
176 // LLVM required tied operands to have the same type,
177 // so we just use the type of the input.
178 &in_value.layout
179 };
180 let ty = llvm_fixup_output_type(self.cx, reg.reg_class(), layout);
181 output_types.push(ty);
182 op_idx.insert(idx, constraints.len());
183 let prefix = if late { "=" } else { "=&" };
184 constraints.push(format!("{}{}", prefix, reg_to_llvm(reg, Some(layout))));
185 }
186 _ => {}
187 }
188 }
189
190 // Collect input operands
191 let mut inputs = vec![];
192 for (idx, op) in operands.iter().enumerate() {
193 match *op {
194 InlineAsmOperandRef::In { reg, value } => {
195 let llval =
196 llvm_fixup_input(self, value.immediate(), reg.reg_class(), &value.layout);
197 inputs.push(llval);
198 op_idx.insert(idx, constraints.len());
199 constraints.push(reg_to_llvm(reg, Some(&value.layout)));
200 }
201 InlineAsmOperandRef::InOut { reg, late: _, in_value, out_place: _ } => {
202 let value = llvm_fixup_input(
203 self,
204 in_value.immediate(),
205 reg.reg_class(),
206 &in_value.layout,
207 );
208 inputs.push(value);
209 constraints.push(format!("{}", op_idx[&idx]));
210 }
211 InlineAsmOperandRef::SymFn { instance } => {
212 inputs.push(self.cx.get_fn(instance));
213 op_idx.insert(idx, constraints.len());
214 constraints.push("s".to_string());
215 }
216 InlineAsmOperandRef::SymStatic { def_id } => {
217 inputs.push(self.cx.get_static(def_id));
218 op_idx.insert(idx, constraints.len());
219 constraints.push("s".to_string());
220 }
221 _ => {}
222 }
223 }
224
225 // Build the template string
226 let mut template_str = String::new();
227 for piece in template {
228 match *piece {
229 InlineAsmTemplatePiece::String(ref s) => {
230 if s.contains('$') {
231 for c in s.chars() {
232 if c == '$' {
233 template_str.push_str("$$");
234 } else {
235 template_str.push(c);
236 }
237 }
238 } else {
239 template_str.push_str(s)
240 }
241 }
242 InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => {
243 match operands[operand_idx] {
244 InlineAsmOperandRef::In { reg, .. }
245 | InlineAsmOperandRef::Out { reg, .. }
246 | InlineAsmOperandRef::InOut { reg, .. } => {
247 let modifier = modifier_to_llvm(asm_arch, reg.reg_class(), modifier);
248 if let Some(modifier) = modifier {
249 template_str.push_str(&format!(
250 "${{{}:{}}}",
251 op_idx[&operand_idx], modifier
252 ));
253 } else {
254 template_str.push_str(&format!("${{{}}}", op_idx[&operand_idx]));
255 }
256 }
257 InlineAsmOperandRef::Const { ref string } => {
258 // Const operands get injected directly into the template
259 template_str.push_str(string);
260 }
261 InlineAsmOperandRef::SymFn { .. }
262 | InlineAsmOperandRef::SymStatic { .. } => {
263 // Only emit the raw symbol name
264 template_str.push_str(&format!("${{{}:c}}", op_idx[&operand_idx]));
265 }
266 }
267 }
268 }
269 }
270
271 constraints.append(&mut clobbers);
272 if !options.contains(InlineAsmOptions::PRESERVES_FLAGS) {
273 match asm_arch {
274 InlineAsmArch::AArch64 | InlineAsmArch::Arm => {
275 constraints.push("~{cc}".to_string());
276 }
277 InlineAsmArch::X86 | InlineAsmArch::X86_64 => {
278 constraints.extend_from_slice(&[
279 "~{dirflag}".to_string(),
280 "~{fpsr}".to_string(),
281 "~{flags}".to_string(),
282 ]);
283 }
284 InlineAsmArch::RiscV32 | InlineAsmArch::RiscV64 => {}
285 InlineAsmArch::Nvptx64 => {}
286 InlineAsmArch::Hexagon => {}
287 InlineAsmArch::Mips | InlineAsmArch::Mips64 => {}
288 InlineAsmArch::SpirV => {}
289 InlineAsmArch::Wasm32 => {}
290 }
291 }
292 if !options.contains(InlineAsmOptions::NOMEM) {
293 // This is actually ignored by LLVM, but it's probably best to keep
294 // it just in case. LLVM instead uses the ReadOnly/ReadNone
295 // attributes on the call instruction to optimize.
296 constraints.push("~{memory}".to_string());
297 }
298 let volatile = !options.contains(InlineAsmOptions::PURE);
299 let alignstack = !options.contains(InlineAsmOptions::NOSTACK);
300 let output_type = match &output_types[..] {
301 [] => self.type_void(),
302 [ty] => ty,
303 tys => self.type_struct(&tys, false),
304 };
305 let dialect = match asm_arch {
306 InlineAsmArch::X86 | InlineAsmArch::X86_64
307 if !options.contains(InlineAsmOptions::ATT_SYNTAX) =>
308 {
309 LlvmAsmDialect::Intel
310 }
311 _ => LlvmAsmDialect::Att,
312 };
313 let result = inline_asm_call(
314 self,
315 &template_str,
316 &constraints.join(","),
317 &inputs,
318 output_type,
319 volatile,
320 alignstack,
321 dialect,
322 line_spans,
323 )
324 .unwrap_or_else(|| span_bug!(line_spans[0], "LLVM asm constraint validation failed"));
325
326 if options.contains(InlineAsmOptions::PURE) {
327 if options.contains(InlineAsmOptions::NOMEM) {
328 llvm::Attribute::ReadNone.apply_callsite(llvm::AttributePlace::Function, result);
329 } else if options.contains(InlineAsmOptions::READONLY) {
330 llvm::Attribute::ReadOnly.apply_callsite(llvm::AttributePlace::Function, result);
331 }
332 llvm::Attribute::WillReturn.apply_callsite(llvm::AttributePlace::Function, result);
333 } else if options.contains(InlineAsmOptions::NOMEM) {
334 llvm::Attribute::InaccessibleMemOnly
335 .apply_callsite(llvm::AttributePlace::Function, result);
336 } else {
337 // LLVM doesn't have an attribute to represent ReadOnly + SideEffect
338 }
339
340 // Write results to outputs
341 for (idx, op) in operands.iter().enumerate() {
342 if let InlineAsmOperandRef::Out { reg, place: Some(place), .. }
343 | InlineAsmOperandRef::InOut { reg, out_place: Some(place), .. } = *op
344 {
345 let value = if output_types.len() == 1 {
346 result
347 } else {
348 self.extract_value(result, op_idx[&idx] as u64)
349 };
350 let value = llvm_fixup_output(self, value, reg.reg_class(), &place.layout);
351 OperandValue::Immediate(value).store(self, place);
352 }
353 }
354 }
355 }
356
357 impl AsmMethods for CodegenCx<'ll, 'tcx> {
358 fn codegen_global_asm(&self, ga: &hir::GlobalAsm) {
359 let asm = ga.asm.as_str();
360 unsafe {
361 llvm::LLVMRustAppendModuleInlineAsm(self.llmod, asm.as_ptr().cast(), asm.len());
362 }
363 }
364 }
365
366 fn inline_asm_call(
367 bx: &mut Builder<'a, 'll, 'tcx>,
368 asm: &str,
369 cons: &str,
370 inputs: &[&'ll Value],
371 output: &'ll llvm::Type,
372 volatile: bool,
373 alignstack: bool,
374 dia: LlvmAsmDialect,
375 line_spans: &[Span],
376 ) -> Option<&'ll Value> {
377 let volatile = if volatile { llvm::True } else { llvm::False };
378 let alignstack = if alignstack { llvm::True } else { llvm::False };
379
380 let argtys = inputs
381 .iter()
382 .map(|v| {
383 debug!("Asm Input Type: {:?}", *v);
384 bx.cx.val_ty(*v)
385 })
386 .collect::<Vec<_>>();
387
388 debug!("Asm Output Type: {:?}", output);
389 let fty = bx.cx.type_func(&argtys[..], output);
390 unsafe {
391 // Ask LLVM to verify that the constraints are well-formed.
392 let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr().cast(), cons.len());
393 debug!("constraint verification result: {:?}", constraints_ok);
394 if constraints_ok {
395 let v = llvm::LLVMRustInlineAsm(
396 fty,
397 asm.as_ptr().cast(),
398 asm.len(),
399 cons.as_ptr().cast(),
400 cons.len(),
401 volatile,
402 alignstack,
403 llvm::AsmDialect::from_generic(dia),
404 );
405 let call = bx.call(v, inputs, None);
406
407 // Store mark in a metadata node so we can map LLVM errors
408 // back to source locations. See #17552.
409 let key = "srcloc";
410 let kind = llvm::LLVMGetMDKindIDInContext(
411 bx.llcx,
412 key.as_ptr() as *const c_char,
413 key.len() as c_uint,
414 );
415
416 // srcloc contains one integer for each line of assembly code.
417 // Unfortunately this isn't enough to encode a full span so instead
418 // we just encode the start position of each line.
419 // FIXME: Figure out a way to pass the entire line spans.
420 let mut srcloc = vec![];
421 if dia == LlvmAsmDialect::Intel && line_spans.len() > 1 {
422 // LLVM inserts an extra line to add the ".intel_syntax", so add
423 // a dummy srcloc entry for it.
424 //
425 // Don't do this if we only have 1 line span since that may be
426 // due to the asm template string coming from a macro. LLVM will
427 // default to the first srcloc for lines that don't have an
428 // associated srcloc.
429 srcloc.push(bx.const_i32(0));
430 }
431 srcloc.extend(line_spans.iter().map(|span| bx.const_i32(span.lo().to_u32() as i32)));
432 let md = llvm::LLVMMDNodeInContext(bx.llcx, srcloc.as_ptr(), srcloc.len() as u32);
433 llvm::LLVMSetMetadata(call, kind, md);
434
435 Some(call)
436 } else {
437 // LLVM has detected an issue with our constraints, bail out
438 None
439 }
440 }
441 }
442
443 /// If the register is an xmm/ymm/zmm register then return its index.
444 fn xmm_reg_index(reg: InlineAsmReg) -> Option<u32> {
445 match reg {
446 InlineAsmReg::X86(reg)
447 if reg as u32 >= X86InlineAsmReg::xmm0 as u32
448 && reg as u32 <= X86InlineAsmReg::xmm15 as u32 =>
449 {
450 Some(reg as u32 - X86InlineAsmReg::xmm0 as u32)
451 }
452 InlineAsmReg::X86(reg)
453 if reg as u32 >= X86InlineAsmReg::ymm0 as u32
454 && reg as u32 <= X86InlineAsmReg::ymm15 as u32 =>
455 {
456 Some(reg as u32 - X86InlineAsmReg::ymm0 as u32)
457 }
458 InlineAsmReg::X86(reg)
459 if reg as u32 >= X86InlineAsmReg::zmm0 as u32
460 && reg as u32 <= X86InlineAsmReg::zmm31 as u32 =>
461 {
462 Some(reg as u32 - X86InlineAsmReg::zmm0 as u32)
463 }
464 _ => None,
465 }
466 }
467
468 /// If the register is an AArch64 vector register then return its index.
469 fn a64_vreg_index(reg: InlineAsmReg) -> Option<u32> {
470 match reg {
471 InlineAsmReg::AArch64(reg)
472 if reg as u32 >= AArch64InlineAsmReg::v0 as u32
473 && reg as u32 <= AArch64InlineAsmReg::v31 as u32 =>
474 {
475 Some(reg as u32 - AArch64InlineAsmReg::v0 as u32)
476 }
477 _ => None,
478 }
479 }
480
481 /// Converts a register class to an LLVM constraint code.
482 fn reg_to_llvm(reg: InlineAsmRegOrRegClass, layout: Option<&TyAndLayout<'tcx>>) -> String {
483 match reg {
484 // For vector registers LLVM wants the register name to match the type size.
485 InlineAsmRegOrRegClass::Reg(reg) => {
486 if let Some(idx) = xmm_reg_index(reg) {
487 let class = if let Some(layout) = layout {
488 match layout.size.bytes() {
489 64 => 'z',
490 32 => 'y',
491 _ => 'x',
492 }
493 } else {
494 // We use f32 as the type for discarded outputs
495 'x'
496 };
497 format!("{{{}mm{}}}", class, idx)
498 } else if let Some(idx) = a64_vreg_index(reg) {
499 let class = if let Some(layout) = layout {
500 match layout.size.bytes() {
501 16 => 'q',
502 8 => 'd',
503 4 => 's',
504 2 => 'h',
505 1 => 'd', // We fixup i8 to i8x8
506 _ => unreachable!(),
507 }
508 } else {
509 // We use i64x2 as the type for discarded outputs
510 'q'
511 };
512 format!("{{{}{}}}", class, idx)
513 } else if reg == InlineAsmReg::AArch64(AArch64InlineAsmReg::x30) {
514 // LLVM doesn't recognize x30
515 "{lr}".to_string()
516 } else if reg == InlineAsmReg::Arm(ArmInlineAsmReg::r14) {
517 // LLVM doesn't recognize r14
518 "{lr}".to_string()
519 } else {
520 format!("{{{}}}", reg.name())
521 }
522 }
523 InlineAsmRegOrRegClass::RegClass(reg) => match reg {
524 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => "r",
525 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg) => "w",
526 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => "x",
527 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) => "r",
528 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => "l",
529 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
530 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
531 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8) => "t",
532 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16)
533 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8)
534 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => "x",
535 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
536 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg) => "w",
537 InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => "r",
538 InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg) => "r",
539 InlineAsmRegClass::Mips(MipsInlineAsmRegClass::freg) => "f",
540 InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => "h",
541 InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => "r",
542 InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => "l",
543 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => "r",
544 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => "f",
545 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg) => "r",
546 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => "Q",
547 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => "q",
548 InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg)
549 | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg) => "x",
550 InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => "v",
551 InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => "^Yk",
552 InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => "r",
553 InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => {
554 bug!("LLVM backend does not support SPIR-V")
555 }
556 InlineAsmRegClass::Err => unreachable!(),
557 }
558 .to_string(),
559 }
560 }
561
562 /// Converts a modifier into LLVM's equivalent modifier.
563 fn modifier_to_llvm(
564 arch: InlineAsmArch,
565 reg: InlineAsmRegClass,
566 modifier: Option<char>,
567 ) -> Option<char> {
568 match reg {
569 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => modifier,
570 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg)
571 | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
572 if modifier == Some('v') { None } else { modifier }
573 }
574 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg)
575 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => None,
576 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
577 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => None,
578 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
579 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
580 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => Some('P'),
581 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg)
582 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8)
583 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => {
584 if modifier.is_none() {
585 Some('q')
586 } else {
587 modifier
588 }
589 }
590 InlineAsmRegClass::Hexagon(_) => None,
591 InlineAsmRegClass::Mips(_) => None,
592 InlineAsmRegClass::Nvptx(_) => None,
593 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg)
594 | InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => None,
595 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg)
596 | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => match modifier {
597 None if arch == InlineAsmArch::X86_64 => Some('q'),
598 None => Some('k'),
599 Some('l') => Some('b'),
600 Some('h') => Some('h'),
601 Some('x') => Some('w'),
602 Some('e') => Some('k'),
603 Some('r') => Some('q'),
604 _ => unreachable!(),
605 },
606 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => None,
607 InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::xmm_reg)
608 | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::ymm_reg)
609 | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::zmm_reg) => match (reg, modifier) {
610 (X86InlineAsmRegClass::xmm_reg, None) => Some('x'),
611 (X86InlineAsmRegClass::ymm_reg, None) => Some('t'),
612 (X86InlineAsmRegClass::zmm_reg, None) => Some('g'),
613 (_, Some('x')) => Some('x'),
614 (_, Some('y')) => Some('t'),
615 (_, Some('z')) => Some('g'),
616 _ => unreachable!(),
617 },
618 InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => None,
619 InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => None,
620 InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => {
621 bug!("LLVM backend does not support SPIR-V")
622 }
623 InlineAsmRegClass::Err => unreachable!(),
624 }
625 }
626
627 /// Type to use for outputs that are discarded. It doesn't really matter what
628 /// the type is, as long as it is valid for the constraint code.
629 fn dummy_output_type(cx: &CodegenCx<'ll, 'tcx>, reg: InlineAsmRegClass) -> &'ll Type {
630 match reg {
631 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => cx.type_i32(),
632 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg)
633 | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
634 cx.type_vector(cx.type_i64(), 2)
635 }
636 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg)
637 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => cx.type_i32(),
638 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
639 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => cx.type_f32(),
640 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
641 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
642 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => cx.type_f64(),
643 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg)
644 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8)
645 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => {
646 cx.type_vector(cx.type_i64(), 2)
647 }
648 InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => cx.type_i32(),
649 InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg) => cx.type_i32(),
650 InlineAsmRegClass::Mips(MipsInlineAsmRegClass::freg) => cx.type_f32(),
651 InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => cx.type_i16(),
652 InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => cx.type_i32(),
653 InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => cx.type_i64(),
654 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => cx.type_i32(),
655 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => cx.type_f32(),
656 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg)
657 | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => cx.type_i32(),
658 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => cx.type_i8(),
659 InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg)
660 | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg)
661 | InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => cx.type_f32(),
662 InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => cx.type_i16(),
663 InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => cx.type_i32(),
664 InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => {
665 bug!("LLVM backend does not support SPIR-V")
666 }
667 InlineAsmRegClass::Err => unreachable!(),
668 }
669 }
670
671 /// Helper function to get the LLVM type for a Scalar. Pointers are returned as
672 /// the equivalent integer type.
673 fn llvm_asm_scalar_type(cx: &CodegenCx<'ll, 'tcx>, scalar: &Scalar) -> &'ll Type {
674 match scalar.value {
675 Primitive::Int(Integer::I8, _) => cx.type_i8(),
676 Primitive::Int(Integer::I16, _) => cx.type_i16(),
677 Primitive::Int(Integer::I32, _) => cx.type_i32(),
678 Primitive::Int(Integer::I64, _) => cx.type_i64(),
679 Primitive::F32 => cx.type_f32(),
680 Primitive::F64 => cx.type_f64(),
681 Primitive::Pointer => cx.type_isize(),
682 _ => unreachable!(),
683 }
684 }
685
686 /// Fix up an input value to work around LLVM bugs.
687 fn llvm_fixup_input(
688 bx: &mut Builder<'a, 'll, 'tcx>,
689 mut value: &'ll Value,
690 reg: InlineAsmRegClass,
691 layout: &TyAndLayout<'tcx>,
692 ) -> &'ll Value {
693 match (reg, &layout.abi) {
694 (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
695 if let Primitive::Int(Integer::I8, _) = s.value {
696 let vec_ty = bx.cx.type_vector(bx.cx.type_i8(), 8);
697 bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
698 } else {
699 value
700 }
701 }
702 (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
703 let elem_ty = llvm_asm_scalar_type(bx.cx, s);
704 let count = 16 / layout.size.bytes();
705 let vec_ty = bx.cx.type_vector(elem_ty, count);
706 if let Primitive::Pointer = s.value {
707 value = bx.ptrtoint(value, bx.cx.type_isize());
708 }
709 bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
710 }
711 (
712 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
713 Abi::Vector { element, count },
714 ) if layout.size.bytes() == 8 => {
715 let elem_ty = llvm_asm_scalar_type(bx.cx, element);
716 let vec_ty = bx.cx.type_vector(elem_ty, *count);
717 let indices: Vec<_> = (0..count * 2).map(|x| bx.const_i32(x as i32)).collect();
718 bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
719 }
720 (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
721 if s.value == Primitive::F64 =>
722 {
723 bx.bitcast(value, bx.cx.type_i64())
724 }
725 (
726 InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
727 Abi::Vector { .. },
728 ) if layout.size.bytes() == 64 => bx.bitcast(value, bx.cx.type_vector(bx.cx.type_f64(), 8)),
729 (
730 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
731 Abi::Scalar(s),
732 ) => {
733 if let Primitive::Int(Integer::I32, _) = s.value {
734 bx.bitcast(value, bx.cx.type_f32())
735 } else {
736 value
737 }
738 }
739 (
740 InlineAsmRegClass::Arm(
741 ArmInlineAsmRegClass::dreg
742 | ArmInlineAsmRegClass::dreg_low8
743 | ArmInlineAsmRegClass::dreg_low16,
744 ),
745 Abi::Scalar(s),
746 ) => {
747 if let Primitive::Int(Integer::I64, _) = s.value {
748 bx.bitcast(value, bx.cx.type_f64())
749 } else {
750 value
751 }
752 }
753 (InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg), Abi::Scalar(s)) => match s.value {
754 // MIPS only supports register-length arithmetics.
755 Primitive::Int(Integer::I8 | Integer::I16, _) => bx.zext(value, bx.cx.type_i32()),
756 Primitive::F32 => bx.bitcast(value, bx.cx.type_i32()),
757 Primitive::F64 => bx.bitcast(value, bx.cx.type_i64()),
758 _ => value,
759 },
760 _ => value,
761 }
762 }
763
764 /// Fix up an output value to work around LLVM bugs.
765 fn llvm_fixup_output(
766 bx: &mut Builder<'a, 'll, 'tcx>,
767 mut value: &'ll Value,
768 reg: InlineAsmRegClass,
769 layout: &TyAndLayout<'tcx>,
770 ) -> &'ll Value {
771 match (reg, &layout.abi) {
772 (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
773 if let Primitive::Int(Integer::I8, _) = s.value {
774 bx.extract_element(value, bx.const_i32(0))
775 } else {
776 value
777 }
778 }
779 (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
780 value = bx.extract_element(value, bx.const_i32(0));
781 if let Primitive::Pointer = s.value {
782 value = bx.inttoptr(value, layout.llvm_type(bx.cx));
783 }
784 value
785 }
786 (
787 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
788 Abi::Vector { element, count },
789 ) if layout.size.bytes() == 8 => {
790 let elem_ty = llvm_asm_scalar_type(bx.cx, element);
791 let vec_ty = bx.cx.type_vector(elem_ty, *count * 2);
792 let indices: Vec<_> = (0..*count).map(|x| bx.const_i32(x as i32)).collect();
793 bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
794 }
795 (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
796 if s.value == Primitive::F64 =>
797 {
798 bx.bitcast(value, bx.cx.type_f64())
799 }
800 (
801 InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
802 Abi::Vector { .. },
803 ) if layout.size.bytes() == 64 => bx.bitcast(value, layout.llvm_type(bx.cx)),
804 (
805 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
806 Abi::Scalar(s),
807 ) => {
808 if let Primitive::Int(Integer::I32, _) = s.value {
809 bx.bitcast(value, bx.cx.type_i32())
810 } else {
811 value
812 }
813 }
814 (
815 InlineAsmRegClass::Arm(
816 ArmInlineAsmRegClass::dreg
817 | ArmInlineAsmRegClass::dreg_low8
818 | ArmInlineAsmRegClass::dreg_low16,
819 ),
820 Abi::Scalar(s),
821 ) => {
822 if let Primitive::Int(Integer::I64, _) = s.value {
823 bx.bitcast(value, bx.cx.type_i64())
824 } else {
825 value
826 }
827 }
828 (InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg), Abi::Scalar(s)) => match s.value {
829 // MIPS only supports register-length arithmetics.
830 Primitive::Int(Integer::I8, _) => bx.trunc(value, bx.cx.type_i8()),
831 Primitive::Int(Integer::I16, _) => bx.trunc(value, bx.cx.type_i16()),
832 Primitive::F32 => bx.bitcast(value, bx.cx.type_f32()),
833 Primitive::F64 => bx.bitcast(value, bx.cx.type_f64()),
834 _ => value,
835 },
836 _ => value,
837 }
838 }
839
840 /// Output type to use for llvm_fixup_output.
841 fn llvm_fixup_output_type(
842 cx: &CodegenCx<'ll, 'tcx>,
843 reg: InlineAsmRegClass,
844 layout: &TyAndLayout<'tcx>,
845 ) -> &'ll Type {
846 match (reg, &layout.abi) {
847 (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
848 if let Primitive::Int(Integer::I8, _) = s.value {
849 cx.type_vector(cx.type_i8(), 8)
850 } else {
851 layout.llvm_type(cx)
852 }
853 }
854 (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
855 let elem_ty = llvm_asm_scalar_type(cx, s);
856 let count = 16 / layout.size.bytes();
857 cx.type_vector(elem_ty, count)
858 }
859 (
860 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
861 Abi::Vector { element, count },
862 ) if layout.size.bytes() == 8 => {
863 let elem_ty = llvm_asm_scalar_type(cx, element);
864 cx.type_vector(elem_ty, count * 2)
865 }
866 (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
867 if s.value == Primitive::F64 =>
868 {
869 cx.type_i64()
870 }
871 (
872 InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
873 Abi::Vector { .. },
874 ) if layout.size.bytes() == 64 => cx.type_vector(cx.type_f64(), 8),
875 (
876 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
877 Abi::Scalar(s),
878 ) => {
879 if let Primitive::Int(Integer::I32, _) = s.value {
880 cx.type_f32()
881 } else {
882 layout.llvm_type(cx)
883 }
884 }
885 (
886 InlineAsmRegClass::Arm(
887 ArmInlineAsmRegClass::dreg
888 | ArmInlineAsmRegClass::dreg_low8
889 | ArmInlineAsmRegClass::dreg_low16,
890 ),
891 Abi::Scalar(s),
892 ) => {
893 if let Primitive::Int(Integer::I64, _) = s.value {
894 cx.type_f64()
895 } else {
896 layout.llvm_type(cx)
897 }
898 }
899 (InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg), Abi::Scalar(s)) => match s.value {
900 // MIPS only supports register-length arithmetics.
901 Primitive::Int(Integer::I8 | Integer::I16, _) => cx.type_i32(),
902 Primitive::F32 => cx.type_i32(),
903 Primitive::F64 => cx.type_i64(),
904 _ => layout.llvm_type(cx),
905 },
906 _ => layout.llvm_type(cx),
907 }
908 }