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