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