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