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