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