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