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 "CGBlocks.h" 17 #include "CGCXXABI.h" 18 #include "CGCleanup.h" 19 #include "CodeGenFunction.h" 20 #include "CodeGenModule.h" 21 #include "TargetInfo.h" 22 #include "clang/AST/Decl.h" 23 #include "clang/AST/DeclCXX.h" 24 #include "clang/AST/DeclObjC.h" 25 #include "clang/Basic/CodeGenOptions.h" 26 #include "clang/Basic/TargetBuiltins.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/CodeGen/CGFunctionInfo.h" 29 #include "clang/CodeGen/SwiftCallingConv.h" 30 #include "llvm/ADT/StringExtras.h" 31 #include "llvm/Transforms/Utils/Local.h" 32 #include "llvm/Analysis/ValueTracking.h" 33 #include "llvm/IR/Attributes.h" 34 #include "llvm/IR/CallingConv.h" 35 #include "llvm/IR/DataLayout.h" 36 #include "llvm/IR/InlineAsm.h" 37 #include "llvm/IR/IntrinsicInst.h" 38 #include "llvm/IR/Intrinsics.h" 39 using namespace clang; 40 using namespace CodeGen; 41 42 /***/ 43 44 unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) { 45 switch (CC) { 46 default: return llvm::CallingConv::C; 47 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall; 48 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall; 49 case CC_X86RegCall: return llvm::CallingConv::X86_RegCall; 50 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall; 51 case CC_Win64: return llvm::CallingConv::Win64; 52 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV; 53 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS; 54 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 55 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI; 56 // TODO: Add support for __pascal to LLVM. 57 case CC_X86Pascal: return llvm::CallingConv::C; 58 // TODO: Add support for __vectorcall to LLVM. 59 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall; 60 case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall; 61 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC; 62 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv(); 63 case CC_PreserveMost: return llvm::CallingConv::PreserveMost; 64 case CC_PreserveAll: return llvm::CallingConv::PreserveAll; 65 case CC_Swift: return llvm::CallingConv::Swift; 66 } 67 } 68 69 /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR 70 /// qualification. Either or both of RD and MD may be null. A null RD indicates 71 /// that there is no meaningful 'this' type, and a null MD can occur when 72 /// calling a method pointer. 73 CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD, 74 const CXXMethodDecl *MD) { 75 QualType RecTy; 76 if (RD) 77 RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal(); 78 else 79 RecTy = Context.VoidTy; 80 81 if (MD) 82 RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace()); 83 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy)); 84 } 85 86 /// Returns the canonical formal type of the given C++ method. 87 static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) { 88 return MD->getType()->getCanonicalTypeUnqualified() 89 .getAs<FunctionProtoType>(); 90 } 91 92 /// Returns the "extra-canonicalized" return type, which discards 93 /// qualifiers on the return type. Codegen doesn't care about them, 94 /// and it makes ABI code a little easier to be able to assume that 95 /// all parameter and return types are top-level unqualified. 96 static CanQualType GetReturnType(QualType RetTy) { 97 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType(); 98 } 99 100 /// Arrange the argument and result information for a value of the given 101 /// unprototyped freestanding function type. 102 const CGFunctionInfo & 103 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) { 104 // When translating an unprototyped function type, always use a 105 // variadic type. 106 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(), 107 /*instanceMethod=*/false, 108 /*chainCall=*/false, None, 109 FTNP->getExtInfo(), {}, RequiredArgs(0)); 110 } 111 112 static void addExtParameterInfosForCall( 113 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> ¶mInfos, 114 const FunctionProtoType *proto, 115 unsigned prefixArgs, 116 unsigned totalArgs) { 117 assert(proto->hasExtParameterInfos()); 118 assert(paramInfos.size() <= prefixArgs); 119 assert(proto->getNumParams() + prefixArgs <= totalArgs); 120 121 paramInfos.reserve(totalArgs); 122 123 // Add default infos for any prefix args that don't already have infos. 124 paramInfos.resize(prefixArgs); 125 126 // Add infos for the prototype. 127 for (const auto &ParamInfo : proto->getExtParameterInfos()) { 128 paramInfos.push_back(ParamInfo); 129 // pass_object_size params have no parameter info. 130 if (ParamInfo.hasPassObjectSize()) 131 paramInfos.emplace_back(); 132 } 133 134 assert(paramInfos.size() <= totalArgs && 135 "Did we forget to insert pass_object_size args?"); 136 // Add default infos for the variadic and/or suffix arguments. 137 paramInfos.resize(totalArgs); 138 } 139 140 /// Adds the formal parameters in FPT to the given prefix. If any parameter in 141 /// FPT has pass_object_size attrs, then we'll add parameters for those, too. 142 static void appendParameterTypes(const CodeGenTypes &CGT, 143 SmallVectorImpl<CanQualType> &prefix, 144 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> ¶mInfos, 145 CanQual<FunctionProtoType> FPT) { 146 // Fast path: don't touch param info if we don't need to. 147 if (!FPT->hasExtParameterInfos()) { 148 assert(paramInfos.empty() && 149 "We have paramInfos, but the prototype doesn't?"); 150 prefix.append(FPT->param_type_begin(), FPT->param_type_end()); 151 return; 152 } 153 154 unsigned PrefixSize = prefix.size(); 155 // In the vast majority of cases, we'll have precisely FPT->getNumParams() 156 // parameters; the only thing that can change this is the presence of 157 // pass_object_size. So, we preallocate for the common case. 158 prefix.reserve(prefix.size() + FPT->getNumParams()); 159 160 auto ExtInfos = FPT->getExtParameterInfos(); 161 assert(ExtInfos.size() == FPT->getNumParams()); 162 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) { 163 prefix.push_back(FPT->getParamType(I)); 164 if (ExtInfos[I].hasPassObjectSize()) 165 prefix.push_back(CGT.getContext().getSizeType()); 166 } 167 168 addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize, 169 prefix.size()); 170 } 171 172 /// Arrange the LLVM function layout for a value of the given function 173 /// type, on top of any implicit parameters already stored. 174 static const CGFunctionInfo & 175 arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod, 176 SmallVectorImpl<CanQualType> &prefix, 177 CanQual<FunctionProtoType> FTP) { 178 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; 179 RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size()); 180 // FIXME: Kill copy. 181 appendParameterTypes(CGT, prefix, paramInfos, FTP); 182 CanQualType resultType = FTP->getReturnType().getUnqualifiedType(); 183 184 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod, 185 /*chainCall=*/false, prefix, 186 FTP->getExtInfo(), paramInfos, 187 Required); 188 } 189 190 /// Arrange the argument and result information for a value of the 191 /// given freestanding function type. 192 const CGFunctionInfo & 193 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) { 194 SmallVector<CanQualType, 16> argTypes; 195 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes, 196 FTP); 197 } 198 199 static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) { 200 // Set the appropriate calling convention for the Function. 201 if (D->hasAttr<StdCallAttr>()) 202 return CC_X86StdCall; 203 204 if (D->hasAttr<FastCallAttr>()) 205 return CC_X86FastCall; 206 207 if (D->hasAttr<RegCallAttr>()) 208 return CC_X86RegCall; 209 210 if (D->hasAttr<ThisCallAttr>()) 211 return CC_X86ThisCall; 212 213 if (D->hasAttr<VectorCallAttr>()) 214 return CC_X86VectorCall; 215 216 if (D->hasAttr<PascalAttr>()) 217 return CC_X86Pascal; 218 219 if (PcsAttr *PCS = D->getAttr<PcsAttr>()) 220 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP); 221 222 if (D->hasAttr<AArch64VectorPcsAttr>()) 223 return CC_AArch64VectorCall; 224 225 if (D->hasAttr<IntelOclBiccAttr>()) 226 return CC_IntelOclBicc; 227 228 if (D->hasAttr<MSABIAttr>()) 229 return IsWindows ? CC_C : CC_Win64; 230 231 if (D->hasAttr<SysVABIAttr>()) 232 return IsWindows ? CC_X86_64SysV : CC_C; 233 234 if (D->hasAttr<PreserveMostAttr>()) 235 return CC_PreserveMost; 236 237 if (D->hasAttr<PreserveAllAttr>()) 238 return CC_PreserveAll; 239 240 return CC_C; 241 } 242 243 /// Arrange the argument and result information for a call to an 244 /// unknown C++ non-static member function of the given abstract type. 245 /// (A null RD means we don't have any meaningful "this" argument type, 246 /// so fall back to a generic pointer type). 247 /// The member function must be an ordinary function, i.e. not a 248 /// constructor or destructor. 249 const CGFunctionInfo & 250 CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD, 251 const FunctionProtoType *FTP, 252 const CXXMethodDecl *MD) { 253 SmallVector<CanQualType, 16> argTypes; 254 255 // Add the 'this' pointer. 256 argTypes.push_back(DeriveThisType(RD, MD)); 257 258 return ::arrangeLLVMFunctionInfo( 259 *this, true, argTypes, 260 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>()); 261 } 262 263 /// Set calling convention for CUDA/HIP kernel. 264 static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM, 265 const FunctionDecl *FD) { 266 if (FD->hasAttr<CUDAGlobalAttr>()) { 267 const FunctionType *FT = FTy->getAs<FunctionType>(); 268 CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT); 269 FTy = FT->getCanonicalTypeUnqualified(); 270 } 271 } 272 273 /// Arrange the argument and result information for a declaration or 274 /// definition of the given C++ non-static member function. The 275 /// member function must be an ordinary function, i.e. not a 276 /// constructor or destructor. 277 const CGFunctionInfo & 278 CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) { 279 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!"); 280 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!"); 281 282 CanQualType FT = GetFormalType(MD).getAs<Type>(); 283 setCUDAKernelCallingConvention(FT, CGM, MD); 284 auto prototype = FT.getAs<FunctionProtoType>(); 285 286 if (MD->isInstance()) { 287 // The abstract case is perfectly fine. 288 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD); 289 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD); 290 } 291 292 return arrangeFreeFunctionType(prototype); 293 } 294 295 bool CodeGenTypes::inheritingCtorHasParams( 296 const InheritedConstructor &Inherited, CXXCtorType Type) { 297 // Parameters are unnecessary if we're constructing a base class subobject 298 // and the inherited constructor lives in a virtual base. 299 return Type == Ctor_Complete || 300 !Inherited.getShadowDecl()->constructsVirtualBase() || 301 !Target.getCXXABI().hasConstructorVariants(); 302 } 303 304 const CGFunctionInfo & 305 CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) { 306 auto *MD = cast<CXXMethodDecl>(GD.getDecl()); 307 308 SmallVector<CanQualType, 16> argTypes; 309 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; 310 argTypes.push_back(DeriveThisType(MD->getParent(), MD)); 311 312 bool PassParams = true; 313 314 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) { 315 // A base class inheriting constructor doesn't get forwarded arguments 316 // needed to construct a virtual base (or base class thereof). 317 if (auto Inherited = CD->getInheritedConstructor()) 318 PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType()); 319 } 320 321 CanQual<FunctionProtoType> FTP = GetFormalType(MD); 322 323 // Add the formal parameters. 324 if (PassParams) 325 appendParameterTypes(*this, argTypes, paramInfos, FTP); 326 327 CGCXXABI::AddedStructorArgs AddedArgs = 328 TheCXXABI.buildStructorSignature(GD, argTypes); 329 if (!paramInfos.empty()) { 330 // Note: prefix implies after the first param. 331 if (AddedArgs.Prefix) 332 paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix, 333 FunctionProtoType::ExtParameterInfo{}); 334 if (AddedArgs.Suffix) 335 paramInfos.append(AddedArgs.Suffix, 336 FunctionProtoType::ExtParameterInfo{}); 337 } 338 339 RequiredArgs required = 340 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size()) 341 : RequiredArgs::All); 342 343 FunctionType::ExtInfo extInfo = FTP->getExtInfo(); 344 CanQualType resultType = TheCXXABI.HasThisReturn(GD) 345 ? argTypes.front() 346 : TheCXXABI.hasMostDerivedReturn(GD) 347 ? CGM.getContext().VoidPtrTy 348 : Context.VoidTy; 349 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true, 350 /*chainCall=*/false, argTypes, extInfo, 351 paramInfos, required); 352 } 353 354 static SmallVector<CanQualType, 16> 355 getArgTypesForCall(ASTContext &ctx, const CallArgList &args) { 356 SmallVector<CanQualType, 16> argTypes; 357 for (auto &arg : args) 358 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty)); 359 return argTypes; 360 } 361 362 static SmallVector<CanQualType, 16> 363 getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) { 364 SmallVector<CanQualType, 16> argTypes; 365 for (auto &arg : args) 366 argTypes.push_back(ctx.getCanonicalParamType(arg->getType())); 367 return argTypes; 368 } 369 370 static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> 371 getExtParameterInfosForCall(const FunctionProtoType *proto, 372 unsigned prefixArgs, unsigned totalArgs) { 373 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result; 374 if (proto->hasExtParameterInfos()) { 375 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs); 376 } 377 return result; 378 } 379 380 /// Arrange a call to a C++ method, passing the given arguments. 381 /// 382 /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this` 383 /// parameter. 384 /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of 385 /// args. 386 /// PassProtoArgs indicates whether `args` has args for the parameters in the 387 /// given CXXConstructorDecl. 388 const CGFunctionInfo & 389 CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args, 390 const CXXConstructorDecl *D, 391 CXXCtorType CtorKind, 392 unsigned ExtraPrefixArgs, 393 unsigned ExtraSuffixArgs, 394 bool PassProtoArgs) { 395 // FIXME: Kill copy. 396 SmallVector<CanQualType, 16> ArgTypes; 397 for (const auto &Arg : args) 398 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty)); 399 400 // +1 for implicit this, which should always be args[0]. 401 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs; 402 403 CanQual<FunctionProtoType> FPT = GetFormalType(D); 404 RequiredArgs Required = PassProtoArgs 405 ? RequiredArgs::forPrototypePlus( 406 FPT, TotalPrefixArgs + ExtraSuffixArgs) 407 : RequiredArgs::All; 408 409 GlobalDecl GD(D, CtorKind); 410 CanQualType ResultType = TheCXXABI.HasThisReturn(GD) 411 ? ArgTypes.front() 412 : TheCXXABI.hasMostDerivedReturn(GD) 413 ? CGM.getContext().VoidPtrTy 414 : Context.VoidTy; 415 416 FunctionType::ExtInfo Info = FPT->getExtInfo(); 417 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos; 418 // If the prototype args are elided, we should only have ABI-specific args, 419 // which never have param info. 420 if (PassProtoArgs && FPT->hasExtParameterInfos()) { 421 // ABI-specific suffix arguments are treated the same as variadic arguments. 422 addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs, 423 ArgTypes.size()); 424 } 425 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true, 426 /*chainCall=*/false, ArgTypes, Info, 427 ParamInfos, Required); 428 } 429 430 /// Arrange the argument and result information for the declaration or 431 /// definition of the given function. 432 const CGFunctionInfo & 433 CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) { 434 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 435 if (MD->isInstance()) 436 return arrangeCXXMethodDeclaration(MD); 437 438 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified(); 439 440 assert(isa<FunctionType>(FTy)); 441 setCUDAKernelCallingConvention(FTy, CGM, FD); 442 443 // When declaring a function without a prototype, always use a 444 // non-variadic type. 445 if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) { 446 return arrangeLLVMFunctionInfo( 447 noProto->getReturnType(), /*instanceMethod=*/false, 448 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All); 449 } 450 451 return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>()); 452 } 453 454 /// Arrange the argument and result information for the declaration or 455 /// definition of an Objective-C method. 456 const CGFunctionInfo & 457 CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) { 458 // It happens that this is the same as a call with no optional 459 // arguments, except also using the formal 'self' type. 460 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType()); 461 } 462 463 /// Arrange the argument and result information for the function type 464 /// through which to perform a send to the given Objective-C method, 465 /// using the given receiver type. The receiver type is not always 466 /// the 'self' type of the method or even an Objective-C pointer type. 467 /// This is *not* the right method for actually performing such a 468 /// message send, due to the possibility of optional arguments. 469 const CGFunctionInfo & 470 CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD, 471 QualType receiverType) { 472 SmallVector<CanQualType, 16> argTys; 473 SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2); 474 argTys.push_back(Context.getCanonicalParamType(receiverType)); 475 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType())); 476 // FIXME: Kill copy? 477 for (const auto *I : MD->parameters()) { 478 argTys.push_back(Context.getCanonicalParamType(I->getType())); 479 auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape( 480 I->hasAttr<NoEscapeAttr>()); 481 extParamInfos.push_back(extParamInfo); 482 } 483 484 FunctionType::ExtInfo einfo; 485 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows(); 486 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows)); 487 488 if (getContext().getLangOpts().ObjCAutoRefCount && 489 MD->hasAttr<NSReturnsRetainedAttr>()) 490 einfo = einfo.withProducesResult(true); 491 492 RequiredArgs required = 493 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All); 494 495 return arrangeLLVMFunctionInfo( 496 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false, 497 /*chainCall=*/false, argTys, einfo, extParamInfos, required); 498 } 499 500 const CGFunctionInfo & 501 CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType, 502 const CallArgList &args) { 503 auto argTypes = getArgTypesForCall(Context, args); 504 FunctionType::ExtInfo einfo; 505 506 return arrangeLLVMFunctionInfo( 507 GetReturnType(returnType), /*instanceMethod=*/false, 508 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All); 509 } 510 511 const CGFunctionInfo & 512 CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) { 513 // FIXME: Do we need to handle ObjCMethodDecl? 514 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 515 516 if (isa<CXXConstructorDecl>(GD.getDecl()) || 517 isa<CXXDestructorDecl>(GD.getDecl())) 518 return arrangeCXXStructorDeclaration(GD); 519 520 return arrangeFunctionDeclaration(FD); 521 } 522 523 /// Arrange a thunk that takes 'this' as the first parameter followed by 524 /// varargs. Return a void pointer, regardless of the actual return type. 525 /// The body of the thunk will end in a musttail call to a function of the 526 /// correct type, and the caller will bitcast the function to the correct 527 /// prototype. 528 const CGFunctionInfo & 529 CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) { 530 assert(MD->isVirtual() && "only methods have thunks"); 531 CanQual<FunctionProtoType> FTP = GetFormalType(MD); 532 CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)}; 533 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false, 534 /*chainCall=*/false, ArgTys, 535 FTP->getExtInfo(), {}, RequiredArgs(1)); 536 } 537 538 const CGFunctionInfo & 539 CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD, 540 CXXCtorType CT) { 541 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure); 542 543 CanQual<FunctionProtoType> FTP = GetFormalType(CD); 544 SmallVector<CanQualType, 2> ArgTys; 545 const CXXRecordDecl *RD = CD->getParent(); 546 ArgTys.push_back(DeriveThisType(RD, CD)); 547 if (CT == Ctor_CopyingClosure) 548 ArgTys.push_back(*FTP->param_type_begin()); 549 if (RD->getNumVBases() > 0) 550 ArgTys.push_back(Context.IntTy); 551 CallingConv CC = Context.getDefaultCallingConvention( 552 /*IsVariadic=*/false, /*IsCXXMethod=*/true); 553 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true, 554 /*chainCall=*/false, ArgTys, 555 FunctionType::ExtInfo(CC), {}, 556 RequiredArgs::All); 557 } 558 559 /// Arrange a call as unto a free function, except possibly with an 560 /// additional number of formal parameters considered required. 561 static const CGFunctionInfo & 562 arrangeFreeFunctionLikeCall(CodeGenTypes &CGT, 563 CodeGenModule &CGM, 564 const CallArgList &args, 565 const FunctionType *fnType, 566 unsigned numExtraRequiredArgs, 567 bool chainCall) { 568 assert(args.size() >= numExtraRequiredArgs); 569 570 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; 571 572 // In most cases, there are no optional arguments. 573 RequiredArgs required = RequiredArgs::All; 574 575 // If we have a variadic prototype, the required arguments are the 576 // extra prefix plus the arguments in the prototype. 577 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) { 578 if (proto->isVariadic()) 579 required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs); 580 581 if (proto->hasExtParameterInfos()) 582 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs, 583 args.size()); 584 585 // If we don't have a prototype at all, but we're supposed to 586 // explicitly use the variadic convention for unprototyped calls, 587 // treat all of the arguments as required but preserve the nominal 588 // possibility of variadics. 589 } else if (CGM.getTargetCodeGenInfo() 590 .isNoProtoCallVariadic(args, 591 cast<FunctionNoProtoType>(fnType))) { 592 required = RequiredArgs(args.size()); 593 } 594 595 // FIXME: Kill copy. 596 SmallVector<CanQualType, 16> argTypes; 597 for (const auto &arg : args) 598 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty)); 599 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()), 600 /*instanceMethod=*/false, chainCall, 601 argTypes, fnType->getExtInfo(), paramInfos, 602 required); 603 } 604 605 /// Figure out the rules for calling a function with the given formal 606 /// type using the given arguments. The arguments are necessary 607 /// because the function might be unprototyped, in which case it's 608 /// target-dependent in crazy ways. 609 const CGFunctionInfo & 610 CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args, 611 const FunctionType *fnType, 612 bool chainCall) { 613 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 614 chainCall ? 1 : 0, chainCall); 615 } 616 617 /// A block function is essentially a free function with an 618 /// extra implicit argument. 619 const CGFunctionInfo & 620 CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args, 621 const FunctionType *fnType) { 622 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1, 623 /*chainCall=*/false); 624 } 625 626 const CGFunctionInfo & 627 CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto, 628 const FunctionArgList ¶ms) { 629 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size()); 630 auto argTypes = getArgTypesForDeclaration(Context, params); 631 632 return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()), 633 /*instanceMethod*/ false, /*chainCall*/ false, 634 argTypes, proto->getExtInfo(), paramInfos, 635 RequiredArgs::forPrototypePlus(proto, 1)); 636 } 637 638 const CGFunctionInfo & 639 CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType, 640 const CallArgList &args) { 641 // FIXME: Kill copy. 642 SmallVector<CanQualType, 16> argTypes; 643 for (const auto &Arg : args) 644 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty)); 645 return arrangeLLVMFunctionInfo( 646 GetReturnType(resultType), /*instanceMethod=*/false, 647 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(), 648 /*paramInfos=*/ {}, RequiredArgs::All); 649 } 650 651 const CGFunctionInfo & 652 CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType, 653 const FunctionArgList &args) { 654 auto argTypes = getArgTypesForDeclaration(Context, args); 655 656 return arrangeLLVMFunctionInfo( 657 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false, 658 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All); 659 } 660 661 const CGFunctionInfo & 662 CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType, 663 ArrayRef<CanQualType> argTypes) { 664 return arrangeLLVMFunctionInfo( 665 resultType, /*instanceMethod=*/false, /*chainCall=*/false, 666 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All); 667 } 668 669 /// Arrange a call to a C++ method, passing the given arguments. 670 /// 671 /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It 672 /// does not count `this`. 673 const CGFunctionInfo & 674 CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args, 675 const FunctionProtoType *proto, 676 RequiredArgs required, 677 unsigned numPrefixArgs) { 678 assert(numPrefixArgs + 1 <= args.size() && 679 "Emitting a call with less args than the required prefix?"); 680 // Add one to account for `this`. It's a bit awkward here, but we don't count 681 // `this` in similar places elsewhere. 682 auto paramInfos = 683 getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size()); 684 685 // FIXME: Kill copy. 686 auto argTypes = getArgTypesForCall(Context, args); 687 688 FunctionType::ExtInfo info = proto->getExtInfo(); 689 return arrangeLLVMFunctionInfo( 690 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true, 691 /*chainCall=*/false, argTypes, info, paramInfos, required); 692 } 693 694 const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() { 695 return arrangeLLVMFunctionInfo( 696 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false, 697 None, FunctionType::ExtInfo(), {}, RequiredArgs::All); 698 } 699 700 const CGFunctionInfo & 701 CodeGenTypes::arrangeCall(const CGFunctionInfo &signature, 702 const CallArgList &args) { 703 assert(signature.arg_size() <= args.size()); 704 if (signature.arg_size() == args.size()) 705 return signature; 706 707 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; 708 auto sigParamInfos = signature.getExtParameterInfos(); 709 if (!sigParamInfos.empty()) { 710 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end()); 711 paramInfos.resize(args.size()); 712 } 713 714 auto argTypes = getArgTypesForCall(Context, args); 715 716 assert(signature.getRequiredArgs().allowsOptionalArgs()); 717 return arrangeLLVMFunctionInfo(signature.getReturnType(), 718 signature.isInstanceMethod(), 719 signature.isChainCall(), 720 argTypes, 721 signature.getExtInfo(), 722 paramInfos, 723 signature.getRequiredArgs()); 724 } 725 726 namespace clang { 727 namespace CodeGen { 728 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI); 729 } 730 } 731 732 /// Arrange the argument and result information for an abstract value 733 /// of a given function type. This is the method which all of the 734 /// above functions ultimately defer to. 735 const CGFunctionInfo & 736 CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType, 737 bool instanceMethod, 738 bool chainCall, 739 ArrayRef<CanQualType> argTypes, 740 FunctionType::ExtInfo info, 741 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos, 742 RequiredArgs required) { 743 assert(llvm::all_of(argTypes, 744 [](CanQualType T) { return T.isCanonicalAsParam(); })); 745 746 // Lookup or create unique function info. 747 llvm::FoldingSetNodeID ID; 748 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos, 749 required, resultType, argTypes); 750 751 void *insertPos = nullptr; 752 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos); 753 if (FI) 754 return *FI; 755 756 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC()); 757 758 // Construct the function info. We co-allocate the ArgInfos. 759 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info, 760 paramInfos, resultType, argTypes, required); 761 FunctionInfos.InsertNode(FI, insertPos); 762 763 bool inserted = FunctionsBeingProcessed.insert(FI).second; 764 (void)inserted; 765 assert(inserted && "Recursively being processed?"); 766 767 // Compute ABI information. 768 if (CC == llvm::CallingConv::SPIR_KERNEL) { 769 // Force target independent argument handling for the host visible 770 // kernel functions. 771 computeSPIRKernelABIInfo(CGM, *FI); 772 } else if (info.getCC() == CC_Swift) { 773 swiftcall::computeABIInfo(CGM, *FI); 774 } else { 775 getABIInfo().computeInfo(*FI); 776 } 777 778 // Loop over all of the computed argument and return value info. If any of 779 // them are direct or extend without a specified coerce type, specify the 780 // default now. 781 ABIArgInfo &retInfo = FI->getReturnInfo(); 782 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr) 783 retInfo.setCoerceToType(ConvertType(FI->getReturnType())); 784 785 for (auto &I : FI->arguments()) 786 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr) 787 I.info.setCoerceToType(ConvertType(I.type)); 788 789 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased; 790 assert(erased && "Not in set?"); 791 792 return *FI; 793 } 794 795 CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC, 796 bool instanceMethod, 797 bool chainCall, 798 const FunctionType::ExtInfo &info, 799 ArrayRef<ExtParameterInfo> paramInfos, 800 CanQualType resultType, 801 ArrayRef<CanQualType> argTypes, 802 RequiredArgs required) { 803 assert(paramInfos.empty() || paramInfos.size() == argTypes.size()); 804 assert(!required.allowsOptionalArgs() || 805 required.getNumRequiredArgs() <= argTypes.size()); 806 807 void *buffer = 808 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>( 809 argTypes.size() + 1, paramInfos.size())); 810 811 CGFunctionInfo *FI = new(buffer) CGFunctionInfo(); 812 FI->CallingConvention = llvmCC; 813 FI->EffectiveCallingConvention = llvmCC; 814 FI->ASTCallingConvention = info.getCC(); 815 FI->InstanceMethod = instanceMethod; 816 FI->ChainCall = chainCall; 817 FI->NoReturn = info.getNoReturn(); 818 FI->ReturnsRetained = info.getProducesResult(); 819 FI->NoCallerSavedRegs = info.getNoCallerSavedRegs(); 820 FI->NoCfCheck = info.getNoCfCheck(); 821 FI->Required = required; 822 FI->HasRegParm = info.getHasRegParm(); 823 FI->RegParm = info.getRegParm(); 824 FI->ArgStruct = nullptr; 825 FI->ArgStructAlign = 0; 826 FI->NumArgs = argTypes.size(); 827 FI->HasExtParameterInfos = !paramInfos.empty(); 828 FI->getArgsBuffer()[0].type = resultType; 829 for (unsigned i = 0, e = argTypes.size(); i != e; ++i) 830 FI->getArgsBuffer()[i + 1].type = argTypes[i]; 831 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i) 832 FI->getExtParameterInfosBuffer()[i] = paramInfos[i]; 833 return FI; 834 } 835 836 /***/ 837 838 namespace { 839 // ABIArgInfo::Expand implementation. 840 841 // Specifies the way QualType passed as ABIArgInfo::Expand is expanded. 842 struct TypeExpansion { 843 enum TypeExpansionKind { 844 // Elements of constant arrays are expanded recursively. 845 TEK_ConstantArray, 846 // Record fields are expanded recursively (but if record is a union, only 847 // the field with the largest size is expanded). 848 TEK_Record, 849 // For complex types, real and imaginary parts are expanded recursively. 850 TEK_Complex, 851 // All other types are not expandable. 852 TEK_None 853 }; 854 855 const TypeExpansionKind Kind; 856 857 TypeExpansion(TypeExpansionKind K) : Kind(K) {} 858 virtual ~TypeExpansion() {} 859 }; 860 861 struct ConstantArrayExpansion : TypeExpansion { 862 QualType EltTy; 863 uint64_t NumElts; 864 865 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts) 866 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {} 867 static bool classof(const TypeExpansion *TE) { 868 return TE->Kind == TEK_ConstantArray; 869 } 870 }; 871 872 struct RecordExpansion : TypeExpansion { 873 SmallVector<const CXXBaseSpecifier *, 1> Bases; 874 875 SmallVector<const FieldDecl *, 1> Fields; 876 877 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases, 878 SmallVector<const FieldDecl *, 1> &&Fields) 879 : TypeExpansion(TEK_Record), Bases(std::move(Bases)), 880 Fields(std::move(Fields)) {} 881 static bool classof(const TypeExpansion *TE) { 882 return TE->Kind == TEK_Record; 883 } 884 }; 885 886 struct ComplexExpansion : TypeExpansion { 887 QualType EltTy; 888 889 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {} 890 static bool classof(const TypeExpansion *TE) { 891 return TE->Kind == TEK_Complex; 892 } 893 }; 894 895 struct NoExpansion : TypeExpansion { 896 NoExpansion() : TypeExpansion(TEK_None) {} 897 static bool classof(const TypeExpansion *TE) { 898 return TE->Kind == TEK_None; 899 } 900 }; 901 } // namespace 902 903 static std::unique_ptr<TypeExpansion> 904 getTypeExpansion(QualType Ty, const ASTContext &Context) { 905 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 906 return std::make_unique<ConstantArrayExpansion>( 907 AT->getElementType(), AT->getSize().getZExtValue()); 908 } 909 if (const RecordType *RT = Ty->getAs<RecordType>()) { 910 SmallVector<const CXXBaseSpecifier *, 1> Bases; 911 SmallVector<const FieldDecl *, 1> Fields; 912 const RecordDecl *RD = RT->getDecl(); 913 assert(!RD->hasFlexibleArrayMember() && 914 "Cannot expand structure with flexible array."); 915 if (RD->isUnion()) { 916 // Unions can be here only in degenerative cases - all the fields are same 917 // after flattening. Thus we have to use the "largest" field. 918 const FieldDecl *LargestFD = nullptr; 919 CharUnits UnionSize = CharUnits::Zero(); 920 921 for (const auto *FD : RD->fields()) { 922 if (FD->isZeroLengthBitField(Context)) 923 continue; 924 assert(!FD->isBitField() && 925 "Cannot expand structure with bit-field members."); 926 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType()); 927 if (UnionSize < FieldSize) { 928 UnionSize = FieldSize; 929 LargestFD = FD; 930 } 931 } 932 if (LargestFD) 933 Fields.push_back(LargestFD); 934 } else { 935 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 936 assert(!CXXRD->isDynamicClass() && 937 "cannot expand vtable pointers in dynamic classes"); 938 for (const CXXBaseSpecifier &BS : CXXRD->bases()) 939 Bases.push_back(&BS); 940 } 941 942 for (const auto *FD : RD->fields()) { 943 if (FD->isZeroLengthBitField(Context)) 944 continue; 945 assert(!FD->isBitField() && 946 "Cannot expand structure with bit-field members."); 947 Fields.push_back(FD); 948 } 949 } 950 return std::make_unique<RecordExpansion>(std::move(Bases), 951 std::move(Fields)); 952 } 953 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 954 return std::make_unique<ComplexExpansion>(CT->getElementType()); 955 } 956 return std::make_unique<NoExpansion>(); 957 } 958 959 static int getExpansionSize(QualType Ty, const ASTContext &Context) { 960 auto Exp = getTypeExpansion(Ty, Context); 961 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 962 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context); 963 } 964 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 965 int Res = 0; 966 for (auto BS : RExp->Bases) 967 Res += getExpansionSize(BS->getType(), Context); 968 for (auto FD : RExp->Fields) 969 Res += getExpansionSize(FD->getType(), Context); 970 return Res; 971 } 972 if (isa<ComplexExpansion>(Exp.get())) 973 return 2; 974 assert(isa<NoExpansion>(Exp.get())); 975 return 1; 976 } 977 978 void 979 CodeGenTypes::getExpandedTypes(QualType Ty, 980 SmallVectorImpl<llvm::Type *>::iterator &TI) { 981 auto Exp = getTypeExpansion(Ty, Context); 982 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 983 for (int i = 0, n = CAExp->NumElts; i < n; i++) { 984 getExpandedTypes(CAExp->EltTy, TI); 985 } 986 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 987 for (auto BS : RExp->Bases) 988 getExpandedTypes(BS->getType(), TI); 989 for (auto FD : RExp->Fields) 990 getExpandedTypes(FD->getType(), TI); 991 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) { 992 llvm::Type *EltTy = ConvertType(CExp->EltTy); 993 *TI++ = EltTy; 994 *TI++ = EltTy; 995 } else { 996 assert(isa<NoExpansion>(Exp.get())); 997 *TI++ = ConvertType(Ty); 998 } 999 } 1000 1001 static void forConstantArrayExpansion(CodeGenFunction &CGF, 1002 ConstantArrayExpansion *CAE, 1003 Address BaseAddr, 1004 llvm::function_ref<void(Address)> Fn) { 1005 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy); 1006 CharUnits EltAlign = 1007 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize); 1008 1009 for (int i = 0, n = CAE->NumElts; i < n; i++) { 1010 llvm::Value *EltAddr = 1011 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i); 1012 Fn(Address(EltAddr, EltAlign)); 1013 } 1014 } 1015 1016 void CodeGenFunction::ExpandTypeFromArgs( 1017 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) { 1018 assert(LV.isSimple() && 1019 "Unexpected non-simple lvalue during struct expansion."); 1020 1021 auto Exp = getTypeExpansion(Ty, getContext()); 1022 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 1023 forConstantArrayExpansion( 1024 *this, CAExp, LV.getAddress(*this), [&](Address EltAddr) { 1025 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy); 1026 ExpandTypeFromArgs(CAExp->EltTy, LV, AI); 1027 }); 1028 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 1029 Address This = LV.getAddress(*this); 1030 for (const CXXBaseSpecifier *BS : RExp->Bases) { 1031 // Perform a single step derived-to-base conversion. 1032 Address Base = 1033 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1, 1034 /*NullCheckValue=*/false, SourceLocation()); 1035 LValue SubLV = MakeAddrLValue(Base, BS->getType()); 1036 1037 // Recurse onto bases. 1038 ExpandTypeFromArgs(BS->getType(), SubLV, AI); 1039 } 1040 for (auto FD : RExp->Fields) { 1041 // FIXME: What are the right qualifiers here? 1042 LValue SubLV = EmitLValueForFieldInitialization(LV, FD); 1043 ExpandTypeFromArgs(FD->getType(), SubLV, AI); 1044 } 1045 } else if (isa<ComplexExpansion>(Exp.get())) { 1046 auto realValue = *AI++; 1047 auto imagValue = *AI++; 1048 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true); 1049 } else { 1050 // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a 1051 // primitive store. 1052 assert(isa<NoExpansion>(Exp.get())); 1053 if (LV.isBitField()) 1054 EmitStoreThroughLValue(RValue::get(*AI++), LV); 1055 else 1056 EmitStoreOfScalar(*AI++, LV); 1057 } 1058 } 1059 1060 void CodeGenFunction::ExpandTypeToArgs( 1061 QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy, 1062 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) { 1063 auto Exp = getTypeExpansion(Ty, getContext()); 1064 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 1065 Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this) 1066 : Arg.getKnownRValue().getAggregateAddress(); 1067 forConstantArrayExpansion( 1068 *this, CAExp, Addr, [&](Address EltAddr) { 1069 CallArg EltArg = CallArg( 1070 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()), 1071 CAExp->EltTy); 1072 ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs, 1073 IRCallArgPos); 1074 }); 1075 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 1076 Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this) 1077 : Arg.getKnownRValue().getAggregateAddress(); 1078 for (const CXXBaseSpecifier *BS : RExp->Bases) { 1079 // Perform a single step derived-to-base conversion. 1080 Address Base = 1081 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1, 1082 /*NullCheckValue=*/false, SourceLocation()); 1083 CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType()); 1084 1085 // Recurse onto bases. 1086 ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs, 1087 IRCallArgPos); 1088 } 1089 1090 LValue LV = MakeAddrLValue(This, Ty); 1091 for (auto FD : RExp->Fields) { 1092 CallArg FldArg = 1093 CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType()); 1094 ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs, 1095 IRCallArgPos); 1096 } 1097 } else if (isa<ComplexExpansion>(Exp.get())) { 1098 ComplexPairTy CV = Arg.getKnownRValue().getComplexVal(); 1099 IRCallArgs[IRCallArgPos++] = CV.first; 1100 IRCallArgs[IRCallArgPos++] = CV.second; 1101 } else { 1102 assert(isa<NoExpansion>(Exp.get())); 1103 auto RV = Arg.getKnownRValue(); 1104 assert(RV.isScalar() && 1105 "Unexpected non-scalar rvalue during struct expansion."); 1106 1107 // Insert a bitcast as needed. 1108 llvm::Value *V = RV.getScalarVal(); 1109 if (IRCallArgPos < IRFuncTy->getNumParams() && 1110 V->getType() != IRFuncTy->getParamType(IRCallArgPos)) 1111 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos)); 1112 1113 IRCallArgs[IRCallArgPos++] = V; 1114 } 1115 } 1116 1117 /// Create a temporary allocation for the purposes of coercion. 1118 static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty, 1119 CharUnits MinAlign) { 1120 // Don't use an alignment that's worse than what LLVM would prefer. 1121 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty); 1122 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign)); 1123 1124 return CGF.CreateTempAlloca(Ty, Align); 1125 } 1126 1127 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are 1128 /// accessing some number of bytes out of it, try to gep into the struct to get 1129 /// at its inner goodness. Dive as deep as possible without entering an element 1130 /// with an in-memory size smaller than DstSize. 1131 static Address 1132 EnterStructPointerForCoercedAccess(Address SrcPtr, 1133 llvm::StructType *SrcSTy, 1134 uint64_t DstSize, CodeGenFunction &CGF) { 1135 // We can't dive into a zero-element struct. 1136 if (SrcSTy->getNumElements() == 0) return SrcPtr; 1137 1138 llvm::Type *FirstElt = SrcSTy->getElementType(0); 1139 1140 // If the first elt is at least as large as what we're looking for, or if the 1141 // first element is the same size as the whole struct, we can enter it. The 1142 // comparison must be made on the store size and not the alloca size. Using 1143 // the alloca size may overstate the size of the load. 1144 uint64_t FirstEltSize = 1145 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt); 1146 if (FirstEltSize < DstSize && 1147 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy)) 1148 return SrcPtr; 1149 1150 // GEP into the first element. 1151 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive"); 1152 1153 // If the first element is a struct, recurse. 1154 llvm::Type *SrcTy = SrcPtr.getElementType(); 1155 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) 1156 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF); 1157 1158 return SrcPtr; 1159 } 1160 1161 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both 1162 /// are either integers or pointers. This does a truncation of the value if it 1163 /// is too large or a zero extension if it is too small. 1164 /// 1165 /// This behaves as if the value were coerced through memory, so on big-endian 1166 /// targets the high bits are preserved in a truncation, while little-endian 1167 /// targets preserve the low bits. 1168 static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val, 1169 llvm::Type *Ty, 1170 CodeGenFunction &CGF) { 1171 if (Val->getType() == Ty) 1172 return Val; 1173 1174 if (isa<llvm::PointerType>(Val->getType())) { 1175 // If this is Pointer->Pointer avoid conversion to and from int. 1176 if (isa<llvm::PointerType>(Ty)) 1177 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val"); 1178 1179 // Convert the pointer to an integer so we can play with its width. 1180 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi"); 1181 } 1182 1183 llvm::Type *DestIntTy = Ty; 1184 if (isa<llvm::PointerType>(DestIntTy)) 1185 DestIntTy = CGF.IntPtrTy; 1186 1187 if (Val->getType() != DestIntTy) { 1188 const llvm::DataLayout &DL = CGF.CGM.getDataLayout(); 1189 if (DL.isBigEndian()) { 1190 // Preserve the high bits on big-endian targets. 1191 // That is what memory coercion does. 1192 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType()); 1193 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy); 1194 1195 if (SrcSize > DstSize) { 1196 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits"); 1197 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii"); 1198 } else { 1199 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii"); 1200 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits"); 1201 } 1202 } else { 1203 // Little-endian targets preserve the low bits. No shifts required. 1204 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii"); 1205 } 1206 } 1207 1208 if (isa<llvm::PointerType>(Ty)) 1209 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip"); 1210 return Val; 1211 } 1212 1213 1214 1215 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as 1216 /// a pointer to an object of type \arg Ty, known to be aligned to 1217 /// \arg SrcAlign bytes. 1218 /// 1219 /// This safely handles the case when the src type is smaller than the 1220 /// destination type; in this situation the values of bits which not 1221 /// present in the src are undefined. 1222 static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty, 1223 CodeGenFunction &CGF) { 1224 llvm::Type *SrcTy = Src.getElementType(); 1225 1226 // If SrcTy and Ty are the same, just do a load. 1227 if (SrcTy == Ty) 1228 return CGF.Builder.CreateLoad(Src); 1229 1230 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty); 1231 1232 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) { 1233 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF); 1234 SrcTy = Src.getType()->getElementType(); 1235 } 1236 1237 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy); 1238 1239 // If the source and destination are integer or pointer types, just do an 1240 // extension or truncation to the desired type. 1241 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) && 1242 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) { 1243 llvm::Value *Load = CGF.Builder.CreateLoad(Src); 1244 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF); 1245 } 1246 1247 // If load is legal, just bitcast the src pointer. 1248 if (SrcSize >= DstSize) { 1249 // Generally SrcSize is never greater than DstSize, since this means we are 1250 // losing bits. However, this can happen in cases where the structure has 1251 // additional padding, for example due to a user specified alignment. 1252 // 1253 // FIXME: Assert that we aren't truncating non-padding bits when have access 1254 // to that information. 1255 Src = CGF.Builder.CreateBitCast(Src, 1256 Ty->getPointerTo(Src.getAddressSpace())); 1257 return CGF.Builder.CreateLoad(Src); 1258 } 1259 1260 // Otherwise do coercion through memory. This is stupid, but simple. 1261 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment()); 1262 Address Casted = CGF.Builder.CreateElementBitCast(Tmp,CGF.Int8Ty); 1263 Address SrcCasted = CGF.Builder.CreateElementBitCast(Src,CGF.Int8Ty); 1264 CGF.Builder.CreateMemCpy(Casted, SrcCasted, 1265 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize), 1266 false); 1267 return CGF.Builder.CreateLoad(Tmp); 1268 } 1269 1270 // Function to store a first-class aggregate into memory. We prefer to 1271 // store the elements rather than the aggregate to be more friendly to 1272 // fast-isel. 1273 // FIXME: Do we need to recurse here? 1274 static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val, 1275 Address Dest, bool DestIsVolatile) { 1276 // Prefer scalar stores to first-class aggregate stores. 1277 if (llvm::StructType *STy = 1278 dyn_cast<llvm::StructType>(Val->getType())) { 1279 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1280 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i); 1281 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i); 1282 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile); 1283 } 1284 } else { 1285 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile); 1286 } 1287 } 1288 1289 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src, 1290 /// where the source and destination may have different types. The 1291 /// destination is known to be aligned to \arg DstAlign bytes. 1292 /// 1293 /// This safely handles the case when the src type is larger than the 1294 /// destination type; the upper bits of the src will be lost. 1295 static void CreateCoercedStore(llvm::Value *Src, 1296 Address Dst, 1297 bool DstIsVolatile, 1298 CodeGenFunction &CGF) { 1299 llvm::Type *SrcTy = Src->getType(); 1300 llvm::Type *DstTy = Dst.getType()->getElementType(); 1301 if (SrcTy == DstTy) { 1302 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1303 return; 1304 } 1305 1306 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy); 1307 1308 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) { 1309 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF); 1310 DstTy = Dst.getType()->getElementType(); 1311 } 1312 1313 llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy); 1314 llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy); 1315 if (SrcPtrTy && DstPtrTy && 1316 SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) { 1317 Src = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy); 1318 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1319 return; 1320 } 1321 1322 // If the source and destination are integer or pointer types, just do an 1323 // extension or truncation to the desired type. 1324 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) && 1325 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) { 1326 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF); 1327 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1328 return; 1329 } 1330 1331 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy); 1332 1333 // If store is legal, just bitcast the src pointer. 1334 if (SrcSize <= DstSize) { 1335 Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy); 1336 BuildAggStore(CGF, Src, Dst, DstIsVolatile); 1337 } else { 1338 // Otherwise do coercion through memory. This is stupid, but 1339 // simple. 1340 1341 // Generally SrcSize is never greater than DstSize, since this means we are 1342 // losing bits. However, this can happen in cases where the structure has 1343 // additional padding, for example due to a user specified alignment. 1344 // 1345 // FIXME: Assert that we aren't truncating non-padding bits when have access 1346 // to that information. 1347 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment()); 1348 CGF.Builder.CreateStore(Src, Tmp); 1349 Address Casted = CGF.Builder.CreateElementBitCast(Tmp,CGF.Int8Ty); 1350 Address DstCasted = CGF.Builder.CreateElementBitCast(Dst,CGF.Int8Ty); 1351 CGF.Builder.CreateMemCpy(DstCasted, Casted, 1352 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize), 1353 false); 1354 } 1355 } 1356 1357 static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr, 1358 const ABIArgInfo &info) { 1359 if (unsigned offset = info.getDirectOffset()) { 1360 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty); 1361 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr, 1362 CharUnits::fromQuantity(offset)); 1363 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType()); 1364 } 1365 return addr; 1366 } 1367 1368 namespace { 1369 1370 /// Encapsulates information about the way function arguments from 1371 /// CGFunctionInfo should be passed to actual LLVM IR function. 1372 class ClangToLLVMArgMapping { 1373 static const unsigned InvalidIndex = ~0U; 1374 unsigned InallocaArgNo; 1375 unsigned SRetArgNo; 1376 unsigned TotalIRArgs; 1377 1378 /// Arguments of LLVM IR function corresponding to single Clang argument. 1379 struct IRArgs { 1380 unsigned PaddingArgIndex; 1381 // Argument is expanded to IR arguments at positions 1382 // [FirstArgIndex, FirstArgIndex + NumberOfArgs). 1383 unsigned FirstArgIndex; 1384 unsigned NumberOfArgs; 1385 1386 IRArgs() 1387 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex), 1388 NumberOfArgs(0) {} 1389 }; 1390 1391 SmallVector<IRArgs, 8> ArgInfo; 1392 1393 public: 1394 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI, 1395 bool OnlyRequiredArgs = false) 1396 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0), 1397 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) { 1398 construct(Context, FI, OnlyRequiredArgs); 1399 } 1400 1401 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; } 1402 unsigned getInallocaArgNo() const { 1403 assert(hasInallocaArg()); 1404 return InallocaArgNo; 1405 } 1406 1407 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; } 1408 unsigned getSRetArgNo() const { 1409 assert(hasSRetArg()); 1410 return SRetArgNo; 1411 } 1412 1413 unsigned totalIRArgs() const { return TotalIRArgs; } 1414 1415 bool hasPaddingArg(unsigned ArgNo) const { 1416 assert(ArgNo < ArgInfo.size()); 1417 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex; 1418 } 1419 unsigned getPaddingArgNo(unsigned ArgNo) const { 1420 assert(hasPaddingArg(ArgNo)); 1421 return ArgInfo[ArgNo].PaddingArgIndex; 1422 } 1423 1424 /// Returns index of first IR argument corresponding to ArgNo, and their 1425 /// quantity. 1426 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const { 1427 assert(ArgNo < ArgInfo.size()); 1428 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex, 1429 ArgInfo[ArgNo].NumberOfArgs); 1430 } 1431 1432 private: 1433 void construct(const ASTContext &Context, const CGFunctionInfo &FI, 1434 bool OnlyRequiredArgs); 1435 }; 1436 1437 void ClangToLLVMArgMapping::construct(const ASTContext &Context, 1438 const CGFunctionInfo &FI, 1439 bool OnlyRequiredArgs) { 1440 unsigned IRArgNo = 0; 1441 bool SwapThisWithSRet = false; 1442 const ABIArgInfo &RetAI = FI.getReturnInfo(); 1443 1444 if (RetAI.getKind() == ABIArgInfo::Indirect) { 1445 SwapThisWithSRet = RetAI.isSRetAfterThis(); 1446 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++; 1447 } 1448 1449 unsigned ArgNo = 0; 1450 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size(); 1451 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs; 1452 ++I, ++ArgNo) { 1453 assert(I != FI.arg_end()); 1454 QualType ArgType = I->type; 1455 const ABIArgInfo &AI = I->info; 1456 // Collect data about IR arguments corresponding to Clang argument ArgNo. 1457 auto &IRArgs = ArgInfo[ArgNo]; 1458 1459 if (AI.getPaddingType()) 1460 IRArgs.PaddingArgIndex = IRArgNo++; 1461 1462 switch (AI.getKind()) { 1463 case ABIArgInfo::Extend: 1464 case ABIArgInfo::Direct: { 1465 // FIXME: handle sseregparm someday... 1466 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType()); 1467 if (AI.isDirect() && AI.getCanBeFlattened() && STy) { 1468 IRArgs.NumberOfArgs = STy->getNumElements(); 1469 } else { 1470 IRArgs.NumberOfArgs = 1; 1471 } 1472 break; 1473 } 1474 case ABIArgInfo::Indirect: 1475 IRArgs.NumberOfArgs = 1; 1476 break; 1477 case ABIArgInfo::Ignore: 1478 case ABIArgInfo::InAlloca: 1479 // ignore and inalloca doesn't have matching LLVM parameters. 1480 IRArgs.NumberOfArgs = 0; 1481 break; 1482 case ABIArgInfo::CoerceAndExpand: 1483 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size(); 1484 break; 1485 case ABIArgInfo::Expand: 1486 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context); 1487 break; 1488 } 1489 1490 if (IRArgs.NumberOfArgs > 0) { 1491 IRArgs.FirstArgIndex = IRArgNo; 1492 IRArgNo += IRArgs.NumberOfArgs; 1493 } 1494 1495 // Skip over the sret parameter when it comes second. We already handled it 1496 // above. 1497 if (IRArgNo == 1 && SwapThisWithSRet) 1498 IRArgNo++; 1499 } 1500 assert(ArgNo == ArgInfo.size()); 1501 1502 if (FI.usesInAlloca()) 1503 InallocaArgNo = IRArgNo++; 1504 1505 TotalIRArgs = IRArgNo; 1506 } 1507 } // namespace 1508 1509 /***/ 1510 1511 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) { 1512 const auto &RI = FI.getReturnInfo(); 1513 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet()); 1514 } 1515 1516 bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) { 1517 return ReturnTypeUsesSRet(FI) && 1518 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs(); 1519 } 1520 1521 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) { 1522 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) { 1523 switch (BT->getKind()) { 1524 default: 1525 return false; 1526 case BuiltinType::Float: 1527 return getTarget().useObjCFPRetForRealType(TargetInfo::Float); 1528 case BuiltinType::Double: 1529 return getTarget().useObjCFPRetForRealType(TargetInfo::Double); 1530 case BuiltinType::LongDouble: 1531 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble); 1532 } 1533 } 1534 1535 return false; 1536 } 1537 1538 bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) { 1539 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) { 1540 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) { 1541 if (BT->getKind() == BuiltinType::LongDouble) 1542 return getTarget().useObjCFP2RetForComplexLongDouble(); 1543 } 1544 } 1545 1546 return false; 1547 } 1548 1549 llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) { 1550 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD); 1551 return GetFunctionType(FI); 1552 } 1553 1554 llvm::FunctionType * 1555 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) { 1556 1557 bool Inserted = FunctionsBeingProcessed.insert(&FI).second; 1558 (void)Inserted; 1559 assert(Inserted && "Recursively being processed?"); 1560 1561 llvm::Type *resultType = nullptr; 1562 const ABIArgInfo &retAI = FI.getReturnInfo(); 1563 switch (retAI.getKind()) { 1564 case ABIArgInfo::Expand: 1565 llvm_unreachable("Invalid ABI kind for return argument"); 1566 1567 case ABIArgInfo::Extend: 1568 case ABIArgInfo::Direct: 1569 resultType = retAI.getCoerceToType(); 1570 break; 1571 1572 case ABIArgInfo::InAlloca: 1573 if (retAI.getInAllocaSRet()) { 1574 // sret things on win32 aren't void, they return the sret pointer. 1575 QualType ret = FI.getReturnType(); 1576 llvm::Type *ty = ConvertType(ret); 1577 unsigned addressSpace = Context.getTargetAddressSpace(ret); 1578 resultType = llvm::PointerType::get(ty, addressSpace); 1579 } else { 1580 resultType = llvm::Type::getVoidTy(getLLVMContext()); 1581 } 1582 break; 1583 1584 case ABIArgInfo::Indirect: 1585 case ABIArgInfo::Ignore: 1586 resultType = llvm::Type::getVoidTy(getLLVMContext()); 1587 break; 1588 1589 case ABIArgInfo::CoerceAndExpand: 1590 resultType = retAI.getUnpaddedCoerceAndExpandType(); 1591 break; 1592 } 1593 1594 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true); 1595 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs()); 1596 1597 // Add type for sret argument. 1598 if (IRFunctionArgs.hasSRetArg()) { 1599 QualType Ret = FI.getReturnType(); 1600 llvm::Type *Ty = ConvertType(Ret); 1601 unsigned AddressSpace = Context.getTargetAddressSpace(Ret); 1602 ArgTypes[IRFunctionArgs.getSRetArgNo()] = 1603 llvm::PointerType::get(Ty, AddressSpace); 1604 } 1605 1606 // Add type for inalloca argument. 1607 if (IRFunctionArgs.hasInallocaArg()) { 1608 auto ArgStruct = FI.getArgStruct(); 1609 assert(ArgStruct); 1610 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo(); 1611 } 1612 1613 // Add in all of the required arguments. 1614 unsigned ArgNo = 0; 1615 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), 1616 ie = it + FI.getNumRequiredArgs(); 1617 for (; it != ie; ++it, ++ArgNo) { 1618 const ABIArgInfo &ArgInfo = it->info; 1619 1620 // Insert a padding type to ensure proper alignment. 1621 if (IRFunctionArgs.hasPaddingArg(ArgNo)) 1622 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 1623 ArgInfo.getPaddingType(); 1624 1625 unsigned FirstIRArg, NumIRArgs; 1626 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 1627 1628 switch (ArgInfo.getKind()) { 1629 case ABIArgInfo::Ignore: 1630 case ABIArgInfo::InAlloca: 1631 assert(NumIRArgs == 0); 1632 break; 1633 1634 case ABIArgInfo::Indirect: { 1635 assert(NumIRArgs == 1); 1636 // indirect arguments are always on the stack, which is alloca addr space. 1637 llvm::Type *LTy = ConvertTypeForMem(it->type); 1638 ArgTypes[FirstIRArg] = LTy->getPointerTo( 1639 CGM.getDataLayout().getAllocaAddrSpace()); 1640 break; 1641 } 1642 1643 case ABIArgInfo::Extend: 1644 case ABIArgInfo::Direct: { 1645 // Fast-isel and the optimizer generally like scalar values better than 1646 // FCAs, so we flatten them if this is safe to do for this argument. 1647 llvm::Type *argType = ArgInfo.getCoerceToType(); 1648 llvm::StructType *st = dyn_cast<llvm::StructType>(argType); 1649 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) { 1650 assert(NumIRArgs == st->getNumElements()); 1651 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i) 1652 ArgTypes[FirstIRArg + i] = st->getElementType(i); 1653 } else { 1654 assert(NumIRArgs == 1); 1655 ArgTypes[FirstIRArg] = argType; 1656 } 1657 break; 1658 } 1659 1660 case ABIArgInfo::CoerceAndExpand: { 1661 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg; 1662 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) { 1663 *ArgTypesIter++ = EltTy; 1664 } 1665 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs); 1666 break; 1667 } 1668 1669 case ABIArgInfo::Expand: 1670 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg; 1671 getExpandedTypes(it->type, ArgTypesIter); 1672 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs); 1673 break; 1674 } 1675 } 1676 1677 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased; 1678 assert(Erased && "Not in set?"); 1679 1680 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic()); 1681 } 1682 1683 llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) { 1684 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1685 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 1686 1687 if (!isFuncTypeConvertible(FPT)) 1688 return llvm::StructType::get(getLLVMContext()); 1689 1690 return GetFunctionType(GD); 1691 } 1692 1693 static void AddAttributesFromFunctionProtoType(ASTContext &Ctx, 1694 llvm::AttrBuilder &FuncAttrs, 1695 const FunctionProtoType *FPT) { 1696 if (!FPT) 1697 return; 1698 1699 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 1700 FPT->isNothrow()) 1701 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1702 } 1703 1704 void CodeGenModule::ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone, 1705 bool AttrOnCallSite, 1706 llvm::AttrBuilder &FuncAttrs) { 1707 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed. 1708 if (!HasOptnone) { 1709 if (CodeGenOpts.OptimizeSize) 1710 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize); 1711 if (CodeGenOpts.OptimizeSize == 2) 1712 FuncAttrs.addAttribute(llvm::Attribute::MinSize); 1713 } 1714 1715 if (CodeGenOpts.DisableRedZone) 1716 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone); 1717 if (CodeGenOpts.IndirectTlsSegRefs) 1718 FuncAttrs.addAttribute("indirect-tls-seg-refs"); 1719 if (CodeGenOpts.NoImplicitFloat) 1720 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat); 1721 1722 if (AttrOnCallSite) { 1723 // Attributes that should go on the call site only. 1724 if (!CodeGenOpts.SimplifyLibCalls || 1725 CodeGenOpts.isNoBuiltinFunc(Name.data())) 1726 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin); 1727 if (!CodeGenOpts.TrapFuncName.empty()) 1728 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName); 1729 } else { 1730 StringRef FpKind; 1731 switch (CodeGenOpts.getFramePointer()) { 1732 case CodeGenOptions::FramePointerKind::None: 1733 FpKind = "none"; 1734 break; 1735 case CodeGenOptions::FramePointerKind::NonLeaf: 1736 FpKind = "non-leaf"; 1737 break; 1738 case CodeGenOptions::FramePointerKind::All: 1739 FpKind = "all"; 1740 break; 1741 } 1742 FuncAttrs.addAttribute("frame-pointer", FpKind); 1743 1744 FuncAttrs.addAttribute("less-precise-fpmad", 1745 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD)); 1746 1747 if (CodeGenOpts.NullPointerIsValid) 1748 FuncAttrs.addAttribute("null-pointer-is-valid", "true"); 1749 if (CodeGenOpts.FPDenormalMode != llvm::DenormalMode::Invalid) 1750 FuncAttrs.addAttribute("denormal-fp-math", 1751 llvm::denormalModeName(CodeGenOpts.FPDenormalMode)); 1752 1753 FuncAttrs.addAttribute("no-trapping-math", 1754 llvm::toStringRef(CodeGenOpts.NoTrappingMath)); 1755 1756 // Strict (compliant) code is the default, so only add this attribute to 1757 // indicate that we are trying to workaround a problem case. 1758 if (!CodeGenOpts.StrictFloatCastOverflow) 1759 FuncAttrs.addAttribute("strict-float-cast-overflow", "false"); 1760 1761 // TODO: Are these all needed? 1762 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags. 1763 FuncAttrs.addAttribute("no-infs-fp-math", 1764 llvm::toStringRef(CodeGenOpts.NoInfsFPMath)); 1765 FuncAttrs.addAttribute("no-nans-fp-math", 1766 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath)); 1767 FuncAttrs.addAttribute("unsafe-fp-math", 1768 llvm::toStringRef(CodeGenOpts.UnsafeFPMath)); 1769 FuncAttrs.addAttribute("use-soft-float", 1770 llvm::toStringRef(CodeGenOpts.SoftFloat)); 1771 FuncAttrs.addAttribute("stack-protector-buffer-size", 1772 llvm::utostr(CodeGenOpts.SSPBufferSize)); 1773 FuncAttrs.addAttribute("no-signed-zeros-fp-math", 1774 llvm::toStringRef(CodeGenOpts.NoSignedZeros)); 1775 FuncAttrs.addAttribute( 1776 "correctly-rounded-divide-sqrt-fp-math", 1777 llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt)); 1778 1779 if (getLangOpts().OpenCL) 1780 FuncAttrs.addAttribute("denorms-are-zero", 1781 llvm::toStringRef(CodeGenOpts.FlushDenorm)); 1782 1783 // TODO: Reciprocal estimate codegen options should apply to instructions? 1784 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals; 1785 if (!Recips.empty()) 1786 FuncAttrs.addAttribute("reciprocal-estimates", 1787 llvm::join(Recips, ",")); 1788 1789 if (!CodeGenOpts.PreferVectorWidth.empty() && 1790 CodeGenOpts.PreferVectorWidth != "none") 1791 FuncAttrs.addAttribute("prefer-vector-width", 1792 CodeGenOpts.PreferVectorWidth); 1793 1794 if (CodeGenOpts.StackRealignment) 1795 FuncAttrs.addAttribute("stackrealign"); 1796 if (CodeGenOpts.Backchain) 1797 FuncAttrs.addAttribute("backchain"); 1798 1799 if (CodeGenOpts.SpeculativeLoadHardening) 1800 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening); 1801 } 1802 1803 if (getLangOpts().assumeFunctionsAreConvergent()) { 1804 // Conservatively, mark all functions and calls in CUDA and OpenCL as 1805 // convergent (meaning, they may call an intrinsically convergent op, such 1806 // as __syncthreads() / barrier(), and so can't have certain optimizations 1807 // applied around them). LLVM will remove this attribute where it safely 1808 // can. 1809 FuncAttrs.addAttribute(llvm::Attribute::Convergent); 1810 } 1811 1812 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 1813 // Exceptions aren't supported in CUDA device code. 1814 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1815 1816 // Respect -fcuda-flush-denormals-to-zero. 1817 if (CodeGenOpts.FlushDenorm) 1818 FuncAttrs.addAttribute("nvptx-f32ftz", "true"); 1819 } 1820 1821 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) { 1822 StringRef Var, Value; 1823 std::tie(Var, Value) = Attr.split('='); 1824 FuncAttrs.addAttribute(Var, Value); 1825 } 1826 } 1827 1828 void CodeGenModule::AddDefaultFnAttrs(llvm::Function &F) { 1829 llvm::AttrBuilder FuncAttrs; 1830 ConstructDefaultFnAttrList(F.getName(), F.hasOptNone(), 1831 /* AttrOnCallSite = */ false, FuncAttrs); 1832 F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs); 1833 } 1834 1835 void CodeGenModule::ConstructAttributeList( 1836 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo, 1837 llvm::AttributeList &AttrList, unsigned &CallingConv, bool AttrOnCallSite) { 1838 llvm::AttrBuilder FuncAttrs; 1839 llvm::AttrBuilder RetAttrs; 1840 1841 CallingConv = FI.getEffectiveCallingConvention(); 1842 if (FI.isNoReturn()) 1843 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1844 1845 // If we have information about the function prototype, we can learn 1846 // attributes from there. 1847 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs, 1848 CalleeInfo.getCalleeFunctionProtoType()); 1849 1850 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl(); 1851 1852 bool HasOptnone = false; 1853 // FIXME: handle sseregparm someday... 1854 if (TargetDecl) { 1855 if (TargetDecl->hasAttr<ReturnsTwiceAttr>()) 1856 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice); 1857 if (TargetDecl->hasAttr<NoThrowAttr>()) 1858 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1859 if (TargetDecl->hasAttr<NoReturnAttr>()) 1860 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1861 if (TargetDecl->hasAttr<ColdAttr>()) 1862 FuncAttrs.addAttribute(llvm::Attribute::Cold); 1863 if (TargetDecl->hasAttr<NoDuplicateAttr>()) 1864 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate); 1865 if (TargetDecl->hasAttr<ConvergentAttr>()) 1866 FuncAttrs.addAttribute(llvm::Attribute::Convergent); 1867 1868 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) { 1869 AddAttributesFromFunctionProtoType( 1870 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>()); 1871 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn); 1872 const bool IsVirtualCall = MD && MD->isVirtual(); 1873 // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a 1874 // virtual function. These attributes are not inherited by overloads. 1875 if (!(AttrOnCallSite && IsVirtualCall)) { 1876 if (Fn->isNoReturn()) 1877 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1878 1879 if (const auto *NBA = TargetDecl->getAttr<NoBuiltinAttr>()) { 1880 bool HasWildcard = llvm::is_contained(NBA->builtinNames(), "*"); 1881 if (HasWildcard) 1882 FuncAttrs.addAttribute("no-builtins"); 1883 else 1884 for (StringRef BuiltinName : NBA->builtinNames()) { 1885 SmallString<32> AttributeName; 1886 AttributeName += "no-builtin-"; 1887 AttributeName += BuiltinName; 1888 FuncAttrs.addAttribute(AttributeName); 1889 } 1890 } 1891 } 1892 } 1893 1894 // 'const', 'pure' and 'noalias' attributed functions are also nounwind. 1895 if (TargetDecl->hasAttr<ConstAttr>()) { 1896 FuncAttrs.addAttribute(llvm::Attribute::ReadNone); 1897 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1898 } else if (TargetDecl->hasAttr<PureAttr>()) { 1899 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly); 1900 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1901 } else if (TargetDecl->hasAttr<NoAliasAttr>()) { 1902 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly); 1903 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1904 } 1905 if (TargetDecl->hasAttr<RestrictAttr>()) 1906 RetAttrs.addAttribute(llvm::Attribute::NoAlias); 1907 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() && 1908 !CodeGenOpts.NullPointerIsValid) 1909 RetAttrs.addAttribute(llvm::Attribute::NonNull); 1910 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) 1911 FuncAttrs.addAttribute("no_caller_saved_registers"); 1912 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>()) 1913 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck); 1914 1915 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>(); 1916 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) { 1917 Optional<unsigned> NumElemsParam; 1918 if (AllocSize->getNumElemsParam().isValid()) 1919 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex(); 1920 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(), 1921 NumElemsParam); 1922 } 1923 } 1924 1925 ConstructDefaultFnAttrList(Name, HasOptnone, AttrOnCallSite, FuncAttrs); 1926 1927 // This must run after constructing the default function attribute list 1928 // to ensure that the speculative load hardening attribute is removed 1929 // in the case where the -mspeculative-load-hardening flag was passed. 1930 if (TargetDecl) { 1931 if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>()) 1932 FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening); 1933 if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>()) 1934 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening); 1935 } 1936 1937 if (CodeGenOpts.EnableSegmentedStacks && 1938 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>())) 1939 FuncAttrs.addAttribute("split-stack"); 1940 1941 // Add NonLazyBind attribute to function declarations when -fno-plt 1942 // is used. 1943 if (TargetDecl && CodeGenOpts.NoPLT) { 1944 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) { 1945 if (!Fn->isDefined() && !AttrOnCallSite) { 1946 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind); 1947 } 1948 } 1949 } 1950 1951 if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>()) { 1952 if (getLangOpts().OpenCLVersion <= 120) { 1953 // OpenCL v1.2 Work groups are always uniform 1954 FuncAttrs.addAttribute("uniform-work-group-size", "true"); 1955 } else { 1956 // OpenCL v2.0 Work groups may be whether uniform or not. 1957 // '-cl-uniform-work-group-size' compile option gets a hint 1958 // to the compiler that the global work-size be a multiple of 1959 // the work-group size specified to clEnqueueNDRangeKernel 1960 // (i.e. work groups are uniform). 1961 FuncAttrs.addAttribute("uniform-work-group-size", 1962 llvm::toStringRef(CodeGenOpts.UniformWGSize)); 1963 } 1964 } 1965 1966 if (!AttrOnCallSite) { 1967 bool DisableTailCalls = false; 1968 1969 if (CodeGenOpts.DisableTailCalls) 1970 DisableTailCalls = true; 1971 else if (TargetDecl) { 1972 if (TargetDecl->hasAttr<DisableTailCallsAttr>() || 1973 TargetDecl->hasAttr<AnyX86InterruptAttr>()) 1974 DisableTailCalls = true; 1975 else if (CodeGenOpts.NoEscapingBlockTailCalls) { 1976 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl)) 1977 if (!BD->doesNotEscape()) 1978 DisableTailCalls = true; 1979 } 1980 } 1981 1982 FuncAttrs.addAttribute("disable-tail-calls", 1983 llvm::toStringRef(DisableTailCalls)); 1984 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs); 1985 } 1986 1987 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI); 1988 1989 QualType RetTy = FI.getReturnType(); 1990 const ABIArgInfo &RetAI = FI.getReturnInfo(); 1991 switch (RetAI.getKind()) { 1992 case ABIArgInfo::Extend: 1993 if (RetAI.isSignExt()) 1994 RetAttrs.addAttribute(llvm::Attribute::SExt); 1995 else 1996 RetAttrs.addAttribute(llvm::Attribute::ZExt); 1997 LLVM_FALLTHROUGH; 1998 case ABIArgInfo::Direct: 1999 if (RetAI.getInReg()) 2000 RetAttrs.addAttribute(llvm::Attribute::InReg); 2001 break; 2002 case ABIArgInfo::Ignore: 2003 break; 2004 2005 case ABIArgInfo::InAlloca: 2006 case ABIArgInfo::Indirect: { 2007 // inalloca and sret disable readnone and readonly 2008 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 2009 .removeAttribute(llvm::Attribute::ReadNone); 2010 break; 2011 } 2012 2013 case ABIArgInfo::CoerceAndExpand: 2014 break; 2015 2016 case ABIArgInfo::Expand: 2017 llvm_unreachable("Invalid ABI kind for return argument"); 2018 } 2019 2020 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) { 2021 QualType PTy = RefTy->getPointeeType(); 2022 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) 2023 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy) 2024 .getQuantity()); 2025 else if (getContext().getTargetAddressSpace(PTy) == 0 && 2026 !CodeGenOpts.NullPointerIsValid) 2027 RetAttrs.addAttribute(llvm::Attribute::NonNull); 2028 } 2029 2030 bool hasUsedSRet = false; 2031 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs()); 2032 2033 // Attach attributes to sret. 2034 if (IRFunctionArgs.hasSRetArg()) { 2035 llvm::AttrBuilder SRETAttrs; 2036 SRETAttrs.addAttribute(llvm::Attribute::StructRet); 2037 hasUsedSRet = true; 2038 if (RetAI.getInReg()) 2039 SRETAttrs.addAttribute(llvm::Attribute::InReg); 2040 ArgAttrs[IRFunctionArgs.getSRetArgNo()] = 2041 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs); 2042 } 2043 2044 // Attach attributes to inalloca argument. 2045 if (IRFunctionArgs.hasInallocaArg()) { 2046 llvm::AttrBuilder Attrs; 2047 Attrs.addAttribute(llvm::Attribute::InAlloca); 2048 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] = 2049 llvm::AttributeSet::get(getLLVMContext(), Attrs); 2050 } 2051 2052 unsigned ArgNo = 0; 2053 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(), 2054 E = FI.arg_end(); 2055 I != E; ++I, ++ArgNo) { 2056 QualType ParamType = I->type; 2057 const ABIArgInfo &AI = I->info; 2058 llvm::AttrBuilder Attrs; 2059 2060 // Add attribute for padding argument, if necessary. 2061 if (IRFunctionArgs.hasPaddingArg(ArgNo)) { 2062 if (AI.getPaddingInReg()) { 2063 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 2064 llvm::AttributeSet::get( 2065 getLLVMContext(), 2066 llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg)); 2067 } 2068 } 2069 2070 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we 2071 // have the corresponding parameter variable. It doesn't make 2072 // sense to do it here because parameters are so messed up. 2073 switch (AI.getKind()) { 2074 case ABIArgInfo::Extend: 2075 if (AI.isSignExt()) 2076 Attrs.addAttribute(llvm::Attribute::SExt); 2077 else 2078 Attrs.addAttribute(llvm::Attribute::ZExt); 2079 LLVM_FALLTHROUGH; 2080 case ABIArgInfo::Direct: 2081 if (ArgNo == 0 && FI.isChainCall()) 2082 Attrs.addAttribute(llvm::Attribute::Nest); 2083 else if (AI.getInReg()) 2084 Attrs.addAttribute(llvm::Attribute::InReg); 2085 break; 2086 2087 case ABIArgInfo::Indirect: { 2088 if (AI.getInReg()) 2089 Attrs.addAttribute(llvm::Attribute::InReg); 2090 2091 if (AI.getIndirectByVal()) 2092 Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType)); 2093 2094 CharUnits Align = AI.getIndirectAlign(); 2095 2096 // In a byval argument, it is important that the required 2097 // alignment of the type is honored, as LLVM might be creating a 2098 // *new* stack object, and needs to know what alignment to give 2099 // it. (Sometimes it can deduce a sensible alignment on its own, 2100 // but not if clang decides it must emit a packed struct, or the 2101 // user specifies increased alignment requirements.) 2102 // 2103 // This is different from indirect *not* byval, where the object 2104 // exists already, and the align attribute is purely 2105 // informative. 2106 assert(!Align.isZero()); 2107 2108 // For now, only add this when we have a byval argument. 2109 // TODO: be less lazy about updating test cases. 2110 if (AI.getIndirectByVal()) 2111 Attrs.addAlignmentAttr(Align.getQuantity()); 2112 2113 // byval disables readnone and readonly. 2114 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 2115 .removeAttribute(llvm::Attribute::ReadNone); 2116 break; 2117 } 2118 case ABIArgInfo::Ignore: 2119 case ABIArgInfo::Expand: 2120 case ABIArgInfo::CoerceAndExpand: 2121 break; 2122 2123 case ABIArgInfo::InAlloca: 2124 // inalloca disables readnone and readonly. 2125 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 2126 .removeAttribute(llvm::Attribute::ReadNone); 2127 continue; 2128 } 2129 2130 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) { 2131 QualType PTy = RefTy->getPointeeType(); 2132 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) 2133 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy) 2134 .getQuantity()); 2135 else if (getContext().getTargetAddressSpace(PTy) == 0 && 2136 !CodeGenOpts.NullPointerIsValid) 2137 Attrs.addAttribute(llvm::Attribute::NonNull); 2138 } 2139 2140 switch (FI.getExtParameterInfo(ArgNo).getABI()) { 2141 case ParameterABI::Ordinary: 2142 break; 2143 2144 case ParameterABI::SwiftIndirectResult: { 2145 // Add 'sret' if we haven't already used it for something, but 2146 // only if the result is void. 2147 if (!hasUsedSRet && RetTy->isVoidType()) { 2148 Attrs.addAttribute(llvm::Attribute::StructRet); 2149 hasUsedSRet = true; 2150 } 2151 2152 // Add 'noalias' in either case. 2153 Attrs.addAttribute(llvm::Attribute::NoAlias); 2154 2155 // Add 'dereferenceable' and 'alignment'. 2156 auto PTy = ParamType->getPointeeType(); 2157 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) { 2158 auto info = getContext().getTypeInfoInChars(PTy); 2159 Attrs.addDereferenceableAttr(info.first.getQuantity()); 2160 Attrs.addAttribute(llvm::Attribute::getWithAlignment( 2161 getLLVMContext(), info.second.getAsAlign())); 2162 } 2163 break; 2164 } 2165 2166 case ParameterABI::SwiftErrorResult: 2167 Attrs.addAttribute(llvm::Attribute::SwiftError); 2168 break; 2169 2170 case ParameterABI::SwiftContext: 2171 Attrs.addAttribute(llvm::Attribute::SwiftSelf); 2172 break; 2173 } 2174 2175 if (FI.getExtParameterInfo(ArgNo).isNoEscape()) 2176 Attrs.addAttribute(llvm::Attribute::NoCapture); 2177 2178 if (Attrs.hasAttributes()) { 2179 unsigned FirstIRArg, NumIRArgs; 2180 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 2181 for (unsigned i = 0; i < NumIRArgs; i++) 2182 ArgAttrs[FirstIRArg + i] = 2183 llvm::AttributeSet::get(getLLVMContext(), Attrs); 2184 } 2185 } 2186 assert(ArgNo == FI.arg_size()); 2187 2188 AttrList = llvm::AttributeList::get( 2189 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs), 2190 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs); 2191 } 2192 2193 /// An argument came in as a promoted argument; demote it back to its 2194 /// declared type. 2195 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF, 2196 const VarDecl *var, 2197 llvm::Value *value) { 2198 llvm::Type *varType = CGF.ConvertType(var->getType()); 2199 2200 // This can happen with promotions that actually don't change the 2201 // underlying type, like the enum promotions. 2202 if (value->getType() == varType) return value; 2203 2204 assert((varType->isIntegerTy() || varType->isFloatingPointTy()) 2205 && "unexpected promotion type"); 2206 2207 if (isa<llvm::IntegerType>(varType)) 2208 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote"); 2209 2210 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote"); 2211 } 2212 2213 /// Returns the attribute (either parameter attribute, or function 2214 /// attribute), which declares argument ArgNo to be non-null. 2215 static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD, 2216 QualType ArgType, unsigned ArgNo) { 2217 // FIXME: __attribute__((nonnull)) can also be applied to: 2218 // - references to pointers, where the pointee is known to be 2219 // nonnull (apparently a Clang extension) 2220 // - transparent unions containing pointers 2221 // In the former case, LLVM IR cannot represent the constraint. In 2222 // the latter case, we have no guarantee that the transparent union 2223 // is in fact passed as a pointer. 2224 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType()) 2225 return nullptr; 2226 // First, check attribute on parameter itself. 2227 if (PVD) { 2228 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>()) 2229 return ParmNNAttr; 2230 } 2231 // Check function attributes. 2232 if (!FD) 2233 return nullptr; 2234 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) { 2235 if (NNAttr->isNonNull(ArgNo)) 2236 return NNAttr; 2237 } 2238 return nullptr; 2239 } 2240 2241 namespace { 2242 struct CopyBackSwiftError final : EHScopeStack::Cleanup { 2243 Address Temp; 2244 Address Arg; 2245 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {} 2246 void Emit(CodeGenFunction &CGF, Flags flags) override { 2247 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp); 2248 CGF.Builder.CreateStore(errorValue, Arg); 2249 } 2250 }; 2251 } 2252 2253 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, 2254 llvm::Function *Fn, 2255 const FunctionArgList &Args) { 2256 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) 2257 // Naked functions don't have prologues. 2258 return; 2259 2260 // If this is an implicit-return-zero function, go ahead and 2261 // initialize the return value. TODO: it might be nice to have 2262 // a more general mechanism for this that didn't require synthesized 2263 // return statements. 2264 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) { 2265 if (FD->hasImplicitReturnZero()) { 2266 QualType RetTy = FD->getReturnType().getUnqualifiedType(); 2267 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy); 2268 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy); 2269 Builder.CreateStore(Zero, ReturnValue); 2270 } 2271 } 2272 2273 // FIXME: We no longer need the types from FunctionArgList; lift up and 2274 // simplify. 2275 2276 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI); 2277 // Flattened function arguments. 2278 SmallVector<llvm::Value *, 16> FnArgs; 2279 FnArgs.reserve(IRFunctionArgs.totalIRArgs()); 2280 for (auto &Arg : Fn->args()) { 2281 FnArgs.push_back(&Arg); 2282 } 2283 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs()); 2284 2285 // If we're using inalloca, all the memory arguments are GEPs off of the last 2286 // parameter, which is a pointer to the complete memory area. 2287 Address ArgStruct = Address::invalid(); 2288 if (IRFunctionArgs.hasInallocaArg()) { 2289 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()], 2290 FI.getArgStructAlignment()); 2291 2292 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo()); 2293 } 2294 2295 // Name the struct return parameter. 2296 if (IRFunctionArgs.hasSRetArg()) { 2297 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]); 2298 AI->setName("agg.result"); 2299 AI->addAttr(llvm::Attribute::NoAlias); 2300 } 2301 2302 // Track if we received the parameter as a pointer (indirect, byval, or 2303 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it 2304 // into a local alloca for us. 2305 SmallVector<ParamValue, 16> ArgVals; 2306 ArgVals.reserve(Args.size()); 2307 2308 // Create a pointer value for every parameter declaration. This usually 2309 // entails copying one or more LLVM IR arguments into an alloca. Don't push 2310 // any cleanups or do anything that might unwind. We do that separately, so 2311 // we can push the cleanups in the correct order for the ABI. 2312 assert(FI.arg_size() == Args.size() && 2313 "Mismatch between function signature & arguments."); 2314 unsigned ArgNo = 0; 2315 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin(); 2316 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 2317 i != e; ++i, ++info_it, ++ArgNo) { 2318 const VarDecl *Arg = *i; 2319 const ABIArgInfo &ArgI = info_it->info; 2320 2321 bool isPromoted = 2322 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted(); 2323 // We are converting from ABIArgInfo type to VarDecl type directly, unless 2324 // the parameter is promoted. In this case we convert to 2325 // CGFunctionInfo::ArgInfo type with subsequent argument demotion. 2326 QualType Ty = isPromoted ? info_it->type : Arg->getType(); 2327 assert(hasScalarEvaluationKind(Ty) == 2328 hasScalarEvaluationKind(Arg->getType())); 2329 2330 unsigned FirstIRArg, NumIRArgs; 2331 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 2332 2333 switch (ArgI.getKind()) { 2334 case ABIArgInfo::InAlloca: { 2335 assert(NumIRArgs == 0); 2336 auto FieldIndex = ArgI.getInAllocaFieldIndex(); 2337 Address V = 2338 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName()); 2339 ArgVals.push_back(ParamValue::forIndirect(V)); 2340 break; 2341 } 2342 2343 case ABIArgInfo::Indirect: { 2344 assert(NumIRArgs == 1); 2345 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign()); 2346 2347 if (!hasScalarEvaluationKind(Ty)) { 2348 // Aggregates and complex variables are accessed by reference. All we 2349 // need to do is realign the value, if requested. 2350 Address V = ParamAddr; 2351 if (ArgI.getIndirectRealign()) { 2352 Address AlignedTemp = CreateMemTemp(Ty, "coerce"); 2353 2354 // Copy from the incoming argument pointer to the temporary with the 2355 // appropriate alignment. 2356 // 2357 // FIXME: We should have a common utility for generating an aggregate 2358 // copy. 2359 CharUnits Size = getContext().getTypeSizeInChars(Ty); 2360 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()); 2361 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy); 2362 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy); 2363 Builder.CreateMemCpy(Dst, Src, SizeVal, false); 2364 V = AlignedTemp; 2365 } 2366 ArgVals.push_back(ParamValue::forIndirect(V)); 2367 } else { 2368 // Load scalar value from indirect argument. 2369 llvm::Value *V = 2370 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc()); 2371 2372 if (isPromoted) 2373 V = emitArgumentDemotion(*this, Arg, V); 2374 ArgVals.push_back(ParamValue::forDirect(V)); 2375 } 2376 break; 2377 } 2378 2379 case ABIArgInfo::Extend: 2380 case ABIArgInfo::Direct: { 2381 2382 // If we have the trivial case, handle it with no muss and fuss. 2383 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) && 2384 ArgI.getCoerceToType() == ConvertType(Ty) && 2385 ArgI.getDirectOffset() == 0) { 2386 assert(NumIRArgs == 1); 2387 llvm::Value *V = FnArgs[FirstIRArg]; 2388 auto AI = cast<llvm::Argument>(V); 2389 2390 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) { 2391 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(), 2392 PVD->getFunctionScopeIndex()) && 2393 !CGM.getCodeGenOpts().NullPointerIsValid) 2394 AI->addAttr(llvm::Attribute::NonNull); 2395 2396 QualType OTy = PVD->getOriginalType(); 2397 if (const auto *ArrTy = 2398 getContext().getAsConstantArrayType(OTy)) { 2399 // A C99 array parameter declaration with the static keyword also 2400 // indicates dereferenceability, and if the size is constant we can 2401 // use the dereferenceable attribute (which requires the size in 2402 // bytes). 2403 if (ArrTy->getSizeModifier() == ArrayType::Static) { 2404 QualType ETy = ArrTy->getElementType(); 2405 uint64_t ArrSize = ArrTy->getSize().getZExtValue(); 2406 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() && 2407 ArrSize) { 2408 llvm::AttrBuilder Attrs; 2409 Attrs.addDereferenceableAttr( 2410 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize); 2411 AI->addAttrs(Attrs); 2412 } else if (getContext().getTargetAddressSpace(ETy) == 0 && 2413 !CGM.getCodeGenOpts().NullPointerIsValid) { 2414 AI->addAttr(llvm::Attribute::NonNull); 2415 } 2416 } 2417 } else if (const auto *ArrTy = 2418 getContext().getAsVariableArrayType(OTy)) { 2419 // For C99 VLAs with the static keyword, we don't know the size so 2420 // we can't use the dereferenceable attribute, but in addrspace(0) 2421 // we know that it must be nonnull. 2422 if (ArrTy->getSizeModifier() == VariableArrayType::Static && 2423 !getContext().getTargetAddressSpace(ArrTy->getElementType()) && 2424 !CGM.getCodeGenOpts().NullPointerIsValid) 2425 AI->addAttr(llvm::Attribute::NonNull); 2426 } 2427 2428 const auto *AVAttr = PVD->getAttr<AlignValueAttr>(); 2429 if (!AVAttr) 2430 if (const auto *TOTy = dyn_cast<TypedefType>(OTy)) 2431 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>(); 2432 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) { 2433 // If alignment-assumption sanitizer is enabled, we do *not* add 2434 // alignment attribute here, but emit normal alignment assumption, 2435 // so the UBSAN check could function. 2436 llvm::Value *AlignmentValue = 2437 EmitScalarExpr(AVAttr->getAlignment()); 2438 llvm::ConstantInt *AlignmentCI = 2439 cast<llvm::ConstantInt>(AlignmentValue); 2440 unsigned Alignment = std::min((unsigned)AlignmentCI->getZExtValue(), 2441 +llvm::Value::MaximumAlignment); 2442 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment)); 2443 } 2444 } 2445 2446 if (Arg->getType().isRestrictQualified()) 2447 AI->addAttr(llvm::Attribute::NoAlias); 2448 2449 // LLVM expects swifterror parameters to be used in very restricted 2450 // ways. Copy the value into a less-restricted temporary. 2451 if (FI.getExtParameterInfo(ArgNo).getABI() 2452 == ParameterABI::SwiftErrorResult) { 2453 QualType pointeeTy = Ty->getPointeeType(); 2454 assert(pointeeTy->isPointerType()); 2455 Address temp = 2456 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp"); 2457 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy)); 2458 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg); 2459 Builder.CreateStore(incomingErrorValue, temp); 2460 V = temp.getPointer(); 2461 2462 // Push a cleanup to copy the value back at the end of the function. 2463 // The convention does not guarantee that the value will be written 2464 // back if the function exits with an unwind exception. 2465 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg); 2466 } 2467 2468 // Ensure the argument is the correct type. 2469 if (V->getType() != ArgI.getCoerceToType()) 2470 V = Builder.CreateBitCast(V, ArgI.getCoerceToType()); 2471 2472 if (isPromoted) 2473 V = emitArgumentDemotion(*this, Arg, V); 2474 2475 // Because of merging of function types from multiple decls it is 2476 // possible for the type of an argument to not match the corresponding 2477 // type in the function type. Since we are codegening the callee 2478 // in here, add a cast to the argument type. 2479 llvm::Type *LTy = ConvertType(Arg->getType()); 2480 if (V->getType() != LTy) 2481 V = Builder.CreateBitCast(V, LTy); 2482 2483 ArgVals.push_back(ParamValue::forDirect(V)); 2484 break; 2485 } 2486 2487 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg), 2488 Arg->getName()); 2489 2490 // Pointer to store into. 2491 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI); 2492 2493 // Fast-isel and the optimizer generally like scalar values better than 2494 // FCAs, so we flatten them if this is safe to do for this argument. 2495 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType()); 2496 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy && 2497 STy->getNumElements() > 1) { 2498 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy); 2499 llvm::Type *DstTy = Ptr.getElementType(); 2500 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy); 2501 2502 Address AddrToStoreInto = Address::invalid(); 2503 if (SrcSize <= DstSize) { 2504 AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy); 2505 } else { 2506 AddrToStoreInto = 2507 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce"); 2508 } 2509 2510 assert(STy->getNumElements() == NumIRArgs); 2511 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 2512 auto AI = FnArgs[FirstIRArg + i]; 2513 AI->setName(Arg->getName() + ".coerce" + Twine(i)); 2514 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i); 2515 Builder.CreateStore(AI, EltPtr); 2516 } 2517 2518 if (SrcSize > DstSize) { 2519 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize); 2520 } 2521 2522 } else { 2523 // Simple case, just do a coerced store of the argument into the alloca. 2524 assert(NumIRArgs == 1); 2525 auto AI = FnArgs[FirstIRArg]; 2526 AI->setName(Arg->getName() + ".coerce"); 2527 CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this); 2528 } 2529 2530 // Match to what EmitParmDecl is expecting for this type. 2531 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) { 2532 llvm::Value *V = 2533 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc()); 2534 if (isPromoted) 2535 V = emitArgumentDemotion(*this, Arg, V); 2536 ArgVals.push_back(ParamValue::forDirect(V)); 2537 } else { 2538 ArgVals.push_back(ParamValue::forIndirect(Alloca)); 2539 } 2540 break; 2541 } 2542 2543 case ABIArgInfo::CoerceAndExpand: { 2544 // Reconstruct into a temporary. 2545 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg)); 2546 ArgVals.push_back(ParamValue::forIndirect(alloca)); 2547 2548 auto coercionType = ArgI.getCoerceAndExpandType(); 2549 alloca = Builder.CreateElementBitCast(alloca, coercionType); 2550 2551 unsigned argIndex = FirstIRArg; 2552 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 2553 llvm::Type *eltType = coercionType->getElementType(i); 2554 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) 2555 continue; 2556 2557 auto eltAddr = Builder.CreateStructGEP(alloca, i); 2558 auto elt = FnArgs[argIndex++]; 2559 Builder.CreateStore(elt, eltAddr); 2560 } 2561 assert(argIndex == FirstIRArg + NumIRArgs); 2562 break; 2563 } 2564 2565 case ABIArgInfo::Expand: { 2566 // If this structure was expanded into multiple arguments then 2567 // we need to create a temporary and reconstruct it from the 2568 // arguments. 2569 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg)); 2570 LValue LV = MakeAddrLValue(Alloca, Ty); 2571 ArgVals.push_back(ParamValue::forIndirect(Alloca)); 2572 2573 auto FnArgIter = FnArgs.begin() + FirstIRArg; 2574 ExpandTypeFromArgs(Ty, LV, FnArgIter); 2575 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs); 2576 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) { 2577 auto AI = FnArgs[FirstIRArg + i]; 2578 AI->setName(Arg->getName() + "." + Twine(i)); 2579 } 2580 break; 2581 } 2582 2583 case ABIArgInfo::Ignore: 2584 assert(NumIRArgs == 0); 2585 // Initialize the local variable appropriately. 2586 if (!hasScalarEvaluationKind(Ty)) { 2587 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty))); 2588 } else { 2589 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType())); 2590 ArgVals.push_back(ParamValue::forDirect(U)); 2591 } 2592 break; 2593 } 2594 } 2595 2596 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 2597 for (int I = Args.size() - 1; I >= 0; --I) 2598 EmitParmDecl(*Args[I], ArgVals[I], I + 1); 2599 } else { 2600 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2601 EmitParmDecl(*Args[I], ArgVals[I], I + 1); 2602 } 2603 } 2604 2605 static void eraseUnusedBitCasts(llvm::Instruction *insn) { 2606 while (insn->use_empty()) { 2607 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn); 2608 if (!bitcast) return; 2609 2610 // This is "safe" because we would have used a ConstantExpr otherwise. 2611 insn = cast<llvm::Instruction>(bitcast->getOperand(0)); 2612 bitcast->eraseFromParent(); 2613 } 2614 } 2615 2616 /// Try to emit a fused autorelease of a return result. 2617 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF, 2618 llvm::Value *result) { 2619 // We must be immediately followed the cast. 2620 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock(); 2621 if (BB->empty()) return nullptr; 2622 if (&BB->back() != result) return nullptr; 2623 2624 llvm::Type *resultType = result->getType(); 2625 2626 // result is in a BasicBlock and is therefore an Instruction. 2627 llvm::Instruction *generator = cast<llvm::Instruction>(result); 2628 2629 SmallVector<llvm::Instruction *, 4> InstsToKill; 2630 2631 // Look for: 2632 // %generator = bitcast %type1* %generator2 to %type2* 2633 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) { 2634 // We would have emitted this as a constant if the operand weren't 2635 // an Instruction. 2636 generator = cast<llvm::Instruction>(bitcast->getOperand(0)); 2637 2638 // Require the generator to be immediately followed by the cast. 2639 if (generator->getNextNode() != bitcast) 2640 return nullptr; 2641 2642 InstsToKill.push_back(bitcast); 2643 } 2644 2645 // Look for: 2646 // %generator = call i8* @objc_retain(i8* %originalResult) 2647 // or 2648 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult) 2649 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator); 2650 if (!call) return nullptr; 2651 2652 bool doRetainAutorelease; 2653 2654 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) { 2655 doRetainAutorelease = true; 2656 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints() 2657 .objc_retainAutoreleasedReturnValue) { 2658 doRetainAutorelease = false; 2659 2660 // If we emitted an assembly marker for this call (and the 2661 // ARCEntrypoints field should have been set if so), go looking 2662 // for that call. If we can't find it, we can't do this 2663 // optimization. But it should always be the immediately previous 2664 // instruction, unless we needed bitcasts around the call. 2665 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) { 2666 llvm::Instruction *prev = call->getPrevNode(); 2667 assert(prev); 2668 if (isa<llvm::BitCastInst>(prev)) { 2669 prev = prev->getPrevNode(); 2670 assert(prev); 2671 } 2672 assert(isa<llvm::CallInst>(prev)); 2673 assert(cast<llvm::CallInst>(prev)->getCalledValue() == 2674 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker); 2675 InstsToKill.push_back(prev); 2676 } 2677 } else { 2678 return nullptr; 2679 } 2680 2681 result = call->getArgOperand(0); 2682 InstsToKill.push_back(call); 2683 2684 // Keep killing bitcasts, for sanity. Note that we no longer care 2685 // about precise ordering as long as there's exactly one use. 2686 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) { 2687 if (!bitcast->hasOneUse()) break; 2688 InstsToKill.push_back(bitcast); 2689 result = bitcast->getOperand(0); 2690 } 2691 2692 // Delete all the unnecessary instructions, from latest to earliest. 2693 for (auto *I : InstsToKill) 2694 I->eraseFromParent(); 2695 2696 // Do the fused retain/autorelease if we were asked to. 2697 if (doRetainAutorelease) 2698 result = CGF.EmitARCRetainAutoreleaseReturnValue(result); 2699 2700 // Cast back to the result type. 2701 return CGF.Builder.CreateBitCast(result, resultType); 2702 } 2703 2704 /// If this is a +1 of the value of an immutable 'self', remove it. 2705 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF, 2706 llvm::Value *result) { 2707 // This is only applicable to a method with an immutable 'self'. 2708 const ObjCMethodDecl *method = 2709 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl); 2710 if (!method) return nullptr; 2711 const VarDecl *self = method->getSelfDecl(); 2712 if (!self->getType().isConstQualified()) return nullptr; 2713 2714 // Look for a retain call. 2715 llvm::CallInst *retainCall = 2716 dyn_cast<llvm::CallInst>(result->stripPointerCasts()); 2717 if (!retainCall || 2718 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain) 2719 return nullptr; 2720 2721 // Look for an ordinary load of 'self'. 2722 llvm::Value *retainedValue = retainCall->getArgOperand(0); 2723 llvm::LoadInst *load = 2724 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts()); 2725 if (!load || load->isAtomic() || load->isVolatile() || 2726 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer()) 2727 return nullptr; 2728 2729 // Okay! Burn it all down. This relies for correctness on the 2730 // assumption that the retain is emitted as part of the return and 2731 // that thereafter everything is used "linearly". 2732 llvm::Type *resultType = result->getType(); 2733 eraseUnusedBitCasts(cast<llvm::Instruction>(result)); 2734 assert(retainCall->use_empty()); 2735 retainCall->eraseFromParent(); 2736 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue)); 2737 2738 return CGF.Builder.CreateBitCast(load, resultType); 2739 } 2740 2741 /// Emit an ARC autorelease of the result of a function. 2742 /// 2743 /// \return the value to actually return from the function 2744 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF, 2745 llvm::Value *result) { 2746 // If we're returning 'self', kill the initial retain. This is a 2747 // heuristic attempt to "encourage correctness" in the really unfortunate 2748 // case where we have a return of self during a dealloc and we desperately 2749 // need to avoid the possible autorelease. 2750 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result)) 2751 return self; 2752 2753 // At -O0, try to emit a fused retain/autorelease. 2754 if (CGF.shouldUseFusedARCCalls()) 2755 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result)) 2756 return fused; 2757 2758 return CGF.EmitARCAutoreleaseReturnValue(result); 2759 } 2760 2761 /// Heuristically search for a dominating store to the return-value slot. 2762 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) { 2763 // Check if a User is a store which pointerOperand is the ReturnValue. 2764 // We are looking for stores to the ReturnValue, not for stores of the 2765 // ReturnValue to some other location. 2766 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * { 2767 auto *SI = dyn_cast<llvm::StoreInst>(U); 2768 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer()) 2769 return nullptr; 2770 // These aren't actually possible for non-coerced returns, and we 2771 // only care about non-coerced returns on this code path. 2772 assert(!SI->isAtomic() && !SI->isVolatile()); 2773 return SI; 2774 }; 2775 // If there are multiple uses of the return-value slot, just check 2776 // for something immediately preceding the IP. Sometimes this can 2777 // happen with how we generate implicit-returns; it can also happen 2778 // with noreturn cleanups. 2779 if (!CGF.ReturnValue.getPointer()->hasOneUse()) { 2780 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 2781 if (IP->empty()) return nullptr; 2782 llvm::Instruction *I = &IP->back(); 2783 2784 // Skip lifetime markers 2785 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(), 2786 IE = IP->rend(); 2787 II != IE; ++II) { 2788 if (llvm::IntrinsicInst *Intrinsic = 2789 dyn_cast<llvm::IntrinsicInst>(&*II)) { 2790 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) { 2791 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1); 2792 ++II; 2793 if (II == IE) 2794 break; 2795 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II)) 2796 continue; 2797 } 2798 } 2799 I = &*II; 2800 break; 2801 } 2802 2803 return GetStoreIfValid(I); 2804 } 2805 2806 llvm::StoreInst *store = 2807 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back()); 2808 if (!store) return nullptr; 2809 2810 // Now do a first-and-dirty dominance check: just walk up the 2811 // single-predecessors chain from the current insertion point. 2812 llvm::BasicBlock *StoreBB = store->getParent(); 2813 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 2814 while (IP != StoreBB) { 2815 if (!(IP = IP->getSinglePredecessor())) 2816 return nullptr; 2817 } 2818 2819 // Okay, the store's basic block dominates the insertion point; we 2820 // can do our thing. 2821 return store; 2822 } 2823 2824 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI, 2825 bool EmitRetDbgLoc, 2826 SourceLocation EndLoc) { 2827 if (FI.isNoReturn()) { 2828 // Noreturn functions don't return. 2829 EmitUnreachable(EndLoc); 2830 return; 2831 } 2832 2833 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) { 2834 // Naked functions don't have epilogues. 2835 Builder.CreateUnreachable(); 2836 return; 2837 } 2838 2839 // Functions with no result always return void. 2840 if (!ReturnValue.isValid()) { 2841 Builder.CreateRetVoid(); 2842 return; 2843 } 2844 2845 llvm::DebugLoc RetDbgLoc; 2846 llvm::Value *RV = nullptr; 2847 QualType RetTy = FI.getReturnType(); 2848 const ABIArgInfo &RetAI = FI.getReturnInfo(); 2849 2850 switch (RetAI.getKind()) { 2851 case ABIArgInfo::InAlloca: 2852 // Aggregrates get evaluated directly into the destination. Sometimes we 2853 // need to return the sret value in a register, though. 2854 assert(hasAggregateEvaluationKind(RetTy)); 2855 if (RetAI.getInAllocaSRet()) { 2856 llvm::Function::arg_iterator EI = CurFn->arg_end(); 2857 --EI; 2858 llvm::Value *ArgStruct = &*EI; 2859 llvm::Value *SRet = Builder.CreateStructGEP( 2860 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex()); 2861 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret"); 2862 } 2863 break; 2864 2865 case ABIArgInfo::Indirect: { 2866 auto AI = CurFn->arg_begin(); 2867 if (RetAI.isSRetAfterThis()) 2868 ++AI; 2869 switch (getEvaluationKind(RetTy)) { 2870 case TEK_Complex: { 2871 ComplexPairTy RT = 2872 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc); 2873 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy), 2874 /*isInit*/ true); 2875 break; 2876 } 2877 case TEK_Aggregate: 2878 // Do nothing; aggregrates get evaluated directly into the destination. 2879 break; 2880 case TEK_Scalar: 2881 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), 2882 MakeNaturalAlignAddrLValue(&*AI, RetTy), 2883 /*isInit*/ true); 2884 break; 2885 } 2886 break; 2887 } 2888 2889 case ABIArgInfo::Extend: 2890 case ABIArgInfo::Direct: 2891 if (RetAI.getCoerceToType() == ConvertType(RetTy) && 2892 RetAI.getDirectOffset() == 0) { 2893 // The internal return value temp always will have pointer-to-return-type 2894 // type, just do a load. 2895 2896 // If there is a dominating store to ReturnValue, we can elide 2897 // the load, zap the store, and usually zap the alloca. 2898 if (llvm::StoreInst *SI = 2899 findDominatingStoreToReturnValue(*this)) { 2900 // Reuse the debug location from the store unless there is 2901 // cleanup code to be emitted between the store and return 2902 // instruction. 2903 if (EmitRetDbgLoc && !AutoreleaseResult) 2904 RetDbgLoc = SI->getDebugLoc(); 2905 // Get the stored value and nuke the now-dead store. 2906 RV = SI->getValueOperand(); 2907 SI->eraseFromParent(); 2908 2909 // Otherwise, we have to do a simple load. 2910 } else { 2911 RV = Builder.CreateLoad(ReturnValue); 2912 } 2913 } else { 2914 // If the value is offset in memory, apply the offset now. 2915 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI); 2916 2917 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this); 2918 } 2919 2920 // In ARC, end functions that return a retainable type with a call 2921 // to objc_autoreleaseReturnValue. 2922 if (AutoreleaseResult) { 2923 #ifndef NDEBUG 2924 // Type::isObjCRetainabletype has to be called on a QualType that hasn't 2925 // been stripped of the typedefs, so we cannot use RetTy here. Get the 2926 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from 2927 // CurCodeDecl or BlockInfo. 2928 QualType RT; 2929 2930 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl)) 2931 RT = FD->getReturnType(); 2932 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl)) 2933 RT = MD->getReturnType(); 2934 else if (isa<BlockDecl>(CurCodeDecl)) 2935 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType(); 2936 else 2937 llvm_unreachable("Unexpected function/method type"); 2938 2939 assert(getLangOpts().ObjCAutoRefCount && 2940 !FI.isReturnsRetained() && 2941 RT->isObjCRetainableType()); 2942 #endif 2943 RV = emitAutoreleaseOfResult(*this, RV); 2944 } 2945 2946 break; 2947 2948 case ABIArgInfo::Ignore: 2949 break; 2950 2951 case ABIArgInfo::CoerceAndExpand: { 2952 auto coercionType = RetAI.getCoerceAndExpandType(); 2953 2954 // Load all of the coerced elements out into results. 2955 llvm::SmallVector<llvm::Value*, 4> results; 2956 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType); 2957 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 2958 auto coercedEltType = coercionType->getElementType(i); 2959 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType)) 2960 continue; 2961 2962 auto eltAddr = Builder.CreateStructGEP(addr, i); 2963 auto elt = Builder.CreateLoad(eltAddr); 2964 results.push_back(elt); 2965 } 2966 2967 // If we have one result, it's the single direct result type. 2968 if (results.size() == 1) { 2969 RV = results[0]; 2970 2971 // Otherwise, we need to make a first-class aggregate. 2972 } else { 2973 // Construct a return type that lacks padding elements. 2974 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType(); 2975 2976 RV = llvm::UndefValue::get(returnType); 2977 for (unsigned i = 0, e = results.size(); i != e; ++i) { 2978 RV = Builder.CreateInsertValue(RV, results[i], i); 2979 } 2980 } 2981 break; 2982 } 2983 2984 case ABIArgInfo::Expand: 2985 llvm_unreachable("Invalid ABI kind for return argument"); 2986 } 2987 2988 llvm::Instruction *Ret; 2989 if (RV) { 2990 EmitReturnValueCheck(RV); 2991 Ret = Builder.CreateRet(RV); 2992 } else { 2993 Ret = Builder.CreateRetVoid(); 2994 } 2995 2996 if (RetDbgLoc) 2997 Ret->setDebugLoc(std::move(RetDbgLoc)); 2998 } 2999 3000 void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) { 3001 // A current decl may not be available when emitting vtable thunks. 3002 if (!CurCodeDecl) 3003 return; 3004 3005 ReturnsNonNullAttr *RetNNAttr = nullptr; 3006 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) 3007 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>(); 3008 3009 if (!RetNNAttr && !requiresReturnValueNullabilityCheck()) 3010 return; 3011 3012 // Prefer the returns_nonnull attribute if it's present. 3013 SourceLocation AttrLoc; 3014 SanitizerMask CheckKind; 3015 SanitizerHandler Handler; 3016 if (RetNNAttr) { 3017 assert(!requiresReturnValueNullabilityCheck() && 3018 "Cannot check nullability and the nonnull attribute"); 3019 AttrLoc = RetNNAttr->getLocation(); 3020 CheckKind = SanitizerKind::ReturnsNonnullAttribute; 3021 Handler = SanitizerHandler::NonnullReturn; 3022 } else { 3023 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl)) 3024 if (auto *TSI = DD->getTypeSourceInfo()) 3025 if (auto FTL = TSI->getTypeLoc().castAs<FunctionTypeLoc>()) 3026 AttrLoc = FTL.getReturnLoc().findNullabilityLoc(); 3027 CheckKind = SanitizerKind::NullabilityReturn; 3028 Handler = SanitizerHandler::NullabilityReturn; 3029 } 3030 3031 SanitizerScope SanScope(this); 3032 3033 // Make sure the "return" source location is valid. If we're checking a 3034 // nullability annotation, make sure the preconditions for the check are met. 3035 llvm::BasicBlock *Check = createBasicBlock("nullcheck"); 3036 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck"); 3037 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load"); 3038 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr); 3039 if (requiresReturnValueNullabilityCheck()) 3040 CanNullCheck = 3041 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition); 3042 Builder.CreateCondBr(CanNullCheck, Check, NoCheck); 3043 EmitBlock(Check); 3044 3045 // Now do the null check. 3046 llvm::Value *Cond = Builder.CreateIsNotNull(RV); 3047 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)}; 3048 llvm::Value *DynamicData[] = {SLocPtr}; 3049 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData); 3050 3051 EmitBlock(NoCheck); 3052 3053 #ifndef NDEBUG 3054 // The return location should not be used after the check has been emitted. 3055 ReturnLocation = Address::invalid(); 3056 #endif 3057 } 3058 3059 static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) { 3060 const CXXRecordDecl *RD = type->getAsCXXRecordDecl(); 3061 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory; 3062 } 3063 3064 static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, 3065 QualType Ty) { 3066 // FIXME: Generate IR in one pass, rather than going back and fixing up these 3067 // placeholders. 3068 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty); 3069 llvm::Type *IRPtrTy = IRTy->getPointerTo(); 3070 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo()); 3071 3072 // FIXME: When we generate this IR in one pass, we shouldn't need 3073 // this win32-specific alignment hack. 3074 CharUnits Align = CharUnits::fromQuantity(4); 3075 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align); 3076 3077 return AggValueSlot::forAddr(Address(Placeholder, Align), 3078 Ty.getQualifiers(), 3079 AggValueSlot::IsNotDestructed, 3080 AggValueSlot::DoesNotNeedGCBarriers, 3081 AggValueSlot::IsNotAliased, 3082 AggValueSlot::DoesNotOverlap); 3083 } 3084 3085 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args, 3086 const VarDecl *param, 3087 SourceLocation loc) { 3088 // StartFunction converted the ABI-lowered parameter(s) into a 3089 // local alloca. We need to turn that into an r-value suitable 3090 // for EmitCall. 3091 Address local = GetAddrOfLocalVar(param); 3092 3093 QualType type = param->getType(); 3094 3095 if (isInAllocaArgument(CGM.getCXXABI(), type)) { 3096 CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter"); 3097 } 3098 3099 // GetAddrOfLocalVar returns a pointer-to-pointer for references, 3100 // but the argument needs to be the original pointer. 3101 if (type->isReferenceType()) { 3102 args.add(RValue::get(Builder.CreateLoad(local)), type); 3103 3104 // In ARC, move out of consumed arguments so that the release cleanup 3105 // entered by StartFunction doesn't cause an over-release. This isn't 3106 // optimal -O0 code generation, but it should get cleaned up when 3107 // optimization is enabled. This also assumes that delegate calls are 3108 // performed exactly once for a set of arguments, but that should be safe. 3109 } else if (getLangOpts().ObjCAutoRefCount && 3110 param->hasAttr<NSConsumedAttr>() && 3111 type->isObjCRetainableType()) { 3112 llvm::Value *ptr = Builder.CreateLoad(local); 3113 auto null = 3114 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType())); 3115 Builder.CreateStore(null, local); 3116 args.add(RValue::get(ptr), type); 3117 3118 // For the most part, we just need to load the alloca, except that 3119 // aggregate r-values are actually pointers to temporaries. 3120 } else { 3121 args.add(convertTempToRValue(local, type, loc), type); 3122 } 3123 3124 // Deactivate the cleanup for the callee-destructed param that was pushed. 3125 if (hasAggregateEvaluationKind(type) && !CurFuncIsThunk && 3126 type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() && 3127 param->needsDestruction(getContext())) { 3128 EHScopeStack::stable_iterator cleanup = 3129 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param)); 3130 assert(cleanup.isValid() && 3131 "cleanup for callee-destructed param not recorded"); 3132 // This unreachable is a temporary marker which will be removed later. 3133 llvm::Instruction *isActive = Builder.CreateUnreachable(); 3134 args.addArgCleanupDeactivation(cleanup, isActive); 3135 } 3136 } 3137 3138 static bool isProvablyNull(llvm::Value *addr) { 3139 return isa<llvm::ConstantPointerNull>(addr); 3140 } 3141 3142 /// Emit the actual writing-back of a writeback. 3143 static void emitWriteback(CodeGenFunction &CGF, 3144 const CallArgList::Writeback &writeback) { 3145 const LValue &srcLV = writeback.Source; 3146 Address srcAddr = srcLV.getAddress(CGF); 3147 assert(!isProvablyNull(srcAddr.getPointer()) && 3148 "shouldn't have writeback for provably null argument"); 3149 3150 llvm::BasicBlock *contBB = nullptr; 3151 3152 // If the argument wasn't provably non-null, we need to null check 3153 // before doing the store. 3154 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(), 3155 CGF.CGM.getDataLayout()); 3156 if (!provablyNonNull) { 3157 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback"); 3158 contBB = CGF.createBasicBlock("icr.done"); 3159 3160 llvm::Value *isNull = 3161 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); 3162 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB); 3163 CGF.EmitBlock(writebackBB); 3164 } 3165 3166 // Load the value to writeback. 3167 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary); 3168 3169 // Cast it back, in case we're writing an id to a Foo* or something. 3170 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(), 3171 "icr.writeback-cast"); 3172 3173 // Perform the writeback. 3174 3175 // If we have a "to use" value, it's something we need to emit a use 3176 // of. This has to be carefully threaded in: if it's done after the 3177 // release it's potentially undefined behavior (and the optimizer 3178 // will ignore it), and if it happens before the retain then the 3179 // optimizer could move the release there. 3180 if (writeback.ToUse) { 3181 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong); 3182 3183 // Retain the new value. No need to block-copy here: the block's 3184 // being passed up the stack. 3185 value = CGF.EmitARCRetainNonBlock(value); 3186 3187 // Emit the intrinsic use here. 3188 CGF.EmitARCIntrinsicUse(writeback.ToUse); 3189 3190 // Load the old value (primitively). 3191 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation()); 3192 3193 // Put the new value in place (primitively). 3194 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false); 3195 3196 // Release the old value. 3197 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime()); 3198 3199 // Otherwise, we can just do a normal lvalue store. 3200 } else { 3201 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV); 3202 } 3203 3204 // Jump to the continuation block. 3205 if (!provablyNonNull) 3206 CGF.EmitBlock(contBB); 3207 } 3208 3209 static void emitWritebacks(CodeGenFunction &CGF, 3210 const CallArgList &args) { 3211 for (const auto &I : args.writebacks()) 3212 emitWriteback(CGF, I); 3213 } 3214 3215 static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF, 3216 const CallArgList &CallArgs) { 3217 ArrayRef<CallArgList::CallArgCleanup> Cleanups = 3218 CallArgs.getCleanupsToDeactivate(); 3219 // Iterate in reverse to increase the likelihood of popping the cleanup. 3220 for (const auto &I : llvm::reverse(Cleanups)) { 3221 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP); 3222 I.IsActiveIP->eraseFromParent(); 3223 } 3224 } 3225 3226 static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) { 3227 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens())) 3228 if (uop->getOpcode() == UO_AddrOf) 3229 return uop->getSubExpr(); 3230 return nullptr; 3231 } 3232 3233 /// Emit an argument that's being passed call-by-writeback. That is, 3234 /// we are passing the address of an __autoreleased temporary; it 3235 /// might be copy-initialized with the current value of the given 3236 /// address, but it will definitely be copied out of after the call. 3237 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, 3238 const ObjCIndirectCopyRestoreExpr *CRE) { 3239 LValue srcLV; 3240 3241 // Make an optimistic effort to emit the address as an l-value. 3242 // This can fail if the argument expression is more complicated. 3243 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) { 3244 srcLV = CGF.EmitLValue(lvExpr); 3245 3246 // Otherwise, just emit it as a scalar. 3247 } else { 3248 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr()); 3249 3250 QualType srcAddrType = 3251 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType(); 3252 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType); 3253 } 3254 Address srcAddr = srcLV.getAddress(CGF); 3255 3256 // The dest and src types don't necessarily match in LLVM terms 3257 // because of the crazy ObjC compatibility rules. 3258 3259 llvm::PointerType *destType = 3260 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType())); 3261 3262 // If the address is a constant null, just pass the appropriate null. 3263 if (isProvablyNull(srcAddr.getPointer())) { 3264 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)), 3265 CRE->getType()); 3266 return; 3267 } 3268 3269 // Create the temporary. 3270 Address temp = CGF.CreateTempAlloca(destType->getElementType(), 3271 CGF.getPointerAlign(), 3272 "icr.temp"); 3273 // Loading an l-value can introduce a cleanup if the l-value is __weak, 3274 // and that cleanup will be conditional if we can't prove that the l-value 3275 // isn't null, so we need to register a dominating point so that the cleanups 3276 // system will make valid IR. 3277 CodeGenFunction::ConditionalEvaluation condEval(CGF); 3278 3279 // Zero-initialize it if we're not doing a copy-initialization. 3280 bool shouldCopy = CRE->shouldCopy(); 3281 if (!shouldCopy) { 3282 llvm::Value *null = 3283 llvm::ConstantPointerNull::get( 3284 cast<llvm::PointerType>(destType->getElementType())); 3285 CGF.Builder.CreateStore(null, temp); 3286 } 3287 3288 llvm::BasicBlock *contBB = nullptr; 3289 llvm::BasicBlock *originBB = nullptr; 3290 3291 // If the address is *not* known to be non-null, we need to switch. 3292 llvm::Value *finalArgument; 3293 3294 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(), 3295 CGF.CGM.getDataLayout()); 3296 if (provablyNonNull) { 3297 finalArgument = temp.getPointer(); 3298 } else { 3299 llvm::Value *isNull = 3300 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); 3301 3302 finalArgument = CGF.Builder.CreateSelect(isNull, 3303 llvm::ConstantPointerNull::get(destType), 3304 temp.getPointer(), "icr.argument"); 3305 3306 // If we need to copy, then the load has to be conditional, which 3307 // means we need control flow. 3308 if (shouldCopy) { 3309 originBB = CGF.Builder.GetInsertBlock(); 3310 contBB = CGF.createBasicBlock("icr.cont"); 3311 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy"); 3312 CGF.Builder.CreateCondBr(isNull, contBB, copyBB); 3313 CGF.EmitBlock(copyBB); 3314 condEval.begin(CGF); 3315 } 3316 } 3317 3318 llvm::Value *valueToUse = nullptr; 3319 3320 // Perform a copy if necessary. 3321 if (shouldCopy) { 3322 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation()); 3323 assert(srcRV.isScalar()); 3324 3325 llvm::Value *src = srcRV.getScalarVal(); 3326 src = CGF.Builder.CreateBitCast(src, destType->getElementType(), 3327 "icr.cast"); 3328 3329 // Use an ordinary store, not a store-to-lvalue. 3330 CGF.Builder.CreateStore(src, temp); 3331 3332 // If optimization is enabled, and the value was held in a 3333 // __strong variable, we need to tell the optimizer that this 3334 // value has to stay alive until we're doing the store back. 3335 // This is because the temporary is effectively unretained, 3336 // and so otherwise we can violate the high-level semantics. 3337 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 && 3338 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) { 3339 valueToUse = src; 3340 } 3341 } 3342 3343 // Finish the control flow if we needed it. 3344 if (shouldCopy && !provablyNonNull) { 3345 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock(); 3346 CGF.EmitBlock(contBB); 3347 3348 // Make a phi for the value to intrinsically use. 3349 if (valueToUse) { 3350 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2, 3351 "icr.to-use"); 3352 phiToUse->addIncoming(valueToUse, copyBB); 3353 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()), 3354 originBB); 3355 valueToUse = phiToUse; 3356 } 3357 3358 condEval.end(CGF); 3359 } 3360 3361 args.addWriteback(srcLV, temp, valueToUse); 3362 args.add(RValue::get(finalArgument), CRE->getType()); 3363 } 3364 3365 void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) { 3366 assert(!StackBase); 3367 3368 // Save the stack. 3369 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave); 3370 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save"); 3371 } 3372 3373 void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const { 3374 if (StackBase) { 3375 // Restore the stack after the call. 3376 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 3377 CGF.Builder.CreateCall(F, StackBase); 3378 } 3379 } 3380 3381 void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType, 3382 SourceLocation ArgLoc, 3383 AbstractCallee AC, 3384 unsigned ParmNum) { 3385 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) || 3386 SanOpts.has(SanitizerKind::NullabilityArg))) 3387 return; 3388 3389 // The param decl may be missing in a variadic function. 3390 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr; 3391 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum; 3392 3393 // Prefer the nonnull attribute if it's present. 3394 const NonNullAttr *NNAttr = nullptr; 3395 if (SanOpts.has(SanitizerKind::NonnullAttribute)) 3396 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo); 3397 3398 bool CanCheckNullability = false; 3399 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) { 3400 auto Nullability = PVD->getType()->getNullability(getContext()); 3401 CanCheckNullability = Nullability && 3402 *Nullability == NullabilityKind::NonNull && 3403 PVD->getTypeSourceInfo(); 3404 } 3405 3406 if (!NNAttr && !CanCheckNullability) 3407 return; 3408 3409 SourceLocation AttrLoc; 3410 SanitizerMask CheckKind; 3411 SanitizerHandler Handler; 3412 if (NNAttr) { 3413 AttrLoc = NNAttr->getLocation(); 3414 CheckKind = SanitizerKind::NonnullAttribute; 3415 Handler = SanitizerHandler::NonnullArg; 3416 } else { 3417 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc(); 3418 CheckKind = SanitizerKind::NullabilityArg; 3419 Handler = SanitizerHandler::NullabilityArg; 3420 } 3421 3422 SanitizerScope SanScope(this); 3423 assert(RV.isScalar()); 3424 llvm::Value *V = RV.getScalarVal(); 3425 llvm::Value *Cond = 3426 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType())); 3427 llvm::Constant *StaticData[] = { 3428 EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc), 3429 llvm::ConstantInt::get(Int32Ty, ArgNo + 1), 3430 }; 3431 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None); 3432 } 3433 3434 void CodeGenFunction::EmitCallArgs( 3435 CallArgList &Args, ArrayRef<QualType> ArgTypes, 3436 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 3437 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) { 3438 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin())); 3439 3440 // We *have* to evaluate arguments from right to left in the MS C++ ABI, 3441 // because arguments are destroyed left to right in the callee. As a special 3442 // case, there are certain language constructs that require left-to-right 3443 // evaluation, and in those cases we consider the evaluation order requirement 3444 // to trump the "destruction order is reverse construction order" guarantee. 3445 bool LeftToRight = 3446 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee() 3447 ? Order == EvaluationOrder::ForceLeftToRight 3448 : Order != EvaluationOrder::ForceRightToLeft; 3449 3450 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg, 3451 RValue EmittedArg) { 3452 if (!AC.hasFunctionDecl() || I >= AC.getNumParams()) 3453 return; 3454 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>(); 3455 if (PS == nullptr) 3456 return; 3457 3458 const auto &Context = getContext(); 3459 auto SizeTy = Context.getSizeType(); 3460 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy)); 3461 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?"); 3462 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T, 3463 EmittedArg.getScalarVal(), 3464 PS->isDynamic()); 3465 Args.add(RValue::get(V), SizeTy); 3466 // If we're emitting args in reverse, be sure to do so with 3467 // pass_object_size, as well. 3468 if (!LeftToRight) 3469 std::swap(Args.back(), *(&Args.back() - 1)); 3470 }; 3471 3472 // Insert a stack save if we're going to need any inalloca args. 3473 bool HasInAllocaArgs = false; 3474 if (CGM.getTarget().getCXXABI().isMicrosoft()) { 3475 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end(); 3476 I != E && !HasInAllocaArgs; ++I) 3477 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I); 3478 if (HasInAllocaArgs) { 3479 assert(getTarget().getTriple().getArch() == llvm::Triple::x86); 3480 Args.allocateArgumentMemory(*this); 3481 } 3482 } 3483 3484 // Evaluate each argument in the appropriate order. 3485 size_t CallArgsStart = Args.size(); 3486 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) { 3487 unsigned Idx = LeftToRight ? I : E - I - 1; 3488 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx; 3489 unsigned InitialArgSize = Args.size(); 3490 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of 3491 // the argument and parameter match or the objc method is parameterized. 3492 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || 3493 getContext().hasSameUnqualifiedType((*Arg)->getType(), 3494 ArgTypes[Idx]) || 3495 (isa<ObjCMethodDecl>(AC.getDecl()) && 3496 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && 3497 "Argument and parameter types don't match"); 3498 EmitCallArg(Args, *Arg, ArgTypes[Idx]); 3499 // In particular, we depend on it being the last arg in Args, and the 3500 // objectsize bits depend on there only being one arg if !LeftToRight. 3501 assert(InitialArgSize + 1 == Args.size() && 3502 "The code below depends on only adding one arg per EmitCallArg"); 3503 (void)InitialArgSize; 3504 // Since pointer argument are never emitted as LValue, it is safe to emit 3505 // non-null argument check for r-value only. 3506 if (!Args.back().hasLValue()) { 3507 RValue RVArg = Args.back().getKnownRValue(); 3508 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC, 3509 ParamsToSkip + Idx); 3510 // @llvm.objectsize should never have side-effects and shouldn't need 3511 // destruction/cleanups, so we can safely "emit" it after its arg, 3512 // regardless of right-to-leftness 3513 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg); 3514 } 3515 } 3516 3517 if (!LeftToRight) { 3518 // Un-reverse the arguments we just evaluated so they match up with the LLVM 3519 // IR function. 3520 std::reverse(Args.begin() + CallArgsStart, Args.end()); 3521 } 3522 } 3523 3524 namespace { 3525 3526 struct DestroyUnpassedArg final : EHScopeStack::Cleanup { 3527 DestroyUnpassedArg(Address Addr, QualType Ty) 3528 : Addr(Addr), Ty(Ty) {} 3529 3530 Address Addr; 3531 QualType Ty; 3532 3533 void Emit(CodeGenFunction &CGF, Flags flags) override { 3534 QualType::DestructionKind DtorKind = Ty.isDestructedType(); 3535 if (DtorKind == QualType::DK_cxx_destructor) { 3536 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor(); 3537 assert(!Dtor->isTrivial()); 3538 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false, 3539 /*Delegating=*/false, Addr, Ty); 3540 } else { 3541 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty)); 3542 } 3543 } 3544 }; 3545 3546 struct DisableDebugLocationUpdates { 3547 CodeGenFunction &CGF; 3548 bool disabledDebugInfo; 3549 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) { 3550 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo())) 3551 CGF.disableDebugInfo(); 3552 } 3553 ~DisableDebugLocationUpdates() { 3554 if (disabledDebugInfo) 3555 CGF.enableDebugInfo(); 3556 } 3557 }; 3558 3559 } // end anonymous namespace 3560 3561 RValue CallArg::getRValue(CodeGenFunction &CGF) const { 3562 if (!HasLV) 3563 return RV; 3564 LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty); 3565 CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap, 3566 LV.isVolatile()); 3567 IsUsed = true; 3568 return RValue::getAggregate(Copy.getAddress(CGF)); 3569 } 3570 3571 void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const { 3572 LValue Dst = CGF.MakeAddrLValue(Addr, Ty); 3573 if (!HasLV && RV.isScalar()) 3574 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true); 3575 else if (!HasLV && RV.isComplex()) 3576 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true); 3577 else { 3578 auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress(); 3579 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty); 3580 // We assume that call args are never copied into subobjects. 3581 CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap, 3582 HasLV ? LV.isVolatileQualified() 3583 : RV.isVolatileQualified()); 3584 } 3585 IsUsed = true; 3586 } 3587 3588 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E, 3589 QualType type) { 3590 DisableDebugLocationUpdates Dis(*this, E); 3591 if (const ObjCIndirectCopyRestoreExpr *CRE 3592 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) { 3593 assert(getLangOpts().ObjCAutoRefCount); 3594 return emitWritebackArg(*this, args, CRE); 3595 } 3596 3597 assert(type->isReferenceType() == E->isGLValue() && 3598 "reference binding to unmaterialized r-value!"); 3599 3600 if (E->isGLValue()) { 3601 assert(E->getObjectKind() == OK_Ordinary); 3602 return args.add(EmitReferenceBindingToExpr(E), type); 3603 } 3604 3605 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type); 3606 3607 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee. 3608 // However, we still have to push an EH-only cleanup in case we unwind before 3609 // we make it to the call. 3610 if (HasAggregateEvalKind && 3611 type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) { 3612 // If we're using inalloca, use the argument memory. Otherwise, use a 3613 // temporary. 3614 AggValueSlot Slot; 3615 if (args.isUsingInAlloca()) 3616 Slot = createPlaceholderSlot(*this, type); 3617 else 3618 Slot = CreateAggTemp(type, "agg.tmp"); 3619 3620 bool DestroyedInCallee = true, NeedsEHCleanup = true; 3621 if (const auto *RD = type->getAsCXXRecordDecl()) 3622 DestroyedInCallee = RD->hasNonTrivialDestructor(); 3623 else 3624 NeedsEHCleanup = needsEHCleanup(type.isDestructedType()); 3625 3626 if (DestroyedInCallee) 3627 Slot.setExternallyDestructed(); 3628 3629 EmitAggExpr(E, Slot); 3630 RValue RV = Slot.asRValue(); 3631 args.add(RV, type); 3632 3633 if (DestroyedInCallee && NeedsEHCleanup) { 3634 // Create a no-op GEP between the placeholder and the cleanup so we can 3635 // RAUW it successfully. It also serves as a marker of the first 3636 // instruction where the cleanup is active. 3637 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(), 3638 type); 3639 // This unreachable is a temporary marker which will be removed later. 3640 llvm::Instruction *IsActive = Builder.CreateUnreachable(); 3641 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive); 3642 } 3643 return; 3644 } 3645 3646 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) && 3647 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) { 3648 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr()); 3649 assert(L.isSimple()); 3650 args.addUncopiedAggregate(L, type); 3651 return; 3652 } 3653 3654 args.add(EmitAnyExprToTemp(E), type); 3655 } 3656 3657 QualType CodeGenFunction::getVarArgType(const Expr *Arg) { 3658 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC 3659 // implicitly widens null pointer constants that are arguments to varargs 3660 // functions to pointer-sized ints. 3661 if (!getTarget().getTriple().isOSWindows()) 3662 return Arg->getType(); 3663 3664 if (Arg->getType()->isIntegerType() && 3665 getContext().getTypeSize(Arg->getType()) < 3666 getContext().getTargetInfo().getPointerWidth(0) && 3667 Arg->isNullPointerConstant(getContext(), 3668 Expr::NPC_ValueDependentIsNotNull)) { 3669 return getContext().getIntPtrType(); 3670 } 3671 3672 return Arg->getType(); 3673 } 3674 3675 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3676 // optimizer it can aggressively ignore unwind edges. 3677 void 3678 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) { 3679 if (CGM.getCodeGenOpts().OptimizationLevel != 0 && 3680 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions) 3681 Inst->setMetadata("clang.arc.no_objc_arc_exceptions", 3682 CGM.getNoObjCARCExceptionsMetadata()); 3683 } 3684 3685 /// Emits a call to the given no-arguments nounwind runtime function. 3686 llvm::CallInst * 3687 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 3688 const llvm::Twine &name) { 3689 return EmitNounwindRuntimeCall(callee, None, name); 3690 } 3691 3692 /// Emits a call to the given nounwind runtime function. 3693 llvm::CallInst * 3694 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 3695 ArrayRef<llvm::Value *> args, 3696 const llvm::Twine &name) { 3697 llvm::CallInst *call = EmitRuntimeCall(callee, args, name); 3698 call->setDoesNotThrow(); 3699 return call; 3700 } 3701 3702 /// Emits a simple call (never an invoke) to the given no-arguments 3703 /// runtime function. 3704 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee, 3705 const llvm::Twine &name) { 3706 return EmitRuntimeCall(callee, None, name); 3707 } 3708 3709 // Calls which may throw must have operand bundles indicating which funclet 3710 // they are nested within. 3711 SmallVector<llvm::OperandBundleDef, 1> 3712 CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) { 3713 SmallVector<llvm::OperandBundleDef, 1> BundleList; 3714 // There is no need for a funclet operand bundle if we aren't inside a 3715 // funclet. 3716 if (!CurrentFuncletPad) 3717 return BundleList; 3718 3719 // Skip intrinsics which cannot throw. 3720 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts()); 3721 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) 3722 return BundleList; 3723 3724 BundleList.emplace_back("funclet", CurrentFuncletPad); 3725 return BundleList; 3726 } 3727 3728 /// Emits a simple call (never an invoke) to the given runtime function. 3729 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee, 3730 ArrayRef<llvm::Value *> args, 3731 const llvm::Twine &name) { 3732 llvm::CallInst *call = Builder.CreateCall( 3733 callee, args, getBundlesForFunclet(callee.getCallee()), name); 3734 call->setCallingConv(getRuntimeCC()); 3735 return call; 3736 } 3737 3738 /// Emits a call or invoke to the given noreturn runtime function. 3739 void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke( 3740 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) { 3741 SmallVector<llvm::OperandBundleDef, 1> BundleList = 3742 getBundlesForFunclet(callee.getCallee()); 3743 3744 if (getInvokeDest()) { 3745 llvm::InvokeInst *invoke = 3746 Builder.CreateInvoke(callee, 3747 getUnreachableBlock(), 3748 getInvokeDest(), 3749 args, 3750 BundleList); 3751 invoke->setDoesNotReturn(); 3752 invoke->setCallingConv(getRuntimeCC()); 3753 } else { 3754 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList); 3755 call->setDoesNotReturn(); 3756 call->setCallingConv(getRuntimeCC()); 3757 Builder.CreateUnreachable(); 3758 } 3759 } 3760 3761 /// Emits a call or invoke instruction to the given nullary runtime function. 3762 llvm::CallBase * 3763 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 3764 const Twine &name) { 3765 return EmitRuntimeCallOrInvoke(callee, None, name); 3766 } 3767 3768 /// Emits a call or invoke instruction to the given runtime function. 3769 llvm::CallBase * 3770 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 3771 ArrayRef<llvm::Value *> args, 3772 const Twine &name) { 3773 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name); 3774 call->setCallingConv(getRuntimeCC()); 3775 return call; 3776 } 3777 3778 /// Emits a call or invoke instruction to the given function, depending 3779 /// on the current state of the EH stack. 3780 llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee, 3781 ArrayRef<llvm::Value *> Args, 3782 const Twine &Name) { 3783 llvm::BasicBlock *InvokeDest = getInvokeDest(); 3784 SmallVector<llvm::OperandBundleDef, 1> BundleList = 3785 getBundlesForFunclet(Callee.getCallee()); 3786 3787 llvm::CallBase *Inst; 3788 if (!InvokeDest) 3789 Inst = Builder.CreateCall(Callee, Args, BundleList, Name); 3790 else { 3791 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont"); 3792 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList, 3793 Name); 3794 EmitBlock(ContBB); 3795 } 3796 3797 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3798 // optimizer it can aggressively ignore unwind edges. 3799 if (CGM.getLangOpts().ObjCAutoRefCount) 3800 AddObjCARCExceptionMetadata(Inst); 3801 3802 return Inst; 3803 } 3804 3805 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old, 3806 llvm::Value *New) { 3807 DeferredReplacements.push_back(std::make_pair(Old, New)); 3808 } 3809 3810 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, 3811 const CGCallee &Callee, 3812 ReturnValueSlot ReturnValue, 3813 const CallArgList &CallArgs, 3814 llvm::CallBase **callOrInvoke, 3815 SourceLocation Loc) { 3816 // FIXME: We no longer need the types from CallArgs; lift up and simplify. 3817 3818 assert(Callee.isOrdinary() || Callee.isVirtual()); 3819 3820 // Handle struct-return functions by passing a pointer to the 3821 // location that we would like to return into. 3822 QualType RetTy = CallInfo.getReturnType(); 3823 const ABIArgInfo &RetAI = CallInfo.getReturnInfo(); 3824 3825 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo); 3826 3827 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl(); 3828 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 3829 // We can only guarantee that a function is called from the correct 3830 // context/function based on the appropriate target attributes, 3831 // so only check in the case where we have both always_inline and target 3832 // since otherwise we could be making a conditional call after a check for 3833 // the proper cpu features (and it won't cause code generation issues due to 3834 // function based code generation). 3835 if (TargetDecl->hasAttr<AlwaysInlineAttr>() && 3836 TargetDecl->hasAttr<TargetAttr>()) 3837 checkTargetFeatures(Loc, FD); 3838 3839 #ifndef NDEBUG 3840 if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) { 3841 // For an inalloca varargs function, we don't expect CallInfo to match the 3842 // function pointer's type, because the inalloca struct a will have extra 3843 // fields in it for the varargs parameters. Code later in this function 3844 // bitcasts the function pointer to the type derived from CallInfo. 3845 // 3846 // In other cases, we assert that the types match up (until pointers stop 3847 // having pointee types). 3848 llvm::Type *TypeFromVal; 3849 if (Callee.isVirtual()) 3850 TypeFromVal = Callee.getVirtualFunctionType(); 3851 else 3852 TypeFromVal = 3853 Callee.getFunctionPointer()->getType()->getPointerElementType(); 3854 assert(IRFuncTy == TypeFromVal); 3855 } 3856 #endif 3857 3858 // 1. Set up the arguments. 3859 3860 // If we're using inalloca, insert the allocation after the stack save. 3861 // FIXME: Do this earlier rather than hacking it in here! 3862 Address ArgMemory = Address::invalid(); 3863 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) { 3864 const llvm::DataLayout &DL = CGM.getDataLayout(); 3865 llvm::Instruction *IP = CallArgs.getStackBase(); 3866 llvm::AllocaInst *AI; 3867 if (IP) { 3868 IP = IP->getNextNode(); 3869 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(), 3870 "argmem", IP); 3871 } else { 3872 AI = CreateTempAlloca(ArgStruct, "argmem"); 3873 } 3874 auto Align = CallInfo.getArgStructAlignment(); 3875 AI->setAlignment(Align.getAsAlign()); 3876 AI->setUsedWithInAlloca(true); 3877 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca()); 3878 ArgMemory = Address(AI, Align); 3879 } 3880 3881 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo); 3882 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs()); 3883 3884 // If the call returns a temporary with struct return, create a temporary 3885 // alloca to hold the result, unless one is given to us. 3886 Address SRetPtr = Address::invalid(); 3887 Address SRetAlloca = Address::invalid(); 3888 llvm::Value *UnusedReturnSizePtr = nullptr; 3889 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) { 3890 if (!ReturnValue.isNull()) { 3891 SRetPtr = ReturnValue.getValue(); 3892 } else { 3893 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca); 3894 if (HaveInsertPoint() && ReturnValue.isUnused()) { 3895 uint64_t size = 3896 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy)); 3897 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer()); 3898 } 3899 } 3900 if (IRFunctionArgs.hasSRetArg()) { 3901 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer(); 3902 } else if (RetAI.isInAlloca()) { 3903 Address Addr = 3904 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex()); 3905 Builder.CreateStore(SRetPtr.getPointer(), Addr); 3906 } 3907 } 3908 3909 Address swiftErrorTemp = Address::invalid(); 3910 Address swiftErrorArg = Address::invalid(); 3911 3912 // When passing arguments using temporary allocas, we need to add the 3913 // appropriate lifetime markers. This vector keeps track of all the lifetime 3914 // markers that need to be ended right after the call. 3915 SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall; 3916 3917 // Translate all of the arguments as necessary to match the IR lowering. 3918 assert(CallInfo.arg_size() == CallArgs.size() && 3919 "Mismatch between function signature & arguments."); 3920 unsigned ArgNo = 0; 3921 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin(); 3922 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); 3923 I != E; ++I, ++info_it, ++ArgNo) { 3924 const ABIArgInfo &ArgInfo = info_it->info; 3925 3926 // Insert a padding argument to ensure proper alignment. 3927 if (IRFunctionArgs.hasPaddingArg(ArgNo)) 3928 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 3929 llvm::UndefValue::get(ArgInfo.getPaddingType()); 3930 3931 unsigned FirstIRArg, NumIRArgs; 3932 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 3933 3934 switch (ArgInfo.getKind()) { 3935 case ABIArgInfo::InAlloca: { 3936 assert(NumIRArgs == 0); 3937 assert(getTarget().getTriple().getArch() == llvm::Triple::x86); 3938 if (I->isAggregate()) { 3939 // Replace the placeholder with the appropriate argument slot GEP. 3940 Address Addr = I->hasLValue() 3941 ? I->getKnownLValue().getAddress(*this) 3942 : I->getKnownRValue().getAggregateAddress(); 3943 llvm::Instruction *Placeholder = 3944 cast<llvm::Instruction>(Addr.getPointer()); 3945 CGBuilderTy::InsertPoint IP = Builder.saveIP(); 3946 Builder.SetInsertPoint(Placeholder); 3947 Addr = 3948 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex()); 3949 Builder.restoreIP(IP); 3950 deferPlaceholderReplacement(Placeholder, Addr.getPointer()); 3951 } else { 3952 // Store the RValue into the argument struct. 3953 Address Addr = 3954 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex()); 3955 unsigned AS = Addr.getType()->getPointerAddressSpace(); 3956 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS); 3957 // There are some cases where a trivial bitcast is not avoidable. The 3958 // definition of a type later in a translation unit may change it's type 3959 // from {}* to (%struct.foo*)*. 3960 if (Addr.getType() != MemType) 3961 Addr = Builder.CreateBitCast(Addr, MemType); 3962 I->copyInto(*this, Addr); 3963 } 3964 break; 3965 } 3966 3967 case ABIArgInfo::Indirect: { 3968 assert(NumIRArgs == 1); 3969 if (!I->isAggregate()) { 3970 // Make a temporary alloca to pass the argument. 3971 Address Addr = CreateMemTempWithoutCast( 3972 I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp"); 3973 IRCallArgs[FirstIRArg] = Addr.getPointer(); 3974 3975 I->copyInto(*this, Addr); 3976 } else { 3977 // We want to avoid creating an unnecessary temporary+copy here; 3978 // however, we need one in three cases: 3979 // 1. If the argument is not byval, and we are required to copy the 3980 // source. (This case doesn't occur on any common architecture.) 3981 // 2. If the argument is byval, RV is not sufficiently aligned, and 3982 // we cannot force it to be sufficiently aligned. 3983 // 3. If the argument is byval, but RV is not located in default 3984 // or alloca address space. 3985 Address Addr = I->hasLValue() 3986 ? I->getKnownLValue().getAddress(*this) 3987 : I->getKnownRValue().getAggregateAddress(); 3988 llvm::Value *V = Addr.getPointer(); 3989 CharUnits Align = ArgInfo.getIndirectAlign(); 3990 const llvm::DataLayout *TD = &CGM.getDataLayout(); 3991 3992 assert((FirstIRArg >= IRFuncTy->getNumParams() || 3993 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == 3994 TD->getAllocaAddrSpace()) && 3995 "indirect argument must be in alloca address space"); 3996 3997 bool NeedCopy = false; 3998 3999 if (Addr.getAlignment() < Align && 4000 llvm::getOrEnforceKnownAlignment(V, Align.getQuantity(), *TD) < 4001 Align.getQuantity()) { 4002 NeedCopy = true; 4003 } else if (I->hasLValue()) { 4004 auto LV = I->getKnownLValue(); 4005 auto AS = LV.getAddressSpace(); 4006 4007 if ((!ArgInfo.getIndirectByVal() && 4008 (LV.getAlignment() >= 4009 getContext().getTypeAlignInChars(I->Ty)))) { 4010 NeedCopy = true; 4011 } 4012 if (!getLangOpts().OpenCL) { 4013 if ((ArgInfo.getIndirectByVal() && 4014 (AS != LangAS::Default && 4015 AS != CGM.getASTAllocaAddressSpace()))) { 4016 NeedCopy = true; 4017 } 4018 } 4019 // For OpenCL even if RV is located in default or alloca address space 4020 // we don't want to perform address space cast for it. 4021 else if ((ArgInfo.getIndirectByVal() && 4022 Addr.getType()->getAddressSpace() != IRFuncTy-> 4023 getParamType(FirstIRArg)->getPointerAddressSpace())) { 4024 NeedCopy = true; 4025 } 4026 } 4027 4028 if (NeedCopy) { 4029 // Create an aligned temporary, and copy to it. 4030 Address AI = CreateMemTempWithoutCast( 4031 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp"); 4032 IRCallArgs[FirstIRArg] = AI.getPointer(); 4033 4034 // Emit lifetime markers for the temporary alloca. 4035 uint64_t ByvalTempElementSize = 4036 CGM.getDataLayout().getTypeAllocSize(AI.getElementType()); 4037 llvm::Value *LifetimeSize = 4038 EmitLifetimeStart(ByvalTempElementSize, AI.getPointer()); 4039 4040 // Add cleanup code to emit the end lifetime marker after the call. 4041 if (LifetimeSize) // In case we disabled lifetime markers. 4042 CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize); 4043 4044 // Generate the copy. 4045 I->copyInto(*this, AI); 4046 } else { 4047 // Skip the extra memcpy call. 4048 auto *T = V->getType()->getPointerElementType()->getPointerTo( 4049 CGM.getDataLayout().getAllocaAddrSpace()); 4050 IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast( 4051 *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T, 4052 true); 4053 } 4054 } 4055 break; 4056 } 4057 4058 case ABIArgInfo::Ignore: 4059 assert(NumIRArgs == 0); 4060 break; 4061 4062 case ABIArgInfo::Extend: 4063 case ABIArgInfo::Direct: { 4064 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) && 4065 ArgInfo.getCoerceToType() == ConvertType(info_it->type) && 4066 ArgInfo.getDirectOffset() == 0) { 4067 assert(NumIRArgs == 1); 4068 llvm::Value *V; 4069 if (!I->isAggregate()) 4070 V = I->getKnownRValue().getScalarVal(); 4071 else 4072 V = Builder.CreateLoad( 4073 I->hasLValue() ? I->getKnownLValue().getAddress(*this) 4074 : I->getKnownRValue().getAggregateAddress()); 4075 4076 // Implement swifterror by copying into a new swifterror argument. 4077 // We'll write back in the normal path out of the call. 4078 if (CallInfo.getExtParameterInfo(ArgNo).getABI() 4079 == ParameterABI::SwiftErrorResult) { 4080 assert(!swiftErrorTemp.isValid() && "multiple swifterror args"); 4081 4082 QualType pointeeTy = I->Ty->getPointeeType(); 4083 swiftErrorArg = 4084 Address(V, getContext().getTypeAlignInChars(pointeeTy)); 4085 4086 swiftErrorTemp = 4087 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp"); 4088 V = swiftErrorTemp.getPointer(); 4089 cast<llvm::AllocaInst>(V)->setSwiftError(true); 4090 4091 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg); 4092 Builder.CreateStore(errorValue, swiftErrorTemp); 4093 } 4094 4095 // We might have to widen integers, but we should never truncate. 4096 if (ArgInfo.getCoerceToType() != V->getType() && 4097 V->getType()->isIntegerTy()) 4098 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType()); 4099 4100 // If the argument doesn't match, perform a bitcast to coerce it. This 4101 // can happen due to trivial type mismatches. 4102 if (FirstIRArg < IRFuncTy->getNumParams() && 4103 V->getType() != IRFuncTy->getParamType(FirstIRArg)) 4104 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg)); 4105 4106 IRCallArgs[FirstIRArg] = V; 4107 break; 4108 } 4109 4110 // FIXME: Avoid the conversion through memory if possible. 4111 Address Src = Address::invalid(); 4112 if (!I->isAggregate()) { 4113 Src = CreateMemTemp(I->Ty, "coerce"); 4114 I->copyInto(*this, Src); 4115 } else { 4116 Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this) 4117 : I->getKnownRValue().getAggregateAddress(); 4118 } 4119 4120 // If the value is offset in memory, apply the offset now. 4121 Src = emitAddressAtOffset(*this, Src, ArgInfo); 4122 4123 // Fast-isel and the optimizer generally like scalar values better than 4124 // FCAs, so we flatten them if this is safe to do for this argument. 4125 llvm::StructType *STy = 4126 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType()); 4127 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) { 4128 llvm::Type *SrcTy = Src.getType()->getElementType(); 4129 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy); 4130 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy); 4131 4132 // If the source type is smaller than the destination type of the 4133 // coerce-to logic, copy the source value into a temp alloca the size 4134 // of the destination type to allow loading all of it. The bits past 4135 // the source value are left undef. 4136 if (SrcSize < DstSize) { 4137 Address TempAlloca 4138 = CreateTempAlloca(STy, Src.getAlignment(), 4139 Src.getName() + ".coerce"); 4140 Builder.CreateMemCpy(TempAlloca, Src, SrcSize); 4141 Src = TempAlloca; 4142 } else { 4143 Src = Builder.CreateBitCast(Src, 4144 STy->getPointerTo(Src.getAddressSpace())); 4145 } 4146 4147 assert(NumIRArgs == STy->getNumElements()); 4148 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 4149 Address EltPtr = Builder.CreateStructGEP(Src, i); 4150 llvm::Value *LI = Builder.CreateLoad(EltPtr); 4151 IRCallArgs[FirstIRArg + i] = LI; 4152 } 4153 } else { 4154 // In the simple case, just pass the coerced loaded value. 4155 assert(NumIRArgs == 1); 4156 IRCallArgs[FirstIRArg] = 4157 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this); 4158 } 4159 4160 break; 4161 } 4162 4163 case ABIArgInfo::CoerceAndExpand: { 4164 auto coercionType = ArgInfo.getCoerceAndExpandType(); 4165 auto layout = CGM.getDataLayout().getStructLayout(coercionType); 4166 4167 llvm::Value *tempSize = nullptr; 4168 Address addr = Address::invalid(); 4169 Address AllocaAddr = Address::invalid(); 4170 if (I->isAggregate()) { 4171 addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this) 4172 : I->getKnownRValue().getAggregateAddress(); 4173 4174 } else { 4175 RValue RV = I->getKnownRValue(); 4176 assert(RV.isScalar()); // complex should always just be direct 4177 4178 llvm::Type *scalarType = RV.getScalarVal()->getType(); 4179 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType); 4180 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType); 4181 4182 // Materialize to a temporary. 4183 addr = CreateTempAlloca( 4184 RV.getScalarVal()->getType(), 4185 CharUnits::fromQuantity(std::max( 4186 (unsigned)layout->getAlignment().value(), scalarAlign)), 4187 "tmp", 4188 /*ArraySize=*/nullptr, &AllocaAddr); 4189 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer()); 4190 4191 Builder.CreateStore(RV.getScalarVal(), addr); 4192 } 4193 4194 addr = Builder.CreateElementBitCast(addr, coercionType); 4195 4196 unsigned IRArgPos = FirstIRArg; 4197 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 4198 llvm::Type *eltType = coercionType->getElementType(i); 4199 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue; 4200 Address eltAddr = Builder.CreateStructGEP(addr, i); 4201 llvm::Value *elt = Builder.CreateLoad(eltAddr); 4202 IRCallArgs[IRArgPos++] = elt; 4203 } 4204 assert(IRArgPos == FirstIRArg + NumIRArgs); 4205 4206 if (tempSize) { 4207 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer()); 4208 } 4209 4210 break; 4211 } 4212 4213 case ABIArgInfo::Expand: 4214 unsigned IRArgPos = FirstIRArg; 4215 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos); 4216 assert(IRArgPos == FirstIRArg + NumIRArgs); 4217 break; 4218 } 4219 } 4220 4221 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this); 4222 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer(); 4223 4224 // If we're using inalloca, set up that argument. 4225 if (ArgMemory.isValid()) { 4226 llvm::Value *Arg = ArgMemory.getPointer(); 4227 if (CallInfo.isVariadic()) { 4228 // When passing non-POD arguments by value to variadic functions, we will 4229 // end up with a variadic prototype and an inalloca call site. In such 4230 // cases, we can't do any parameter mismatch checks. Give up and bitcast 4231 // the callee. 4232 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace(); 4233 CalleePtr = 4234 Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS)); 4235 } else { 4236 llvm::Type *LastParamTy = 4237 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1); 4238 if (Arg->getType() != LastParamTy) { 4239 #ifndef NDEBUG 4240 // Assert that these structs have equivalent element types. 4241 llvm::StructType *FullTy = CallInfo.getArgStruct(); 4242 llvm::StructType *DeclaredTy = cast<llvm::StructType>( 4243 cast<llvm::PointerType>(LastParamTy)->getElementType()); 4244 assert(DeclaredTy->getNumElements() == FullTy->getNumElements()); 4245 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(), 4246 DE = DeclaredTy->element_end(), 4247 FI = FullTy->element_begin(); 4248 DI != DE; ++DI, ++FI) 4249 assert(*DI == *FI); 4250 #endif 4251 Arg = Builder.CreateBitCast(Arg, LastParamTy); 4252 } 4253 } 4254 assert(IRFunctionArgs.hasInallocaArg()); 4255 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg; 4256 } 4257 4258 // 2. Prepare the function pointer. 4259 4260 // If the callee is a bitcast of a non-variadic function to have a 4261 // variadic function pointer type, check to see if we can remove the 4262 // bitcast. This comes up with unprototyped functions. 4263 // 4264 // This makes the IR nicer, but more importantly it ensures that we 4265 // can inline the function at -O0 if it is marked always_inline. 4266 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT, 4267 llvm::Value *Ptr) -> llvm::Function * { 4268 if (!CalleeFT->isVarArg()) 4269 return nullptr; 4270 4271 // Get underlying value if it's a bitcast 4272 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) { 4273 if (CE->getOpcode() == llvm::Instruction::BitCast) 4274 Ptr = CE->getOperand(0); 4275 } 4276 4277 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr); 4278 if (!OrigFn) 4279 return nullptr; 4280 4281 llvm::FunctionType *OrigFT = OrigFn->getFunctionType(); 4282 4283 // If the original type is variadic, or if any of the component types 4284 // disagree, we cannot remove the cast. 4285 if (OrigFT->isVarArg() || 4286 OrigFT->getNumParams() != CalleeFT->getNumParams() || 4287 OrigFT->getReturnType() != CalleeFT->getReturnType()) 4288 return nullptr; 4289 4290 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i) 4291 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i)) 4292 return nullptr; 4293 4294 return OrigFn; 4295 }; 4296 4297 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) { 4298 CalleePtr = OrigFn; 4299 IRFuncTy = OrigFn->getFunctionType(); 4300 } 4301 4302 // 3. Perform the actual call. 4303 4304 // Deactivate any cleanups that we're supposed to do immediately before 4305 // the call. 4306 if (!CallArgs.getCleanupsToDeactivate().empty()) 4307 deactivateArgCleanupsBeforeCall(*this, CallArgs); 4308 4309 // Assert that the arguments we computed match up. The IR verifier 4310 // will catch this, but this is a common enough source of problems 4311 // during IRGen changes that it's way better for debugging to catch 4312 // it ourselves here. 4313 #ifndef NDEBUG 4314 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg()); 4315 for (unsigned i = 0; i < IRCallArgs.size(); ++i) { 4316 // Inalloca argument can have different type. 4317 if (IRFunctionArgs.hasInallocaArg() && 4318 i == IRFunctionArgs.getInallocaArgNo()) 4319 continue; 4320 if (i < IRFuncTy->getNumParams()) 4321 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i)); 4322 } 4323 #endif 4324 4325 // Update the largest vector width if any arguments have vector types. 4326 for (unsigned i = 0; i < IRCallArgs.size(); ++i) { 4327 if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType())) 4328 LargestVectorWidth = std::max((uint64_t)LargestVectorWidth, 4329 VT->getPrimitiveSizeInBits().getFixedSize()); 4330 } 4331 4332 // Compute the calling convention and attributes. 4333 unsigned CallingConv; 4334 llvm::AttributeList Attrs; 4335 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo, 4336 Callee.getAbstractInfo(), Attrs, CallingConv, 4337 /*AttrOnCallSite=*/true); 4338 4339 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) 4340 if (FD->usesFPIntrin()) 4341 // All calls within a strictfp function are marked strictfp 4342 Attrs = 4343 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4344 llvm::Attribute::StrictFP); 4345 4346 // Apply some call-site-specific attributes. 4347 // TODO: work this into building the attribute set. 4348 4349 // Apply always_inline to all calls within flatten functions. 4350 // FIXME: should this really take priority over __try, below? 4351 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() && 4352 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) { 4353 Attrs = 4354 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4355 llvm::Attribute::AlwaysInline); 4356 } 4357 4358 // Disable inlining inside SEH __try blocks. 4359 if (isSEHTryScope()) { 4360 Attrs = 4361 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4362 llvm::Attribute::NoInline); 4363 } 4364 4365 // Decide whether to use a call or an invoke. 4366 bool CannotThrow; 4367 if (currentFunctionUsesSEHTry()) { 4368 // SEH cares about asynchronous exceptions, so everything can "throw." 4369 CannotThrow = false; 4370 } else if (isCleanupPadScope() && 4371 EHPersonality::get(*this).isMSVCXXPersonality()) { 4372 // The MSVC++ personality will implicitly terminate the program if an 4373 // exception is thrown during a cleanup outside of a try/catch. 4374 // We don't need to model anything in IR to get this behavior. 4375 CannotThrow = true; 4376 } else { 4377 // Otherwise, nounwind call sites will never throw. 4378 CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex, 4379 llvm::Attribute::NoUnwind); 4380 } 4381 4382 // If we made a temporary, be sure to clean up after ourselves. Note that we 4383 // can't depend on being inside of an ExprWithCleanups, so we need to manually 4384 // pop this cleanup later on. Being eager about this is OK, since this 4385 // temporary is 'invisible' outside of the callee. 4386 if (UnusedReturnSizePtr) 4387 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca, 4388 UnusedReturnSizePtr); 4389 4390 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest(); 4391 4392 SmallVector<llvm::OperandBundleDef, 1> BundleList = 4393 getBundlesForFunclet(CalleePtr); 4394 4395 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) 4396 if (FD->usesFPIntrin()) 4397 // All calls within a strictfp function are marked strictfp 4398 Attrs = 4399 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4400 llvm::Attribute::StrictFP); 4401 4402 // Emit the actual call/invoke instruction. 4403 llvm::CallBase *CI; 4404 if (!InvokeDest) { 4405 CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList); 4406 } else { 4407 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont"); 4408 CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs, 4409 BundleList); 4410 EmitBlock(Cont); 4411 } 4412 if (callOrInvoke) 4413 *callOrInvoke = CI; 4414 4415 // Apply the attributes and calling convention. 4416 CI->setAttributes(Attrs); 4417 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 4418 4419 // Apply various metadata. 4420 4421 if (!CI->getType()->isVoidTy()) 4422 CI->setName("call"); 4423 4424 // Update largest vector width from the return type. 4425 if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType())) 4426 LargestVectorWidth = std::max((uint64_t)LargestVectorWidth, 4427 VT->getPrimitiveSizeInBits().getFixedSize()); 4428 4429 // Insert instrumentation or attach profile metadata at indirect call sites. 4430 // For more details, see the comment before the definition of 4431 // IPVK_IndirectCallTarget in InstrProfData.inc. 4432 if (!CI->getCalledFunction()) 4433 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget, 4434 CI, CalleePtr); 4435 4436 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 4437 // optimizer it can aggressively ignore unwind edges. 4438 if (CGM.getLangOpts().ObjCAutoRefCount) 4439 AddObjCARCExceptionMetadata(CI); 4440 4441 // Suppress tail calls if requested. 4442 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) { 4443 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>()) 4444 Call->setTailCallKind(llvm::CallInst::TCK_NoTail); 4445 } 4446 4447 // Add metadata for calls to MSAllocator functions 4448 if (getDebugInfo() && TargetDecl && 4449 TargetDecl->hasAttr<MSAllocatorAttr>()) 4450 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc); 4451 4452 // 4. Finish the call. 4453 4454 // If the call doesn't return, finish the basic block and clear the 4455 // insertion point; this allows the rest of IRGen to discard 4456 // unreachable code. 4457 if (CI->doesNotReturn()) { 4458 if (UnusedReturnSizePtr) 4459 PopCleanupBlock(); 4460 4461 // Strip away the noreturn attribute to better diagnose unreachable UB. 4462 if (SanOpts.has(SanitizerKind::Unreachable)) { 4463 // Also remove from function since CallBase::hasFnAttr additionally checks 4464 // attributes of the called function. 4465 if (auto *F = CI->getCalledFunction()) 4466 F->removeFnAttr(llvm::Attribute::NoReturn); 4467 CI->removeAttribute(llvm::AttributeList::FunctionIndex, 4468 llvm::Attribute::NoReturn); 4469 4470 // Avoid incompatibility with ASan which relies on the `noreturn` 4471 // attribute to insert handler calls. 4472 if (SanOpts.hasOneOf(SanitizerKind::Address | 4473 SanitizerKind::KernelAddress)) { 4474 SanitizerScope SanScope(this); 4475 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder); 4476 Builder.SetInsertPoint(CI); 4477 auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 4478 llvm::FunctionCallee Fn = 4479 CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return"); 4480 EmitNounwindRuntimeCall(Fn); 4481 } 4482 } 4483 4484 EmitUnreachable(Loc); 4485 Builder.ClearInsertionPoint(); 4486 4487 // FIXME: For now, emit a dummy basic block because expr emitters in 4488 // generally are not ready to handle emitting expressions at unreachable 4489 // points. 4490 EnsureInsertPoint(); 4491 4492 // Return a reasonable RValue. 4493 return GetUndefRValue(RetTy); 4494 } 4495 4496 // Perform the swifterror writeback. 4497 if (swiftErrorTemp.isValid()) { 4498 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp); 4499 Builder.CreateStore(errorResult, swiftErrorArg); 4500 } 4501 4502 // Emit any call-associated writebacks immediately. Arguably this 4503 // should happen after any return-value munging. 4504 if (CallArgs.hasWritebacks()) 4505 emitWritebacks(*this, CallArgs); 4506 4507 // The stack cleanup for inalloca arguments has to run out of the normal 4508 // lexical order, so deactivate it and run it manually here. 4509 CallArgs.freeArgumentMemory(*this); 4510 4511 // Extract the return value. 4512 RValue Ret = [&] { 4513 switch (RetAI.getKind()) { 4514 case ABIArgInfo::CoerceAndExpand: { 4515 auto coercionType = RetAI.getCoerceAndExpandType(); 4516 4517 Address addr = SRetPtr; 4518 addr = Builder.CreateElementBitCast(addr, coercionType); 4519 4520 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType()); 4521 bool requiresExtract = isa<llvm::StructType>(CI->getType()); 4522 4523 unsigned unpaddedIndex = 0; 4524 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 4525 llvm::Type *eltType = coercionType->getElementType(i); 4526 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue; 4527 Address eltAddr = Builder.CreateStructGEP(addr, i); 4528 llvm::Value *elt = CI; 4529 if (requiresExtract) 4530 elt = Builder.CreateExtractValue(elt, unpaddedIndex++); 4531 else 4532 assert(unpaddedIndex == 0); 4533 Builder.CreateStore(elt, eltAddr); 4534 } 4535 // FALLTHROUGH 4536 LLVM_FALLTHROUGH; 4537 } 4538 4539 case ABIArgInfo::InAlloca: 4540 case ABIArgInfo::Indirect: { 4541 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation()); 4542 if (UnusedReturnSizePtr) 4543 PopCleanupBlock(); 4544 return ret; 4545 } 4546 4547 case ABIArgInfo::Ignore: 4548 // If we are ignoring an argument that had a result, make sure to 4549 // construct the appropriate return value for our caller. 4550 return GetUndefRValue(RetTy); 4551 4552 case ABIArgInfo::Extend: 4553 case ABIArgInfo::Direct: { 4554 llvm::Type *RetIRTy = ConvertType(RetTy); 4555 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) { 4556 switch (getEvaluationKind(RetTy)) { 4557 case TEK_Complex: { 4558 llvm::Value *Real = Builder.CreateExtractValue(CI, 0); 4559 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1); 4560 return RValue::getComplex(std::make_pair(Real, Imag)); 4561 } 4562 case TEK_Aggregate: { 4563 Address DestPtr = ReturnValue.getValue(); 4564 bool DestIsVolatile = ReturnValue.isVolatile(); 4565 4566 if (!DestPtr.isValid()) { 4567 DestPtr = CreateMemTemp(RetTy, "agg.tmp"); 4568 DestIsVolatile = false; 4569 } 4570 BuildAggStore(*this, CI, DestPtr, DestIsVolatile); 4571 return RValue::getAggregate(DestPtr); 4572 } 4573 case TEK_Scalar: { 4574 // If the argument doesn't match, perform a bitcast to coerce it. This 4575 // can happen due to trivial type mismatches. 4576 llvm::Value *V = CI; 4577 if (V->getType() != RetIRTy) 4578 V = Builder.CreateBitCast(V, RetIRTy); 4579 return RValue::get(V); 4580 } 4581 } 4582 llvm_unreachable("bad evaluation kind"); 4583 } 4584 4585 Address DestPtr = ReturnValue.getValue(); 4586 bool DestIsVolatile = ReturnValue.isVolatile(); 4587 4588 if (!DestPtr.isValid()) { 4589 DestPtr = CreateMemTemp(RetTy, "coerce"); 4590 DestIsVolatile = false; 4591 } 4592 4593 // If the value is offset in memory, apply the offset now. 4594 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI); 4595 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this); 4596 4597 return convertTempToRValue(DestPtr, RetTy, SourceLocation()); 4598 } 4599 4600 case ABIArgInfo::Expand: 4601 llvm_unreachable("Invalid ABI kind for return argument"); 4602 } 4603 4604 llvm_unreachable("Unhandled ABIArgInfo::Kind"); 4605 } (); 4606 4607 // Emit the assume_aligned check on the return value. 4608 if (Ret.isScalar() && TargetDecl) { 4609 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) { 4610 llvm::Value *OffsetValue = nullptr; 4611 if (const auto *Offset = AA->getOffset()) 4612 OffsetValue = EmitScalarExpr(Offset); 4613 4614 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment()); 4615 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment); 4616 EmitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, AA->getLocation(), 4617 AlignmentCI, OffsetValue); 4618 } else if (const auto *AA = TargetDecl->getAttr<AllocAlignAttr>()) { 4619 llvm::Value *AlignmentVal = CallArgs[AA->getParamIndex().getLLVMIndex()] 4620 .getRValue(*this) 4621 .getScalarVal(); 4622 EmitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, AA->getLocation(), 4623 AlignmentVal); 4624 } 4625 } 4626 4627 // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though 4628 // we can't use the full cleanup mechanism. 4629 for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall) 4630 LifetimeEnd.Emit(*this, /*Flags=*/{}); 4631 4632 return Ret; 4633 } 4634 4635 CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const { 4636 if (isVirtual()) { 4637 const CallExpr *CE = getVirtualCallExpr(); 4638 return CGF.CGM.getCXXABI().getVirtualFunctionPointer( 4639 CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(), 4640 CE ? CE->getBeginLoc() : SourceLocation()); 4641 } 4642 4643 return *this; 4644 } 4645 4646 /* VarArg handling */ 4647 4648 Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) { 4649 VAListAddr = VE->isMicrosoftABI() 4650 ? EmitMSVAListRef(VE->getSubExpr()) 4651 : EmitVAListRef(VE->getSubExpr()); 4652 QualType Ty = VE->getType(); 4653 if (VE->isMicrosoftABI()) 4654 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty); 4655 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty); 4656 } 4657