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