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