clang  19.0.0git
CGCall.cpp
Go to the documentation of this file.
1 //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // These classes wrap the information about a call or function
10 // definition used to handle ABI compliancy.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGCall.h"
15 #include "ABIInfo.h"
16 #include "ABIInfoImpl.h"
17 #include "CGBlocks.h"
18 #include "CGCXXABI.h"
19 #include "CGCleanup.h"
20 #include "CGRecordLayout.h"
21 #include "CGSYCLRuntime.h"
22 #include "CodeGenFunction.h"
23 #include "CodeGenModule.h"
24 #include "TargetInfo.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/Decl.h"
27 #include "clang/AST/DeclCXX.h"
28 #include "clang/AST/DeclObjC.h"
30 #include "clang/Basic/TargetInfo.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/IR/Assumptions.h"
36 #include "llvm/IR/AttributeMask.h"
37 #include "llvm/IR/Attributes.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/FPAccuracy.h"
41 #include "llvm/IR/InlineAsm.h"
42 #include "llvm/IR/IntrinsicInst.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include <optional>
47 using namespace clang;
48 using namespace CodeGen;
49 
50 /***/
51 
53  switch (CC) {
54  default: return llvm::CallingConv::C;
55  case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
56  case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
57  case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
58  case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
59  case CC_Win64: return llvm::CallingConv::Win64;
60  case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
61  case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
62  case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
63  case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
64  // TODO: Add support for __pascal to LLVM.
66  // TODO: Add support for __vectorcall to LLVM.
67  case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
68  case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
69  case CC_AArch64SVEPCS: return llvm::CallingConv::AArch64_SVE_VectorCall;
70  case CC_AMDGPUKernelCall: return llvm::CallingConv::AMDGPU_KERNEL;
71  case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
73  case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
74  case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
75  case CC_Swift: return llvm::CallingConv::Swift;
76  case CC_SwiftAsync: return llvm::CallingConv::SwiftTail;
77  case CC_M68kRTD: return llvm::CallingConv::M68k_RTD;
78  case CC_PreserveNone: return llvm::CallingConv::PreserveNone;
79  // clang-format off
80  case CC_RISCVVectorCall: return llvm::CallingConv::RISCV_VectorCall;
81  // clang-format on
82  }
83 }
84 
85 /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
86 /// qualification. Either or both of RD and MD may be null. A null RD indicates
87 /// that there is no meaningful 'this' type, and a null MD can occur when
88 /// calling a method pointer.
90  const CXXMethodDecl *MD) {
91  QualType RecTy;
92  if (RD)
93  RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
94  else
95  RecTy = Context.VoidTy;
96 
97  if (MD)
98  RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
99  return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
100 }
101 
102 /// Returns the canonical formal type of the given C++ method.
104  return MD->getType()->getCanonicalTypeUnqualified()
106 }
107 
108 /// Returns the "extra-canonicalized" return type, which discards
109 /// qualifiers on the return type. Codegen doesn't care about them,
110 /// and it makes ABI code a little easier to be able to assume that
111 /// all parameter and return types are top-level unqualified.
114 }
115 
116 /// Arrange the argument and result information for a value of the given
117 /// unprototyped freestanding function type.
118 const CGFunctionInfo &
120  // When translating an unprototyped function type, always use a
121  // variadic type.
122  return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
123  FnInfoOpts::None, std::nullopt,
124  FTNP->getExtInfo(), {}, RequiredArgs(0));
125 }
126 
129  const FunctionProtoType *proto,
130  unsigned prefixArgs,
131  unsigned totalArgs) {
132  assert(proto->hasExtParameterInfos());
133  assert(paramInfos.size() <= prefixArgs);
134  assert(proto->getNumParams() + prefixArgs <= totalArgs);
135 
136  paramInfos.reserve(totalArgs);
137 
138  // Add default infos for any prefix args that don't already have infos.
139  paramInfos.resize(prefixArgs);
140 
141  // Add infos for the prototype.
142  for (const auto &ParamInfo : proto->getExtParameterInfos()) {
143  paramInfos.push_back(ParamInfo);
144  // pass_object_size params have no parameter info.
145  if (ParamInfo.hasPassObjectSize())
146  paramInfos.emplace_back();
147  }
148 
149  assert(paramInfos.size() <= totalArgs &&
150  "Did we forget to insert pass_object_size args?");
151  // Add default infos for the variadic and/or suffix arguments.
152  paramInfos.resize(totalArgs);
153 }
154 
155 /// Adds the formal parameters in FPT to the given prefix. If any parameter in
156 /// FPT has pass_object_size attrs, then we'll add parameters for those, too.
157 static void appendParameterTypes(const CodeGenTypes &CGT,
161  // Fast path: don't touch param info if we don't need to.
162  if (!FPT->hasExtParameterInfos()) {
163  assert(paramInfos.empty() &&
164  "We have paramInfos, but the prototype doesn't?");
165  prefix.append(FPT->param_type_begin(), FPT->param_type_end());
166  return;
167  }
168 
169  unsigned PrefixSize = prefix.size();
170  // In the vast majority of cases, we'll have precisely FPT->getNumParams()
171  // parameters; the only thing that can change this is the presence of
172  // pass_object_size. So, we preallocate for the common case.
173  prefix.reserve(prefix.size() + FPT->getNumParams());
174 
175  auto ExtInfos = FPT->getExtParameterInfos();
176  assert(ExtInfos.size() == FPT->getNumParams());
177  for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
178  prefix.push_back(FPT->getParamType(I));
179  if (ExtInfos[I].hasPassObjectSize())
180  prefix.push_back(CGT.getContext().getSizeType());
181  }
182 
183  addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
184  prefix.size());
185 }
186 
187 /// Arrange the LLVM function layout for a value of the given function
188 /// type, on top of any implicit parameters already stored.
189 static const CGFunctionInfo &
190 arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
195  // FIXME: Kill copy.
196  appendParameterTypes(CGT, prefix, paramInfos, FTP);
197  CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
198 
199  FnInfoOpts opts =
201  return CGT.arrangeLLVMFunctionInfo(resultType, opts, prefix,
202  FTP->getExtInfo(), paramInfos, Required);
203 }
204 
205 /// Arrange the argument and result information for a value of the
206 /// given freestanding function type.
207 const CGFunctionInfo &
210  return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
211  FTP);
212 }
213 
215  bool IsWindows) {
216  // Set the appropriate calling convention for the Function.
217  if (D->hasAttr<StdCallAttr>())
218  return CC_X86StdCall;
219 
220  if (D->hasAttr<FastCallAttr>())
221  return CC_X86FastCall;
222 
223  if (D->hasAttr<RegCallAttr>())
224  return CC_X86RegCall;
225 
226  if (D->hasAttr<ThisCallAttr>())
227  return CC_X86ThisCall;
228 
229  if (D->hasAttr<VectorCallAttr>())
230  return CC_X86VectorCall;
231 
232  if (D->hasAttr<PascalAttr>())
233  return CC_X86Pascal;
234 
235  if (PcsAttr *PCS = D->getAttr<PcsAttr>())
236  return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
237 
238  if (D->hasAttr<AArch64VectorPcsAttr>())
239  return CC_AArch64VectorCall;
240 
241  if (D->hasAttr<AArch64SVEPcsAttr>())
242  return CC_AArch64SVEPCS;
243 
244  if (D->hasAttr<AMDGPUKernelCallAttr>())
245  return CC_AMDGPUKernelCall;
246 
247  if (D->hasAttr<IntelOclBiccAttr>())
248  return CC_IntelOclBicc;
249 
250  if (D->hasAttr<MSABIAttr>())
251  return IsWindows ? CC_C : CC_Win64;
252 
253  if (D->hasAttr<SysVABIAttr>())
254  return IsWindows ? CC_X86_64SysV : CC_C;
255 
256  if (D->hasAttr<PreserveMostAttr>())
257  return CC_PreserveMost;
258 
259  if (D->hasAttr<PreserveAllAttr>())
260  return CC_PreserveAll;
261 
262  if (D->hasAttr<M68kRTDAttr>())
263  return CC_M68kRTD;
264 
265  if (D->hasAttr<PreserveNoneAttr>())
266  return CC_PreserveNone;
267 
268  if (D->hasAttr<RISCVVectorCCAttr>())
269  return CC_RISCVVectorCall;
270 
271  return CC_C;
272 }
273 
274 /// Arrange the argument and result information for a call to an
275 /// unknown C++ non-static member function of the given abstract type.
276 /// (A null RD means we don't have any meaningful "this" argument type,
277 /// so fall back to a generic pointer type).
278 /// The member function must be an ordinary function, i.e. not a
279 /// constructor or destructor.
280 const CGFunctionInfo &
282  const FunctionProtoType *FTP,
283  const CXXMethodDecl *MD) {
285 
286  // Add the 'this' pointer.
287  argTypes.push_back(DeriveThisType(RD, MD));
288 
290  *this, /*instanceMethod=*/true, argTypes,
292 }
293 
294 /// Set calling convention for CUDA/HIP kernel.
296  const FunctionDecl *FD) {
297  if (FD->hasAttr<CUDAGlobalAttr>()) {
298  const FunctionType *FT = FTy->getAs<FunctionType>();
300  FTy = FT->getCanonicalTypeUnqualified();
301  }
302 }
303 
304 /// Arrange the argument and result information for a declaration or
305 /// definition of the given C++ non-static member function. The
306 /// member function must be an ordinary function, i.e. not a
307 /// constructor or destructor.
308 const CGFunctionInfo &
310  assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
311  assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
312 
313  CanQualType FT = GetFormalType(MD).getAs<Type>();
314  setCUDAKernelCallingConvention(FT, CGM, MD);
315  auto prototype = FT.getAs<FunctionProtoType>();
316 
317  if (MD->isImplicitObjectMemberFunction()) {
318  // The abstract case is perfectly fine.
319  const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
320  return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
321  }
322 
323  return arrangeFreeFunctionType(prototype);
324 }
325 
327  const InheritedConstructor &Inherited, CXXCtorType Type) {
328  // Parameters are unnecessary if we're constructing a base class subobject
329  // and the inherited constructor lives in a virtual base.
330  return Type == Ctor_Complete ||
331  !Inherited.getShadowDecl()->constructsVirtualBase() ||
332  !Target.getCXXABI().hasConstructorVariants();
333 }
334 
335 const CGFunctionInfo &
337  auto *MD = cast<CXXMethodDecl>(GD.getDecl());
338 
341 
342  const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(GD);
343  argTypes.push_back(DeriveThisType(ThisType, MD));
344 
345  bool PassParams = true;
346 
347  if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
348  // A base class inheriting constructor doesn't get forwarded arguments
349  // needed to construct a virtual base (or base class thereof).
350  if (auto Inherited = CD->getInheritedConstructor())
351  PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
352  }
353 
355 
356  // Add the formal parameters.
357  if (PassParams)
358  appendParameterTypes(*this, argTypes, paramInfos, FTP);
359 
361  TheCXXABI.buildStructorSignature(GD, argTypes);
362  if (!paramInfos.empty()) {
363  // Note: prefix implies after the first param.
364  if (AddedArgs.Prefix)
365  paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
367  if (AddedArgs.Suffix)
368  paramInfos.append(AddedArgs.Suffix,
370  }
371 
372  RequiredArgs required =
373  (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
375 
376  FunctionType::ExtInfo extInfo = FTP->getExtInfo();
377  CanQualType resultType = TheCXXABI.HasThisReturn(GD)
378  ? argTypes.front()
379  : TheCXXABI.hasMostDerivedReturn(GD)
380  ? CGM.getContext().VoidPtrTy
381  : Context.VoidTy;
383  argTypes, extInfo, paramInfos, required);
384 }
385 
389  for (auto &arg : args)
390  argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
391  return argTypes;
392 }
393 
397  for (auto &arg : args)
398  argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
399  return argTypes;
400 }
401 
404  unsigned prefixArgs, unsigned totalArgs) {
406  if (proto->hasExtParameterInfos()) {
407  addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
408  }
409  return result;
410 }
411 
412 /// Arrange a call to a C++ method, passing the given arguments.
413 ///
414 /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
415 /// parameter.
416 /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
417 /// args.
418 /// PassProtoArgs indicates whether `args` has args for the parameters in the
419 /// given CXXConstructorDecl.
420 const CGFunctionInfo &
422  const CXXConstructorDecl *D,
423  CXXCtorType CtorKind,
424  unsigned ExtraPrefixArgs,
425  unsigned ExtraSuffixArgs,
426  bool PassProtoArgs) {
427  // FIXME: Kill copy.
429  for (const auto &Arg : args)
430  ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
431 
432  // +1 for implicit this, which should always be args[0].
433  unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
434 
436  RequiredArgs Required = PassProtoArgs
438  FPT, TotalPrefixArgs + ExtraSuffixArgs)
440 
441  GlobalDecl GD(D, CtorKind);
442  CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
443  ? ArgTypes.front()
444  : TheCXXABI.hasMostDerivedReturn(GD)
445  ? CGM.getContext().VoidPtrTy
446  : Context.VoidTy;
447 
448  FunctionType::ExtInfo Info = FPT->getExtInfo();
450  // If the prototype args are elided, we should only have ABI-specific args,
451  // which never have param info.
452  if (PassProtoArgs && FPT->hasExtParameterInfos()) {
453  // ABI-specific suffix arguments are treated the same as variadic arguments.
454  addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
455  ArgTypes.size());
456  }
457 
459  ArgTypes, Info, ParamInfos, Required);
460 }
461 
462 /// Arrange the argument and result information for the declaration or
463 /// definition of the given function.
464 const CGFunctionInfo &
466  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
467  if (MD->isImplicitObjectMemberFunction())
468  return arrangeCXXMethodDeclaration(MD);
469 
471 
472  assert(isa<FunctionType>(FTy));
473  setCUDAKernelCallingConvention(FTy, CGM, FD);
474 
475  // When declaring a function without a prototype, always use a
476  // non-variadic type.
478  return arrangeLLVMFunctionInfo(noProto->getReturnType(), FnInfoOpts::None,
479  std::nullopt, noProto->getExtInfo(), {},
481  }
482 
484 }
485 
486 /// Arrange the argument and result information for the declaration or
487 /// definition of an Objective-C method.
488 const CGFunctionInfo &
490  // It happens that this is the same as a call with no optional
491  // arguments, except also using the formal 'self' type.
493 }
494 
495 /// Arrange the argument and result information for the function type
496 /// through which to perform a send to the given Objective-C method,
497 /// using the given receiver type. The receiver type is not always
498 /// the 'self' type of the method or even an Objective-C pointer type.
499 /// This is *not* the right method for actually performing such a
500 /// message send, due to the possibility of optional arguments.
501 const CGFunctionInfo &
503  QualType receiverType) {
506  MD->isDirectMethod() ? 1 : 2);
507  argTys.push_back(Context.getCanonicalParamType(receiverType));
508  if (!MD->isDirectMethod())
509  argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
510  // FIXME: Kill copy?
511  for (const auto *I : MD->parameters()) {
512  argTys.push_back(Context.getCanonicalParamType(I->getType()));
514  I->hasAttr<NoEscapeAttr>());
515  extParamInfos.push_back(extParamInfo);
516  }
517 
518  FunctionType::ExtInfo einfo;
519  bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
520  einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
521 
522  if (getContext().getLangOpts().ObjCAutoRefCount &&
523  MD->hasAttr<NSReturnsRetainedAttr>())
524  einfo = einfo.withProducesResult(true);
525 
526  RequiredArgs required =
527  (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
528 
530  FnInfoOpts::None, argTys, einfo, extParamInfos,
531  required);
532 }
533 
534 const CGFunctionInfo &
536  const CallArgList &args) {
537  auto argTypes = getArgTypesForCall(Context, args);
538  FunctionType::ExtInfo einfo;
539 
541  argTypes, einfo, {}, RequiredArgs::All);
542 }
543 
544 const CGFunctionInfo &
546  // FIXME: Do we need to handle ObjCMethodDecl?
547  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
548 
549  if (isa<CXXConstructorDecl>(GD.getDecl()) ||
550  isa<CXXDestructorDecl>(GD.getDecl()))
552 
553  return arrangeFunctionDeclaration(FD);
554 }
555 
556 /// Arrange a thunk that takes 'this' as the first parameter followed by
557 /// varargs. Return a void pointer, regardless of the actual return type.
558 /// The body of the thunk will end in a musttail call to a function of the
559 /// correct type, and the caller will bitcast the function to the correct
560 /// prototype.
561 const CGFunctionInfo &
563  assert(MD->isVirtual() && "only methods have thunks");
565  CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
566  return arrangeLLVMFunctionInfo(Context.VoidTy, FnInfoOpts::None, ArgTys,
567  FTP->getExtInfo(), {}, RequiredArgs(1));
568 }
569 
570 const CGFunctionInfo &
572  CXXCtorType CT) {
573  assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
574 
577  const CXXRecordDecl *RD = CD->getParent();
578  ArgTys.push_back(DeriveThisType(RD, CD));
579  if (CT == Ctor_CopyingClosure)
580  ArgTys.push_back(*FTP->param_type_begin());
581  if (RD->getNumVBases() > 0)
582  ArgTys.push_back(Context.IntTy);
584  /*IsVariadic=*/false, /*IsCXXMethod=*/true);
586  ArgTys, FunctionType::ExtInfo(CC), {},
588 }
589 
590 /// Arrange a call as unto a free function, except possibly with an
591 /// additional number of formal parameters considered required.
592 static const CGFunctionInfo &
594  CodeGenModule &CGM,
595  const CallArgList &args,
596  const FunctionType *fnType,
597  unsigned numExtraRequiredArgs,
598  bool chainCall) {
599  assert(args.size() >= numExtraRequiredArgs);
600 
602 
603  // In most cases, there are no optional arguments.
604  RequiredArgs required = RequiredArgs::All;
605 
606  // If we have a variadic prototype, the required arguments are the
607  // extra prefix plus the arguments in the prototype.
608  if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
609  if (proto->isVariadic())
610  required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
611 
612  if (proto->hasExtParameterInfos())
613  addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
614  args.size());
615 
616  // If we don't have a prototype at all, but we're supposed to
617  // explicitly use the variadic convention for unprototyped calls,
618  // treat all of the arguments as required but preserve the nominal
619  // possibility of variadics.
620  } else if (CGM.getTargetCodeGenInfo()
621  .isNoProtoCallVariadic(args,
622  cast<FunctionNoProtoType>(fnType))) {
623  required = RequiredArgs(args.size());
624  }
625 
626  // FIXME: Kill copy.
628  for (const auto &arg : args)
629  argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
632  opts, argTypes, fnType->getExtInfo(),
633  paramInfos, required);
634 }
635 
636 /// Figure out the rules for calling a function with the given formal
637 /// type using the given arguments. The arguments are necessary
638 /// because the function might be unprototyped, in which case it's
639 /// target-dependent in crazy ways.
640 const CGFunctionInfo &
642  const FunctionType *fnType,
643  bool chainCall) {
644  return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
645  chainCall ? 1 : 0, chainCall);
646 }
647 
648 /// A block function is essentially a free function with an
649 /// extra implicit argument.
650 const CGFunctionInfo &
652  const FunctionType *fnType) {
653  return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
654  /*chainCall=*/false);
655 }
656 
657 const CGFunctionInfo &
659  const FunctionArgList &params) {
660  auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
661  auto argTypes = getArgTypesForDeclaration(Context, params);
662 
664  FnInfoOpts::None, argTypes,
665  proto->getExtInfo(), paramInfos,
667 }
668 
669 const CGFunctionInfo &
671  const CallArgList &args) {
672  // FIXME: Kill copy.
674  for (const auto &Arg : args)
675  argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
677  argTypes, FunctionType::ExtInfo(),
678  /*paramInfos=*/{}, RequiredArgs::All);
679 }
680 
681 const CGFunctionInfo &
683  const FunctionArgList &args) {
684  auto argTypes = getArgTypesForDeclaration(Context, args);
685 
687  argTypes, FunctionType::ExtInfo(), {},
689 }
690 
691 const CGFunctionInfo &
693  ArrayRef<CanQualType> argTypes) {
694  return arrangeLLVMFunctionInfo(resultType, FnInfoOpts::None, argTypes,
695  FunctionType::ExtInfo(), {},
697 }
698 
699 /// Arrange a call to a C++ method, passing the given arguments.
700 ///
701 /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
702 /// does not count `this`.
703 const CGFunctionInfo &
705  const FunctionProtoType *proto,
706  RequiredArgs required,
707  unsigned numPrefixArgs) {
708  assert(numPrefixArgs + 1 <= args.size() &&
709  "Emitting a call with less args than the required prefix?");
710  // Add one to account for `this`. It's a bit awkward here, but we don't count
711  // `this` in similar places elsewhere.
712  auto paramInfos =
713  getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
714 
715  // FIXME: Kill copy.
716  auto argTypes = getArgTypesForCall(Context, args);
717 
718  FunctionType::ExtInfo info = proto->getExtInfo();
720  FnInfoOpts::IsInstanceMethod, argTypes, info,
721  paramInfos, required);
722 }
723 
726  std::nullopt, FunctionType::ExtInfo(), {},
728 }
729 
730 const CGFunctionInfo &
732  const CallArgList &args) {
733  assert(signature.arg_size() <= args.size());
734  if (signature.arg_size() == args.size())
735  return signature;
736 
738  auto sigParamInfos = signature.getExtParameterInfos();
739  if (!sigParamInfos.empty()) {
740  paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
741  paramInfos.resize(args.size());
742  }
743 
744  auto argTypes = getArgTypesForCall(Context, args);
745 
746  assert(signature.getRequiredArgs().allowsOptionalArgs());
748  if (signature.isInstanceMethod())
750  if (signature.isChainCall())
751  opts |= FnInfoOpts::IsChainCall;
752  if (signature.isDelegateCall())
754  return arrangeLLVMFunctionInfo(signature.getReturnType(), opts, argTypes,
755  signature.getExtInfo(), paramInfos,
756  signature.getRequiredArgs());
757 }
758 
759 namespace clang {
760 namespace CodeGen {
762 }
763 }
764 
765 /// Arrange the argument and result information for an abstract value
766 /// of a given function type. This is the method which all of the
767 /// above functions ultimately defer to.
769  CanQualType resultType, FnInfoOpts opts, ArrayRef<CanQualType> argTypes,
772  RequiredArgs required) {
773  assert(llvm::all_of(argTypes,
774  [](CanQualType T) { return T.isCanonicalAsParam(); }));
775 
776  // Lookup or create unique function info.
777  llvm::FoldingSetNodeID ID;
778  bool isInstanceMethod =
780  bool isChainCall =
782  bool isDelegateCall =
784  CGFunctionInfo::Profile(ID, isInstanceMethod, isChainCall, isDelegateCall,
785  info, paramInfos, required, resultType, argTypes);
786 
787  void *insertPos = nullptr;
788  CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
789  if (FI)
790  return *FI;
791 
792  unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
793  // This is required so SYCL kernels are successfully processed by tools from CUDA. Kernels
794  // with a `spir_kernel` calling convention are ignored otherwise.
795  if (CC == llvm::CallingConv::SPIR_KERNEL &&
796  (CGM.getTriple().isNVPTX() || CGM.getTriple().isAMDGCN()) &&
797  getContext().getLangOpts().SYCLIsDevice) {
799  }
800 
801  // Construct the function info. We co-allocate the ArgInfos.
802  FI = CGFunctionInfo::create(CC, isInstanceMethod, isChainCall, isDelegateCall,
803  info, paramInfos, resultType, argTypes, required);
804  FunctionInfos.InsertNode(FI, insertPos);
805 
806  bool inserted = FunctionsBeingProcessed.insert(FI).second;
807  (void)inserted;
808  assert(inserted && "Recursively being processed?");
809 
810  // Compute ABI information.
811  if (CC == llvm::CallingConv::SPIR_KERNEL) {
812  // Force target independent argument handling for the host visible
813  // kernel functions.
814  computeSPIRKernelABIInfo(CGM, *FI);
815  } else if (info.getCC() == CC_Swift || info.getCC() == CC_SwiftAsync) {
816  swiftcall::computeABIInfo(CGM, *FI);
817  } else {
818  getABIInfo().computeInfo(*FI);
819  }
820 
821  // Loop over all of the computed argument and return value info. If any of
822  // them are direct or extend without a specified coerce type, specify the
823  // default now.
824  ABIArgInfo &retInfo = FI->getReturnInfo();
825  if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
826  retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
827 
828  for (auto &I : FI->arguments())
829  if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
830  I.info.setCoerceToType(ConvertType(I.type));
831 
832  bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
833  assert(erased && "Not in set?");
834 
835  return *FI;
836 }
837 
838 CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC, bool instanceMethod,
839  bool chainCall, bool delegateCall,
840  const FunctionType::ExtInfo &info,
841  ArrayRef<ExtParameterInfo> paramInfos,
842  CanQualType resultType,
843  ArrayRef<CanQualType> argTypes,
844  RequiredArgs required) {
845  assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
846  assert(!required.allowsOptionalArgs() ||
847  required.getNumRequiredArgs() <= argTypes.size());
848 
849  void *buffer =
850  operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
851  argTypes.size() + 1, paramInfos.size()));
852 
853  CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
854  FI->CallingConvention = llvmCC;
855  FI->EffectiveCallingConvention = llvmCC;
856  FI->ASTCallingConvention = info.getCC();
857  FI->InstanceMethod = instanceMethod;
858  FI->ChainCall = chainCall;
859  FI->DelegateCall = delegateCall;
860  FI->CmseNSCall = info.getCmseNSCall();
861  FI->NoReturn = info.getNoReturn();
862  FI->ReturnsRetained = info.getProducesResult();
863  FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
864  FI->NoCfCheck = info.getNoCfCheck();
865  FI->Required = required;
866  FI->HasRegParm = info.getHasRegParm();
867  FI->RegParm = info.getRegParm();
868  FI->ArgStruct = nullptr;
869  FI->ArgStructAlign = 0;
870  FI->NumArgs = argTypes.size();
871  FI->HasExtParameterInfos = !paramInfos.empty();
872  FI->getArgsBuffer()[0].type = resultType;
873  FI->MaxVectorWidth = 0;
874  for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
875  FI->getArgsBuffer()[i + 1].type = argTypes[i];
876  for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
877  FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
878  return FI;
879 }
880 
881 /***/
882 
883 namespace {
884 // ABIArgInfo::Expand implementation.
885 
886 // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
887 struct TypeExpansion {
888  enum TypeExpansionKind {
889  // Elements of constant arrays are expanded recursively.
890  TEK_ConstantArray,
891  // Record fields are expanded recursively (but if record is a union, only
892  // the field with the largest size is expanded).
893  TEK_Record,
894  // For complex types, real and imaginary parts are expanded recursively.
895  TEK_Complex,
896  // All other types are not expandable.
897  TEK_None
898  };
899 
900  const TypeExpansionKind Kind;
901 
902  TypeExpansion(TypeExpansionKind K) : Kind(K) {}
903  virtual ~TypeExpansion() {}
904 };
905 
906 struct ConstantArrayExpansion : TypeExpansion {
907  QualType EltTy;
908  uint64_t NumElts;
909 
910  ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
911  : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
912  static bool classof(const TypeExpansion *TE) {
913  return TE->Kind == TEK_ConstantArray;
914  }
915 };
916 
917 struct RecordExpansion : TypeExpansion {
919 
921 
922  RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
924  : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
925  Fields(std::move(Fields)) {}
926  static bool classof(const TypeExpansion *TE) {
927  return TE->Kind == TEK_Record;
928  }
929 };
930 
931 struct ComplexExpansion : TypeExpansion {
932  QualType EltTy;
933 
934  ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
935  static bool classof(const TypeExpansion *TE) {
936  return TE->Kind == TEK_Complex;
937  }
938 };
939 
940 struct NoExpansion : TypeExpansion {
941  NoExpansion() : TypeExpansion(TEK_None) {}
942  static bool classof(const TypeExpansion *TE) {
943  return TE->Kind == TEK_None;
944  }
945 };
946 } // namespace
947 
948 static std::unique_ptr<TypeExpansion>
949 getTypeExpansion(QualType Ty, const ASTContext &Context) {
950  if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
951  return std::make_unique<ConstantArrayExpansion>(AT->getElementType(),
952  AT->getZExtSize());
953  }
954  if (const RecordType *RT = Ty->getAs<RecordType>()) {
957  const RecordDecl *RD = RT->getDecl();
958  assert(!RD->hasFlexibleArrayMember() &&
959  "Cannot expand structure with flexible array.");
960  if (RD->isUnion()) {
961  // Unions can be here only in degenerative cases - all the fields are same
962  // after flattening. Thus we have to use the "largest" field.
963  const FieldDecl *LargestFD = nullptr;
964  CharUnits UnionSize = CharUnits::Zero();
965 
966  for (const auto *FD : RD->fields()) {
967  if (FD->isZeroLengthBitField(Context))
968  continue;
969  assert(!FD->isBitField() &&
970  "Cannot expand structure with bit-field members.");
971  CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
972  if (UnionSize < FieldSize) {
973  UnionSize = FieldSize;
974  LargestFD = FD;
975  }
976  }
977  if (LargestFD)
978  Fields.push_back(LargestFD);
979  } else {
980  if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
981  assert(!CXXRD->isDynamicClass() &&
982  "cannot expand vtable pointers in dynamic classes");
983  llvm::append_range(Bases, llvm::make_pointer_range(CXXRD->bases()));
984  }
985 
986  for (const auto *FD : RD->fields()) {
987  if (FD->isZeroLengthBitField(Context))
988  continue;
989  assert(!FD->isBitField() &&
990  "Cannot expand structure with bit-field members.");
991  Fields.push_back(FD);
992  }
993  }
994  return std::make_unique<RecordExpansion>(std::move(Bases),
995  std::move(Fields));
996  }
997  if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
998  return std::make_unique<ComplexExpansion>(CT->getElementType());
999  }
1000  return std::make_unique<NoExpansion>();
1001 }
1002 
1003 static int getExpansionSize(QualType Ty, const ASTContext &Context) {
1004  auto Exp = getTypeExpansion(Ty, Context);
1005  if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1006  return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
1007  }
1008  if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1009  int Res = 0;
1010  for (auto BS : RExp->Bases)
1011  Res += getExpansionSize(BS->getType(), Context);
1012  for (auto FD : RExp->Fields)
1013  Res += getExpansionSize(FD->getType(), Context);
1014  return Res;
1015  }
1016  if (isa<ComplexExpansion>(Exp.get()))
1017  return 2;
1018  assert(isa<NoExpansion>(Exp.get()));
1019  return 1;
1020 }
1021 
1022 void
1025  auto Exp = getTypeExpansion(Ty, Context);
1026  if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1027  for (int i = 0, n = CAExp->NumElts; i < n; i++) {
1028  getExpandedTypes(CAExp->EltTy, TI);
1029  }
1030  } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1031  for (auto BS : RExp->Bases)
1032  getExpandedTypes(BS->getType(), TI);
1033  for (auto FD : RExp->Fields)
1034  getExpandedTypes(FD->getType(), TI);
1035  } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
1036  llvm::Type *EltTy = ConvertType(CExp->EltTy);
1037  *TI++ = EltTy;
1038  *TI++ = EltTy;
1039  } else {
1040  assert(isa<NoExpansion>(Exp.get()));
1041  *TI++ = ConvertType(Ty);
1042  }
1043 }
1044 
1046  ConstantArrayExpansion *CAE,
1047  Address BaseAddr,
1048  llvm::function_ref<void(Address)> Fn) {
1049  for (int i = 0, n = CAE->NumElts; i < n; i++) {
1050  Address EltAddr = CGF.Builder.CreateConstGEP2_32(BaseAddr, 0, i);
1051  Fn(EltAddr);
1052  }
1053 }
1054 
1055 void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1056  llvm::Function::arg_iterator &AI) {
1057  assert(LV.isSimple() &&
1058  "Unexpected non-simple lvalue during struct expansion.");
1059 
1060  auto Exp = getTypeExpansion(Ty, getContext());
1061  if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1063  *this, CAExp, LV.getAddress(), [&](Address EltAddr) {
1064  LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
1065  ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
1066  });
1067  } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1068  Address This = LV.getAddress();
1069  for (const CXXBaseSpecifier *BS : RExp->Bases) {
1070  // Perform a single step derived-to-base conversion.
1071  Address Base =
1072  GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1073  /*NullCheckValue=*/false, SourceLocation());
1074  LValue SubLV = MakeAddrLValue(Base, BS->getType());
1075 
1076  // Recurse onto bases.
1077  ExpandTypeFromArgs(BS->getType(), SubLV, AI);
1078  }
1079  for (auto FD : RExp->Fields) {
1080  // FIXME: What are the right qualifiers here?
1081  LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
1082  ExpandTypeFromArgs(FD->getType(), SubLV, AI);
1083  }
1084  } else if (isa<ComplexExpansion>(Exp.get())) {
1085  auto realValue = &*AI++;
1086  auto imagValue = &*AI++;
1087  EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
1088  } else {
1089  // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a
1090  // primitive store.
1091  assert(isa<NoExpansion>(Exp.get()));
1092  llvm::Value *Arg = &*AI++;
1093  if (LV.isBitField()) {
1095  } else {
1096  // TODO: currently there are some places are inconsistent in what LLVM
1097  // pointer type they use (see D118744). Once clang uses opaque pointers
1098  // all LLVM pointer types will be the same and we can remove this check.
1099  if (Arg->getType()->isPointerTy()) {
1100  Address Addr = LV.getAddress();
1101  Arg = Builder.CreateBitCast(Arg, Addr.getElementType());
1102  }
1103  EmitStoreOfScalar(Arg, LV);
1104  }
1105  }
1106 }
1107 
1108 void CodeGenFunction::ExpandTypeToArgs(
1109  QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
1110  SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1111  auto Exp = getTypeExpansion(Ty, getContext());
1112  if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1113  Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1116  *this, CAExp, Addr, [&](Address EltAddr) {
1117  CallArg EltArg = CallArg(
1118  convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
1119  CAExp->EltTy);
1120  ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
1121  IRCallArgPos);
1122  });
1123  } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1124  Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1126  for (const CXXBaseSpecifier *BS : RExp->Bases) {
1127  // Perform a single step derived-to-base conversion.
1128  Address Base =
1129  GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1130  /*NullCheckValue=*/false, SourceLocation());
1131  CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
1132 
1133  // Recurse onto bases.
1134  ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
1135  IRCallArgPos);
1136  }
1137 
1138  LValue LV = MakeAddrLValue(This, Ty);
1139  for (auto FD : RExp->Fields) {
1140  CallArg FldArg =
1141  CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
1142  ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
1143  IRCallArgPos);
1144  }
1145  } else if (isa<ComplexExpansion>(Exp.get())) {
1147  IRCallArgs[IRCallArgPos++] = CV.first;
1148  IRCallArgs[IRCallArgPos++] = CV.second;
1149  } else {
1150  assert(isa<NoExpansion>(Exp.get()));
1151  auto RV = Arg.getKnownRValue();
1152  assert(RV.isScalar() &&
1153  "Unexpected non-scalar rvalue during struct expansion.");
1154 
1155  // Insert a bitcast as needed.
1156  llvm::Value *V = RV.getScalarVal();
1157  if (IRCallArgPos < IRFuncTy->getNumParams() &&
1158  V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1159  V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1160 
1161  IRCallArgs[IRCallArgPos++] = V;
1162  }
1163 }
1164 
1165 /// Create a temporary allocation for the purposes of coercion.
1167  llvm::Type *Ty,
1168  CharUnits MinAlign,
1169  const Twine &Name = "tmp") {
1170  // Don't use an alignment that's worse than what LLVM would prefer.
1171  auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(Ty);
1172  CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1173 
1174  return CGF.CreateTempAlloca(Ty, Align, Name + ".coerce");
1175 }
1176 
1177 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
1178 /// accessing some number of bytes out of it, try to gep into the struct to get
1179 /// at its inner goodness. Dive as deep as possible without entering an element
1180 /// with an in-memory size smaller than DstSize.
1181 static Address
1183  llvm::StructType *SrcSTy,
1184  uint64_t DstSize, CodeGenFunction &CGF) {
1185  // We can't dive into a zero-element struct.
1186  if (SrcSTy->getNumElements() == 0) return SrcPtr;
1187 
1188  llvm::Type *FirstElt = SrcSTy->getElementType(0);
1189 
1190  // If the first elt is at least as large as what we're looking for, or if the
1191  // first element is the same size as the whole struct, we can enter it. The
1192  // comparison must be made on the store size and not the alloca size. Using
1193  // the alloca size may overstate the size of the load.
1194  uint64_t FirstEltSize =
1195  CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
1196  if (FirstEltSize < DstSize &&
1197  FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
1198  return SrcPtr;
1199 
1200  // GEP into the first element.
1201  SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
1202 
1203  // If the first element is a struct, recurse.
1204  llvm::Type *SrcTy = SrcPtr.getElementType();
1205  if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
1206  return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
1207 
1208  return SrcPtr;
1209 }
1210 
1211 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1212 /// are either integers or pointers. This does a truncation of the value if it
1213 /// is too large or a zero extension if it is too small.
1214 ///
1215 /// This behaves as if the value were coerced through memory, so on big-endian
1216 /// targets the high bits are preserved in a truncation, while little-endian
1217 /// targets preserve the low bits.
1218 static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
1219  llvm::Type *Ty,
1220  CodeGenFunction &CGF) {
1221  if (Val->getType() == Ty)
1222  return Val;
1223 
1224  if (isa<llvm::PointerType>(Val->getType())) {
1225  // If this is Pointer->Pointer avoid conversion to and from int.
1226  if (isa<llvm::PointerType>(Ty))
1227  return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
1228 
1229  // Convert the pointer to an integer so we can play with its width.
1230  Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
1231  }
1232 
1233  llvm::Type *DestIntTy = Ty;
1234  if (isa<llvm::PointerType>(DestIntTy))
1235  DestIntTy = CGF.IntPtrTy;
1236 
1237  if (Val->getType() != DestIntTy) {
1238  const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1239  if (DL.isBigEndian()) {
1240  // Preserve the high bits on big-endian targets.
1241  // That is what memory coercion does.
1242  uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1243  uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1244 
1245  if (SrcSize > DstSize) {
1246  Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1247  Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1248  } else {
1249  Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1250  Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1251  }
1252  } else {
1253  // Little-endian targets preserve the low bits. No shifts required.
1254  Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1255  }
1256  }
1257 
1258  if (isa<llvm::PointerType>(Ty))
1259  Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1260  return Val;
1261 }
1262 
1263 
1264 
1265 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1266 /// a pointer to an object of type \arg Ty, known to be aligned to
1267 /// \arg SrcAlign bytes.
1268 ///
1269 /// This safely handles the case when the src type is smaller than the
1270 /// destination type; in this situation the values of bits which not
1271 /// present in the src are undefined.
1272 static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
1273  CodeGenFunction &CGF) {
1274  llvm::Type *SrcTy = Src.getElementType();
1275 
1276  // If SrcTy and Ty are the same, just do a load.
1277  if (SrcTy == Ty)
1278  return CGF.Builder.CreateLoad(Src);
1279 
1280  llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
1281 
1282  if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1283  Src = EnterStructPointerForCoercedAccess(Src, SrcSTy,
1284  DstSize.getFixedValue(), CGF);
1285  SrcTy = Src.getElementType();
1286  }
1287 
1288  llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1289 
1290  // If the source and destination are integer or pointer types, just do an
1291  // extension or truncation to the desired type.
1292  if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1293  (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
1294  llvm::Value *Load = CGF.Builder.CreateLoad(Src);
1295  return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1296  }
1297 
1298  // If load is legal, just bitcast the src pointer.
1299  if (!SrcSize.isScalable() && !DstSize.isScalable() &&
1300  SrcSize.getFixedValue() >= DstSize.getFixedValue()) {
1301  // Generally SrcSize is never greater than DstSize, since this means we are
1302  // losing bits. However, this can happen in cases where the structure has
1303  // additional padding, for example due to a user specified alignment.
1304  //
1305  // FIXME: Assert that we aren't truncating non-padding bits when have access
1306  // to that information.
1307  Src = Src.withElementType(Ty);
1308  return CGF.Builder.CreateLoad(Src);
1309  }
1310 
1311  // If coercing a fixed vector to a scalable vector for ABI compatibility, and
1312  // the types match, use the llvm.vector.insert intrinsic to perform the
1313  // conversion.
1314  if (auto *ScalableDstTy = dyn_cast<llvm::ScalableVectorType>(Ty)) {
1315  if (auto *FixedSrcTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
1316  // If we are casting a fixed i8 vector to a scalable i1 predicate
1317  // vector, use a vector insert and bitcast the result.
1318  if (ScalableDstTy->getElementType()->isIntegerTy(1) &&
1319  ScalableDstTy->getElementCount().isKnownMultipleOf(8) &&
1320  FixedSrcTy->getElementType()->isIntegerTy(8)) {
1321  ScalableDstTy = llvm::ScalableVectorType::get(
1322  FixedSrcTy->getElementType(),
1323  ScalableDstTy->getElementCount().getKnownMinValue() / 8);
1324  }
1325  if (ScalableDstTy->getElementType() == FixedSrcTy->getElementType()) {
1326  auto *Load = CGF.Builder.CreateLoad(Src);
1327  auto *UndefVec = llvm::UndefValue::get(ScalableDstTy);
1328  auto *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
1329  llvm::Value *Result = CGF.Builder.CreateInsertVector(
1330  ScalableDstTy, UndefVec, Load, Zero, "cast.scalable");
1331  if (ScalableDstTy != Ty)
1332  Result = CGF.Builder.CreateBitCast(Result, Ty);
1333  return Result;
1334  }
1335  }
1336  }
1337 
1338  // Otherwise do coercion through memory. This is stupid, but simple.
1339  RawAddress Tmp =
1340  CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment(), Src.getName());
1341  CGF.Builder.CreateMemCpy(
1342  Tmp.getPointer(), Tmp.getAlignment().getAsAlign(),
1343  Src.emitRawPointer(CGF), Src.getAlignment().getAsAlign(),
1344  llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize.getKnownMinValue()));
1345  return CGF.Builder.CreateLoad(Tmp);
1346 }
1347 
1348 // Function to store a first-class aggregate into memory. We prefer to
1349 // store the elements rather than the aggregate to be more friendly to
1350 // fast-isel.
1351 // FIXME: Do we need to recurse here?
1352 void CodeGenFunction::EmitAggregateStore(llvm::Value *Val, Address Dest,
1353  bool DestIsVolatile) {
1354  // Prefer scalar stores to first-class aggregate stores.
1355  if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val->getType())) {
1356  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1357  Address EltPtr = Builder.CreateStructGEP(Dest, i);
1358  llvm::Value *Elt = Builder.CreateExtractValue(Val, i);
1359  Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
1360  }
1361  } else {
1362  Builder.CreateStore(Val, Dest, DestIsVolatile);
1363  }
1364 }
1365 
1366 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1367 /// where the source and destination may have different types. The
1368 /// destination is known to be aligned to \arg DstAlign bytes.
1369 ///
1370 /// This safely handles the case when the src type is larger than the
1371 /// destination type; the upper bits of the src will be lost.
1372 static void CreateCoercedStore(llvm::Value *Src,
1373  Address Dst,
1374  bool DstIsVolatile,
1375  CodeGenFunction &CGF) {
1376  llvm::Type *SrcTy = Src->getType();
1377  llvm::Type *DstTy = Dst.getElementType();
1378  if (SrcTy == DstTy) {
1379  CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1380  return;
1381  }
1382 
1383  llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1384 
1385  if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1386  Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy,
1387  SrcSize.getFixedValue(), CGF);
1388  DstTy = Dst.getElementType();
1389  }
1390 
1391  llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy);
1392  llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy);
1393  if (SrcPtrTy && DstPtrTy &&
1394  SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) {
1395  Src = CGF.Builder.CreateAddrSpaceCast(Src, DstTy);
1396  CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1397  return;
1398  }
1399 
1400  // If the source and destination are integer or pointer types, just do an
1401  // extension or truncation to the desired type.
1402  if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1403  (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1404  Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1405  CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1406  return;
1407  }
1408 
1409  llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
1410 
1411  // If store is legal, just bitcast the src pointer.
1412  if (isa<llvm::ScalableVectorType>(SrcTy) ||
1413  isa<llvm::ScalableVectorType>(DstTy) ||
1414  SrcSize.getFixedValue() <= DstSize.getFixedValue()) {
1415  Dst = Dst.withElementType(SrcTy);
1416  CGF.EmitAggregateStore(Src, Dst, DstIsVolatile);
1417  } else {
1418  // Otherwise do coercion through memory. This is stupid, but
1419  // simple.
1420 
1421  // Generally SrcSize is never greater than DstSize, since this means we are
1422  // losing bits. However, this can happen in cases where the structure has
1423  // additional padding, for example due to a user specified alignment.
1424  //
1425  // FIXME: Assert that we aren't truncating non-padding bits when have access
1426  // to that information.
1427  RawAddress Tmp =
1428  CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1429  CGF.Builder.CreateStore(Src, Tmp);
1430  CGF.Builder.CreateMemCpy(
1431  Dst.emitRawPointer(CGF), Dst.getAlignment().getAsAlign(),
1432  Tmp.getPointer(), Tmp.getAlignment().getAsAlign(),
1433  llvm::ConstantInt::get(CGF.IntPtrTy, DstSize.getFixedValue()));
1434  }
1435 }
1436 
1438  const ABIArgInfo &info) {
1439  if (unsigned offset = info.getDirectOffset()) {
1440  addr = addr.withElementType(CGF.Int8Ty);
1441  addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1442  CharUnits::fromQuantity(offset));
1443  addr = addr.withElementType(info.getCoerceToType());
1444  }
1445  return addr;
1446 }
1447 
1448 namespace {
1449 
1450 /// Encapsulates information about the way function arguments from
1451 /// CGFunctionInfo should be passed to actual LLVM IR function.
1452 class ClangToLLVMArgMapping {
1453  static const unsigned InvalidIndex = ~0U;
1454  unsigned InallocaArgNo;
1455  unsigned SRetArgNo;
1456  unsigned TotalIRArgs;
1457 
1458  /// Arguments of LLVM IR function corresponding to single Clang argument.
1459  struct IRArgs {
1460  unsigned PaddingArgIndex;
1461  // Argument is expanded to IR arguments at positions
1462  // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1463  unsigned FirstArgIndex;
1464  unsigned NumberOfArgs;
1465 
1466  IRArgs()
1467  : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1468  NumberOfArgs(0) {}
1469  };
1470 
1471  SmallVector<IRArgs, 8> ArgInfo;
1472 
1473 public:
1474  ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1475  bool OnlyRequiredArgs = false)
1476  : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1477  ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1478  construct(Context, FI, OnlyRequiredArgs);
1479  }
1480 
1481  bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1482  unsigned getInallocaArgNo() const {
1483  assert(hasInallocaArg());
1484  return InallocaArgNo;
1485  }
1486 
1487  bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1488  unsigned getSRetArgNo() const {
1489  assert(hasSRetArg());
1490  return SRetArgNo;
1491  }
1492 
1493  unsigned totalIRArgs() const { return TotalIRArgs; }
1494 
1495  bool hasPaddingArg(unsigned ArgNo) const {
1496  assert(ArgNo < ArgInfo.size());
1497  return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1498  }
1499  unsigned getPaddingArgNo(unsigned ArgNo) const {
1500  assert(hasPaddingArg(ArgNo));
1501  return ArgInfo[ArgNo].PaddingArgIndex;
1502  }
1503 
1504  /// Returns index of first IR argument corresponding to ArgNo, and their
1505  /// quantity.
1506  std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1507  assert(ArgNo < ArgInfo.size());
1508  return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1509  ArgInfo[ArgNo].NumberOfArgs);
1510  }
1511 
1512 private:
1513  void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1514  bool OnlyRequiredArgs);
1515 };
1516 
1517 void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1518  const CGFunctionInfo &FI,
1519  bool OnlyRequiredArgs) {
1520  unsigned IRArgNo = 0;
1521  bool SwapThisWithSRet = false;
1522  const ABIArgInfo &RetAI = FI.getReturnInfo();
1523 
1524  if (RetAI.getKind() == ABIArgInfo::Indirect) {
1525  SwapThisWithSRet = RetAI.isSRetAfterThis();
1526  SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1527  }
1528 
1529  unsigned ArgNo = 0;
1530  unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1531  for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1532  ++I, ++ArgNo) {
1533  assert(I != FI.arg_end());
1534  QualType ArgType = I->type;
1535  const ABIArgInfo &AI = I->info;
1536  // Collect data about IR arguments corresponding to Clang argument ArgNo.
1537  auto &IRArgs = ArgInfo[ArgNo];
1538 
1539  if (AI.getPaddingType())
1540  IRArgs.PaddingArgIndex = IRArgNo++;
1541 
1542  switch (AI.getKind()) {
1543  case ABIArgInfo::Extend:
1544  case ABIArgInfo::Direct: {
1545  // FIXME: handle sseregparm someday...
1546  llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1547  if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1548  IRArgs.NumberOfArgs = STy->getNumElements();
1549  } else {
1550  IRArgs.NumberOfArgs = 1;
1551  }
1552  break;
1553  }
1554  case ABIArgInfo::Indirect:
1556  IRArgs.NumberOfArgs = 1;
1557  break;
1558  case ABIArgInfo::Ignore:
1559  case ABIArgInfo::InAlloca:
1560  // ignore and inalloca doesn't have matching LLVM parameters.
1561  IRArgs.NumberOfArgs = 0;
1562  break;
1564  IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1565  break;
1566  case ABIArgInfo::Expand:
1567  IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1568  break;
1569  }
1570 
1571  if (IRArgs.NumberOfArgs > 0) {
1572  IRArgs.FirstArgIndex = IRArgNo;
1573  IRArgNo += IRArgs.NumberOfArgs;
1574  }
1575 
1576  // Skip over the sret parameter when it comes second. We already handled it
1577  // above.
1578  if (IRArgNo == 1 && SwapThisWithSRet)
1579  IRArgNo++;
1580  }
1581  assert(ArgNo == ArgInfo.size());
1582 
1583  if (FI.usesInAlloca())
1584  InallocaArgNo = IRArgNo++;
1585 
1586  TotalIRArgs = IRArgNo;
1587 }
1588 } // namespace
1589 
1590 /***/
1591 
1593  const auto &RI = FI.getReturnInfo();
1594  return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
1595 }
1596 
1598  const auto &RI = FI.getReturnInfo();
1599  return RI.getInReg();
1600 }
1601 
1603  return ReturnTypeUsesSRet(FI) &&
1605 }
1606 
1608  if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1609  switch (BT->getKind()) {
1610  default:
1611  return false;
1612  case BuiltinType::Float:
1614  case BuiltinType::Double:
1616  case BuiltinType::LongDouble:
1618  }
1619  }
1620 
1621  return false;
1622 }
1623 
1625  if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1626  if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1627  if (BT->getKind() == BuiltinType::LongDouble)
1629  }
1630  }
1631 
1632  return false;
1633 }
1634 
1636  const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1637  return GetFunctionType(FI);
1638 }
1639 
1640 llvm::FunctionType *
1642 
1643  bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1644  (void)Inserted;
1645  assert(Inserted && "Recursively being processed?");
1646 
1647  llvm::Type *resultType = nullptr;
1648  const ABIArgInfo &retAI = FI.getReturnInfo();
1649  switch (retAI.getKind()) {
1650  case ABIArgInfo::Expand:
1652  llvm_unreachable("Invalid ABI kind for return argument");
1653 
1654  case ABIArgInfo::Extend:
1655  case ABIArgInfo::Direct:
1656  resultType = retAI.getCoerceToType();
1657  break;
1658 
1659  case ABIArgInfo::InAlloca:
1660  if (retAI.getInAllocaSRet()) {
1661  // sret things on win32 aren't void, they return the sret pointer.
1662  QualType ret = FI.getReturnType();
1663  unsigned addressSpace = CGM.getTypes().getTargetAddressSpace(ret);
1664  resultType = llvm::PointerType::get(getLLVMContext(), addressSpace);
1665  } else {
1666  resultType = llvm::Type::getVoidTy(getLLVMContext());
1667  }
1668  break;
1669 
1670  case ABIArgInfo::Indirect:
1671  case ABIArgInfo::Ignore:
1672  resultType = llvm::Type::getVoidTy(getLLVMContext());
1673  break;
1674 
1676  resultType = retAI.getUnpaddedCoerceAndExpandType();
1677  break;
1678  }
1679 
1680  ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1681  SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1682 
1683  // Add type for sret argument.
1684  if (IRFunctionArgs.hasSRetArg()) {
1685  QualType Ret = FI.getReturnType();
1686  unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(Ret);
1687  ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1688  llvm::PointerType::get(getLLVMContext(), AddressSpace);
1689  }
1690 
1691  // Add type for inalloca argument.
1692  if (IRFunctionArgs.hasInallocaArg())
1693  ArgTypes[IRFunctionArgs.getInallocaArgNo()] =
1694  llvm::PointerType::getUnqual(getLLVMContext());
1695 
1696  // Add in all of the required arguments.
1697  unsigned ArgNo = 0;
1699  ie = it + FI.getNumRequiredArgs();
1700  for (; it != ie; ++it, ++ArgNo) {
1701  const ABIArgInfo &ArgInfo = it->info;
1702 
1703  // Insert a padding type to ensure proper alignment.
1704  if (IRFunctionArgs.hasPaddingArg(ArgNo))
1705  ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1706  ArgInfo.getPaddingType();
1707 
1708  unsigned FirstIRArg, NumIRArgs;
1709  std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1710 
1711  switch (ArgInfo.getKind()) {
1712  case ABIArgInfo::Ignore:
1713  case ABIArgInfo::InAlloca:
1714  assert(NumIRArgs == 0);
1715  break;
1716 
1717  case ABIArgInfo::Indirect:
1718  assert(NumIRArgs == 1);
1719  // indirect arguments are always on the stack, which is alloca addr space.
1720  ArgTypes[FirstIRArg] = llvm::PointerType::get(
1721  getLLVMContext(), CGM.getDataLayout().getAllocaAddrSpace());
1722  break;
1724  assert(NumIRArgs == 1);
1725  ArgTypes[FirstIRArg] = llvm::PointerType::get(
1726  getLLVMContext(), ArgInfo.getIndirectAddrSpace());
1727  break;
1728  case ABIArgInfo::Extend:
1729  case ABIArgInfo::Direct: {
1730  // Fast-isel and the optimizer generally like scalar values better than
1731  // FCAs, so we flatten them if this is safe to do for this argument.
1732  llvm::Type *argType = ArgInfo.getCoerceToType();
1733  llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1734  if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1735  assert(NumIRArgs == st->getNumElements());
1736  for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1737  ArgTypes[FirstIRArg + i] = st->getElementType(i);
1738  } else {
1739  assert(NumIRArgs == 1);
1740  ArgTypes[FirstIRArg] = argType;
1741  }
1742  break;
1743  }
1744 
1746  auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1747  for (auto *EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1748  *ArgTypesIter++ = EltTy;
1749  }
1750  assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1751  break;
1752  }
1753 
1754  case ABIArgInfo::Expand:
1755  auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1756  getExpandedTypes(it->type, ArgTypesIter);
1757  assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1758  break;
1759  }
1760  }
1761 
1762  bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1763  assert(Erased && "Not in set?");
1764 
1765  return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1766 }
1767 
1769  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1770  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1771 
1772  if (!isFuncTypeConvertible(FPT))
1773  return llvm::StructType::get(getLLVMContext());
1774 
1775  return GetFunctionType(GD);
1776 }
1777 
1779  llvm::AttrBuilder &FuncAttrs,
1780  const FunctionProtoType *FPT) {
1781  if (!FPT)
1782  return;
1783 
1785  FPT->isNothrow())
1786  FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1787 
1788  unsigned SMEBits = FPT->getAArch64SMEAttributes();
1790  FuncAttrs.addAttribute("aarch64_pstate_sm_enabled");
1792  FuncAttrs.addAttribute("aarch64_pstate_sm_compatible");
1793 
1794  // ZA
1796  FuncAttrs.addAttribute("aarch64_preserves_za");
1798  FuncAttrs.addAttribute("aarch64_in_za");
1800  FuncAttrs.addAttribute("aarch64_out_za");
1802  FuncAttrs.addAttribute("aarch64_inout_za");
1803 
1804  // ZT0
1806  FuncAttrs.addAttribute("aarch64_preserves_zt0");
1808  FuncAttrs.addAttribute("aarch64_in_zt0");
1810  FuncAttrs.addAttribute("aarch64_out_zt0");
1812  FuncAttrs.addAttribute("aarch64_inout_zt0");
1813 }
1814 
1815 static void AddAttributesFromOMPAssumes(llvm::AttrBuilder &FuncAttrs,
1816  const Decl *Callee) {
1817  if (!Callee)
1818  return;
1819 
1821 
1822  for (const OMPAssumeAttr *AA : Callee->specific_attrs<OMPAssumeAttr>())
1823  AA->getAssumption().split(Attrs, ",");
1824 
1825  if (!Attrs.empty())
1826  FuncAttrs.addAttribute(llvm::AssumptionAttrKey,
1827  llvm::join(Attrs.begin(), Attrs.end(), ","));
1828 }
1829 
1831  QualType ReturnType) const {
1832  // We can't just discard the return value for a record type with a
1833  // complex destructor or a non-trivially copyable type.
1834  if (const RecordType *RT =
1835  ReturnType.getCanonicalType()->getAs<RecordType>()) {
1836  if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1837  return ClassDecl->hasTrivialDestructor();
1838  }
1839  return ReturnType.isTriviallyCopyableType(Context);
1840 }
1841 
1842 static bool HasStrictReturn(const CodeGenModule &Module, QualType RetTy,
1843  const Decl *TargetDecl) {
1844  // As-is msan can not tolerate noundef mismatch between caller and
1845  // implementation. Mismatch is possible for e.g. indirect calls from C-caller
1846  // into C++. Such mismatches lead to confusing false reports. To avoid
1847  // expensive workaround on msan we enforce initialization event in uncommon
1848  // cases where it's allowed.
1849  if (Module.getLangOpts().Sanitize.has(SanitizerKind::Memory))
1850  return true;
1851  // C++ explicitly makes returning undefined values UB. C's rule only applies
1852  // to used values, so we never mark them noundef for now.
1853  if (!Module.getLangOpts().CPlusPlus)
1854  return false;
1855  if (TargetDecl) {
1856  if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl)) {
1857  if (FDecl->isExternC())
1858  return false;
1859  } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl)) {
1860  // Function pointer.
1861  if (VDecl->isExternC())
1862  return false;
1863  }
1864  }
1865 
1866  // We don't want to be too aggressive with the return checking, unless
1867  // it's explicit in the code opts or we're using an appropriate sanitizer.
1868  // Try to respect what the programmer intended.
1869  return Module.getCodeGenOpts().StrictReturn ||
1870  !Module.MayDropFunctionReturn(Module.getContext(), RetTy) ||
1871  Module.getLangOpts().Sanitize.has(SanitizerKind::Return);
1872 }
1873 
1874 static llvm::fp::FPAccuracy convertFPAccuracy(StringRef FPAccuracyStr) {
1875  return llvm::StringSwitch<llvm::fp::FPAccuracy>(FPAccuracyStr)
1876  .Case("high", llvm::fp::FPAccuracy::High)
1877  .Case("medium", llvm::fp::FPAccuracy::Medium)
1878  .Case("low", llvm::fp::FPAccuracy::Low)
1879  .Case("sycl", llvm::fp::FPAccuracy::SYCL)
1880  .Case("cuda", llvm::fp::FPAccuracy::CUDA);
1881 }
1882 
1883 static int32_t convertFPAccuracyToAspect(StringRef FPAccuracyStr) {
1884  assert(FPAccuracyStr == "high" || FPAccuracyStr == "medium" ||
1885  FPAccuracyStr == "low" || FPAccuracyStr == "sycl" ||
1886  FPAccuracyStr == "cuda");
1887  return llvm::StringSwitch<int32_t>(FPAccuracyStr)
1893 }
1894 
1895 void CodeGenModule::getDefaultFunctionFPAccuracyAttributes(
1896  StringRef Name, llvm::AttrBuilder &FuncAttrs, llvm::Metadata *&MD,
1897  unsigned ID, const llvm::Type *FuncType) {
1898  // Priority is given to to the accuracy specific to the function.
1899  // So, if the command line is something like this:
1900  // 'clang -fp-accuracy = high -fp-accuracy = low:[sin]'.
1901  // This means, all library functions will have the accuracy 'high'
1902  // except 'sin', which should have an accuracy value of 'low'.
1903  // To ensure that, first check if Name has a required accuracy by visiting
1904  // the 'FPAccuracyFuncMap'; if no accuracy is mapped to Name (FuncAttrs
1905  // is empty), then set its accuracy from the TU's accuracy value.
1906  if (!getLangOpts().FPAccuracyFuncMap.empty()) {
1907  auto FuncMapIt = getLangOpts().FPAccuracyFuncMap.find(Name.str());
1908  if (FuncMapIt != getLangOpts().FPAccuracyFuncMap.end()) {
1909  StringRef FPAccuracyVal = llvm::fp::getAccuracyForFPBuiltin(
1910  ID, FuncType, convertFPAccuracy(FuncMapIt->second));
1911  assert(!FPAccuracyVal.empty() && "A valid accuracy value is expected");
1912  FuncAttrs.addAttribute("fpbuiltin-max-error", FPAccuracyVal);
1913  MD = llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1914  Int32Ty, convertFPAccuracyToAspect(FuncMapIt->second)));
1915  }
1916  }
1917  if (FuncAttrs.attrs().size() == 0)
1918  if (!getLangOpts().FPAccuracyVal.empty()) {
1919  StringRef FPAccuracyVal = llvm::fp::getAccuracyForFPBuiltin(
1920  ID, FuncType, convertFPAccuracy(getLangOpts().FPAccuracyVal));
1921  assert(!FPAccuracyVal.empty() && "A valid accuracy value is expected");
1922  FuncAttrs.addAttribute("fpbuiltin-max-error", FPAccuracyVal);
1923  MD = llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1924  Int32Ty, convertFPAccuracyToAspect(getLangOpts().FPAccuracyVal)));
1925  }
1926 }
1927 
1928 /// Add denormal-fp-math and denormal-fp-math-f32 as appropriate for the
1929 /// requested denormal behavior, accounting for the overriding behavior of the
1930 /// -f32 case.
1931 static void addDenormalModeAttrs(llvm::DenormalMode FPDenormalMode,
1932  llvm::DenormalMode FP32DenormalMode,
1933  llvm::AttrBuilder &FuncAttrs) {
1934  if (FPDenormalMode != llvm::DenormalMode::getDefault())
1935  FuncAttrs.addAttribute("denormal-fp-math", FPDenormalMode.str());
1936 
1937  if (FP32DenormalMode != FPDenormalMode && FP32DenormalMode.isValid())
1938  FuncAttrs.addAttribute("denormal-fp-math-f32", FP32DenormalMode.str());
1939 }
1940 
1941 /// Add default attributes to a function, which have merge semantics under
1942 /// -mlink-builtin-bitcode and should not simply overwrite any existing
1943 /// attributes in the linked library.
1944 static void
1946  llvm::AttrBuilder &FuncAttrs) {
1947  addDenormalModeAttrs(CodeGenOpts.FPDenormalMode, CodeGenOpts.FP32DenormalMode,
1948  FuncAttrs);
1949 }
1950 
1952  StringRef Name, bool HasOptnone, const CodeGenOptions &CodeGenOpts,
1953  const LangOptions &LangOpts, bool AttrOnCallSite,
1954  llvm::AttrBuilder &FuncAttrs) {
1955  // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1956  if (!HasOptnone) {
1957  if (CodeGenOpts.OptimizeSize)
1958  FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1959  if (CodeGenOpts.OptimizeSize == 2)
1960  FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1961  }
1962 
1963  if (CodeGenOpts.DisableRedZone)
1964  FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1965  if (CodeGenOpts.IndirectTlsSegRefs)
1966  FuncAttrs.addAttribute("indirect-tls-seg-refs");
1967  if (CodeGenOpts.NoImplicitFloat)
1968  FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1969 
1970  if (AttrOnCallSite) {
1971  // Attributes that should go on the call site only.
1972  // FIXME: Look for 'BuiltinAttr' on the function rather than re-checking
1973  // the -fno-builtin-foo list.
1974  if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
1975  FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1976  if (!CodeGenOpts.TrapFuncName.empty())
1977  FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1978  } else {
1979  switch (CodeGenOpts.getFramePointer()) {
1981  // This is the default behavior.
1982  break;
1985  FuncAttrs.addAttribute("frame-pointer",
1987  CodeGenOpts.getFramePointer()));
1988  }
1989 
1990  if (CodeGenOpts.LessPreciseFPMAD)
1991  FuncAttrs.addAttribute("less-precise-fpmad", "true");
1992 
1993  if (CodeGenOpts.NullPointerIsValid)
1994  FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
1995 
1997  FuncAttrs.addAttribute("no-trapping-math", "true");
1998 
1999  // TODO: Are these all needed?
2000  // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
2001  if (LangOpts.NoHonorInfs)
2002  FuncAttrs.addAttribute("no-infs-fp-math", "true");
2003  if (LangOpts.NoHonorNaNs)
2004  FuncAttrs.addAttribute("no-nans-fp-math", "true");
2005  if (LangOpts.ApproxFunc)
2006  FuncAttrs.addAttribute("approx-func-fp-math", "true");
2007  if (LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
2008  LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
2009  (LangOpts.getDefaultFPContractMode() ==
2010  LangOptions::FPModeKind::FPM_Fast ||
2011  LangOpts.getDefaultFPContractMode() ==
2012  LangOptions::FPModeKind::FPM_FastHonorPragmas))
2013  FuncAttrs.addAttribute("unsafe-fp-math", "true");
2014  if (CodeGenOpts.SoftFloat)
2015  FuncAttrs.addAttribute("use-soft-float", "true");
2016  FuncAttrs.addAttribute("stack-protector-buffer-size",
2017  llvm::utostr(CodeGenOpts.SSPBufferSize));
2018  if (LangOpts.NoSignedZero)
2019  FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
2020 
2021  // TODO: Reciprocal estimate codegen options should apply to instructions?
2022  const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
2023  if (!Recips.empty())
2024  FuncAttrs.addAttribute("reciprocal-estimates",
2025  llvm::join(Recips, ","));
2026 
2027  if (!CodeGenOpts.PreferVectorWidth.empty() &&
2028  CodeGenOpts.PreferVectorWidth != "none")
2029  FuncAttrs.addAttribute("prefer-vector-width",
2030  CodeGenOpts.PreferVectorWidth);
2031 
2032  if (CodeGenOpts.StackRealignment)
2033  FuncAttrs.addAttribute("stackrealign");
2034  if (CodeGenOpts.Backchain)
2035  FuncAttrs.addAttribute("backchain");
2036  if (CodeGenOpts.EnableSegmentedStacks)
2037  FuncAttrs.addAttribute("split-stack");
2038 
2039  if (CodeGenOpts.SpeculativeLoadHardening)
2040  FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2041 
2042  // Add zero-call-used-regs attribute.
2043  switch (CodeGenOpts.getZeroCallUsedRegs()) {
2044  case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Skip:
2045  FuncAttrs.removeAttribute("zero-call-used-regs");
2046  break;
2047  case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPRArg:
2048  FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr-arg");
2049  break;
2050  case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPR:
2051  FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr");
2052  break;
2053  case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedArg:
2054  FuncAttrs.addAttribute("zero-call-used-regs", "used-arg");
2055  break;
2057  FuncAttrs.addAttribute("zero-call-used-regs", "used");
2058  break;
2059  case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPRArg:
2060  FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr-arg");
2061  break;
2062  case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPR:
2063  FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr");
2064  break;
2065  case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllArg:
2066  FuncAttrs.addAttribute("zero-call-used-regs", "all-arg");
2067  break;
2069  FuncAttrs.addAttribute("zero-call-used-regs", "all");
2070  break;
2071  }
2072  }
2073 
2074  if (LangOpts.assumeFunctionsAreConvergent()) {
2075  // Conservatively, mark all functions and calls in CUDA and OpenCL as
2076  // convergent (meaning, they may call an intrinsically convergent op, such
2077  // as __syncthreads() / barrier(), and so can't have certain optimizations
2078  // applied around them). LLVM will remove this attribute where it safely
2079  // can.
2080  FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2081  }
2082 
2083  // TODO: NoUnwind attribute should be added for other GPU modes HIP,
2084  // OpenMP offload. AFAIK, neither of them support exceptions in device code.
2085  if ((LangOpts.CUDA && LangOpts.CUDAIsDevice) || LangOpts.OpenCL ||
2086  LangOpts.SYCLIsDevice) {
2087  FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2088  }
2089 
2090  for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
2091  StringRef Var, Value;
2092  std::tie(Var, Value) = Attr.split('=');
2093  FuncAttrs.addAttribute(Var, Value);
2094  }
2095 }
2096 
2097 /// Merges `target-features` from \TargetOpts and \F, and sets the result in
2098 /// \FuncAttr
2099 /// * features from \F are always kept
2100 /// * a feature from \TargetOpts is kept if itself and its opposite are absent
2101 /// from \F
2102 static void
2104  const llvm::Function &F,
2105  const TargetOptions &TargetOpts) {
2106  auto FFeatures = F.getFnAttribute("target-features");
2107 
2108  llvm::StringSet<> MergedNames;
2109  SmallVector<StringRef> MergedFeatures;
2110  MergedFeatures.reserve(TargetOpts.Features.size());
2111 
2112  auto AddUnmergedFeatures = [&](auto &&FeatureRange) {
2113  for (StringRef Feature : FeatureRange) {
2114  if (Feature.empty())
2115  continue;
2116  assert(Feature[0] == '+' || Feature[0] == '-');
2117  StringRef Name = Feature.drop_front(1);
2118  bool Merged = !MergedNames.insert(Name).second;
2119  if (!Merged)
2120  MergedFeatures.push_back(Feature);
2121  }
2122  };
2123 
2124  if (FFeatures.isValid())
2125  AddUnmergedFeatures(llvm::split(FFeatures.getValueAsString(), ','));
2126  AddUnmergedFeatures(TargetOpts.Features);
2127 
2128  if (!MergedFeatures.empty()) {
2129  llvm::sort(MergedFeatures);
2130  FuncAttr.addAttribute("target-features", llvm::join(MergedFeatures, ","));
2131  }
2132 }
2133 
2135  llvm::Function &F, const CodeGenOptions &CodeGenOpts,
2136  const LangOptions &LangOpts, const TargetOptions &TargetOpts,
2137  bool WillInternalize) {
2138 
2139  llvm::AttrBuilder FuncAttrs(F.getContext());
2140  // Here we only extract the options that are relevant compared to the version
2141  // from GetCPUAndFeaturesAttributes.
2142  if (!TargetOpts.CPU.empty())
2143  FuncAttrs.addAttribute("target-cpu", TargetOpts.CPU);
2144  if (!TargetOpts.TuneCPU.empty())
2145  FuncAttrs.addAttribute("tune-cpu", TargetOpts.TuneCPU);
2146 
2147  ::getTrivialDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
2148  CodeGenOpts, LangOpts,
2149  /*AttrOnCallSite=*/false, FuncAttrs);
2150 
2151  if (!WillInternalize && F.isInterposable()) {
2152  // Do not promote "dynamic" denormal-fp-math to this translation unit's
2153  // setting for weak functions that won't be internalized. The user has no
2154  // real control for how builtin bitcode is linked, so we shouldn't assume
2155  // later copies will use a consistent mode.
2156  F.addFnAttrs(FuncAttrs);
2157  return;
2158  }
2159 
2160  llvm::AttributeMask AttrsToRemove;
2161 
2162  llvm::DenormalMode DenormModeToMerge = F.getDenormalModeRaw();
2163  llvm::DenormalMode DenormModeToMergeF32 = F.getDenormalModeF32Raw();
2164  llvm::DenormalMode Merged =
2165  CodeGenOpts.FPDenormalMode.mergeCalleeMode(DenormModeToMerge);
2166  llvm::DenormalMode MergedF32 = CodeGenOpts.FP32DenormalMode;
2167 
2168  if (DenormModeToMergeF32.isValid()) {
2169  MergedF32 =
2170  CodeGenOpts.FP32DenormalMode.mergeCalleeMode(DenormModeToMergeF32);
2171  }
2172 
2173  if (Merged == llvm::DenormalMode::getDefault()) {
2174  AttrsToRemove.addAttribute("denormal-fp-math");
2175  } else if (Merged != DenormModeToMerge) {
2176  // Overwrite existing attribute
2177  FuncAttrs.addAttribute("denormal-fp-math",
2178  CodeGenOpts.FPDenormalMode.str());
2179  }
2180 
2181  if (MergedF32 == llvm::DenormalMode::getDefault()) {
2182  AttrsToRemove.addAttribute("denormal-fp-math-f32");
2183  } else if (MergedF32 != DenormModeToMergeF32) {
2184  // Overwrite existing attribute
2185  FuncAttrs.addAttribute("denormal-fp-math-f32",
2186  CodeGenOpts.FP32DenormalMode.str());
2187  }
2188 
2189  F.removeFnAttrs(AttrsToRemove);
2190  addDenormalModeAttrs(Merged, MergedF32, FuncAttrs);
2191 
2192  overrideFunctionFeaturesWithTargetFeatures(FuncAttrs, F, TargetOpts);
2193 
2194  F.addFnAttrs(FuncAttrs);
2195 }
2196 
2197 void CodeGenModule::getTrivialDefaultFunctionAttributes(
2198  StringRef Name, bool HasOptnone, bool AttrOnCallSite,
2199  llvm::AttrBuilder &FuncAttrs) {
2200  ::getTrivialDefaultFunctionAttributes(Name, HasOptnone, getCodeGenOpts(),
2201  getLangOpts(), AttrOnCallSite,
2202  FuncAttrs);
2203 }
2204 
2205 void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
2206  bool HasOptnone,
2207  bool AttrOnCallSite,
2208  llvm::AttrBuilder &FuncAttrs) {
2209  getTrivialDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite,
2210  FuncAttrs);
2211  // If we're just getting the default, get the default values for mergeable
2212  // attributes.
2213  if (!AttrOnCallSite)
2214  addMergableDefaultFunctionAttributes(CodeGenOpts, FuncAttrs);
2215 }
2216 
2218  llvm::AttrBuilder &attrs) {
2219  getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
2220  /*for call*/ false, attrs);
2221  GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
2222 }
2223 
2224 static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
2225  const LangOptions &LangOpts,
2226  const NoBuiltinAttr *NBA = nullptr) {
2227  auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
2228  SmallString<32> AttributeName;
2229  AttributeName += "no-builtin-";
2230  AttributeName += BuiltinName;
2231  FuncAttrs.addAttribute(AttributeName);
2232  };
2233 
2234  // First, handle the language options passed through -fno-builtin.
2235  if (LangOpts.NoBuiltin) {
2236  // -fno-builtin disables them all.
2237  FuncAttrs.addAttribute("no-builtins");
2238  return;
2239  }
2240 
2241  // Then, add attributes for builtins specified through -fno-builtin-<name>.
2242  llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
2243 
2244  // Now, let's check the __attribute__((no_builtin("...")) attribute added to
2245  // the source.
2246  if (!NBA)
2247  return;
2248 
2249  // If there is a wildcard in the builtin names specified through the
2250  // attribute, disable them all.
2251  if (llvm::is_contained(NBA->builtinNames(), "*")) {
2252  FuncAttrs.addAttribute("no-builtins");
2253  return;
2254  }
2255 
2256  // And last, add the rest of the builtin names.
2257  llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
2258 }
2259 
2260 static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types,
2261  const llvm::DataLayout &DL, const ABIArgInfo &AI,
2262  bool CheckCoerce = true) {
2263  llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
2264  if (AI.getKind() == ABIArgInfo::Indirect ||
2266  return true;
2267  if (AI.getKind() == ABIArgInfo::Extend)
2268  return true;
2269  if (!DL.typeSizeEqualsStoreSize(Ty))
2270  // TODO: This will result in a modest amount of values not marked noundef
2271  // when they could be. We care about values that *invisibly* contain undef
2272  // bits from the perspective of LLVM IR.
2273  return false;
2274  if (CheckCoerce && AI.canHaveCoerceToType()) {
2275  llvm::Type *CoerceTy = AI.getCoerceToType();
2276  if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
2277  DL.getTypeSizeInBits(Ty)))
2278  // If we're coercing to a type with a greater size than the canonical one,
2279  // we're introducing new undef bits.
2280  // Coercing to a type of smaller or equal size is ok, as we know that
2281  // there's no internal padding (typeSizeEqualsStoreSize).
2282  return false;
2283  }
2284  if (QTy->isBitIntType())
2285  return true;
2286  if (QTy->isReferenceType())
2287  return true;
2288  if (QTy->isNullPtrType())
2289  return false;
2290  if (QTy->isMemberPointerType())
2291  // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
2292  // now, never mark them.
2293  return false;
2294  if (QTy->isScalarType()) {
2295  if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
2296  return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
2297  return true;
2298  }
2299  if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
2300  return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
2301  if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
2302  return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
2303  if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
2304  return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
2305 
2306  // TODO: Some structs may be `noundef`, in specific situations.
2307  return false;
2308 }
2309 
2310 /// Check if the argument of a function has maybe_undef attribute.
2311 static bool IsArgumentMaybeUndef(const Decl *TargetDecl,
2312  unsigned NumRequiredArgs, unsigned ArgNo) {
2313  const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
2314  if (!FD)
2315  return false;
2316 
2317  // Assume variadic arguments do not have maybe_undef attribute.
2318  if (ArgNo >= NumRequiredArgs)
2319  return false;
2320 
2321  // Check if argument has maybe_undef attribute.
2322  if (ArgNo < FD->getNumParams()) {
2323  const ParmVarDecl *Param = FD->getParamDecl(ArgNo);
2324  if (Param && Param->hasAttr<MaybeUndefAttr>())
2325  return true;
2326  }
2327 
2328  return false;
2329 }
2330 
2331 /// Test if it's legal to apply nofpclass for the given parameter type and it's
2332 /// lowered IR type.
2333 static bool canApplyNoFPClass(const ABIArgInfo &AI, QualType ParamType,
2334  bool IsReturn) {
2335  // Should only apply to FP types in the source, not ABI promoted.
2336  if (!ParamType->hasFloatingRepresentation())
2337  return false;
2338 
2339  // The promoted-to IR type also needs to support nofpclass.
2340  llvm::Type *IRTy = AI.getCoerceToType();
2341  if (llvm::AttributeFuncs::isNoFPClassCompatibleType(IRTy))
2342  return true;
2343 
2344  if (llvm::StructType *ST = dyn_cast<llvm::StructType>(IRTy)) {
2345  return !IsReturn && AI.getCanBeFlattened() &&
2346  llvm::all_of(ST->elements(), [](llvm::Type *Ty) {
2347  return llvm::AttributeFuncs::isNoFPClassCompatibleType(Ty);
2348  });
2349  }
2350 
2351  return false;
2352 }
2353 
2354 /// Return the nofpclass mask that can be applied to floating-point parameters.
2355 static llvm::FPClassTest getNoFPClassTestMask(const LangOptions &LangOpts) {
2356  llvm::FPClassTest Mask = llvm::fcNone;
2357  if (LangOpts.NoHonorInfs)
2358  Mask |= llvm::fcInf;
2359  if (LangOpts.NoHonorNaNs)
2360  Mask |= llvm::fcNan;
2361  return Mask;
2362 }
2363 
2365  CGCalleeInfo CalleeInfo,
2366  llvm::AttributeList &Attrs) {
2367  if (Attrs.getMemoryEffects().getModRef() == llvm::ModRefInfo::NoModRef) {
2368  Attrs = Attrs.removeFnAttribute(getLLVMContext(), llvm::Attribute::Memory);
2369  llvm::Attribute MemoryAttr = llvm::Attribute::getWithMemoryEffects(
2370  getLLVMContext(), llvm::MemoryEffects::writeOnly());
2371  Attrs = Attrs.addFnAttribute(getLLVMContext(), MemoryAttr);
2372  }
2373 }
2374 
2375 /// Construct the IR attribute list of a function or call.
2376 ///
2377 /// When adding an attribute, please consider where it should be handled:
2378 ///
2379 /// - getDefaultFunctionAttributes is for attributes that are essentially
2380 /// part of the global target configuration (but perhaps can be
2381 /// overridden on a per-function basis). Adding attributes there
2382 /// will cause them to also be set in frontends that build on Clang's
2383 /// target-configuration logic, as well as for code defined in library
2384 /// modules such as CUDA's libdevice.
2385 ///
2386 /// - ConstructAttributeList builds on top of getDefaultFunctionAttributes
2387 /// and adds declaration-specific, convention-specific, and
2388 /// frontend-specific logic. The last is of particular importance:
2389 /// attributes that restrict how the frontend generates code must be
2390 /// added here rather than getDefaultFunctionAttributes.
2391 ///
2393  const CGFunctionInfo &FI,
2394  CGCalleeInfo CalleeInfo,
2395  llvm::AttributeList &AttrList,
2396  unsigned &CallingConv,
2397  bool AttrOnCallSite, bool IsThunk) {
2398  llvm::AttrBuilder FuncAttrs(getLLVMContext());
2399  llvm::AttrBuilder RetAttrs(getLLVMContext());
2400 
2401  // Collect function IR attributes from the CC lowering.
2402  // We'll collect the paramete and result attributes later.
2404  if (FI.isNoReturn())
2405  FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2406  if (FI.isCmseNSCall())
2407  FuncAttrs.addAttribute("cmse_nonsecure_call");
2408 
2409  // Collect function IR attributes from the callee prototype if we have one.
2411  CalleeInfo.getCalleeFunctionProtoType());
2412 
2413  const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
2414 
2415  // Attach assumption attributes to the declaration. If this is a call
2416  // site, attach assumptions from the caller to the call as well.
2417  AddAttributesFromOMPAssumes(FuncAttrs, TargetDecl);
2418 
2419  bool HasOptnone = false;
2420  // The NoBuiltinAttr attached to the target FunctionDecl.
2421  const NoBuiltinAttr *NBA = nullptr;
2422 
2423  // Some ABIs may result in additional accesses to arguments that may
2424  // otherwise not be present.
2425  auto AddPotentialArgAccess = [&]() {
2426  llvm::Attribute A = FuncAttrs.getAttribute(llvm::Attribute::Memory);
2427  if (A.isValid())
2428  FuncAttrs.addMemoryAttr(A.getMemoryEffects() |
2429  llvm::MemoryEffects::argMemOnly());
2430  };
2431 
2432  // Collect function IR attributes based on declaration-specific
2433  // information.
2434  // FIXME: handle sseregparm someday...
2435  if (TargetDecl) {
2436  if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
2437  FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2438  if (TargetDecl->hasAttr<NoThrowAttr>())
2439  FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2440  if (TargetDecl->hasAttr<NoReturnAttr>())
2441  FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2442  if (TargetDecl->hasAttr<ColdAttr>())
2443  FuncAttrs.addAttribute(llvm::Attribute::Cold);
2444  if (TargetDecl->hasAttr<HotAttr>())
2445  FuncAttrs.addAttribute(llvm::Attribute::Hot);
2446  if (TargetDecl->hasAttr<NoDuplicateAttr>())
2447  FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
2448  if (TargetDecl->hasAttr<ConvergentAttr>())
2449  FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2450 
2451  if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2453  getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
2454  if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2455  // A sane operator new returns a non-aliasing pointer.
2456  auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
2457  if (getCodeGenOpts().AssumeSaneOperatorNew &&
2458  (Kind == OO_New || Kind == OO_Array_New))
2459  RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2460  }
2461  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
2462  const bool IsVirtualCall = MD && MD->isVirtual();
2463  // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2464  // virtual function. These attributes are not inherited by overloads.
2465  if (!(AttrOnCallSite && IsVirtualCall)) {
2466  if (Fn->isNoReturn())
2467  FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2468  NBA = Fn->getAttr<NoBuiltinAttr>();
2469  }
2470  }
2471 
2472  if (isa<FunctionDecl>(TargetDecl) || isa<VarDecl>(TargetDecl)) {
2473  // Only place nomerge attribute on call sites, never functions. This
2474  // allows it to work on indirect virtual function calls.
2475  if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2476  FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2477  }
2478 
2479  // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
2480  if (TargetDecl->hasAttr<ConstAttr>()) {
2481  FuncAttrs.addMemoryAttr(llvm::MemoryEffects::none());
2482  FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2483  // gcc specifies that 'const' functions have greater restrictions than
2484  // 'pure' functions, so they also cannot have infinite loops.
2485  FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2486  } else if (TargetDecl->hasAttr<PureAttr>()) {
2487  FuncAttrs.addMemoryAttr(llvm::MemoryEffects::readOnly());
2488  FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2489  // gcc specifies that 'pure' functions cannot have infinite loops.
2490  FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2491  } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
2492  FuncAttrs.addMemoryAttr(llvm::MemoryEffects::inaccessibleOrArgMemOnly());
2493  FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2494  }
2495  if (TargetDecl->hasAttr<RestrictAttr>())
2496  RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2497  if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
2498  !CodeGenOpts.NullPointerIsValid)
2499  RetAttrs.addAttribute(llvm::Attribute::NonNull);
2500  if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
2501  FuncAttrs.addAttribute("no_caller_saved_registers");
2502  if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
2503  FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2504  if (TargetDecl->hasAttr<LeafAttr>())
2505  FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
2506 
2507  HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
2508  if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
2509  std::optional<unsigned> NumElemsParam;
2510  if (AllocSize->getNumElemsParam().isValid())
2511  NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
2512  FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
2513  NumElemsParam);
2514  }
2515 
2516  if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
2517  if (getLangOpts().OpenCLVersion <= 120) {
2518  // OpenCL v1.2 Work groups are always uniform
2519  FuncAttrs.addAttribute("uniform-work-group-size", "true");
2520  } else {
2521  // OpenCL v2.0 Work groups may be whether uniform or not.
2522  // '-cl-uniform-work-group-size' compile option gets a hint
2523  // to the compiler that the global work-size be a multiple of
2524  // the work-group size specified to clEnqueueNDRangeKernel
2525  // (i.e. work groups are uniform).
2526  FuncAttrs.addAttribute(
2527  "uniform-work-group-size",
2528  llvm::toStringRef(getLangOpts().OffloadUniformBlock));
2529  }
2530  }
2531 
2532  if (TargetDecl->hasAttr<CUDAGlobalAttr>() &&
2533  getLangOpts().OffloadUniformBlock)
2534  FuncAttrs.addAttribute("uniform-work-group-size", "true");
2535 
2536  if (TargetDecl->hasAttr<ArmLocallyStreamingAttr>())
2537  FuncAttrs.addAttribute("aarch64_pstate_sm_body");
2538  }
2539 
2540  // Attach "no-builtins" attributes to:
2541  // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2542  // * definitions: "no-builtins" or "no-builtin-<name>" only.
2543  // The attributes can come from:
2544  // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2545  // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2546  addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
2547 
2548  // Collect function IR attributes based on global settiings.
2549  getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2550 
2551  // Override some default IR attributes based on declaration-specific
2552  // information.
2553  if (TargetDecl) {
2554  if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2555  FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2556  if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2557  FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2558  if (TargetDecl->hasAttr<NoSplitStackAttr>())
2559  FuncAttrs.removeAttribute("split-stack");
2560  if (TargetDecl->hasAttr<ZeroCallUsedRegsAttr>()) {
2561  // A function "__attribute__((...))" overrides the command-line flag.
2562  auto Kind =
2563  TargetDecl->getAttr<ZeroCallUsedRegsAttr>()->getZeroCallUsedRegs();
2564  FuncAttrs.removeAttribute("zero-call-used-regs");
2565  FuncAttrs.addAttribute(
2566  "zero-call-used-regs",
2567  ZeroCallUsedRegsAttr::ConvertZeroCallUsedRegsKindToStr(Kind));
2568  }
2569 
2570  // Add NonLazyBind attribute to function declarations when -fno-plt
2571  // is used.
2572  // FIXME: what if we just haven't processed the function definition
2573  // yet, or if it's an external definition like C99 inline?
2574  if (CodeGenOpts.NoPLT) {
2575  if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2576  if (!Fn->isDefined() && !AttrOnCallSite) {
2577  FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2578  }
2579  }
2580  }
2581  }
2582 
2583  // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2584  // functions with -funique-internal-linkage-names.
2585  if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2586  if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2587  if (!FD->isExternallyVisible())
2588  FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
2589  "selected");
2590  }
2591  }
2592 
2593  // Collect non-call-site function IR attributes from declaration-specific
2594  // information.
2595  if (!AttrOnCallSite) {
2596  if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2597  FuncAttrs.addAttribute("cmse_nonsecure_entry");
2598 
2599  // Whether tail calls are enabled.
2600  auto shouldDisableTailCalls = [&] {
2601  // Should this be honored in getDefaultFunctionAttributes?
2602  if (CodeGenOpts.DisableTailCalls)
2603  return true;
2604 
2605  if (!TargetDecl)
2606  return false;
2607 
2608  if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
2609  TargetDecl->hasAttr<AnyX86InterruptAttr>())
2610  return true;
2611 
2612  if (CodeGenOpts.NoEscapingBlockTailCalls) {
2613  if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
2614  if (!BD->doesNotEscape())
2615  return true;
2616  }
2617 
2618  return false;
2619  };
2620  if (shouldDisableTailCalls())
2621  FuncAttrs.addAttribute("disable-tail-calls", "true");
2622 
2623  // CPU/feature overrides. addDefaultFunctionDefinitionAttributes
2624  // handles these separately to set them based on the global defaults.
2625  GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
2626  }
2627 
2628  // Collect attributes from arguments and return values.
2629  ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
2630 
2631  QualType RetTy = FI.getReturnType();
2632  const ABIArgInfo &RetAI = FI.getReturnInfo();
2633  const llvm::DataLayout &DL = getDataLayout();
2634 
2635  // Determine if the return type could be partially undef
2636  if (CodeGenOpts.EnableNoundefAttrs &&
2637  HasStrictReturn(*this, RetTy, TargetDecl)) {
2638  if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
2639  DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
2640  RetAttrs.addAttribute(llvm::Attribute::NoUndef);
2641  }
2642 
2643  switch (RetAI.getKind()) {
2644  case ABIArgInfo::Extend:
2645  if (RetAI.isSignExt())
2646  RetAttrs.addAttribute(llvm::Attribute::SExt);
2647  else
2648  RetAttrs.addAttribute(llvm::Attribute::ZExt);
2649  [[fallthrough]];
2650  case ABIArgInfo::Direct:
2651  if (RetAI.getInReg())
2652  RetAttrs.addAttribute(llvm::Attribute::InReg);
2653 
2654  if (canApplyNoFPClass(RetAI, RetTy, true))
2655  RetAttrs.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2656 
2657  break;
2658  case ABIArgInfo::Ignore:
2659  break;
2660 
2661  case ABIArgInfo::InAlloca:
2662  case ABIArgInfo::Indirect: {
2663  // inalloca and sret disable readnone and readonly
2664  AddPotentialArgAccess();
2665  break;
2666  }
2667 
2669  break;
2670 
2671  case ABIArgInfo::Expand:
2673  llvm_unreachable("Invalid ABI kind for return argument");
2674  }
2675 
2676  if (!IsThunk) {
2677  // FIXME: fix this properly, https://reviews.llvm.org/D100388
2678  if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
2679  QualType PTy = RefTy->getPointeeType();
2680  if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2681  RetAttrs.addDereferenceableAttr(
2682  getMinimumObjectSize(PTy).getQuantity());
2683  if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2684  !CodeGenOpts.NullPointerIsValid)
2685  RetAttrs.addAttribute(llvm::Attribute::NonNull);
2686  if (PTy->isObjectType()) {
2687  llvm::Align Alignment =
2689  RetAttrs.addAlignmentAttr(Alignment);
2690  }
2691  }
2692  }
2693 
2694  bool hasUsedSRet = false;
2695  SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
2696 
2697  // Attach attributes to sret.
2698  if (IRFunctionArgs.hasSRetArg()) {
2699  llvm::AttrBuilder SRETAttrs(getLLVMContext());
2700  SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
2701  SRETAttrs.addAttribute(llvm::Attribute::Writable);
2702  SRETAttrs.addAttribute(llvm::Attribute::DeadOnUnwind);
2703  hasUsedSRet = true;
2704  if (RetAI.getInReg())
2705  SRETAttrs.addAttribute(llvm::Attribute::InReg);
2706  SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
2707  ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2708  llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
2709  }
2710 
2711  // Attach attributes to inalloca argument.
2712  if (IRFunctionArgs.hasInallocaArg()) {
2713  llvm::AttrBuilder Attrs(getLLVMContext());
2714  Attrs.addInAllocaAttr(FI.getArgStruct());
2715  ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2716  llvm::AttributeSet::get(getLLVMContext(), Attrs);
2717  }
2718 
2719  // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
2720  // unless this is a thunk function.
2721  // FIXME: fix this properly, https://reviews.llvm.org/D100388
2722  if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2723  !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
2724  auto IRArgs = IRFunctionArgs.getIRArgs(0);
2725 
2726  assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
2727 
2728  llvm::AttrBuilder Attrs(getLLVMContext());
2729 
2730  QualType ThisTy =
2732 
2733  if (!CodeGenOpts.NullPointerIsValid &&
2734  getTypes().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2735  Attrs.addAttribute(llvm::Attribute::NonNull);
2736  Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
2737  } else {
2738  // FIXME dereferenceable should be correct here, regardless of
2739  // NullPointerIsValid. However, dereferenceable currently does not always
2740  // respect NullPointerIsValid and may imply nonnull and break the program.
2741  // See https://reviews.llvm.org/D66618 for discussions.
2742  Attrs.addDereferenceableOrNullAttr(
2745  .getQuantity());
2746  }
2747 
2748  llvm::Align Alignment =
2749  getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
2750  /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2751  .getAsAlign();
2752  Attrs.addAlignmentAttr(Alignment);
2753 
2754  ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2755  }
2756 
2757  unsigned ArgNo = 0;
2759  E = FI.arg_end();
2760  I != E; ++I, ++ArgNo) {
2761  QualType ParamType = I->type;
2762  const ABIArgInfo &AI = I->info;
2763  llvm::AttrBuilder Attrs(getLLVMContext());
2764 
2765  // Add attribute for padding argument, if necessary.
2766  if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2767  if (AI.getPaddingInReg()) {
2768  ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2769  llvm::AttributeSet::get(
2770  getLLVMContext(),
2771  llvm::AttrBuilder(getLLVMContext()).addAttribute(llvm::Attribute::InReg));
2772  }
2773  }
2774 
2775  // Decide whether the argument we're handling could be partially undef
2776  if (CodeGenOpts.EnableNoundefAttrs &&
2777  DetermineNoUndef(ParamType, getTypes(), DL, AI)) {
2778  Attrs.addAttribute(llvm::Attribute::NoUndef);
2779  }
2780 
2781  // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2782  // have the corresponding parameter variable. It doesn't make
2783  // sense to do it here because parameters are so messed up.
2784  switch (AI.getKind()) {
2785  case ABIArgInfo::Extend:
2786  if (AI.isSignExt())
2787  Attrs.addAttribute(llvm::Attribute::SExt);
2788  else
2789  Attrs.addAttribute(llvm::Attribute::ZExt);
2790  [[fallthrough]];
2791  case ABIArgInfo::Direct:
2792  if (ArgNo == 0 && FI.isChainCall())
2793  Attrs.addAttribute(llvm::Attribute::Nest);
2794  else if (AI.getInReg())
2795  Attrs.addAttribute(llvm::Attribute::InReg);
2796  Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
2797 
2798  if (canApplyNoFPClass(AI, ParamType, false))
2799  Attrs.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2800  break;
2801  case ABIArgInfo::Indirect: {
2802  if (AI.getInReg())
2803  Attrs.addAttribute(llvm::Attribute::InReg);
2804 
2805  if (AI.getIndirectByVal())
2806  Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
2807 
2808  auto *Decl = ParamType->getAsRecordDecl();
2809  if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2810  Decl->getArgPassingRestrictions() ==
2812  // When calling the function, the pointer passed in will be the only
2813  // reference to the underlying object. Mark it accordingly.
2814  Attrs.addAttribute(llvm::Attribute::NoAlias);
2815 
2816  // TODO: We could add the byref attribute if not byval, but it would
2817  // require updating many testcases.
2818 
2819  CharUnits Align = AI.getIndirectAlign();
2820 
2821  // In a byval argument, it is important that the required
2822  // alignment of the type is honored, as LLVM might be creating a
2823  // *new* stack object, and needs to know what alignment to give
2824  // it. (Sometimes it can deduce a sensible alignment on its own,
2825  // but not if clang decides it must emit a packed struct, or the
2826  // user specifies increased alignment requirements.)
2827  //
2828  // This is different from indirect *not* byval, where the object
2829  // exists already, and the align attribute is purely
2830  // informative.
2831  assert(!Align.isZero());
2832 
2833  // For now, only add this when we have a byval argument.
2834  // TODO: be less lazy about updating test cases.
2835  if (AI.getIndirectByVal())
2836  Attrs.addAlignmentAttr(Align.getQuantity());
2837 
2838  // byval disables readnone and readonly.
2839  AddPotentialArgAccess();
2840  break;
2841  }
2843  CharUnits Align = AI.getIndirectAlign();
2844  Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2845  Attrs.addAlignmentAttr(Align.getQuantity());
2846  break;
2847  }
2848  case ABIArgInfo::Ignore:
2849  case ABIArgInfo::Expand:
2851  break;
2852 
2853  case ABIArgInfo::InAlloca:
2854  // inalloca disables readnone and readonly.
2855  AddPotentialArgAccess();
2856  continue;
2857  }
2858 
2859  if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2860  QualType PTy = RefTy->getPointeeType();
2861  if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2862  Attrs.addDereferenceableAttr(
2863  getMinimumObjectSize(PTy).getQuantity());
2864  if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2865  !CodeGenOpts.NullPointerIsValid)
2866  Attrs.addAttribute(llvm::Attribute::NonNull);
2867  if (PTy->isObjectType()) {
2868  llvm::Align Alignment =
2870  Attrs.addAlignmentAttr(Alignment);
2871  }
2872  }
2873 
2874  // From OpenCL spec v3.0.10 section 6.3.5 Alignment of Types:
2875  // > For arguments to a __kernel function declared to be a pointer to a
2876  // > data type, the OpenCL compiler can assume that the pointee is always
2877  // > appropriately aligned as required by the data type.
2878  if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>() &&
2879  ParamType->isPointerType()) {
2880  QualType PTy = ParamType->getPointeeType();
2881  if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2882  llvm::Align Alignment =
2884  Attrs.addAlignmentAttr(Alignment);
2885  }
2886  }
2887 
2888  switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2890  break;
2891 
2893  // Add 'sret' if we haven't already used it for something, but
2894  // only if the result is void.
2895  if (!hasUsedSRet && RetTy->isVoidType()) {
2896  Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
2897  hasUsedSRet = true;
2898  }
2899 
2900  // Add 'noalias' in either case.
2901  Attrs.addAttribute(llvm::Attribute::NoAlias);
2902 
2903  // Add 'dereferenceable' and 'alignment'.
2904  auto PTy = ParamType->getPointeeType();
2905  if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2906  auto info = getContext().getTypeInfoInChars(PTy);
2907  Attrs.addDereferenceableAttr(info.Width.getQuantity());
2908  Attrs.addAlignmentAttr(info.Align.getAsAlign());
2909  }
2910  break;
2911  }
2912 
2914  Attrs.addAttribute(llvm::Attribute::SwiftError);
2915  break;
2916 
2918  Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2919  break;
2920 
2922  Attrs.addAttribute(llvm::Attribute::SwiftAsync);
2923  break;
2924  }
2925 
2926  if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2927  Attrs.addAttribute(llvm::Attribute::NoCapture);
2928 
2929  if (Attrs.hasAttributes()) {
2930  unsigned FirstIRArg, NumIRArgs;
2931  std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2932  for (unsigned i = 0; i < NumIRArgs; i++)
2933  ArgAttrs[FirstIRArg + i] = ArgAttrs[FirstIRArg + i].addAttributes(
2934  getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), Attrs));
2935  }
2936  }
2937  assert(ArgNo == FI.arg_size());
2938 
2939  AttrList = llvm::AttributeList::get(
2940  getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2941  llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2942 }
2943 
2944 /// An argument came in as a promoted argument; demote it back to its
2945 /// declared type.
2946 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2947  const VarDecl *var,
2948  llvm::Value *value) {
2949  llvm::Type *varType = CGF.ConvertType(var->getType());
2950 
2951  // This can happen with promotions that actually don't change the
2952  // underlying type, like the enum promotions.
2953  if (value->getType() == varType) return value;
2954 
2955  assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2956  && "unexpected promotion type");
2957 
2958  if (isa<llvm::IntegerType>(varType))
2959  return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2960 
2961  return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2962 }
2963 
2964 /// Returns the attribute (either parameter attribute, or function
2965 /// attribute), which declares argument ArgNo to be non-null.
2966 static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2967  QualType ArgType, unsigned ArgNo) {
2968  // FIXME: __attribute__((nonnull)) can also be applied to:
2969  // - references to pointers, where the pointee is known to be
2970  // nonnull (apparently a Clang extension)
2971  // - transparent unions containing pointers
2972  // In the former case, LLVM IR cannot represent the constraint. In
2973  // the latter case, we have no guarantee that the transparent union
2974  // is in fact passed as a pointer.
2975  if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2976  return nullptr;
2977  // First, check attribute on parameter itself.
2978  if (PVD) {
2979  if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2980  return ParmNNAttr;
2981  }
2982  // Check function attributes.
2983  if (!FD)
2984  return nullptr;
2985  for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2986  if (NNAttr->isNonNull(ArgNo))
2987  return NNAttr;
2988  }
2989  return nullptr;
2990 }
2991 
2992 namespace {
2993  struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2994  Address Temp;
2995  Address Arg;
2996  CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2997  void Emit(CodeGenFunction &CGF, Flags flags) override {
2998  llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2999  CGF.Builder.CreateStore(errorValue, Arg);
3000  }
3001  };
3002 }
3003 
3005  llvm::Function *Fn,
3006  const FunctionArgList &Args) {
3007  if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
3008  // Naked functions don't have prologues.
3009  return;
3010 
3011  // If this is an implicit-return-zero function, go ahead and
3012  // initialize the return value. TODO: it might be nice to have
3013  // a more general mechanism for this that didn't require synthesized
3014  // return statements.
3015  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
3016  if (FD->hasImplicitReturnZero()) {
3017  QualType RetTy = FD->getReturnType().getUnqualifiedType();
3018  llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
3019  llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
3021  }
3022  }
3023 
3024  // FIXME: We no longer need the types from FunctionArgList; lift up and
3025  // simplify.
3026 
3027  ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
3028  assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
3029 
3030  // If we're using inalloca, all the memory arguments are GEPs off of the last
3031  // parameter, which is a pointer to the complete memory area.
3032  Address ArgStruct = Address::invalid();
3033  if (IRFunctionArgs.hasInallocaArg())
3034  ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
3035  FI.getArgStruct(), FI.getArgStructAlignment());
3036 
3037  // Name the struct return parameter.
3038  if (IRFunctionArgs.hasSRetArg()) {
3039  auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
3040  AI->setName("agg.result");
3041  AI->addAttr(llvm::Attribute::NoAlias);
3042  }
3043 
3044  // Track if we received the parameter as a pointer (indirect, byval, or
3045  // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
3046  // into a local alloca for us.
3048  ArgVals.reserve(Args.size());
3049 
3050  // Create a pointer value for every parameter declaration. This usually
3051  // entails copying one or more LLVM IR arguments into an alloca. Don't push
3052  // any cleanups or do anything that might unwind. We do that separately, so
3053  // we can push the cleanups in the correct order for the ABI.
3054  assert(FI.arg_size() == Args.size() &&
3055  "Mismatch between function signature & arguments.");
3056  unsigned ArgNo = 0;
3058  for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
3059  i != e; ++i, ++info_it, ++ArgNo) {
3060  const VarDecl *Arg = *i;
3061  const ABIArgInfo &ArgI = info_it->info;
3062 
3063  bool isPromoted =
3064  isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
3065  // We are converting from ABIArgInfo type to VarDecl type directly, unless
3066  // the parameter is promoted. In this case we convert to
3067  // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
3068  QualType Ty = isPromoted ? info_it->type : Arg->getType();
3069  assert(hasScalarEvaluationKind(Ty) ==
3071 
3072  unsigned FirstIRArg, NumIRArgs;
3073  std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3074 
3075  if (Arg->hasAttr<SYCLAccessorReadonlyAttr>())
3076  Fn->getArg(FirstIRArg)->addAttr(llvm::Attribute::ReadOnly);
3077 
3078  if (const auto *AddIRAttr =
3079  Arg->getAttr<SYCLAddIRAttributesKernelParameterAttr>()) {
3081  AddIRAttr->getFilteredAttributeNameValuePairs(CGM.getContext());
3082 
3083  llvm::AttrBuilder KernelParamAttrBuilder(Fn->getContext());
3084  for (const auto &NameValuePair : NameValuePairs)
3085  KernelParamAttrBuilder.addAttribute(NameValuePair.first,
3086  NameValuePair.second);
3087  Fn->addParamAttrs(ArgNo, KernelParamAttrBuilder);
3088  }
3089 
3090  switch (ArgI.getKind()) {
3091  case ABIArgInfo::InAlloca: {
3092  assert(NumIRArgs == 0);
3093  auto FieldIndex = ArgI.getInAllocaFieldIndex();
3094  Address V =
3095  Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
3096  if (ArgI.getInAllocaIndirect())
3098  getContext().getTypeAlignInChars(Ty));
3099  ArgVals.push_back(ParamValue::forIndirect(V));
3100  break;
3101  }
3102 
3103  case ABIArgInfo::Indirect:
3105  assert(NumIRArgs == 1);
3107  Fn->getArg(FirstIRArg), Ty, ArgI.getIndirectAlign(), false, nullptr,
3108  nullptr, KnownNonNull);
3109 
3110  if (!hasScalarEvaluationKind(Ty)) {
3111  // Aggregates and complex variables are accessed by reference. All we
3112  // need to do is realign the value, if requested. Also, if the address
3113  // may be aliased, copy it to ensure that the parameter variable is
3114  // mutable and has a unique adress, as C requires.
3115  if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
3116  RawAddress AlignedTemp = CreateMemTemp(Ty, "coerce");
3117 
3118  // Copy from the incoming argument pointer to the temporary with the
3119  // appropriate alignment.
3120  //
3121  // FIXME: We should have a common utility for generating an aggregate
3122  // copy.
3125  AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
3126  ParamAddr.emitRawPointer(*this),
3127  ParamAddr.getAlignment().getAsAlign(),
3128  llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
3129  ParamAddr = AlignedTemp;
3130  }
3131  ArgVals.push_back(ParamValue::forIndirect(ParamAddr));
3132  } else {
3133  // Load scalar value from indirect argument.
3134  llvm::Value *V =
3135  EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
3136 
3137  if (isPromoted)
3138  V = emitArgumentDemotion(*this, Arg, V);
3139  ArgVals.push_back(ParamValue::forDirect(V));
3140  }
3141  break;
3142  }
3143 
3144  case ABIArgInfo::Extend:
3145  case ABIArgInfo::Direct: {
3146  auto AI = Fn->getArg(FirstIRArg);
3147  llvm::Type *LTy = ConvertType(Arg->getType());
3148 
3149  // Prepare parameter attributes. So far, only attributes for pointer
3150  // parameters are prepared. See
3151  // http://llvm.org/docs/LangRef.html#paramattrs.
3152  if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
3153  ArgI.getCoerceToType()->isPointerTy()) {
3154  assert(NumIRArgs == 1);
3155 
3156  if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
3157  // Set `nonnull` attribute if any.
3158  if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
3159  PVD->getFunctionScopeIndex()) &&
3160  !CGM.getCodeGenOpts().NullPointerIsValid)
3161  AI->addAttr(llvm::Attribute::NonNull);
3162 
3163  QualType OTy = PVD->getOriginalType();
3164  if (const auto *ArrTy =
3165  getContext().getAsConstantArrayType(OTy)) {
3166  // A C99 array parameter declaration with the static keyword also
3167  // indicates dereferenceability, and if the size is constant we can
3168  // use the dereferenceable attribute (which requires the size in
3169  // bytes).
3170  if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3171  QualType ETy = ArrTy->getElementType();
3172  llvm::Align Alignment =
3174  AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
3175  uint64_t ArrSize = ArrTy->getZExtSize();
3176  if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
3177  ArrSize) {
3178  llvm::AttrBuilder Attrs(getLLVMContext());
3179  Attrs.addDereferenceableAttr(
3180  getContext().getTypeSizeInChars(ETy).getQuantity() *
3181  ArrSize);
3182  AI->addAttrs(Attrs);
3183  } else if (getContext().getTargetInfo().getNullPointerValue(
3184  ETy.getAddressSpace()) == 0 &&
3185  !CGM.getCodeGenOpts().NullPointerIsValid) {
3186  AI->addAttr(llvm::Attribute::NonNull);
3187  }
3188  }
3189  } else if (const auto *ArrTy =
3190  getContext().getAsVariableArrayType(OTy)) {
3191  // For C99 VLAs with the static keyword, we don't know the size so
3192  // we can't use the dereferenceable attribute, but in addrspace(0)
3193  // we know that it must be nonnull.
3194  if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3195  QualType ETy = ArrTy->getElementType();
3196  llvm::Align Alignment =
3198  AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
3199  if (!getTypes().getTargetAddressSpace(ETy) &&
3200  !CGM.getCodeGenOpts().NullPointerIsValid)
3201  AI->addAttr(llvm::Attribute::NonNull);
3202  }
3203  }
3204 
3205  // Set `align` attribute if any.
3206  const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
3207  if (!AVAttr)
3208  if (const auto *TOTy = OTy->getAs<TypedefType>())
3209  AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
3210  if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
3211  // If alignment-assumption sanitizer is enabled, we do *not* add
3212  // alignment attribute here, but emit normal alignment assumption,
3213  // so the UBSAN check could function.
3214  llvm::ConstantInt *AlignmentCI =
3215  cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
3216  uint64_t AlignmentInt =
3217  AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
3218  if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
3219  AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
3220  AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(
3221  llvm::Align(AlignmentInt)));
3222  }
3223  }
3224  }
3225 
3226  // Set 'noalias' if an argument type has the `restrict` qualifier.
3227  if (Arg->getType().isRestrictQualified() ||
3228  (CurCodeDecl &&
3229  CurCodeDecl->hasAttr<SYCLIntelKernelArgsRestrictAttr>() &&
3230  Arg->getType()->isPointerType()) ||
3231  (Arg->hasAttr<RestrictAttr>() && Arg->getType()->isPointerType()))
3232  AI->addAttr(llvm::Attribute::NoAlias);
3233  }
3234 
3235  // Prepare the argument value. If we have the trivial case, handle it
3236  // with no muss and fuss.
3237  if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
3238  ArgI.getCoerceToType() == ConvertType(Ty) &&
3239  ArgI.getDirectOffset() == 0) {
3240  assert(NumIRArgs == 1);
3241 
3242  // LLVM expects swifterror parameters to be used in very restricted
3243  // ways. Copy the value into a less-restricted temporary.
3244  llvm::Value *V = AI;
3245  if (FI.getExtParameterInfo(ArgNo).getABI()
3247  QualType pointeeTy = Ty->getPointeeType();
3248  assert(pointeeTy->isPointerType());
3249  RawAddress temp =
3250  CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3252  V, pointeeTy, getContext().getTypeAlignInChars(pointeeTy));
3253  llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
3254  Builder.CreateStore(incomingErrorValue, temp);
3255  V = temp.getPointer();
3256 
3257  // Push a cleanup to copy the value back at the end of the function.
3258  // The convention does not guarantee that the value will be written
3259  // back if the function exits with an unwind exception.
3260  EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
3261  }
3262 
3263  // Ensure the argument is the correct type.
3264  if (V->getType() != ArgI.getCoerceToType())
3265  V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
3266 
3267  if (isPromoted)
3268  V = emitArgumentDemotion(*this, Arg, V);
3269 
3270  // Because of merging of function types from multiple decls it is
3271  // possible for the type of an argument to not match the corresponding
3272  // type in the function type. Since we are codegening the callee
3273  // in here, add a cast to the argument type.
3274  llvm::Type *LTy = ConvertType(Arg->getType());
3275  if (V->getType() != LTy)
3276  V = Builder.CreateBitCast(V, LTy);
3277 
3278  ArgVals.push_back(ParamValue::forDirect(V));
3279  break;
3280  }
3281 
3282  // VLST arguments are coerced to VLATs at the function boundary for
3283  // ABI consistency. If this is a VLST that was coerced to
3284  // a VLAT at the function boundary and the types match up, use
3285  // llvm.vector.extract to convert back to the original VLST.
3286  if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
3287  llvm::Value *Coerced = Fn->getArg(FirstIRArg);
3288  if (auto *VecTyFrom =
3289  dyn_cast<llvm::ScalableVectorType>(Coerced->getType())) {
3290  // If we are casting a scalable i1 predicate vector to a fixed i8
3291  // vector, bitcast the source and use a vector extract.
3292  if (VecTyFrom->getElementType()->isIntegerTy(1) &&
3293  VecTyFrom->getElementCount().isKnownMultipleOf(8) &&
3294  VecTyTo->getElementType() == Builder.getInt8Ty()) {
3295  VecTyFrom = llvm::ScalableVectorType::get(
3296  VecTyTo->getElementType(),
3297  VecTyFrom->getElementCount().getKnownMinValue() / 8);
3298  Coerced = Builder.CreateBitCast(Coerced, VecTyFrom);
3299  }
3300  if (VecTyFrom->getElementType() == VecTyTo->getElementType()) {
3301  llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
3302 
3303  assert(NumIRArgs == 1);
3304  Coerced->setName(Arg->getName() + ".coerce");
3305  ArgVals.push_back(ParamValue::forDirect(Builder.CreateExtractVector(
3306  VecTyTo, Coerced, Zero, "cast.fixed")));
3307  break;
3308  }
3309  }
3310  }
3311 
3312  llvm::StructType *STy =
3313  dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
3314  if (ArgI.isDirect() && !ArgI.getCanBeFlattened() && STy &&
3315  STy->getNumElements() > 1) {
3316  [[maybe_unused]] llvm::TypeSize StructSize =
3317  CGM.getDataLayout().getTypeAllocSize(STy);
3318  [[maybe_unused]] llvm::TypeSize PtrElementSize =
3319  CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(Ty));
3320  if (STy->containsHomogeneousScalableVectorTypes()) {
3321  assert(StructSize == PtrElementSize &&
3322  "Only allow non-fractional movement of structure with"
3323  "homogeneous scalable vector type");
3324 
3325  ArgVals.push_back(ParamValue::forDirect(AI));
3326  break;
3327  }
3328  }
3329 
3330  Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
3331  Arg->getName());
3332 
3333  // Pointer to store into.
3334  Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
3335 
3336  // Fast-isel and the optimizer generally like scalar values better than
3337  // FCAs, so we flatten them if this is safe to do for this argument.
3338  if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
3339  STy->getNumElements() > 1) {
3340  llvm::TypeSize StructSize = CGM.getDataLayout().getTypeAllocSize(STy);
3341  llvm::TypeSize PtrElementSize =
3342  CGM.getDataLayout().getTypeAllocSize(Ptr.getElementType());
3343  if (StructSize.isScalable()) {
3344  assert(STy->containsHomogeneousScalableVectorTypes() &&
3345  "ABI only supports structure with homogeneous scalable vector "
3346  "type");
3347  assert(StructSize == PtrElementSize &&
3348  "Only allow non-fractional movement of structure with"
3349  "homogeneous scalable vector type");
3350  assert(STy->getNumElements() == NumIRArgs);
3351 
3352  llvm::Value *LoadedStructValue = llvm::PoisonValue::get(STy);
3353  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3354  auto *AI = Fn->getArg(FirstIRArg + i);
3355  AI->setName(Arg->getName() + ".coerce" + Twine(i));
3356  LoadedStructValue =
3357  Builder.CreateInsertValue(LoadedStructValue, AI, i);
3358  }
3359 
3360  Builder.CreateStore(LoadedStructValue, Ptr);
3361  } else {
3362  uint64_t SrcSize = StructSize.getFixedValue();
3363  uint64_t DstSize = PtrElementSize.getFixedValue();
3364 
3365  Address AddrToStoreInto = Address::invalid();
3366  if (SrcSize <= DstSize) {
3367  AddrToStoreInto = Ptr.withElementType(STy);
3368  } else {
3369  AddrToStoreInto =
3370  CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
3371  }
3372 
3373  assert(STy->getNumElements() == NumIRArgs);
3374  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3375  auto AI = Fn->getArg(FirstIRArg + i);
3376  AI->setName(Arg->getName() + ".coerce" + Twine(i));
3377  Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
3378  Builder.CreateStore(AI, EltPtr);
3379  }
3380 
3381  if (SrcSize > DstSize) {
3382  Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
3383  }
3384  }
3385  } else {
3386  // Simple case, just do a coerced store of the argument into the alloca.
3387  assert(NumIRArgs == 1);
3388  auto AI = Fn->getArg(FirstIRArg);
3389  AI->setName(Arg->getName() + ".coerce");
3390  CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
3391  }
3392 
3393  // Match to what EmitParmDecl is expecting for this type.
3395  llvm::Value *V =
3396  EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
3397  if (isPromoted)
3398  V = emitArgumentDemotion(*this, Arg, V);
3399  ArgVals.push_back(ParamValue::forDirect(V));
3400  } else {
3401  ArgVals.push_back(ParamValue::forIndirect(Alloca));
3402  }
3403  break;
3404  }
3405 
3407  // Reconstruct into a temporary.
3408  Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3409  ArgVals.push_back(ParamValue::forIndirect(alloca));
3410 
3411  auto coercionType = ArgI.getCoerceAndExpandType();
3412  alloca = alloca.withElementType(coercionType);
3413  unsigned argIndex = FirstIRArg;
3414  for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3415  llvm::Type *eltType = coercionType->getElementType(i);
3417  continue;
3418 
3419  auto eltAddr = Builder.CreateStructGEP(alloca, i);
3420  auto elt = Fn->getArg(argIndex++);
3421  Builder.CreateStore(elt, eltAddr);
3422  }
3423  assert(argIndex == FirstIRArg + NumIRArgs);
3424  break;
3425  }
3426 
3427  case ABIArgInfo::Expand: {
3428  // If this structure was expanded into multiple arguments then
3429  // we need to create a temporary and reconstruct it from the
3430  // arguments.
3431  Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3432  LValue LV = MakeAddrLValue(Alloca, Ty);
3433  ArgVals.push_back(ParamValue::forIndirect(Alloca));
3434 
3435  auto FnArgIter = Fn->arg_begin() + FirstIRArg;
3436  ExpandTypeFromArgs(Ty, LV, FnArgIter);
3437  assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
3438  for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
3439  auto AI = Fn->getArg(FirstIRArg + i);
3440  AI->setName(Arg->getName() + "." + Twine(i));
3441  }
3442  break;
3443  }
3444 
3445  case ABIArgInfo::Ignore:
3446  assert(NumIRArgs == 0);
3447  // Initialize the local variable appropriately.
3448  if (!hasScalarEvaluationKind(Ty)) {
3449  ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
3450  } else {
3451  llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
3452  ArgVals.push_back(ParamValue::forDirect(U));
3453  }
3454  break;
3455  }
3456  }
3457 
3458  if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3459  for (int I = Args.size() - 1; I >= 0; --I)
3460  EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3461  } else {
3462  for (unsigned I = 0, E = Args.size(); I != E; ++I)
3463  EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3464  }
3465 }
3466 
3467 static void eraseUnusedBitCasts(llvm::Instruction *insn) {
3468  while (insn->use_empty()) {
3469  llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
3470  if (!bitcast) return;
3471 
3472  // This is "safe" because we would have used a ConstantExpr otherwise.
3473  insn = cast<llvm::Instruction>(bitcast->getOperand(0));
3474  bitcast->eraseFromParent();
3475  }
3476 }
3477 
3478 /// Try to emit a fused autorelease of a return result.
3480  llvm::Value *result) {
3481  // We must be immediately followed the cast.
3482  llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
3483  if (BB->empty()) return nullptr;
3484  if (&BB->back() != result) return nullptr;
3485 
3486  llvm::Type *resultType = result->getType();
3487 
3488  // result is in a BasicBlock and is therefore an Instruction.
3489  llvm::Instruction *generator = cast<llvm::Instruction>(result);
3490 
3492 
3493  // Look for:
3494  // %generator = bitcast %type1* %generator2 to %type2*
3495  while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
3496  // We would have emitted this as a constant if the operand weren't
3497  // an Instruction.
3498  generator = cast<llvm::Instruction>(bitcast->getOperand(0));
3499 
3500  // Require the generator to be immediately followed by the cast.
3501  if (generator->getNextNode() != bitcast)
3502  return nullptr;
3503 
3504  InstsToKill.push_back(bitcast);
3505  }
3506 
3507  // Look for:
3508  // %generator = call i8* @objc_retain(i8* %originalResult)
3509  // or
3510  // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
3511  llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
3512  if (!call) return nullptr;
3513 
3514  bool doRetainAutorelease;
3515 
3516  if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
3517  doRetainAutorelease = true;
3518  } else if (call->getCalledOperand() ==
3520  doRetainAutorelease = false;
3521 
3522  // If we emitted an assembly marker for this call (and the
3523  // ARCEntrypoints field should have been set if so), go looking
3524  // for that call. If we can't find it, we can't do this
3525  // optimization. But it should always be the immediately previous
3526  // instruction, unless we needed bitcasts around the call.
3528  llvm::Instruction *prev = call->getPrevNode();
3529  assert(prev);
3530  if (isa<llvm::BitCastInst>(prev)) {
3531  prev = prev->getPrevNode();
3532  assert(prev);
3533  }
3534  assert(isa<llvm::CallInst>(prev));
3535  assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
3537  InstsToKill.push_back(prev);
3538  }
3539  } else {
3540  return nullptr;
3541  }
3542 
3543  result = call->getArgOperand(0);
3544  InstsToKill.push_back(call);
3545 
3546  // Keep killing bitcasts, for sanity. Note that we no longer care
3547  // about precise ordering as long as there's exactly one use.
3548  while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
3549  if (!bitcast->hasOneUse()) break;
3550  InstsToKill.push_back(bitcast);
3551  result = bitcast->getOperand(0);
3552  }
3553 
3554  // Delete all the unnecessary instructions, from latest to earliest.
3555  for (auto *I : InstsToKill)
3556  I->eraseFromParent();
3557 
3558  // Do the fused retain/autorelease if we were asked to.
3559  if (doRetainAutorelease)
3560  result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
3561 
3562  // Cast back to the result type.
3563  return CGF.Builder.CreateBitCast(result, resultType);
3564 }
3565 
3566 /// If this is a +1 of the value of an immutable 'self', remove it.
3567 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
3568  llvm::Value *result) {
3569  // This is only applicable to a method with an immutable 'self'.
3570  const ObjCMethodDecl *method =
3571  dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
3572  if (!method) return nullptr;
3573  const VarDecl *self = method->getSelfDecl();
3574  if (!self->getType().isConstQualified()) return nullptr;
3575 
3576  // Look for a retain call. Note: stripPointerCasts looks through returned arg
3577  // functions, which would cause us to miss the retain.
3578  llvm::CallInst *retainCall = dyn_cast<llvm::CallInst>(result);
3579  if (!retainCall || retainCall->getCalledOperand() !=
3581  return nullptr;
3582 
3583  // Look for an ordinary load of 'self'.
3584  llvm::Value *retainedValue = retainCall->getArgOperand(0);
3585  llvm::LoadInst *load =
3586  dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
3587  if (!load || load->isAtomic() || load->isVolatile() ||
3588  load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getBasePointer())
3589  return nullptr;
3590 
3591  // Okay! Burn it all down. This relies for correctness on the
3592  // assumption that the retain is emitted as part of the return and
3593  // that thereafter everything is used "linearly".
3594  llvm::Type *resultType = result->getType();
3595  eraseUnusedBitCasts(cast<llvm::Instruction>(result));
3596  assert(retainCall->use_empty());
3597  retainCall->eraseFromParent();
3598  eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
3599 
3600  return CGF.Builder.CreateBitCast(load, resultType);
3601 }
3602 
3603 /// Emit an ARC autorelease of the result of a function.
3604 ///
3605 /// \return the value to actually return from the function
3606 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
3607  llvm::Value *result) {
3608  // If we're returning 'self', kill the initial retain. This is a
3609  // heuristic attempt to "encourage correctness" in the really unfortunate
3610  // case where we have a return of self during a dealloc and we desperately
3611  // need to avoid the possible autorelease.
3612  if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
3613  return self;
3614 
3615  // At -O0, try to emit a fused retain/autorelease.
3616  if (CGF.shouldUseFusedARCCalls())
3617  if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
3618  return fused;
3619 
3620  return CGF.EmitARCAutoreleaseReturnValue(result);
3621 }
3622 
3623 /// Heuristically search for a dominating store to the return-value slot.
3624 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
3625  llvm::Value *ReturnValuePtr = CGF.ReturnValue.getBasePointer();
3626 
3627  // Check if a User is a store which pointerOperand is the ReturnValue.
3628  // We are looking for stores to the ReturnValue, not for stores of the
3629  // ReturnValue to some other location.
3630  auto GetStoreIfValid = [&CGF,
3631  ReturnValuePtr](llvm::User *U) -> llvm::StoreInst * {
3632  auto *SI = dyn_cast<llvm::StoreInst>(U);
3633  if (!SI || SI->getPointerOperand() != ReturnValuePtr ||
3634  SI->getValueOperand()->getType() != CGF.ReturnValue.getElementType())
3635  return nullptr;
3636  // These aren't actually possible for non-coerced returns, and we
3637  // only care about non-coerced returns on this code path.
3638  // All memory instructions inside __try block are volatile.
3639  assert(!SI->isAtomic() &&
3640  (!SI->isVolatile() || CGF.currentFunctionUsesSEHTry()));
3641  return SI;
3642  };
3643  // If there are multiple uses of the return-value slot, just check
3644  // for something immediately preceding the IP. Sometimes this can
3645  // happen with how we generate implicit-returns; it can also happen
3646  // with noreturn cleanups.
3647  if (!ReturnValuePtr->hasOneUse()) {
3648  llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3649  if (IP->empty()) return nullptr;
3650 
3651  // Look at directly preceding instruction, skipping bitcasts and lifetime
3652  // markers.
3653  for (llvm::Instruction &I : make_range(IP->rbegin(), IP->rend())) {
3654  if (isa<llvm::BitCastInst>(&I))
3655  continue;
3656  if (auto *II = dyn_cast<llvm::IntrinsicInst>(&I))
3657  if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_end)
3658  continue;
3659 
3660  return GetStoreIfValid(&I);
3661  }
3662  return nullptr;
3663  }
3664 
3665  llvm::StoreInst *store = GetStoreIfValid(ReturnValuePtr->user_back());
3666  if (!store) return nullptr;
3667 
3668  // Now do a first-and-dirty dominance check: just walk up the
3669  // single-predecessors chain from the current insertion point.
3670  llvm::BasicBlock *StoreBB = store->getParent();
3671  llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3673  while (IP != StoreBB) {
3674  if (!SeenBBs.insert(IP).second || !(IP = IP->getSinglePredecessor()))
3675  return nullptr;
3676  }
3677 
3678  // Okay, the store's basic block dominates the insertion point; we
3679  // can do our thing.
3680  return store;
3681 }
3682 
3683 // Helper functions for EmitCMSEClearRecord
3684 
3685 // Set the bits corresponding to a field having width `BitWidth` and located at
3686 // offset `BitOffset` (from the least significant bit) within a storage unit of
3687 // `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3688 // Use little-endian layout, i.e.`Bits[0]` is the LSB.
3689 static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3690  int BitWidth, int CharWidth) {
3691  assert(CharWidth <= 64);
3692  assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
3693 
3694  int Pos = 0;
3695  if (BitOffset >= CharWidth) {
3696  Pos += BitOffset / CharWidth;
3697  BitOffset = BitOffset % CharWidth;
3698  }
3699 
3700  const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3701  if (BitOffset + BitWidth >= CharWidth) {
3702  Bits[Pos++] |= (Used << BitOffset) & Used;
3703  BitWidth -= CharWidth - BitOffset;
3704  BitOffset = 0;
3705  }
3706 
3707  while (BitWidth >= CharWidth) {
3708  Bits[Pos++] = Used;
3709  BitWidth -= CharWidth;
3710  }
3711 
3712  if (BitWidth > 0)
3713  Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3714 }
3715 
3716 // Set the bits corresponding to a field having width `BitWidth` and located at
3717 // offset `BitOffset` (from the least significant bit) within a storage unit of
3718 // `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3719 // `Bits` corresponds to one target byte. Use target endian layout.
3720 static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3721  int StorageSize, int BitOffset, int BitWidth,
3722  int CharWidth, bool BigEndian) {
3723 
3724  SmallVector<uint64_t, 8> TmpBits(StorageSize);
3725  setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3726 
3727  if (BigEndian)
3728  std::reverse(TmpBits.begin(), TmpBits.end());
3729 
3730  for (uint64_t V : TmpBits)
3731  Bits[StorageOffset++] |= V;
3732 }
3733 
3734 static void setUsedBits(CodeGenModule &, QualType, int,
3736 
3737 // Set the bits in `Bits`, which correspond to the value representations of
3738 // the actual members of the record type `RTy`. Note that this function does
3739 // not handle base classes, virtual tables, etc, since they cannot happen in
3740 // CMSE function arguments or return. The bit mask corresponds to the target
3741 // memory layout, i.e. it's endian dependent.
3742 static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3743  SmallVectorImpl<uint64_t> &Bits) {
3744  ASTContext &Context = CGM.getContext();
3745  int CharWidth = Context.getCharWidth();
3746  const RecordDecl *RD = RTy->getDecl()->getDefinition();
3747  const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3748  const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3749 
3750  int Idx = 0;
3751  for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3752  const FieldDecl *F = *I;
3753 
3754  if (F->isUnnamedBitField() || F->isZeroLengthBitField(Context) ||
3756  continue;
3757 
3758  if (F->isBitField()) {
3759  const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3761  BFI.StorageSize / CharWidth, BFI.Offset,
3762  BFI.Size, CharWidth,
3763  CGM.getDataLayout().isBigEndian());
3764  continue;
3765  }
3766 
3767  setUsedBits(CGM, F->getType(),
3768  Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3769  }
3770 }
3771 
3772 // Set the bits in `Bits`, which correspond to the value representations of
3773 // the elements of an array type `ATy`.
3774 static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3775  int Offset, SmallVectorImpl<uint64_t> &Bits) {
3776  const ASTContext &Context = CGM.getContext();
3777 
3778  QualType ETy = Context.getBaseElementType(ATy);
3779  int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3780  SmallVector<uint64_t, 4> TmpBits(Size);
3781  setUsedBits(CGM, ETy, 0, TmpBits);
3782 
3783  for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3784  auto Src = TmpBits.begin();
3785  auto Dst = Bits.begin() + Offset + I * Size;
3786  for (int J = 0; J < Size; ++J)
3787  *Dst++ |= *Src++;
3788  }
3789 }
3790 
3791 // Set the bits in `Bits`, which correspond to the value representations of
3792 // the type `QTy`.
3793 static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3794  SmallVectorImpl<uint64_t> &Bits) {
3795  if (const auto *RTy = QTy->getAs<RecordType>())
3796  return setUsedBits(CGM, RTy, Offset, Bits);
3797 
3798  ASTContext &Context = CGM.getContext();
3799  if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3800  return setUsedBits(CGM, ATy, Offset, Bits);
3801 
3802  int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3803  if (Size <= 0)
3804  return;
3805 
3806  std::fill_n(Bits.begin() + Offset, Size,
3807  (uint64_t(1) << Context.getCharWidth()) - 1);
3808 }
3809 
3811  int Pos, int Size, int CharWidth,
3812  bool BigEndian) {
3813  assert(Size > 0);
3814  uint64_t Mask = 0;
3815  if (BigEndian) {
3816  for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3817  ++P)
3818  Mask = (Mask << CharWidth) | *P;
3819  } else {
3820  auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3821  do
3822  Mask = (Mask << CharWidth) | *--P;
3823  while (P != End);
3824  }
3825  return Mask;
3826 }
3827 
3828 // Emit code to clear the bits in a record, which aren't a part of any user
3829 // declared member, when the record is a function return.
3830 llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3831  llvm::IntegerType *ITy,
3832  QualType QTy) {
3833  assert(Src->getType() == ITy);
3834  assert(ITy->getScalarSizeInBits() <= 64);
3835 
3836  const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3837  int Size = DataLayout.getTypeStoreSize(ITy);
3838  SmallVector<uint64_t, 4> Bits(Size);
3839  setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3840 
3841  int CharWidth = CGM.getContext().getCharWidth();
3842  uint64_t Mask =
3843  buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3844 
3845  return Builder.CreateAnd(Src, Mask, "cmse.clear");
3846 }
3847 
3848 // Emit code to clear the bits in a record, which aren't a part of any user
3849 // declared member, when the record is a function argument.
3850 llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3851  llvm::ArrayType *ATy,
3852  QualType QTy) {
3853  const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3854  int Size = DataLayout.getTypeStoreSize(ATy);
3855  SmallVector<uint64_t, 16> Bits(Size);
3856  setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3857 
3858  // Clear each element of the LLVM array.
3859  int CharWidth = CGM.getContext().getCharWidth();
3860  int CharsPerElt =
3861  ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3862  int MaskIndex = 0;
3863  llvm::Value *R = llvm::PoisonValue::get(ATy);
3864  for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3865  uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3866  DataLayout.isBigEndian());
3867  MaskIndex += CharsPerElt;
3868  llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3869  llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3870  R = Builder.CreateInsertValue(R, T1, I);
3871  }
3872 
3873  return R;
3874 }
3875 
3877  bool EmitRetDbgLoc,
3878  SourceLocation EndLoc) {
3879  if (FI.isNoReturn()) {
3880  // Noreturn functions don't return.
3881  EmitUnreachable(EndLoc);
3882  return;
3883  }
3884 
3885  if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
3886  // Naked functions don't have epilogues.
3887  Builder.CreateUnreachable();
3888  return;
3889  }
3890 
3891  // Functions with no result always return void.
3892  if (!ReturnValue.isValid()) {
3893  Builder.CreateRetVoid();
3894  return;
3895  }
3896 
3897  llvm::DebugLoc RetDbgLoc;
3898  llvm::Value *RV = nullptr;
3899  QualType RetTy = FI.getReturnType();
3900  const ABIArgInfo &RetAI = FI.getReturnInfo();
3901 
3902  switch (RetAI.getKind()) {
3903  case ABIArgInfo::InAlloca:
3904  // Aggregates get evaluated directly into the destination. Sometimes we
3905  // need to return the sret value in a register, though.
3906  assert(hasAggregateEvaluationKind(RetTy));
3907  if (RetAI.getInAllocaSRet()) {
3908  llvm::Function::arg_iterator EI = CurFn->arg_end();
3909  --EI;
3910  llvm::Value *ArgStruct = &*EI;
3911  llvm::Value *SRet = Builder.CreateStructGEP(
3912  FI.getArgStruct(), ArgStruct, RetAI.getInAllocaFieldIndex());
3913  llvm::Type *Ty =
3914  cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
3915  RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
3916  }
3917  break;
3918 
3919  case ABIArgInfo::Indirect: {
3920  auto AI = CurFn->arg_begin();
3921  if (RetAI.isSRetAfterThis())
3922  ++AI;
3923  switch (getEvaluationKind(RetTy)) {
3924  case TEK_Complex: {
3925  ComplexPairTy RT =
3926  EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
3928  /*isInit*/ true);
3929  break;
3930  }
3931  case TEK_Aggregate:
3932  // Do nothing; aggregates get evaluated directly into the destination.
3933  break;
3934  case TEK_Scalar: {
3935  LValueBaseInfo BaseInfo;
3936  TBAAAccessInfo TBAAInfo;
3937  CharUnits Alignment =
3938  CGM.getNaturalTypeAlignment(RetTy, &BaseInfo, &TBAAInfo);
3939  Address ArgAddr(&*AI, ConvertType(RetTy), Alignment);
3940  LValue ArgVal =
3941  LValue::MakeAddr(ArgAddr, RetTy, getContext(), BaseInfo, TBAAInfo);
3943  Builder.CreateLoad(ReturnValue), ArgVal, /*isInit*/ true);
3944  break;
3945  }
3946  }
3947  break;
3948  }
3949 
3950  case ABIArgInfo::Extend:
3951  case ABIArgInfo::Direct:
3952  if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
3953  RetAI.getDirectOffset() == 0) {
3954  // The internal return value temp always will have pointer-to-return-type
3955  // type, just do a load.
3956 
3957  // If there is a dominating store to ReturnValue, we can elide
3958  // the load, zap the store, and usually zap the alloca.
3959  if (llvm::StoreInst *SI =
3961  // Reuse the debug location from the store unless there is
3962  // cleanup code to be emitted between the store and return
3963  // instruction.
3964  if (EmitRetDbgLoc && !AutoreleaseResult)
3965  RetDbgLoc = SI->getDebugLoc();
3966  // Get the stored value and nuke the now-dead store.
3967  RV = SI->getValueOperand();
3968  SI->eraseFromParent();
3969 
3970  // Otherwise, we have to do a simple load.
3971  } else {
3973  }
3974  } else {
3975  // If the value is offset in memory, apply the offset now.
3976  Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
3977 
3978  RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
3979  }
3980 
3981  // In ARC, end functions that return a retainable type with a call
3982  // to objc_autoreleaseReturnValue.
3983  if (AutoreleaseResult) {
3984 #ifndef NDEBUG
3985  // Type::isObjCRetainabletype has to be called on a QualType that hasn't
3986  // been stripped of the typedefs, so we cannot use RetTy here. Get the
3987  // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
3988  // CurCodeDecl or BlockInfo.
3989  QualType RT;
3990 
3991  if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
3992  RT = FD->getReturnType();
3993  else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
3994  RT = MD->getReturnType();
3995  else if (isa<BlockDecl>(CurCodeDecl))
3997  else
3998  llvm_unreachable("Unexpected function/method type");
3999 
4000  assert(getLangOpts().ObjCAutoRefCount &&
4001  !FI.isReturnsRetained() &&
4002  RT->isObjCRetainableType());
4003 #endif
4004  RV = emitAutoreleaseOfResult(*this, RV);
4005  }
4006 
4007  break;
4008 
4009  case ABIArgInfo::Ignore:
4010  break;
4011 
4013  auto coercionType = RetAI.getCoerceAndExpandType();
4014 
4015  // Load all of the coerced elements out into results.
4017  Address addr = ReturnValue.withElementType(coercionType);
4018  for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4019  auto coercedEltType = coercionType->getElementType(i);
4020  if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
4021  continue;
4022 
4023  auto eltAddr = Builder.CreateStructGEP(addr, i);
4024  auto elt = Builder.CreateLoad(eltAddr);
4025  results.push_back(elt);
4026  }
4027 
4028  // If we have one result, it's the single direct result type.
4029  if (results.size() == 1) {
4030  RV = results[0];
4031 
4032  // Otherwise, we need to make a first-class aggregate.
4033  } else {
4034  // Construct a return type that lacks padding elements.
4035  llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
4036 
4037  RV = llvm::PoisonValue::get(returnType);
4038  for (unsigned i = 0, e = results.size(); i != e; ++i) {
4039  RV = Builder.CreateInsertValue(RV, results[i], i);
4040  }
4041  }
4042  break;
4043  }
4044  case ABIArgInfo::Expand:
4046  llvm_unreachable("Invalid ABI kind for return argument");
4047  }
4048 
4049  llvm::Instruction *Ret;
4050  if (RV) {
4051  if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
4052  // For certain return types, clear padding bits, as they may reveal
4053  // sensitive information.
4054  // Small struct/union types are passed as integers.
4055  auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
4056  if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
4057  RV = EmitCMSEClearRecord(RV, ITy, RetTy);
4058  }
4060  Ret = Builder.CreateRet(RV);
4061  } else {
4062  Ret = Builder.CreateRetVoid();
4063  }
4064 
4065  if (RetDbgLoc)
4066  Ret->setDebugLoc(std::move(RetDbgLoc));
4067 }
4068 
4070  // A current decl may not be available when emitting vtable thunks.
4071  if (!CurCodeDecl)
4072  return;
4073 
4074  // If the return block isn't reachable, neither is this check, so don't emit
4075  // it.
4076  if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
4077  return;
4078 
4079  ReturnsNonNullAttr *RetNNAttr = nullptr;
4080  if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
4081  RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
4082 
4083  if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
4084  return;
4085 
4086  // Prefer the returns_nonnull attribute if it's present.
4087  SourceLocation AttrLoc;
4088  SanitizerMask CheckKind;
4089  SanitizerHandler Handler;
4090  if (RetNNAttr) {
4091  assert(!requiresReturnValueNullabilityCheck() &&
4092  "Cannot check nullability and the nonnull attribute");
4093  AttrLoc = RetNNAttr->getLocation();
4094  CheckKind = SanitizerKind::ReturnsNonnullAttribute;
4095  Handler = SanitizerHandler::NonnullReturn;
4096  } else {
4097  if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
4098  if (auto *TSI = DD->getTypeSourceInfo())
4099  if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
4100  AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
4101  CheckKind = SanitizerKind::NullabilityReturn;
4102  Handler = SanitizerHandler::NullabilityReturn;
4103  }
4104 
4105  SanitizerScope SanScope(this);
4106 
4107  // Make sure the "return" source location is valid. If we're checking a
4108  // nullability annotation, make sure the preconditions for the check are met.
4109  llvm::BasicBlock *Check = createBasicBlock("nullcheck");
4110  llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
4111  llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
4112  llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
4113  if (requiresReturnValueNullabilityCheck())
4114  CanNullCheck =
4115  Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
4116  Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
4117  EmitBlock(Check);
4118 
4119  // Now do the null check.
4120  llvm::Value *Cond = Builder.CreateIsNotNull(RV);
4121  llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
4122  llvm::Value *DynamicData[] = {SLocPtr};
4123  EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
4124 
4125  EmitBlock(NoCheck);
4126 
4127 #ifndef NDEBUG
4128  // The return location should not be used after the check has been emitted.
4129  ReturnLocation = Address::invalid();
4130 #endif
4131 }
4132 
4134  const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
4135  return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
4136 }
4137 
4139  QualType Ty) {
4140  // FIXME: Generate IR in one pass, rather than going back and fixing up these
4141  // placeholders.
4142  llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
4143  llvm::Type *IRPtrTy = llvm::PointerType::getUnqual(CGF.getLLVMContext());
4144  llvm::Value *Placeholder = llvm::PoisonValue::get(IRPtrTy);
4145 
4146  // FIXME: When we generate this IR in one pass, we shouldn't need
4147  // this win32-specific alignment hack.
4149  Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
4150 
4151  return AggValueSlot::forAddr(Address(Placeholder, IRTy, Align),
4152  Ty.getQualifiers(),
4157 }
4158 
4160  const VarDecl *param,
4161  SourceLocation loc) {
4162  // StartFunction converted the ABI-lowered parameter(s) into a
4163  // local alloca. We need to turn that into an r-value suitable
4164  // for EmitCall.
4165  Address local = GetAddrOfLocalVar(param);
4166 
4167  QualType type = param->getType();
4168 
4169  // GetAddrOfLocalVar returns a pointer-to-pointer for references,
4170  // but the argument needs to be the original pointer.
4171  if (type->isReferenceType()) {
4173 
4174  // In ARC, move out of consumed arguments so that the release cleanup
4175  // entered by StartFunction doesn't cause an over-release. This isn't
4176  // optimal -O0 code generation, but it should get cleaned up when
4177  // optimization is enabled. This also assumes that delegate calls are
4178  // performed exactly once for a set of arguments, but that should be safe.
4179  } else if (getLangOpts().ObjCAutoRefCount &&
4180  param->hasAttr<NSConsumedAttr>() &&
4181  type->isObjCRetainableType()) {
4182  llvm::Value *ptr = Builder.CreateLoad(local);
4183  auto null =
4184  llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
4185  Builder.CreateStore(null, local);
4186  args.add(RValue::get(ptr), type);
4187 
4188  // For the most part, we just need to load the alloca, except that
4189  // aggregate r-values are actually pointers to temporaries.
4190  } else {
4191  args.add(convertTempToRValue(local, type, loc), type);
4192  }
4193 
4194  // Deactivate the cleanup for the callee-destructed param that was pushed.
4195  if (type->isRecordType() && !CurFuncIsThunk &&
4196  type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
4197  param->needsDestruction(getContext())) {
4199  CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
4200  assert(cleanup.isValid() &&
4201  "cleanup for callee-destructed param not recorded");
4202  // This unreachable is a temporary marker which will be removed later.
4203  llvm::Instruction *isActive = Builder.CreateUnreachable();
4204  args.addArgCleanupDeactivation(cleanup, isActive);
4205  }
4206 }
4207 
4208 static bool isProvablyNull(llvm::Value *addr) {
4209  return llvm::isa_and_nonnull<llvm::ConstantPointerNull>(addr);
4210 }
4211 
4212 static bool isProvablyNonNull(Address Addr, CodeGenFunction &CGF) {
4213  return llvm::isKnownNonZero(Addr.getBasePointer(), CGF.CGM.getDataLayout());
4214 }
4215 
4216 /// Emit the actual writing-back of a writeback.
4218  const CallArgList::Writeback &writeback) {
4219  const LValue &srcLV = writeback.Source;
4220  Address srcAddr = srcLV.getAddress();
4221  assert(!isProvablyNull(srcAddr.getBasePointer()) &&
4222  "shouldn't have writeback for provably null argument");
4223 
4224  llvm::BasicBlock *contBB = nullptr;
4225 
4226  // If the argument wasn't provably non-null, we need to null check
4227  // before doing the store.
4228  bool provablyNonNull = isProvablyNonNull(srcAddr, CGF);
4229 
4230  if (!provablyNonNull) {
4231  llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
4232  contBB = CGF.createBasicBlock("icr.done");
4233 
4234  llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
4235  CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
4236  CGF.EmitBlock(writebackBB);
4237  }
4238 
4239  // Load the value to writeback.
4240  llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
4241 
4242  // Cast it back, in case we're writing an id to a Foo* or something.
4243  value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
4244  "icr.writeback-cast");
4245 
4246  // Perform the writeback.
4247 
4248  // If we have a "to use" value, it's something we need to emit a use
4249  // of. This has to be carefully threaded in: if it's done after the
4250  // release it's potentially undefined behavior (and the optimizer
4251  // will ignore it), and if it happens before the retain then the
4252  // optimizer could move the release there.
4253  if (writeback.ToUse) {
4254  assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
4255 
4256  // Retain the new value. No need to block-copy here: the block's
4257  // being passed up the stack.
4258  value = CGF.EmitARCRetainNonBlock(value);
4259 
4260  // Emit the intrinsic use here.
4261  CGF.EmitARCIntrinsicUse(writeback.ToUse);
4262 
4263  // Load the old value (primitively).
4264  llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
4265 
4266  // Put the new value in place (primitively).
4267  CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
4268 
4269  // Release the old value.
4270  CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
4271 
4272  // Otherwise, we can just do a normal lvalue store.
4273  } else {
4274  CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
4275  }
4276 
4277  // Jump to the continuation block.
4278  if (!provablyNonNull)
4279  CGF.EmitBlock(contBB);
4280 }
4281 
4283  const CallArgList &args) {
4284  for (const auto &I : args.writebacks())
4285  emitWriteback(CGF, I);
4286 }
4287 
4289  const CallArgList &CallArgs) {
4291  CallArgs.getCleanupsToDeactivate();
4292  // Iterate in reverse to increase the likelihood of popping the cleanup.
4293  for (const auto &I : llvm::reverse(Cleanups)) {
4294  CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
4295  I.IsActiveIP->eraseFromParent();
4296  }
4297 }
4298 
4299 static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
4300  if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
4301  if (uop->getOpcode() == UO_AddrOf)
4302  return uop->getSubExpr();
4303  return nullptr;
4304 }
4305 
4306 /// Emit an argument that's being passed call-by-writeback. That is,
4307 /// we are passing the address of an __autoreleased temporary; it
4308 /// might be copy-initialized with the current value of the given
4309 /// address, but it will definitely be copied out of after the call.
4311  const ObjCIndirectCopyRestoreExpr *CRE) {
4312  LValue srcLV;
4313 
4314  // Make an optimistic effort to emit the address as an l-value.
4315  // This can fail if the argument expression is more complicated.
4316  if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
4317  srcLV = CGF.EmitLValue(lvExpr);
4318 
4319  // Otherwise, just emit it as a scalar.
4320  } else {
4321  Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
4322 
4323  QualType srcAddrType =
4324  CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
4325  srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
4326  }
4327  Address srcAddr = srcLV.getAddress();
4328 
4329  // The dest and src types don't necessarily match in LLVM terms
4330  // because of the crazy ObjC compatibility rules.
4331 
4332  llvm::PointerType *destType =
4333  cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
4334  llvm::Type *destElemType =
4335  CGF.ConvertTypeForMem(CRE->getType()->getPointeeType());
4336 
4337  // If the address is a constant null, just pass the appropriate null.
4338  if (isProvablyNull(srcAddr.getBasePointer())) {
4339  args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
4340  CRE->getType());
4341  return;
4342  }
4343 
4344  // Create the temporary.
4345  Address temp =
4346  CGF.CreateTempAlloca(destElemType, CGF.getPointerAlign(), "icr.temp");
4347  // Loading an l-value can introduce a cleanup if the l-value is __weak,
4348  // and that cleanup will be conditional if we can't prove that the l-value
4349  // isn't null, so we need to register a dominating point so that the cleanups
4350  // system will make valid IR.
4352 
4353  // Zero-initialize it if we're not doing a copy-initialization.
4354  bool shouldCopy = CRE->shouldCopy();
4355  if (!shouldCopy) {
4356  llvm::Value *null =
4357  llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destElemType));
4358  CGF.Builder.CreateStore(null, temp);
4359  }
4360 
4361  llvm::BasicBlock *contBB = nullptr;
4362  llvm::BasicBlock *originBB = nullptr;
4363 
4364  // If the address is *not* known to be non-null, we need to switch.
4365  llvm::Value *finalArgument;
4366 
4367  bool provablyNonNull = isProvablyNonNull(srcAddr, CGF);
4368 
4369  if (provablyNonNull) {
4370  finalArgument = temp.emitRawPointer(CGF);
4371  } else {
4372  llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
4373 
4374  finalArgument = CGF.Builder.CreateSelect(
4375  isNull, llvm::ConstantPointerNull::get(destType),
4376  temp.emitRawPointer(CGF), "icr.argument");
4377 
4378  // If we need to copy, then the load has to be conditional, which
4379  // means we need control flow.
4380  if (shouldCopy) {
4381  originBB = CGF.Builder.GetInsertBlock();
4382  contBB = CGF.createBasicBlock("icr.cont");
4383  llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
4384  CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
4385  CGF.EmitBlock(copyBB);
4386  condEval.begin(CGF);
4387  }
4388  }
4389 
4390  llvm::Value *valueToUse = nullptr;
4391 
4392  // Perform a copy if necessary.
4393  if (shouldCopy) {
4394  RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
4395  assert(srcRV.isScalar());
4396 
4397  llvm::Value *src = srcRV.getScalarVal();
4398  src = CGF.Builder.CreateBitCast(src, destElemType, "icr.cast");
4399 
4400  // Use an ordinary store, not a store-to-lvalue.
4401  CGF.Builder.CreateStore(src, temp);
4402 
4403  // If optimization is enabled, and the value was held in a
4404  // __strong variable, we need to tell the optimizer that this
4405  // value has to stay alive until we're doing the store back.
4406  // This is because the temporary is effectively unretained,
4407  // and so otherwise we can violate the high-level semantics.
4408  if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4410  valueToUse = src;
4411  }
4412  }
4413 
4414  // Finish the control flow if we needed it.
4415  if (shouldCopy && !provablyNonNull) {
4416  llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
4417  CGF.EmitBlock(contBB);
4418 
4419  // Make a phi for the value to intrinsically use.
4420  if (valueToUse) {
4421  llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
4422  "icr.to-use");
4423  phiToUse->addIncoming(valueToUse, copyBB);
4424  phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
4425  originBB);
4426  valueToUse = phiToUse;
4427  }
4428 
4429  condEval.end(CGF);
4430  }
4431 
4432  args.addWriteback(srcLV, temp, valueToUse);
4433  args.add(RValue::get(finalArgument), CRE->getType());
4434 }
4435 
4437  assert(!StackBase);
4438 
4439  // Save the stack.
4440  StackBase = CGF.Builder.CreateStackSave("inalloca.save");
4441 }
4442 
4444  if (StackBase) {
4445  // Restore the stack after the call.
4446  CGF.Builder.CreateStackRestore(StackBase);
4447  }
4448 }
4449 
4451  SourceLocation ArgLoc,
4452  AbstractCallee AC,
4453  unsigned ParmNum) {
4454  if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4455  SanOpts.has(SanitizerKind::NullabilityArg)))
4456  return;
4457 
4458  // The param decl may be missing in a variadic function.
4459  auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
4460  unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
4461 
4462  // Prefer the nonnull attribute if it's present.
4463  const NonNullAttr *NNAttr = nullptr;
4464  if (SanOpts.has(SanitizerKind::NonnullAttribute))
4465  NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
4466 
4467  bool CanCheckNullability = false;
4468  if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD &&
4469  !PVD->getType()->isRecordType()) {
4470  auto Nullability = PVD->getType()->getNullability();
4471  CanCheckNullability = Nullability &&
4473  PVD->getTypeSourceInfo();
4474  }
4475 
4476  if (!NNAttr && !CanCheckNullability)
4477  return;
4478 
4479  SourceLocation AttrLoc;
4480  SanitizerMask CheckKind;
4481  SanitizerHandler Handler;
4482  if (NNAttr) {
4483  AttrLoc = NNAttr->getLocation();
4484  CheckKind = SanitizerKind::NonnullAttribute;
4485  Handler = SanitizerHandler::NonnullArg;
4486  } else {
4487  AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
4488  CheckKind = SanitizerKind::NullabilityArg;
4489  Handler = SanitizerHandler::NullabilityArg;
4490  }
4491 
4492  SanitizerScope SanScope(this);
4493  llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
4494  llvm::Constant *StaticData[] = {
4496  llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
4497  };
4498  EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, std::nullopt);
4499 }
4500 
4502  SourceLocation ArgLoc,
4503  AbstractCallee AC, unsigned ParmNum) {
4504  if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4505  SanOpts.has(SanitizerKind::NullabilityArg)))
4506  return;
4507 
4508  EmitNonNullArgCheck(RValue::get(Addr, *this), ArgType, ArgLoc, AC, ParmNum);
4509 }
4510 
4511 // Check if the call is going to use the inalloca convention. This needs to
4512 // agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4513 // later, so we can't check it directly.
4514 static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
4515  ArrayRef<QualType> ArgTypes) {
4516  // The Swift calling conventions don't go through the target-specific
4517  // argument classification, they never use inalloca.
4518  // TODO: Consider limiting inalloca use to only calling conventions supported
4519  // by MSVC.
4520  if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
4521  return false;
4522  if (!CGM.getTarget().getCXXABI().isMicrosoft())
4523  return false;
4524  return llvm::any_of(ArgTypes, [&](QualType Ty) {
4525  return isInAllocaArgument(CGM.getCXXABI(), Ty);
4526  });
4527 }
4528 
4529 #ifndef NDEBUG
4530 // Determine whether the given argument is an Objective-C method
4531 // that may have type parameters in its signature.
4532 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4533  const DeclContext *dc = method->getDeclContext();
4534  if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
4535  return classDecl->getTypeParamListAsWritten();
4536  }
4537 
4538  if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4539  return catDecl->getTypeParamList();
4540  }
4541 
4542  return false;
4543 }
4544 #endif
4545 
4546 /// EmitCallArgs - Emit call arguments for a function.
4548  CallArgList &Args, PrototypeWrapper Prototype,
4549  llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4550  AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
4551  SmallVector<QualType, 16> ArgTypes;
4552 
4553  assert((ParamsToSkip == 0 || Prototype.P) &&
4554  "Can't skip parameters if type info is not provided");
4555 
4556  // This variable only captures *explicitly* written conventions, not those
4557  // applied by default via command line flags or target defaults, such as
4558  // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4559  // require knowing if this is a C++ instance method or being able to see
4560  // unprototyped FunctionTypes.
4561  CallingConv ExplicitCC = CC_C;
4562 
4563  // First, if a prototype was provided, use those argument types.
4564  bool IsVariadic = false;
4565  if (Prototype.P) {
4566  const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>();
4567  if (MD) {
4568  IsVariadic = MD->isVariadic();
4569  ExplicitCC = getCallingConventionForDecl(
4570  MD, CGM.getTarget().getTriple().isOSWindows());
4571  ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
4572  MD->param_type_end());
4573  } else {
4574  const auto *FPT = Prototype.P.get<const FunctionProtoType *>();
4575  IsVariadic = FPT->isVariadic();
4576  ExplicitCC = FPT->getExtInfo().getCC();
4577  ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
4578  FPT->param_type_end());
4579  }
4580 
4581 #ifndef NDEBUG
4582  // Check that the prototyped types match the argument expression types.
4583  bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
4584  CallExpr::const_arg_iterator Arg = ArgRange.begin();
4585  for (QualType Ty : ArgTypes) {
4586  assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4587  assert(
4588  (isGenericMethod || Ty->isVariablyModifiedType() ||
4590  getContext()
4591  .getCanonicalType(Ty.getNonReferenceType())
4592  .getTypePtr() ==
4593  getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
4594  "type mismatch in call argument!");
4595  ++Arg;
4596  }
4597 
4598  // Either we've emitted all the call args, or we have a call to variadic
4599  // function.
4600  assert((Arg == ArgRange.end() || IsVariadic) &&
4601  "Extra arguments in non-variadic function!");
4602 #endif
4603  }
4604 
4605  // If we still have any arguments, emit them using the type of the argument.
4606  for (auto *A : llvm::drop_begin(ArgRange, ArgTypes.size()))
4607  ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
4608  assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
4609 
4610  // We must evaluate arguments from right to left in the MS C++ ABI,
4611  // because arguments are destroyed left to right in the callee. As a special
4612  // case, there are certain language constructs that require left-to-right
4613  // evaluation, and in those cases we consider the evaluation order requirement
4614  // to trump the "destruction order is reverse construction order" guarantee.
4615  bool LeftToRight =
4619 
4620  auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
4621  RValue EmittedArg) {
4622  if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
4623  return;
4624  auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
4625  if (PS == nullptr)
4626  return;
4627 
4628  const auto &Context = getContext();
4629  auto SizeTy = Context.getSizeType();
4630  auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
4631  assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
4632  llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
4633  EmittedArg.getScalarVal(),
4634  PS->isDynamic());
4635  Args.add(RValue::get(V), SizeTy);
4636  // If we're emitting args in reverse, be sure to do so with
4637  // pass_object_size, as well.
4638  if (!LeftToRight)
4639  std::swap(Args.back(), *(&Args.back() - 1));
4640  };
4641 
4642  // Insert a stack save if we're going to need any inalloca args.
4643  if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
4644  assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
4645  "inalloca only supported on x86");
4646  Args.allocateArgumentMemory(*this);
4647  }
4648 
4649  // Evaluate each argument in the appropriate order.
4650  size_t CallArgsStart = Args.size();
4651  for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
4652  unsigned Idx = LeftToRight ? I : E - I - 1;
4653  CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
4654  unsigned InitialArgSize = Args.size();
4655  // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
4656  // the argument and parameter match or the objc method is parameterized.
4657  assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
4658  getContext().hasSameUnqualifiedType((*Arg)->getType(),
4659  ArgTypes[Idx]) ||
4660  (isa<ObjCMethodDecl>(AC.getDecl()) &&
4661  isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
4662  "Argument and parameter types don't match");
4663  EmitCallArg(Args, *Arg, ArgTypes[Idx]);
4664  // In particular, we depend on it being the last arg in Args, and the
4665  // objectsize bits depend on there only being one arg if !LeftToRight.
4666  assert(InitialArgSize + 1 == Args.size() &&
4667  "The code below depends on only adding one arg per EmitCallArg");
4668  (void)InitialArgSize;
4669  // Since pointer argument are never emitted as LValue, it is safe to emit
4670  // non-null argument check for r-value only.
4671  if (!Args.back().hasLValue()) {
4672  RValue RVArg = Args.back().getKnownRValue();
4673  EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
4674  ParamsToSkip + Idx);
4675  // @llvm.objectsize should never have side-effects and shouldn't need
4676  // destruction/cleanups, so we can safely "emit" it after its arg,
4677  // regardless of right-to-leftness
4678  MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
4679  }
4680  }
4681 
4682  if (!LeftToRight) {
4683  // Un-reverse the arguments we just evaluated so they match up with the LLVM
4684  // IR function.
4685  std::reverse(Args.begin() + CallArgsStart, Args.end());
4686  }
4687 }
4688 
4689 namespace {
4690 
4691 struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
4692  DestroyUnpassedArg(Address Addr, QualType Ty)
4693  : Addr(Addr), Ty(Ty) {}
4694 
4695  Address Addr;
4696  QualType Ty;
4697 
4698  void Emit(CodeGenFunction &CGF, Flags flags) override {
4700  if (DtorKind == QualType::DK_cxx_destructor) {
4701  const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
4702  assert(!Dtor->isTrivial());
4703  CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
4704  /*Delegating=*/false, Addr, Ty);
4705  } else {
4706  CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
4707  }
4708  }
4709 };
4710 
4711 struct DisableDebugLocationUpdates {
4712  CodeGenFunction &CGF;
4713  bool disabledDebugInfo;
4714  DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
4715  if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
4716  CGF.disableDebugInfo();
4717  }
4718  ~DisableDebugLocationUpdates() {
4719  if (disabledDebugInfo)
4720  CGF.enableDebugInfo();
4721  }
4722 };
4723 
4724 } // end anonymous namespace
4725 
4727  if (!HasLV)
4728  return RV;
4731  LV.isVolatile());
4732  IsUsed = true;
4733  return RValue::getAggregate(Copy.getAddress());
4734 }
4735 
4737  LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
4738  if (!HasLV && RV.isScalar())
4739  CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
4740  else if (!HasLV && RV.isComplex())
4741  CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
4742  else {
4743  auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
4744  LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
4745  // We assume that call args are never copied into subobjects.
4747  HasLV ? LV.isVolatileQualified()
4748  : RV.isVolatileQualified());
4749  }
4750  IsUsed = true;
4751 }
4752 
4754  QualType type) {
4755  DisableDebugLocationUpdates Dis(*this, E);
4756  if (const ObjCIndirectCopyRestoreExpr *CRE
4757  = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
4758  assert(getLangOpts().ObjCAutoRefCount);
4759  return emitWritebackArg(*this, args, CRE);
4760  }
4761 
4762  assert(type->isReferenceType() == E->isGLValue() &&
4763  "reference binding to unmaterialized r-value!");
4764 
4765  if (E->isGLValue()) {
4766  assert(E->getObjectKind() == OK_Ordinary);
4767  return args.add(EmitReferenceBindingToExpr(E), type);
4768  }
4769 
4770  bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
4771 
4772  // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
4773  // However, we still have to push an EH-only cleanup in case we unwind before
4774  // we make it to the call.
4775  if (type->isRecordType() &&
4776  type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
4777  // If we're using inalloca, use the argument memory. Otherwise, use a
4778  // temporary.
4779  AggValueSlot Slot = args.isUsingInAlloca()
4780  ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
4781 
4782  bool DestroyedInCallee = true, NeedsCleanup = true;
4783  if (const auto *RD = type->getAsCXXRecordDecl())
4784  DestroyedInCallee = RD->hasNonTrivialDestructor();
4785  else
4786  NeedsCleanup = type.isDestructedType();
4787 
4788  if (DestroyedInCallee)
4789  Slot.setExternallyDestructed();
4790 
4791  EmitAggExpr(E, Slot);
4792  RValue RV = Slot.asRValue();
4793  args.add(RV, type);
4794 
4795  if (DestroyedInCallee && NeedsCleanup) {
4796  // Create a no-op GEP between the placeholder and the cleanup so we can
4797  // RAUW it successfully. It also serves as a marker of the first
4798  // instruction where the cleanup is active.
4799  pushFullExprCleanup<DestroyUnpassedArg>(NormalAndEHCleanup,
4800  Slot.getAddress(), type);
4801  // This unreachable is a temporary marker which will be removed later.
4802  llvm::Instruction *IsActive =
4803  Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
4805  }
4806  return;
4807  }
4808 
4809  if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
4810  cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue &&
4811  !type->isArrayParameterType()) {
4812  LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
4813  assert(L.isSimple());
4814  args.addUncopiedAggregate(L, type);
4815  return;
4816  }
4817 
4818  args.add(EmitAnyExprToTemp(E), type);
4819 }
4820 
4821 QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
4822  // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
4823  // implicitly widens null pointer constants that are arguments to varargs
4824  // functions to pointer-sized ints.
4825  if (!getTarget().getTriple().isOSWindows())
4826  return Arg->getType();
4827 
4828  if (Arg->getType()->isIntegerType() &&
4829  getContext().getTypeSize(Arg->getType()) <
4830  getContext().getTargetInfo().getPointerWidth(LangAS::Default) &&
4833  return getContext().getIntPtrType();
4834  }
4835 
4836  return Arg->getType();
4837 }
4838 
4839 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4840 // optimizer it can aggressively ignore unwind edges.
4841 void
4842 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
4843  if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4844  !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
4845  Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
4847 }
4848 
4849 /// Emits a call to the given no-arguments nounwind runtime function.
4850 llvm::CallInst *
4851 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4852  const llvm::Twine &name) {
4854 }
4855 
4856 /// Emits a call to the given nounwind runtime function.
4857 llvm::CallInst *
4858 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4859  ArrayRef<Address> args,
4860  const llvm::Twine &name) {
4862  for (auto arg : args)
4863  values.push_back(arg.emitRawPointer(*this));
4864  return EmitNounwindRuntimeCall(callee, values, name);
4865 }
4866 
4867 llvm::CallInst *
4868 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4870  const llvm::Twine &name) {
4871  llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
4872  call->setDoesNotThrow();
4873  return call;
4874 }
4875 
4876 /// Emits a simple call (never an invoke) to the given no-arguments
4877 /// runtime function.
4878 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4879  const llvm::Twine &name) {
4880  return EmitRuntimeCall(callee, std::nullopt, name);
4881 }
4882 
4883 // Calls which may throw must have operand bundles indicating which funclet
4884 // they are nested within.
4887  // There is no need for a funclet operand bundle if we aren't inside a
4888  // funclet.
4889  if (!CurrentFuncletPad)
4891 
4892  // Skip intrinsics which cannot throw (as long as they don't lower into
4893  // regular function calls in the course of IR transformations).
4894  if (auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts())) {
4895  if (CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) {
4896  auto IID = CalleeFn->getIntrinsicID();
4897  if (!llvm::IntrinsicInst::mayLowerToFunctionCall(IID))
4899  }
4900  }
4901 
4903  BundleList.emplace_back("funclet", CurrentFuncletPad);
4904  return BundleList;
4905 }
4906 
4907 /// Emits a simple call (never an invoke) to the given runtime function.
4908 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4910  const llvm::Twine &name) {
4911  llvm::CallInst *call = Builder.CreateCall(
4912  callee, args, getBundlesForFunclet(callee.getCallee()), name);
4913  call->setCallingConv(getRuntimeCC());
4914 
4915  if (CGM.shouldEmitConvergenceTokens() && call->isConvergent())
4916  return addControlledConvergenceToken(call);
4917  return call;
4918 }
4919 
4920 /// Emits a call or invoke to the given noreturn runtime function.
4922  llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
4924  getBundlesForFunclet(callee.getCallee());
4925 
4926  if (getInvokeDest()) {
4927  llvm::InvokeInst *invoke =
4928  Builder.CreateInvoke(callee,
4930  getInvokeDest(),
4931  args,
4932  BundleList);
4933  invoke->setDoesNotReturn();
4934  invoke->setCallingConv(getRuntimeCC());
4935  } else {
4936  llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
4937  call->setDoesNotReturn();
4938  call->setCallingConv(getRuntimeCC());
4939  Builder.CreateUnreachable();
4940  }
4941 }
4942 
4943 /// Emits a call or invoke instruction to the given nullary runtime function.
4944 llvm::CallBase *
4945 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4946  const Twine &name) {
4947  return EmitRuntimeCallOrInvoke(callee, std::nullopt, name);
4948 }
4949 
4950 /// Emits a call or invoke instruction to the given runtime function.
4951 llvm::CallBase *
4952 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4954  const Twine &name) {
4955  llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
4956  call->setCallingConv(getRuntimeCC());
4957  return call;
4958 }
4959 
4960 /// Emits a call or invoke instruction to the given function, depending
4961 /// on the current state of the EH stack.
4962 llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
4964  const Twine &Name) {
4965  llvm::BasicBlock *InvokeDest = getInvokeDest();
4967  getBundlesForFunclet(Callee.getCallee());
4968 
4969  llvm::CallBase *Inst;
4970  if (!InvokeDest)
4971  Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
4972  else {
4973  llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
4974  Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
4975  Name);
4976  EmitBlock(ContBB);
4977  }
4978 
4979  // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4980  // optimizer it can aggressively ignore unwind edges.
4981  if (CGM.getLangOpts().ObjCAutoRefCount)
4982  AddObjCARCExceptionMetadata(Inst);
4983 
4984  return Inst;
4985 }
4986 
4987 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
4988  llvm::Value *New) {
4989  DeferredReplacements.push_back(
4990  std::make_pair(llvm::WeakTrackingVH(Old), New));
4991 }
4992 
4993 namespace {
4994 
4995 /// Specify given \p NewAlign as the alignment of return value attribute. If
4996 /// such attribute already exists, re-set it to the maximal one of two options.
4997 [[nodiscard]] llvm::AttributeList
4998 maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
4999  const llvm::AttributeList &Attrs,
5000  llvm::Align NewAlign) {
5001  llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
5002  if (CurAlign >= NewAlign)
5003  return Attrs;
5004  llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
5005  return Attrs.removeRetAttribute(Ctx, llvm::Attribute::AttrKind::Alignment)
5006  .addRetAttribute(Ctx, AlignAttr);
5007 }
5008 
5009 template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
5010 protected:
5011  CodeGenFunction &CGF;
5012 
5013  /// We do nothing if this is, or becomes, nullptr.
5014  const AlignedAttrTy *AA = nullptr;
5015 
5016  llvm::Value *Alignment = nullptr; // May or may not be a constant.
5017  llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
5018 
5019  AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
5020  : CGF(CGF_) {
5021  if (!FuncDecl)
5022  return;
5023  AA = FuncDecl->getAttr<AlignedAttrTy>();
5024  }
5025 
5026 public:
5027  /// If we can, materialize the alignment as an attribute on return value.
5028  [[nodiscard]] llvm::AttributeList
5029  TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
5030  if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
5031  return Attrs;
5032  const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
5033  if (!AlignmentCI)
5034  return Attrs;
5035  // We may legitimately have non-power-of-2 alignment here.
5036  // If so, this is UB land, emit it via `@llvm.assume` instead.
5037  if (!AlignmentCI->getValue().isPowerOf2())
5038  return Attrs;
5039  llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
5040  CGF.getLLVMContext(), Attrs,
5041  llvm::Align(
5042  AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
5043  AA = nullptr; // We're done. Disallow doing anything else.
5044  return NewAttrs;
5045  }
5046 
5047  /// Emit alignment assumption.
5048  /// This is a general fallback that we take if either there is an offset,
5049  /// or the alignment is variable or we are sanitizing for alignment.
5050  void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
5051  if (!AA)
5052  return;
5053  CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
5054  AA->getLocation(), Alignment, OffsetCI);
5055  AA = nullptr; // We're done. Disallow doing anything else.
5056  }
5057 };
5058 
5059 /// Helper data structure to emit `AssumeAlignedAttr`.
5060 class AssumeAlignedAttrEmitter final
5061  : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
5062 public:
5063  AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
5064  : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
5065  if (!AA)
5066  return;
5067  // It is guaranteed that the alignment/offset are constants.
5068  Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
5069  if (Expr *Offset = AA->getOffset()) {
5070  OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
5071  if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
5072  OffsetCI = nullptr;
5073  }
5074  }
5075 };
5076 
5077 /// Helper data structure to emit `AllocAlignAttr`.
5078 class AllocAlignAttrEmitter final
5079  : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
5080 public:
5081  AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
5082  const CallArgList &CallArgs)
5083  : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
5084  if (!AA)
5085  return;
5086  // Alignment may or may not be a constant, and that is okay.
5087  Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
5088  .getRValue(CGF)
5089  .getScalarVal();
5090  }
5091 };
5092 
5093 } // namespace
5094 
5095 static unsigned getMaxVectorWidth(const llvm::Type *Ty) {
5096  if (auto *VT = dyn_cast<llvm::VectorType>(Ty))
5097  return VT->getPrimitiveSizeInBits().getKnownMinValue();
5098  if (auto *AT = dyn_cast<llvm::ArrayType>(Ty))
5099  return getMaxVectorWidth(AT->getElementType());
5100 
5101  unsigned MaxVectorWidth = 0;
5102  if (auto *ST = dyn_cast<llvm::StructType>(Ty))
5103  for (auto *I : ST->elements())
5104  MaxVectorWidth = std::max(MaxVectorWidth, getMaxVectorWidth(I));
5105  return MaxVectorWidth;
5106 }
5107 
5109  const CGCallee &Callee,
5110  ReturnValueSlot ReturnValue,
5111  const CallArgList &CallArgs,
5112  llvm::CallBase **callOrInvoke, bool IsMustTail,
5113  SourceLocation Loc) {
5114  // FIXME: We no longer need the types from CallArgs; lift up and simplify.
5115 
5116  assert(Callee.isOrdinary() || Callee.isVirtual());
5117 
5118  // Handle struct-return functions by passing a pointer to the
5119  // location that we would like to return into.
5120  QualType RetTy = CallInfo.getReturnType();
5121  const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
5122 
5123  llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
5124 
5125  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
5126  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5127  // We can only guarantee that a function is called from the correct
5128  // context/function based on the appropriate target attributes,
5129  // so only check in the case where we have both always_inline and target
5130  // since otherwise we could be making a conditional call after a check for
5131  // the proper cpu features (and it won't cause code generation issues due to
5132  // function based code generation).
5133  if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
5134  (TargetDecl->hasAttr<TargetAttr>() ||
5135  (CurFuncDecl && CurFuncDecl->hasAttr<TargetAttr>())))
5136  checkTargetFeatures(Loc, FD);
5137  }
5138 
5139  // Some architectures (such as x86-64) have the ABI changed based on
5140  // attribute-target/features. Give them a chance to diagnose.
5142  CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl),
5143  dyn_cast_or_null<FunctionDecl>(TargetDecl), CallArgs, RetTy);
5144 
5145  // 1. Set up the arguments.
5146 
5147  // If we're using inalloca, insert the allocation after the stack save.
5148  // FIXME: Do this earlier rather than hacking it in here!
5149  RawAddress ArgMemory = RawAddress::invalid();
5150  if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
5151  const llvm::DataLayout &DL = CGM.getDataLayout();
5152  llvm::Instruction *IP = CallArgs.getStackBase();
5153  llvm::AllocaInst *AI;
5154  if (IP) {
5155  IP = IP->getNextNode();
5156  AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
5157  "argmem", IP);
5158  } else {
5159  AI = CreateTempAlloca(ArgStruct, "argmem");
5160  }
5161  auto Align = CallInfo.getArgStructAlignment();
5162  AI->setAlignment(Align.getAsAlign());
5163  AI->setUsedWithInAlloca(true);
5164  assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
5165  ArgMemory = RawAddress(AI, ArgStruct, Align);
5166  }
5167 
5168  ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
5169  SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
5170 
5171  // If the call returns a temporary with struct return, create a temporary
5172  // alloca to hold the result, unless one is given to us.
5173  Address SRetPtr = Address::invalid();
5174  RawAddress SRetAlloca = RawAddress::invalid();
5175  llvm::Value *UnusedReturnSizePtr = nullptr;
5176  if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
5177  if (!ReturnValue.isNull()) {
5178  SRetPtr = ReturnValue.getAddress();
5179  } else {
5180  SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
5181  if (HaveInsertPoint() && ReturnValue.isUnused()) {
5182  llvm::TypeSize size =
5183  CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
5184  UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
5185  }
5186  }
5187  if (IRFunctionArgs.hasSRetArg()) {
5188  IRCallArgs[IRFunctionArgs.getSRetArgNo()] =
5189  getAsNaturalPointerTo(SRetPtr, RetTy);
5190  } else if (RetAI.isInAlloca()) {
5191  Address Addr =
5192  Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
5193  Builder.CreateStore(getAsNaturalPointerTo(SRetPtr, RetTy), Addr);
5194  }
5195  }
5196 
5197  RawAddress swiftErrorTemp = RawAddress::invalid();
5198  Address swiftErrorArg = Address::invalid();
5199 
5200  // When passing arguments using temporary allocas, we need to add the
5201  // appropriate lifetime markers. This vector keeps track of all the lifetime
5202  // markers that need to be ended right after the call.
5203  SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
5204 
5205  // Translate all of the arguments as necessary to match the IR lowering.
5206  assert(CallInfo.arg_size() == CallArgs.size() &&
5207  "Mismatch between function signature & arguments.");
5208  unsigned ArgNo = 0;
5209  CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
5210  for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
5211  I != E; ++I, ++info_it, ++ArgNo) {
5212  const ABIArgInfo &ArgInfo = info_it->info;
5213 
5214  // Insert a padding argument to ensure proper alignment.
5215  if (IRFunctionArgs.hasPaddingArg(ArgNo))
5216  IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
5217  llvm::UndefValue::get(ArgInfo.getPaddingType());
5218 
5219  unsigned FirstIRArg, NumIRArgs;
5220  std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
5221 
5222  bool ArgHasMaybeUndefAttr =
5223  IsArgumentMaybeUndef(TargetDecl, CallInfo.getNumRequiredArgs(), ArgNo);
5224 
5225  switch (ArgInfo.getKind()) {
5226  case ABIArgInfo::InAlloca: {
5227  assert(NumIRArgs == 0);
5228  assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
5229  if (I->isAggregate()) {
5230  RawAddress Addr = I->hasLValue()
5231  ? I->getKnownLValue().getAddress()
5232  : I->getKnownRValue().getAggregateAddress();
5233  llvm::Instruction *Placeholder =
5234  cast<llvm::Instruction>(Addr.getPointer());
5235 
5236  if (!ArgInfo.getInAllocaIndirect()) {
5237  // Replace the placeholder with the appropriate argument slot GEP.
5238  CGBuilderTy::InsertPoint IP = Builder.saveIP();
5239  Builder.SetInsertPoint(Placeholder);
5240  Addr = Builder.CreateStructGEP(ArgMemory,
5241  ArgInfo.getInAllocaFieldIndex());
5242  Builder.restoreIP(IP);
5243  } else {
5244  // For indirect things such as overaligned structs, replace the
5245  // placeholder with a regular aggregate temporary alloca. Store the
5246  // address of this alloca into the struct.
5247  Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
5248  Address ArgSlot = Builder.CreateStructGEP(
5249  ArgMemory, ArgInfo.getInAllocaFieldIndex());
5250  Builder.CreateStore(Addr.getPointer(), ArgSlot);
5251  }
5252  deferPlaceholderReplacement(Placeholder, Addr.getPointer());
5253  } else if (ArgInfo.getInAllocaIndirect()) {
5254  // Make a temporary alloca and store the address of it into the argument
5255  // struct.
5257  I->Ty, getContext().getTypeAlignInChars(I->Ty),
5258  "indirect-arg-temp");
5259  I->copyInto(*this, Addr);
5260  Address ArgSlot =
5261  Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
5262  Builder.CreateStore(Addr.getPointer(), ArgSlot);
5263  } else {
5264  // Store the RValue into the argument struct.
5265  Address Addr =
5266  Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
5267  Addr = Addr.withElementType(ConvertTypeForMem(I->Ty));
5268  I->copyInto(*this, Addr);
5269  }
5270  break;
5271  }
5272 
5273  case ABIArgInfo::Indirect:
5275  assert(NumIRArgs == 1);
5276  if (I->isAggregate()) {
5277  // We want to avoid creating an unnecessary temporary+copy here;
5278  // however, we need one in three cases:
5279  // 1. If the argument is not byval, and we are required to copy the
5280  // source. (This case doesn't occur on any common architecture.)
5281  // 2. If the argument is byval, RV is not sufficiently aligned, and
5282  // we cannot force it to be sufficiently aligned.
5283  // 3. If the argument is byval, but RV is not located in default
5284  // or alloca address space.
5285  Address Addr = I->hasLValue()
5286  ? I->getKnownLValue().getAddress()
5287  : I->getKnownRValue().getAggregateAddress();
5288  CharUnits Align = ArgInfo.getIndirectAlign();
5289  const llvm::DataLayout *TD = &CGM.getDataLayout();
5290 
5291  assert((FirstIRArg >= IRFuncTy->getNumParams() ||
5292  IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
5293  TD->getAllocaAddrSpace()) &&
5294  "indirect argument must be in alloca address space");
5295 
5296  bool NeedCopy = false;
5297  if (Addr.getAlignment() < Align &&
5298  llvm::getOrEnforceKnownAlignment(Addr.emitRawPointer(*this),
5299  Align.getAsAlign(),
5300  *TD) < Align.getAsAlign()) {
5301  NeedCopy = true;
5302  } else if (I->hasLValue()) {
5303  auto LV = I->getKnownLValue();
5304  auto AS = LV.getAddressSpace();
5305 
5306  bool isByValOrRef =
5307  ArgInfo.isIndirectAliased() || ArgInfo.getIndirectByVal();
5308 
5309  if (!isByValOrRef ||
5310  (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
5311  NeedCopy = true;
5312  }
5313  if (!getLangOpts().OpenCL) {
5314  if ((isByValOrRef &&
5315  (AS != LangAS::Default &&
5316  AS != CGM.getASTAllocaAddressSpace()))) {
5317  NeedCopy = true;
5318  }
5319  }
5320  // For OpenCL even if RV is located in default or alloca address space
5321  // we don't want to perform address space cast for it.
5322  else if ((isByValOrRef &&
5323  Addr.getType()->getAddressSpace() != IRFuncTy->
5324  getParamType(FirstIRArg)->getPointerAddressSpace())) {
5325  NeedCopy = true;
5326  }
5327  }
5328 
5329  if (!NeedCopy) {
5330  // Skip the extra memcpy call.
5331  llvm::Value *V = getAsNaturalPointerTo(Addr, I->Ty);
5332  auto *T = llvm::PointerType::get(
5333  CGM.getLLVMContext(), CGM.getDataLayout().getAllocaAddrSpace());
5334  llvm::Value *Val = getTargetHooks().performAddrSpaceCast(
5336  true);
5337  if (ArgHasMaybeUndefAttr)
5338  Val = Builder.CreateFreeze(Val);
5339  IRCallArgs[FirstIRArg] = Val;
5340  break;
5341  }
5342  }
5343 
5344  // For non-aggregate args and aggregate args meeting conditions above
5345  // we need to create an aligned temporary, and copy to it.
5347  I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
5348  llvm::Value *Val = getAsNaturalPointerTo(AI, I->Ty);
5349  if (ArgHasMaybeUndefAttr)
5350  Val = Builder.CreateFreeze(Val);
5351  IRCallArgs[FirstIRArg] = Val;
5352 
5353  // Emit lifetime markers for the temporary alloca.
5354  llvm::TypeSize ByvalTempElementSize =
5355  CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
5356  llvm::Value *LifetimeSize =
5357  EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
5358 
5359  // Add cleanup code to emit the end lifetime marker after the call.
5360  if (LifetimeSize) // In case we disabled lifetime markers.
5361  CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
5362 
5363  // Generate the copy.
5364  I->copyInto(*this, AI);
5365  break;
5366  }
5367 
5368  case ABIArgInfo::Ignore:
5369  assert(NumIRArgs == 0);
5370  break;
5371 
5372  case ABIArgInfo::Extend:
5373  case ABIArgInfo::Direct: {
5374  if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
5375  ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
5376  ArgInfo.getDirectOffset() == 0) {
5377  assert(NumIRArgs == 1);
5378  llvm::Value *V;
5379  if (!I->isAggregate())
5380  V = I->getKnownRValue().getScalarVal();
5381  else
5382  V = Builder.CreateLoad(
5383  I->hasLValue() ? I->getKnownLValue().getAddress()
5384  : I->getKnownRValue().getAggregateAddress());
5385 
5386  // Implement swifterror by copying into a new swifterror argument.
5387  // We'll write back in the normal path out of the call.
5388  if (CallInfo.getExtParameterInfo(ArgNo).getABI()
5390  assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
5391 
5392  QualType pointeeTy = I->Ty->getPointeeType();
5393  swiftErrorArg = makeNaturalAddressForPointer(
5394  V, pointeeTy, getContext().getTypeAlignInChars(pointeeTy));
5395 
5396  swiftErrorTemp =
5397  CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
5398  V = swiftErrorTemp.getPointer();
5399  cast<llvm::AllocaInst>(V)->setSwiftError(true);
5400 
5401  llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
5402  Builder.CreateStore(errorValue, swiftErrorTemp);
5403  }
5404 
5405  // We might have to widen integers, but we should never truncate.
5406  if (ArgInfo.getCoerceToType() != V->getType() &&
5407  V->getType()->isIntegerTy())
5408  V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
5409 
5410  // If the argument doesn't match, perform a bitcast to coerce it. This
5411  // can happen due to trivial type mismatches.
5412  if (FirstIRArg < IRFuncTy->getNumParams() &&
5413  V->getType() != IRFuncTy->getParamType(FirstIRArg)) {
5414  if (V->getType()->getPointerAddressSpace() !=
5415  IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace())
5417  IRFuncTy->getParamType(FirstIRArg));
5418  else
5419  V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
5420  }
5421 
5422  if (ArgHasMaybeUndefAttr)
5423  V = Builder.CreateFreeze(V);
5424  IRCallArgs[FirstIRArg] = V;
5425  break;
5426  }
5427 
5428  llvm::StructType *STy =
5429  dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
5430  if (STy && ArgInfo.isDirect() && !ArgInfo.getCanBeFlattened()) {
5431  llvm::Type *SrcTy = ConvertTypeForMem(I->Ty);
5432  [[maybe_unused]] llvm::TypeSize SrcTypeSize =
5433  CGM.getDataLayout().getTypeAllocSize(SrcTy);
5434  [[maybe_unused]] llvm::TypeSize DstTypeSize =
5435  CGM.getDataLayout().getTypeAllocSize(STy);
5436  if (STy->containsHomogeneousScalableVectorTypes()) {
5437  assert(SrcTypeSize == DstTypeSize &&
5438  "Only allow non-fractional movement of structure with "
5439  "homogeneous scalable vector type");
5440 
5441  IRCallArgs[FirstIRArg] = I->getKnownRValue().getScalarVal();
5442  break;
5443  }
5444  }
5445 
5446  // FIXME: Avoid the conversion through memory if possible.
5447  Address Src = Address::invalid();
5448  if (!I->isAggregate()) {
5449  Src = CreateMemTemp(I->Ty, "coerce");
5450  I->copyInto(*this, Src);
5451  } else {
5452  Src = I->hasLValue() ? I->getKnownLValue().getAddress()
5453  : I->getKnownRValue().getAggregateAddress();
5454  }
5455 
5456  // If the value is offset in memory, apply the offset now.
5457  Src = emitAddressAtOffset(*this, Src, ArgInfo);
5458 
5459  // Fast-isel and the optimizer generally like scalar values better than
5460  // FCAs, so we flatten them if this is safe to do for this argument.
5461  if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
5462  llvm::Type *SrcTy = Src.getElementType();
5463  llvm::TypeSize SrcTypeSize =
5464  CGM.getDataLayout().getTypeAllocSize(SrcTy);
5465  llvm::TypeSize DstTypeSize = CGM.getDataLayout().getTypeAllocSize(STy);
5466  if (SrcTypeSize.isScalable()) {
5467  assert(STy->containsHomogeneousScalableVectorTypes() &&
5468  "ABI only supports structure with homogeneous scalable vector "
5469  "type");
5470  assert(SrcTypeSize == DstTypeSize &&
5471  "Only allow non-fractional movement of structure with "
5472  "homogeneous scalable vector type");
5473  assert(NumIRArgs == STy->getNumElements());
5474 
5475  llvm::Value *StoredStructValue =
5476  Builder.CreateLoad(Src, Src.getName() + ".tuple");
5477  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5478  llvm::Value *Extract = Builder.CreateExtractValue(
5479  StoredStructValue, i, Src.getName() + ".extract" + Twine(i));
5480  IRCallArgs[FirstIRArg + i] = Extract;
5481  }
5482  } else {
5483  Src = Src.withElementType(STy);
5484  uint64_t SrcSize = SrcTypeSize.getFixedValue();
5485  uint64_t DstSize = DstTypeSize.getFixedValue();
5486 
5487  // If the source type is smaller than the destination type of the
5488  // coerce-to logic, copy the source value into a temp alloca the size
5489  // of the destination type to allow loading all of it. The bits past
5490  // the source value are left undef.
5491  if (SrcSize < DstSize) {
5492  Address TempAlloca = CreateTempAlloca(STy, Src.getAlignment(),
5493  Src.getName() + ".coerce");
5494  Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
5495  Src = TempAlloca;
5496  } else {
5497  Src = Src.withElementType(STy);
5498  }
5499 
5500  assert(NumIRArgs == STy->getNumElements());
5501  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5502  Address EltPtr = Builder.CreateStructGEP(Src, i);
5503  llvm::Value *LI = Builder.CreateLoad(EltPtr);
5504  if (ArgHasMaybeUndefAttr)
5505  LI = Builder.CreateFreeze(LI);
5506  IRCallArgs[FirstIRArg + i] = LI;
5507  }
5508  }
5509  } else {
5510  // In the simple case, just pass the coerced loaded value.
5511  assert(NumIRArgs == 1);
5512  llvm::Value *Load =
5513  CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
5514 
5515  if (CallInfo.isCmseNSCall()) {
5516  // For certain parameter types, clear padding bits, as they may reveal
5517  // sensitive information.
5518  // Small struct/union types are passed as integer arrays.
5519  auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
5520  if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
5521  Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
5522  }
5523 
5524  if (ArgHasMaybeUndefAttr)
5525  Load = Builder.CreateFreeze(Load);
5526  IRCallArgs[FirstIRArg] = Load;
5527  }
5528 
5529  break;
5530  }
5531 
5533  auto coercionType = ArgInfo.getCoerceAndExpandType();
5534  auto layout = CGM.getDataLayout().getStructLayout(coercionType);
5535 
5536  llvm::Value *tempSize = nullptr;
5537  Address addr = Address::invalid();
5538  RawAddress AllocaAddr = RawAddress::invalid();
5539  if (I->isAggregate()) {
5540  addr = I->hasLValue() ? I->getKnownLValue().getAddress()
5541  : I->getKnownRValue().getAggregateAddress();
5542 
5543  } else {
5544  RValue RV = I->getKnownRValue();
5545  assert(RV.isScalar()); // complex should always just be direct
5546 
5547  llvm::Type *scalarType = RV.getScalarVal()->getType();
5548  auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
5549  auto scalarAlign = CGM.getDataLayout().getPrefTypeAlign(scalarType);
5550 
5551  // Materialize to a temporary.
5552  addr = CreateTempAlloca(
5553  RV.getScalarVal()->getType(),
5554  CharUnits::fromQuantity(std::max(layout->getAlignment(), scalarAlign)),
5555  "tmp",
5556  /*ArraySize=*/nullptr, &AllocaAddr);
5557  tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
5558 
5559  Builder.CreateStore(RV.getScalarVal(), addr);
5560  }
5561 
5562  addr = addr.withElementType(coercionType);
5563 
5564  unsigned IRArgPos = FirstIRArg;
5565  for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5566  llvm::Type *eltType = coercionType->getElementType(i);
5567  if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5568  Address eltAddr = Builder.CreateStructGEP(addr, i);
5569  llvm::Value *elt = Builder.CreateLoad(eltAddr);
5570  if (ArgHasMaybeUndefAttr)
5571  elt = Builder.CreateFreeze(elt);
5572  IRCallArgs[IRArgPos++] = elt;
5573  }
5574  assert(IRArgPos == FirstIRArg + NumIRArgs);
5575 
5576  if (tempSize) {
5577  EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
5578  }
5579 
5580  break;
5581  }
5582 
5583  case ABIArgInfo::Expand: {
5584  unsigned IRArgPos = FirstIRArg;
5585  ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
5586  assert(IRArgPos == FirstIRArg + NumIRArgs);
5587  break;
5588  }
5589  }
5590  }
5591 
5592  const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
5593  llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
5594 
5595  // If we're using inalloca, set up that argument.
5596  if (ArgMemory.isValid()) {
5597  llvm::Value *Arg = ArgMemory.getPointer();
5598  assert(IRFunctionArgs.hasInallocaArg());
5599  IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
5600  }
5601 
5602  // 2. Prepare the function pointer.
5603 
5604  // If the callee is a bitcast of a non-variadic function to have a
5605  // variadic function pointer type, check to see if we can remove the
5606  // bitcast. This comes up with unprototyped functions.
5607  //
5608  // This makes the IR nicer, but more importantly it ensures that we
5609  // can inline the function at -O0 if it is marked always_inline.
5610  auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
5611  llvm::Value *Ptr) -> llvm::Function * {
5612  if (!CalleeFT->isVarArg())
5613  return nullptr;
5614 
5615  // Get underlying value if it's a bitcast
5616  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
5617  if (CE->getOpcode() == llvm::Instruction::BitCast)
5618  Ptr = CE->getOperand(0);
5619  }
5620 
5621  llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
5622  if (!OrigFn)
5623  return nullptr;
5624 
5625  llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
5626 
5627  // If the original type is variadic, or if any of the component types
5628  // disagree, we cannot remove the cast.
5629  if (OrigFT->isVarArg() ||
5630  OrigFT->getNumParams() != CalleeFT->getNumParams() ||
5631  OrigFT->getReturnType() != CalleeFT->getReturnType())
5632  return nullptr;
5633 
5634  for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
5635  if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
5636  return nullptr;
5637 
5638  return OrigFn;
5639  };
5640 
5641  if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
5642  CalleePtr = OrigFn;
5643  IRFuncTy = OrigFn->getFunctionType();
5644  }
5645 
5646  // 3. Perform the actual call.
5647 
5648  // Deactivate any cleanups that we're supposed to do immediately before
5649  // the call.
5650  if (!CallArgs.getCleanupsToDeactivate().empty())
5651  deactivateArgCleanupsBeforeCall(*this, CallArgs);
5652 
5653  // Assert that the arguments we computed match up. The IR verifier
5654  // will catch this, but this is a common enough source of problems
5655  // during IRGen changes that it's way better for debugging to catch
5656  // it ourselves here.
5657 #ifndef NDEBUG
5658  assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
5659  for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
5660  // Inalloca argument can have different type.
5661  if (IRFunctionArgs.hasInallocaArg() &&
5662  i == IRFunctionArgs.getInallocaArgNo())
5663  continue;
5664  if (i < IRFuncTy->getNumParams())
5665  assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
5666  }
5667 #endif
5668 
5669  // Update the largest vector width if any arguments have vector types.
5670  for (unsigned i = 0; i < IRCallArgs.size(); ++i)
5671  LargestVectorWidth = std::max(LargestVectorWidth,
5672  getMaxVectorWidth(IRCallArgs[i]->getType()));
5673 
5674  // Compute the calling convention and attributes.
5675  unsigned CallingConv;
5676  llvm::AttributeList Attrs;
5677  CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
5678  Callee.getAbstractInfo(), Attrs, CallingConv,
5679  /*AttrOnCallSite=*/true,
5680  /*IsThunk=*/false);
5681 
5682  if (CallingConv == llvm::CallingConv::X86_VectorCall &&
5683  getTarget().getTriple().isWindowsArm64EC()) {
5684  CGM.Error(Loc, "__vectorcall calling convention is not currently "
5685  "supported");
5686  }
5687 
5688  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5689  if (FD->hasAttr<StrictFPAttr>())
5690  // All calls within a strictfp function are marked strictfp
5691  Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5692 
5693  // If -ffast-math is enabled and the function is guarded by an
5694  // '__attribute__((optnone)) adjust the memory attribute so the BE emits the
5695  // library call instead of the intrinsic.
5696  if (FD->hasAttr<OptimizeNoneAttr>() && getLangOpts().FastMath)
5697  CGM.AdjustMemoryAttribute(CalleePtr->getName(), Callee.getAbstractInfo(),
5698  Attrs);
5699  }
5700  // Add call-site nomerge attribute if exists.
5702  Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoMerge);
5703 
5704  // Add call-site noinline attribute if exists.
5706  Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5707 
5708  // Add call-site always_inline attribute if exists.
5710  Attrs =
5711  Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5712 
5713  // Apply some call-site-specific attributes.
5714  // TODO: work this into building the attribute set.
5715 
5716  // Apply always_inline to all calls within flatten functions.
5717  // FIXME: should this really take priority over __try, below?
5718  if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
5720  !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
5721  Attrs =
5722  Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5723  }
5724 
5725  // Disable inlining inside SEH __try blocks.
5726  if (isSEHTryScope()) {
5727  Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5728  }
5729 
5730  // Decide whether to use a call or an invoke.
5731  bool CannotThrow;
5732  if (currentFunctionUsesSEHTry()) {
5733  // SEH cares about asynchronous exceptions, so everything can "throw."
5734  CannotThrow = false;
5735  } else if (isCleanupPadScope() &&
5737  // The MSVC++ personality will implicitly terminate the program if an
5738  // exception is thrown during a cleanup outside of a try/catch.
5739  // We don't need to model anything in IR to get this behavior.
5740  CannotThrow = true;
5741  } else {
5742  // Otherwise, nounwind call sites will never throw.
5743  CannotThrow = Attrs.hasFnAttr(llvm::Attribute::NoUnwind);
5744 
5745  if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
5746  if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
5747  CannotThrow = true;
5748  }
5749 
5750  // If we made a temporary, be sure to clean up after ourselves. Note that we
5751  // can't depend on being inside of an ExprWithCleanups, so we need to manually
5752  // pop this cleanup later on. Being eager about this is OK, since this
5753  // temporary is 'invisible' outside of the callee.
5754  if (UnusedReturnSizePtr)
5755  pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
5756  UnusedReturnSizePtr);
5757 
5758  llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
5759 
5761  getBundlesForFunclet(CalleePtr);
5762 
5763  if (SanOpts.has(SanitizerKind::KCFI) &&
5764  !isa_and_nonnull<FunctionDecl>(TargetDecl))
5765  EmitKCFIOperandBundle(ConcreteCallee, BundleList);
5766 
5767  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5768  if (FD->hasAttr<StrictFPAttr>())
5769  // All calls within a strictfp function are marked strictfp
5770  Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5771 
5772  AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
5773  Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5774 
5775  AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
5776  Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5777 
5778  // Emit the actual call/invoke instruction.
5779  llvm::CallBase *CI;
5780  if (!InvokeDest) {
5781  if (!getLangOpts().FPAccuracyFuncMap.empty() ||
5782  !getLangOpts().FPAccuracyVal.empty()) {
5783  const auto *FD = dyn_cast_if_present<FunctionDecl>(TargetDecl);
5784  if (FD && FD->getNameInfo().getName().isIdentifier()) {
5785  CI = MaybeEmitFPBuiltinofFD(IRFuncTy, IRCallArgs, CalleePtr,
5786  FD->getName(), FD->getBuiltinID());
5787  if (CI)
5788  return RValue::get(CI);
5789  }
5790  }
5791  CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
5792  } else {
5793  llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
5794  CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
5795  BundleList);
5796  EmitBlock(Cont);
5797  }
5798  if (CI->getCalledFunction() && CI->getCalledFunction()->hasName() &&
5799  CI->getCalledFunction()->getName().starts_with("_Z4sqrt")) {
5800  SetSqrtFPAccuracy(CI);
5801  }
5802  if (callOrInvoke)
5803  *callOrInvoke = CI;
5804 
5805  // If this is within a function that has the guard(nocf) attribute and is an
5806  // indirect call, add the "guard_nocf" attribute to this call to indicate that
5807  // Control Flow Guard checks should not be added, even if the call is inlined.
5808  if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5809  if (const auto *A = FD->getAttr<CFGuardAttr>()) {
5810  if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
5811  Attrs = Attrs.addFnAttribute(getLLVMContext(), "guard_nocf");
5812  }
5813  }
5814 
5815  // Apply the attributes and calling convention.
5816  CI->setAttributes(Attrs);
5817  CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
5818 
5819  // Apply various metadata.
5820 
5821  if (!CI->getType()->isVoidTy())
5822  CI->setName("call");
5823 
5824  if (CGM.shouldEmitConvergenceTokens() && CI->isConvergent())
5826 
5827  // Update largest vector width from the return type.
5828  LargestVectorWidth =
5829  std::max(LargestVectorWidth, getMaxVectorWidth(CI->getType()));
5830 
5831  // Insert instrumentation or attach profile metadata at indirect call sites.
5832  // For more details, see the comment before the definition of
5833  // IPVK_IndirectCallTarget in InstrProfData.inc.
5834  if (!CI->getCalledFunction())
5835  PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
5836  CI, CalleePtr);
5837 
5838  // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5839  // optimizer it can aggressively ignore unwind edges.
5840  if (CGM.getLangOpts().ObjCAutoRefCount)
5841  AddObjCARCExceptionMetadata(CI);
5842 
5843  // Set tail call kind if necessary.
5844  if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
5845  if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
5846  Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
5847  else if (IsMustTail)
5848  Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
5849  }
5850 
5851  // Add metadata for calls to MSAllocator functions
5852  if (getDebugInfo() && TargetDecl &&
5853  TargetDecl->hasAttr<MSAllocatorAttr>())
5855 
5856  // Add metadata if calling an __attribute__((error(""))) or warning fn.
5857  if (TargetDecl && TargetDecl->hasAttr<ErrorAttr>()) {
5858  llvm::ConstantInt *Line =
5859  llvm::ConstantInt::get(Int32Ty, Loc.getRawEncoding());
5860  llvm::ConstantAsMetadata *MD = llvm::ConstantAsMetadata::get(Line);
5861  llvm::MDTuple *MDT = llvm::MDNode::get(getLLVMContext(), {MD});
5862  CI->setMetadata("srcloc", MDT);
5863  }
5864 
5865  // 4. Finish the call.
5866 
5867  // SYCL does not support C++ exceptions or termination in device code, so all
5868  // functions have to return.
5869  bool SyclSkipNoReturn = false;
5870  if (getLangOpts().SYCLIsDevice && CI->doesNotReturn()) {
5871  if (auto *F = CI->getCalledFunction())
5872  F->removeFnAttr(llvm::Attribute::NoReturn);
5873  CI->removeFnAttr(llvm::Attribute::NoReturn);
5874  SyclSkipNoReturn = true;
5875  }
5876 
5877  // If the call doesn't return for non-sycl devices, finish the basic block and
5878  // clear the insertion point; this allows the rest of IRGen to discard
5879  // unreachable code.
5880  if (!SyclSkipNoReturn && CI->doesNotReturn()) {
5881  if (UnusedReturnSizePtr)
5882  PopCleanupBlock();
5883 
5884  // Strip away the noreturn attribute to better diagnose unreachable UB.
5885  if (SanOpts.has(SanitizerKind::Unreachable)) {
5886  // Also remove from function since CallBase::hasFnAttr additionally checks
5887  // attributes of the called function.
5888  if (auto *F = CI->getCalledFunction())
5889  F->removeFnAttr(llvm::Attribute::NoReturn);
5890  CI->removeFnAttr(llvm::Attribute::NoReturn);
5891 
5892  // Avoid incompatibility with ASan which relies on the `noreturn`
5893  // attribute to insert handler calls.
5894  if (SanOpts.hasOneOf(SanitizerKind::Address |
5895  SanitizerKind::KernelAddress)) {
5896  SanitizerScope SanScope(this);
5897  llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
5898  Builder.SetInsertPoint(CI);
5899  auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
5900  llvm::FunctionCallee Fn =
5901  CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
5903  }
5904  }
5905 
5907  Builder.ClearInsertionPoint();
5908 
5909  // FIXME: For now, emit a dummy basic block because expr emitters in
5910  // generally are not ready to handle emitting expressions at unreachable
5911  // points.
5913 
5914  // Return a reasonable RValue.
5915  return GetUndefRValue(RetTy);
5916  }
5917 
5918  // If this is a musttail call, return immediately. We do not branch to the
5919  // epilogue in this case.
5920  if (IsMustTail) {
5921  for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
5922  ++it) {
5923  EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
5924  if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
5925  CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
5926  }
5927  if (CI->getType()->isVoidTy())
5928  Builder.CreateRetVoid();
5929  else
5930  Builder.CreateRet(CI);
5931  Builder.ClearInsertionPoint();
5933  return GetUndefRValue(RetTy);
5934  }
5935 
5936  // Perform the swifterror writeback.
5937  if (swiftErrorTemp.isValid()) {
5938  llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
5939  Builder.CreateStore(errorResult, swiftErrorArg);
5940  }
5941 
5942  // Emit any call-associated writebacks immediately. Arguably this
5943  // should happen after any return-value munging.
5944  if (CallArgs.hasWritebacks())
5945  emitWritebacks(*this, CallArgs);
5946 
5947  // The stack cleanup for inalloca arguments has to run out of the normal
5948  // lexical order, so deactivate it and run it manually here.
5949  CallArgs.freeArgumentMemory(*this);
5950 
5951  // Extract the return value.
5952  RValue Ret = [&] {
5953  switch (RetAI.getKind()) {
5955  auto coercionType = RetAI.getCoerceAndExpandType();
5956 
5957  Address addr = SRetPtr.withElementType(coercionType);
5958 
5959  assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
5960  bool requiresExtract = isa<llvm::StructType>(CI->getType());
5961 
5962  unsigned unpaddedIndex = 0;
5963  for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5964  llvm::Type *eltType = coercionType->getElementType(i);
5965  if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5966  Address eltAddr = Builder.CreateStructGEP(addr, i);
5967  llvm::Value *elt = CI;
5968  if (requiresExtract)
5969  elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
5970  else
5971  assert(unpaddedIndex == 0);
5972  Builder.CreateStore(elt, eltAddr);
5973  }
5974  [[fallthrough]];
5975  }
5976 
5977  case ABIArgInfo::InAlloca:
5978  case ABIArgInfo::Indirect: {
5979  RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
5980  if (UnusedReturnSizePtr)
5981  PopCleanupBlock();
5982  return ret;
5983  }
5984 
5985  case ABIArgInfo::Ignore:
5986  // If we are ignoring an argument that had a result, make sure to
5987  // construct the appropriate return value for our caller.
5988  return GetUndefRValue(RetTy);
5989 
5990  case ABIArgInfo::Extend:
5991  case ABIArgInfo::Direct: {
5992  llvm::Type *RetIRTy = ConvertType(RetTy);
5993  if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
5994  switch (getEvaluationKind(RetTy)) {
5995  case TEK_Complex: {
5996  llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
5997  llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
5998  return RValue::getComplex(std::make_pair(Real, Imag));
5999  }
6000  case TEK_Aggregate: {
6001  Address DestPtr = ReturnValue.getAddress();
6002  bool DestIsVolatile = ReturnValue.isVolatile();
6003 
6004  if (!DestPtr.isValid()) {
6005  DestPtr = CreateMemTemp(RetTy, "agg.tmp");
6006  DestIsVolatile = false;
6007  }
6008  EmitAggregateStore(CI, DestPtr, DestIsVolatile);
6009  return RValue::getAggregate(DestPtr);
6010  }
6011  case TEK_Scalar: {
6012  // If the argument doesn't match, perform a bitcast to coerce it. This
6013  // can happen due to trivial type mismatches.
6014  llvm::Value *V = CI;
6015  if (V->getType() != RetIRTy)
6016  V = Builder.CreateBitCast(V, RetIRTy);
6017  return RValue::get(V);
6018  }
6019  }
6020  llvm_unreachable("bad evaluation kind");
6021  }
6022 
6023  // If coercing a fixed vector from a scalable vector for ABI
6024  // compatibility, and the types match, use the llvm.vector.extract
6025  // intrinsic to perform the conversion.
6026  if (auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(RetIRTy)) {
6027  llvm::Value *V = CI;
6028  if (auto *ScalableSrcTy =
6029  dyn_cast<llvm::ScalableVectorType>(V->getType())) {
6030  if (FixedDstTy->getElementType() == ScalableSrcTy->getElementType()) {
6031  llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
6032  V = Builder.CreateExtractVector(FixedDstTy, V, Zero, "cast.fixed");
6033  return RValue::get(V);
6034  }
6035  }
6036  }
6037 
6038  Address DestPtr = ReturnValue.getValue();
6039  bool DestIsVolatile = ReturnValue.isVolatile();
6040 
6041  if (!DestPtr.isValid()) {
6042  DestPtr = CreateMemTemp(RetTy, "coerce");
6043  DestIsVolatile = false;
6044  }
6045 
6046  // An empty record can overlap other data (if declared with
6047  // no_unique_address); omit the store for such types - as there is no
6048  // actual data to store.
6049  if (!isEmptyRecord(getContext(), RetTy, true)) {
6050  // If the value is offset in memory, apply the offset now.
6051  Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
6052  CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
6053  }
6054 
6055  return convertTempToRValue(DestPtr, RetTy, SourceLocation());
6056  }
6057 
6058  case ABIArgInfo::Expand:
6060  llvm_unreachable("Invalid ABI kind for return argument");
6061  }
6062 
6063  llvm_unreachable("Unhandled ABIArgInfo::Kind");
6064  } ();
6065 
6066  // Emit the assume_aligned check on the return value.
6067  if (Ret.isScalar() && TargetDecl) {
6068  AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6069  AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6070  }
6071 
6072  // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
6073  // we can't use the full cleanup mechanism.
6074  for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
6075  LifetimeEnd.Emit(*this, /*Flags=*/{});
6076 
6077  if (!ReturnValue.isExternallyDestructed() &&
6079  pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
6080  RetTy);
6081 
6082  return Ret;
6083 }
6084 
6086  if (isVirtual()) {
6087  const CallExpr *CE = getVirtualCallExpr();
6090  CE ? CE->getBeginLoc() : SourceLocation());
6091  }
6092 
6093  return *this;
6094 }
6095 
6096 /* VarArg handling */
6097 
6099  VAListAddr = VE->isMicrosoftABI()
6100  ? EmitMSVAListRef(VE->getSubExpr())
6101  : EmitVAListRef(VE->getSubExpr());
6102  QualType Ty = VE->getType();
6103  if (VE->isMicrosoftABI())
6104  return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
6105  return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
6106 }
#define V(N, I)
Definition: ASTContext.h:3299
StringRef P
static char ID
Definition: Arena.cpp:183
static void appendParameterTypes(const CodeGenTypes &CGT, SmallVectorImpl< CanQualType > &prefix, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &paramInfos, CanQual< FunctionProtoType > FPT)
Adds the formal parameters in FPT to the given prefix.
Definition: CGCall.cpp:157
static bool isInAllocaArgument(CGCXXABI &ABI, QualType type)
Definition: CGCall.cpp:4133
static uint64_t buildMultiCharMask(const SmallVectorImpl< uint64_t > &Bits, int Pos, int Size, int CharWidth, bool BigEndian)
Definition: CGCall.cpp:3810
static const CGFunctionInfo & arrangeFreeFunctionLikeCall(CodeGenTypes &CGT, CodeGenModule &CGM, const CallArgList &args, const FunctionType *fnType, unsigned numExtraRequiredArgs, bool chainCall)
Arrange a call as unto a free function, except possibly with an additional number of formal parameter...
Definition: CGCall.cpp:593
static CanQualType GetReturnType(QualType RetTy)
Returns the "extra-canonicalized" return type, which discards qualifiers on the return type.
Definition: CGCall.cpp:112
static llvm::Value * emitAutoreleaseOfResult(CodeGenFunction &CGF, llvm::Value *result)
Emit an ARC autorelease of the result of a function.
Definition: CGCall.cpp:3606
static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr, const ABIArgInfo &info)
Definition: CGCall.cpp:1437
static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty)
Definition: CGCall.cpp:4138
static void setBitRange(SmallVectorImpl< uint64_t > &Bits, int BitOffset, int BitWidth, int CharWidth)
Definition: CGCall.cpp:3689
static bool isProvablyNull(llvm::Value *addr)
Definition: CGCall.cpp:4208
static void AddAttributesFromFunctionProtoType(ASTContext &Ctx, llvm::AttrBuilder &FuncAttrs, const FunctionProtoType *FPT)
Definition: CGCall.cpp:1778
static llvm::StoreInst * findDominatingStoreToReturnValue(CodeGenFunction &CGF)
Heuristically search for a dominating store to the return-value slot.
Definition: CGCall.cpp:3624
static const Expr * maybeGetUnaryAddrOfOperand(const Expr *E)
Definition: CGCall.cpp:4299
static llvm::SmallVector< FunctionProtoType::ExtParameterInfo, 16 > getExtParameterInfosForCall(const FunctionProtoType *proto, unsigned prefixArgs, unsigned totalArgs)
Definition: CGCall.cpp:403
static void eraseUnusedBitCasts(llvm::Instruction *insn)
Definition: CGCall.cpp:3467
static llvm::Value * CreateCoercedLoad(Address Src, llvm::Type *Ty, CodeGenFunction &CGF)
CreateCoercedLoad - Create a load from.
Definition: CGCall.cpp:1272
static llvm::Value * emitArgumentDemotion(CodeGenFunction &CGF, const VarDecl *var, llvm::Value *value)
An argument came in as a promoted argument; demote it back to its declared type.
Definition: CGCall.cpp:2946
static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method)
Definition: CGCall.cpp:4532
static llvm::Value * tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF, llvm::Value *result)
Try to emit a fused autorelease of a return result.
Definition: CGCall.cpp:3479
static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs, const LangOptions &LangOpts, const NoBuiltinAttr *NBA=nullptr)
Definition: CGCall.cpp:2224
static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, const ObjCIndirectCopyRestoreExpr *CRE)
Emit an argument that's being passed call-by-writeback.
Definition: CGCall.cpp:4310
static void overrideFunctionFeaturesWithTargetFeatures(llvm::AttrBuilder &FuncAttr, const llvm::Function &F, const TargetOptions &TargetOpts)
Merges target-features from \TargetOpts and \F, and sets the result in \FuncAttr.
Definition: CGCall.cpp:2103
static std::unique_ptr< TypeExpansion > getTypeExpansion(QualType Ty, const ASTContext &Context)
Definition: CGCall.cpp:949
static llvm::fp::FPAccuracy convertFPAccuracy(StringRef FPAccuracyStr)
Definition: CGCall.cpp:1874
static CallingConv getCallingConventionForDecl(const ObjCMethodDecl *D, bool IsWindows)
Definition: CGCall.cpp:214
static int getExpansionSize(QualType Ty, const ASTContext &Context)
Definition: CGCall.cpp:1003
static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types, const llvm::DataLayout &DL, const ABIArgInfo &AI, bool CheckCoerce=true)
Definition: CGCall.cpp:2260
static void addDenormalModeAttrs(llvm::DenormalMode FPDenormalMode, llvm::DenormalMode FP32DenormalMode, llvm::AttrBuilder &FuncAttrs)
Add denormal-fp-math and denormal-fp-math-f32 as appropriate for the requested denormal behavior,...
Definition: CGCall.cpp:1931
static void emitWritebacks(CodeGenFunction &CGF, const CallArgList &args)
Definition: CGCall.cpp:4282
static int32_t convertFPAccuracyToAspect(StringRef FPAccuracyStr)
Definition: CGCall.cpp:1883
static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF, const CallArgList &CallArgs)
Definition: CGCall.cpp:4288
static bool isProvablyNonNull(Address Addr, CodeGenFunction &CGF)
Definition: CGCall.cpp:4212
static void CreateCoercedStore(llvm::Value *Src, Address Dst, bool DstIsVolatile, CodeGenFunction &CGF)
CreateCoercedStore - Create a store to.
Definition: CGCall.cpp:1372
static llvm::Value * tryRemoveRetainOfSelf(CodeGenFunction &CGF, llvm::Value *result)
If this is a +1 of the value of an immutable 'self', remove it.
Definition: CGCall.cpp:3567
static void addExtParameterInfosForCall(llvm::SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &paramInfos, const FunctionProtoType *proto, unsigned prefixArgs, unsigned totalArgs)
Definition: CGCall.cpp:127
static bool canApplyNoFPClass(const ABIArgInfo &AI, QualType ParamType, bool IsReturn)
Test if it's legal to apply nofpclass for the given parameter type and it's lowered IR type.
Definition: CGCall.cpp:2333
static void getTrivialDefaultFunctionAttributes(StringRef Name, bool HasOptnone, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, bool AttrOnCallSite, llvm::AttrBuilder &FuncAttrs)
Definition: CGCall.cpp:1951
static CanQual< FunctionProtoType > GetFormalType(const CXXMethodDecl *MD)
Returns the canonical formal type of the given C++ method.
Definition: CGCall.cpp:103
static llvm::FPClassTest getNoFPClassTestMask(const LangOptions &LangOpts)
Return the nofpclass mask that can be applied to floating-point parameters.
Definition: CGCall.cpp:2355
static void forConstantArrayExpansion(CodeGenFunction &CGF, ConstantArrayExpansion *CAE, Address BaseAddr, llvm::function_ref< void(Address)> Fn)
Definition: CGCall.cpp:1045
static bool IsArgumentMaybeUndef(const Decl *TargetDecl, unsigned NumRequiredArgs, unsigned ArgNo)
Check if the argument of a function has maybe_undef attribute.
Definition: CGCall.cpp:2311
static const NonNullAttr * getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD, QualType ArgType, unsigned ArgNo)
Returns the attribute (either parameter attribute, or function attribute), which declares argument Ar...
Definition: CGCall.cpp:2966
static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC, ArrayRef< QualType > ArgTypes)
Definition: CGCall.cpp:4514
static SmallVector< CanQualType, 16 > getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args)
Definition: CGCall.cpp:395
static RawAddress CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty, CharUnits MinAlign, const Twine &Name="tmp")
Create a temporary allocation for the purposes of coercion.
Definition: CGCall.cpp:1166
static void setUsedBits(CodeGenModule &, QualType, int, SmallVectorImpl< uint64_t > &)
Definition: CGCall.cpp:3793
static SmallVector< CanQualType, 16 > getArgTypesForCall(ASTContext &ctx, const CallArgList &args)
Definition: CGCall.cpp:387
static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM, const FunctionDecl *FD)
Set calling convention for CUDA/HIP kernel.
Definition: CGCall.cpp:295
static Address EnterStructPointerForCoercedAccess(Address SrcPtr, llvm::StructType *SrcSTy, uint64_t DstSize, CodeGenFunction &CGF)
EnterStructPointerForCoercedAccess - Given a struct pointer that we are accessing some number of byte...
Definition: CGCall.cpp:1182
static const CGFunctionInfo & arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod, SmallVectorImpl< CanQualType > &prefix, CanQual< FunctionProtoType > FTP)
Arrange the LLVM function layout for a value of the given function type, on top of any implicit param...
Definition: CGCall.cpp:190
static void emitWriteback(CodeGenFunction &CGF, const CallArgList::Writeback &writeback)
Emit the actual writing-back of a writeback.
Definition: CGCall.cpp:4217
static bool HasStrictReturn(const CodeGenModule &Module, QualType RetTy, const Decl *TargetDecl)
Definition: CGCall.cpp:1842
static void addMergableDefaultFunctionAttributes(const CodeGenOptions &CodeGenOpts, llvm::AttrBuilder &FuncAttrs)
Add default attributes to a function, which have merge semantics under -mlink-builtin-bitcode and sho...
Definition: CGCall.cpp:1945
static void AddAttributesFromOMPAssumes(llvm::AttrBuilder &FuncAttrs, const Decl *Callee)
Definition: CGCall.cpp:1815
static unsigned getMaxVectorWidth(const llvm::Type *Ty)
Definition: CGCall.cpp:5095
static llvm::Value * CoerceIntOrPtrToIntOrPtr(llvm::Value *Val, llvm::Type *Ty, CodeGenFunction &CGF)
CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both are either integers or p...
Definition: CGCall.cpp:1218
CodeGenFunction::ComplexPairTy ComplexPairTy
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
unsigned Offset
Definition: Format.cpp:2978
llvm::MachO::Target Target
Definition: MachO.h:50
static QualType getParamType(Sema &SemaRef, ArrayRef< ResultCandidate > Candidates, unsigned N)
Get the type of the Nth parameter from a given set of overload candidates.
static bool isInstanceMethod(const Decl *D)
SourceLocation Loc
Definition: SemaObjC.cpp:755
@ local
Definition: SemaSYCL.cpp:48
SourceLocation End
__DEVICE__ int max(int __a, int __b)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1121
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2782
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2088
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType IntTy
Definition: ASTContext.h:1103
TypeInfoChars getTypeInfoInChars(const Type *T) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2355
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1094
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:760
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2359
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3530
Attr - This represents one attribute.
Definition: Attr.h:46
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
Definition: Expr.cpp:2554
This class is used for builtin types like 'int'.
Definition: Type.h:2989
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2462
bool isVirtual() const
Definition: DeclCXX.h:2115
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2221
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1975
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:634
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2872
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1693
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
CanProxy< U > castAs() const
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition: CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
llvm::DenormalMode FPDenormalMode
The floating-point denormal mode to use.
static StringRef getFramePointerKindName(FramePointerKind Kind)
std::vector< std::string > Reciprocals
llvm::DenormalMode FP32DenormalMode
The floating-point denormal mode to use, for float.
std::string TrapFuncName
If not an empty string, trap intrinsics are lowered to calls to this function instead of to trap inst...
std::vector< std::string > DefaultFunctionAttrs
std::string PreferVectorWidth
The preferred width for auto-vectorization transforms.
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
unsigned getInAllocaFieldIndex() const
void setCoerceToType(llvm::Type *T)
unsigned getDirectOffset() const
static bool isPaddingForCoerceAndExpand(llvm::Type *eltType)
bool getInAllocaSRet() const
Return true if this field of an inalloca struct should be returned to implement a struct return calli...
llvm::Type * getUnpaddedCoerceAndExpandType() const
unsigned getDirectAlign() const
unsigned getIndirectAddrSpace() const
ArrayRef< llvm::Type * > getCoerceAndExpandTypeSequence() const
llvm::Type * getPaddingType() const
@ Extend
Extend - Valid only for integer argument types.
@ Ignore
Ignore - Ignore the argument (treat as void).
@ IndirectAliased
IndirectAliased - Similar to Indirect, but the pointer may be to an object that is otherwise referenc...
@ Expand
Expand - Only valid for aggregate argument types.
@ InAlloca
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
@ CoerceAndExpand
CoerceAndExpand - Only valid for aggregate argument types.
@ Direct
Direct - Pass the argument directly using the normal converted LLVM type, or by coercing to another s...
llvm::Type * getCoerceToType() const
unsigned getInAllocaIndirect() const
llvm::StructType * getCoerceAndExpandType() const
CharUnits getIndirectAlign() const
virtual CodeGen::Address EmitMSVAArg(CodeGen::CodeGenFunction &CGF, CodeGen::Address VAListAddr, QualType Ty) const
Emit the target dependent code to load a value of.
Definition: ABIInfo.cpp:42
virtual CodeGen::Address EmitVAArg(CodeGen::CodeGenFunction &CGF, CodeGen::Address VAListAddr, QualType Ty) const =0
EmitVAArg - Emit the target dependent code to load a value of.
virtual void computeInfo(CodeGen::CGFunctionInfo &FI) const =0
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:111
static Address invalid()
Definition: Address.h:153
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition: Address.h:220
CharUnits getAlignment() const
Definition: Address.h:166
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:184
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:241
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:176
llvm::Value * getBasePointer() const
Definition: Address.h:170
llvm::StringRef getName() const
Return the IR name of the pointer value.
Definition: Address.h:193
bool isValid() const
Definition: Address.h:154
An aggregate value slot.
Definition: CGValue.h:509
Address getAddress() const
Definition: CGValue.h:649
void setExternallyDestructed(bool destructed=true)
Definition: CGValue.h:618
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition: CGValue.h:592
RValue asRValue() const
Definition: CGValue.h:671
const BlockExpr * BlockExpression
Definition: CGBlocks.h:278
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition: CGBuilder.h:305
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:128
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:136
Address CreateConstGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name="")
Definition: CGBuilder.h:331
llvm::LoadInst * CreateFlagLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Emit a load from an i1 flag variable.
Definition: CGBuilder.h:158
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:219
llvm::Value * CreateIsNull(Address Addr, const Twine &Name="")
Definition: CGBuilder.h:355
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition: CGBuilder.h:189
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:108
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:364
Implements C++ ABI-specific code generation functions.
Definition: CGCXXABI.h:43
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
Definition: CGCXXABI.h:131
virtual bool HasThisReturn(GlobalDecl GD) const
Returns true if the given constructor or destructor is one of the kinds that the ABI says returns 'th...
Definition: CGCXXABI.h:123
virtual const CXXRecordDecl * getThisArgumentTypeForMethod(GlobalDecl GD)
Get the type of the implicit "this" parameter used by a method.
Definition: CGCXXABI.h:388
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
Definition: CGCXXABI.h:158
virtual CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, Address This, llvm::Type *Ty, SourceLocation Loc)=0
Build a virtual function pointer in the ABI-specific way.
virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const =0
Returns how an argument of the given record type should be passed.
virtual AddedStructorArgCounts buildStructorSignature(GlobalDecl GD, SmallVectorImpl< CanQualType > &ArgTys)=0
Build the signature of the given constructor or destructor variant by adding any required parameters.
Abstract information about a function or function prototype.
Definition: CGCall.h:40
const GlobalDecl getCalleeDecl() const
Definition: CGCall.h:58
const FunctionProtoType * getCalleeFunctionProtoType() const
Definition: CGCall.h:55
All available information about a concrete callee.
Definition: CGCall.h:62
CGCallee prepareConcreteCallee(CodeGenFunction &CGF) const
If this is a delayed callee computation of some sort, prepare a concrete callee.
Definition: CGCall.cpp:6085
bool isVirtual() const
Definition: CGCall.h:187
Address getThisAddress() const
Definition: CGCall.h:198
llvm::Value * getFunctionPointer() const
Definition: CGCall.h:177
const CallExpr * getVirtualCallExpr() const
Definition: CGCall.h:190
GlobalDecl getVirtualMethodDecl() const
Definition: CGCall.h:194
llvm::FunctionType * getVirtualFunctionType() const
Definition: CGCall.h:202
void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy, SourceLocation Loc)
Add heapallocsite metadata for MSAllocator calls.
CGFunctionInfo - Class to encapsulate the information about a function definition.
bool usesInAlloca() const
Return true if this function uses inalloca arguments.
FunctionType::ExtInfo getExtInfo() const
bool isReturnsRetained() const
In ARC, whether this function retains its return value.
void Profile(llvm::FoldingSetNodeID &ID)
const_arg_iterator arg_begin() const
CanQualType getReturnType() const
static CGFunctionInfo * create(unsigned llvmCC, bool instanceMethod, bool chainCall, bool delegateCall, const FunctionType::ExtInfo &extInfo, ArrayRef< ExtParameterInfo > paramInfos, CanQualType resultType, ArrayRef< CanQualType > argTypes, RequiredArgs required)
Definition: CGCall.cpp:838
MutableArrayRef< ArgInfo > arguments()
const_arg_iterator arg_end() const
unsigned getEffectiveCallingConvention() const
getEffectiveCallingConvention - Return the actual calling convention to use, which may depend on the ...
ExtParameterInfo getExtParameterInfo(unsigned argIndex) const
CharUnits getArgStructAlignment() const
llvm::StructType * getArgStruct() const
Get the struct type used to represent all the arguments in memory.
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
RequiredArgs getRequiredArgs() const
unsigned getNumRequiredArgs() const
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:257
void addUncopiedAggregate(LValue LV, QualType type)
Definition: CGCall.h:283
ArrayRef< CallArgCleanup > getCleanupsToDeactivate() const
Definition: CGCall.h:324
llvm::Instruction * getStackBase() const
Definition: CGCall.h:329
void addArgCleanupDeactivation(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *IsActiveIP)
Definition: CGCall.h:316
bool hasWritebacks() const
Definition: CGCall.h:307
void add(RValue rvalue, QualType type)
Definition: CGCall.h:281
bool isUsingInAlloca() const
Returns if we're using an inalloca struct to pass arguments in memory.
Definition: CGCall.h:334
void allocateArgumentMemory(CodeGenFunction &CGF)
Definition: CGCall.cpp:4436
void freeArgumentMemory(CodeGenFunction &CGF) const
Definition: CGCall.cpp:4443
writeback_const_range writebacks() const
Definition: CGCall.h:312
void addWriteback(LValue srcLV, Address temporary, llvm::Value *toUse)
Definition: CGCall.h:302
An abstract representation of regular/ObjC call/message targets.
An object to manage conditionally-evaluated expressions.
static ParamValue forIndirect(Address addr)
static ParamValue forDirect(llvm::Value *value)
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
EHScopeStack::stable_iterator CurrentCleanupScopeDepth
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerMask >> Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
Definition: CGExpr.cpp:3521
llvm::Value * EmitARCRetainAutoreleaseReturnValue(llvm::Value *value)
Do a fused retain/autorelease of the given object.
Definition: CGObjC.cpp:2554
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
SanitizerSet SanOpts
Sanitizers enabled for this function.
void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc)
EmitFunctionEpilog - Emit the target specific LLVM code to return the given temporary.
Definition: CGCall.cpp:3876
void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl)
static bool hasScalarEvaluationKind(QualType T)
llvm::Type * ConvertType(QualType T)
bool isCleanupPadScope() const
Returns true while emitting a cleanuppad.
llvm::CallBase * EmitCallOrInvoke(llvm::FunctionCallee Callee, ArrayRef< llvm::Value * > Args, const Twine &Name="")
Emits a call or invoke instruction to the given function, depending on the current state of the EH st...
Definition: CGCall.cpp:4962
void EmitAggregateStore(llvm::Value *Val, Address Dest, bool DestIsVolatile)
Build all the stores needed to initialize an aggregate at Dest with the value Val.
Definition: CGCall.cpp:1352
void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args)
Emits a call or invoke to the given noreturn runtime function.
Definition: CGCall.cpp:4921
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition: CGCall.cpp:4952
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
llvm::Value * EmitLifetimeStart(llvm::TypeSize Size, llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
Definition: CGDecl.cpp:1392
llvm::Value * EmitARCAutoreleaseReturnValue(llvm::Value *value)
Autorelease the given object.
Definition: CGObjC.cpp:2544
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue, SourceLocation Loc)
GetAddressOfBaseClass - This function will add the necessary delta to the load of 'this' and returns ...
Definition: CGClass.cpp:293
bool isSEHTryScope() const
Returns true inside SEH __try blocks.
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
Definition: CGExpr.cpp:6100
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition: CGExpr.cpp:3386
void SetSqrtFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
Definition: CGExpr.cpp:6126
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitReturnValueCheck(llvm::Value *RV)
Emit a test that checks if the return value RV is nonnull.
Definition: CGCall.cpp:4069
llvm::LLVMContext & getLLVMContext()
void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, SourceLocation loc)
EmitDelegateCallArg - We are performing a delegate call; that is, the current function is delegating ...
Definition: CGCall.cpp:4159
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
Definition: CGExpr.cpp:626
llvm::BasicBlock * getUnreachableBlock()
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup.
Definition: CGDecl.cpp:2242
const CodeGen::CGBlockInfo * BlockInfo
void EmitKCFIOperandBundle(const CGCallee &Callee, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr)
Definition: CGDecl.cpp:1408
llvm::Value * getAsNaturalPointerTo(Address Addr, QualType PointeeType)
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This, QualType ThisTy)
Definition: CGClass.cpp:2511
bool InNoMergeAttributedStmt
True if the current statement has nomerge attribute.
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise)
Release the given object.
Definition: CGObjC.cpp:2436
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **callOrInvoke, bool IsMustTail, SourceLocation Loc)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition: CGCall.cpp:5108
JumpDest ReturnBlock
ReturnBlock - Unified return block.
@ ForceLeftToRight
! Language semantics require left-to-right evaluation.
@ ForceRightToLeft
! Language semantics require right-to-left evaluation.
void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc, AbstractCallee AC, unsigned ParmNum)
Create a check for a function parameter that may potentially be declared as non-null.
Definition: CGCall.cpp:4450
void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, AggValueSlot::Overlap_t MayOverlap, bool isVolatile=false)
EmitAggregateCopy - Emit an aggregate copy.
Definition: CGExprAgg.cpp:2093
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition: CGExpr.cpp:2168
void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
DeactivateCleanupBlock - Deactivates the given cleanup block.
Definition: CGCleanup.cpp:1275
void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType)
EmitCallArg - Emit a single call argument.
Definition: CGCall.cpp:4753
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
CallType * addControlledConvergenceToken(CallType *Input)
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
Definition: CGExpr.cpp:5014
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition: CGExpr.cpp:116
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
const TargetInfo & getTarget() const
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition: CGExpr.cpp:176
bool InNoInlineAttributedStmt
True if the current statement has noinline attribute.
SmallVector< llvm::OperandBundleDef, 1 > getBundlesForFunclet(llvm::Value *Callee)
Definition: CGCall.cpp:4886
RValue EmitAnyExprToTemp(const Expr *E)
EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will always be accessible even if...
Definition: CGExpr.cpp:244
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
void EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn, const FunctionArgList &Args)
EmitFunctionProlog - Emit the target specific LLVM code to load the arguments for the given function.
Definition: CGCall.cpp:3004
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition: CGExpr.cpp:2344
Address EmitVAListRef(const Expr *E)
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
Definition: CGExpr.cpp:1404
void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo)
EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
Definition: CGDecl.cpp:2601
llvm::CallInst * MaybeEmitFPBuiltinofFD(llvm::FunctionType *IRFuncTy, const SmallVectorImpl< llvm::Value * > &IRArgs, llvm::Value *FnPtr, StringRef Name, unsigned FDBuiltinID)
llvm::BasicBlock * getInvokeDest()
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
llvm::Value * EmitARCRetainNonBlock(llvm::Value *value)
Retain the given object, with normal retain semantics.
Definition: CGObjC.cpp:2293
llvm::Type * ConvertTypeForMem(QualType T)
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
bool InAlwaysInlineAttributedStmt
True if the current statement has always_inline attribute.
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Definition: CGExpr.cpp:1387
const TargetCodeGenInfo & getTargetHooks() const
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition: CGExpr.cpp:147
RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc)
Definition: CGExpr.cpp:5452
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
Definition: CGExprAgg.cpp:2030
Address EmitMSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_ms_va_list; this is always the value of the expression,...
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
static bool hasAggregateEvaluationKind(QualType T)
void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
EmitCallArgs - Emit call arguments for a function.
Definition: CGCall.cpp:4547
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitUnreachable(SourceLocation Loc)
Emit a reached-unreachable diagnostic if Loc is valid and runtime checking is enabled.
Definition: CGExpr.cpp:3818
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition: CGExpr.cpp:1503
CodeGenTypes & getTypes() const
llvm::Instruction * CurrentFuncletPad
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr)
Generate code to get an argument from the passed in pointer and update it accordingly.
Definition: CGCall.cpp:6098
llvm::Value * EmitNonNullRValueCheck(RValue RV, QualType T)
Create a check that a scalar RValue is non-null.
Definition: CGExpr.cpp:1397
void EmitARCIntrinsicUse(ArrayRef< llvm::Value * > values)
Given a number of pointers, inform the optimizer that they're being intrinsically used up until this ...
Definition: CGObjC.cpp:2123
llvm::Value * EmitCMSEClearRecord(llvm::Value *V, llvm::IntegerType *ITy, QualType RTy)
Definition: CGCall.cpp:3830
void PopCleanupBlock(bool FallThroughIsBranchThrough=false, bool ForDeactivation=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
Definition: CGCleanup.cpp:637
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:578
const LangOptions & getLangOpts() const
This class organizes the cross-function state that is used while generating LLVM code.
const TargetInfo & getTarget() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
const llvm::DataLayout & getDataLayout() const
bool ReturnTypeUsesFPRet(QualType ResultType)
Return true iff the given type uses 'fpret' when used as a return type.
Definition: CGCall.cpp:1607
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
const LangOptions & getLangOpts() const
const llvm::Triple & getTriple() const
llvm::LLVMContext & getLLVMContext()
llvm::MDNode * getNoObjCARCExceptionsMetadata()
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
bool shouldEmitConvergenceTokens() const
bool ReturnTypeUsesFP2Ret(QualType ResultType)
Return true iff the given type uses 'fp2ret' when used as a return type.
Definition: CGCall.cpp:1624
ObjCEntrypoints & getObjCEntrypoints() const
CGCXXABI & getCXXABI() const
bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI)
Return true iff the given type uses an argument slot when 'sret' is used as a return type.
Definition: CGCall.cpp:1602
bool ReturnTypeHasInReg(const CGFunctionInfo &FI)
Return true iff the given type has inreg set.
Definition: CGCall.cpp:1597
void AdjustMemoryAttribute(StringRef Name, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs)
Adjust Memory attribute to ensure that the BE gets the right attribute.
Definition: CGCall.cpp:2364
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite, bool IsThunk)
Get the LLVM attributes and calling convention to use for a particular function type.
Definition: CGCall.cpp:2392
bool ReturnTypeUsesSRet(const CGFunctionInfo &FI)
Return true iff the given type uses 'sret' when used as a return type.
Definition: CGCall.cpp:1592
const TargetCodeGenInfo & getTargetCodeGenInfo()
ASTContext & getContext() const
void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs)
Like the overload taking a Function &, but intended specifically for frontends that want to build on ...
Definition: CGCall.cpp:2217
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
const CodeGenOptions & getCodeGenOpts() const
CharUnits getMinimumObjectSize(QualType Ty)
Returns the minimum object size for an object of the given type.
bool MayDropFunctionReturn(const ASTContext &Context, QualType ReturnType) const
Whether this function's return type has no side effects, and thus may be trivially discarded if it is...
Definition: CGCall.cpp:1830
void valueProfile(CGBuilderTy &Builder, uint32_t ValueKind, llvm::Instruction *ValueSite, llvm::Value *ValuePtr)
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
Definition: CodeGenTypes.h:54
const CGFunctionInfo & arrangeCXXMethodType(const CXXRecordDecl *RD, const FunctionProtoType *FTP, const CXXMethodDecl *MD)
Arrange the argument and result information for a call to an unknown C++ non-static member function o...
Definition: CGCall.cpp:281
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
Definition: CGCall.cpp:309
const CGFunctionInfo & arrangeLLVMFunctionInfo(CanQualType returnType, FnInfoOpts opts, ArrayRef< CanQualType > argTypes, FunctionType::ExtInfo info, ArrayRef< FunctionProtoType::ExtParameterInfo > paramInfos, RequiredArgs args)
"Arrange" the LLVM information for a call or type with the given signature.
Definition: CGCall.cpp:768
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
Definition: CGCall.cpp:208
CanQualType DeriveThisType(const CXXRecordDecl *RD, const CXXMethodDecl *MD)
Derives the 'this' type for codegen purposes, i.e.
Definition: CGCall.cpp:89
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1641
bool inheritingCtorHasParams(const InheritedConstructor &Inherited, CXXCtorType Type)
Determine if a C++ inheriting constructor should have parameters matching those of its inherited cons...
Definition: CGCall.cpp:326
bool isFuncTypeConvertible(const FunctionType *FT)
isFuncTypeConvertible - Utility to check whether a function type can be converted to an LLVM type (i....
const CGFunctionInfo & arrangeBlockFunctionCall(const CallArgList &args, const FunctionType *type)
A block function is essentially a free function with an extra implicit argument.
Definition: CGCall.cpp:651
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:682
const CGFunctionInfo & arrangeUnprototypedObjCMessageSend(QualType returnType, const CallArgList &args)
Definition: CGCall.cpp:535
const ABIInfo & getABIInfo() const
Definition: CodeGenTypes.h:109
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
unsigned getTargetAddressSpace(QualType T) const
void getExpandedTypes(QualType Ty, SmallVectorImpl< llvm::Type * >::iterator &TI)
getExpandedTypes - Expand the type
Definition: CGCall.cpp:1023
const CGFunctionInfo & arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD)
Objective-C methods are C functions with some implicit parameters.
Definition: CGCall.cpp:489
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:545
const CGFunctionInfo & arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD)
Arrange a thunk that takes 'this' as the first parameter followed by varargs.
Definition: CGCall.cpp:562
const CGFunctionInfo & arrangeCXXMethodCall(const CallArgList &args, const FunctionProtoType *type, RequiredArgs required, unsigned numPrefixArgs)
Arrange a call to a C++ method, passing the given arguments.
Definition: CGCall.cpp:704
const CGFunctionInfo & arrangeFreeFunctionCall(const CallArgList &Args, const FunctionType *Ty, bool ChainCall)
Figure out the rules for calling a function with the given formal type using the given arguments.
Definition: CGCall.cpp:641
ASTContext & getContext() const
Definition: CodeGenTypes.h:108
const CGFunctionInfo & arrangeBuiltinFunctionCall(QualType resultType, const CallArgList &args)
Definition: CGCall.cpp:670
const CGFunctionInfo & arrangeFunctionDeclaration(const FunctionDecl *FD)
Free functions are functions that are compatible with an ordinary C function pointer type.
Definition: CGCall.cpp:465
const CGFunctionInfo & arrangeBlockFunctionDeclaration(const FunctionProtoType *type, const FunctionArgList &args)
Block invocation functions are C functions with an implicit parameter.
Definition: CGCall.cpp:658
unsigned ClangCallConvToLLVMCallConv(CallingConv CC)
Convert clang calling convention to LLVM callilng convention.
Definition: CGCall.cpp:52
llvm::Type * GetFunctionTypeForVTable(GlobalDecl GD)
GetFunctionTypeForVTable - Get the LLVM function type for use in a vtable, given a CXXMethodDecl.
Definition: CGCall.cpp:1768
const CGFunctionInfo & arrangeCXXConstructorCall(const CallArgList &Args, const CXXConstructorDecl *D, CXXCtorType CtorKind, unsigned ExtraPrefixArgs, unsigned ExtraSuffixArgs, bool PassProtoArgs=true)
Arrange a call to a C++ method, passing the given arguments.
Definition: CGCall.cpp:421
const CGFunctionInfo & arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD, QualType receiverType)
Arrange the argument and result information for the function type through which to perform a send to ...
Definition: CGCall.cpp:502
const CGFunctionInfo & arrangeCXXStructorDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:336
llvm::LLVMContext & getLLVMContext()
Definition: CodeGenTypes.h:112
const CGFunctionInfo & arrangeMSCtorClosure(const CXXConstructorDecl *CD, CXXCtorType CT)
Definition: CGCall.cpp:571
const CGFunctionInfo & arrangeCall(const CGFunctionInfo &declFI, const CallArgList &args)
Given a function info for a declaration, return the function info for a call with the given arguments...
Definition: CGCall.cpp:731
const CGFunctionInfo & arrangeNullaryFunction()
A nullary function is a freestanding function of type 'void ()'.
Definition: CGCall.cpp:724
A cleanup scope which generates the cleanup blocks lazily.
Definition: CGCleanup.h:243
EHScopeStack::Cleanup * getCleanup()
Definition: CGCleanup.h:418
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:141
A saved depth on the scope stack.
Definition: EHScopeStack.h:101
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:393
iterator end() const
Returns an iterator pointing to the outermost EH scope.
Definition: CGCleanup.h:619
iterator find(stable_iterator save) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack.
Definition: CGCleanup.h:639
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition: CGCall.h:351
LValue - This represents an lvalue references.
Definition: CGValue.h:181
bool isBitField() const
Definition: CGValue.h:283
bool isSimple() const
Definition: CGValue.h:281
bool isVolatileQualified() const
Definition: CGValue.h:288
LangAS getAddressSpace() const
Definition: CGValue.h:344
CharUnits getAlignment() const
Definition: CGValue.h:346
static LValue MakeAddr(Address Addr, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition: CGValue.h:437
bool isVolatile() const
Definition: CGValue.h:331
Address getAddress() const
Definition: CGValue.h:370
ARCPreciseLifetime_t isARCPreciseLifetime() const
Definition: CGValue.h:315
Qualifiers::ObjCLifetime getObjCLifetime() const
Definition: CGValue.h:296
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:41
bool isScalar() const
Definition: CGValue.h:63
static RValue get(llvm::Value *V)
Definition: CGValue.h:97
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition: CGValue.h:77
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:70
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition: CGValue.h:124
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition: CGValue.h:107
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition: CGValue.h:82
bool isComplex() const
Definition: CGValue.h:64
bool isVolatileQualified() const
Definition: CGValue.h:67
An abstract representation of an aligned address.
Definition: Address.h:41
CharUnits getAlignment() const
Return the alignment of this pointer.
Definition: Address.h:92
llvm::Value * getPointer() const
Definition: Address.h:65
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:76
static RawAddress invalid()
Definition: Address.h:60
bool isValid() const
Definition: Address.h:61
A class for recording the number of arguments that a function signature requires.
unsigned getNumRequiredArgs() const
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype, unsigned additional)
Compute the arguments required by the given formal prototype, given that there may be some additional...
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition: CGCall.h:355
virtual bool doesReturnSlotInterfereWithArgs() const
doesReturnSlotInterfereWithArgs - Return true if the target uses an argument slot for an 'sret' type.
Definition: TargetInfo.h:194
virtual void setCUDAKernelCallingConvention(const FunctionType *&FT) const
Definition: TargetInfo.h:377
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
virtual void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, const FunctionDecl *Callee, const CallArgList &Args, QualType ReturnType) const
Any further codegen related checks that need to be done on a function call in a target specific manne...
Definition: TargetInfo.h:94
virtual unsigned getOpenCLKernelCallingConv() const
Get LLVM calling convention for OpenCL kernel.
Definition: TargetInfo.cpp:105
virtual bool isNoProtoCallVariadic(const CodeGen::CallArgList &args, const FunctionNoProtoType *fnType) const
Determine whether a call to an unprototyped functions under the given calling convention should use t...
Definition: TargetInfo.cpp:86
Complex values, per C99 6.2.5p11.
Definition: Type.h:3098
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3568
bool constructsVirtualBase() const
Returns true if the constructed base class is a virtual base class subobject of this declaration's cl...
Definition: DeclCXX.h:3698
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
bool hasAttr() const
Definition: DeclBase.h:583
T * getAttr() const
Definition: DeclBase.h:579
DeclContext * getDeclContext()
Definition: DeclBase.h:454
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:823
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3107
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3980
QualType getType() const
Definition: Expr.h:142
Represents a member of a struct/union/class.
Definition: Decl.h:3060
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3151
bool isZeroLengthBitField(const ASTContext &Ctx) const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4601
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:3154
Represents a function declaration or definition.
Definition: Decl.h:1972
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2342
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4623
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4668
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4927
unsigned getNumParams() const
Definition: Type.h:4901
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5106
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5024
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5089
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5019
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5085
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4379
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4494
CallingConv getCC() const
Definition: Type.h:4441
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4460
bool getCmseNSCall() const
Definition: Type.h:4429
bool getNoCfCheck() const
Definition: Type.h:4431
unsigned getRegParm() const
Definition: Type.h:4434
bool getNoCallerSavedRegs() const
Definition: Type.h:4430
bool getHasRegParm() const
Definition: Type.h:4432
bool getNoReturn() const
Definition: Type.h:4427
bool getProducesResult() const
Definition: Type.h:4428
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4294
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: Type.h:4307
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:4334
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4268
ExtInfo getExtInfo() const
Definition: Type.h:4597
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4555
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4551
QualType getReturnType() const
Definition: Type.h:4585
@ SME_PStateSMEnabledMask
Definition: Type.h:4529
@ SME_PStateSMCompatibleMask
Definition: Type.h:4530
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
CXXCtorType getCtorType() const
Definition: GlobalDecl.h:105
const Decl * getDecl() const
Definition: GlobalDecl.h:103
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2506
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2518
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:289
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:482
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
Definition: LangOptions.h:549
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:794
bool isNoBuiltinFunc(StringRef Name) const
Is this a libc/libm function that is no longer recognized as a builtin because a -fno-builtin-* optio...
Definition: LangOptions.cpp:49
bool assumeFunctionsAreConvergent() const
Definition: LangOptions.h:683
FPAccuracyFuncMapTy FPAccuracyFuncMap
Definition: LangOptions.h:608
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:4143
Describes a module or submodule.
Definition: Module.h:105
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2326
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
Definition: ExprObjC.h:1575
bool shouldCopy() const
shouldCopy - True if we should do the 'copy' part of the copy-restore.
Definition: ExprObjC.h:1603
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
bool isVariadic() const
Definition: DeclObjC.h:431
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:418
bool isDirectMethod() const
True if the method is tagged as objc_direct.
Definition: DeclObjC.cpp:871
QualType getReturnType() const
Definition: DeclObjC.h:329
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
Represents a parameter to a function.
Definition: Decl.h:1762
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3151
QualType getPointeeType() const
Definition: Type.h:3161
A (possibly-)qualified type.
Definition: Type.h:940
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7449
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2747
@ DK_cxx_destructor
Definition: Type.h:1520
@ DK_nontrivial_c_struct
Definition: Type.h:1523
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7497
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7411
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7572
QualType getCanonicalType() const
Definition: Type.h:7423
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1530
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
LangAS getAddressSpace() const
Definition: Type.h:557
Represents a struct/union/class.
Definition: Decl.h:4171
bool hasFlexibleArrayMember() const
Definition: Decl.h:4204
field_iterator field_end() const
Definition: Decl.h:4380
field_range fields() const
Definition: Decl.h:4377
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4362
bool isParamDestroyedInCallee() const
Definition: Decl.h:4313
field_iterator field_begin() const
Definition: Decl.cpp:5073
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5561
RecordDecl * getDecl() const
Definition: Type.h:5571
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3392
Encodes a location in the source.
UIntTy getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it.
bool isUnion() const
Definition: Decl.h:3793
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change,...
Definition: TargetCXXABI.h:188
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool useObjCFPRetForRealType(FloatModeKind T) const
Check whether the given real type should use the "fpret" flavor of Objective-C message passing on thi...
Definition: TargetInfo.h:978
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
bool useObjCFP2RetForComplexLongDouble() const
Check whether _Complex long double should use the "fp2ret" flavor of Objective-C message passing on t...
Definition: TargetInfo.h:984
Options for controlling the target.
Definition: TargetOptions.h:26
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
Definition: TargetOptions.h:58
std::string TuneCPU
If given, the name of the target CPU to tune code for.
Definition: TargetOptions.h:39
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
The base class of the type hierarchy.
Definition: Type.h:1813
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1881
bool isBlockPointerType() const
Definition: Type.h:7632
bool isVoidType() const
Definition: Type.h:7939
bool isIncompleteArrayType() const
Definition: Type.h:7698
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2351
bool isPointerType() const
Definition: Type.h:7624
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7979
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8227
bool isReferenceType() const
Definition: Type.h:7636
bool isScalarType() const
Definition: Type.h:8038
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isBitIntType() const
Definition: Type.h:7874
QualType getCanonicalTypeInternal() const
Definition: Type.h:2944
bool isMemberPointerType() const
Definition: Type.h:7672
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2679
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2405
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2361
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2257
bool isAnyPointerType() const
Definition: Type.h:7628
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8160
bool isNullPtrType() const
Definition: Type.h:7972
bool isObjCRetainableType() const
Definition: Type.cpp:4907
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1885
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2235
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4719
bool isMicrosoftABI() const
Returns whether this is really a Win64 ABI va_arg expression.
Definition: Expr.h:4740
const Expr * getSubExpr() const
Definition: Expr.h:4735
QualType getType() const
Definition: Decl.h:718
Represents a variable declaration or definition.
Definition: Decl.h:919
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2824
Represents a GCC generic vector type.
Definition: Type.h:3981
Defines the clang::TargetInfo interface.
void computeABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI)
Compute the ABI information of a swiftcall function.
@ fp_intrinsic_accuracy_high
Definition: CGSYCLRuntime.h:32
@ fp_intrinsic_accuracy_medium
Definition: CGSYCLRuntime.h:33
@ fp_intrinsic_accuracy_cuda
Definition: CGSYCLRuntime.h:36
@ fp_intrinsic_accuracy_sycl
Definition: CGSYCLRuntime.h:35
void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI)
Definition: SPIR.cpp:247
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:84
void mergeDefaultFunctionDefinitionAttributes(llvm::Function &F, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, const TargetOptions &TargetOpts, bool WillInternalize)
Adds attributes to F according to our CodeGenOpts and LangOpts, as though we had emitted it ourselves...
Definition: CGCall.cpp:2134
bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays, bool AsIfNoUniqueAddr=false)
isEmptyRecord - Return true iff a structure contains only empty fields.
constexpr XRayInstrMask All
Definition: XRayInstr.h:43
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
constexpr Variable var(Literal L)
Returns the variable of L.
Definition: CNFFormula.h:64
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition: Format.cpp:3799
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:218
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1903
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1396
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
CXXCtorType
C++ constructor types.
Definition: ABI.h:24
@ Ctor_DefaultClosure
Default closure variant of a ctor.
Definition: ABI.h:29
@ Ctor_CopyingClosure
Copying closure variant of a ctor.
Definition: ABI.h:28
@ Ctor_Complete
Complete object ctor.
Definition: ABI.h:25
@ OpenCL
Definition: LangStandard.h:65
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ NonNull
Values of this type can never be null.
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
@ SwiftAsyncContext
This parameter (which must have pointer type) uses the special Swift asynchronous context-pointer ABI...
@ SwiftErrorResult
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
@ Ordinary
This parameter uses ordinary ABI rules for its type.
@ SwiftIndirectResult
This parameter (which must have pointer type) is a Swift indirect result parameter.
@ SwiftContext
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment.
@ Dtor_Complete
Complete object dtor.
Definition: ABI.h:35
@ CanPassInRegs
The argument of this type can be passed directly in registers.
const FunctionProtoType * T
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_X86Pascal
Definition: Specifiers.h:281
@ CC_Swift
Definition: Specifiers.h:290
@ CC_IntelOclBicc
Definition: Specifiers.h:287
@ CC_OpenCLKernel
Definition: Specifiers.h:289
@ CC_PreserveMost
Definition: Specifiers.h:292
@ CC_Win64
Definition: Specifiers.h:282
@ CC_X86ThisCall
Definition: Specifiers.h:279
@ CC_AArch64VectorCall
Definition: Specifiers.h:294
@ CC_AAPCS
Definition: Specifiers.h:285
@ CC_PreserveNone
Definition: Specifiers.h:298
@ CC_C
Definition: Specifiers.h:276
@ CC_AMDGPUKernelCall
Definition: Specifiers.h:296
@ CC_M68kRTD
Definition: Specifiers.h:297
@ CC_SwiftAsync
Definition: Specifiers.h:291
@ CC_X86RegCall
Definition: Specifiers.h:284
@ CC_RISCVVectorCall
Definition: Specifiers.h:299
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_SpirFunction
Definition: Specifiers.h:288
@ CC_AArch64SVEPCS
Definition: Specifiers.h:295
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86_64SysV
Definition: Specifiers.h:283
@ CC_PreserveAll
Definition: Specifiers.h:293
@ CC_X86FastCall
Definition: Specifiers.h:278
@ CC_AAPCS_VFP
Definition: Specifiers.h:286
unsigned long uint64_t
Definition: Format.h:5433
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:40
Structure with information about how a bitfield should be accessed.
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Size
The total size of the bit-field, in bits.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
Similar to AddedStructorArgs, but only notes the number of additional arguments.
Definition: CGCXXABI.h:351
llvm::Value * ToUse
A value to "use" after the writeback, or null.
Definition: CGCall.h:270
LValue Source
The original argument.
Definition: CGCall.h:264
Address Temporary
The temporary alloca.
Definition: CGCall.h:267
LValue getKnownLValue() const
Definition: CGCall.h:237
RValue getKnownRValue() const
Definition: CGCall.h:241
void copyInto(CodeGenFunction &CGF, Address A) const
Definition: CGCall.cpp:4736
bool hasLValue() const
Definition: CGCall.h:230
RValue getRValue(CodeGenFunction &CGF) const
Definition: CGCall.cpp:4726
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::CallingConv::ID getRuntimeCC() const
bool isMSVCXXPersonality() const
Definition: CGCleanup.h:695
static const EHPersonality & get(CodeGenModule &CGM, const FunctionDecl *FD)
llvm::Function * objc_retainAutoreleasedReturnValue
id objc_retainAutoreleasedReturnValue(id);
llvm::Function * objc_retain
id objc_retain(id);
llvm::InlineAsm * retainAutoreleasedReturnValueMarker
A void(void) inline asm to use to mark that the return value of a call will be immediately retain.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:159
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.
Definition: Sanitizers.h:165
Iterator for iterating over Stmt * arrays that contain only T *.
Definition: Stmt.h:1316