clang API Documentation
00001 //===--- CGCall.cpp - Encapsulate calling convention details ----*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // These classes wrap the information about a call or function 00011 // definition used to handle ABI compliancy. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #include "CGCall.h" 00016 #include "CGCXXABI.h" 00017 #include "ABIInfo.h" 00018 #include "CodeGenFunction.h" 00019 #include "CodeGenModule.h" 00020 #include "TargetInfo.h" 00021 #include "clang/Basic/TargetInfo.h" 00022 #include "clang/AST/Decl.h" 00023 #include "clang/AST/DeclCXX.h" 00024 #include "clang/AST/DeclObjC.h" 00025 #include "clang/Frontend/CodeGenOptions.h" 00026 #include "llvm/Attributes.h" 00027 #include "llvm/Support/CallSite.h" 00028 #include "llvm/Target/TargetData.h" 00029 #include "llvm/InlineAsm.h" 00030 #include "llvm/Transforms/Utils/Local.h" 00031 using namespace clang; 00032 using namespace CodeGen; 00033 00034 /***/ 00035 00036 static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) { 00037 switch (CC) { 00038 default: return llvm::CallingConv::C; 00039 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall; 00040 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall; 00041 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall; 00042 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS; 00043 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 00044 // TODO: add support for CC_X86Pascal to llvm 00045 } 00046 } 00047 00048 /// Derives the 'this' type for codegen purposes, i.e. ignoring method 00049 /// qualification. 00050 /// FIXME: address space qualification? 00051 static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) { 00052 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal(); 00053 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy)); 00054 } 00055 00056 /// Returns the canonical formal type of the given C++ method. 00057 static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) { 00058 return MD->getType()->getCanonicalTypeUnqualified() 00059 .getAs<FunctionProtoType>(); 00060 } 00061 00062 /// Returns the "extra-canonicalized" return type, which discards 00063 /// qualifiers on the return type. Codegen doesn't care about them, 00064 /// and it makes ABI code a little easier to be able to assume that 00065 /// all parameter and return types are top-level unqualified. 00066 static CanQualType GetReturnType(QualType RetTy) { 00067 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType(); 00068 } 00069 00070 /// Arrange the argument and result information for a value of the 00071 /// given unprototyped function type. 00072 const CGFunctionInfo & 00073 CodeGenTypes::arrangeFunctionType(CanQual<FunctionNoProtoType> FTNP) { 00074 // When translating an unprototyped function type, always use a 00075 // variadic type. 00076 return arrangeFunctionType(FTNP->getResultType().getUnqualifiedType(), 00077 ArrayRef<CanQualType>(), 00078 FTNP->getExtInfo(), 00079 RequiredArgs(0)); 00080 } 00081 00082 /// Arrange the argument and result information for a value of the 00083 /// given function type, on top of any implicit parameters already 00084 /// stored. 00085 static const CGFunctionInfo &arrangeFunctionType(CodeGenTypes &CGT, 00086 SmallVectorImpl<CanQualType> &argTypes, 00087 CanQual<FunctionProtoType> FTP) { 00088 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, argTypes.size()); 00089 // FIXME: Kill copy. 00090 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i) 00091 argTypes.push_back(FTP->getArgType(i)); 00092 CanQualType resultType = FTP->getResultType().getUnqualifiedType(); 00093 return CGT.arrangeFunctionType(resultType, argTypes, 00094 FTP->getExtInfo(), required); 00095 } 00096 00097 /// Arrange the argument and result information for a value of the 00098 /// given function type. 00099 const CGFunctionInfo & 00100 CodeGenTypes::arrangeFunctionType(CanQual<FunctionProtoType> FTP) { 00101 SmallVector<CanQualType, 16> argTypes; 00102 return ::arrangeFunctionType(*this, argTypes, FTP); 00103 } 00104 00105 static CallingConv getCallingConventionForDecl(const Decl *D) { 00106 // Set the appropriate calling convention for the Function. 00107 if (D->hasAttr<StdCallAttr>()) 00108 return CC_X86StdCall; 00109 00110 if (D->hasAttr<FastCallAttr>()) 00111 return CC_X86FastCall; 00112 00113 if (D->hasAttr<ThisCallAttr>()) 00114 return CC_X86ThisCall; 00115 00116 if (D->hasAttr<PascalAttr>()) 00117 return CC_X86Pascal; 00118 00119 if (PcsAttr *PCS = D->getAttr<PcsAttr>()) 00120 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP); 00121 00122 return CC_C; 00123 } 00124 00125 /// Arrange the argument and result information for a call to an 00126 /// unknown C++ non-static member function of the given abstract type. 00127 /// The member function must be an ordinary function, i.e. not a 00128 /// constructor or destructor. 00129 const CGFunctionInfo & 00130 CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD, 00131 const FunctionProtoType *FTP) { 00132 SmallVector<CanQualType, 16> argTypes; 00133 00134 // Add the 'this' pointer. 00135 argTypes.push_back(GetThisType(Context, RD)); 00136 00137 return ::arrangeFunctionType(*this, argTypes, 00138 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>()); 00139 } 00140 00141 /// Arrange the argument and result information for a declaration or 00142 /// definition of the given C++ non-static member function. The 00143 /// member function must be an ordinary function, i.e. not a 00144 /// constructor or destructor. 00145 const CGFunctionInfo & 00146 CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) { 00147 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for contructors!"); 00148 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!"); 00149 00150 CanQual<FunctionProtoType> prototype = GetFormalType(MD); 00151 00152 if (MD->isInstance()) { 00153 // The abstract case is perfectly fine. 00154 return arrangeCXXMethodType(MD->getParent(), prototype.getTypePtr()); 00155 } 00156 00157 return arrangeFunctionType(prototype); 00158 } 00159 00160 /// Arrange the argument and result information for a declaration 00161 /// or definition to the given constructor variant. 00162 const CGFunctionInfo & 00163 CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D, 00164 CXXCtorType ctorKind) { 00165 SmallVector<CanQualType, 16> argTypes; 00166 argTypes.push_back(GetThisType(Context, D->getParent())); 00167 CanQualType resultType = Context.VoidTy; 00168 00169 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes); 00170 00171 CanQual<FunctionProtoType> FTP = GetFormalType(D); 00172 00173 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, argTypes.size()); 00174 00175 // Add the formal parameters. 00176 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i) 00177 argTypes.push_back(FTP->getArgType(i)); 00178 00179 return arrangeFunctionType(resultType, argTypes, FTP->getExtInfo(), required); 00180 } 00181 00182 /// Arrange the argument and result information for a declaration, 00183 /// definition, or call to the given destructor variant. It so 00184 /// happens that all three cases produce the same information. 00185 const CGFunctionInfo & 00186 CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D, 00187 CXXDtorType dtorKind) { 00188 SmallVector<CanQualType, 2> argTypes; 00189 argTypes.push_back(GetThisType(Context, D->getParent())); 00190 CanQualType resultType = Context.VoidTy; 00191 00192 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes); 00193 00194 CanQual<FunctionProtoType> FTP = GetFormalType(D); 00195 assert(FTP->getNumArgs() == 0 && "dtor with formal parameters"); 00196 00197 return arrangeFunctionType(resultType, argTypes, FTP->getExtInfo(), 00198 RequiredArgs::All); 00199 } 00200 00201 /// Arrange the argument and result information for the declaration or 00202 /// definition of the given function. 00203 const CGFunctionInfo & 00204 CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) { 00205 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 00206 if (MD->isInstance()) 00207 return arrangeCXXMethodDeclaration(MD); 00208 00209 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified(); 00210 00211 assert(isa<FunctionType>(FTy)); 00212 00213 // When declaring a function without a prototype, always use a 00214 // non-variadic type. 00215 if (isa<FunctionNoProtoType>(FTy)) { 00216 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>(); 00217 return arrangeFunctionType(noProto->getResultType(), 00218 ArrayRef<CanQualType>(), 00219 noProto->getExtInfo(), 00220 RequiredArgs::All); 00221 } 00222 00223 assert(isa<FunctionProtoType>(FTy)); 00224 return arrangeFunctionType(FTy.getAs<FunctionProtoType>()); 00225 } 00226 00227 /// Arrange the argument and result information for the declaration or 00228 /// definition of an Objective-C method. 00229 const CGFunctionInfo & 00230 CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) { 00231 // It happens that this is the same as a call with no optional 00232 // arguments, except also using the formal 'self' type. 00233 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType()); 00234 } 00235 00236 /// Arrange the argument and result information for the function type 00237 /// through which to perform a send to the given Objective-C method, 00238 /// using the given receiver type. The receiver type is not always 00239 /// the 'self' type of the method or even an Objective-C pointer type. 00240 /// This is *not* the right method for actually performing such a 00241 /// message send, due to the possibility of optional arguments. 00242 const CGFunctionInfo & 00243 CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD, 00244 QualType receiverType) { 00245 SmallVector<CanQualType, 16> argTys; 00246 argTys.push_back(Context.getCanonicalParamType(receiverType)); 00247 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType())); 00248 // FIXME: Kill copy? 00249 for (ObjCMethodDecl::param_const_iterator i = MD->param_begin(), 00250 e = MD->param_end(); i != e; ++i) { 00251 argTys.push_back(Context.getCanonicalParamType((*i)->getType())); 00252 } 00253 00254 FunctionType::ExtInfo einfo; 00255 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD)); 00256 00257 if (getContext().getLangOpts().ObjCAutoRefCount && 00258 MD->hasAttr<NSReturnsRetainedAttr>()) 00259 einfo = einfo.withProducesResult(true); 00260 00261 RequiredArgs required = 00262 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All); 00263 00264 return arrangeFunctionType(GetReturnType(MD->getResultType()), argTys, 00265 einfo, required); 00266 } 00267 00268 const CGFunctionInfo & 00269 CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) { 00270 // FIXME: Do we need to handle ObjCMethodDecl? 00271 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 00272 00273 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 00274 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType()); 00275 00276 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) 00277 return arrangeCXXDestructor(DD, GD.getDtorType()); 00278 00279 return arrangeFunctionDeclaration(FD); 00280 } 00281 00282 /// Figure out the rules for calling a function with the given formal 00283 /// type using the given arguments. The arguments are necessary 00284 /// because the function might be unprototyped, in which case it's 00285 /// target-dependent in crazy ways. 00286 const CGFunctionInfo & 00287 CodeGenTypes::arrangeFunctionCall(const CallArgList &args, 00288 const FunctionType *fnType) { 00289 RequiredArgs required = RequiredArgs::All; 00290 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) { 00291 if (proto->isVariadic()) 00292 required = RequiredArgs(proto->getNumArgs()); 00293 } else if (CGM.getTargetCodeGenInfo() 00294 .isNoProtoCallVariadic(args, cast<FunctionNoProtoType>(fnType))) { 00295 required = RequiredArgs(0); 00296 } 00297 00298 return arrangeFunctionCall(fnType->getResultType(), args, 00299 fnType->getExtInfo(), required); 00300 } 00301 00302 const CGFunctionInfo & 00303 CodeGenTypes::arrangeFunctionCall(QualType resultType, 00304 const CallArgList &args, 00305 const FunctionType::ExtInfo &info, 00306 RequiredArgs required) { 00307 // FIXME: Kill copy. 00308 SmallVector<CanQualType, 16> argTypes; 00309 for (CallArgList::const_iterator i = args.begin(), e = args.end(); 00310 i != e; ++i) 00311 argTypes.push_back(Context.getCanonicalParamType(i->Ty)); 00312 return arrangeFunctionType(GetReturnType(resultType), argTypes, info, 00313 required); 00314 } 00315 00316 const CGFunctionInfo & 00317 CodeGenTypes::arrangeFunctionDeclaration(QualType resultType, 00318 const FunctionArgList &args, 00319 const FunctionType::ExtInfo &info, 00320 bool isVariadic) { 00321 // FIXME: Kill copy. 00322 SmallVector<CanQualType, 16> argTypes; 00323 for (FunctionArgList::const_iterator i = args.begin(), e = args.end(); 00324 i != e; ++i) 00325 argTypes.push_back(Context.getCanonicalParamType((*i)->getType())); 00326 00327 RequiredArgs required = 00328 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All); 00329 return arrangeFunctionType(GetReturnType(resultType), argTypes, info, 00330 required); 00331 } 00332 00333 const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() { 00334 return arrangeFunctionType(getContext().VoidTy, ArrayRef<CanQualType>(), 00335 FunctionType::ExtInfo(), RequiredArgs::All); 00336 } 00337 00338 /// Arrange the argument and result information for an abstract value 00339 /// of a given function type. This is the method which all of the 00340 /// above functions ultimately defer to. 00341 const CGFunctionInfo & 00342 CodeGenTypes::arrangeFunctionType(CanQualType resultType, 00343 ArrayRef<CanQualType> argTypes, 00344 const FunctionType::ExtInfo &info, 00345 RequiredArgs required) { 00346 #ifndef NDEBUG 00347 for (ArrayRef<CanQualType>::const_iterator 00348 I = argTypes.begin(), E = argTypes.end(); I != E; ++I) 00349 assert(I->isCanonicalAsParam()); 00350 #endif 00351 00352 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC()); 00353 00354 // Lookup or create unique function info. 00355 llvm::FoldingSetNodeID ID; 00356 CGFunctionInfo::Profile(ID, info, required, resultType, argTypes); 00357 00358 void *insertPos = 0; 00359 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos); 00360 if (FI) 00361 return *FI; 00362 00363 // Construct the function info. We co-allocate the ArgInfos. 00364 FI = CGFunctionInfo::create(CC, info, resultType, argTypes, required); 00365 FunctionInfos.InsertNode(FI, insertPos); 00366 00367 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted; 00368 assert(inserted && "Recursively being processed?"); 00369 00370 // Compute ABI information. 00371 getABIInfo().computeInfo(*FI); 00372 00373 // Loop over all of the computed argument and return value info. If any of 00374 // them are direct or extend without a specified coerce type, specify the 00375 // default now. 00376 ABIArgInfo &retInfo = FI->getReturnInfo(); 00377 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == 0) 00378 retInfo.setCoerceToType(ConvertType(FI->getReturnType())); 00379 00380 for (CGFunctionInfo::arg_iterator I = FI->arg_begin(), E = FI->arg_end(); 00381 I != E; ++I) 00382 if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() == 0) 00383 I->info.setCoerceToType(ConvertType(I->type)); 00384 00385 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased; 00386 assert(erased && "Not in set?"); 00387 00388 return *FI; 00389 } 00390 00391 CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC, 00392 const FunctionType::ExtInfo &info, 00393 CanQualType resultType, 00394 ArrayRef<CanQualType> argTypes, 00395 RequiredArgs required) { 00396 void *buffer = operator new(sizeof(CGFunctionInfo) + 00397 sizeof(ArgInfo) * (argTypes.size() + 1)); 00398 CGFunctionInfo *FI = new(buffer) CGFunctionInfo(); 00399 FI->CallingConvention = llvmCC; 00400 FI->EffectiveCallingConvention = llvmCC; 00401 FI->ASTCallingConvention = info.getCC(); 00402 FI->NoReturn = info.getNoReturn(); 00403 FI->ReturnsRetained = info.getProducesResult(); 00404 FI->Required = required; 00405 FI->HasRegParm = info.getHasRegParm(); 00406 FI->RegParm = info.getRegParm(); 00407 FI->NumArgs = argTypes.size(); 00408 FI->getArgsBuffer()[0].type = resultType; 00409 for (unsigned i = 0, e = argTypes.size(); i != e; ++i) 00410 FI->getArgsBuffer()[i + 1].type = argTypes[i]; 00411 return FI; 00412 } 00413 00414 /***/ 00415 00416 void CodeGenTypes::GetExpandedTypes(QualType type, 00417 SmallVectorImpl<llvm::Type*> &expandedTypes) { 00418 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) { 00419 uint64_t NumElts = AT->getSize().getZExtValue(); 00420 for (uint64_t Elt = 0; Elt < NumElts; ++Elt) 00421 GetExpandedTypes(AT->getElementType(), expandedTypes); 00422 } else if (const RecordType *RT = type->getAs<RecordType>()) { 00423 const RecordDecl *RD = RT->getDecl(); 00424 assert(!RD->hasFlexibleArrayMember() && 00425 "Cannot expand structure with flexible array."); 00426 if (RD->isUnion()) { 00427 // Unions can be here only in degenerative cases - all the fields are same 00428 // after flattening. Thus we have to use the "largest" field. 00429 const FieldDecl *LargestFD = 0; 00430 CharUnits UnionSize = CharUnits::Zero(); 00431 00432 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 00433 i != e; ++i) { 00434 const FieldDecl *FD = &*i; 00435 assert(!FD->isBitField() && 00436 "Cannot expand structure with bit-field members."); 00437 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType()); 00438 if (UnionSize < FieldSize) { 00439 UnionSize = FieldSize; 00440 LargestFD = FD; 00441 } 00442 } 00443 if (LargestFD) 00444 GetExpandedTypes(LargestFD->getType(), expandedTypes); 00445 } else { 00446 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 00447 i != e; ++i) { 00448 const FieldDecl &FD = *i; 00449 assert(!FD.isBitField() && 00450 "Cannot expand structure with bit-field members."); 00451 GetExpandedTypes(FD.getType(), expandedTypes); 00452 } 00453 } 00454 } else if (const ComplexType *CT = type->getAs<ComplexType>()) { 00455 llvm::Type *EltTy = ConvertType(CT->getElementType()); 00456 expandedTypes.push_back(EltTy); 00457 expandedTypes.push_back(EltTy); 00458 } else 00459 expandedTypes.push_back(ConvertType(type)); 00460 } 00461 00462 llvm::Function::arg_iterator 00463 CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV, 00464 llvm::Function::arg_iterator AI) { 00465 assert(LV.isSimple() && 00466 "Unexpected non-simple lvalue during struct expansion."); 00467 00468 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 00469 unsigned NumElts = AT->getSize().getZExtValue(); 00470 QualType EltTy = AT->getElementType(); 00471 for (unsigned Elt = 0; Elt < NumElts; ++Elt) { 00472 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt); 00473 LValue LV = MakeAddrLValue(EltAddr, EltTy); 00474 AI = ExpandTypeFromArgs(EltTy, LV, AI); 00475 } 00476 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 00477 RecordDecl *RD = RT->getDecl(); 00478 if (RD->isUnion()) { 00479 // Unions can be here only in degenerative cases - all the fields are same 00480 // after flattening. Thus we have to use the "largest" field. 00481 const FieldDecl *LargestFD = 0; 00482 CharUnits UnionSize = CharUnits::Zero(); 00483 00484 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 00485 i != e; ++i) { 00486 const FieldDecl *FD = &*i; 00487 assert(!FD->isBitField() && 00488 "Cannot expand structure with bit-field members."); 00489 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType()); 00490 if (UnionSize < FieldSize) { 00491 UnionSize = FieldSize; 00492 LargestFD = FD; 00493 } 00494 } 00495 if (LargestFD) { 00496 // FIXME: What are the right qualifiers here? 00497 LValue SubLV = EmitLValueForField(LV, LargestFD); 00498 AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI); 00499 } 00500 } else { 00501 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 00502 i != e; ++i) { 00503 FieldDecl *FD = &*i; 00504 QualType FT = FD->getType(); 00505 00506 // FIXME: What are the right qualifiers here? 00507 LValue SubLV = EmitLValueForField(LV, FD); 00508 AI = ExpandTypeFromArgs(FT, SubLV, AI); 00509 } 00510 } 00511 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 00512 QualType EltTy = CT->getElementType(); 00513 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real"); 00514 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy)); 00515 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag"); 00516 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy)); 00517 } else { 00518 EmitStoreThroughLValue(RValue::get(AI), LV); 00519 ++AI; 00520 } 00521 00522 return AI; 00523 } 00524 00525 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are 00526 /// accessing some number of bytes out of it, try to gep into the struct to get 00527 /// at its inner goodness. Dive as deep as possible without entering an element 00528 /// with an in-memory size smaller than DstSize. 00529 static llvm::Value * 00530 EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr, 00531 llvm::StructType *SrcSTy, 00532 uint64_t DstSize, CodeGenFunction &CGF) { 00533 // We can't dive into a zero-element struct. 00534 if (SrcSTy->getNumElements() == 0) return SrcPtr; 00535 00536 llvm::Type *FirstElt = SrcSTy->getElementType(0); 00537 00538 // If the first elt is at least as large as what we're looking for, or if the 00539 // first element is the same size as the whole struct, we can enter it. 00540 uint64_t FirstEltSize = 00541 CGF.CGM.getTargetData().getTypeAllocSize(FirstElt); 00542 if (FirstEltSize < DstSize && 00543 FirstEltSize < CGF.CGM.getTargetData().getTypeAllocSize(SrcSTy)) 00544 return SrcPtr; 00545 00546 // GEP into the first element. 00547 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive"); 00548 00549 // If the first element is a struct, recurse. 00550 llvm::Type *SrcTy = 00551 cast<llvm::PointerType>(SrcPtr->getType())->getElementType(); 00552 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) 00553 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF); 00554 00555 return SrcPtr; 00556 } 00557 00558 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both 00559 /// are either integers or pointers. This does a truncation of the value if it 00560 /// is too large or a zero extension if it is too small. 00561 static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val, 00562 llvm::Type *Ty, 00563 CodeGenFunction &CGF) { 00564 if (Val->getType() == Ty) 00565 return Val; 00566 00567 if (isa<llvm::PointerType>(Val->getType())) { 00568 // If this is Pointer->Pointer avoid conversion to and from int. 00569 if (isa<llvm::PointerType>(Ty)) 00570 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val"); 00571 00572 // Convert the pointer to an integer so we can play with its width. 00573 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi"); 00574 } 00575 00576 llvm::Type *DestIntTy = Ty; 00577 if (isa<llvm::PointerType>(DestIntTy)) 00578 DestIntTy = CGF.IntPtrTy; 00579 00580 if (Val->getType() != DestIntTy) 00581 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii"); 00582 00583 if (isa<llvm::PointerType>(Ty)) 00584 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip"); 00585 return Val; 00586 } 00587 00588 00589 00590 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as 00591 /// a pointer to an object of type \arg Ty. 00592 /// 00593 /// This safely handles the case when the src type is smaller than the 00594 /// destination type; in this situation the values of bits which not 00595 /// present in the src are undefined. 00596 static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr, 00597 llvm::Type *Ty, 00598 CodeGenFunction &CGF) { 00599 llvm::Type *SrcTy = 00600 cast<llvm::PointerType>(SrcPtr->getType())->getElementType(); 00601 00602 // If SrcTy and Ty are the same, just do a load. 00603 if (SrcTy == Ty) 00604 return CGF.Builder.CreateLoad(SrcPtr); 00605 00606 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty); 00607 00608 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) { 00609 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF); 00610 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType(); 00611 } 00612 00613 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy); 00614 00615 // If the source and destination are integer or pointer types, just do an 00616 // extension or truncation to the desired type. 00617 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) && 00618 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) { 00619 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr); 00620 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF); 00621 } 00622 00623 // If load is legal, just bitcast the src pointer. 00624 if (SrcSize >= DstSize) { 00625 // Generally SrcSize is never greater than DstSize, since this means we are 00626 // losing bits. However, this can happen in cases where the structure has 00627 // additional padding, for example due to a user specified alignment. 00628 // 00629 // FIXME: Assert that we aren't truncating non-padding bits when have access 00630 // to that information. 00631 llvm::Value *Casted = 00632 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty)); 00633 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted); 00634 // FIXME: Use better alignment / avoid requiring aligned load. 00635 Load->setAlignment(1); 00636 return Load; 00637 } 00638 00639 // Otherwise do coercion through memory. This is stupid, but 00640 // simple. 00641 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty); 00642 llvm::Value *Casted = 00643 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy)); 00644 llvm::StoreInst *Store = 00645 CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted); 00646 // FIXME: Use better alignment / avoid requiring aligned store. 00647 Store->setAlignment(1); 00648 return CGF.Builder.CreateLoad(Tmp); 00649 } 00650 00651 // Function to store a first-class aggregate into memory. We prefer to 00652 // store the elements rather than the aggregate to be more friendly to 00653 // fast-isel. 00654 // FIXME: Do we need to recurse here? 00655 static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val, 00656 llvm::Value *DestPtr, bool DestIsVolatile, 00657 bool LowAlignment) { 00658 // Prefer scalar stores to first-class aggregate stores. 00659 if (llvm::StructType *STy = 00660 dyn_cast<llvm::StructType>(Val->getType())) { 00661 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 00662 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i); 00663 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i); 00664 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr, 00665 DestIsVolatile); 00666 if (LowAlignment) 00667 SI->setAlignment(1); 00668 } 00669 } else { 00670 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile); 00671 if (LowAlignment) 00672 SI->setAlignment(1); 00673 } 00674 } 00675 00676 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src, 00677 /// where the source and destination may have different types. 00678 /// 00679 /// This safely handles the case when the src type is larger than the 00680 /// destination type; the upper bits of the src will be lost. 00681 static void CreateCoercedStore(llvm::Value *Src, 00682 llvm::Value *DstPtr, 00683 bool DstIsVolatile, 00684 CodeGenFunction &CGF) { 00685 llvm::Type *SrcTy = Src->getType(); 00686 llvm::Type *DstTy = 00687 cast<llvm::PointerType>(DstPtr->getType())->getElementType(); 00688 if (SrcTy == DstTy) { 00689 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile); 00690 return; 00691 } 00692 00693 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy); 00694 00695 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) { 00696 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF); 00697 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType(); 00698 } 00699 00700 // If the source and destination are integer or pointer types, just do an 00701 // extension or truncation to the desired type. 00702 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) && 00703 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) { 00704 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF); 00705 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile); 00706 return; 00707 } 00708 00709 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy); 00710 00711 // If store is legal, just bitcast the src pointer. 00712 if (SrcSize <= DstSize) { 00713 llvm::Value *Casted = 00714 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy)); 00715 // FIXME: Use better alignment / avoid requiring aligned store. 00716 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true); 00717 } else { 00718 // Otherwise do coercion through memory. This is stupid, but 00719 // simple. 00720 00721 // Generally SrcSize is never greater than DstSize, since this means we are 00722 // losing bits. However, this can happen in cases where the structure has 00723 // additional padding, for example due to a user specified alignment. 00724 // 00725 // FIXME: Assert that we aren't truncating non-padding bits when have access 00726 // to that information. 00727 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy); 00728 CGF.Builder.CreateStore(Src, Tmp); 00729 llvm::Value *Casted = 00730 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy)); 00731 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted); 00732 // FIXME: Use better alignment / avoid requiring aligned load. 00733 Load->setAlignment(1); 00734 CGF.Builder.CreateStore(Load, DstPtr, DstIsVolatile); 00735 } 00736 } 00737 00738 /***/ 00739 00740 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) { 00741 return FI.getReturnInfo().isIndirect(); 00742 } 00743 00744 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) { 00745 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) { 00746 switch (BT->getKind()) { 00747 default: 00748 return false; 00749 case BuiltinType::Float: 00750 return getContext().getTargetInfo().useObjCFPRetForRealType(TargetInfo::Float); 00751 case BuiltinType::Double: 00752 return getContext().getTargetInfo().useObjCFPRetForRealType(TargetInfo::Double); 00753 case BuiltinType::LongDouble: 00754 return getContext().getTargetInfo().useObjCFPRetForRealType( 00755 TargetInfo::LongDouble); 00756 } 00757 } 00758 00759 return false; 00760 } 00761 00762 bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) { 00763 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) { 00764 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) { 00765 if (BT->getKind() == BuiltinType::LongDouble) 00766 return getContext().getTargetInfo().useObjCFP2RetForComplexLongDouble(); 00767 } 00768 } 00769 00770 return false; 00771 } 00772 00773 llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) { 00774 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD); 00775 return GetFunctionType(FI); 00776 } 00777 00778 llvm::FunctionType * 00779 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) { 00780 00781 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted; 00782 assert(Inserted && "Recursively being processed?"); 00783 00784 SmallVector<llvm::Type*, 8> argTypes; 00785 llvm::Type *resultType = 0; 00786 00787 const ABIArgInfo &retAI = FI.getReturnInfo(); 00788 switch (retAI.getKind()) { 00789 case ABIArgInfo::Expand: 00790 llvm_unreachable("Invalid ABI kind for return argument"); 00791 00792 case ABIArgInfo::Extend: 00793 case ABIArgInfo::Direct: 00794 resultType = retAI.getCoerceToType(); 00795 break; 00796 00797 case ABIArgInfo::Indirect: { 00798 assert(!retAI.getIndirectAlign() && "Align unused on indirect return."); 00799 resultType = llvm::Type::getVoidTy(getLLVMContext()); 00800 00801 QualType ret = FI.getReturnType(); 00802 llvm::Type *ty = ConvertType(ret); 00803 unsigned addressSpace = Context.getTargetAddressSpace(ret); 00804 argTypes.push_back(llvm::PointerType::get(ty, addressSpace)); 00805 break; 00806 } 00807 00808 case ABIArgInfo::Ignore: 00809 resultType = llvm::Type::getVoidTy(getLLVMContext()); 00810 break; 00811 } 00812 00813 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), 00814 ie = FI.arg_end(); it != ie; ++it) { 00815 const ABIArgInfo &argAI = it->info; 00816 00817 switch (argAI.getKind()) { 00818 case ABIArgInfo::Ignore: 00819 break; 00820 00821 case ABIArgInfo::Indirect: { 00822 // indirect arguments are always on the stack, which is addr space #0. 00823 llvm::Type *LTy = ConvertTypeForMem(it->type); 00824 argTypes.push_back(LTy->getPointerTo()); 00825 break; 00826 } 00827 00828 case ABIArgInfo::Extend: 00829 case ABIArgInfo::Direct: { 00830 // Insert a padding type to ensure proper alignment. 00831 if (llvm::Type *PaddingType = argAI.getPaddingType()) 00832 argTypes.push_back(PaddingType); 00833 // If the coerce-to type is a first class aggregate, flatten it. Either 00834 // way is semantically identical, but fast-isel and the optimizer 00835 // generally likes scalar values better than FCAs. 00836 llvm::Type *argType = argAI.getCoerceToType(); 00837 if (llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) { 00838 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i) 00839 argTypes.push_back(st->getElementType(i)); 00840 } else { 00841 argTypes.push_back(argType); 00842 } 00843 break; 00844 } 00845 00846 case ABIArgInfo::Expand: 00847 GetExpandedTypes(it->type, argTypes); 00848 break; 00849 } 00850 } 00851 00852 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased; 00853 assert(Erased && "Not in set?"); 00854 00855 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic()); 00856 } 00857 00858 llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) { 00859 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 00860 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 00861 00862 if (!isFuncTypeConvertible(FPT)) 00863 return llvm::StructType::get(getLLVMContext()); 00864 00865 const CGFunctionInfo *Info; 00866 if (isa<CXXDestructorDecl>(MD)) 00867 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType()); 00868 else 00869 Info = &arrangeCXXMethodDeclaration(MD); 00870 return GetFunctionType(*Info); 00871 } 00872 00873 void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI, 00874 const Decl *TargetDecl, 00875 AttributeListType &PAL, 00876 unsigned &CallingConv) { 00877 llvm::Attributes FuncAttrs; 00878 llvm::Attributes RetAttrs; 00879 00880 CallingConv = FI.getEffectiveCallingConvention(); 00881 00882 if (FI.isNoReturn()) 00883 FuncAttrs |= llvm::Attribute::NoReturn; 00884 00885 // FIXME: handle sseregparm someday... 00886 if (TargetDecl) { 00887 if (TargetDecl->hasAttr<ReturnsTwiceAttr>()) 00888 FuncAttrs |= llvm::Attribute::ReturnsTwice; 00889 if (TargetDecl->hasAttr<NoThrowAttr>()) 00890 FuncAttrs |= llvm::Attribute::NoUnwind; 00891 else if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) { 00892 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>(); 00893 if (FPT && FPT->isNothrow(getContext())) 00894 FuncAttrs |= llvm::Attribute::NoUnwind; 00895 } 00896 00897 if (TargetDecl->hasAttr<NoReturnAttr>()) 00898 FuncAttrs |= llvm::Attribute::NoReturn; 00899 00900 if (TargetDecl->hasAttr<ReturnsTwiceAttr>()) 00901 FuncAttrs |= llvm::Attribute::ReturnsTwice; 00902 00903 // 'const' and 'pure' attribute functions are also nounwind. 00904 if (TargetDecl->hasAttr<ConstAttr>()) { 00905 FuncAttrs |= llvm::Attribute::ReadNone; 00906 FuncAttrs |= llvm::Attribute::NoUnwind; 00907 } else if (TargetDecl->hasAttr<PureAttr>()) { 00908 FuncAttrs |= llvm::Attribute::ReadOnly; 00909 FuncAttrs |= llvm::Attribute::NoUnwind; 00910 } 00911 if (TargetDecl->hasAttr<MallocAttr>()) 00912 RetAttrs |= llvm::Attribute::NoAlias; 00913 } 00914 00915 if (CodeGenOpts.OptimizeSize) 00916 FuncAttrs |= llvm::Attribute::OptimizeForSize; 00917 if (CodeGenOpts.DisableRedZone) 00918 FuncAttrs |= llvm::Attribute::NoRedZone; 00919 if (CodeGenOpts.NoImplicitFloat) 00920 FuncAttrs |= llvm::Attribute::NoImplicitFloat; 00921 00922 QualType RetTy = FI.getReturnType(); 00923 unsigned Index = 1; 00924 const ABIArgInfo &RetAI = FI.getReturnInfo(); 00925 switch (RetAI.getKind()) { 00926 case ABIArgInfo::Extend: 00927 if (RetTy->hasSignedIntegerRepresentation()) 00928 RetAttrs |= llvm::Attribute::SExt; 00929 else if (RetTy->hasUnsignedIntegerRepresentation()) 00930 RetAttrs |= llvm::Attribute::ZExt; 00931 break; 00932 case ABIArgInfo::Direct: 00933 case ABIArgInfo::Ignore: 00934 break; 00935 00936 case ABIArgInfo::Indirect: 00937 PAL.push_back(llvm::AttributeWithIndex::get(Index, 00938 llvm::Attribute::StructRet)); 00939 ++Index; 00940 // sret disables readnone and readonly 00941 FuncAttrs &= ~(llvm::Attribute::ReadOnly | 00942 llvm::Attribute::ReadNone); 00943 break; 00944 00945 case ABIArgInfo::Expand: 00946 llvm_unreachable("Invalid ABI kind for return argument"); 00947 } 00948 00949 if (RetAttrs) 00950 PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs)); 00951 00952 // FIXME: RegParm should be reduced in case of global register variable. 00953 signed RegParm; 00954 if (FI.getHasRegParm()) 00955 RegParm = FI.getRegParm(); 00956 else 00957 RegParm = CodeGenOpts.NumRegisterParameters; 00958 00959 unsigned PointerWidth = getContext().getTargetInfo().getPointerWidth(0); 00960 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), 00961 ie = FI.arg_end(); it != ie; ++it) { 00962 QualType ParamType = it->type; 00963 const ABIArgInfo &AI = it->info; 00964 llvm::Attributes Attrs; 00965 00966 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we 00967 // have the corresponding parameter variable. It doesn't make 00968 // sense to do it here because parameters are so messed up. 00969 switch (AI.getKind()) { 00970 case ABIArgInfo::Extend: 00971 if (ParamType->isSignedIntegerOrEnumerationType()) 00972 Attrs |= llvm::Attribute::SExt; 00973 else if (ParamType->isUnsignedIntegerOrEnumerationType()) 00974 Attrs |= llvm::Attribute::ZExt; 00975 // FALL THROUGH 00976 case ABIArgInfo::Direct: 00977 if (RegParm > 0 && 00978 (ParamType->isIntegerType() || ParamType->isPointerType() || 00979 ParamType->isReferenceType())) { 00980 RegParm -= 00981 (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth; 00982 if (RegParm >= 0) 00983 Attrs |= llvm::Attribute::InReg; 00984 } 00985 // FIXME: handle sseregparm someday... 00986 00987 // Increment Index if there is padding. 00988 Index += (AI.getPaddingType() != 0); 00989 00990 if (llvm::StructType *STy = 00991 dyn_cast<llvm::StructType>(AI.getCoerceToType())) 00992 Index += STy->getNumElements()-1; // 1 will be added below. 00993 break; 00994 00995 case ABIArgInfo::Indirect: 00996 if (AI.getIndirectByVal()) 00997 Attrs |= llvm::Attribute::ByVal; 00998 00999 Attrs |= 01000 llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign()); 01001 // byval disables readnone and readonly. 01002 FuncAttrs &= ~(llvm::Attribute::ReadOnly | 01003 llvm::Attribute::ReadNone); 01004 break; 01005 01006 case ABIArgInfo::Ignore: 01007 // Skip increment, no matching LLVM parameter. 01008 continue; 01009 01010 case ABIArgInfo::Expand: { 01011 SmallVector<llvm::Type*, 8> types; 01012 // FIXME: This is rather inefficient. Do we ever actually need to do 01013 // anything here? The result should be just reconstructed on the other 01014 // side, so extension should be a non-issue. 01015 getTypes().GetExpandedTypes(ParamType, types); 01016 Index += types.size(); 01017 continue; 01018 } 01019 } 01020 01021 if (Attrs) 01022 PAL.push_back(llvm::AttributeWithIndex::get(Index, Attrs)); 01023 ++Index; 01024 } 01025 if (FuncAttrs) 01026 PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs)); 01027 } 01028 01029 /// An argument came in as a promoted argument; demote it back to its 01030 /// declared type. 01031 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF, 01032 const VarDecl *var, 01033 llvm::Value *value) { 01034 llvm::Type *varType = CGF.ConvertType(var->getType()); 01035 01036 // This can happen with promotions that actually don't change the 01037 // underlying type, like the enum promotions. 01038 if (value->getType() == varType) return value; 01039 01040 assert((varType->isIntegerTy() || varType->isFloatingPointTy()) 01041 && "unexpected promotion type"); 01042 01043 if (isa<llvm::IntegerType>(varType)) 01044 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote"); 01045 01046 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote"); 01047 } 01048 01049 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, 01050 llvm::Function *Fn, 01051 const FunctionArgList &Args) { 01052 // If this is an implicit-return-zero function, go ahead and 01053 // initialize the return value. TODO: it might be nice to have 01054 // a more general mechanism for this that didn't require synthesized 01055 // return statements. 01056 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) { 01057 if (FD->hasImplicitReturnZero()) { 01058 QualType RetTy = FD->getResultType().getUnqualifiedType(); 01059 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy); 01060 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy); 01061 Builder.CreateStore(Zero, ReturnValue); 01062 } 01063 } 01064 01065 // FIXME: We no longer need the types from FunctionArgList; lift up and 01066 // simplify. 01067 01068 // Emit allocs for param decls. Give the LLVM Argument nodes names. 01069 llvm::Function::arg_iterator AI = Fn->arg_begin(); 01070 01071 // Name the struct return argument. 01072 if (CGM.ReturnTypeUsesSRet(FI)) { 01073 AI->setName("agg.result"); 01074 AI->addAttr(llvm::Attribute::NoAlias); 01075 ++AI; 01076 } 01077 01078 assert(FI.arg_size() == Args.size() && 01079 "Mismatch between function signature & arguments."); 01080 unsigned ArgNo = 1; 01081 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin(); 01082 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 01083 i != e; ++i, ++info_it, ++ArgNo) { 01084 const VarDecl *Arg = *i; 01085 QualType Ty = info_it->type; 01086 const ABIArgInfo &ArgI = info_it->info; 01087 01088 bool isPromoted = 01089 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted(); 01090 01091 switch (ArgI.getKind()) { 01092 case ABIArgInfo::Indirect: { 01093 llvm::Value *V = AI; 01094 01095 if (hasAggregateLLVMType(Ty)) { 01096 // Aggregates and complex variables are accessed by reference. All we 01097 // need to do is realign the value, if requested 01098 if (ArgI.getIndirectRealign()) { 01099 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce"); 01100 01101 // Copy from the incoming argument pointer to the temporary with the 01102 // appropriate alignment. 01103 // 01104 // FIXME: We should have a common utility for generating an aggregate 01105 // copy. 01106 llvm::Type *I8PtrTy = Builder.getInt8PtrTy(); 01107 CharUnits Size = getContext().getTypeSizeInChars(Ty); 01108 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy); 01109 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy); 01110 Builder.CreateMemCpy(Dst, 01111 Src, 01112 llvm::ConstantInt::get(IntPtrTy, 01113 Size.getQuantity()), 01114 ArgI.getIndirectAlign(), 01115 false); 01116 V = AlignedTemp; 01117 } 01118 } else { 01119 // Load scalar value from indirect argument. 01120 CharUnits Alignment = getContext().getTypeAlignInChars(Ty); 01121 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty); 01122 01123 if (isPromoted) 01124 V = emitArgumentDemotion(*this, Arg, V); 01125 } 01126 EmitParmDecl(*Arg, V, ArgNo); 01127 break; 01128 } 01129 01130 case ABIArgInfo::Extend: 01131 case ABIArgInfo::Direct: { 01132 // Skip the dummy padding argument. 01133 if (ArgI.getPaddingType()) 01134 ++AI; 01135 01136 // If we have the trivial case, handle it with no muss and fuss. 01137 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) && 01138 ArgI.getCoerceToType() == ConvertType(Ty) && 01139 ArgI.getDirectOffset() == 0) { 01140 assert(AI != Fn->arg_end() && "Argument mismatch!"); 01141 llvm::Value *V = AI; 01142 01143 if (Arg->getType().isRestrictQualified()) 01144 AI->addAttr(llvm::Attribute::NoAlias); 01145 01146 // Ensure the argument is the correct type. 01147 if (V->getType() != ArgI.getCoerceToType()) 01148 V = Builder.CreateBitCast(V, ArgI.getCoerceToType()); 01149 01150 if (isPromoted) 01151 V = emitArgumentDemotion(*this, Arg, V); 01152 01153 EmitParmDecl(*Arg, V, ArgNo); 01154 break; 01155 } 01156 01157 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName()); 01158 01159 // The alignment we need to use is the max of the requested alignment for 01160 // the argument plus the alignment required by our access code below. 01161 unsigned AlignmentToUse = 01162 CGM.getTargetData().getABITypeAlignment(ArgI.getCoerceToType()); 01163 AlignmentToUse = std::max(AlignmentToUse, 01164 (unsigned)getContext().getDeclAlign(Arg).getQuantity()); 01165 01166 Alloca->setAlignment(AlignmentToUse); 01167 llvm::Value *V = Alloca; 01168 llvm::Value *Ptr = V; // Pointer to store into. 01169 01170 // If the value is offset in memory, apply the offset now. 01171 if (unsigned Offs = ArgI.getDirectOffset()) { 01172 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy()); 01173 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs); 01174 Ptr = Builder.CreateBitCast(Ptr, 01175 llvm::PointerType::getUnqual(ArgI.getCoerceToType())); 01176 } 01177 01178 // If the coerce-to type is a first class aggregate, we flatten it and 01179 // pass the elements. Either way is semantically identical, but fast-isel 01180 // and the optimizer generally likes scalar values better than FCAs. 01181 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType()); 01182 if (STy && STy->getNumElements() > 1) { 01183 uint64_t SrcSize = CGM.getTargetData().getTypeAllocSize(STy); 01184 llvm::Type *DstTy = 01185 cast<llvm::PointerType>(Ptr->getType())->getElementType(); 01186 uint64_t DstSize = CGM.getTargetData().getTypeAllocSize(DstTy); 01187 01188 if (SrcSize <= DstSize) { 01189 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy)); 01190 01191 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 01192 assert(AI != Fn->arg_end() && "Argument mismatch!"); 01193 AI->setName(Arg->getName() + ".coerce" + Twine(i)); 01194 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i); 01195 Builder.CreateStore(AI++, EltPtr); 01196 } 01197 } else { 01198 llvm::AllocaInst *TempAlloca = 01199 CreateTempAlloca(ArgI.getCoerceToType(), "coerce"); 01200 TempAlloca->setAlignment(AlignmentToUse); 01201 llvm::Value *TempV = TempAlloca; 01202 01203 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 01204 assert(AI != Fn->arg_end() && "Argument mismatch!"); 01205 AI->setName(Arg->getName() + ".coerce" + Twine(i)); 01206 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i); 01207 Builder.CreateStore(AI++, EltPtr); 01208 } 01209 01210 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse); 01211 } 01212 } else { 01213 // Simple case, just do a coerced store of the argument into the alloca. 01214 assert(AI != Fn->arg_end() && "Argument mismatch!"); 01215 AI->setName(Arg->getName() + ".coerce"); 01216 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this); 01217 } 01218 01219 01220 // Match to what EmitParmDecl is expecting for this type. 01221 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) { 01222 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty); 01223 if (isPromoted) 01224 V = emitArgumentDemotion(*this, Arg, V); 01225 } 01226 EmitParmDecl(*Arg, V, ArgNo); 01227 continue; // Skip ++AI increment, already done. 01228 } 01229 01230 case ABIArgInfo::Expand: { 01231 // If this structure was expanded into multiple arguments then 01232 // we need to create a temporary and reconstruct it from the 01233 // arguments. 01234 llvm::AllocaInst *Alloca = CreateMemTemp(Ty); 01235 CharUnits Align = getContext().getDeclAlign(Arg); 01236 Alloca->setAlignment(Align.getQuantity()); 01237 LValue LV = MakeAddrLValue(Alloca, Ty, Align); 01238 llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI); 01239 EmitParmDecl(*Arg, Alloca, ArgNo); 01240 01241 // Name the arguments used in expansion and increment AI. 01242 unsigned Index = 0; 01243 for (; AI != End; ++AI, ++Index) 01244 AI->setName(Arg->getName() + "." + Twine(Index)); 01245 continue; 01246 } 01247 01248 case ABIArgInfo::Ignore: 01249 // Initialize the local variable appropriately. 01250 if (hasAggregateLLVMType(Ty)) 01251 EmitParmDecl(*Arg, CreateMemTemp(Ty), ArgNo); 01252 else 01253 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())), 01254 ArgNo); 01255 01256 // Skip increment, no matching LLVM parameter. 01257 continue; 01258 } 01259 01260 ++AI; 01261 } 01262 assert(AI == Fn->arg_end() && "Argument mismatch!"); 01263 } 01264 01265 static void eraseUnusedBitCasts(llvm::Instruction *insn) { 01266 while (insn->use_empty()) { 01267 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn); 01268 if (!bitcast) return; 01269 01270 // This is "safe" because we would have used a ConstantExpr otherwise. 01271 insn = cast<llvm::Instruction>(bitcast->getOperand(0)); 01272 bitcast->eraseFromParent(); 01273 } 01274 } 01275 01276 /// Try to emit a fused autorelease of a return result. 01277 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF, 01278 llvm::Value *result) { 01279 // We must be immediately followed the cast. 01280 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock(); 01281 if (BB->empty()) return 0; 01282 if (&BB->back() != result) return 0; 01283 01284 llvm::Type *resultType = result->getType(); 01285 01286 // result is in a BasicBlock and is therefore an Instruction. 01287 llvm::Instruction *generator = cast<llvm::Instruction>(result); 01288 01289 SmallVector<llvm::Instruction*,4> insnsToKill; 01290 01291 // Look for: 01292 // %generator = bitcast %type1* %generator2 to %type2* 01293 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) { 01294 // We would have emitted this as a constant if the operand weren't 01295 // an Instruction. 01296 generator = cast<llvm::Instruction>(bitcast->getOperand(0)); 01297 01298 // Require the generator to be immediately followed by the cast. 01299 if (generator->getNextNode() != bitcast) 01300 return 0; 01301 01302 insnsToKill.push_back(bitcast); 01303 } 01304 01305 // Look for: 01306 // %generator = call i8* @objc_retain(i8* %originalResult) 01307 // or 01308 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult) 01309 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator); 01310 if (!call) return 0; 01311 01312 bool doRetainAutorelease; 01313 01314 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) { 01315 doRetainAutorelease = true; 01316 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints() 01317 .objc_retainAutoreleasedReturnValue) { 01318 doRetainAutorelease = false; 01319 01320 // Look for an inline asm immediately preceding the call and kill it, too. 01321 llvm::Instruction *prev = call->getPrevNode(); 01322 if (llvm::CallInst *asmCall = dyn_cast_or_null<llvm::CallInst>(prev)) 01323 if (asmCall->getCalledValue() 01324 == CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) 01325 insnsToKill.push_back(prev); 01326 } else { 01327 return 0; 01328 } 01329 01330 result = call->getArgOperand(0); 01331 insnsToKill.push_back(call); 01332 01333 // Keep killing bitcasts, for sanity. Note that we no longer care 01334 // about precise ordering as long as there's exactly one use. 01335 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) { 01336 if (!bitcast->hasOneUse()) break; 01337 insnsToKill.push_back(bitcast); 01338 result = bitcast->getOperand(0); 01339 } 01340 01341 // Delete all the unnecessary instructions, from latest to earliest. 01342 for (SmallVectorImpl<llvm::Instruction*>::iterator 01343 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i) 01344 (*i)->eraseFromParent(); 01345 01346 // Do the fused retain/autorelease if we were asked to. 01347 if (doRetainAutorelease) 01348 result = CGF.EmitARCRetainAutoreleaseReturnValue(result); 01349 01350 // Cast back to the result type. 01351 return CGF.Builder.CreateBitCast(result, resultType); 01352 } 01353 01354 /// If this is a +1 of the value of an immutable 'self', remove it. 01355 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF, 01356 llvm::Value *result) { 01357 // This is only applicable to a method with an immutable 'self'. 01358 const ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CGF.CurCodeDecl); 01359 if (!method) return 0; 01360 const VarDecl *self = method->getSelfDecl(); 01361 if (!self->getType().isConstQualified()) return 0; 01362 01363 // Look for a retain call. 01364 llvm::CallInst *retainCall = 01365 dyn_cast<llvm::CallInst>(result->stripPointerCasts()); 01366 if (!retainCall || 01367 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain) 01368 return 0; 01369 01370 // Look for an ordinary load of 'self'. 01371 llvm::Value *retainedValue = retainCall->getArgOperand(0); 01372 llvm::LoadInst *load = 01373 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts()); 01374 if (!load || load->isAtomic() || load->isVolatile() || 01375 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self)) 01376 return 0; 01377 01378 // Okay! Burn it all down. This relies for correctness on the 01379 // assumption that the retain is emitted as part of the return and 01380 // that thereafter everything is used "linearly". 01381 llvm::Type *resultType = result->getType(); 01382 eraseUnusedBitCasts(cast<llvm::Instruction>(result)); 01383 assert(retainCall->use_empty()); 01384 retainCall->eraseFromParent(); 01385 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue)); 01386 01387 return CGF.Builder.CreateBitCast(load, resultType); 01388 } 01389 01390 /// Emit an ARC autorelease of the result of a function. 01391 /// 01392 /// \return the value to actually return from the function 01393 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF, 01394 llvm::Value *result) { 01395 // If we're returning 'self', kill the initial retain. This is a 01396 // heuristic attempt to "encourage correctness" in the really unfortunate 01397 // case where we have a return of self during a dealloc and we desperately 01398 // need to avoid the possible autorelease. 01399 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result)) 01400 return self; 01401 01402 // At -O0, try to emit a fused retain/autorelease. 01403 if (CGF.shouldUseFusedARCCalls()) 01404 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result)) 01405 return fused; 01406 01407 return CGF.EmitARCAutoreleaseReturnValue(result); 01408 } 01409 01410 /// Heuristically search for a dominating store to the return-value slot. 01411 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) { 01412 // If there are multiple uses of the return-value slot, just check 01413 // for something immediately preceding the IP. Sometimes this can 01414 // happen with how we generate implicit-returns; it can also happen 01415 // with noreturn cleanups. 01416 if (!CGF.ReturnValue->hasOneUse()) { 01417 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 01418 if (IP->empty()) return 0; 01419 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back()); 01420 if (!store) return 0; 01421 if (store->getPointerOperand() != CGF.ReturnValue) return 0; 01422 assert(!store->isAtomic() && !store->isVolatile()); // see below 01423 return store; 01424 } 01425 01426 llvm::StoreInst *store = 01427 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->use_back()); 01428 if (!store) return 0; 01429 01430 // These aren't actually possible for non-coerced returns, and we 01431 // only care about non-coerced returns on this code path. 01432 assert(!store->isAtomic() && !store->isVolatile()); 01433 01434 // Now do a first-and-dirty dominance check: just walk up the 01435 // single-predecessors chain from the current insertion point. 01436 llvm::BasicBlock *StoreBB = store->getParent(); 01437 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 01438 while (IP != StoreBB) { 01439 if (!(IP = IP->getSinglePredecessor())) 01440 return 0; 01441 } 01442 01443 // Okay, the store's basic block dominates the insertion point; we 01444 // can do our thing. 01445 return store; 01446 } 01447 01448 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI) { 01449 // Functions with no result always return void. 01450 if (ReturnValue == 0) { 01451 Builder.CreateRetVoid(); 01452 return; 01453 } 01454 01455 llvm::DebugLoc RetDbgLoc; 01456 llvm::Value *RV = 0; 01457 QualType RetTy = FI.getReturnType(); 01458 const ABIArgInfo &RetAI = FI.getReturnInfo(); 01459 01460 switch (RetAI.getKind()) { 01461 case ABIArgInfo::Indirect: { 01462 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity(); 01463 if (RetTy->isAnyComplexType()) { 01464 ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false); 01465 StoreComplexToAddr(RT, CurFn->arg_begin(), false); 01466 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) { 01467 // Do nothing; aggregrates get evaluated directly into the destination. 01468 } else { 01469 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(), 01470 false, Alignment, RetTy); 01471 } 01472 break; 01473 } 01474 01475 case ABIArgInfo::Extend: 01476 case ABIArgInfo::Direct: 01477 if (RetAI.getCoerceToType() == ConvertType(RetTy) && 01478 RetAI.getDirectOffset() == 0) { 01479 // The internal return value temp always will have pointer-to-return-type 01480 // type, just do a load. 01481 01482 // If there is a dominating store to ReturnValue, we can elide 01483 // the load, zap the store, and usually zap the alloca. 01484 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) { 01485 // Get the stored value and nuke the now-dead store. 01486 RetDbgLoc = SI->getDebugLoc(); 01487 RV = SI->getValueOperand(); 01488 SI->eraseFromParent(); 01489 01490 // If that was the only use of the return value, nuke it as well now. 01491 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) { 01492 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent(); 01493 ReturnValue = 0; 01494 } 01495 01496 // Otherwise, we have to do a simple load. 01497 } else { 01498 RV = Builder.CreateLoad(ReturnValue); 01499 } 01500 } else { 01501 llvm::Value *V = ReturnValue; 01502 // If the value is offset in memory, apply the offset now. 01503 if (unsigned Offs = RetAI.getDirectOffset()) { 01504 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy()); 01505 V = Builder.CreateConstGEP1_32(V, Offs); 01506 V = Builder.CreateBitCast(V, 01507 llvm::PointerType::getUnqual(RetAI.getCoerceToType())); 01508 } 01509 01510 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this); 01511 } 01512 01513 // In ARC, end functions that return a retainable type with a call 01514 // to objc_autoreleaseReturnValue. 01515 if (AutoreleaseResult) { 01516 assert(getLangOpts().ObjCAutoRefCount && 01517 !FI.isReturnsRetained() && 01518 RetTy->isObjCRetainableType()); 01519 RV = emitAutoreleaseOfResult(*this, RV); 01520 } 01521 01522 break; 01523 01524 case ABIArgInfo::Ignore: 01525 break; 01526 01527 case ABIArgInfo::Expand: 01528 llvm_unreachable("Invalid ABI kind for return argument"); 01529 } 01530 01531 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid(); 01532 if (!RetDbgLoc.isUnknown()) 01533 Ret->setDebugLoc(RetDbgLoc); 01534 } 01535 01536 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args, 01537 const VarDecl *param) { 01538 // StartFunction converted the ABI-lowered parameter(s) into a 01539 // local alloca. We need to turn that into an r-value suitable 01540 // for EmitCall. 01541 llvm::Value *local = GetAddrOfLocalVar(param); 01542 01543 QualType type = param->getType(); 01544 01545 // For the most part, we just need to load the alloca, except: 01546 // 1) aggregate r-values are actually pointers to temporaries, and 01547 // 2) references to aggregates are pointers directly to the aggregate. 01548 // I don't know why references to non-aggregates are different here. 01549 if (const ReferenceType *ref = type->getAs<ReferenceType>()) { 01550 if (hasAggregateLLVMType(ref->getPointeeType())) 01551 return args.add(RValue::getAggregate(local), type); 01552 01553 // Locals which are references to scalars are represented 01554 // with allocas holding the pointer. 01555 return args.add(RValue::get(Builder.CreateLoad(local)), type); 01556 } 01557 01558 if (type->isAnyComplexType()) { 01559 ComplexPairTy complex = LoadComplexFromAddr(local, /*volatile*/ false); 01560 return args.add(RValue::getComplex(complex), type); 01561 } 01562 01563 if (hasAggregateLLVMType(type)) 01564 return args.add(RValue::getAggregate(local), type); 01565 01566 unsigned alignment = getContext().getDeclAlign(param).getQuantity(); 01567 llvm::Value *value = EmitLoadOfScalar(local, false, alignment, type); 01568 return args.add(RValue::get(value), type); 01569 } 01570 01571 static bool isProvablyNull(llvm::Value *addr) { 01572 return isa<llvm::ConstantPointerNull>(addr); 01573 } 01574 01575 static bool isProvablyNonNull(llvm::Value *addr) { 01576 return isa<llvm::AllocaInst>(addr); 01577 } 01578 01579 /// Emit the actual writing-back of a writeback. 01580 static void emitWriteback(CodeGenFunction &CGF, 01581 const CallArgList::Writeback &writeback) { 01582 llvm::Value *srcAddr = writeback.Address; 01583 assert(!isProvablyNull(srcAddr) && 01584 "shouldn't have writeback for provably null argument"); 01585 01586 llvm::BasicBlock *contBB = 0; 01587 01588 // If the argument wasn't provably non-null, we need to null check 01589 // before doing the store. 01590 bool provablyNonNull = isProvablyNonNull(srcAddr); 01591 if (!provablyNonNull) { 01592 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback"); 01593 contBB = CGF.createBasicBlock("icr.done"); 01594 01595 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull"); 01596 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB); 01597 CGF.EmitBlock(writebackBB); 01598 } 01599 01600 // Load the value to writeback. 01601 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary); 01602 01603 // Cast it back, in case we're writing an id to a Foo* or something. 01604 value = CGF.Builder.CreateBitCast(value, 01605 cast<llvm::PointerType>(srcAddr->getType())->getElementType(), 01606 "icr.writeback-cast"); 01607 01608 // Perform the writeback. 01609 QualType srcAddrType = writeback.AddressType; 01610 CGF.EmitStoreThroughLValue(RValue::get(value), 01611 CGF.MakeAddrLValue(srcAddr, srcAddrType)); 01612 01613 // Jump to the continuation block. 01614 if (!provablyNonNull) 01615 CGF.EmitBlock(contBB); 01616 } 01617 01618 static void emitWritebacks(CodeGenFunction &CGF, 01619 const CallArgList &args) { 01620 for (CallArgList::writeback_iterator 01621 i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i) 01622 emitWriteback(CGF, *i); 01623 } 01624 01625 /// Emit an argument that's being passed call-by-writeback. That is, 01626 /// we are passing the address of 01627 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, 01628 const ObjCIndirectCopyRestoreExpr *CRE) { 01629 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr()); 01630 01631 // The dest and src types don't necessarily match in LLVM terms 01632 // because of the crazy ObjC compatibility rules. 01633 01634 llvm::PointerType *destType = 01635 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType())); 01636 01637 // If the address is a constant null, just pass the appropriate null. 01638 if (isProvablyNull(srcAddr)) { 01639 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)), 01640 CRE->getType()); 01641 return; 01642 } 01643 01644 QualType srcAddrType = 01645 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType(); 01646 01647 // Create the temporary. 01648 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(), 01649 "icr.temp"); 01650 01651 // Zero-initialize it if we're not doing a copy-initialization. 01652 bool shouldCopy = CRE->shouldCopy(); 01653 if (!shouldCopy) { 01654 llvm::Value *null = 01655 llvm::ConstantPointerNull::get( 01656 cast<llvm::PointerType>(destType->getElementType())); 01657 CGF.Builder.CreateStore(null, temp); 01658 } 01659 01660 llvm::BasicBlock *contBB = 0; 01661 01662 // If the address is *not* known to be non-null, we need to switch. 01663 llvm::Value *finalArgument; 01664 01665 bool provablyNonNull = isProvablyNonNull(srcAddr); 01666 if (provablyNonNull) { 01667 finalArgument = temp; 01668 } else { 01669 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull"); 01670 01671 finalArgument = CGF.Builder.CreateSelect(isNull, 01672 llvm::ConstantPointerNull::get(destType), 01673 temp, "icr.argument"); 01674 01675 // If we need to copy, then the load has to be conditional, which 01676 // means we need control flow. 01677 if (shouldCopy) { 01678 contBB = CGF.createBasicBlock("icr.cont"); 01679 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy"); 01680 CGF.Builder.CreateCondBr(isNull, contBB, copyBB); 01681 CGF.EmitBlock(copyBB); 01682 } 01683 } 01684 01685 // Perform a copy if necessary. 01686 if (shouldCopy) { 01687 LValue srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType); 01688 RValue srcRV = CGF.EmitLoadOfLValue(srcLV); 01689 assert(srcRV.isScalar()); 01690 01691 llvm::Value *src = srcRV.getScalarVal(); 01692 src = CGF.Builder.CreateBitCast(src, destType->getElementType(), 01693 "icr.cast"); 01694 01695 // Use an ordinary store, not a store-to-lvalue. 01696 CGF.Builder.CreateStore(src, temp); 01697 } 01698 01699 // Finish the control flow if we needed it. 01700 if (shouldCopy && !provablyNonNull) 01701 CGF.EmitBlock(contBB); 01702 01703 args.addWriteback(srcAddr, srcAddrType, temp); 01704 args.add(RValue::get(finalArgument), CRE->getType()); 01705 } 01706 01707 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E, 01708 QualType type) { 01709 if (const ObjCIndirectCopyRestoreExpr *CRE 01710 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) { 01711 assert(getContext().getLangOpts().ObjCAutoRefCount); 01712 assert(getContext().hasSameType(E->getType(), type)); 01713 return emitWritebackArg(*this, args, CRE); 01714 } 01715 01716 assert(type->isReferenceType() == E->isGLValue() && 01717 "reference binding to unmaterialized r-value!"); 01718 01719 if (E->isGLValue()) { 01720 assert(E->getObjectKind() == OK_Ordinary); 01721 return args.add(EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0), 01722 type); 01723 } 01724 01725 if (hasAggregateLLVMType(type) && !E->getType()->isAnyComplexType() && 01726 isa<ImplicitCastExpr>(E) && 01727 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) { 01728 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr()); 01729 assert(L.isSimple()); 01730 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true); 01731 return; 01732 } 01733 01734 args.add(EmitAnyExprToTemp(E), type); 01735 } 01736 01737 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 01738 // optimizer it can aggressively ignore unwind edges. 01739 void 01740 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) { 01741 if (CGM.getCodeGenOpts().OptimizationLevel != 0 && 01742 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions) 01743 Inst->setMetadata("clang.arc.no_objc_arc_exceptions", 01744 CGM.getNoObjCARCExceptionsMetadata()); 01745 } 01746 01747 /// Emits a call or invoke instruction to the given function, depending 01748 /// on the current state of the EH stack. 01749 llvm::CallSite 01750 CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee, 01751 ArrayRef<llvm::Value *> Args, 01752 const Twine &Name) { 01753 llvm::BasicBlock *InvokeDest = getInvokeDest(); 01754 01755 llvm::Instruction *Inst; 01756 if (!InvokeDest) 01757 Inst = Builder.CreateCall(Callee, Args, Name); 01758 else { 01759 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont"); 01760 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name); 01761 EmitBlock(ContBB); 01762 } 01763 01764 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 01765 // optimizer it can aggressively ignore unwind edges. 01766 if (CGM.getLangOpts().ObjCAutoRefCount) 01767 AddObjCARCExceptionMetadata(Inst); 01768 01769 return Inst; 01770 } 01771 01772 llvm::CallSite 01773 CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee, 01774 const Twine &Name) { 01775 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name); 01776 } 01777 01778 static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo, 01779 llvm::FunctionType *FTy) { 01780 if (ArgNo < FTy->getNumParams()) 01781 assert(Elt->getType() == FTy->getParamType(ArgNo)); 01782 else 01783 assert(FTy->isVarArg()); 01784 ++ArgNo; 01785 } 01786 01787 void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV, 01788 SmallVector<llvm::Value*,16> &Args, 01789 llvm::FunctionType *IRFuncTy) { 01790 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 01791 unsigned NumElts = AT->getSize().getZExtValue(); 01792 QualType EltTy = AT->getElementType(); 01793 llvm::Value *Addr = RV.getAggregateAddr(); 01794 for (unsigned Elt = 0; Elt < NumElts; ++Elt) { 01795 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt); 01796 LValue LV = MakeAddrLValue(EltAddr, EltTy); 01797 RValue EltRV; 01798 if (EltTy->isAnyComplexType()) 01799 // FIXME: Volatile? 01800 EltRV = RValue::getComplex(LoadComplexFromAddr(LV.getAddress(), false)); 01801 else if (CodeGenFunction::hasAggregateLLVMType(EltTy)) 01802 EltRV = LV.asAggregateRValue(); 01803 else 01804 EltRV = EmitLoadOfLValue(LV); 01805 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy); 01806 } 01807 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 01808 RecordDecl *RD = RT->getDecl(); 01809 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion"); 01810 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty); 01811 01812 if (RD->isUnion()) { 01813 const FieldDecl *LargestFD = 0; 01814 CharUnits UnionSize = CharUnits::Zero(); 01815 01816 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 01817 i != e; ++i) { 01818 const FieldDecl *FD = &*i; 01819 assert(!FD->isBitField() && 01820 "Cannot expand structure with bit-field members."); 01821 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType()); 01822 if (UnionSize < FieldSize) { 01823 UnionSize = FieldSize; 01824 LargestFD = FD; 01825 } 01826 } 01827 if (LargestFD) { 01828 RValue FldRV = EmitRValueForField(LV, LargestFD); 01829 ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy); 01830 } 01831 } else { 01832 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 01833 i != e; ++i) { 01834 FieldDecl *FD = &*i; 01835 01836 RValue FldRV = EmitRValueForField(LV, FD); 01837 ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy); 01838 } 01839 } 01840 } else if (Ty->isAnyComplexType()) { 01841 ComplexPairTy CV = RV.getComplexVal(); 01842 Args.push_back(CV.first); 01843 Args.push_back(CV.second); 01844 } else { 01845 assert(RV.isScalar() && 01846 "Unexpected non-scalar rvalue during struct expansion."); 01847 01848 // Insert a bitcast as needed. 01849 llvm::Value *V = RV.getScalarVal(); 01850 if (Args.size() < IRFuncTy->getNumParams() && 01851 V->getType() != IRFuncTy->getParamType(Args.size())) 01852 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size())); 01853 01854 Args.push_back(V); 01855 } 01856 } 01857 01858 01859 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, 01860 llvm::Value *Callee, 01861 ReturnValueSlot ReturnValue, 01862 const CallArgList &CallArgs, 01863 const Decl *TargetDecl, 01864 llvm::Instruction **callOrInvoke) { 01865 // FIXME: We no longer need the types from CallArgs; lift up and simplify. 01866 SmallVector<llvm::Value*, 16> Args; 01867 01868 // Handle struct-return functions by passing a pointer to the 01869 // location that we would like to return into. 01870 QualType RetTy = CallInfo.getReturnType(); 01871 const ABIArgInfo &RetAI = CallInfo.getReturnInfo(); 01872 01873 // IRArgNo - Keep track of the argument number in the callee we're looking at. 01874 unsigned IRArgNo = 0; 01875 llvm::FunctionType *IRFuncTy = 01876 cast<llvm::FunctionType>( 01877 cast<llvm::PointerType>(Callee->getType())->getElementType()); 01878 01879 // If the call returns a temporary with struct return, create a temporary 01880 // alloca to hold the result, unless one is given to us. 01881 if (CGM.ReturnTypeUsesSRet(CallInfo)) { 01882 llvm::Value *Value = ReturnValue.getValue(); 01883 if (!Value) 01884 Value = CreateMemTemp(RetTy); 01885 Args.push_back(Value); 01886 checkArgMatches(Value, IRArgNo, IRFuncTy); 01887 } 01888 01889 assert(CallInfo.arg_size() == CallArgs.size() && 01890 "Mismatch between function signature & arguments."); 01891 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin(); 01892 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); 01893 I != E; ++I, ++info_it) { 01894 const ABIArgInfo &ArgInfo = info_it->info; 01895 RValue RV = I->RV; 01896 01897 unsigned TypeAlign = 01898 getContext().getTypeAlignInChars(I->Ty).getQuantity(); 01899 switch (ArgInfo.getKind()) { 01900 case ABIArgInfo::Indirect: { 01901 if (RV.isScalar() || RV.isComplex()) { 01902 // Make a temporary alloca to pass the argument. 01903 llvm::AllocaInst *AI = CreateMemTemp(I->Ty); 01904 if (ArgInfo.getIndirectAlign() > AI->getAlignment()) 01905 AI->setAlignment(ArgInfo.getIndirectAlign()); 01906 Args.push_back(AI); 01907 01908 if (RV.isScalar()) 01909 EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false, 01910 TypeAlign, I->Ty); 01911 else 01912 StoreComplexToAddr(RV.getComplexVal(), Args.back(), false); 01913 01914 // Validate argument match. 01915 checkArgMatches(AI, IRArgNo, IRFuncTy); 01916 } else { 01917 // We want to avoid creating an unnecessary temporary+copy here; 01918 // however, we need one in two cases: 01919 // 1. If the argument is not byval, and we are required to copy the 01920 // source. (This case doesn't occur on any common architecture.) 01921 // 2. If the argument is byval, RV is not sufficiently aligned, and 01922 // we cannot force it to be sufficiently aligned. 01923 llvm::Value *Addr = RV.getAggregateAddr(); 01924 unsigned Align = ArgInfo.getIndirectAlign(); 01925 const llvm::TargetData *TD = &CGM.getTargetData(); 01926 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) || 01927 (ArgInfo.getIndirectByVal() && TypeAlign < Align && 01928 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align)) { 01929 // Create an aligned temporary, and copy to it. 01930 llvm::AllocaInst *AI = CreateMemTemp(I->Ty); 01931 if (Align > AI->getAlignment()) 01932 AI->setAlignment(Align); 01933 Args.push_back(AI); 01934 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified()); 01935 01936 // Validate argument match. 01937 checkArgMatches(AI, IRArgNo, IRFuncTy); 01938 } else { 01939 // Skip the extra memcpy call. 01940 Args.push_back(Addr); 01941 01942 // Validate argument match. 01943 checkArgMatches(Addr, IRArgNo, IRFuncTy); 01944 } 01945 } 01946 break; 01947 } 01948 01949 case ABIArgInfo::Ignore: 01950 break; 01951 01952 case ABIArgInfo::Extend: 01953 case ABIArgInfo::Direct: { 01954 // Insert a padding argument to ensure proper alignment. 01955 if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) { 01956 Args.push_back(llvm::UndefValue::get(PaddingType)); 01957 ++IRArgNo; 01958 } 01959 01960 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) && 01961 ArgInfo.getCoerceToType() == ConvertType(info_it->type) && 01962 ArgInfo.getDirectOffset() == 0) { 01963 llvm::Value *V; 01964 if (RV.isScalar()) 01965 V = RV.getScalarVal(); 01966 else 01967 V = Builder.CreateLoad(RV.getAggregateAddr()); 01968 01969 // If the argument doesn't match, perform a bitcast to coerce it. This 01970 // can happen due to trivial type mismatches. 01971 if (IRArgNo < IRFuncTy->getNumParams() && 01972 V->getType() != IRFuncTy->getParamType(IRArgNo)) 01973 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo)); 01974 Args.push_back(V); 01975 01976 checkArgMatches(V, IRArgNo, IRFuncTy); 01977 break; 01978 } 01979 01980 // FIXME: Avoid the conversion through memory if possible. 01981 llvm::Value *SrcPtr; 01982 if (RV.isScalar()) { 01983 SrcPtr = CreateMemTemp(I->Ty, "coerce"); 01984 EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, TypeAlign, I->Ty); 01985 } else if (RV.isComplex()) { 01986 SrcPtr = CreateMemTemp(I->Ty, "coerce"); 01987 StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false); 01988 } else 01989 SrcPtr = RV.getAggregateAddr(); 01990 01991 // If the value is offset in memory, apply the offset now. 01992 if (unsigned Offs = ArgInfo.getDirectOffset()) { 01993 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy()); 01994 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs); 01995 SrcPtr = Builder.CreateBitCast(SrcPtr, 01996 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType())); 01997 01998 } 01999 02000 // If the coerce-to type is a first class aggregate, we flatten it and 02001 // pass the elements. Either way is semantically identical, but fast-isel 02002 // and the optimizer generally likes scalar values better than FCAs. 02003 if (llvm::StructType *STy = 02004 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) { 02005 SrcPtr = Builder.CreateBitCast(SrcPtr, 02006 llvm::PointerType::getUnqual(STy)); 02007 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 02008 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i); 02009 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr); 02010 // We don't know what we're loading from. 02011 LI->setAlignment(1); 02012 Args.push_back(LI); 02013 02014 // Validate argument match. 02015 checkArgMatches(LI, IRArgNo, IRFuncTy); 02016 } 02017 } else { 02018 // In the simple case, just pass the coerced loaded value. 02019 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), 02020 *this)); 02021 02022 // Validate argument match. 02023 checkArgMatches(Args.back(), IRArgNo, IRFuncTy); 02024 } 02025 02026 break; 02027 } 02028 02029 case ABIArgInfo::Expand: 02030 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy); 02031 IRArgNo = Args.size(); 02032 break; 02033 } 02034 } 02035 02036 // If the callee is a bitcast of a function to a varargs pointer to function 02037 // type, check to see if we can remove the bitcast. This handles some cases 02038 // with unprototyped functions. 02039 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee)) 02040 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) { 02041 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType()); 02042 llvm::FunctionType *CurFT = 02043 cast<llvm::FunctionType>(CurPT->getElementType()); 02044 llvm::FunctionType *ActualFT = CalleeF->getFunctionType(); 02045 02046 if (CE->getOpcode() == llvm::Instruction::BitCast && 02047 ActualFT->getReturnType() == CurFT->getReturnType() && 02048 ActualFT->getNumParams() == CurFT->getNumParams() && 02049 ActualFT->getNumParams() == Args.size() && 02050 (CurFT->isVarArg() || !ActualFT->isVarArg())) { 02051 bool ArgsMatch = true; 02052 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i) 02053 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) { 02054 ArgsMatch = false; 02055 break; 02056 } 02057 02058 // Strip the cast if we can get away with it. This is a nice cleanup, 02059 // but also allows us to inline the function at -O0 if it is marked 02060 // always_inline. 02061 if (ArgsMatch) 02062 Callee = CalleeF; 02063 } 02064 } 02065 02066 unsigned CallingConv; 02067 CodeGen::AttributeListType AttributeList; 02068 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList, CallingConv); 02069 llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(), 02070 AttributeList.end()); 02071 02072 llvm::BasicBlock *InvokeDest = 0; 02073 if (!(Attrs.getFnAttributes() & llvm::Attribute::NoUnwind)) 02074 InvokeDest = getInvokeDest(); 02075 02076 llvm::CallSite CS; 02077 if (!InvokeDest) { 02078 CS = Builder.CreateCall(Callee, Args); 02079 } else { 02080 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont"); 02081 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args); 02082 EmitBlock(Cont); 02083 } 02084 if (callOrInvoke) 02085 *callOrInvoke = CS.getInstruction(); 02086 02087 CS.setAttributes(Attrs); 02088 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 02089 02090 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 02091 // optimizer it can aggressively ignore unwind edges. 02092 if (CGM.getLangOpts().ObjCAutoRefCount) 02093 AddObjCARCExceptionMetadata(CS.getInstruction()); 02094 02095 // If the call doesn't return, finish the basic block and clear the 02096 // insertion point; this allows the rest of IRgen to discard 02097 // unreachable code. 02098 if (CS.doesNotReturn()) { 02099 Builder.CreateUnreachable(); 02100 Builder.ClearInsertionPoint(); 02101 02102 // FIXME: For now, emit a dummy basic block because expr emitters in 02103 // generally are not ready to handle emitting expressions at unreachable 02104 // points. 02105 EnsureInsertPoint(); 02106 02107 // Return a reasonable RValue. 02108 return GetUndefRValue(RetTy); 02109 } 02110 02111 llvm::Instruction *CI = CS.getInstruction(); 02112 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy()) 02113 CI->setName("call"); 02114 02115 // Emit any writebacks immediately. Arguably this should happen 02116 // after any return-value munging. 02117 if (CallArgs.hasWritebacks()) 02118 emitWritebacks(*this, CallArgs); 02119 02120 switch (RetAI.getKind()) { 02121 case ABIArgInfo::Indirect: { 02122 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity(); 02123 if (RetTy->isAnyComplexType()) 02124 return RValue::getComplex(LoadComplexFromAddr(Args[0], false)); 02125 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) 02126 return RValue::getAggregate(Args[0]); 02127 return RValue::get(EmitLoadOfScalar(Args[0], false, Alignment, RetTy)); 02128 } 02129 02130 case ABIArgInfo::Ignore: 02131 // If we are ignoring an argument that had a result, make sure to 02132 // construct the appropriate return value for our caller. 02133 return GetUndefRValue(RetTy); 02134 02135 case ABIArgInfo::Extend: 02136 case ABIArgInfo::Direct: { 02137 llvm::Type *RetIRTy = ConvertType(RetTy); 02138 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) { 02139 if (RetTy->isAnyComplexType()) { 02140 llvm::Value *Real = Builder.CreateExtractValue(CI, 0); 02141 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1); 02142 return RValue::getComplex(std::make_pair(Real, Imag)); 02143 } 02144 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) { 02145 llvm::Value *DestPtr = ReturnValue.getValue(); 02146 bool DestIsVolatile = ReturnValue.isVolatile(); 02147 02148 if (!DestPtr) { 02149 DestPtr = CreateMemTemp(RetTy, "agg.tmp"); 02150 DestIsVolatile = false; 02151 } 02152 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false); 02153 return RValue::getAggregate(DestPtr); 02154 } 02155 02156 // If the argument doesn't match, perform a bitcast to coerce it. This 02157 // can happen due to trivial type mismatches. 02158 llvm::Value *V = CI; 02159 if (V->getType() != RetIRTy) 02160 V = Builder.CreateBitCast(V, RetIRTy); 02161 return RValue::get(V); 02162 } 02163 02164 llvm::Value *DestPtr = ReturnValue.getValue(); 02165 bool DestIsVolatile = ReturnValue.isVolatile(); 02166 02167 if (!DestPtr) { 02168 DestPtr = CreateMemTemp(RetTy, "coerce"); 02169 DestIsVolatile = false; 02170 } 02171 02172 // If the value is offset in memory, apply the offset now. 02173 llvm::Value *StorePtr = DestPtr; 02174 if (unsigned Offs = RetAI.getDirectOffset()) { 02175 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy()); 02176 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs); 02177 StorePtr = Builder.CreateBitCast(StorePtr, 02178 llvm::PointerType::getUnqual(RetAI.getCoerceToType())); 02179 } 02180 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this); 02181 02182 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity(); 02183 if (RetTy->isAnyComplexType()) 02184 return RValue::getComplex(LoadComplexFromAddr(DestPtr, false)); 02185 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) 02186 return RValue::getAggregate(DestPtr); 02187 return RValue::get(EmitLoadOfScalar(DestPtr, false, Alignment, RetTy)); 02188 } 02189 02190 case ABIArgInfo::Expand: 02191 llvm_unreachable("Invalid ABI kind for return argument"); 02192 } 02193 02194 llvm_unreachable("Unhandled ABIArgInfo::Kind"); 02195 } 02196 02197 /* VarArg handling */ 02198 02199 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) { 02200 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this); 02201 }