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