1 //===--- CGCall.cpp - Encapsulate calling convention details --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // These classes wrap the information about a call or function 11 // definition used to handle ABI compliancy. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "CGCall.h" 16 #include "ABIInfo.h" 17 #include "CGBlocks.h" 18 #include "CGCXXABI.h" 19 #include "CGCleanup.h" 20 #include "CodeGenFunction.h" 21 #include "CodeGenModule.h" 22 #include "TargetInfo.h" 23 #include "clang/AST/Decl.h" 24 #include "clang/AST/DeclCXX.h" 25 #include "clang/AST/DeclObjC.h" 26 #include "clang/Basic/TargetBuiltins.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/CodeGen/CGFunctionInfo.h" 29 #include "clang/Frontend/CodeGenOptions.h" 30 #include "llvm/ADT/StringExtras.h" 31 #include "llvm/IR/Attributes.h" 32 #include "llvm/IR/CallSite.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/InlineAsm.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/Transforms/Utils/Local.h" 38 using namespace clang; 39 using namespace CodeGen; 40 41 /***/ 42 43 static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) { 44 switch (CC) { 45 default: return llvm::CallingConv::C; 46 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall; 47 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall; 48 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall; 49 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64; 50 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV; 51 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS; 52 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 53 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI; 54 // TODO: Add support for __pascal to LLVM. 55 case CC_X86Pascal: return llvm::CallingConv::C; 56 // TODO: Add support for __vectorcall to LLVM. 57 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall; 58 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC; 59 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL; 60 } 61 } 62 63 /// Derives the 'this' type for codegen purposes, i.e. ignoring method 64 /// qualification. 65 /// FIXME: address space qualification? 66 static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) { 67 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal(); 68 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy)); 69 } 70 71 /// Returns the canonical formal type of the given C++ method. 72 static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) { 73 return MD->getType()->getCanonicalTypeUnqualified() 74 .getAs<FunctionProtoType>(); 75 } 76 77 /// Returns the "extra-canonicalized" return type, which discards 78 /// qualifiers on the return type. Codegen doesn't care about them, 79 /// and it makes ABI code a little easier to be able to assume that 80 /// all parameter and return types are top-level unqualified. 81 static CanQualType GetReturnType(QualType RetTy) { 82 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType(); 83 } 84 85 /// Arrange the argument and result information for a value of the given 86 /// unprototyped freestanding function type. 87 const CGFunctionInfo & 88 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) { 89 // When translating an unprototyped function type, always use a 90 // variadic type. 91 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(), 92 /*instanceMethod=*/false, 93 /*chainCall=*/false, None, 94 FTNP->getExtInfo(), RequiredArgs(0)); 95 } 96 97 /// Adds the formal paramaters in FPT to the given prefix. If any parameter in 98 /// FPT has pass_object_size attrs, then we'll add parameters for those, too. 99 static void appendParameterTypes(const CodeGenTypes &CGT, 100 SmallVectorImpl<CanQualType> &prefix, 101 const CanQual<FunctionProtoType> &FPT, 102 const FunctionDecl *FD) { 103 // Fast path: unknown target. 104 if (FD == nullptr) { 105 prefix.append(FPT->param_type_begin(), FPT->param_type_end()); 106 return; 107 } 108 109 // In the vast majority cases, we'll have precisely FPT->getNumParams() 110 // parameters; the only thing that can change this is the presence of 111 // pass_object_size. So, we preallocate for the common case. 112 prefix.reserve(prefix.size() + FPT->getNumParams()); 113 114 assert(FD->getNumParams() == FPT->getNumParams()); 115 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) { 116 prefix.push_back(FPT->getParamType(I)); 117 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>()) 118 prefix.push_back(CGT.getContext().getSizeType()); 119 } 120 } 121 122 /// Arrange the LLVM function layout for a value of the given function 123 /// type, on top of any implicit parameters already stored. 124 static const CGFunctionInfo & 125 arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod, 126 SmallVectorImpl<CanQualType> &prefix, 127 CanQual<FunctionProtoType> FTP, 128 const FunctionDecl *FD) { 129 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size()); 130 // FIXME: Kill copy. 131 appendParameterTypes(CGT, prefix, FTP, FD); 132 CanQualType resultType = FTP->getReturnType().getUnqualifiedType(); 133 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod, 134 /*chainCall=*/false, prefix, 135 FTP->getExtInfo(), required); 136 } 137 138 /// Arrange the argument and result information for a value of the 139 /// given freestanding function type. 140 const CGFunctionInfo & 141 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP, 142 const FunctionDecl *FD) { 143 SmallVector<CanQualType, 16> argTypes; 144 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes, 145 FTP, FD); 146 } 147 148 static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) { 149 // Set the appropriate calling convention for the Function. 150 if (D->hasAttr<StdCallAttr>()) 151 return CC_X86StdCall; 152 153 if (D->hasAttr<FastCallAttr>()) 154 return CC_X86FastCall; 155 156 if (D->hasAttr<ThisCallAttr>()) 157 return CC_X86ThisCall; 158 159 if (D->hasAttr<VectorCallAttr>()) 160 return CC_X86VectorCall; 161 162 if (D->hasAttr<PascalAttr>()) 163 return CC_X86Pascal; 164 165 if (PcsAttr *PCS = D->getAttr<PcsAttr>()) 166 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP); 167 168 if (D->hasAttr<IntelOclBiccAttr>()) 169 return CC_IntelOclBicc; 170 171 if (D->hasAttr<MSABIAttr>()) 172 return IsWindows ? CC_C : CC_X86_64Win64; 173 174 if (D->hasAttr<SysVABIAttr>()) 175 return IsWindows ? CC_X86_64SysV : CC_C; 176 177 return CC_C; 178 } 179 180 /// Arrange the argument and result information for a call to an 181 /// unknown C++ non-static member function of the given abstract type. 182 /// (Zero value of RD means we don't have any meaningful "this" argument type, 183 /// so fall back to a generic pointer type). 184 /// The member function must be an ordinary function, i.e. not a 185 /// constructor or destructor. 186 const CGFunctionInfo & 187 CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD, 188 const FunctionProtoType *FTP, 189 const CXXMethodDecl *MD) { 190 SmallVector<CanQualType, 16> argTypes; 191 192 // Add the 'this' pointer. 193 if (RD) 194 argTypes.push_back(GetThisType(Context, RD)); 195 else 196 argTypes.push_back(Context.VoidPtrTy); 197 198 return ::arrangeLLVMFunctionInfo( 199 *this, true, argTypes, 200 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD); 201 } 202 203 /// Arrange the argument and result information for a declaration or 204 /// definition of the given C++ non-static member function. The 205 /// member function must be an ordinary function, i.e. not a 206 /// constructor or destructor. 207 const CGFunctionInfo & 208 CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) { 209 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!"); 210 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!"); 211 212 CanQual<FunctionProtoType> prototype = GetFormalType(MD); 213 214 if (MD->isInstance()) { 215 // The abstract case is perfectly fine. 216 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD); 217 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD); 218 } 219 220 return arrangeFreeFunctionType(prototype, MD); 221 } 222 223 const CGFunctionInfo & 224 CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD, 225 StructorType Type) { 226 227 SmallVector<CanQualType, 16> argTypes; 228 argTypes.push_back(GetThisType(Context, MD->getParent())); 229 230 GlobalDecl GD; 231 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) { 232 GD = GlobalDecl(CD, toCXXCtorType(Type)); 233 } else { 234 auto *DD = dyn_cast<CXXDestructorDecl>(MD); 235 GD = GlobalDecl(DD, toCXXDtorType(Type)); 236 } 237 238 CanQual<FunctionProtoType> FTP = GetFormalType(MD); 239 240 // Add the formal parameters. 241 appendParameterTypes(*this, argTypes, FTP, MD); 242 243 TheCXXABI.buildStructorSignature(MD, Type, argTypes); 244 245 RequiredArgs required = 246 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All); 247 248 FunctionType::ExtInfo extInfo = FTP->getExtInfo(); 249 CanQualType resultType = TheCXXABI.HasThisReturn(GD) 250 ? argTypes.front() 251 : TheCXXABI.hasMostDerivedReturn(GD) 252 ? CGM.getContext().VoidPtrTy 253 : Context.VoidTy; 254 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true, 255 /*chainCall=*/false, argTypes, extInfo, 256 required); 257 } 258 259 /// Arrange a call to a C++ method, passing the given arguments. 260 const CGFunctionInfo & 261 CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args, 262 const CXXConstructorDecl *D, 263 CXXCtorType CtorKind, 264 unsigned ExtraArgs) { 265 // FIXME: Kill copy. 266 SmallVector<CanQualType, 16> ArgTypes; 267 for (const auto &Arg : args) 268 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty)); 269 270 CanQual<FunctionProtoType> FPT = GetFormalType(D); 271 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs); 272 GlobalDecl GD(D, CtorKind); 273 CanQualType ResultType = TheCXXABI.HasThisReturn(GD) 274 ? ArgTypes.front() 275 : TheCXXABI.hasMostDerivedReturn(GD) 276 ? CGM.getContext().VoidPtrTy 277 : Context.VoidTy; 278 279 FunctionType::ExtInfo Info = FPT->getExtInfo(); 280 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true, 281 /*chainCall=*/false, ArgTypes, Info, 282 Required); 283 } 284 285 /// Arrange the argument and result information for the declaration or 286 /// definition of the given function. 287 const CGFunctionInfo & 288 CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) { 289 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 290 if (MD->isInstance()) 291 return arrangeCXXMethodDeclaration(MD); 292 293 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified(); 294 295 assert(isa<FunctionType>(FTy)); 296 297 // When declaring a function without a prototype, always use a 298 // non-variadic type. 299 if (isa<FunctionNoProtoType>(FTy)) { 300 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>(); 301 return arrangeLLVMFunctionInfo( 302 noProto->getReturnType(), /*instanceMethod=*/false, 303 /*chainCall=*/false, None, noProto->getExtInfo(), RequiredArgs::All); 304 } 305 306 assert(isa<FunctionProtoType>(FTy)); 307 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>(), FD); 308 } 309 310 /// Arrange the argument and result information for the declaration or 311 /// definition of an Objective-C method. 312 const CGFunctionInfo & 313 CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) { 314 // It happens that this is the same as a call with no optional 315 // arguments, except also using the formal 'self' type. 316 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType()); 317 } 318 319 /// Arrange the argument and result information for the function type 320 /// through which to perform a send to the given Objective-C method, 321 /// using the given receiver type. The receiver type is not always 322 /// the 'self' type of the method or even an Objective-C pointer type. 323 /// This is *not* the right method for actually performing such a 324 /// message send, due to the possibility of optional arguments. 325 const CGFunctionInfo & 326 CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD, 327 QualType receiverType) { 328 SmallVector<CanQualType, 16> argTys; 329 argTys.push_back(Context.getCanonicalParamType(receiverType)); 330 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType())); 331 // FIXME: Kill copy? 332 for (const auto *I : MD->params()) { 333 argTys.push_back(Context.getCanonicalParamType(I->getType())); 334 } 335 336 FunctionType::ExtInfo einfo; 337 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows(); 338 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows)); 339 340 if (getContext().getLangOpts().ObjCAutoRefCount && 341 MD->hasAttr<NSReturnsRetainedAttr>()) 342 einfo = einfo.withProducesResult(true); 343 344 RequiredArgs required = 345 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All); 346 347 return arrangeLLVMFunctionInfo( 348 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false, 349 /*chainCall=*/false, argTys, einfo, required); 350 } 351 352 const CGFunctionInfo & 353 CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) { 354 // FIXME: Do we need to handle ObjCMethodDecl? 355 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 356 357 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 358 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType())); 359 360 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) 361 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType())); 362 363 return arrangeFunctionDeclaration(FD); 364 } 365 366 /// Arrange a thunk that takes 'this' as the first parameter followed by 367 /// varargs. Return a void pointer, regardless of the actual return type. 368 /// The body of the thunk will end in a musttail call to a function of the 369 /// correct type, and the caller will bitcast the function to the correct 370 /// prototype. 371 const CGFunctionInfo & 372 CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) { 373 assert(MD->isVirtual() && "only virtual memptrs have thunks"); 374 CanQual<FunctionProtoType> FTP = GetFormalType(MD); 375 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) }; 376 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false, 377 /*chainCall=*/false, ArgTys, 378 FTP->getExtInfo(), RequiredArgs(1)); 379 } 380 381 const CGFunctionInfo & 382 CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD, 383 CXXCtorType CT) { 384 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure); 385 386 CanQual<FunctionProtoType> FTP = GetFormalType(CD); 387 SmallVector<CanQualType, 2> ArgTys; 388 const CXXRecordDecl *RD = CD->getParent(); 389 ArgTys.push_back(GetThisType(Context, RD)); 390 if (CT == Ctor_CopyingClosure) 391 ArgTys.push_back(*FTP->param_type_begin()); 392 if (RD->getNumVBases() > 0) 393 ArgTys.push_back(Context.IntTy); 394 CallingConv CC = Context.getDefaultCallingConvention( 395 /*IsVariadic=*/false, /*IsCXXMethod=*/true); 396 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true, 397 /*chainCall=*/false, ArgTys, 398 FunctionType::ExtInfo(CC), RequiredArgs::All); 399 } 400 401 /// Arrange a call as unto a free function, except possibly with an 402 /// additional number of formal parameters considered required. 403 static const CGFunctionInfo & 404 arrangeFreeFunctionLikeCall(CodeGenTypes &CGT, 405 CodeGenModule &CGM, 406 const CallArgList &args, 407 const FunctionType *fnType, 408 unsigned numExtraRequiredArgs, 409 bool chainCall) { 410 assert(args.size() >= numExtraRequiredArgs); 411 412 // In most cases, there are no optional arguments. 413 RequiredArgs required = RequiredArgs::All; 414 415 // If we have a variadic prototype, the required arguments are the 416 // extra prefix plus the arguments in the prototype. 417 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) { 418 if (proto->isVariadic()) 419 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs); 420 421 // If we don't have a prototype at all, but we're supposed to 422 // explicitly use the variadic convention for unprototyped calls, 423 // treat all of the arguments as required but preserve the nominal 424 // possibility of variadics. 425 } else if (CGM.getTargetCodeGenInfo() 426 .isNoProtoCallVariadic(args, 427 cast<FunctionNoProtoType>(fnType))) { 428 required = RequiredArgs(args.size()); 429 } 430 431 // FIXME: Kill copy. 432 SmallVector<CanQualType, 16> argTypes; 433 for (const auto &arg : args) 434 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty)); 435 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()), 436 /*instanceMethod=*/false, chainCall, 437 argTypes, fnType->getExtInfo(), required); 438 } 439 440 /// Figure out the rules for calling a function with the given formal 441 /// type using the given arguments. The arguments are necessary 442 /// because the function might be unprototyped, in which case it's 443 /// target-dependent in crazy ways. 444 const CGFunctionInfo & 445 CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args, 446 const FunctionType *fnType, 447 bool chainCall) { 448 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 449 chainCall ? 1 : 0, chainCall); 450 } 451 452 /// A block function call is essentially a free-function call with an 453 /// extra implicit argument. 454 const CGFunctionInfo & 455 CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args, 456 const FunctionType *fnType) { 457 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1, 458 /*chainCall=*/false); 459 } 460 461 const CGFunctionInfo & 462 CodeGenTypes::arrangeFreeFunctionCall(QualType resultType, 463 const CallArgList &args, 464 FunctionType::ExtInfo info, 465 RequiredArgs required) { 466 // FIXME: Kill copy. 467 SmallVector<CanQualType, 16> argTypes; 468 for (const auto &Arg : args) 469 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty)); 470 return arrangeLLVMFunctionInfo( 471 GetReturnType(resultType), /*instanceMethod=*/false, 472 /*chainCall=*/false, argTypes, info, required); 473 } 474 475 /// Arrange a call to a C++ method, passing the given arguments. 476 const CGFunctionInfo & 477 CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args, 478 const FunctionProtoType *FPT, 479 RequiredArgs required) { 480 // FIXME: Kill copy. 481 SmallVector<CanQualType, 16> argTypes; 482 for (const auto &Arg : args) 483 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty)); 484 485 FunctionType::ExtInfo info = FPT->getExtInfo(); 486 return arrangeLLVMFunctionInfo( 487 GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true, 488 /*chainCall=*/false, argTypes, info, required); 489 } 490 491 const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration( 492 QualType resultType, const FunctionArgList &args, 493 const FunctionType::ExtInfo &info, bool isVariadic) { 494 // FIXME: Kill copy. 495 SmallVector<CanQualType, 16> argTypes; 496 for (auto Arg : args) 497 argTypes.push_back(Context.getCanonicalParamType(Arg->getType())); 498 499 RequiredArgs required = 500 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All); 501 return arrangeLLVMFunctionInfo( 502 GetReturnType(resultType), /*instanceMethod=*/false, 503 /*chainCall=*/false, argTypes, info, required); 504 } 505 506 const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() { 507 return arrangeLLVMFunctionInfo( 508 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false, 509 None, FunctionType::ExtInfo(), RequiredArgs::All); 510 } 511 512 /// Arrange the argument and result information for an abstract value 513 /// of a given function type. This is the method which all of the 514 /// above functions ultimately defer to. 515 const CGFunctionInfo & 516 CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType, 517 bool instanceMethod, 518 bool chainCall, 519 ArrayRef<CanQualType> argTypes, 520 FunctionType::ExtInfo info, 521 RequiredArgs required) { 522 assert(std::all_of(argTypes.begin(), argTypes.end(), 523 std::mem_fun_ref(&CanQualType::isCanonicalAsParam))); 524 525 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC()); 526 527 // Lookup or create unique function info. 528 llvm::FoldingSetNodeID ID; 529 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required, 530 resultType, argTypes); 531 532 void *insertPos = nullptr; 533 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos); 534 if (FI) 535 return *FI; 536 537 // Construct the function info. We co-allocate the ArgInfos. 538 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info, 539 resultType, argTypes, required); 540 FunctionInfos.InsertNode(FI, insertPos); 541 542 bool inserted = FunctionsBeingProcessed.insert(FI).second; 543 (void)inserted; 544 assert(inserted && "Recursively being processed?"); 545 546 // Compute ABI information. 547 getABIInfo().computeInfo(*FI); 548 549 // Loop over all of the computed argument and return value info. If any of 550 // them are direct or extend without a specified coerce type, specify the 551 // default now. 552 ABIArgInfo &retInfo = FI->getReturnInfo(); 553 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr) 554 retInfo.setCoerceToType(ConvertType(FI->getReturnType())); 555 556 for (auto &I : FI->arguments()) 557 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr) 558 I.info.setCoerceToType(ConvertType(I.type)); 559 560 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased; 561 assert(erased && "Not in set?"); 562 563 return *FI; 564 } 565 566 CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC, 567 bool instanceMethod, 568 bool chainCall, 569 const FunctionType::ExtInfo &info, 570 CanQualType resultType, 571 ArrayRef<CanQualType> argTypes, 572 RequiredArgs required) { 573 void *buffer = operator new(totalSizeToAlloc<ArgInfo>(argTypes.size() + 1)); 574 CGFunctionInfo *FI = new(buffer) CGFunctionInfo(); 575 FI->CallingConvention = llvmCC; 576 FI->EffectiveCallingConvention = llvmCC; 577 FI->ASTCallingConvention = info.getCC(); 578 FI->InstanceMethod = instanceMethod; 579 FI->ChainCall = chainCall; 580 FI->NoReturn = info.getNoReturn(); 581 FI->ReturnsRetained = info.getProducesResult(); 582 FI->Required = required; 583 FI->HasRegParm = info.getHasRegParm(); 584 FI->RegParm = info.getRegParm(); 585 FI->ArgStruct = nullptr; 586 FI->ArgStructAlign = 0; 587 FI->NumArgs = argTypes.size(); 588 FI->getArgsBuffer()[0].type = resultType; 589 for (unsigned i = 0, e = argTypes.size(); i != e; ++i) 590 FI->getArgsBuffer()[i + 1].type = argTypes[i]; 591 return FI; 592 } 593 594 /***/ 595 596 namespace { 597 // ABIArgInfo::Expand implementation. 598 599 // Specifies the way QualType passed as ABIArgInfo::Expand is expanded. 600 struct TypeExpansion { 601 enum TypeExpansionKind { 602 // Elements of constant arrays are expanded recursively. 603 TEK_ConstantArray, 604 // Record fields are expanded recursively (but if record is a union, only 605 // the field with the largest size is expanded). 606 TEK_Record, 607 // For complex types, real and imaginary parts are expanded recursively. 608 TEK_Complex, 609 // All other types are not expandable. 610 TEK_None 611 }; 612 613 const TypeExpansionKind Kind; 614 615 TypeExpansion(TypeExpansionKind K) : Kind(K) {} 616 virtual ~TypeExpansion() {} 617 }; 618 619 struct ConstantArrayExpansion : TypeExpansion { 620 QualType EltTy; 621 uint64_t NumElts; 622 623 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts) 624 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {} 625 static bool classof(const TypeExpansion *TE) { 626 return TE->Kind == TEK_ConstantArray; 627 } 628 }; 629 630 struct RecordExpansion : TypeExpansion { 631 SmallVector<const CXXBaseSpecifier *, 1> Bases; 632 633 SmallVector<const FieldDecl *, 1> Fields; 634 635 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases, 636 SmallVector<const FieldDecl *, 1> &&Fields) 637 : TypeExpansion(TEK_Record), Bases(std::move(Bases)), 638 Fields(std::move(Fields)) {} 639 static bool classof(const TypeExpansion *TE) { 640 return TE->Kind == TEK_Record; 641 } 642 }; 643 644 struct ComplexExpansion : TypeExpansion { 645 QualType EltTy; 646 647 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {} 648 static bool classof(const TypeExpansion *TE) { 649 return TE->Kind == TEK_Complex; 650 } 651 }; 652 653 struct NoExpansion : TypeExpansion { 654 NoExpansion() : TypeExpansion(TEK_None) {} 655 static bool classof(const TypeExpansion *TE) { 656 return TE->Kind == TEK_None; 657 } 658 }; 659 } // namespace 660 661 static std::unique_ptr<TypeExpansion> 662 getTypeExpansion(QualType Ty, const ASTContext &Context) { 663 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 664 return llvm::make_unique<ConstantArrayExpansion>( 665 AT->getElementType(), AT->getSize().getZExtValue()); 666 } 667 if (const RecordType *RT = Ty->getAs<RecordType>()) { 668 SmallVector<const CXXBaseSpecifier *, 1> Bases; 669 SmallVector<const FieldDecl *, 1> Fields; 670 const RecordDecl *RD = RT->getDecl(); 671 assert(!RD->hasFlexibleArrayMember() && 672 "Cannot expand structure with flexible array."); 673 if (RD->isUnion()) { 674 // Unions can be here only in degenerative cases - all the fields are same 675 // after flattening. Thus we have to use the "largest" field. 676 const FieldDecl *LargestFD = nullptr; 677 CharUnits UnionSize = CharUnits::Zero(); 678 679 for (const auto *FD : RD->fields()) { 680 // Skip zero length bitfields. 681 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0) 682 continue; 683 assert(!FD->isBitField() && 684 "Cannot expand structure with bit-field members."); 685 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType()); 686 if (UnionSize < FieldSize) { 687 UnionSize = FieldSize; 688 LargestFD = FD; 689 } 690 } 691 if (LargestFD) 692 Fields.push_back(LargestFD); 693 } else { 694 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 695 assert(!CXXRD->isDynamicClass() && 696 "cannot expand vtable pointers in dynamic classes"); 697 for (const CXXBaseSpecifier &BS : CXXRD->bases()) 698 Bases.push_back(&BS); 699 } 700 701 for (const auto *FD : RD->fields()) { 702 // Skip zero length bitfields. 703 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0) 704 continue; 705 assert(!FD->isBitField() && 706 "Cannot expand structure with bit-field members."); 707 Fields.push_back(FD); 708 } 709 } 710 return llvm::make_unique<RecordExpansion>(std::move(Bases), 711 std::move(Fields)); 712 } 713 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 714 return llvm::make_unique<ComplexExpansion>(CT->getElementType()); 715 } 716 return llvm::make_unique<NoExpansion>(); 717 } 718 719 static int getExpansionSize(QualType Ty, const ASTContext &Context) { 720 auto Exp = getTypeExpansion(Ty, Context); 721 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 722 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context); 723 } 724 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 725 int Res = 0; 726 for (auto BS : RExp->Bases) 727 Res += getExpansionSize(BS->getType(), Context); 728 for (auto FD : RExp->Fields) 729 Res += getExpansionSize(FD->getType(), Context); 730 return Res; 731 } 732 if (isa<ComplexExpansion>(Exp.get())) 733 return 2; 734 assert(isa<NoExpansion>(Exp.get())); 735 return 1; 736 } 737 738 void 739 CodeGenTypes::getExpandedTypes(QualType Ty, 740 SmallVectorImpl<llvm::Type *>::iterator &TI) { 741 auto Exp = getTypeExpansion(Ty, Context); 742 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 743 for (int i = 0, n = CAExp->NumElts; i < n; i++) { 744 getExpandedTypes(CAExp->EltTy, TI); 745 } 746 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 747 for (auto BS : RExp->Bases) 748 getExpandedTypes(BS->getType(), TI); 749 for (auto FD : RExp->Fields) 750 getExpandedTypes(FD->getType(), TI); 751 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) { 752 llvm::Type *EltTy = ConvertType(CExp->EltTy); 753 *TI++ = EltTy; 754 *TI++ = EltTy; 755 } else { 756 assert(isa<NoExpansion>(Exp.get())); 757 *TI++ = ConvertType(Ty); 758 } 759 } 760 761 static void forConstantArrayExpansion(CodeGenFunction &CGF, 762 ConstantArrayExpansion *CAE, 763 Address BaseAddr, 764 llvm::function_ref<void(Address)> Fn) { 765 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy); 766 CharUnits EltAlign = 767 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize); 768 769 for (int i = 0, n = CAE->NumElts; i < n; i++) { 770 llvm::Value *EltAddr = 771 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i); 772 Fn(Address(EltAddr, EltAlign)); 773 } 774 } 775 776 void CodeGenFunction::ExpandTypeFromArgs( 777 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) { 778 assert(LV.isSimple() && 779 "Unexpected non-simple lvalue during struct expansion."); 780 781 auto Exp = getTypeExpansion(Ty, getContext()); 782 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 783 forConstantArrayExpansion(*this, CAExp, LV.getAddress(), 784 [&](Address EltAddr) { 785 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy); 786 ExpandTypeFromArgs(CAExp->EltTy, LV, AI); 787 }); 788 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 789 Address This = LV.getAddress(); 790 for (const CXXBaseSpecifier *BS : RExp->Bases) { 791 // Perform a single step derived-to-base conversion. 792 Address Base = 793 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1, 794 /*NullCheckValue=*/false, SourceLocation()); 795 LValue SubLV = MakeAddrLValue(Base, BS->getType()); 796 797 // Recurse onto bases. 798 ExpandTypeFromArgs(BS->getType(), SubLV, AI); 799 } 800 for (auto FD : RExp->Fields) { 801 // FIXME: What are the right qualifiers here? 802 LValue SubLV = EmitLValueForField(LV, FD); 803 ExpandTypeFromArgs(FD->getType(), SubLV, AI); 804 } 805 } else if (isa<ComplexExpansion>(Exp.get())) { 806 auto realValue = *AI++; 807 auto imagValue = *AI++; 808 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true); 809 } else { 810 assert(isa<NoExpansion>(Exp.get())); 811 EmitStoreThroughLValue(RValue::get(*AI++), LV); 812 } 813 } 814 815 void CodeGenFunction::ExpandTypeToArgs( 816 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy, 817 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) { 818 auto Exp = getTypeExpansion(Ty, getContext()); 819 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 820 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(), 821 [&](Address EltAddr) { 822 RValue EltRV = 823 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()); 824 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos); 825 }); 826 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 827 Address This = RV.getAggregateAddress(); 828 for (const CXXBaseSpecifier *BS : RExp->Bases) { 829 // Perform a single step derived-to-base conversion. 830 Address Base = 831 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1, 832 /*NullCheckValue=*/false, SourceLocation()); 833 RValue BaseRV = RValue::getAggregate(Base); 834 835 // Recurse onto bases. 836 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs, 837 IRCallArgPos); 838 } 839 840 LValue LV = MakeAddrLValue(This, Ty); 841 for (auto FD : RExp->Fields) { 842 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation()); 843 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs, 844 IRCallArgPos); 845 } 846 } else if (isa<ComplexExpansion>(Exp.get())) { 847 ComplexPairTy CV = RV.getComplexVal(); 848 IRCallArgs[IRCallArgPos++] = CV.first; 849 IRCallArgs[IRCallArgPos++] = CV.second; 850 } else { 851 assert(isa<NoExpansion>(Exp.get())); 852 assert(RV.isScalar() && 853 "Unexpected non-scalar rvalue during struct expansion."); 854 855 // Insert a bitcast as needed. 856 llvm::Value *V = RV.getScalarVal(); 857 if (IRCallArgPos < IRFuncTy->getNumParams() && 858 V->getType() != IRFuncTy->getParamType(IRCallArgPos)) 859 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos)); 860 861 IRCallArgs[IRCallArgPos++] = V; 862 } 863 } 864 865 /// Create a temporary allocation for the purposes of coercion. 866 static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty, 867 CharUnits MinAlign) { 868 // Don't use an alignment that's worse than what LLVM would prefer. 869 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty); 870 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign)); 871 872 return CGF.CreateTempAlloca(Ty, Align); 873 } 874 875 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are 876 /// accessing some number of bytes out of it, try to gep into the struct to get 877 /// at its inner goodness. Dive as deep as possible without entering an element 878 /// with an in-memory size smaller than DstSize. 879 static Address 880 EnterStructPointerForCoercedAccess(Address SrcPtr, 881 llvm::StructType *SrcSTy, 882 uint64_t DstSize, CodeGenFunction &CGF) { 883 // We can't dive into a zero-element struct. 884 if (SrcSTy->getNumElements() == 0) return SrcPtr; 885 886 llvm::Type *FirstElt = SrcSTy->getElementType(0); 887 888 // If the first elt is at least as large as what we're looking for, or if the 889 // first element is the same size as the whole struct, we can enter it. The 890 // comparison must be made on the store size and not the alloca size. Using 891 // the alloca size may overstate the size of the load. 892 uint64_t FirstEltSize = 893 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt); 894 if (FirstEltSize < DstSize && 895 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy)) 896 return SrcPtr; 897 898 // GEP into the first element. 899 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive"); 900 901 // If the first element is a struct, recurse. 902 llvm::Type *SrcTy = SrcPtr.getElementType(); 903 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) 904 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF); 905 906 return SrcPtr; 907 } 908 909 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both 910 /// are either integers or pointers. This does a truncation of the value if it 911 /// is too large or a zero extension if it is too small. 912 /// 913 /// This behaves as if the value were coerced through memory, so on big-endian 914 /// targets the high bits are preserved in a truncation, while little-endian 915 /// targets preserve the low bits. 916 static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val, 917 llvm::Type *Ty, 918 CodeGenFunction &CGF) { 919 if (Val->getType() == Ty) 920 return Val; 921 922 if (isa<llvm::PointerType>(Val->getType())) { 923 // If this is Pointer->Pointer avoid conversion to and from int. 924 if (isa<llvm::PointerType>(Ty)) 925 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val"); 926 927 // Convert the pointer to an integer so we can play with its width. 928 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi"); 929 } 930 931 llvm::Type *DestIntTy = Ty; 932 if (isa<llvm::PointerType>(DestIntTy)) 933 DestIntTy = CGF.IntPtrTy; 934 935 if (Val->getType() != DestIntTy) { 936 const llvm::DataLayout &DL = CGF.CGM.getDataLayout(); 937 if (DL.isBigEndian()) { 938 // Preserve the high bits on big-endian targets. 939 // That is what memory coercion does. 940 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType()); 941 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy); 942 943 if (SrcSize > DstSize) { 944 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits"); 945 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii"); 946 } else { 947 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii"); 948 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits"); 949 } 950 } else { 951 // Little-endian targets preserve the low bits. No shifts required. 952 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii"); 953 } 954 } 955 956 if (isa<llvm::PointerType>(Ty)) 957 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip"); 958 return Val; 959 } 960 961 962 963 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as 964 /// a pointer to an object of type \arg Ty, known to be aligned to 965 /// \arg SrcAlign bytes. 966 /// 967 /// This safely handles the case when the src type is smaller than the 968 /// destination type; in this situation the values of bits which not 969 /// present in the src are undefined. 970 static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty, 971 CodeGenFunction &CGF) { 972 llvm::Type *SrcTy = Src.getElementType(); 973 974 // If SrcTy and Ty are the same, just do a load. 975 if (SrcTy == Ty) 976 return CGF.Builder.CreateLoad(Src); 977 978 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty); 979 980 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) { 981 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF); 982 SrcTy = Src.getType()->getElementType(); 983 } 984 985 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy); 986 987 // If the source and destination are integer or pointer types, just do an 988 // extension or truncation to the desired type. 989 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) && 990 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) { 991 llvm::Value *Load = CGF.Builder.CreateLoad(Src); 992 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF); 993 } 994 995 // If load is legal, just bitcast the src pointer. 996 if (SrcSize >= DstSize) { 997 // Generally SrcSize is never greater than DstSize, since this means we are 998 // losing bits. However, this can happen in cases where the structure has 999 // additional padding, for example due to a user specified alignment. 1000 // 1001 // FIXME: Assert that we aren't truncating non-padding bits when have access 1002 // to that information. 1003 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty)); 1004 return CGF.Builder.CreateLoad(Src); 1005 } 1006 1007 // Otherwise do coercion through memory. This is stupid, but simple. 1008 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment()); 1009 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy); 1010 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy); 1011 CGF.Builder.CreateMemCpy(Casted, SrcCasted, 1012 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize), 1013 false); 1014 return CGF.Builder.CreateLoad(Tmp); 1015 } 1016 1017 // Function to store a first-class aggregate into memory. We prefer to 1018 // store the elements rather than the aggregate to be more friendly to 1019 // fast-isel. 1020 // FIXME: Do we need to recurse here? 1021 static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val, 1022 Address Dest, bool DestIsVolatile) { 1023 // Prefer scalar stores to first-class aggregate stores. 1024 if (llvm::StructType *STy = 1025 dyn_cast<llvm::StructType>(Val->getType())) { 1026 const llvm::StructLayout *Layout = 1027 CGF.CGM.getDataLayout().getStructLayout(STy); 1028 1029 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1030 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i)); 1031 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset); 1032 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i); 1033 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile); 1034 } 1035 } else { 1036 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile); 1037 } 1038 } 1039 1040 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src, 1041 /// where the source and destination may have different types. The 1042 /// destination is known to be aligned to \arg DstAlign bytes. 1043 /// 1044 /// This safely handles the case when the src type is larger than the 1045 /// destination type; the upper bits of the src will be lost. 1046 static void CreateCoercedStore(llvm::Value *Src, 1047 Address Dst, 1048 bool DstIsVolatile, 1049 CodeGenFunction &CGF) { 1050 llvm::Type *SrcTy = Src->getType(); 1051 llvm::Type *DstTy = Dst.getType()->getElementType(); 1052 if (SrcTy == DstTy) { 1053 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1054 return; 1055 } 1056 1057 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy); 1058 1059 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) { 1060 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF); 1061 DstTy = Dst.getType()->getElementType(); 1062 } 1063 1064 // If the source and destination are integer or pointer types, just do an 1065 // extension or truncation to the desired type. 1066 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) && 1067 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) { 1068 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF); 1069 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1070 return; 1071 } 1072 1073 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy); 1074 1075 // If store is legal, just bitcast the src pointer. 1076 if (SrcSize <= DstSize) { 1077 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy)); 1078 BuildAggStore(CGF, Src, Dst, DstIsVolatile); 1079 } else { 1080 // Otherwise do coercion through memory. This is stupid, but 1081 // simple. 1082 1083 // Generally SrcSize is never greater than DstSize, since this means we are 1084 // losing bits. However, this can happen in cases where the structure has 1085 // additional padding, for example due to a user specified alignment. 1086 // 1087 // FIXME: Assert that we aren't truncating non-padding bits when have access 1088 // to that information. 1089 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment()); 1090 CGF.Builder.CreateStore(Src, Tmp); 1091 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy); 1092 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy); 1093 CGF.Builder.CreateMemCpy(DstCasted, Casted, 1094 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize), 1095 false); 1096 } 1097 } 1098 1099 static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr, 1100 const ABIArgInfo &info) { 1101 if (unsigned offset = info.getDirectOffset()) { 1102 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty); 1103 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr, 1104 CharUnits::fromQuantity(offset)); 1105 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType()); 1106 } 1107 return addr; 1108 } 1109 1110 namespace { 1111 1112 /// Encapsulates information about the way function arguments from 1113 /// CGFunctionInfo should be passed to actual LLVM IR function. 1114 class ClangToLLVMArgMapping { 1115 static const unsigned InvalidIndex = ~0U; 1116 unsigned InallocaArgNo; 1117 unsigned SRetArgNo; 1118 unsigned TotalIRArgs; 1119 1120 /// Arguments of LLVM IR function corresponding to single Clang argument. 1121 struct IRArgs { 1122 unsigned PaddingArgIndex; 1123 // Argument is expanded to IR arguments at positions 1124 // [FirstArgIndex, FirstArgIndex + NumberOfArgs). 1125 unsigned FirstArgIndex; 1126 unsigned NumberOfArgs; 1127 1128 IRArgs() 1129 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex), 1130 NumberOfArgs(0) {} 1131 }; 1132 1133 SmallVector<IRArgs, 8> ArgInfo; 1134 1135 public: 1136 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI, 1137 bool OnlyRequiredArgs = false) 1138 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0), 1139 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) { 1140 construct(Context, FI, OnlyRequiredArgs); 1141 } 1142 1143 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; } 1144 unsigned getInallocaArgNo() const { 1145 assert(hasInallocaArg()); 1146 return InallocaArgNo; 1147 } 1148 1149 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; } 1150 unsigned getSRetArgNo() const { 1151 assert(hasSRetArg()); 1152 return SRetArgNo; 1153 } 1154 1155 unsigned totalIRArgs() const { return TotalIRArgs; } 1156 1157 bool hasPaddingArg(unsigned ArgNo) const { 1158 assert(ArgNo < ArgInfo.size()); 1159 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex; 1160 } 1161 unsigned getPaddingArgNo(unsigned ArgNo) const { 1162 assert(hasPaddingArg(ArgNo)); 1163 return ArgInfo[ArgNo].PaddingArgIndex; 1164 } 1165 1166 /// Returns index of first IR argument corresponding to ArgNo, and their 1167 /// quantity. 1168 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const { 1169 assert(ArgNo < ArgInfo.size()); 1170 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex, 1171 ArgInfo[ArgNo].NumberOfArgs); 1172 } 1173 1174 private: 1175 void construct(const ASTContext &Context, const CGFunctionInfo &FI, 1176 bool OnlyRequiredArgs); 1177 }; 1178 1179 void ClangToLLVMArgMapping::construct(const ASTContext &Context, 1180 const CGFunctionInfo &FI, 1181 bool OnlyRequiredArgs) { 1182 unsigned IRArgNo = 0; 1183 bool SwapThisWithSRet = false; 1184 const ABIArgInfo &RetAI = FI.getReturnInfo(); 1185 1186 if (RetAI.getKind() == ABIArgInfo::Indirect) { 1187 SwapThisWithSRet = RetAI.isSRetAfterThis(); 1188 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++; 1189 } 1190 1191 unsigned ArgNo = 0; 1192 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size(); 1193 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs; 1194 ++I, ++ArgNo) { 1195 assert(I != FI.arg_end()); 1196 QualType ArgType = I->type; 1197 const ABIArgInfo &AI = I->info; 1198 // Collect data about IR arguments corresponding to Clang argument ArgNo. 1199 auto &IRArgs = ArgInfo[ArgNo]; 1200 1201 if (AI.getPaddingType()) 1202 IRArgs.PaddingArgIndex = IRArgNo++; 1203 1204 switch (AI.getKind()) { 1205 case ABIArgInfo::Extend: 1206 case ABIArgInfo::Direct: { 1207 // FIXME: handle sseregparm someday... 1208 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType()); 1209 if (AI.isDirect() && AI.getCanBeFlattened() && STy) { 1210 IRArgs.NumberOfArgs = STy->getNumElements(); 1211 } else { 1212 IRArgs.NumberOfArgs = 1; 1213 } 1214 break; 1215 } 1216 case ABIArgInfo::Indirect: 1217 IRArgs.NumberOfArgs = 1; 1218 break; 1219 case ABIArgInfo::Ignore: 1220 case ABIArgInfo::InAlloca: 1221 // ignore and inalloca doesn't have matching LLVM parameters. 1222 IRArgs.NumberOfArgs = 0; 1223 break; 1224 case ABIArgInfo::Expand: { 1225 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context); 1226 break; 1227 } 1228 } 1229 1230 if (IRArgs.NumberOfArgs > 0) { 1231 IRArgs.FirstArgIndex = IRArgNo; 1232 IRArgNo += IRArgs.NumberOfArgs; 1233 } 1234 1235 // Skip over the sret parameter when it comes second. We already handled it 1236 // above. 1237 if (IRArgNo == 1 && SwapThisWithSRet) 1238 IRArgNo++; 1239 } 1240 assert(ArgNo == ArgInfo.size()); 1241 1242 if (FI.usesInAlloca()) 1243 InallocaArgNo = IRArgNo++; 1244 1245 TotalIRArgs = IRArgNo; 1246 } 1247 } // namespace 1248 1249 /***/ 1250 1251 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) { 1252 return FI.getReturnInfo().isIndirect(); 1253 } 1254 1255 bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) { 1256 return ReturnTypeUsesSRet(FI) && 1257 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs(); 1258 } 1259 1260 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) { 1261 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) { 1262 switch (BT->getKind()) { 1263 default: 1264 return false; 1265 case BuiltinType::Float: 1266 return getTarget().useObjCFPRetForRealType(TargetInfo::Float); 1267 case BuiltinType::Double: 1268 return getTarget().useObjCFPRetForRealType(TargetInfo::Double); 1269 case BuiltinType::LongDouble: 1270 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble); 1271 } 1272 } 1273 1274 return false; 1275 } 1276 1277 bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) { 1278 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) { 1279 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) { 1280 if (BT->getKind() == BuiltinType::LongDouble) 1281 return getTarget().useObjCFP2RetForComplexLongDouble(); 1282 } 1283 } 1284 1285 return false; 1286 } 1287 1288 llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) { 1289 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD); 1290 return GetFunctionType(FI); 1291 } 1292 1293 llvm::FunctionType * 1294 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) { 1295 1296 bool Inserted = FunctionsBeingProcessed.insert(&FI).second; 1297 (void)Inserted; 1298 assert(Inserted && "Recursively being processed?"); 1299 1300 llvm::Type *resultType = nullptr; 1301 const ABIArgInfo &retAI = FI.getReturnInfo(); 1302 switch (retAI.getKind()) { 1303 case ABIArgInfo::Expand: 1304 llvm_unreachable("Invalid ABI kind for return argument"); 1305 1306 case ABIArgInfo::Extend: 1307 case ABIArgInfo::Direct: 1308 resultType = retAI.getCoerceToType(); 1309 break; 1310 1311 case ABIArgInfo::InAlloca: 1312 if (retAI.getInAllocaSRet()) { 1313 // sret things on win32 aren't void, they return the sret pointer. 1314 QualType ret = FI.getReturnType(); 1315 llvm::Type *ty = ConvertType(ret); 1316 unsigned addressSpace = Context.getTargetAddressSpace(ret); 1317 resultType = llvm::PointerType::get(ty, addressSpace); 1318 } else { 1319 resultType = llvm::Type::getVoidTy(getLLVMContext()); 1320 } 1321 break; 1322 1323 case ABIArgInfo::Indirect: 1324 case ABIArgInfo::Ignore: 1325 resultType = llvm::Type::getVoidTy(getLLVMContext()); 1326 break; 1327 } 1328 1329 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true); 1330 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs()); 1331 1332 // Add type for sret argument. 1333 if (IRFunctionArgs.hasSRetArg()) { 1334 QualType Ret = FI.getReturnType(); 1335 llvm::Type *Ty = ConvertType(Ret); 1336 unsigned AddressSpace = Context.getTargetAddressSpace(Ret); 1337 ArgTypes[IRFunctionArgs.getSRetArgNo()] = 1338 llvm::PointerType::get(Ty, AddressSpace); 1339 } 1340 1341 // Add type for inalloca argument. 1342 if (IRFunctionArgs.hasInallocaArg()) { 1343 auto ArgStruct = FI.getArgStruct(); 1344 assert(ArgStruct); 1345 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo(); 1346 } 1347 1348 // Add in all of the required arguments. 1349 unsigned ArgNo = 0; 1350 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), 1351 ie = it + FI.getNumRequiredArgs(); 1352 for (; it != ie; ++it, ++ArgNo) { 1353 const ABIArgInfo &ArgInfo = it->info; 1354 1355 // Insert a padding type to ensure proper alignment. 1356 if (IRFunctionArgs.hasPaddingArg(ArgNo)) 1357 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 1358 ArgInfo.getPaddingType(); 1359 1360 unsigned FirstIRArg, NumIRArgs; 1361 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 1362 1363 switch (ArgInfo.getKind()) { 1364 case ABIArgInfo::Ignore: 1365 case ABIArgInfo::InAlloca: 1366 assert(NumIRArgs == 0); 1367 break; 1368 1369 case ABIArgInfo::Indirect: { 1370 assert(NumIRArgs == 1); 1371 // indirect arguments are always on the stack, which is addr space #0. 1372 llvm::Type *LTy = ConvertTypeForMem(it->type); 1373 ArgTypes[FirstIRArg] = LTy->getPointerTo(); 1374 break; 1375 } 1376 1377 case ABIArgInfo::Extend: 1378 case ABIArgInfo::Direct: { 1379 // Fast-isel and the optimizer generally like scalar values better than 1380 // FCAs, so we flatten them if this is safe to do for this argument. 1381 llvm::Type *argType = ArgInfo.getCoerceToType(); 1382 llvm::StructType *st = dyn_cast<llvm::StructType>(argType); 1383 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) { 1384 assert(NumIRArgs == st->getNumElements()); 1385 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i) 1386 ArgTypes[FirstIRArg + i] = st->getElementType(i); 1387 } else { 1388 assert(NumIRArgs == 1); 1389 ArgTypes[FirstIRArg] = argType; 1390 } 1391 break; 1392 } 1393 1394 case ABIArgInfo::Expand: 1395 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg; 1396 getExpandedTypes(it->type, ArgTypesIter); 1397 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs); 1398 break; 1399 } 1400 } 1401 1402 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased; 1403 assert(Erased && "Not in set?"); 1404 1405 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic()); 1406 } 1407 1408 llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) { 1409 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1410 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 1411 1412 if (!isFuncTypeConvertible(FPT)) 1413 return llvm::StructType::get(getLLVMContext()); 1414 1415 const CGFunctionInfo *Info; 1416 if (isa<CXXDestructorDecl>(MD)) 1417 Info = 1418 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType())); 1419 else 1420 Info = &arrangeCXXMethodDeclaration(MD); 1421 return GetFunctionType(*Info); 1422 } 1423 1424 static void AddAttributesFromFunctionProtoType(ASTContext &Ctx, 1425 llvm::AttrBuilder &FuncAttrs, 1426 const FunctionProtoType *FPT) { 1427 if (!FPT) 1428 return; 1429 1430 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 1431 FPT->isNothrow(Ctx)) 1432 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1433 } 1434 1435 void CodeGenModule::ConstructAttributeList( 1436 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo, 1437 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) { 1438 llvm::AttrBuilder FuncAttrs; 1439 llvm::AttrBuilder RetAttrs; 1440 bool HasOptnone = false; 1441 1442 CallingConv = FI.getEffectiveCallingConvention(); 1443 1444 if (FI.isNoReturn()) 1445 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1446 1447 // If we have information about the function prototype, we can learn 1448 // attributes form there. 1449 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs, 1450 CalleeInfo.getCalleeFunctionProtoType()); 1451 1452 const Decl *TargetDecl = CalleeInfo.getCalleeDecl(); 1453 1454 // FIXME: handle sseregparm someday... 1455 if (TargetDecl) { 1456 if (TargetDecl->hasAttr<ReturnsTwiceAttr>()) 1457 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice); 1458 if (TargetDecl->hasAttr<NoThrowAttr>()) 1459 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1460 if (TargetDecl->hasAttr<NoReturnAttr>()) 1461 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1462 if (TargetDecl->hasAttr<NoDuplicateAttr>()) 1463 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate); 1464 1465 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) { 1466 AddAttributesFromFunctionProtoType( 1467 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>()); 1468 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function. 1469 // These attributes are not inherited by overloads. 1470 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn); 1471 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual())) 1472 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1473 } 1474 1475 // 'const', 'pure' and 'noalias' attributed functions are also nounwind. 1476 if (TargetDecl->hasAttr<ConstAttr>()) { 1477 FuncAttrs.addAttribute(llvm::Attribute::ReadNone); 1478 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1479 } else if (TargetDecl->hasAttr<PureAttr>()) { 1480 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly); 1481 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1482 } else if (TargetDecl->hasAttr<NoAliasAttr>()) { 1483 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly); 1484 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1485 } 1486 if (TargetDecl->hasAttr<RestrictAttr>()) 1487 RetAttrs.addAttribute(llvm::Attribute::NoAlias); 1488 if (TargetDecl->hasAttr<ReturnsNonNullAttr>()) 1489 RetAttrs.addAttribute(llvm::Attribute::NonNull); 1490 1491 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>(); 1492 } 1493 1494 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed. 1495 if (!HasOptnone) { 1496 if (CodeGenOpts.OptimizeSize) 1497 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize); 1498 if (CodeGenOpts.OptimizeSize == 2) 1499 FuncAttrs.addAttribute(llvm::Attribute::MinSize); 1500 } 1501 1502 if (CodeGenOpts.DisableRedZone) 1503 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone); 1504 if (CodeGenOpts.NoImplicitFloat) 1505 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat); 1506 if (CodeGenOpts.EnableSegmentedStacks && 1507 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>())) 1508 FuncAttrs.addAttribute("split-stack"); 1509 1510 if (AttrOnCallSite) { 1511 // Attributes that should go on the call site only. 1512 if (!CodeGenOpts.SimplifyLibCalls || 1513 CodeGenOpts.isNoBuiltinFunc(Name.data())) 1514 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin); 1515 if (!CodeGenOpts.TrapFuncName.empty()) 1516 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName); 1517 } else { 1518 // Attributes that should go on the function, but not the call site. 1519 if (!CodeGenOpts.DisableFPElim) { 1520 FuncAttrs.addAttribute("no-frame-pointer-elim", "false"); 1521 } else if (CodeGenOpts.OmitLeafFramePointer) { 1522 FuncAttrs.addAttribute("no-frame-pointer-elim", "false"); 1523 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf"); 1524 } else { 1525 FuncAttrs.addAttribute("no-frame-pointer-elim", "true"); 1526 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf"); 1527 } 1528 1529 bool DisableTailCalls = 1530 CodeGenOpts.DisableTailCalls || 1531 (TargetDecl && TargetDecl->hasAttr<DisableTailCallsAttr>()); 1532 FuncAttrs.addAttribute("disable-tail-calls", 1533 llvm::toStringRef(DisableTailCalls)); 1534 1535 FuncAttrs.addAttribute("less-precise-fpmad", 1536 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD)); 1537 FuncAttrs.addAttribute("no-infs-fp-math", 1538 llvm::toStringRef(CodeGenOpts.NoInfsFPMath)); 1539 FuncAttrs.addAttribute("no-nans-fp-math", 1540 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath)); 1541 FuncAttrs.addAttribute("unsafe-fp-math", 1542 llvm::toStringRef(CodeGenOpts.UnsafeFPMath)); 1543 FuncAttrs.addAttribute("use-soft-float", 1544 llvm::toStringRef(CodeGenOpts.SoftFloat)); 1545 FuncAttrs.addAttribute("stack-protector-buffer-size", 1546 llvm::utostr(CodeGenOpts.SSPBufferSize)); 1547 1548 if (CodeGenOpts.StackRealignment) 1549 FuncAttrs.addAttribute("stackrealign"); 1550 1551 // Add target-cpu and target-features attributes to functions. If 1552 // we have a decl for the function and it has a target attribute then 1553 // parse that and add it to the feature set. 1554 StringRef TargetCPU = getTarget().getTargetOpts().CPU; 1555 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl); 1556 if (FD && FD->hasAttr<TargetAttr>()) { 1557 llvm::StringMap<bool> FeatureMap; 1558 getFunctionFeatureMap(FeatureMap, FD); 1559 1560 // Produce the canonical string for this set of features. 1561 std::vector<std::string> Features; 1562 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(), 1563 ie = FeatureMap.end(); 1564 it != ie; ++it) 1565 Features.push_back((it->second ? "+" : "-") + it->first().str()); 1566 1567 // Now add the target-cpu and target-features to the function. 1568 // While we populated the feature map above, we still need to 1569 // get and parse the target attribute so we can get the cpu for 1570 // the function. 1571 const auto *TD = FD->getAttr<TargetAttr>(); 1572 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 1573 if (ParsedAttr.second != "") 1574 TargetCPU = ParsedAttr.second; 1575 if (TargetCPU != "") 1576 FuncAttrs.addAttribute("target-cpu", TargetCPU); 1577 if (!Features.empty()) { 1578 std::sort(Features.begin(), Features.end()); 1579 FuncAttrs.addAttribute( 1580 "target-features", 1581 llvm::join(Features.begin(), Features.end(), ",")); 1582 } 1583 } else { 1584 // Otherwise just add the existing target cpu and target features to the 1585 // function. 1586 std::vector<std::string> &Features = getTarget().getTargetOpts().Features; 1587 if (TargetCPU != "") 1588 FuncAttrs.addAttribute("target-cpu", TargetCPU); 1589 if (!Features.empty()) { 1590 std::sort(Features.begin(), Features.end()); 1591 FuncAttrs.addAttribute( 1592 "target-features", 1593 llvm::join(Features.begin(), Features.end(), ",")); 1594 } 1595 } 1596 } 1597 1598 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 1599 // Conservatively, mark all functions and calls in CUDA as convergent 1600 // (meaning, they may call an intrinsically convergent op, such as 1601 // __syncthreads(), and so can't have certain optimizations applied around 1602 // them). LLVM will remove this attribute where it safely can. 1603 FuncAttrs.addAttribute(llvm::Attribute::Convergent); 1604 } 1605 1606 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI); 1607 1608 QualType RetTy = FI.getReturnType(); 1609 const ABIArgInfo &RetAI = FI.getReturnInfo(); 1610 switch (RetAI.getKind()) { 1611 case ABIArgInfo::Extend: 1612 if (RetTy->hasSignedIntegerRepresentation()) 1613 RetAttrs.addAttribute(llvm::Attribute::SExt); 1614 else if (RetTy->hasUnsignedIntegerRepresentation()) 1615 RetAttrs.addAttribute(llvm::Attribute::ZExt); 1616 // FALL THROUGH 1617 case ABIArgInfo::Direct: 1618 if (RetAI.getInReg()) 1619 RetAttrs.addAttribute(llvm::Attribute::InReg); 1620 break; 1621 case ABIArgInfo::Ignore: 1622 break; 1623 1624 case ABIArgInfo::InAlloca: 1625 case ABIArgInfo::Indirect: { 1626 // inalloca and sret disable readnone and readonly 1627 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 1628 .removeAttribute(llvm::Attribute::ReadNone); 1629 break; 1630 } 1631 1632 case ABIArgInfo::Expand: 1633 llvm_unreachable("Invalid ABI kind for return argument"); 1634 } 1635 1636 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) { 1637 QualType PTy = RefTy->getPointeeType(); 1638 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) 1639 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy) 1640 .getQuantity()); 1641 else if (getContext().getTargetAddressSpace(PTy) == 0) 1642 RetAttrs.addAttribute(llvm::Attribute::NonNull); 1643 } 1644 1645 // Attach return attributes. 1646 if (RetAttrs.hasAttributes()) { 1647 PAL.push_back(llvm::AttributeSet::get( 1648 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs)); 1649 } 1650 1651 // Attach attributes to sret. 1652 if (IRFunctionArgs.hasSRetArg()) { 1653 llvm::AttrBuilder SRETAttrs; 1654 SRETAttrs.addAttribute(llvm::Attribute::StructRet); 1655 if (RetAI.getInReg()) 1656 SRETAttrs.addAttribute(llvm::Attribute::InReg); 1657 PAL.push_back(llvm::AttributeSet::get( 1658 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs)); 1659 } 1660 1661 // Attach attributes to inalloca argument. 1662 if (IRFunctionArgs.hasInallocaArg()) { 1663 llvm::AttrBuilder Attrs; 1664 Attrs.addAttribute(llvm::Attribute::InAlloca); 1665 PAL.push_back(llvm::AttributeSet::get( 1666 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs)); 1667 } 1668 1669 unsigned ArgNo = 0; 1670 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(), 1671 E = FI.arg_end(); 1672 I != E; ++I, ++ArgNo) { 1673 QualType ParamType = I->type; 1674 const ABIArgInfo &AI = I->info; 1675 llvm::AttrBuilder Attrs; 1676 1677 // Add attribute for padding argument, if necessary. 1678 if (IRFunctionArgs.hasPaddingArg(ArgNo)) { 1679 if (AI.getPaddingInReg()) 1680 PAL.push_back(llvm::AttributeSet::get( 1681 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1, 1682 llvm::Attribute::InReg)); 1683 } 1684 1685 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we 1686 // have the corresponding parameter variable. It doesn't make 1687 // sense to do it here because parameters are so messed up. 1688 switch (AI.getKind()) { 1689 case ABIArgInfo::Extend: 1690 if (ParamType->isSignedIntegerOrEnumerationType()) 1691 Attrs.addAttribute(llvm::Attribute::SExt); 1692 else if (ParamType->isUnsignedIntegerOrEnumerationType()) { 1693 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType)) 1694 Attrs.addAttribute(llvm::Attribute::SExt); 1695 else 1696 Attrs.addAttribute(llvm::Attribute::ZExt); 1697 } 1698 // FALL THROUGH 1699 case ABIArgInfo::Direct: 1700 if (ArgNo == 0 && FI.isChainCall()) 1701 Attrs.addAttribute(llvm::Attribute::Nest); 1702 else if (AI.getInReg()) 1703 Attrs.addAttribute(llvm::Attribute::InReg); 1704 break; 1705 1706 case ABIArgInfo::Indirect: { 1707 if (AI.getInReg()) 1708 Attrs.addAttribute(llvm::Attribute::InReg); 1709 1710 if (AI.getIndirectByVal()) 1711 Attrs.addAttribute(llvm::Attribute::ByVal); 1712 1713 CharUnits Align = AI.getIndirectAlign(); 1714 1715 // In a byval argument, it is important that the required 1716 // alignment of the type is honored, as LLVM might be creating a 1717 // *new* stack object, and needs to know what alignment to give 1718 // it. (Sometimes it can deduce a sensible alignment on its own, 1719 // but not if clang decides it must emit a packed struct, or the 1720 // user specifies increased alignment requirements.) 1721 // 1722 // This is different from indirect *not* byval, where the object 1723 // exists already, and the align attribute is purely 1724 // informative. 1725 assert(!Align.isZero()); 1726 1727 // For now, only add this when we have a byval argument. 1728 // TODO: be less lazy about updating test cases. 1729 if (AI.getIndirectByVal()) 1730 Attrs.addAlignmentAttr(Align.getQuantity()); 1731 1732 // byval disables readnone and readonly. 1733 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 1734 .removeAttribute(llvm::Attribute::ReadNone); 1735 break; 1736 } 1737 case ABIArgInfo::Ignore: 1738 case ABIArgInfo::Expand: 1739 continue; 1740 1741 case ABIArgInfo::InAlloca: 1742 // inalloca disables readnone and readonly. 1743 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 1744 .removeAttribute(llvm::Attribute::ReadNone); 1745 continue; 1746 } 1747 1748 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) { 1749 QualType PTy = RefTy->getPointeeType(); 1750 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) 1751 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy) 1752 .getQuantity()); 1753 else if (getContext().getTargetAddressSpace(PTy) == 0) 1754 Attrs.addAttribute(llvm::Attribute::NonNull); 1755 } 1756 1757 if (Attrs.hasAttributes()) { 1758 unsigned FirstIRArg, NumIRArgs; 1759 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 1760 for (unsigned i = 0; i < NumIRArgs; i++) 1761 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), 1762 FirstIRArg + i + 1, Attrs)); 1763 } 1764 } 1765 assert(ArgNo == FI.arg_size()); 1766 1767 if (FuncAttrs.hasAttributes()) 1768 PAL.push_back(llvm:: 1769 AttributeSet::get(getLLVMContext(), 1770 llvm::AttributeSet::FunctionIndex, 1771 FuncAttrs)); 1772 } 1773 1774 /// An argument came in as a promoted argument; demote it back to its 1775 /// declared type. 1776 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF, 1777 const VarDecl *var, 1778 llvm::Value *value) { 1779 llvm::Type *varType = CGF.ConvertType(var->getType()); 1780 1781 // This can happen with promotions that actually don't change the 1782 // underlying type, like the enum promotions. 1783 if (value->getType() == varType) return value; 1784 1785 assert((varType->isIntegerTy() || varType->isFloatingPointTy()) 1786 && "unexpected promotion type"); 1787 1788 if (isa<llvm::IntegerType>(varType)) 1789 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote"); 1790 1791 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote"); 1792 } 1793 1794 /// Returns the attribute (either parameter attribute, or function 1795 /// attribute), which declares argument ArgNo to be non-null. 1796 static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD, 1797 QualType ArgType, unsigned ArgNo) { 1798 // FIXME: __attribute__((nonnull)) can also be applied to: 1799 // - references to pointers, where the pointee is known to be 1800 // nonnull (apparently a Clang extension) 1801 // - transparent unions containing pointers 1802 // In the former case, LLVM IR cannot represent the constraint. In 1803 // the latter case, we have no guarantee that the transparent union 1804 // is in fact passed as a pointer. 1805 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType()) 1806 return nullptr; 1807 // First, check attribute on parameter itself. 1808 if (PVD) { 1809 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>()) 1810 return ParmNNAttr; 1811 } 1812 // Check function attributes. 1813 if (!FD) 1814 return nullptr; 1815 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) { 1816 if (NNAttr->isNonNull(ArgNo)) 1817 return NNAttr; 1818 } 1819 return nullptr; 1820 } 1821 1822 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, 1823 llvm::Function *Fn, 1824 const FunctionArgList &Args) { 1825 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) 1826 // Naked functions don't have prologues. 1827 return; 1828 1829 // If this is an implicit-return-zero function, go ahead and 1830 // initialize the return value. TODO: it might be nice to have 1831 // a more general mechanism for this that didn't require synthesized 1832 // return statements. 1833 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) { 1834 if (FD->hasImplicitReturnZero()) { 1835 QualType RetTy = FD->getReturnType().getUnqualifiedType(); 1836 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy); 1837 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy); 1838 Builder.CreateStore(Zero, ReturnValue); 1839 } 1840 } 1841 1842 // FIXME: We no longer need the types from FunctionArgList; lift up and 1843 // simplify. 1844 1845 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI); 1846 // Flattened function arguments. 1847 SmallVector<llvm::Argument *, 16> FnArgs; 1848 FnArgs.reserve(IRFunctionArgs.totalIRArgs()); 1849 for (auto &Arg : Fn->args()) { 1850 FnArgs.push_back(&Arg); 1851 } 1852 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs()); 1853 1854 // If we're using inalloca, all the memory arguments are GEPs off of the last 1855 // parameter, which is a pointer to the complete memory area. 1856 Address ArgStruct = Address::invalid(); 1857 const llvm::StructLayout *ArgStructLayout = nullptr; 1858 if (IRFunctionArgs.hasInallocaArg()) { 1859 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct()); 1860 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()], 1861 FI.getArgStructAlignment()); 1862 1863 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo()); 1864 } 1865 1866 // Name the struct return parameter. 1867 if (IRFunctionArgs.hasSRetArg()) { 1868 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()]; 1869 AI->setName("agg.result"); 1870 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1, 1871 llvm::Attribute::NoAlias)); 1872 } 1873 1874 // Track if we received the parameter as a pointer (indirect, byval, or 1875 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it 1876 // into a local alloca for us. 1877 SmallVector<ParamValue, 16> ArgVals; 1878 ArgVals.reserve(Args.size()); 1879 1880 // Create a pointer value for every parameter declaration. This usually 1881 // entails copying one or more LLVM IR arguments into an alloca. Don't push 1882 // any cleanups or do anything that might unwind. We do that separately, so 1883 // we can push the cleanups in the correct order for the ABI. 1884 assert(FI.arg_size() == Args.size() && 1885 "Mismatch between function signature & arguments."); 1886 unsigned ArgNo = 0; 1887 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin(); 1888 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 1889 i != e; ++i, ++info_it, ++ArgNo) { 1890 const VarDecl *Arg = *i; 1891 QualType Ty = info_it->type; 1892 const ABIArgInfo &ArgI = info_it->info; 1893 1894 bool isPromoted = 1895 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted(); 1896 1897 unsigned FirstIRArg, NumIRArgs; 1898 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 1899 1900 switch (ArgI.getKind()) { 1901 case ABIArgInfo::InAlloca: { 1902 assert(NumIRArgs == 0); 1903 auto FieldIndex = ArgI.getInAllocaFieldIndex(); 1904 CharUnits FieldOffset = 1905 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex)); 1906 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset, 1907 Arg->getName()); 1908 ArgVals.push_back(ParamValue::forIndirect(V)); 1909 break; 1910 } 1911 1912 case ABIArgInfo::Indirect: { 1913 assert(NumIRArgs == 1); 1914 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign()); 1915 1916 if (!hasScalarEvaluationKind(Ty)) { 1917 // Aggregates and complex variables are accessed by reference. All we 1918 // need to do is realign the value, if requested. 1919 Address V = ParamAddr; 1920 if (ArgI.getIndirectRealign()) { 1921 Address AlignedTemp = CreateMemTemp(Ty, "coerce"); 1922 1923 // Copy from the incoming argument pointer to the temporary with the 1924 // appropriate alignment. 1925 // 1926 // FIXME: We should have a common utility for generating an aggregate 1927 // copy. 1928 CharUnits Size = getContext().getTypeSizeInChars(Ty); 1929 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()); 1930 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy); 1931 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy); 1932 Builder.CreateMemCpy(Dst, Src, SizeVal, false); 1933 V = AlignedTemp; 1934 } 1935 ArgVals.push_back(ParamValue::forIndirect(V)); 1936 } else { 1937 // Load scalar value from indirect argument. 1938 llvm::Value *V = 1939 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart()); 1940 1941 if (isPromoted) 1942 V = emitArgumentDemotion(*this, Arg, V); 1943 ArgVals.push_back(ParamValue::forDirect(V)); 1944 } 1945 break; 1946 } 1947 1948 case ABIArgInfo::Extend: 1949 case ABIArgInfo::Direct: { 1950 1951 // If we have the trivial case, handle it with no muss and fuss. 1952 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) && 1953 ArgI.getCoerceToType() == ConvertType(Ty) && 1954 ArgI.getDirectOffset() == 0) { 1955 assert(NumIRArgs == 1); 1956 auto AI = FnArgs[FirstIRArg]; 1957 llvm::Value *V = AI; 1958 1959 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) { 1960 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(), 1961 PVD->getFunctionScopeIndex())) 1962 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), 1963 AI->getArgNo() + 1, 1964 llvm::Attribute::NonNull)); 1965 1966 QualType OTy = PVD->getOriginalType(); 1967 if (const auto *ArrTy = 1968 getContext().getAsConstantArrayType(OTy)) { 1969 // A C99 array parameter declaration with the static keyword also 1970 // indicates dereferenceability, and if the size is constant we can 1971 // use the dereferenceable attribute (which requires the size in 1972 // bytes). 1973 if (ArrTy->getSizeModifier() == ArrayType::Static) { 1974 QualType ETy = ArrTy->getElementType(); 1975 uint64_t ArrSize = ArrTy->getSize().getZExtValue(); 1976 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() && 1977 ArrSize) { 1978 llvm::AttrBuilder Attrs; 1979 Attrs.addDereferenceableAttr( 1980 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize); 1981 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), 1982 AI->getArgNo() + 1, Attrs)); 1983 } else if (getContext().getTargetAddressSpace(ETy) == 0) { 1984 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), 1985 AI->getArgNo() + 1, 1986 llvm::Attribute::NonNull)); 1987 } 1988 } 1989 } else if (const auto *ArrTy = 1990 getContext().getAsVariableArrayType(OTy)) { 1991 // For C99 VLAs with the static keyword, we don't know the size so 1992 // we can't use the dereferenceable attribute, but in addrspace(0) 1993 // we know that it must be nonnull. 1994 if (ArrTy->getSizeModifier() == VariableArrayType::Static && 1995 !getContext().getTargetAddressSpace(ArrTy->getElementType())) 1996 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), 1997 AI->getArgNo() + 1, 1998 llvm::Attribute::NonNull)); 1999 } 2000 2001 const auto *AVAttr = PVD->getAttr<AlignValueAttr>(); 2002 if (!AVAttr) 2003 if (const auto *TOTy = dyn_cast<TypedefType>(OTy)) 2004 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>(); 2005 if (AVAttr) { 2006 llvm::Value *AlignmentValue = 2007 EmitScalarExpr(AVAttr->getAlignment()); 2008 llvm::ConstantInt *AlignmentCI = 2009 cast<llvm::ConstantInt>(AlignmentValue); 2010 unsigned Alignment = 2011 std::min((unsigned) AlignmentCI->getZExtValue(), 2012 +llvm::Value::MaximumAlignment); 2013 2014 llvm::AttrBuilder Attrs; 2015 Attrs.addAlignmentAttr(Alignment); 2016 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), 2017 AI->getArgNo() + 1, Attrs)); 2018 } 2019 } 2020 2021 if (Arg->getType().isRestrictQualified()) 2022 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), 2023 AI->getArgNo() + 1, 2024 llvm::Attribute::NoAlias)); 2025 2026 // Ensure the argument is the correct type. 2027 if (V->getType() != ArgI.getCoerceToType()) 2028 V = Builder.CreateBitCast(V, ArgI.getCoerceToType()); 2029 2030 if (isPromoted) 2031 V = emitArgumentDemotion(*this, Arg, V); 2032 2033 if (const CXXMethodDecl *MD = 2034 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) { 2035 if (MD->isVirtual() && Arg == CXXABIThisDecl) 2036 V = CGM.getCXXABI(). 2037 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V); 2038 } 2039 2040 // Because of merging of function types from multiple decls it is 2041 // possible for the type of an argument to not match the corresponding 2042 // type in the function type. Since we are codegening the callee 2043 // in here, add a cast to the argument type. 2044 llvm::Type *LTy = ConvertType(Arg->getType()); 2045 if (V->getType() != LTy) 2046 V = Builder.CreateBitCast(V, LTy); 2047 2048 ArgVals.push_back(ParamValue::forDirect(V)); 2049 break; 2050 } 2051 2052 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg), 2053 Arg->getName()); 2054 2055 // Pointer to store into. 2056 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI); 2057 2058 // Fast-isel and the optimizer generally like scalar values better than 2059 // FCAs, so we flatten them if this is safe to do for this argument. 2060 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType()); 2061 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy && 2062 STy->getNumElements() > 1) { 2063 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy); 2064 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy); 2065 llvm::Type *DstTy = Ptr.getElementType(); 2066 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy); 2067 2068 Address AddrToStoreInto = Address::invalid(); 2069 if (SrcSize <= DstSize) { 2070 AddrToStoreInto = 2071 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy)); 2072 } else { 2073 AddrToStoreInto = 2074 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce"); 2075 } 2076 2077 assert(STy->getNumElements() == NumIRArgs); 2078 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 2079 auto AI = FnArgs[FirstIRArg + i]; 2080 AI->setName(Arg->getName() + ".coerce" + Twine(i)); 2081 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i)); 2082 Address EltPtr = 2083 Builder.CreateStructGEP(AddrToStoreInto, i, Offset); 2084 Builder.CreateStore(AI, EltPtr); 2085 } 2086 2087 if (SrcSize > DstSize) { 2088 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize); 2089 } 2090 2091 } else { 2092 // Simple case, just do a coerced store of the argument into the alloca. 2093 assert(NumIRArgs == 1); 2094 auto AI = FnArgs[FirstIRArg]; 2095 AI->setName(Arg->getName() + ".coerce"); 2096 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this); 2097 } 2098 2099 // Match to what EmitParmDecl is expecting for this type. 2100 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) { 2101 llvm::Value *V = 2102 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart()); 2103 if (isPromoted) 2104 V = emitArgumentDemotion(*this, Arg, V); 2105 ArgVals.push_back(ParamValue::forDirect(V)); 2106 } else { 2107 ArgVals.push_back(ParamValue::forIndirect(Alloca)); 2108 } 2109 break; 2110 } 2111 2112 case ABIArgInfo::Expand: { 2113 // If this structure was expanded into multiple arguments then 2114 // we need to create a temporary and reconstruct it from the 2115 // arguments. 2116 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg)); 2117 LValue LV = MakeAddrLValue(Alloca, Ty); 2118 ArgVals.push_back(ParamValue::forIndirect(Alloca)); 2119 2120 auto FnArgIter = FnArgs.begin() + FirstIRArg; 2121 ExpandTypeFromArgs(Ty, LV, FnArgIter); 2122 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs); 2123 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) { 2124 auto AI = FnArgs[FirstIRArg + i]; 2125 AI->setName(Arg->getName() + "." + Twine(i)); 2126 } 2127 break; 2128 } 2129 2130 case ABIArgInfo::Ignore: 2131 assert(NumIRArgs == 0); 2132 // Initialize the local variable appropriately. 2133 if (!hasScalarEvaluationKind(Ty)) { 2134 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty))); 2135 } else { 2136 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType())); 2137 ArgVals.push_back(ParamValue::forDirect(U)); 2138 } 2139 break; 2140 } 2141 } 2142 2143 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 2144 for (int I = Args.size() - 1; I >= 0; --I) 2145 EmitParmDecl(*Args[I], ArgVals[I], I + 1); 2146 } else { 2147 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2148 EmitParmDecl(*Args[I], ArgVals[I], I + 1); 2149 } 2150 } 2151 2152 static void eraseUnusedBitCasts(llvm::Instruction *insn) { 2153 while (insn->use_empty()) { 2154 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn); 2155 if (!bitcast) return; 2156 2157 // This is "safe" because we would have used a ConstantExpr otherwise. 2158 insn = cast<llvm::Instruction>(bitcast->getOperand(0)); 2159 bitcast->eraseFromParent(); 2160 } 2161 } 2162 2163 /// Try to emit a fused autorelease of a return result. 2164 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF, 2165 llvm::Value *result) { 2166 // We must be immediately followed the cast. 2167 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock(); 2168 if (BB->empty()) return nullptr; 2169 if (&BB->back() != result) return nullptr; 2170 2171 llvm::Type *resultType = result->getType(); 2172 2173 // result is in a BasicBlock and is therefore an Instruction. 2174 llvm::Instruction *generator = cast<llvm::Instruction>(result); 2175 2176 SmallVector<llvm::Instruction*,4> insnsToKill; 2177 2178 // Look for: 2179 // %generator = bitcast %type1* %generator2 to %type2* 2180 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) { 2181 // We would have emitted this as a constant if the operand weren't 2182 // an Instruction. 2183 generator = cast<llvm::Instruction>(bitcast->getOperand(0)); 2184 2185 // Require the generator to be immediately followed by the cast. 2186 if (generator->getNextNode() != bitcast) 2187 return nullptr; 2188 2189 insnsToKill.push_back(bitcast); 2190 } 2191 2192 // Look for: 2193 // %generator = call i8* @objc_retain(i8* %originalResult) 2194 // or 2195 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult) 2196 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator); 2197 if (!call) return nullptr; 2198 2199 bool doRetainAutorelease; 2200 2201 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) { 2202 doRetainAutorelease = true; 2203 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints() 2204 .objc_retainAutoreleasedReturnValue) { 2205 doRetainAutorelease = false; 2206 2207 // If we emitted an assembly marker for this call (and the 2208 // ARCEntrypoints field should have been set if so), go looking 2209 // for that call. If we can't find it, we can't do this 2210 // optimization. But it should always be the immediately previous 2211 // instruction, unless we needed bitcasts around the call. 2212 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) { 2213 llvm::Instruction *prev = call->getPrevNode(); 2214 assert(prev); 2215 if (isa<llvm::BitCastInst>(prev)) { 2216 prev = prev->getPrevNode(); 2217 assert(prev); 2218 } 2219 assert(isa<llvm::CallInst>(prev)); 2220 assert(cast<llvm::CallInst>(prev)->getCalledValue() == 2221 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker); 2222 insnsToKill.push_back(prev); 2223 } 2224 } else { 2225 return nullptr; 2226 } 2227 2228 result = call->getArgOperand(0); 2229 insnsToKill.push_back(call); 2230 2231 // Keep killing bitcasts, for sanity. Note that we no longer care 2232 // about precise ordering as long as there's exactly one use. 2233 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) { 2234 if (!bitcast->hasOneUse()) break; 2235 insnsToKill.push_back(bitcast); 2236 result = bitcast->getOperand(0); 2237 } 2238 2239 // Delete all the unnecessary instructions, from latest to earliest. 2240 for (SmallVectorImpl<llvm::Instruction*>::iterator 2241 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i) 2242 (*i)->eraseFromParent(); 2243 2244 // Do the fused retain/autorelease if we were asked to. 2245 if (doRetainAutorelease) 2246 result = CGF.EmitARCRetainAutoreleaseReturnValue(result); 2247 2248 // Cast back to the result type. 2249 return CGF.Builder.CreateBitCast(result, resultType); 2250 } 2251 2252 /// If this is a +1 of the value of an immutable 'self', remove it. 2253 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF, 2254 llvm::Value *result) { 2255 // This is only applicable to a method with an immutable 'self'. 2256 const ObjCMethodDecl *method = 2257 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl); 2258 if (!method) return nullptr; 2259 const VarDecl *self = method->getSelfDecl(); 2260 if (!self->getType().isConstQualified()) return nullptr; 2261 2262 // Look for a retain call. 2263 llvm::CallInst *retainCall = 2264 dyn_cast<llvm::CallInst>(result->stripPointerCasts()); 2265 if (!retainCall || 2266 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain) 2267 return nullptr; 2268 2269 // Look for an ordinary load of 'self'. 2270 llvm::Value *retainedValue = retainCall->getArgOperand(0); 2271 llvm::LoadInst *load = 2272 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts()); 2273 if (!load || load->isAtomic() || load->isVolatile() || 2274 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer()) 2275 return nullptr; 2276 2277 // Okay! Burn it all down. This relies for correctness on the 2278 // assumption that the retain is emitted as part of the return and 2279 // that thereafter everything is used "linearly". 2280 llvm::Type *resultType = result->getType(); 2281 eraseUnusedBitCasts(cast<llvm::Instruction>(result)); 2282 assert(retainCall->use_empty()); 2283 retainCall->eraseFromParent(); 2284 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue)); 2285 2286 return CGF.Builder.CreateBitCast(load, resultType); 2287 } 2288 2289 /// Emit an ARC autorelease of the result of a function. 2290 /// 2291 /// \return the value to actually return from the function 2292 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF, 2293 llvm::Value *result) { 2294 // If we're returning 'self', kill the initial retain. This is a 2295 // heuristic attempt to "encourage correctness" in the really unfortunate 2296 // case where we have a return of self during a dealloc and we desperately 2297 // need to avoid the possible autorelease. 2298 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result)) 2299 return self; 2300 2301 // At -O0, try to emit a fused retain/autorelease. 2302 if (CGF.shouldUseFusedARCCalls()) 2303 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result)) 2304 return fused; 2305 2306 return CGF.EmitARCAutoreleaseReturnValue(result); 2307 } 2308 2309 /// Heuristically search for a dominating store to the return-value slot. 2310 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) { 2311 // Check if a User is a store which pointerOperand is the ReturnValue. 2312 // We are looking for stores to the ReturnValue, not for stores of the 2313 // ReturnValue to some other location. 2314 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * { 2315 auto *SI = dyn_cast<llvm::StoreInst>(U); 2316 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer()) 2317 return nullptr; 2318 // These aren't actually possible for non-coerced returns, and we 2319 // only care about non-coerced returns on this code path. 2320 assert(!SI->isAtomic() && !SI->isVolatile()); 2321 return SI; 2322 }; 2323 // If there are multiple uses of the return-value slot, just check 2324 // for something immediately preceding the IP. Sometimes this can 2325 // happen with how we generate implicit-returns; it can also happen 2326 // with noreturn cleanups. 2327 if (!CGF.ReturnValue.getPointer()->hasOneUse()) { 2328 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 2329 if (IP->empty()) return nullptr; 2330 llvm::Instruction *I = &IP->back(); 2331 2332 // Skip lifetime markers 2333 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(), 2334 IE = IP->rend(); 2335 II != IE; ++II) { 2336 if (llvm::IntrinsicInst *Intrinsic = 2337 dyn_cast<llvm::IntrinsicInst>(&*II)) { 2338 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) { 2339 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1); 2340 ++II; 2341 if (II == IE) 2342 break; 2343 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II)) 2344 continue; 2345 } 2346 } 2347 I = &*II; 2348 break; 2349 } 2350 2351 return GetStoreIfValid(I); 2352 } 2353 2354 llvm::StoreInst *store = 2355 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back()); 2356 if (!store) return nullptr; 2357 2358 // Now do a first-and-dirty dominance check: just walk up the 2359 // single-predecessors chain from the current insertion point. 2360 llvm::BasicBlock *StoreBB = store->getParent(); 2361 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 2362 while (IP != StoreBB) { 2363 if (!(IP = IP->getSinglePredecessor())) 2364 return nullptr; 2365 } 2366 2367 // Okay, the store's basic block dominates the insertion point; we 2368 // can do our thing. 2369 return store; 2370 } 2371 2372 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI, 2373 bool EmitRetDbgLoc, 2374 SourceLocation EndLoc) { 2375 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) { 2376 // Naked functions don't have epilogues. 2377 Builder.CreateUnreachable(); 2378 return; 2379 } 2380 2381 // Functions with no result always return void. 2382 if (!ReturnValue.isValid()) { 2383 Builder.CreateRetVoid(); 2384 return; 2385 } 2386 2387 llvm::DebugLoc RetDbgLoc; 2388 llvm::Value *RV = nullptr; 2389 QualType RetTy = FI.getReturnType(); 2390 const ABIArgInfo &RetAI = FI.getReturnInfo(); 2391 2392 switch (RetAI.getKind()) { 2393 case ABIArgInfo::InAlloca: 2394 // Aggregrates get evaluated directly into the destination. Sometimes we 2395 // need to return the sret value in a register, though. 2396 assert(hasAggregateEvaluationKind(RetTy)); 2397 if (RetAI.getInAllocaSRet()) { 2398 llvm::Function::arg_iterator EI = CurFn->arg_end(); 2399 --EI; 2400 llvm::Value *ArgStruct = &*EI; 2401 llvm::Value *SRet = Builder.CreateStructGEP( 2402 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex()); 2403 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret"); 2404 } 2405 break; 2406 2407 case ABIArgInfo::Indirect: { 2408 auto AI = CurFn->arg_begin(); 2409 if (RetAI.isSRetAfterThis()) 2410 ++AI; 2411 switch (getEvaluationKind(RetTy)) { 2412 case TEK_Complex: { 2413 ComplexPairTy RT = 2414 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc); 2415 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy), 2416 /*isInit*/ true); 2417 break; 2418 } 2419 case TEK_Aggregate: 2420 // Do nothing; aggregrates get evaluated directly into the destination. 2421 break; 2422 case TEK_Scalar: 2423 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), 2424 MakeNaturalAlignAddrLValue(&*AI, RetTy), 2425 /*isInit*/ true); 2426 break; 2427 } 2428 break; 2429 } 2430 2431 case ABIArgInfo::Extend: 2432 case ABIArgInfo::Direct: 2433 if (RetAI.getCoerceToType() == ConvertType(RetTy) && 2434 RetAI.getDirectOffset() == 0) { 2435 // The internal return value temp always will have pointer-to-return-type 2436 // type, just do a load. 2437 2438 // If there is a dominating store to ReturnValue, we can elide 2439 // the load, zap the store, and usually zap the alloca. 2440 if (llvm::StoreInst *SI = 2441 findDominatingStoreToReturnValue(*this)) { 2442 // Reuse the debug location from the store unless there is 2443 // cleanup code to be emitted between the store and return 2444 // instruction. 2445 if (EmitRetDbgLoc && !AutoreleaseResult) 2446 RetDbgLoc = SI->getDebugLoc(); 2447 // Get the stored value and nuke the now-dead store. 2448 RV = SI->getValueOperand(); 2449 SI->eraseFromParent(); 2450 2451 // If that was the only use of the return value, nuke it as well now. 2452 auto returnValueInst = ReturnValue.getPointer(); 2453 if (returnValueInst->use_empty()) { 2454 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) { 2455 alloca->eraseFromParent(); 2456 ReturnValue = Address::invalid(); 2457 } 2458 } 2459 2460 // Otherwise, we have to do a simple load. 2461 } else { 2462 RV = Builder.CreateLoad(ReturnValue); 2463 } 2464 } else { 2465 // If the value is offset in memory, apply the offset now. 2466 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI); 2467 2468 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this); 2469 } 2470 2471 // In ARC, end functions that return a retainable type with a call 2472 // to objc_autoreleaseReturnValue. 2473 if (AutoreleaseResult) { 2474 #ifndef NDEBUG 2475 // Type::isObjCRetainabletype has to be called on a QualType that hasn't 2476 // been stripped of the typedefs, so we cannot use RetTy here. Get the 2477 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from 2478 // CurCodeDecl or BlockInfo. 2479 QualType RT; 2480 2481 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl)) 2482 RT = FD->getReturnType(); 2483 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl)) 2484 RT = MD->getReturnType(); 2485 else if (isa<BlockDecl>(CurCodeDecl)) 2486 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType(); 2487 else 2488 llvm_unreachable("Unexpected function/method type"); 2489 2490 assert(getLangOpts().ObjCAutoRefCount && 2491 !FI.isReturnsRetained() && 2492 RT->isObjCRetainableType()); 2493 #endif 2494 RV = emitAutoreleaseOfResult(*this, RV); 2495 } 2496 2497 break; 2498 2499 case ABIArgInfo::Ignore: 2500 break; 2501 2502 case ABIArgInfo::Expand: 2503 llvm_unreachable("Invalid ABI kind for return argument"); 2504 } 2505 2506 llvm::Instruction *Ret; 2507 if (RV) { 2508 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) { 2509 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) { 2510 SanitizerScope SanScope(this); 2511 llvm::Value *Cond = Builder.CreateICmpNE( 2512 RV, llvm::Constant::getNullValue(RV->getType())); 2513 llvm::Constant *StaticData[] = { 2514 EmitCheckSourceLocation(EndLoc), 2515 EmitCheckSourceLocation(RetNNAttr->getLocation()), 2516 }; 2517 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute), 2518 "nonnull_return", StaticData, None); 2519 } 2520 } 2521 Ret = Builder.CreateRet(RV); 2522 } else { 2523 Ret = Builder.CreateRetVoid(); 2524 } 2525 2526 if (RetDbgLoc) 2527 Ret->setDebugLoc(std::move(RetDbgLoc)); 2528 } 2529 2530 static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) { 2531 const CXXRecordDecl *RD = type->getAsCXXRecordDecl(); 2532 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory; 2533 } 2534 2535 static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, 2536 QualType Ty) { 2537 // FIXME: Generate IR in one pass, rather than going back and fixing up these 2538 // placeholders. 2539 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty); 2540 llvm::Value *Placeholder = 2541 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo()); 2542 Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder); 2543 2544 // FIXME: When we generate this IR in one pass, we shouldn't need 2545 // this win32-specific alignment hack. 2546 CharUnits Align = CharUnits::fromQuantity(4); 2547 2548 return AggValueSlot::forAddr(Address(Placeholder, Align), 2549 Ty.getQualifiers(), 2550 AggValueSlot::IsNotDestructed, 2551 AggValueSlot::DoesNotNeedGCBarriers, 2552 AggValueSlot::IsNotAliased); 2553 } 2554 2555 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args, 2556 const VarDecl *param, 2557 SourceLocation loc) { 2558 // StartFunction converted the ABI-lowered parameter(s) into a 2559 // local alloca. We need to turn that into an r-value suitable 2560 // for EmitCall. 2561 Address local = GetAddrOfLocalVar(param); 2562 2563 QualType type = param->getType(); 2564 2565 // For the most part, we just need to load the alloca, except: 2566 // 1) aggregate r-values are actually pointers to temporaries, and 2567 // 2) references to non-scalars are pointers directly to the aggregate. 2568 // I don't know why references to scalars are different here. 2569 if (const ReferenceType *ref = type->getAs<ReferenceType>()) { 2570 if (!hasScalarEvaluationKind(ref->getPointeeType())) 2571 return args.add(RValue::getAggregate(local), type); 2572 2573 // Locals which are references to scalars are represented 2574 // with allocas holding the pointer. 2575 return args.add(RValue::get(Builder.CreateLoad(local)), type); 2576 } 2577 2578 assert(!isInAllocaArgument(CGM.getCXXABI(), type) && 2579 "cannot emit delegate call arguments for inalloca arguments!"); 2580 2581 args.add(convertTempToRValue(local, type, loc), type); 2582 } 2583 2584 static bool isProvablyNull(llvm::Value *addr) { 2585 return isa<llvm::ConstantPointerNull>(addr); 2586 } 2587 2588 static bool isProvablyNonNull(llvm::Value *addr) { 2589 return isa<llvm::AllocaInst>(addr); 2590 } 2591 2592 /// Emit the actual writing-back of a writeback. 2593 static void emitWriteback(CodeGenFunction &CGF, 2594 const CallArgList::Writeback &writeback) { 2595 const LValue &srcLV = writeback.Source; 2596 Address srcAddr = srcLV.getAddress(); 2597 assert(!isProvablyNull(srcAddr.getPointer()) && 2598 "shouldn't have writeback for provably null argument"); 2599 2600 llvm::BasicBlock *contBB = nullptr; 2601 2602 // If the argument wasn't provably non-null, we need to null check 2603 // before doing the store. 2604 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer()); 2605 if (!provablyNonNull) { 2606 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback"); 2607 contBB = CGF.createBasicBlock("icr.done"); 2608 2609 llvm::Value *isNull = 2610 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); 2611 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB); 2612 CGF.EmitBlock(writebackBB); 2613 } 2614 2615 // Load the value to writeback. 2616 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary); 2617 2618 // Cast it back, in case we're writing an id to a Foo* or something. 2619 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(), 2620 "icr.writeback-cast"); 2621 2622 // Perform the writeback. 2623 2624 // If we have a "to use" value, it's something we need to emit a use 2625 // of. This has to be carefully threaded in: if it's done after the 2626 // release it's potentially undefined behavior (and the optimizer 2627 // will ignore it), and if it happens before the retain then the 2628 // optimizer could move the release there. 2629 if (writeback.ToUse) { 2630 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong); 2631 2632 // Retain the new value. No need to block-copy here: the block's 2633 // being passed up the stack. 2634 value = CGF.EmitARCRetainNonBlock(value); 2635 2636 // Emit the intrinsic use here. 2637 CGF.EmitARCIntrinsicUse(writeback.ToUse); 2638 2639 // Load the old value (primitively). 2640 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation()); 2641 2642 // Put the new value in place (primitively). 2643 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false); 2644 2645 // Release the old value. 2646 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime()); 2647 2648 // Otherwise, we can just do a normal lvalue store. 2649 } else { 2650 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV); 2651 } 2652 2653 // Jump to the continuation block. 2654 if (!provablyNonNull) 2655 CGF.EmitBlock(contBB); 2656 } 2657 2658 static void emitWritebacks(CodeGenFunction &CGF, 2659 const CallArgList &args) { 2660 for (const auto &I : args.writebacks()) 2661 emitWriteback(CGF, I); 2662 } 2663 2664 static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF, 2665 const CallArgList &CallArgs) { 2666 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()); 2667 ArrayRef<CallArgList::CallArgCleanup> Cleanups = 2668 CallArgs.getCleanupsToDeactivate(); 2669 // Iterate in reverse to increase the likelihood of popping the cleanup. 2670 for (const auto &I : llvm::reverse(Cleanups)) { 2671 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP); 2672 I.IsActiveIP->eraseFromParent(); 2673 } 2674 } 2675 2676 static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) { 2677 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens())) 2678 if (uop->getOpcode() == UO_AddrOf) 2679 return uop->getSubExpr(); 2680 return nullptr; 2681 } 2682 2683 /// Emit an argument that's being passed call-by-writeback. That is, 2684 /// we are passing the address of an __autoreleased temporary; it 2685 /// might be copy-initialized with the current value of the given 2686 /// address, but it will definitely be copied out of after the call. 2687 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, 2688 const ObjCIndirectCopyRestoreExpr *CRE) { 2689 LValue srcLV; 2690 2691 // Make an optimistic effort to emit the address as an l-value. 2692 // This can fail if the argument expression is more complicated. 2693 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) { 2694 srcLV = CGF.EmitLValue(lvExpr); 2695 2696 // Otherwise, just emit it as a scalar. 2697 } else { 2698 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr()); 2699 2700 QualType srcAddrType = 2701 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType(); 2702 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType); 2703 } 2704 Address srcAddr = srcLV.getAddress(); 2705 2706 // The dest and src types don't necessarily match in LLVM terms 2707 // because of the crazy ObjC compatibility rules. 2708 2709 llvm::PointerType *destType = 2710 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType())); 2711 2712 // If the address is a constant null, just pass the appropriate null. 2713 if (isProvablyNull(srcAddr.getPointer())) { 2714 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)), 2715 CRE->getType()); 2716 return; 2717 } 2718 2719 // Create the temporary. 2720 Address temp = CGF.CreateTempAlloca(destType->getElementType(), 2721 CGF.getPointerAlign(), 2722 "icr.temp"); 2723 // Loading an l-value can introduce a cleanup if the l-value is __weak, 2724 // and that cleanup will be conditional if we can't prove that the l-value 2725 // isn't null, so we need to register a dominating point so that the cleanups 2726 // system will make valid IR. 2727 CodeGenFunction::ConditionalEvaluation condEval(CGF); 2728 2729 // Zero-initialize it if we're not doing a copy-initialization. 2730 bool shouldCopy = CRE->shouldCopy(); 2731 if (!shouldCopy) { 2732 llvm::Value *null = 2733 llvm::ConstantPointerNull::get( 2734 cast<llvm::PointerType>(destType->getElementType())); 2735 CGF.Builder.CreateStore(null, temp); 2736 } 2737 2738 llvm::BasicBlock *contBB = nullptr; 2739 llvm::BasicBlock *originBB = nullptr; 2740 2741 // If the address is *not* known to be non-null, we need to switch. 2742 llvm::Value *finalArgument; 2743 2744 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer()); 2745 if (provablyNonNull) { 2746 finalArgument = temp.getPointer(); 2747 } else { 2748 llvm::Value *isNull = 2749 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); 2750 2751 finalArgument = CGF.Builder.CreateSelect(isNull, 2752 llvm::ConstantPointerNull::get(destType), 2753 temp.getPointer(), "icr.argument"); 2754 2755 // If we need to copy, then the load has to be conditional, which 2756 // means we need control flow. 2757 if (shouldCopy) { 2758 originBB = CGF.Builder.GetInsertBlock(); 2759 contBB = CGF.createBasicBlock("icr.cont"); 2760 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy"); 2761 CGF.Builder.CreateCondBr(isNull, contBB, copyBB); 2762 CGF.EmitBlock(copyBB); 2763 condEval.begin(CGF); 2764 } 2765 } 2766 2767 llvm::Value *valueToUse = nullptr; 2768 2769 // Perform a copy if necessary. 2770 if (shouldCopy) { 2771 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation()); 2772 assert(srcRV.isScalar()); 2773 2774 llvm::Value *src = srcRV.getScalarVal(); 2775 src = CGF.Builder.CreateBitCast(src, destType->getElementType(), 2776 "icr.cast"); 2777 2778 // Use an ordinary store, not a store-to-lvalue. 2779 CGF.Builder.CreateStore(src, temp); 2780 2781 // If optimization is enabled, and the value was held in a 2782 // __strong variable, we need to tell the optimizer that this 2783 // value has to stay alive until we're doing the store back. 2784 // This is because the temporary is effectively unretained, 2785 // and so otherwise we can violate the high-level semantics. 2786 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 && 2787 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) { 2788 valueToUse = src; 2789 } 2790 } 2791 2792 // Finish the control flow if we needed it. 2793 if (shouldCopy && !provablyNonNull) { 2794 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock(); 2795 CGF.EmitBlock(contBB); 2796 2797 // Make a phi for the value to intrinsically use. 2798 if (valueToUse) { 2799 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2, 2800 "icr.to-use"); 2801 phiToUse->addIncoming(valueToUse, copyBB); 2802 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()), 2803 originBB); 2804 valueToUse = phiToUse; 2805 } 2806 2807 condEval.end(CGF); 2808 } 2809 2810 args.addWriteback(srcLV, temp, valueToUse); 2811 args.add(RValue::get(finalArgument), CRE->getType()); 2812 } 2813 2814 void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) { 2815 assert(!StackBase && !StackCleanup.isValid()); 2816 2817 // Save the stack. 2818 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave); 2819 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save"); 2820 } 2821 2822 void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const { 2823 if (StackBase) { 2824 // Restore the stack after the call. 2825 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 2826 CGF.Builder.CreateCall(F, StackBase); 2827 } 2828 } 2829 2830 void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType, 2831 SourceLocation ArgLoc, 2832 const FunctionDecl *FD, 2833 unsigned ParmNum) { 2834 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD) 2835 return; 2836 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr; 2837 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum; 2838 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo); 2839 if (!NNAttr) 2840 return; 2841 SanitizerScope SanScope(this); 2842 assert(RV.isScalar()); 2843 llvm::Value *V = RV.getScalarVal(); 2844 llvm::Value *Cond = 2845 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType())); 2846 llvm::Constant *StaticData[] = { 2847 EmitCheckSourceLocation(ArgLoc), 2848 EmitCheckSourceLocation(NNAttr->getLocation()), 2849 llvm::ConstantInt::get(Int32Ty, ArgNo + 1), 2850 }; 2851 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute), 2852 "nonnull_arg", StaticData, None); 2853 } 2854 2855 void CodeGenFunction::EmitCallArgs( 2856 CallArgList &Args, ArrayRef<QualType> ArgTypes, 2857 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 2858 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip) { 2859 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin())); 2860 2861 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) { 2862 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams()) 2863 return; 2864 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>(); 2865 if (PS == nullptr) 2866 return; 2867 2868 const auto &Context = getContext(); 2869 auto SizeTy = Context.getSizeType(); 2870 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy)); 2871 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T); 2872 Args.add(RValue::get(V), SizeTy); 2873 }; 2874 2875 // We *have* to evaluate arguments from right to left in the MS C++ ABI, 2876 // because arguments are destroyed left to right in the callee. 2877 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 2878 // Insert a stack save if we're going to need any inalloca args. 2879 bool HasInAllocaArgs = false; 2880 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end(); 2881 I != E && !HasInAllocaArgs; ++I) 2882 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I); 2883 if (HasInAllocaArgs) { 2884 assert(getTarget().getTriple().getArch() == llvm::Triple::x86); 2885 Args.allocateArgumentMemory(*this); 2886 } 2887 2888 // Evaluate each argument. 2889 size_t CallArgsStart = Args.size(); 2890 for (int I = ArgTypes.size() - 1; I >= 0; --I) { 2891 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I; 2892 EmitCallArg(Args, *Arg, ArgTypes[I]); 2893 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(), 2894 CalleeDecl, ParamsToSkip + I); 2895 MaybeEmitImplicitObjectSize(I, *Arg); 2896 } 2897 2898 // Un-reverse the arguments we just evaluated so they match up with the LLVM 2899 // IR function. 2900 std::reverse(Args.begin() + CallArgsStart, Args.end()); 2901 return; 2902 } 2903 2904 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) { 2905 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I; 2906 assert(Arg != ArgRange.end()); 2907 EmitCallArg(Args, *Arg, ArgTypes[I]); 2908 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(), 2909 CalleeDecl, ParamsToSkip + I); 2910 MaybeEmitImplicitObjectSize(I, *Arg); 2911 } 2912 } 2913 2914 namespace { 2915 2916 struct DestroyUnpassedArg final : EHScopeStack::Cleanup { 2917 DestroyUnpassedArg(Address Addr, QualType Ty) 2918 : Addr(Addr), Ty(Ty) {} 2919 2920 Address Addr; 2921 QualType Ty; 2922 2923 void Emit(CodeGenFunction &CGF, Flags flags) override { 2924 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor(); 2925 assert(!Dtor->isTrivial()); 2926 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false, 2927 /*Delegating=*/false, Addr); 2928 } 2929 }; 2930 2931 struct DisableDebugLocationUpdates { 2932 CodeGenFunction &CGF; 2933 bool disabledDebugInfo; 2934 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) { 2935 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo())) 2936 CGF.disableDebugInfo(); 2937 } 2938 ~DisableDebugLocationUpdates() { 2939 if (disabledDebugInfo) 2940 CGF.enableDebugInfo(); 2941 } 2942 }; 2943 2944 } // end anonymous namespace 2945 2946 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E, 2947 QualType type) { 2948 DisableDebugLocationUpdates Dis(*this, E); 2949 if (const ObjCIndirectCopyRestoreExpr *CRE 2950 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) { 2951 assert(getLangOpts().ObjCAutoRefCount); 2952 assert(getContext().hasSameType(E->getType(), type)); 2953 return emitWritebackArg(*this, args, CRE); 2954 } 2955 2956 assert(type->isReferenceType() == E->isGLValue() && 2957 "reference binding to unmaterialized r-value!"); 2958 2959 if (E->isGLValue()) { 2960 assert(E->getObjectKind() == OK_Ordinary); 2961 return args.add(EmitReferenceBindingToExpr(E), type); 2962 } 2963 2964 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type); 2965 2966 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee. 2967 // However, we still have to push an EH-only cleanup in case we unwind before 2968 // we make it to the call. 2969 if (HasAggregateEvalKind && 2970 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 2971 // If we're using inalloca, use the argument memory. Otherwise, use a 2972 // temporary. 2973 AggValueSlot Slot; 2974 if (args.isUsingInAlloca()) 2975 Slot = createPlaceholderSlot(*this, type); 2976 else 2977 Slot = CreateAggTemp(type, "agg.tmp"); 2978 2979 const CXXRecordDecl *RD = type->getAsCXXRecordDecl(); 2980 bool DestroyedInCallee = 2981 RD && RD->hasNonTrivialDestructor() && 2982 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default; 2983 if (DestroyedInCallee) 2984 Slot.setExternallyDestructed(); 2985 2986 EmitAggExpr(E, Slot); 2987 RValue RV = Slot.asRValue(); 2988 args.add(RV, type); 2989 2990 if (DestroyedInCallee) { 2991 // Create a no-op GEP between the placeholder and the cleanup so we can 2992 // RAUW it successfully. It also serves as a marker of the first 2993 // instruction where the cleanup is active. 2994 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(), 2995 type); 2996 // This unreachable is a temporary marker which will be removed later. 2997 llvm::Instruction *IsActive = Builder.CreateUnreachable(); 2998 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive); 2999 } 3000 return; 3001 } 3002 3003 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) && 3004 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) { 3005 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr()); 3006 assert(L.isSimple()); 3007 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) { 3008 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true); 3009 } else { 3010 // We can't represent a misaligned lvalue in the CallArgList, so copy 3011 // to an aligned temporary now. 3012 Address tmp = CreateMemTemp(type); 3013 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile()); 3014 args.add(RValue::getAggregate(tmp), type); 3015 } 3016 return; 3017 } 3018 3019 args.add(EmitAnyExprToTemp(E), type); 3020 } 3021 3022 QualType CodeGenFunction::getVarArgType(const Expr *Arg) { 3023 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC 3024 // implicitly widens null pointer constants that are arguments to varargs 3025 // functions to pointer-sized ints. 3026 if (!getTarget().getTriple().isOSWindows()) 3027 return Arg->getType(); 3028 3029 if (Arg->getType()->isIntegerType() && 3030 getContext().getTypeSize(Arg->getType()) < 3031 getContext().getTargetInfo().getPointerWidth(0) && 3032 Arg->isNullPointerConstant(getContext(), 3033 Expr::NPC_ValueDependentIsNotNull)) { 3034 return getContext().getIntPtrType(); 3035 } 3036 3037 return Arg->getType(); 3038 } 3039 3040 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3041 // optimizer it can aggressively ignore unwind edges. 3042 void 3043 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) { 3044 if (CGM.getCodeGenOpts().OptimizationLevel != 0 && 3045 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions) 3046 Inst->setMetadata("clang.arc.no_objc_arc_exceptions", 3047 CGM.getNoObjCARCExceptionsMetadata()); 3048 } 3049 3050 /// Emits a call to the given no-arguments nounwind runtime function. 3051 llvm::CallInst * 3052 CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee, 3053 const llvm::Twine &name) { 3054 return EmitNounwindRuntimeCall(callee, None, name); 3055 } 3056 3057 /// Emits a call to the given nounwind runtime function. 3058 llvm::CallInst * 3059 CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee, 3060 ArrayRef<llvm::Value*> args, 3061 const llvm::Twine &name) { 3062 llvm::CallInst *call = EmitRuntimeCall(callee, args, name); 3063 call->setDoesNotThrow(); 3064 return call; 3065 } 3066 3067 /// Emits a simple call (never an invoke) to the given no-arguments 3068 /// runtime function. 3069 llvm::CallInst * 3070 CodeGenFunction::EmitRuntimeCall(llvm::Value *callee, 3071 const llvm::Twine &name) { 3072 return EmitRuntimeCall(callee, None, name); 3073 } 3074 3075 // Calls which may throw must have operand bundles indicating which funclet 3076 // they are nested within. 3077 static void 3078 getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad, 3079 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) { 3080 // There is no need for a funclet operand bundle if we aren't inside a 3081 // funclet. 3082 if (!CurrentFuncletPad) 3083 return; 3084 3085 // Skip intrinsics which cannot throw. 3086 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts()); 3087 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) 3088 return; 3089 3090 BundleList.emplace_back("funclet", CurrentFuncletPad); 3091 } 3092 3093 /// Emits a simple call (never an invoke) to the given runtime function. 3094 llvm::CallInst * 3095 CodeGenFunction::EmitRuntimeCall(llvm::Value *callee, 3096 ArrayRef<llvm::Value*> args, 3097 const llvm::Twine &name) { 3098 SmallVector<llvm::OperandBundleDef, 1> BundleList; 3099 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList); 3100 3101 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name); 3102 call->setCallingConv(getRuntimeCC()); 3103 return call; 3104 } 3105 3106 /// Emits a call or invoke to the given noreturn runtime function. 3107 void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee, 3108 ArrayRef<llvm::Value*> args) { 3109 SmallVector<llvm::OperandBundleDef, 1> BundleList; 3110 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList); 3111 3112 if (getInvokeDest()) { 3113 llvm::InvokeInst *invoke = 3114 Builder.CreateInvoke(callee, 3115 getUnreachableBlock(), 3116 getInvokeDest(), 3117 args, 3118 BundleList); 3119 invoke->setDoesNotReturn(); 3120 invoke->setCallingConv(getRuntimeCC()); 3121 } else { 3122 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList); 3123 call->setDoesNotReturn(); 3124 call->setCallingConv(getRuntimeCC()); 3125 Builder.CreateUnreachable(); 3126 } 3127 } 3128 3129 /// Emits a call or invoke instruction to the given nullary runtime function. 3130 llvm::CallSite 3131 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee, 3132 const Twine &name) { 3133 return EmitRuntimeCallOrInvoke(callee, None, name); 3134 } 3135 3136 /// Emits a call or invoke instruction to the given runtime function. 3137 llvm::CallSite 3138 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee, 3139 ArrayRef<llvm::Value*> args, 3140 const Twine &name) { 3141 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name); 3142 callSite.setCallingConv(getRuntimeCC()); 3143 return callSite; 3144 } 3145 3146 /// Emits a call or invoke instruction to the given function, depending 3147 /// on the current state of the EH stack. 3148 llvm::CallSite 3149 CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee, 3150 ArrayRef<llvm::Value *> Args, 3151 const Twine &Name) { 3152 llvm::BasicBlock *InvokeDest = getInvokeDest(); 3153 SmallVector<llvm::OperandBundleDef, 1> BundleList; 3154 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList); 3155 3156 llvm::Instruction *Inst; 3157 if (!InvokeDest) 3158 Inst = Builder.CreateCall(Callee, Args, BundleList, Name); 3159 else { 3160 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont"); 3161 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList, 3162 Name); 3163 EmitBlock(ContBB); 3164 } 3165 3166 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3167 // optimizer it can aggressively ignore unwind edges. 3168 if (CGM.getLangOpts().ObjCAutoRefCount) 3169 AddObjCARCExceptionMetadata(Inst); 3170 3171 return llvm::CallSite(Inst); 3172 } 3173 3174 /// \brief Store a non-aggregate value to an address to initialize it. For 3175 /// initialization, a non-atomic store will be used. 3176 static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src, 3177 LValue Dst) { 3178 if (Src.isScalar()) 3179 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true); 3180 else 3181 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true); 3182 } 3183 3184 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old, 3185 llvm::Value *New) { 3186 DeferredReplacements.push_back(std::make_pair(Old, New)); 3187 } 3188 3189 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, 3190 llvm::Value *Callee, 3191 ReturnValueSlot ReturnValue, 3192 const CallArgList &CallArgs, 3193 CGCalleeInfo CalleeInfo, 3194 llvm::Instruction **callOrInvoke) { 3195 // FIXME: We no longer need the types from CallArgs; lift up and simplify. 3196 3197 // Handle struct-return functions by passing a pointer to the 3198 // location that we would like to return into. 3199 QualType RetTy = CallInfo.getReturnType(); 3200 const ABIArgInfo &RetAI = CallInfo.getReturnInfo(); 3201 3202 llvm::FunctionType *IRFuncTy = 3203 cast<llvm::FunctionType>( 3204 cast<llvm::PointerType>(Callee->getType())->getElementType()); 3205 3206 // If we're using inalloca, insert the allocation after the stack save. 3207 // FIXME: Do this earlier rather than hacking it in here! 3208 Address ArgMemory = Address::invalid(); 3209 const llvm::StructLayout *ArgMemoryLayout = nullptr; 3210 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) { 3211 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct); 3212 llvm::Instruction *IP = CallArgs.getStackBase(); 3213 llvm::AllocaInst *AI; 3214 if (IP) { 3215 IP = IP->getNextNode(); 3216 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP); 3217 } else { 3218 AI = CreateTempAlloca(ArgStruct, "argmem"); 3219 } 3220 auto Align = CallInfo.getArgStructAlignment(); 3221 AI->setAlignment(Align.getQuantity()); 3222 AI->setUsedWithInAlloca(true); 3223 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca()); 3224 ArgMemory = Address(AI, Align); 3225 } 3226 3227 // Helper function to drill into the inalloca allocation. 3228 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address { 3229 auto FieldOffset = 3230 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex)); 3231 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset); 3232 }; 3233 3234 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo); 3235 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs()); 3236 3237 // If the call returns a temporary with struct return, create a temporary 3238 // alloca to hold the result, unless one is given to us. 3239 Address SRetPtr = Address::invalid(); 3240 size_t UnusedReturnSize = 0; 3241 if (RetAI.isIndirect() || RetAI.isInAlloca()) { 3242 if (!ReturnValue.isNull()) { 3243 SRetPtr = ReturnValue.getValue(); 3244 } else { 3245 SRetPtr = CreateMemTemp(RetTy); 3246 if (HaveInsertPoint() && ReturnValue.isUnused()) { 3247 uint64_t size = 3248 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy)); 3249 if (EmitLifetimeStart(size, SRetPtr.getPointer())) 3250 UnusedReturnSize = size; 3251 } 3252 } 3253 if (IRFunctionArgs.hasSRetArg()) { 3254 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer(); 3255 } else { 3256 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex()); 3257 Builder.CreateStore(SRetPtr.getPointer(), Addr); 3258 } 3259 } 3260 3261 assert(CallInfo.arg_size() == CallArgs.size() && 3262 "Mismatch between function signature & arguments."); 3263 unsigned ArgNo = 0; 3264 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin(); 3265 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); 3266 I != E; ++I, ++info_it, ++ArgNo) { 3267 const ABIArgInfo &ArgInfo = info_it->info; 3268 RValue RV = I->RV; 3269 3270 // Insert a padding argument to ensure proper alignment. 3271 if (IRFunctionArgs.hasPaddingArg(ArgNo)) 3272 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 3273 llvm::UndefValue::get(ArgInfo.getPaddingType()); 3274 3275 unsigned FirstIRArg, NumIRArgs; 3276 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 3277 3278 switch (ArgInfo.getKind()) { 3279 case ABIArgInfo::InAlloca: { 3280 assert(NumIRArgs == 0); 3281 assert(getTarget().getTriple().getArch() == llvm::Triple::x86); 3282 if (RV.isAggregate()) { 3283 // Replace the placeholder with the appropriate argument slot GEP. 3284 llvm::Instruction *Placeholder = 3285 cast<llvm::Instruction>(RV.getAggregatePointer()); 3286 CGBuilderTy::InsertPoint IP = Builder.saveIP(); 3287 Builder.SetInsertPoint(Placeholder); 3288 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex()); 3289 Builder.restoreIP(IP); 3290 deferPlaceholderReplacement(Placeholder, Addr.getPointer()); 3291 } else { 3292 // Store the RValue into the argument struct. 3293 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex()); 3294 unsigned AS = Addr.getType()->getPointerAddressSpace(); 3295 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS); 3296 // There are some cases where a trivial bitcast is not avoidable. The 3297 // definition of a type later in a translation unit may change it's type 3298 // from {}* to (%struct.foo*)*. 3299 if (Addr.getType() != MemType) 3300 Addr = Builder.CreateBitCast(Addr, MemType); 3301 LValue argLV = MakeAddrLValue(Addr, I->Ty); 3302 EmitInitStoreOfNonAggregate(*this, RV, argLV); 3303 } 3304 break; 3305 } 3306 3307 case ABIArgInfo::Indirect: { 3308 assert(NumIRArgs == 1); 3309 if (RV.isScalar() || RV.isComplex()) { 3310 // Make a temporary alloca to pass the argument. 3311 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign()); 3312 IRCallArgs[FirstIRArg] = Addr.getPointer(); 3313 3314 LValue argLV = MakeAddrLValue(Addr, I->Ty); 3315 EmitInitStoreOfNonAggregate(*this, RV, argLV); 3316 } else { 3317 // We want to avoid creating an unnecessary temporary+copy here; 3318 // however, we need one in three cases: 3319 // 1. If the argument is not byval, and we are required to copy the 3320 // source. (This case doesn't occur on any common architecture.) 3321 // 2. If the argument is byval, RV is not sufficiently aligned, and 3322 // we cannot force it to be sufficiently aligned. 3323 // 3. If the argument is byval, but RV is located in an address space 3324 // different than that of the argument (0). 3325 Address Addr = RV.getAggregateAddress(); 3326 CharUnits Align = ArgInfo.getIndirectAlign(); 3327 const llvm::DataLayout *TD = &CGM.getDataLayout(); 3328 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace(); 3329 const unsigned ArgAddrSpace = 3330 (FirstIRArg < IRFuncTy->getNumParams() 3331 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() 3332 : 0); 3333 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) || 3334 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align && 3335 llvm::getOrEnforceKnownAlignment(Addr.getPointer(), 3336 Align.getQuantity(), *TD) 3337 < Align.getQuantity()) || 3338 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) { 3339 // Create an aligned temporary, and copy to it. 3340 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign()); 3341 IRCallArgs[FirstIRArg] = AI.getPointer(); 3342 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified()); 3343 } else { 3344 // Skip the extra memcpy call. 3345 IRCallArgs[FirstIRArg] = Addr.getPointer(); 3346 } 3347 } 3348 break; 3349 } 3350 3351 case ABIArgInfo::Ignore: 3352 assert(NumIRArgs == 0); 3353 break; 3354 3355 case ABIArgInfo::Extend: 3356 case ABIArgInfo::Direct: { 3357 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) && 3358 ArgInfo.getCoerceToType() == ConvertType(info_it->type) && 3359 ArgInfo.getDirectOffset() == 0) { 3360 assert(NumIRArgs == 1); 3361 llvm::Value *V; 3362 if (RV.isScalar()) 3363 V = RV.getScalarVal(); 3364 else 3365 V = Builder.CreateLoad(RV.getAggregateAddress()); 3366 3367 // We might have to widen integers, but we should never truncate. 3368 if (ArgInfo.getCoerceToType() != V->getType() && 3369 V->getType()->isIntegerTy()) 3370 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType()); 3371 3372 // If the argument doesn't match, perform a bitcast to coerce it. This 3373 // can happen due to trivial type mismatches. 3374 if (FirstIRArg < IRFuncTy->getNumParams() && 3375 V->getType() != IRFuncTy->getParamType(FirstIRArg)) 3376 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg)); 3377 IRCallArgs[FirstIRArg] = V; 3378 break; 3379 } 3380 3381 // FIXME: Avoid the conversion through memory if possible. 3382 Address Src = Address::invalid(); 3383 if (RV.isScalar() || RV.isComplex()) { 3384 Src = CreateMemTemp(I->Ty, "coerce"); 3385 LValue SrcLV = MakeAddrLValue(Src, I->Ty); 3386 EmitInitStoreOfNonAggregate(*this, RV, SrcLV); 3387 } else { 3388 Src = RV.getAggregateAddress(); 3389 } 3390 3391 // If the value is offset in memory, apply the offset now. 3392 Src = emitAddressAtOffset(*this, Src, ArgInfo); 3393 3394 // Fast-isel and the optimizer generally like scalar values better than 3395 // FCAs, so we flatten them if this is safe to do for this argument. 3396 llvm::StructType *STy = 3397 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType()); 3398 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) { 3399 llvm::Type *SrcTy = Src.getType()->getElementType(); 3400 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy); 3401 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy); 3402 3403 // If the source type is smaller than the destination type of the 3404 // coerce-to logic, copy the source value into a temp alloca the size 3405 // of the destination type to allow loading all of it. The bits past 3406 // the source value are left undef. 3407 if (SrcSize < DstSize) { 3408 Address TempAlloca 3409 = CreateTempAlloca(STy, Src.getAlignment(), 3410 Src.getName() + ".coerce"); 3411 Builder.CreateMemCpy(TempAlloca, Src, SrcSize); 3412 Src = TempAlloca; 3413 } else { 3414 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy)); 3415 } 3416 3417 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy); 3418 assert(NumIRArgs == STy->getNumElements()); 3419 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 3420 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i)); 3421 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset); 3422 llvm::Value *LI = Builder.CreateLoad(EltPtr); 3423 IRCallArgs[FirstIRArg + i] = LI; 3424 } 3425 } else { 3426 // In the simple case, just pass the coerced loaded value. 3427 assert(NumIRArgs == 1); 3428 IRCallArgs[FirstIRArg] = 3429 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this); 3430 } 3431 3432 break; 3433 } 3434 3435 case ABIArgInfo::Expand: 3436 unsigned IRArgPos = FirstIRArg; 3437 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos); 3438 assert(IRArgPos == FirstIRArg + NumIRArgs); 3439 break; 3440 } 3441 } 3442 3443 if (ArgMemory.isValid()) { 3444 llvm::Value *Arg = ArgMemory.getPointer(); 3445 if (CallInfo.isVariadic()) { 3446 // When passing non-POD arguments by value to variadic functions, we will 3447 // end up with a variadic prototype and an inalloca call site. In such 3448 // cases, we can't do any parameter mismatch checks. Give up and bitcast 3449 // the callee. 3450 unsigned CalleeAS = 3451 cast<llvm::PointerType>(Callee->getType())->getAddressSpace(); 3452 Callee = Builder.CreateBitCast( 3453 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS)); 3454 } else { 3455 llvm::Type *LastParamTy = 3456 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1); 3457 if (Arg->getType() != LastParamTy) { 3458 #ifndef NDEBUG 3459 // Assert that these structs have equivalent element types. 3460 llvm::StructType *FullTy = CallInfo.getArgStruct(); 3461 llvm::StructType *DeclaredTy = cast<llvm::StructType>( 3462 cast<llvm::PointerType>(LastParamTy)->getElementType()); 3463 assert(DeclaredTy->getNumElements() == FullTy->getNumElements()); 3464 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(), 3465 DE = DeclaredTy->element_end(), 3466 FI = FullTy->element_begin(); 3467 DI != DE; ++DI, ++FI) 3468 assert(*DI == *FI); 3469 #endif 3470 Arg = Builder.CreateBitCast(Arg, LastParamTy); 3471 } 3472 } 3473 assert(IRFunctionArgs.hasInallocaArg()); 3474 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg; 3475 } 3476 3477 if (!CallArgs.getCleanupsToDeactivate().empty()) 3478 deactivateArgCleanupsBeforeCall(*this, CallArgs); 3479 3480 // If the callee is a bitcast of a function to a varargs pointer to function 3481 // type, check to see if we can remove the bitcast. This handles some cases 3482 // with unprototyped functions. 3483 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee)) 3484 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) { 3485 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType()); 3486 llvm::FunctionType *CurFT = 3487 cast<llvm::FunctionType>(CurPT->getElementType()); 3488 llvm::FunctionType *ActualFT = CalleeF->getFunctionType(); 3489 3490 if (CE->getOpcode() == llvm::Instruction::BitCast && 3491 ActualFT->getReturnType() == CurFT->getReturnType() && 3492 ActualFT->getNumParams() == CurFT->getNumParams() && 3493 ActualFT->getNumParams() == IRCallArgs.size() && 3494 (CurFT->isVarArg() || !ActualFT->isVarArg())) { 3495 bool ArgsMatch = true; 3496 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i) 3497 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) { 3498 ArgsMatch = false; 3499 break; 3500 } 3501 3502 // Strip the cast if we can get away with it. This is a nice cleanup, 3503 // but also allows us to inline the function at -O0 if it is marked 3504 // always_inline. 3505 if (ArgsMatch) 3506 Callee = CalleeF; 3507 } 3508 } 3509 3510 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg()); 3511 for (unsigned i = 0; i < IRCallArgs.size(); ++i) { 3512 // Inalloca argument can have different type. 3513 if (IRFunctionArgs.hasInallocaArg() && 3514 i == IRFunctionArgs.getInallocaArgNo()) 3515 continue; 3516 if (i < IRFuncTy->getNumParams()) 3517 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i)); 3518 } 3519 3520 unsigned CallingConv; 3521 CodeGen::AttributeListType AttributeList; 3522 CGM.ConstructAttributeList(Callee->getName(), CallInfo, CalleeInfo, 3523 AttributeList, CallingConv, 3524 /*AttrOnCallSite=*/true); 3525 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(), 3526 AttributeList); 3527 3528 bool CannotThrow; 3529 if (currentFunctionUsesSEHTry()) { 3530 // SEH cares about asynchronous exceptions, everything can "throw." 3531 CannotThrow = false; 3532 } else if (isCleanupPadScope() && 3533 EHPersonality::get(*this).isMSVCXXPersonality()) { 3534 // The MSVC++ personality will implicitly terminate the program if an 3535 // exception is thrown. An unwind edge cannot be reached. 3536 CannotThrow = true; 3537 } else { 3538 // Otherwise, nowunind callsites will never throw. 3539 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex, 3540 llvm::Attribute::NoUnwind); 3541 } 3542 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest(); 3543 3544 SmallVector<llvm::OperandBundleDef, 1> BundleList; 3545 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList); 3546 3547 llvm::CallSite CS; 3548 if (!InvokeDest) { 3549 CS = Builder.CreateCall(Callee, IRCallArgs, BundleList); 3550 } else { 3551 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont"); 3552 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs, 3553 BundleList); 3554 EmitBlock(Cont); 3555 } 3556 if (callOrInvoke) 3557 *callOrInvoke = CS.getInstruction(); 3558 3559 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() && 3560 !CS.hasFnAttr(llvm::Attribute::NoInline)) 3561 Attrs = 3562 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex, 3563 llvm::Attribute::AlwaysInline); 3564 3565 // Disable inlining inside SEH __try blocks. 3566 if (isSEHTryScope()) 3567 Attrs = 3568 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex, 3569 llvm::Attribute::NoInline); 3570 3571 CS.setAttributes(Attrs); 3572 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 3573 3574 // Insert instrumentation or attach profile metadata at indirect call sites 3575 if (!CS.getCalledFunction()) 3576 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget, 3577 CS.getInstruction(), Callee); 3578 3579 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3580 // optimizer it can aggressively ignore unwind edges. 3581 if (CGM.getLangOpts().ObjCAutoRefCount) 3582 AddObjCARCExceptionMetadata(CS.getInstruction()); 3583 3584 // If the call doesn't return, finish the basic block and clear the 3585 // insertion point; this allows the rest of IRgen to discard 3586 // unreachable code. 3587 if (CS.doesNotReturn()) { 3588 if (UnusedReturnSize) 3589 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize), 3590 SRetPtr.getPointer()); 3591 3592 Builder.CreateUnreachable(); 3593 Builder.ClearInsertionPoint(); 3594 3595 // FIXME: For now, emit a dummy basic block because expr emitters in 3596 // generally are not ready to handle emitting expressions at unreachable 3597 // points. 3598 EnsureInsertPoint(); 3599 3600 // Return a reasonable RValue. 3601 return GetUndefRValue(RetTy); 3602 } 3603 3604 llvm::Instruction *CI = CS.getInstruction(); 3605 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy()) 3606 CI->setName("call"); 3607 3608 // Emit any writebacks immediately. Arguably this should happen 3609 // after any return-value munging. 3610 if (CallArgs.hasWritebacks()) 3611 emitWritebacks(*this, CallArgs); 3612 3613 // The stack cleanup for inalloca arguments has to run out of the normal 3614 // lexical order, so deactivate it and run it manually here. 3615 CallArgs.freeArgumentMemory(*this); 3616 3617 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) { 3618 const Decl *TargetDecl = CalleeInfo.getCalleeDecl(); 3619 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>()) 3620 Call->setTailCallKind(llvm::CallInst::TCK_NoTail); 3621 } 3622 3623 RValue Ret = [&] { 3624 switch (RetAI.getKind()) { 3625 case ABIArgInfo::InAlloca: 3626 case ABIArgInfo::Indirect: { 3627 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation()); 3628 if (UnusedReturnSize) 3629 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize), 3630 SRetPtr.getPointer()); 3631 return ret; 3632 } 3633 3634 case ABIArgInfo::Ignore: 3635 // If we are ignoring an argument that had a result, make sure to 3636 // construct the appropriate return value for our caller. 3637 return GetUndefRValue(RetTy); 3638 3639 case ABIArgInfo::Extend: 3640 case ABIArgInfo::Direct: { 3641 llvm::Type *RetIRTy = ConvertType(RetTy); 3642 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) { 3643 switch (getEvaluationKind(RetTy)) { 3644 case TEK_Complex: { 3645 llvm::Value *Real = Builder.CreateExtractValue(CI, 0); 3646 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1); 3647 return RValue::getComplex(std::make_pair(Real, Imag)); 3648 } 3649 case TEK_Aggregate: { 3650 Address DestPtr = ReturnValue.getValue(); 3651 bool DestIsVolatile = ReturnValue.isVolatile(); 3652 3653 if (!DestPtr.isValid()) { 3654 DestPtr = CreateMemTemp(RetTy, "agg.tmp"); 3655 DestIsVolatile = false; 3656 } 3657 BuildAggStore(*this, CI, DestPtr, DestIsVolatile); 3658 return RValue::getAggregate(DestPtr); 3659 } 3660 case TEK_Scalar: { 3661 // If the argument doesn't match, perform a bitcast to coerce it. This 3662 // can happen due to trivial type mismatches. 3663 llvm::Value *V = CI; 3664 if (V->getType() != RetIRTy) 3665 V = Builder.CreateBitCast(V, RetIRTy); 3666 return RValue::get(V); 3667 } 3668 } 3669 llvm_unreachable("bad evaluation kind"); 3670 } 3671 3672 Address DestPtr = ReturnValue.getValue(); 3673 bool DestIsVolatile = ReturnValue.isVolatile(); 3674 3675 if (!DestPtr.isValid()) { 3676 DestPtr = CreateMemTemp(RetTy, "coerce"); 3677 DestIsVolatile = false; 3678 } 3679 3680 // If the value is offset in memory, apply the offset now. 3681 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI); 3682 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this); 3683 3684 return convertTempToRValue(DestPtr, RetTy, SourceLocation()); 3685 } 3686 3687 case ABIArgInfo::Expand: 3688 llvm_unreachable("Invalid ABI kind for return argument"); 3689 } 3690 3691 llvm_unreachable("Unhandled ABIArgInfo::Kind"); 3692 } (); 3693 3694 const Decl *TargetDecl = CalleeInfo.getCalleeDecl(); 3695 3696 if (Ret.isScalar() && TargetDecl) { 3697 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) { 3698 llvm::Value *OffsetValue = nullptr; 3699 if (const auto *Offset = AA->getOffset()) 3700 OffsetValue = EmitScalarExpr(Offset); 3701 3702 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment()); 3703 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment); 3704 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(), 3705 OffsetValue); 3706 } 3707 } 3708 3709 return Ret; 3710 } 3711 3712 /* VarArg handling */ 3713 3714 Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) { 3715 VAListAddr = VE->isMicrosoftABI() 3716 ? EmitMSVAListRef(VE->getSubExpr()) 3717 : EmitVAListRef(VE->getSubExpr()); 3718 QualType Ty = VE->getType(); 3719 if (VE->isMicrosoftABI()) 3720 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty); 3721 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty); 3722 } 3723