CGCall.cpp revision 208600
1//===----- CGCall.h - Encapsulate calling convention details ----*- C++ -*-===// 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 "CodeGenFunction.h" 17#include "CodeGenModule.h" 18#include "clang/Basic/TargetInfo.h" 19#include "clang/AST/Decl.h" 20#include "clang/AST/DeclCXX.h" 21#include "clang/AST/DeclObjC.h" 22#include "clang/CodeGen/CodeGenOptions.h" 23#include "llvm/Attributes.h" 24#include "llvm/Support/CallSite.h" 25#include "llvm/Target/TargetData.h" 26 27#include "ABIInfo.h" 28 29using namespace clang; 30using namespace CodeGen; 31 32/***/ 33 34// FIXME: Use iterator and sidestep silly type array creation. 35 36static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) { 37 switch (CC) { 38 default: return llvm::CallingConv::C; 39 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall; 40 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall; 41 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall; 42 } 43} 44 45/// Derives the 'this' type for codegen purposes, i.e. ignoring method 46/// qualification. 47/// FIXME: address space qualification? 48static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) { 49 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal(); 50 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy)); 51} 52 53/// Returns the canonical formal type of the given C++ method. 54static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) { 55 return MD->getType()->getCanonicalTypeUnqualified() 56 .getAs<FunctionProtoType>(); 57} 58 59/// Returns the "extra-canonicalized" return type, which discards 60/// qualifiers on the return type. Codegen doesn't care about them, 61/// and it makes ABI code a little easier to be able to assume that 62/// all parameter and return types are top-level unqualified. 63static CanQualType GetReturnType(QualType RetTy) { 64 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType(); 65} 66 67const CGFunctionInfo & 68CodeGenTypes::getFunctionInfo(CanQual<FunctionNoProtoType> FTNP) { 69 return getFunctionInfo(FTNP->getResultType().getUnqualifiedType(), 70 llvm::SmallVector<CanQualType, 16>(), 71 FTNP->getExtInfo()); 72} 73 74/// \param Args - contains any initial parameters besides those 75/// in the formal type 76static const CGFunctionInfo &getFunctionInfo(CodeGenTypes &CGT, 77 llvm::SmallVectorImpl<CanQualType> &ArgTys, 78 CanQual<FunctionProtoType> FTP) { 79 // FIXME: Kill copy. 80 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i) 81 ArgTys.push_back(FTP->getArgType(i)); 82 CanQualType ResTy = FTP->getResultType().getUnqualifiedType(); 83 return CGT.getFunctionInfo(ResTy, ArgTys, 84 FTP->getExtInfo()); 85} 86 87const CGFunctionInfo & 88CodeGenTypes::getFunctionInfo(CanQual<FunctionProtoType> FTP) { 89 llvm::SmallVector<CanQualType, 16> ArgTys; 90 return ::getFunctionInfo(*this, ArgTys, FTP); 91} 92 93static CallingConv getCallingConventionForDecl(const Decl *D) { 94 // Set the appropriate calling convention for the Function. 95 if (D->hasAttr<StdCallAttr>()) 96 return CC_X86StdCall; 97 98 if (D->hasAttr<FastCallAttr>()) 99 return CC_X86FastCall; 100 101 if (D->hasAttr<ThisCallAttr>()) 102 return CC_X86ThisCall; 103 104 return CC_C; 105} 106 107const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXRecordDecl *RD, 108 const FunctionProtoType *FTP) { 109 llvm::SmallVector<CanQualType, 16> ArgTys; 110 111 // Add the 'this' pointer. 112 ArgTys.push_back(GetThisType(Context, RD)); 113 114 return ::getFunctionInfo(*this, ArgTys, 115 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>()); 116} 117 118const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) { 119 llvm::SmallVector<CanQualType, 16> ArgTys; 120 121 // Add the 'this' pointer unless this is a static method. 122 if (MD->isInstance()) 123 ArgTys.push_back(GetThisType(Context, MD->getParent())); 124 125 return ::getFunctionInfo(*this, ArgTys, GetFormalType(MD)); 126} 127 128const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXConstructorDecl *D, 129 CXXCtorType Type) { 130 llvm::SmallVector<CanQualType, 16> ArgTys; 131 132 // Add the 'this' pointer. 133 ArgTys.push_back(GetThisType(Context, D->getParent())); 134 135 // Check if we need to add a VTT parameter (which has type void **). 136 if (Type == Ctor_Base && D->getParent()->getNumVBases() != 0) 137 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy)); 138 139 return ::getFunctionInfo(*this, ArgTys, GetFormalType(D)); 140} 141 142const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXDestructorDecl *D, 143 CXXDtorType Type) { 144 llvm::SmallVector<CanQualType, 16> ArgTys; 145 146 // Add the 'this' pointer. 147 ArgTys.push_back(GetThisType(Context, D->getParent())); 148 149 // Check if we need to add a VTT parameter (which has type void **). 150 if (Type == Dtor_Base && D->getParent()->getNumVBases() != 0) 151 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy)); 152 153 return ::getFunctionInfo(*this, ArgTys, GetFormalType(D)); 154} 155 156const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) { 157 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 158 if (MD->isInstance()) 159 return getFunctionInfo(MD); 160 161 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified(); 162 assert(isa<FunctionType>(FTy)); 163 if (isa<FunctionNoProtoType>(FTy)) 164 return getFunctionInfo(FTy.getAs<FunctionNoProtoType>()); 165 assert(isa<FunctionProtoType>(FTy)); 166 return getFunctionInfo(FTy.getAs<FunctionProtoType>()); 167} 168 169const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) { 170 llvm::SmallVector<CanQualType, 16> ArgTys; 171 ArgTys.push_back(Context.getCanonicalParamType(MD->getSelfDecl()->getType())); 172 ArgTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType())); 173 // FIXME: Kill copy? 174 for (ObjCMethodDecl::param_iterator i = MD->param_begin(), 175 e = MD->param_end(); i != e; ++i) { 176 ArgTys.push_back(Context.getCanonicalParamType((*i)->getType())); 177 } 178 return getFunctionInfo(GetReturnType(MD->getResultType()), 179 ArgTys, 180 FunctionType::ExtInfo( 181 /*NoReturn*/ false, 182 /*RegParm*/ 0, 183 getCallingConventionForDecl(MD))); 184} 185 186const CGFunctionInfo &CodeGenTypes::getFunctionInfo(GlobalDecl GD) { 187 // FIXME: Do we need to handle ObjCMethodDecl? 188 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 189 190 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 191 return getFunctionInfo(CD, GD.getCtorType()); 192 193 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) 194 return getFunctionInfo(DD, GD.getDtorType()); 195 196 return getFunctionInfo(FD); 197} 198 199const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, 200 const CallArgList &Args, 201 const FunctionType::ExtInfo &Info) { 202 // FIXME: Kill copy. 203 llvm::SmallVector<CanQualType, 16> ArgTys; 204 for (CallArgList::const_iterator i = Args.begin(), e = Args.end(); 205 i != e; ++i) 206 ArgTys.push_back(Context.getCanonicalParamType(i->second)); 207 return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info); 208} 209 210const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, 211 const FunctionArgList &Args, 212 const FunctionType::ExtInfo &Info) { 213 // FIXME: Kill copy. 214 llvm::SmallVector<CanQualType, 16> ArgTys; 215 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 216 i != e; ++i) 217 ArgTys.push_back(Context.getCanonicalParamType(i->second)); 218 return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info); 219} 220 221const CGFunctionInfo &CodeGenTypes::getFunctionInfo(CanQualType ResTy, 222 const llvm::SmallVectorImpl<CanQualType> &ArgTys, 223 const FunctionType::ExtInfo &Info) { 224#ifndef NDEBUG 225 for (llvm::SmallVectorImpl<CanQualType>::const_iterator 226 I = ArgTys.begin(), E = ArgTys.end(); I != E; ++I) 227 assert(I->isCanonicalAsParam()); 228#endif 229 230 unsigned CC = ClangCallConvToLLVMCallConv(Info.getCC()); 231 232 // Lookup or create unique function info. 233 llvm::FoldingSetNodeID ID; 234 CGFunctionInfo::Profile(ID, Info, ResTy, 235 ArgTys.begin(), ArgTys.end()); 236 237 void *InsertPos = 0; 238 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos); 239 if (FI) 240 return *FI; 241 242 // Construct the function info. 243 FI = new CGFunctionInfo(CC, Info.getNoReturn(), Info.getRegParm(), ResTy, ArgTys); 244 FunctionInfos.InsertNode(FI, InsertPos); 245 246 // Compute ABI information. 247 getABIInfo().computeInfo(*FI, getContext(), TheModule.getContext()); 248 249 return *FI; 250} 251 252CGFunctionInfo::CGFunctionInfo(unsigned _CallingConvention, 253 bool _NoReturn, 254 unsigned _RegParm, 255 CanQualType ResTy, 256 const llvm::SmallVectorImpl<CanQualType> &ArgTys) 257 : CallingConvention(_CallingConvention), 258 EffectiveCallingConvention(_CallingConvention), 259 NoReturn(_NoReturn), RegParm(_RegParm) 260{ 261 NumArgs = ArgTys.size(); 262 Args = new ArgInfo[1 + NumArgs]; 263 Args[0].type = ResTy; 264 for (unsigned i = 0; i < NumArgs; ++i) 265 Args[1 + i].type = ArgTys[i]; 266} 267 268/***/ 269 270void CodeGenTypes::GetExpandedTypes(QualType Ty, 271 std::vector<const llvm::Type*> &ArgTys) { 272 const RecordType *RT = Ty->getAsStructureType(); 273 assert(RT && "Can only expand structure types."); 274 const RecordDecl *RD = RT->getDecl(); 275 assert(!RD->hasFlexibleArrayMember() && 276 "Cannot expand structure with flexible array."); 277 278 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 279 i != e; ++i) { 280 const FieldDecl *FD = *i; 281 assert(!FD->isBitField() && 282 "Cannot expand structure with bit-field members."); 283 284 QualType FT = FD->getType(); 285 if (CodeGenFunction::hasAggregateLLVMType(FT)) { 286 GetExpandedTypes(FT, ArgTys); 287 } else { 288 ArgTys.push_back(ConvertType(FT)); 289 } 290 } 291} 292 293llvm::Function::arg_iterator 294CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV, 295 llvm::Function::arg_iterator AI) { 296 const RecordType *RT = Ty->getAsStructureType(); 297 assert(RT && "Can only expand structure types."); 298 299 RecordDecl *RD = RT->getDecl(); 300 assert(LV.isSimple() && 301 "Unexpected non-simple lvalue during struct expansion."); 302 llvm::Value *Addr = LV.getAddress(); 303 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 304 i != e; ++i) { 305 FieldDecl *FD = *i; 306 QualType FT = FD->getType(); 307 308 // FIXME: What are the right qualifiers here? 309 LValue LV = EmitLValueForField(Addr, FD, 0); 310 if (CodeGenFunction::hasAggregateLLVMType(FT)) { 311 AI = ExpandTypeFromArgs(FT, LV, AI); 312 } else { 313 EmitStoreThroughLValue(RValue::get(AI), LV, FT); 314 ++AI; 315 } 316 } 317 318 return AI; 319} 320 321void 322CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV, 323 llvm::SmallVector<llvm::Value*, 16> &Args) { 324 const RecordType *RT = Ty->getAsStructureType(); 325 assert(RT && "Can only expand structure types."); 326 327 RecordDecl *RD = RT->getDecl(); 328 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion"); 329 llvm::Value *Addr = RV.getAggregateAddr(); 330 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 331 i != e; ++i) { 332 FieldDecl *FD = *i; 333 QualType FT = FD->getType(); 334 335 // FIXME: What are the right qualifiers here? 336 LValue LV = EmitLValueForField(Addr, FD, 0); 337 if (CodeGenFunction::hasAggregateLLVMType(FT)) { 338 ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args); 339 } else { 340 RValue RV = EmitLoadOfLValue(LV, FT); 341 assert(RV.isScalar() && 342 "Unexpected non-scalar rvalue during struct expansion."); 343 Args.push_back(RV.getScalarVal()); 344 } 345 } 346} 347 348/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as 349/// a pointer to an object of type \arg Ty. 350/// 351/// This safely handles the case when the src type is smaller than the 352/// destination type; in this situation the values of bits which not 353/// present in the src are undefined. 354static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr, 355 const llvm::Type *Ty, 356 CodeGenFunction &CGF) { 357 const llvm::Type *SrcTy = 358 cast<llvm::PointerType>(SrcPtr->getType())->getElementType(); 359 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy); 360 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty); 361 362 // If load is legal, just bitcast the src pointer. 363 if (SrcSize >= DstSize) { 364 // Generally SrcSize is never greater than DstSize, since this means we are 365 // losing bits. However, this can happen in cases where the structure has 366 // additional padding, for example due to a user specified alignment. 367 // 368 // FIXME: Assert that we aren't truncating non-padding bits when have access 369 // to that information. 370 llvm::Value *Casted = 371 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty)); 372 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted); 373 // FIXME: Use better alignment / avoid requiring aligned load. 374 Load->setAlignment(1); 375 return Load; 376 } else { 377 // Otherwise do coercion through memory. This is stupid, but 378 // simple. 379 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty); 380 llvm::Value *Casted = 381 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy)); 382 llvm::StoreInst *Store = 383 CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted); 384 // FIXME: Use better alignment / avoid requiring aligned store. 385 Store->setAlignment(1); 386 return CGF.Builder.CreateLoad(Tmp); 387 } 388} 389 390/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src, 391/// where the source and destination may have different types. 392/// 393/// This safely handles the case when the src type is larger than the 394/// destination type; the upper bits of the src will be lost. 395static void CreateCoercedStore(llvm::Value *Src, 396 llvm::Value *DstPtr, 397 bool DstIsVolatile, 398 CodeGenFunction &CGF) { 399 const llvm::Type *SrcTy = Src->getType(); 400 const llvm::Type *DstTy = 401 cast<llvm::PointerType>(DstPtr->getType())->getElementType(); 402 403 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy); 404 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy); 405 406 // If store is legal, just bitcast the src pointer. 407 if (SrcSize <= DstSize) { 408 llvm::Value *Casted = 409 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy)); 410 // FIXME: Use better alignment / avoid requiring aligned store. 411 CGF.Builder.CreateStore(Src, Casted, DstIsVolatile)->setAlignment(1); 412 } else { 413 // Otherwise do coercion through memory. This is stupid, but 414 // simple. 415 416 // Generally SrcSize is never greater than DstSize, since this means we are 417 // losing bits. However, this can happen in cases where the structure has 418 // additional padding, for example due to a user specified alignment. 419 // 420 // FIXME: Assert that we aren't truncating non-padding bits when have access 421 // to that information. 422 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy); 423 CGF.Builder.CreateStore(Src, Tmp); 424 llvm::Value *Casted = 425 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy)); 426 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted); 427 // FIXME: Use better alignment / avoid requiring aligned load. 428 Load->setAlignment(1); 429 CGF.Builder.CreateStore(Load, DstPtr, DstIsVolatile); 430 } 431} 432 433/***/ 434 435bool CodeGenModule::ReturnTypeUsesSret(const CGFunctionInfo &FI) { 436 return FI.getReturnInfo().isIndirect(); 437} 438 439const llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) { 440 const CGFunctionInfo &FI = getFunctionInfo(GD); 441 442 // For definition purposes, don't consider a K&R function variadic. 443 bool Variadic = false; 444 if (const FunctionProtoType *FPT = 445 cast<FunctionDecl>(GD.getDecl())->getType()->getAs<FunctionProtoType>()) 446 Variadic = FPT->isVariadic(); 447 448 return GetFunctionType(FI, Variadic); 449} 450 451const llvm::FunctionType * 452CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool IsVariadic) { 453 std::vector<const llvm::Type*> ArgTys; 454 455 const llvm::Type *ResultType = 0; 456 457 QualType RetTy = FI.getReturnType(); 458 const ABIArgInfo &RetAI = FI.getReturnInfo(); 459 switch (RetAI.getKind()) { 460 case ABIArgInfo::Expand: 461 assert(0 && "Invalid ABI kind for return argument"); 462 463 case ABIArgInfo::Extend: 464 case ABIArgInfo::Direct: 465 ResultType = ConvertType(RetTy); 466 break; 467 468 case ABIArgInfo::Indirect: { 469 assert(!RetAI.getIndirectAlign() && "Align unused on indirect return."); 470 ResultType = llvm::Type::getVoidTy(getLLVMContext()); 471 const llvm::Type *STy = ConvertType(RetTy); 472 ArgTys.push_back(llvm::PointerType::get(STy, RetTy.getAddressSpace())); 473 break; 474 } 475 476 case ABIArgInfo::Ignore: 477 ResultType = llvm::Type::getVoidTy(getLLVMContext()); 478 break; 479 480 case ABIArgInfo::Coerce: 481 ResultType = RetAI.getCoerceToType(); 482 break; 483 } 484 485 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), 486 ie = FI.arg_end(); it != ie; ++it) { 487 const ABIArgInfo &AI = it->info; 488 489 switch (AI.getKind()) { 490 case ABIArgInfo::Ignore: 491 break; 492 493 case ABIArgInfo::Coerce: 494 ArgTys.push_back(AI.getCoerceToType()); 495 break; 496 497 case ABIArgInfo::Indirect: { 498 // indirect arguments are always on the stack, which is addr space #0. 499 const llvm::Type *LTy = ConvertTypeForMem(it->type); 500 ArgTys.push_back(llvm::PointerType::getUnqual(LTy)); 501 break; 502 } 503 504 case ABIArgInfo::Extend: 505 case ABIArgInfo::Direct: 506 ArgTys.push_back(ConvertType(it->type)); 507 break; 508 509 case ABIArgInfo::Expand: 510 GetExpandedTypes(it->type, ArgTys); 511 break; 512 } 513 } 514 515 return llvm::FunctionType::get(ResultType, ArgTys, IsVariadic); 516} 517 518static bool HasIncompleteReturnTypeOrArgumentTypes(const FunctionProtoType *T) { 519 if (const TagType *TT = T->getResultType()->getAs<TagType>()) { 520 if (!TT->getDecl()->isDefinition()) 521 return true; 522 } 523 524 for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) { 525 if (const TagType *TT = T->getArgType(i)->getAs<TagType>()) { 526 if (!TT->getDecl()->isDefinition()) 527 return true; 528 } 529 } 530 531 return false; 532} 533 534const llvm::Type * 535CodeGenTypes::GetFunctionTypeForVTable(const CXXMethodDecl *MD) { 536 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 537 538 if (!HasIncompleteReturnTypeOrArgumentTypes(FPT)) 539 return GetFunctionType(getFunctionInfo(MD), FPT->isVariadic()); 540 541 return llvm::OpaqueType::get(getLLVMContext()); 542} 543 544void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI, 545 const Decl *TargetDecl, 546 AttributeListType &PAL, 547 unsigned &CallingConv) { 548 unsigned FuncAttrs = 0; 549 unsigned RetAttrs = 0; 550 551 CallingConv = FI.getEffectiveCallingConvention(); 552 553 if (FI.isNoReturn()) 554 FuncAttrs |= llvm::Attribute::NoReturn; 555 556 // FIXME: handle sseregparm someday... 557 if (TargetDecl) { 558 if (TargetDecl->hasAttr<NoThrowAttr>()) 559 FuncAttrs |= llvm::Attribute::NoUnwind; 560 if (TargetDecl->hasAttr<NoReturnAttr>()) 561 FuncAttrs |= llvm::Attribute::NoReturn; 562 if (TargetDecl->hasAttr<ConstAttr>()) 563 FuncAttrs |= llvm::Attribute::ReadNone; 564 else if (TargetDecl->hasAttr<PureAttr>()) 565 FuncAttrs |= llvm::Attribute::ReadOnly; 566 if (TargetDecl->hasAttr<MallocAttr>()) 567 RetAttrs |= llvm::Attribute::NoAlias; 568 } 569 570 if (CodeGenOpts.OptimizeSize) 571 FuncAttrs |= llvm::Attribute::OptimizeForSize; 572 if (CodeGenOpts.DisableRedZone) 573 FuncAttrs |= llvm::Attribute::NoRedZone; 574 if (CodeGenOpts.NoImplicitFloat) 575 FuncAttrs |= llvm::Attribute::NoImplicitFloat; 576 577 QualType RetTy = FI.getReturnType(); 578 unsigned Index = 1; 579 const ABIArgInfo &RetAI = FI.getReturnInfo(); 580 switch (RetAI.getKind()) { 581 case ABIArgInfo::Extend: 582 if (RetTy->isSignedIntegerType()) { 583 RetAttrs |= llvm::Attribute::SExt; 584 } else if (RetTy->isUnsignedIntegerType()) { 585 RetAttrs |= llvm::Attribute::ZExt; 586 } 587 // FALLTHROUGH 588 case ABIArgInfo::Direct: 589 break; 590 591 case ABIArgInfo::Indirect: 592 PAL.push_back(llvm::AttributeWithIndex::get(Index, 593 llvm::Attribute::StructRet)); 594 ++Index; 595 // sret disables readnone and readonly 596 FuncAttrs &= ~(llvm::Attribute::ReadOnly | 597 llvm::Attribute::ReadNone); 598 break; 599 600 case ABIArgInfo::Ignore: 601 case ABIArgInfo::Coerce: 602 break; 603 604 case ABIArgInfo::Expand: 605 assert(0 && "Invalid ABI kind for return argument"); 606 } 607 608 if (RetAttrs) 609 PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs)); 610 611 // FIXME: we need to honour command line settings also... 612 // FIXME: RegParm should be reduced in case of nested functions and/or global 613 // register variable. 614 signed RegParm = FI.getRegParm(); 615 616 unsigned PointerWidth = getContext().Target.getPointerWidth(0); 617 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), 618 ie = FI.arg_end(); it != ie; ++it) { 619 QualType ParamType = it->type; 620 const ABIArgInfo &AI = it->info; 621 unsigned Attributes = 0; 622 623 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we 624 // have the corresponding parameter variable. It doesn't make 625 // sense to do it here because parameters are so fucked up. 626 627 switch (AI.getKind()) { 628 case ABIArgInfo::Coerce: 629 break; 630 631 case ABIArgInfo::Indirect: 632 if (AI.getIndirectByVal()) 633 Attributes |= llvm::Attribute::ByVal; 634 635 Attributes |= 636 llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign()); 637 // byval disables readnone and readonly. 638 FuncAttrs &= ~(llvm::Attribute::ReadOnly | 639 llvm::Attribute::ReadNone); 640 break; 641 642 case ABIArgInfo::Extend: 643 if (ParamType->isSignedIntegerType()) { 644 Attributes |= llvm::Attribute::SExt; 645 } else if (ParamType->isUnsignedIntegerType()) { 646 Attributes |= llvm::Attribute::ZExt; 647 } 648 // FALLS THROUGH 649 case ABIArgInfo::Direct: 650 if (RegParm > 0 && 651 (ParamType->isIntegerType() || ParamType->isPointerType())) { 652 RegParm -= 653 (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth; 654 if (RegParm >= 0) 655 Attributes |= llvm::Attribute::InReg; 656 } 657 // FIXME: handle sseregparm someday... 658 break; 659 660 case ABIArgInfo::Ignore: 661 // Skip increment, no matching LLVM parameter. 662 continue; 663 664 case ABIArgInfo::Expand: { 665 std::vector<const llvm::Type*> Tys; 666 // FIXME: This is rather inefficient. Do we ever actually need to do 667 // anything here? The result should be just reconstructed on the other 668 // side, so extension should be a non-issue. 669 getTypes().GetExpandedTypes(ParamType, Tys); 670 Index += Tys.size(); 671 continue; 672 } 673 } 674 675 if (Attributes) 676 PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes)); 677 ++Index; 678 } 679 if (FuncAttrs) 680 PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs)); 681} 682 683void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, 684 llvm::Function *Fn, 685 const FunctionArgList &Args) { 686 // If this is an implicit-return-zero function, go ahead and 687 // initialize the return value. TODO: it might be nice to have 688 // a more general mechanism for this that didn't require synthesized 689 // return statements. 690 if (const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) { 691 if (FD->hasImplicitReturnZero()) { 692 QualType RetTy = FD->getResultType().getUnqualifiedType(); 693 const llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy); 694 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy); 695 Builder.CreateStore(Zero, ReturnValue); 696 } 697 } 698 699 // FIXME: We no longer need the types from FunctionArgList; lift up and 700 // simplify. 701 702 // Emit allocs for param decls. Give the LLVM Argument nodes names. 703 llvm::Function::arg_iterator AI = Fn->arg_begin(); 704 705 // Name the struct return argument. 706 if (CGM.ReturnTypeUsesSret(FI)) { 707 AI->setName("agg.result"); 708 ++AI; 709 } 710 711 assert(FI.arg_size() == Args.size() && 712 "Mismatch between function signature & arguments."); 713 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin(); 714 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 715 i != e; ++i, ++info_it) { 716 const VarDecl *Arg = i->first; 717 QualType Ty = info_it->type; 718 const ABIArgInfo &ArgI = info_it->info; 719 720 switch (ArgI.getKind()) { 721 case ABIArgInfo::Indirect: { 722 llvm::Value* V = AI; 723 if (hasAggregateLLVMType(Ty)) { 724 // Do nothing, aggregates and complex variables are accessed by 725 // reference. 726 } else { 727 // Load scalar value from indirect argument. 728 V = EmitLoadOfScalar(V, false, Ty); 729 if (!getContext().typesAreCompatible(Ty, Arg->getType())) { 730 // This must be a promotion, for something like 731 // "void a(x) short x; {..." 732 V = EmitScalarConversion(V, Ty, Arg->getType()); 733 } 734 } 735 EmitParmDecl(*Arg, V); 736 break; 737 } 738 739 case ABIArgInfo::Extend: 740 case ABIArgInfo::Direct: { 741 assert(AI != Fn->arg_end() && "Argument mismatch!"); 742 llvm::Value* V = AI; 743 if (hasAggregateLLVMType(Ty)) { 744 // Create a temporary alloca to hold the argument; the rest of 745 // codegen expects to access aggregates & complex values by 746 // reference. 747 V = CreateMemTemp(Ty); 748 Builder.CreateStore(AI, V); 749 } else { 750 if (Arg->getType().isRestrictQualified()) 751 AI->addAttr(llvm::Attribute::NoAlias); 752 753 if (!getContext().typesAreCompatible(Ty, Arg->getType())) { 754 // This must be a promotion, for something like 755 // "void a(x) short x; {..." 756 V = EmitScalarConversion(V, Ty, Arg->getType()); 757 } 758 } 759 EmitParmDecl(*Arg, V); 760 break; 761 } 762 763 case ABIArgInfo::Expand: { 764 // If this structure was expanded into multiple arguments then 765 // we need to create a temporary and reconstruct it from the 766 // arguments. 767 llvm::Value *Temp = CreateMemTemp(Ty, Arg->getName() + ".addr"); 768 // FIXME: What are the right qualifiers here? 769 llvm::Function::arg_iterator End = 770 ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp, Qualifiers()), AI); 771 EmitParmDecl(*Arg, Temp); 772 773 // Name the arguments used in expansion and increment AI. 774 unsigned Index = 0; 775 for (; AI != End; ++AI, ++Index) 776 AI->setName(Arg->getName() + "." + llvm::Twine(Index)); 777 continue; 778 } 779 780 case ABIArgInfo::Ignore: 781 // Initialize the local variable appropriately. 782 if (hasAggregateLLVMType(Ty)) { 783 EmitParmDecl(*Arg, CreateMemTemp(Ty)); 784 } else { 785 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType()))); 786 } 787 788 // Skip increment, no matching LLVM parameter. 789 continue; 790 791 case ABIArgInfo::Coerce: { 792 assert(AI != Fn->arg_end() && "Argument mismatch!"); 793 // FIXME: This is very wasteful; EmitParmDecl is just going to drop the 794 // result in a new alloca anyway, so we could just store into that 795 // directly if we broke the abstraction down more. 796 llvm::Value *V = CreateMemTemp(Ty, "coerce"); 797 CreateCoercedStore(AI, V, /*DestIsVolatile=*/false, *this); 798 // Match to what EmitParmDecl is expecting for this type. 799 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) { 800 V = EmitLoadOfScalar(V, false, Ty); 801 if (!getContext().typesAreCompatible(Ty, Arg->getType())) { 802 // This must be a promotion, for something like 803 // "void a(x) short x; {..." 804 V = EmitScalarConversion(V, Ty, Arg->getType()); 805 } 806 } 807 EmitParmDecl(*Arg, V); 808 break; 809 } 810 } 811 812 ++AI; 813 } 814 assert(AI == Fn->arg_end() && "Argument mismatch!"); 815} 816 817void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI, 818 llvm::Value *ReturnValue) { 819 llvm::Value *RV = 0; 820 821 // Functions with no result always return void. 822 if (ReturnValue) { 823 QualType RetTy = FI.getReturnType(); 824 const ABIArgInfo &RetAI = FI.getReturnInfo(); 825 826 switch (RetAI.getKind()) { 827 case ABIArgInfo::Indirect: 828 if (RetTy->isAnyComplexType()) { 829 ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false); 830 StoreComplexToAddr(RT, CurFn->arg_begin(), false); 831 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) { 832 // Do nothing; aggregrates get evaluated directly into the destination. 833 } else { 834 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(), 835 false, RetTy); 836 } 837 break; 838 839 case ABIArgInfo::Extend: 840 case ABIArgInfo::Direct: 841 // The internal return value temp always will have 842 // pointer-to-return-type type. 843 RV = Builder.CreateLoad(ReturnValue); 844 break; 845 846 case ABIArgInfo::Ignore: 847 break; 848 849 case ABIArgInfo::Coerce: 850 RV = CreateCoercedLoad(ReturnValue, RetAI.getCoerceToType(), *this); 851 break; 852 853 case ABIArgInfo::Expand: 854 assert(0 && "Invalid ABI kind for return argument"); 855 } 856 } 857 858 if (RV) { 859 Builder.CreateRet(RV); 860 } else { 861 Builder.CreateRetVoid(); 862 } 863} 864 865RValue CodeGenFunction::EmitDelegateCallArg(const VarDecl *Param) { 866 // StartFunction converted the ABI-lowered parameter(s) into a 867 // local alloca. We need to turn that into an r-value suitable 868 // for EmitCall. 869 llvm::Value *Local = GetAddrOfLocalVar(Param); 870 871 QualType ArgType = Param->getType(); 872 873 // For the most part, we just need to load the alloca, except: 874 // 1) aggregate r-values are actually pointers to temporaries, and 875 // 2) references to aggregates are pointers directly to the aggregate. 876 // I don't know why references to non-aggregates are different here. 877 if (const ReferenceType *RefType = ArgType->getAs<ReferenceType>()) { 878 if (hasAggregateLLVMType(RefType->getPointeeType())) 879 return RValue::getAggregate(Local); 880 881 // Locals which are references to scalars are represented 882 // with allocas holding the pointer. 883 return RValue::get(Builder.CreateLoad(Local)); 884 } 885 886 if (ArgType->isAnyComplexType()) 887 return RValue::getComplex(LoadComplexFromAddr(Local, /*volatile*/ false)); 888 889 if (hasAggregateLLVMType(ArgType)) 890 return RValue::getAggregate(Local); 891 892 return RValue::get(EmitLoadOfScalar(Local, false, ArgType)); 893} 894 895RValue CodeGenFunction::EmitCallArg(const Expr *E, QualType ArgType) { 896 if (ArgType->isReferenceType()) 897 return EmitReferenceBindingToExpr(E); 898 899 return EmitAnyExprToTemp(E); 900} 901 902RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, 903 llvm::Value *Callee, 904 ReturnValueSlot ReturnValue, 905 const CallArgList &CallArgs, 906 const Decl *TargetDecl, 907 llvm::Instruction **callOrInvoke) { 908 // FIXME: We no longer need the types from CallArgs; lift up and simplify. 909 llvm::SmallVector<llvm::Value*, 16> Args; 910 911 // Handle struct-return functions by passing a pointer to the 912 // location that we would like to return into. 913 QualType RetTy = CallInfo.getReturnType(); 914 const ABIArgInfo &RetAI = CallInfo.getReturnInfo(); 915 916 917 // If the call returns a temporary with struct return, create a temporary 918 // alloca to hold the result, unless one is given to us. 919 if (CGM.ReturnTypeUsesSret(CallInfo)) { 920 llvm::Value *Value = ReturnValue.getValue(); 921 if (!Value) 922 Value = CreateMemTemp(RetTy); 923 Args.push_back(Value); 924 } 925 926 assert(CallInfo.arg_size() == CallArgs.size() && 927 "Mismatch between function signature & arguments."); 928 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin(); 929 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); 930 I != E; ++I, ++info_it) { 931 const ABIArgInfo &ArgInfo = info_it->info; 932 RValue RV = I->first; 933 934 switch (ArgInfo.getKind()) { 935 case ABIArgInfo::Indirect: 936 if (RV.isScalar() || RV.isComplex()) { 937 // Make a temporary alloca to pass the argument. 938 Args.push_back(CreateMemTemp(I->second)); 939 if (RV.isScalar()) 940 EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false, I->second); 941 else 942 StoreComplexToAddr(RV.getComplexVal(), Args.back(), false); 943 } else { 944 Args.push_back(RV.getAggregateAddr()); 945 } 946 break; 947 948 case ABIArgInfo::Extend: 949 case ABIArgInfo::Direct: 950 if (RV.isScalar()) { 951 Args.push_back(RV.getScalarVal()); 952 } else if (RV.isComplex()) { 953 llvm::Value *Tmp = llvm::UndefValue::get(ConvertType(I->second)); 954 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().first, 0); 955 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().second, 1); 956 Args.push_back(Tmp); 957 } else { 958 Args.push_back(Builder.CreateLoad(RV.getAggregateAddr())); 959 } 960 break; 961 962 case ABIArgInfo::Ignore: 963 break; 964 965 case ABIArgInfo::Coerce: { 966 // FIXME: Avoid the conversion through memory if possible. 967 llvm::Value *SrcPtr; 968 if (RV.isScalar()) { 969 SrcPtr = CreateMemTemp(I->second, "coerce"); 970 EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, I->second); 971 } else if (RV.isComplex()) { 972 SrcPtr = CreateMemTemp(I->second, "coerce"); 973 StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false); 974 } else 975 SrcPtr = RV.getAggregateAddr(); 976 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), 977 *this)); 978 break; 979 } 980 981 case ABIArgInfo::Expand: 982 ExpandTypeToArgs(I->second, RV, Args); 983 break; 984 } 985 } 986 987 // If the callee is a bitcast of a function to a varargs pointer to function 988 // type, check to see if we can remove the bitcast. This handles some cases 989 // with unprototyped functions. 990 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee)) 991 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) { 992 const llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType()); 993 const llvm::FunctionType *CurFT = 994 cast<llvm::FunctionType>(CurPT->getElementType()); 995 const llvm::FunctionType *ActualFT = CalleeF->getFunctionType(); 996 997 if (CE->getOpcode() == llvm::Instruction::BitCast && 998 ActualFT->getReturnType() == CurFT->getReturnType() && 999 ActualFT->getNumParams() == CurFT->getNumParams() && 1000 ActualFT->getNumParams() == Args.size()) { 1001 bool ArgsMatch = true; 1002 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i) 1003 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) { 1004 ArgsMatch = false; 1005 break; 1006 } 1007 1008 // Strip the cast if we can get away with it. This is a nice cleanup, 1009 // but also allows us to inline the function at -O0 if it is marked 1010 // always_inline. 1011 if (ArgsMatch) 1012 Callee = CalleeF; 1013 } 1014 } 1015 1016 1017 llvm::BasicBlock *InvokeDest = getInvokeDest(); 1018 unsigned CallingConv; 1019 CodeGen::AttributeListType AttributeList; 1020 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList, CallingConv); 1021 llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(), 1022 AttributeList.end()); 1023 1024 llvm::CallSite CS; 1025 if (!InvokeDest || (Attrs.getFnAttributes() & llvm::Attribute::NoUnwind)) { 1026 CS = Builder.CreateCall(Callee, Args.data(), Args.data()+Args.size()); 1027 } else { 1028 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont"); 1029 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, 1030 Args.data(), Args.data()+Args.size()); 1031 EmitBlock(Cont); 1032 } 1033 if (callOrInvoke) { 1034 *callOrInvoke = CS.getInstruction(); 1035 } 1036 1037 CS.setAttributes(Attrs); 1038 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 1039 1040 // If the call doesn't return, finish the basic block and clear the 1041 // insertion point; this allows the rest of IRgen to discard 1042 // unreachable code. 1043 if (CS.doesNotReturn()) { 1044 Builder.CreateUnreachable(); 1045 Builder.ClearInsertionPoint(); 1046 1047 // FIXME: For now, emit a dummy basic block because expr emitters in 1048 // generally are not ready to handle emitting expressions at unreachable 1049 // points. 1050 EnsureInsertPoint(); 1051 1052 // Return a reasonable RValue. 1053 return GetUndefRValue(RetTy); 1054 } 1055 1056 llvm::Instruction *CI = CS.getInstruction(); 1057 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy()) 1058 CI->setName("call"); 1059 1060 switch (RetAI.getKind()) { 1061 case ABIArgInfo::Indirect: 1062 if (RetTy->isAnyComplexType()) 1063 return RValue::getComplex(LoadComplexFromAddr(Args[0], false)); 1064 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) 1065 return RValue::getAggregate(Args[0]); 1066 return RValue::get(EmitLoadOfScalar(Args[0], false, RetTy)); 1067 1068 case ABIArgInfo::Extend: 1069 case ABIArgInfo::Direct: 1070 if (RetTy->isAnyComplexType()) { 1071 llvm::Value *Real = Builder.CreateExtractValue(CI, 0); 1072 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1); 1073 return RValue::getComplex(std::make_pair(Real, Imag)); 1074 } 1075 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) { 1076 llvm::Value *DestPtr = ReturnValue.getValue(); 1077 bool DestIsVolatile = ReturnValue.isVolatile(); 1078 1079 if (!DestPtr) { 1080 DestPtr = CreateMemTemp(RetTy, "agg.tmp"); 1081 DestIsVolatile = false; 1082 } 1083 Builder.CreateStore(CI, DestPtr, DestIsVolatile); 1084 return RValue::getAggregate(DestPtr); 1085 } 1086 return RValue::get(CI); 1087 1088 case ABIArgInfo::Ignore: 1089 // If we are ignoring an argument that had a result, make sure to 1090 // construct the appropriate return value for our caller. 1091 return GetUndefRValue(RetTy); 1092 1093 case ABIArgInfo::Coerce: { 1094 llvm::Value *DestPtr = ReturnValue.getValue(); 1095 bool DestIsVolatile = ReturnValue.isVolatile(); 1096 1097 if (!DestPtr) { 1098 DestPtr = CreateMemTemp(RetTy, "coerce"); 1099 DestIsVolatile = false; 1100 } 1101 1102 CreateCoercedStore(CI, DestPtr, DestIsVolatile, *this); 1103 if (RetTy->isAnyComplexType()) 1104 return RValue::getComplex(LoadComplexFromAddr(DestPtr, false)); 1105 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) 1106 return RValue::getAggregate(DestPtr); 1107 return RValue::get(EmitLoadOfScalar(DestPtr, false, RetTy)); 1108 } 1109 1110 case ABIArgInfo::Expand: 1111 assert(0 && "Invalid ABI kind for return argument"); 1112 } 1113 1114 assert(0 && "Unhandled ABIArgInfo::Kind"); 1115 return RValue::get(0); 1116} 1117 1118/* VarArg handling */ 1119 1120llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) { 1121 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this); 1122} 1123