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