]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_codegen_llvm/src/abi.rs
New upstream version 1.74.1+dfsg1
[rustc.git] / compiler / rustc_codegen_llvm / src / abi.rs
CommitLineData
5e7ed085 1use crate::attributes;
9fa01778
XL
2use crate::builder::Builder;
3use crate::context::CodegenCx;
5e7ed085 4use crate::llvm::{self, Attribute, AttributePlace};
9fa01778 5use crate::type_::Type;
60c5eb7d 6use crate::type_of::LayoutLlvmExt;
9fa01778 7use crate::value::Value;
60c5eb7d 8
dfeec247
XL
9use rustc_codegen_ssa::mir::operand::OperandValue;
10use rustc_codegen_ssa::mir::place::PlaceRef;
a1dfa0c6 11use rustc_codegen_ssa::traits::*;
dfeec247 12use rustc_codegen_ssa::MemFlags;
ba9703b0 13use rustc_middle::bug;
c295e0f8 14use rustc_middle::ty::layout::LayoutOf;
ba9703b0
XL
15pub use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
16use rustc_middle::ty::Ty;
5e7ed085 17use rustc_session::config;
60c5eb7d 18use rustc_target::abi::call::ArgAbi;
83c7162d 19pub use rustc_target::abi::call::*;
c295e0f8 20use rustc_target::abi::{self, HasDataLayout, Int};
dfeec247 21pub use rustc_target::spec::abi::Abi;
f2b60f7d 22use rustc_target::spec::SanitizerSet;
476ff2be 23
ba9703b0 24use libc::c_uint;
5e7ed085 25use smallvec::SmallVec;
476ff2be 26
83c7162d 27pub trait ArgAttributesExt {
cdc7bbd5
XL
28 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value);
29 fn apply_attrs_to_callsite(
30 &self,
31 idx: AttributePlace,
32 cx: &CodegenCx<'_, '_>,
33 callsite: &Value,
34 );
35}
36
5e7ed085
FG
37const ABI_AFFECTING_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 1] =
38 [(ArgAttribute::InReg, llvm::AttributeKind::InReg)];
39
40const OPTIMIZATION_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 5] = [
41 (ArgAttribute::NoAlias, llvm::AttributeKind::NoAlias),
42 (ArgAttribute::NoCapture, llvm::AttributeKind::NoCapture),
43 (ArgAttribute::NonNull, llvm::AttributeKind::NonNull),
44 (ArgAttribute::ReadOnly, llvm::AttributeKind::ReadOnly),
45 (ArgAttribute::NoUndef, llvm::AttributeKind::NoUndef),
46];
47
48fn get_attrs<'ll>(this: &ArgAttributes, cx: &CodegenCx<'ll, '_>) -> SmallVec<[&'ll Attribute; 8]> {
49 let mut regular = this.regular;
50
51 let mut attrs = SmallVec::new();
52
53 // ABI-affecting attributes must always be applied
54 for (attr, llattr) in ABI_AFFECTING_ATTRIBUTES {
55 if regular.contains(attr) {
56 attrs.push(llattr.create_attr(cx.llcx));
57 }
58 }
59 if let Some(align) = this.pointee_align {
60 attrs.push(llvm::CreateAlignmentAttr(cx.llcx, align.bytes()));
61 }
62 match this.arg_ext {
63 ArgExtension::None => {}
64 ArgExtension::Zext => attrs.push(llvm::AttributeKind::ZExt.create_attr(cx.llcx)),
65 ArgExtension::Sext => attrs.push(llvm::AttributeKind::SExt.create_attr(cx.llcx)),
66 }
67
68 // Only apply remaining attributes when optimizing
69 if cx.sess().opts.optimize != config::OptLevel::No {
70 let deref = this.pointee_size.bytes();
71 if deref != 0 {
72 if regular.contains(ArgAttribute::NonNull) {
73 attrs.push(llvm::CreateDereferenceableAttr(cx.llcx, deref));
74 } else {
75 attrs.push(llvm::CreateDereferenceableOrNullAttr(cx.llcx, deref));
cdc7bbd5 76 }
5e7ed085
FG
77 regular -= ArgAttribute::NonNull;
78 }
79 for (attr, llattr) in OPTIMIZATION_ATTRIBUTES {
80 if regular.contains(attr) {
81 attrs.push(llattr.create_attr(cx.llcx));
fc512014 82 }
476ff2be 83 }
f2b60f7d
FG
84 } else if cx.tcx.sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::MEMORY) {
85 // If we're not optimising, *but* memory sanitizer is on, emit noundef, since it affects
86 // memory sanitizer's behavior.
87
88 if regular.contains(ArgAttribute::NoUndef) {
89 attrs.push(llvm::AttributeKind::NoUndef.create_attr(cx.llcx));
90 }
5e7ed085
FG
91 }
92
93 attrs
94}
95
96impl ArgAttributesExt for ArgAttributes {
97 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value) {
98 let attrs = get_attrs(self, cx);
99 attributes::apply_to_llfn(llfn, idx, &attrs);
476ff2be
SL
100 }
101
cdc7bbd5
XL
102 fn apply_attrs_to_callsite(
103 &self,
104 idx: AttributePlace,
105 cx: &CodegenCx<'_, '_>,
106 callsite: &Value,
107 ) {
5e7ed085
FG
108 let attrs = get_attrs(self, cx);
109 attributes::apply_to_callsite(callsite, idx, &attrs);
476ff2be
SL
110 }
111}
cc61c64b 112
83c7162d 113pub trait LlvmType {
a2a8927a 114 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
cc61c64b
XL
115}
116
83c7162d 117impl LlvmType for Reg {
a2a8927a 118 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
cc61c64b 119 match self.kind {
a1dfa0c6 120 RegKind::Integer => cx.type_ix(self.size.bits()),
dfeec247
XL
121 RegKind::Float => match self.size.bits() {
122 32 => cx.type_f32(),
123 64 => cx.type_f64(),
124 _ => bug!("unsupported float: {:?}", self),
125 },
126 RegKind::Vector => cx.type_vector(cx.type_i8(), self.size.bytes()),
cc61c64b
XL
127 }
128 }
129}
130
83c7162d 131impl LlvmType for CastTarget {
a2a8927a 132 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
0531ce1d 133 let rest_ll_unit = self.rest.unit.llvm_type(cx);
94b46f34
XL
134 let (rest_count, rem_bytes) = if self.rest.unit.size.bytes() == 0 {
135 (0, 0)
136 } else {
dfeec247
XL
137 (
138 self.rest.total.bytes() / self.rest.unit.size.bytes(),
139 self.rest.total.bytes() % self.rest.unit.size.bytes(),
140 )
94b46f34 141 };
0531ce1d
XL
142
143 if self.prefix.iter().all(|x| x.is_none()) {
144 // Simplify to a single unit when there is no prefix and size <= unit size
145 if self.rest.total <= self.rest.unit.size {
146 return rest_ll_unit;
147 }
148
149 // Simplify to array when all chunks are the same size and type
150 if rem_bytes == 0 {
a1dfa0c6 151 return cx.type_array(rest_ll_unit, rest_count);
cc61c64b
XL
152 }
153 }
0531ce1d
XL
154
155 // Create list of fields in the main structure
dfeec247
XL
156 let mut args: Vec<_> = self
157 .prefix
158 .iter()
a2a8927a 159 .flat_map(|option_reg| option_reg.map(|reg| reg.llvm_type(cx)))
0531ce1d
XL
160 .chain((0..rest_count).map(|_| rest_ll_unit))
161 .collect();
162
163 // Append final integer
164 if rem_bytes != 0 {
165 // Only integers can be really split further.
166 assert_eq!(self.rest.unit.kind, RegKind::Integer);
a1dfa0c6 167 args.push(cx.type_ix(rem_bytes * 8));
0531ce1d
XL
168 }
169
a1dfa0c6 170 cx.type_struct(&args, false)
cc61c64b
XL
171 }
172}
476ff2be 173
60c5eb7d 174pub trait ArgAbiExt<'ll, 'tcx> {
b7449926 175 fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
a1dfa0c6
XL
176 fn store(
177 &self,
178 bx: &mut Builder<'_, 'll, 'tcx>,
179 val: &'ll Value,
180 dst: PlaceRef<'tcx, &'ll Value>,
181 );
182 fn store_fn_arg(
183 &self,
184 bx: &mut Builder<'_, 'll, 'tcx>,
185 idx: &mut usize,
186 dst: PlaceRef<'tcx, &'ll Value>,
187 );
54a0048b
SL
188}
189
a2a8927a 190impl<'ll, 'tcx> ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
9fa01778 191 /// Gets the LLVM type for a place of the original Rust type of
0731742a 192 /// this argument/return, i.e., the result of `type_of::type_of`.
b7449926 193 fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
2c00a5a8 194 self.layout.llvm_type(cx)
54a0048b
SL
195 }
196
60c5eb7d 197 /// Stores a direct/indirect value described by this ArgAbi into a
ff7c6d11 198 /// place for the original Rust type of this argument/return.
54a0048b
SL
199 /// Can be used for both storing formal arguments into Rust variables
200 /// or results of call/invoke instructions into their destinations.
a1dfa0c6
XL
201 fn store(
202 &self,
203 bx: &mut Builder<'_, 'll, 'tcx>,
204 val: &'ll Value,
205 dst: PlaceRef<'tcx, &'ll Value>,
206 ) {
54a0048b
SL
207 if self.is_ignore() {
208 return;
209 }
b7449926 210 if self.is_sized_indirect() {
a1dfa0c6 211 OperandValue::Ref(val, None, self.layout.align.abi).store(bx, dst)
b7449926 212 } else if self.is_unsized_indirect() {
60c5eb7d 213 bug!("unsized `ArgAbi` must be handled through `store_fn_arg`");
781aab86 214 } else if let PassMode::Cast { cast, pad_i32: _ } = &self.mode {
a7813a04
XL
215 // FIXME(eddyb): Figure out when the simpler Store is safe, clang
216 // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
217 let can_store_through_cast_ptr = false;
218 if can_store_through_cast_ptr {
add651ee 219 bx.store(val, dst.llval, self.layout.align.abi);
a7813a04
XL
220 } else {
221 // The actual return type is a struct, but the ABI
9c376795 222 // adaptation code has cast it into some scalar type. The
a7813a04
XL
223 // code that follows is the only reliable way I have
224 // found to do a transform like i64 -> {i32,i32}.
225 // Basically we dump the data onto the stack then memcpy it.
226 //
227 // Other approaches I tried:
228 // - Casting rust ret pointer to the foreign type and using Store
229 // is (a) unsafe if size of foreign type > size of rust type and
230 // (b) runs afoul of strict aliasing rules, yielding invalid
231 // assembly under -O (specifically, the store gets removed).
232 // - Truncating foreign type to correct integral type and then
233 // bitcasting to the struct type yields invalid cast errors.
234
235 // We instead thus allocate some scratch space...
a1dfa0c6
XL
236 let scratch_size = cast.size(bx);
237 let scratch_align = cast.align(bx);
e1599b0c 238 let llscratch = bx.alloca(cast.llvm_type(bx), scratch_align);
2c00a5a8 239 bx.lifetime_start(llscratch, scratch_size);
a7813a04 240
60c5eb7d 241 // ... where we first store the value...
2c00a5a8 242 bx.store(val, llscratch, scratch_align);
a7813a04 243
60c5eb7d 244 // ... and then memcpy it to the intended destination.
a1dfa0c6
XL
245 bx.memcpy(
246 dst.llval,
247 self.layout.align.abi,
248 llscratch,
249 scratch_align,
250 bx.const_usize(self.layout.size.bytes()),
dfeec247 251 MemFlags::empty(),
a1dfa0c6 252 );
a7813a04 253
2c00a5a8 254 bx.lifetime_end(llscratch, scratch_size);
54a0048b
SL
255 }
256 } else {
2c00a5a8 257 OperandValue::Immediate(val).store(bx, dst);
54a0048b
SL
258 }
259 }
260
a1dfa0c6
XL
261 fn store_fn_arg(
262 &self,
a2a8927a 263 bx: &mut Builder<'_, 'll, 'tcx>,
a1dfa0c6
XL
264 idx: &mut usize,
265 dst: PlaceRef<'tcx, &'ll Value>,
266 ) {
ff7c6d11 267 let mut next = || {
2c00a5a8 268 let val = llvm::get_param(bx.llfn(), *idx as c_uint);
54a0048b 269 *idx += 1;
ff7c6d11
XL
270 val
271 };
272 match self.mode {
e74abb32 273 PassMode::Ignore => {}
ff7c6d11 274 PassMode::Pair(..) => {
2c00a5a8 275 OperandValue::Pair(next(), next()).store(bx, dst);
ff7c6d11 276 }
781aab86 277 PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => {
a1dfa0c6 278 OperandValue::Ref(next(), Some(next()), self.layout.align.abi).store(bx, dst);
b7449926 279 }
fc512014 280 PassMode::Direct(_)
781aab86
FG
281 | PassMode::Indirect { attrs: _, meta_attrs: None, on_stack: _ }
282 | PassMode::Cast { .. } => {
532ac7d7
XL
283 let next_arg = next();
284 self.store(bx, next_arg, dst);
ff7c6d11 285 }
54a0048b 286 }
54a0048b
SL
287 }
288}
289
a2a8927a 290impl<'ll, 'tcx> ArgAbiMethods<'tcx> for Builder<'_, 'll, 'tcx> {
a1dfa0c6
XL
291 fn store_fn_arg(
292 &mut self,
60c5eb7d 293 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
dfeec247
XL
294 idx: &mut usize,
295 dst: PlaceRef<'tcx, Self::Value>,
a1dfa0c6 296 ) {
60c5eb7d 297 arg_abi.store_fn_arg(self, idx, dst)
a1dfa0c6 298 }
60c5eb7d 299 fn store_arg(
a1dfa0c6 300 &mut self,
60c5eb7d 301 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
a1dfa0c6 302 val: &'ll Value,
dfeec247 303 dst: PlaceRef<'tcx, &'ll Value>,
a1dfa0c6 304 ) {
60c5eb7d 305 arg_abi.store(self, val, dst)
a1dfa0c6 306 }
60c5eb7d
XL
307 fn arg_memory_ty(&self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
308 arg_abi.memory_ty(self)
a1dfa0c6
XL
309 }
310}
311
a2a8927a 312pub trait FnAbiLlvmExt<'ll, 'tcx> {
b7449926 313 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
a1dfa0c6 314 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
83c7162d 315 fn llvm_cconv(&self) -> llvm::CallConv;
416331ca 316 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value);
a2a8927a 317 fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value);
54a0048b
SL
318}
319
a2a8927a 320impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
b7449926 321 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
94222f64
XL
322 // Ignore "extra" args from the call site for C variadic functions.
323 // Only the "fixed" args are part of the LLVM function signature.
f2b60f7d
FG
324 let args =
325 if self.c_variadic { &self.args[..self.fixed_count as usize] } else { &self.args };
94222f64 326
f2b60f7d 327 // This capacity calculation is approximate.
8faf50e0 328 let mut llargument_tys = Vec::with_capacity(
f2b60f7d 329 self.args.len() + if let PassMode::Indirect { .. } = self.ret.mode { 1 } else { 0 },
8faf50e0 330 );
54a0048b 331
f2b60f7d 332 let llreturn_ty = match &self.ret.mode {
e74abb32 333 PassMode::Ignore => cx.type_void(),
dfeec247 334 PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
781aab86 335 PassMode::Cast { cast, pad_i32: _ } => cast.llvm_type(cx),
fc512014 336 PassMode::Indirect { .. } => {
add651ee 337 llargument_tys.push(cx.type_ptr());
a1dfa0c6 338 cx.type_void()
ff7c6d11 339 }
54a0048b
SL
340 };
341
94222f64 342 for arg in args {
781aab86
FG
343 // Note that the exact number of arguments pushed here is carefully synchronized with
344 // code all over the place, both in the codegen_llvm and codegen_ssa crates. That's how
345 // other code then knows which LLVM argument(s) correspond to the n-th Rust argument.
f2b60f7d 346 let llarg_ty = match &arg.mode {
e74abb32 347 PassMode::Ignore => continue,
781aab86
FG
348 PassMode::Direct(_) => {
349 // ABI-compatible Rust types have the same `layout.abi` (up to validity ranges),
350 // and for Scalar ABIs the LLVM type is fully determined by `layout.abi`,
351 // guarnateeing that we generate ABI-compatible LLVM IR. Things get tricky for
352 // aggregates...
353 if matches!(arg.layout.abi, abi::Abi::Aggregate { .. }) {
354 assert!(
355 arg.layout.is_sized(),
356 "`PassMode::Direct` for unsized type: {}",
357 arg.layout.ty
358 );
359 // This really shouldn't happen, since `immediate_llvm_type` will use
360 // `layout.fields` to turn this Rust type into an LLVM type. This means all
361 // sorts of Rust type details leak into the ABI. However wasm sadly *does*
362 // currently use this mode so we have to allow it -- but we absolutely
363 // shouldn't let any more targets do that.
364 // (Also see <https://github.com/rust-lang/rust/issues/115666>.)
365 assert!(
366 matches!(&*cx.tcx.sess.target.arch, "wasm32" | "wasm64"),
367 "`PassMode::Direct` for aggregates only allowed on wasm targets\nProblematic type: {:#?}",
368 arg.layout,
369 );
370 }
371 arg.layout.immediate_llvm_type(cx)
372 }
ff7c6d11 373 PassMode::Pair(..) => {
781aab86
FG
374 // ABI-compatible Rust types have the same `layout.abi` (up to validity ranges),
375 // so for ScalarPair we can easily be sure that we are generating ABI-compatible
376 // LLVM IR.
377 assert!(
378 matches!(arg.layout.abi, abi::Abi::ScalarPair(..)),
379 "PassMode::Pair for type {}",
380 arg.layout.ty
381 );
8faf50e0
XL
382 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
383 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
ff7c6d11
XL
384 continue;
385 }
781aab86
FG
386 PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack } => {
387 // `Indirect` with metadata is only for unsized types, and doesn't work with
388 // on-stack passing.
389 assert!(arg.layout.is_unsized() && !on_stack);
390 // Construct the type of a (wide) pointer to `ty`, and pass its two fields.
391 // Any two ABI-compatible unsized types have the same metadata type and
392 // moreover the same metadata value leads to the same dynamic size and
393 // alignment, so this respects ABI compatibility.
fe692bf9 394 let ptr_ty = Ty::new_mut_ptr(cx.tcx, arg.layout.ty);
b7449926
XL
395 let ptr_layout = cx.layout_of(ptr_ty);
396 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
397 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
398 continue;
399 }
781aab86
FG
400 PassMode::Indirect { attrs: _, meta_attrs: None, on_stack: _ } => {
401 assert!(arg.layout.is_sized());
402 cx.type_ptr()
403 }
404 PassMode::Cast { cast, pad_i32 } => {
405 // `Cast` means "transmute to `CastType`"; that only makes sense for sized types.
406 assert!(arg.layout.is_sized());
f2b60f7d
FG
407 // add padding
408 if *pad_i32 {
409 llargument_tys.push(Reg::i32().llvm_type(cx));
410 }
781aab86
FG
411 // Compute the LLVM type we use for this function from the cast type.
412 // We assume here that ABI-compatible Rust types have the same cast type.
f2b60f7d
FG
413 cast.llvm_type(cx)
414 }
54a0048b 415 };
54a0048b
SL
416 llargument_tys.push(llarg_ty);
417 }
418
532ac7d7 419 if self.c_variadic {
a1dfa0c6 420 cx.type_variadic_func(&llargument_tys, llreturn_ty)
54a0048b 421 } else {
a1dfa0c6
XL
422 cx.type_func(&llargument_tys, llreturn_ty)
423 }
424 }
425
426 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
add651ee 427 cx.type_ptr_ext(cx.data_layout().instruction_address_space)
54a0048b
SL
428 }
429
83c7162d 430 fn llvm_cconv(&self) -> llvm::CallConv {
487cf647 431 self.conv.into()
83c7162d
XL
432 }
433
416331ca 434 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value) {
add651ee 435 let mut func_attrs = SmallVec::<[_; 3]>::new();
60c5eb7d 436 if self.ret.layout.abi.is_uninhabited() {
5e7ed085 437 func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(cx.llcx));
60c5eb7d 438 }
ba9703b0 439 if !self.can_unwind {
5e7ed085 440 func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(cx.llcx));
ba9703b0 441 }
add651ee
FG
442 if let Conv::RiscvInterrupt { kind } = self.conv {
443 func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", kind.as_str()));
444 }
5e7ed085 445 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &{ func_attrs });
ba9703b0 446
ff7c6d11 447 let mut i = 0;
fc512014 448 let mut apply = |attrs: &ArgAttributes| {
cdc7bbd5 449 attrs.apply_attrs_to_llfn(llvm::AttributePlace::Argument(i), cx, llfn);
ff7c6d11 450 i += 1;
fc512014 451 i - 1
ff7c6d11 452 };
f2b60f7d
FG
453 match &self.ret.mode {
454 PassMode::Direct(attrs) => {
cdc7bbd5 455 attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
fc512014 456 }
781aab86 457 PassMode::Indirect { attrs, meta_attrs: _, on_stack } => {
fc512014
XL
458 assert!(!on_stack);
459 let i = apply(attrs);
5e7ed085
FG
460 let sret = llvm::CreateStructRetAttr(cx.llcx, self.ret.layout.llvm_type(cx));
461 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[sret]);
ff7c6d11 462 }
781aab86 463 PassMode::Cast { cast, pad_i32: _ } => {
a2a8927a
XL
464 cast.attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
465 }
ff7c6d11 466 _ => {}
54a0048b 467 }
f2b60f7d
FG
468 for arg in self.args.iter() {
469 match &arg.mode {
e74abb32 470 PassMode::Ignore => {}
781aab86 471 PassMode::Indirect { attrs, meta_attrs: None, on_stack: true } => {
fc512014 472 let i = apply(attrs);
5e7ed085
FG
473 let byval = llvm::CreateByValAttr(cx.llcx, arg.layout.llvm_type(cx));
474 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byval]);
dfeec247 475 }
f2b60f7d 476 PassMode::Direct(attrs)
781aab86 477 | PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => {
fc512014
XL
478 apply(attrs);
479 }
781aab86 480 PassMode::Indirect { attrs, meta_attrs: Some(meta_attrs), on_stack } => {
fc512014
XL
481 assert!(!on_stack);
482 apply(attrs);
781aab86 483 apply(meta_attrs);
b7449926 484 }
f2b60f7d 485 PassMode::Pair(a, b) => {
fc512014
XL
486 apply(a);
487 apply(b);
488 }
781aab86 489 PassMode::Cast { cast, pad_i32 } => {
f2b60f7d
FG
490 if *pad_i32 {
491 apply(&ArgAttributes::new());
492 }
a2a8927a 493 apply(&cast.attrs);
ff7c6d11 494 }
54a0048b
SL
495 }
496 }
497 }
498
a2a8927a 499 fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value) {
5e7ed085 500 let mut func_attrs = SmallVec::<[_; 2]>::new();
c295e0f8 501 if self.ret.layout.abi.is_uninhabited() {
5e7ed085 502 func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx));
c295e0f8
XL
503 }
504 if !self.can_unwind {
5e7ed085 505 func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(bx.cx.llcx));
c295e0f8 506 }
5e7ed085 507 attributes::apply_to_callsite(callsite, llvm::AttributePlace::Function, &{ func_attrs });
ba9703b0 508
ff7c6d11 509 let mut i = 0;
cdc7bbd5
XL
510 let mut apply = |cx: &CodegenCx<'_, '_>, attrs: &ArgAttributes| {
511 attrs.apply_attrs_to_callsite(llvm::AttributePlace::Argument(i), cx, callsite);
ff7c6d11 512 i += 1;
fc512014 513 i - 1
ff7c6d11 514 };
f2b60f7d
FG
515 match &self.ret.mode {
516 PassMode::Direct(attrs) => {
c295e0f8 517 attrs.apply_attrs_to_callsite(llvm::AttributePlace::ReturnValue, bx.cx, callsite);
fc512014 518 }
781aab86 519 PassMode::Indirect { attrs, meta_attrs: _, on_stack } => {
fc512014 520 assert!(!on_stack);
cdc7bbd5 521 let i = apply(bx.cx, attrs);
5e7ed085
FG
522 let sret = llvm::CreateStructRetAttr(bx.cx.llcx, self.ret.layout.llvm_type(bx));
523 attributes::apply_to_callsite(callsite, llvm::AttributePlace::Argument(i), &[sret]);
ff7c6d11 524 }
781aab86 525 PassMode::Cast { cast, pad_i32: _ } => {
a2a8927a
XL
526 cast.attrs.apply_attrs_to_callsite(
527 llvm::AttributePlace::ReturnValue,
528 &bx.cx,
529 callsite,
530 );
531 }
ff7c6d11 532 _ => {}
54a0048b 533 }
c295e0f8 534 if let abi::Abi::Scalar(scalar) = self.ret.layout.abi {
83c7162d
XL
535 // If the value is a boolean, the range is 0..2 and that ultimately
536 // become 0..0 when the type becomes i1, which would be rejected
537 // by the LLVM verifier.
04454e1e 538 if let Int(..) = scalar.primitive() {
c295e0f8 539 if !scalar.is_bool() && !scalar.is_always_valid(bx) {
04454e1e 540 bx.range_metadata(callsite, scalar.valid_range(bx));
83c7162d 541 }
83c7162d
XL
542 }
543 }
f2b60f7d
FG
544 for arg in self.args.iter() {
545 match &arg.mode {
e74abb32 546 PassMode::Ignore => {}
781aab86 547 PassMode::Indirect { attrs, meta_attrs: None, on_stack: true } => {
cdc7bbd5 548 let i = apply(bx.cx, attrs);
5e7ed085
FG
549 let byval = llvm::CreateByValAttr(bx.cx.llcx, arg.layout.llvm_type(bx));
550 attributes::apply_to_callsite(
551 callsite,
552 llvm::AttributePlace::Argument(i),
553 &[byval],
554 );
dfeec247 555 }
f2b60f7d 556 PassMode::Direct(attrs)
781aab86 557 | PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => {
cdc7bbd5 558 apply(bx.cx, attrs);
fc512014 559 }
781aab86 560 PassMode::Indirect { attrs, meta_attrs: Some(meta_attrs), on_stack: _ } => {
cdc7bbd5 561 apply(bx.cx, attrs);
781aab86 562 apply(bx.cx, meta_attrs);
b7449926 563 }
f2b60f7d 564 PassMode::Pair(a, b) => {
cdc7bbd5
XL
565 apply(bx.cx, a);
566 apply(bx.cx, b);
fc512014 567 }
781aab86 568 PassMode::Cast { cast, pad_i32 } => {
f2b60f7d
FG
569 if *pad_i32 {
570 apply(bx.cx, &ArgAttributes::new());
571 }
a2a8927a 572 apply(bx.cx, &cast.attrs);
ff7c6d11 573 }
54a0048b
SL
574 }
575 }
576
83c7162d
XL
577 let cconv = self.llvm_cconv();
578 if cconv != llvm::CCallConv {
579 llvm::SetInstructionCallConv(callsite, cconv);
54a0048b 580 }
5869c6ff
XL
581
582 if self.conv == Conv::CCmseNonSecureCall {
583 // This will probably get ignored on all targets but those supporting the TrustZone-M
584 // extension (thumbv8m targets).
5e7ed085
FG
585 let cmse_nonsecure_call = llvm::CreateAttrString(bx.cx.llcx, "cmse_nonsecure_call");
586 attributes::apply_to_callsite(
587 callsite,
588 llvm::AttributePlace::Function,
589 &[cmse_nonsecure_call],
590 );
5869c6ff 591 }
064997fb
FG
592
593 // Some intrinsics require that an elementtype attribute (with the pointee type of a
594 // pointer argument) is added to the callsite.
595 let element_type_index = unsafe { llvm::LLVMRustGetElementTypeArgIndex(callsite) };
596 if element_type_index >= 0 {
597 let arg_ty = self.args[element_type_index as usize].layout.ty;
598 let pointee_ty = arg_ty.builtin_deref(true).expect("Must be pointer argument").ty;
599 let element_type_attr = unsafe {
600 llvm::LLVMRustCreateElementTypeAttr(bx.llcx, bx.layout_of(pointee_ty).llvm_type(bx))
601 };
602 attributes::apply_to_callsite(
603 callsite,
604 llvm::AttributePlace::Argument(element_type_index as u32),
605 &[element_type_attr],
606 );
607 }
54a0048b
SL
608 }
609}
a1dfa0c6 610
a2a8927a 611impl<'tcx> AbiBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> {
3c0e092e 612 fn get_param(&mut self, index: usize) -> Self::Value {
532ac7d7
XL
613 llvm::get_param(self.llfn(), index as c_uint)
614 }
a1dfa0c6 615}
487cf647
FG
616
617impl From<Conv> for llvm::CallConv {
618 fn from(conv: Conv) -> Self {
619 match conv {
add651ee
FG
620 Conv::C | Conv::Rust | Conv::CCmseNonSecureCall | Conv::RiscvInterrupt { .. } => {
621 llvm::CCallConv
622 }
781aab86
FG
623 Conv::Cold => llvm::ColdCallConv,
624 Conv::PreserveMost => llvm::PreserveMost,
625 Conv::PreserveAll => llvm::PreserveAll,
487cf647
FG
626 Conv::AmdGpuKernel => llvm::AmdGpuKernel,
627 Conv::AvrInterrupt => llvm::AvrInterrupt,
628 Conv::AvrNonBlockingInterrupt => llvm::AvrNonBlockingInterrupt,
629 Conv::ArmAapcs => llvm::ArmAapcsCallConv,
630 Conv::Msp430Intr => llvm::Msp430Intr,
631 Conv::PtxKernel => llvm::PtxKernel,
632 Conv::X86Fastcall => llvm::X86FastcallCallConv,
633 Conv::X86Intr => llvm::X86_Intr,
634 Conv::X86Stdcall => llvm::X86StdcallCallConv,
635 Conv::X86ThisCall => llvm::X86_ThisCall,
636 Conv::X86VectorCall => llvm::X86_VectorCall,
637 Conv::X86_64SysV => llvm::X86_64_SysV,
638 Conv::X86_64Win64 => llvm::X86_64_Win64,
639 }
640 }
641}