TargetInfo.cpp revision b914e87377fd4d7642f544000a79f8648c6f06c9
1//===---- TargetInfo.cpp - Encapsulate target 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 "TargetInfo.h" 16#include "ABIInfo.h" 17#include "CGCXXABI.h" 18#include "CodeGenFunction.h" 19#include "clang/AST/RecordLayout.h" 20#include "clang/Frontend/CodeGenOptions.h" 21#include "llvm/ADT/Triple.h" 22#include "llvm/IR/DataLayout.h" 23#include "llvm/IR/Type.h" 24#include "llvm/Support/raw_ostream.h" 25using namespace clang; 26using namespace CodeGen; 27 28static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 29 llvm::Value *Array, 30 llvm::Value *Value, 31 unsigned FirstIndex, 32 unsigned LastIndex) { 33 // Alternatively, we could emit this as a loop in the source. 34 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 35 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I); 36 Builder.CreateStore(Value, Cell); 37 } 38} 39 40static bool isAggregateTypeForABI(QualType T) { 41 return !CodeGenFunction::hasScalarEvaluationKind(T) || 42 T->isMemberFunctionPointerType(); 43} 44 45ABIInfo::~ABIInfo() {} 46 47static bool isRecordReturnIndirect(const RecordType *RT, 48 CGCXXABI &CXXABI) { 49 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 50 if (!RD) 51 return false; 52 return CXXABI.isReturnTypeIndirect(RD); 53} 54 55 56static bool isRecordReturnIndirect(QualType T, CGCXXABI &CXXABI) { 57 const RecordType *RT = T->getAs<RecordType>(); 58 if (!RT) 59 return false; 60 return isRecordReturnIndirect(RT, CXXABI); 61} 62 63static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 64 CGCXXABI &CXXABI) { 65 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 66 if (!RD) 67 return CGCXXABI::RAA_Default; 68 return CXXABI.getRecordArgABI(RD); 69} 70 71static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 72 CGCXXABI &CXXABI) { 73 const RecordType *RT = T->getAs<RecordType>(); 74 if (!RT) 75 return CGCXXABI::RAA_Default; 76 return getRecordArgABI(RT, CXXABI); 77} 78 79CGCXXABI &ABIInfo::getCXXABI() const { 80 return CGT.getCXXABI(); 81} 82 83ASTContext &ABIInfo::getContext() const { 84 return CGT.getContext(); 85} 86 87llvm::LLVMContext &ABIInfo::getVMContext() const { 88 return CGT.getLLVMContext(); 89} 90 91const llvm::DataLayout &ABIInfo::getDataLayout() const { 92 return CGT.getDataLayout(); 93} 94 95const TargetInfo &ABIInfo::getTarget() const { 96 return CGT.getTarget(); 97} 98 99void ABIArgInfo::dump() const { 100 raw_ostream &OS = llvm::errs(); 101 OS << "(ABIArgInfo Kind="; 102 switch (TheKind) { 103 case Direct: 104 OS << "Direct Type="; 105 if (llvm::Type *Ty = getCoerceToType()) 106 Ty->print(OS); 107 else 108 OS << "null"; 109 break; 110 case Extend: 111 OS << "Extend"; 112 break; 113 case Ignore: 114 OS << "Ignore"; 115 break; 116 case Indirect: 117 OS << "Indirect Align=" << getIndirectAlign() 118 << " ByVal=" << getIndirectByVal() 119 << " Realign=" << getIndirectRealign(); 120 break; 121 case Expand: 122 OS << "Expand"; 123 break; 124 } 125 OS << ")\n"; 126} 127 128TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; } 129 130// If someone can figure out a general rule for this, that would be great. 131// It's probably just doomed to be platform-dependent, though. 132unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 133 // Verified for: 134 // x86-64 FreeBSD, Linux, Darwin 135 // x86-32 FreeBSD, Linux, Darwin 136 // PowerPC Linux, Darwin 137 // ARM Darwin (*not* EABI) 138 // AArch64 Linux 139 return 32; 140} 141 142bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 143 const FunctionNoProtoType *fnType) const { 144 // The following conventions are known to require this to be false: 145 // x86_stdcall 146 // MIPS 147 // For everything else, we just prefer false unless we opt out. 148 return false; 149} 150 151void 152TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 153 llvm::SmallString<24> &Opt) const { 154 // This assumes the user is passing a library name like "rt" instead of a 155 // filename like "librt.a/so", and that they don't care whether it's static or 156 // dynamic. 157 Opt = "-l"; 158 Opt += Lib; 159} 160 161static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 162 163/// isEmptyField - Return true iff a the field is "empty", that is it 164/// is an unnamed bit-field or an (array of) empty record(s). 165static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 166 bool AllowArrays) { 167 if (FD->isUnnamedBitfield()) 168 return true; 169 170 QualType FT = FD->getType(); 171 172 // Constant arrays of empty records count as empty, strip them off. 173 // Constant arrays of zero length always count as empty. 174 if (AllowArrays) 175 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 176 if (AT->getSize() == 0) 177 return true; 178 FT = AT->getElementType(); 179 } 180 181 const RecordType *RT = FT->getAs<RecordType>(); 182 if (!RT) 183 return false; 184 185 // C++ record fields are never empty, at least in the Itanium ABI. 186 // 187 // FIXME: We should use a predicate for whether this behavior is true in the 188 // current ABI. 189 if (isa<CXXRecordDecl>(RT->getDecl())) 190 return false; 191 192 return isEmptyRecord(Context, FT, AllowArrays); 193} 194 195/// isEmptyRecord - Return true iff a structure contains only empty 196/// fields. Note that a structure with a flexible array member is not 197/// considered empty. 198static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 199 const RecordType *RT = T->getAs<RecordType>(); 200 if (!RT) 201 return 0; 202 const RecordDecl *RD = RT->getDecl(); 203 if (RD->hasFlexibleArrayMember()) 204 return false; 205 206 // If this is a C++ record, check the bases first. 207 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 208 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 209 e = CXXRD->bases_end(); i != e; ++i) 210 if (!isEmptyRecord(Context, i->getType(), true)) 211 return false; 212 213 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 214 i != e; ++i) 215 if (!isEmptyField(Context, *i, AllowArrays)) 216 return false; 217 return true; 218} 219 220/// isSingleElementStruct - Determine if a structure is a "single 221/// element struct", i.e. it has exactly one non-empty field or 222/// exactly one field which is itself a single element 223/// struct. Structures with flexible array members are never 224/// considered single element structs. 225/// 226/// \return The field declaration for the single non-empty field, if 227/// it exists. 228static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 229 const RecordType *RT = T->getAsStructureType(); 230 if (!RT) 231 return 0; 232 233 const RecordDecl *RD = RT->getDecl(); 234 if (RD->hasFlexibleArrayMember()) 235 return 0; 236 237 const Type *Found = 0; 238 239 // If this is a C++ record, check the bases first. 240 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 241 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 242 e = CXXRD->bases_end(); i != e; ++i) { 243 // Ignore empty records. 244 if (isEmptyRecord(Context, i->getType(), true)) 245 continue; 246 247 // If we already found an element then this isn't a single-element struct. 248 if (Found) 249 return 0; 250 251 // If this is non-empty and not a single element struct, the composite 252 // cannot be a single element struct. 253 Found = isSingleElementStruct(i->getType(), Context); 254 if (!Found) 255 return 0; 256 } 257 } 258 259 // Check for single element. 260 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 261 i != e; ++i) { 262 const FieldDecl *FD = *i; 263 QualType FT = FD->getType(); 264 265 // Ignore empty fields. 266 if (isEmptyField(Context, FD, true)) 267 continue; 268 269 // If we already found an element then this isn't a single-element 270 // struct. 271 if (Found) 272 return 0; 273 274 // Treat single element arrays as the element. 275 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 276 if (AT->getSize().getZExtValue() != 1) 277 break; 278 FT = AT->getElementType(); 279 } 280 281 if (!isAggregateTypeForABI(FT)) { 282 Found = FT.getTypePtr(); 283 } else { 284 Found = isSingleElementStruct(FT, Context); 285 if (!Found) 286 return 0; 287 } 288 } 289 290 // We don't consider a struct a single-element struct if it has 291 // padding beyond the element type. 292 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 293 return 0; 294 295 return Found; 296} 297 298static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 299 // Treat complex types as the element type. 300 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 301 Ty = CTy->getElementType(); 302 303 // Check for a type which we know has a simple scalar argument-passing 304 // convention without any padding. (We're specifically looking for 32 305 // and 64-bit integer and integer-equivalents, float, and double.) 306 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 307 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 308 return false; 309 310 uint64_t Size = Context.getTypeSize(Ty); 311 return Size == 32 || Size == 64; 312} 313 314/// canExpandIndirectArgument - Test whether an argument type which is to be 315/// passed indirectly (on the stack) would have the equivalent layout if it was 316/// expanded into separate arguments. If so, we prefer to do the latter to avoid 317/// inhibiting optimizations. 318/// 319// FIXME: This predicate is missing many cases, currently it just follows 320// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We 321// should probably make this smarter, or better yet make the LLVM backend 322// capable of handling it. 323static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) { 324 // We can only expand structure types. 325 const RecordType *RT = Ty->getAs<RecordType>(); 326 if (!RT) 327 return false; 328 329 // We can only expand (C) structures. 330 // 331 // FIXME: This needs to be generalized to handle classes as well. 332 const RecordDecl *RD = RT->getDecl(); 333 if (!RD->isStruct() || isa<CXXRecordDecl>(RD)) 334 return false; 335 336 uint64_t Size = 0; 337 338 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 339 i != e; ++i) { 340 const FieldDecl *FD = *i; 341 342 if (!is32Or64BitBasicType(FD->getType(), Context)) 343 return false; 344 345 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 346 // how to expand them yet, and the predicate for telling if a bitfield still 347 // counts as "basic" is more complicated than what we were doing previously. 348 if (FD->isBitField()) 349 return false; 350 351 Size += Context.getTypeSize(FD->getType()); 352 } 353 354 // Make sure there are not any holes in the struct. 355 if (Size != Context.getTypeSize(Ty)) 356 return false; 357 358 return true; 359} 360 361namespace { 362/// DefaultABIInfo - The default implementation for ABI specific 363/// details. This implementation provides information which results in 364/// self-consistent and sensible LLVM IR generation, but does not 365/// conform to any particular ABI. 366class DefaultABIInfo : public ABIInfo { 367public: 368 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 369 370 ABIArgInfo classifyReturnType(QualType RetTy) const; 371 ABIArgInfo classifyArgumentType(QualType RetTy) const; 372 373 virtual void computeInfo(CGFunctionInfo &FI) const { 374 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 375 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 376 it != ie; ++it) 377 it->info = classifyArgumentType(it->type); 378 } 379 380 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 381 CodeGenFunction &CGF) const; 382}; 383 384class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 385public: 386 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 387 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 388}; 389 390llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 391 CodeGenFunction &CGF) const { 392 return 0; 393} 394 395ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 396 if (isAggregateTypeForABI(Ty)) { 397 // Records with non trivial destructors/constructors should not be passed 398 // by value. 399 if (isRecordReturnIndirect(Ty, getCXXABI())) 400 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 401 402 return ABIArgInfo::getIndirect(0); 403 } 404 405 // Treat an enum type as its underlying type. 406 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 407 Ty = EnumTy->getDecl()->getIntegerType(); 408 409 return (Ty->isPromotableIntegerType() ? 410 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 411} 412 413ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 414 if (RetTy->isVoidType()) 415 return ABIArgInfo::getIgnore(); 416 417 if (isAggregateTypeForABI(RetTy)) 418 return ABIArgInfo::getIndirect(0); 419 420 // Treat an enum type as its underlying type. 421 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 422 RetTy = EnumTy->getDecl()->getIntegerType(); 423 424 return (RetTy->isPromotableIntegerType() ? 425 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 426} 427 428//===----------------------------------------------------------------------===// 429// le32/PNaCl bitcode ABI Implementation 430// 431// This is a simplified version of the x86_32 ABI. Arguments and return values 432// are always passed on the stack. 433//===----------------------------------------------------------------------===// 434 435class PNaClABIInfo : public ABIInfo { 436 public: 437 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 438 439 ABIArgInfo classifyReturnType(QualType RetTy) const; 440 ABIArgInfo classifyArgumentType(QualType RetTy) const; 441 442 virtual void computeInfo(CGFunctionInfo &FI) const; 443 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 444 CodeGenFunction &CGF) const; 445}; 446 447class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 448 public: 449 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 450 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {} 451}; 452 453void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 454 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 455 456 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 457 it != ie; ++it) 458 it->info = classifyArgumentType(it->type); 459 } 460 461llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 462 CodeGenFunction &CGF) const { 463 return 0; 464} 465 466/// \brief Classify argument of given type \p Ty. 467ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 468 if (isAggregateTypeForABI(Ty)) { 469 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 470 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 471 return ABIArgInfo::getIndirect(0); 472 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 473 // Treat an enum type as its underlying type. 474 Ty = EnumTy->getDecl()->getIntegerType(); 475 } else if (Ty->isFloatingType()) { 476 // Floating-point types don't go inreg. 477 return ABIArgInfo::getDirect(); 478 } 479 480 return (Ty->isPromotableIntegerType() ? 481 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 482} 483 484ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 485 if (RetTy->isVoidType()) 486 return ABIArgInfo::getIgnore(); 487 488 // In the PNaCl ABI we always return records/structures on the stack. 489 if (isAggregateTypeForABI(RetTy)) 490 return ABIArgInfo::getIndirect(0); 491 492 // Treat an enum type as its underlying type. 493 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 494 RetTy = EnumTy->getDecl()->getIntegerType(); 495 496 return (RetTy->isPromotableIntegerType() ? 497 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 498} 499 500/// IsX86_MMXType - Return true if this is an MMX type. 501bool IsX86_MMXType(llvm::Type *IRType) { 502 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 503 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 504 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 505 IRType->getScalarSizeInBits() != 64; 506} 507 508static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 509 StringRef Constraint, 510 llvm::Type* Ty) { 511 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) { 512 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) { 513 // Invalid MMX constraint 514 return 0; 515 } 516 517 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 518 } 519 520 // No operation needed 521 return Ty; 522} 523 524//===----------------------------------------------------------------------===// 525// X86-32 ABI Implementation 526//===----------------------------------------------------------------------===// 527 528/// X86_32ABIInfo - The X86-32 ABI information. 529class X86_32ABIInfo : public ABIInfo { 530 enum Class { 531 Integer, 532 Float 533 }; 534 535 static const unsigned MinABIStackAlignInBytes = 4; 536 537 bool IsDarwinVectorABI; 538 bool IsSmallStructInRegABI; 539 bool IsWin32StructABI; 540 unsigned DefaultNumRegisterParameters; 541 542 static bool isRegisterSize(unsigned Size) { 543 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 544 } 545 546 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context, 547 unsigned callingConvention); 548 549 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 550 /// such that the argument will be passed in memory. 551 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, 552 unsigned &FreeRegs) const; 553 554 /// \brief Return the alignment to use for the given type on the stack. 555 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 556 557 Class classify(QualType Ty) const; 558 ABIArgInfo classifyReturnType(QualType RetTy, 559 unsigned callingConvention) const; 560 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &FreeRegs, 561 bool IsFastCall) const; 562 bool shouldUseInReg(QualType Ty, unsigned &FreeRegs, 563 bool IsFastCall, bool &NeedsPadding) const; 564 565public: 566 567 virtual void computeInfo(CGFunctionInfo &FI) const; 568 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 569 CodeGenFunction &CGF) const; 570 571 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w, 572 unsigned r) 573 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p), 574 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {} 575}; 576 577class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 578public: 579 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 580 bool d, bool p, bool w, unsigned r) 581 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {} 582 583 static bool isStructReturnInRegABI( 584 const llvm::Triple &Triple, const CodeGenOptions &Opts); 585 586 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 587 CodeGen::CodeGenModule &CGM) const; 588 589 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 590 // Darwin uses different dwarf register numbers for EH. 591 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 592 return 4; 593 } 594 595 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 596 llvm::Value *Address) const; 597 598 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 599 StringRef Constraint, 600 llvm::Type* Ty) const { 601 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 602 } 603 604 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const { 605 unsigned Sig = (0xeb << 0) | // jmp rel8 606 (0x06 << 8) | // .+0x08 607 ('F' << 16) | 608 ('T' << 24); 609 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 610 } 611 612}; 613 614} 615 616/// shouldReturnTypeInRegister - Determine if the given type should be 617/// passed in a register (for the Darwin ABI). 618bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 619 ASTContext &Context, 620 unsigned callingConvention) { 621 uint64_t Size = Context.getTypeSize(Ty); 622 623 // Type must be register sized. 624 if (!isRegisterSize(Size)) 625 return false; 626 627 if (Ty->isVectorType()) { 628 // 64- and 128- bit vectors inside structures are not returned in 629 // registers. 630 if (Size == 64 || Size == 128) 631 return false; 632 633 return true; 634 } 635 636 // If this is a builtin, pointer, enum, complex type, member pointer, or 637 // member function pointer it is ok. 638 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 639 Ty->isAnyComplexType() || Ty->isEnumeralType() || 640 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 641 return true; 642 643 // Arrays are treated like records. 644 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 645 return shouldReturnTypeInRegister(AT->getElementType(), Context, 646 callingConvention); 647 648 // Otherwise, it must be a record type. 649 const RecordType *RT = Ty->getAs<RecordType>(); 650 if (!RT) return false; 651 652 // FIXME: Traverse bases here too. 653 654 // For thiscall conventions, structures will never be returned in 655 // a register. This is for compatibility with the MSVC ABI 656 if (callingConvention == llvm::CallingConv::X86_ThisCall && 657 RT->isStructureType()) { 658 return false; 659 } 660 661 // Structure types are passed in register if all fields would be 662 // passed in a register. 663 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(), 664 e = RT->getDecl()->field_end(); i != e; ++i) { 665 const FieldDecl *FD = *i; 666 667 // Empty fields are ignored. 668 if (isEmptyField(Context, FD, true)) 669 continue; 670 671 // Check fields recursively. 672 if (!shouldReturnTypeInRegister(FD->getType(), Context, 673 callingConvention)) 674 return false; 675 } 676 return true; 677} 678 679ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 680 unsigned callingConvention) const { 681 if (RetTy->isVoidType()) 682 return ABIArgInfo::getIgnore(); 683 684 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 685 // On Darwin, some vectors are returned in registers. 686 if (IsDarwinVectorABI) { 687 uint64_t Size = getContext().getTypeSize(RetTy); 688 689 // 128-bit vectors are a special case; they are returned in 690 // registers and we need to make sure to pick a type the LLVM 691 // backend will like. 692 if (Size == 128) 693 return ABIArgInfo::getDirect(llvm::VectorType::get( 694 llvm::Type::getInt64Ty(getVMContext()), 2)); 695 696 // Always return in register if it fits in a general purpose 697 // register, or if it is 64 bits and has a single element. 698 if ((Size == 8 || Size == 16 || Size == 32) || 699 (Size == 64 && VT->getNumElements() == 1)) 700 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 701 Size)); 702 703 return ABIArgInfo::getIndirect(0); 704 } 705 706 return ABIArgInfo::getDirect(); 707 } 708 709 if (isAggregateTypeForABI(RetTy)) { 710 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 711 if (isRecordReturnIndirect(RT, getCXXABI())) 712 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 713 714 // Structures with flexible arrays are always indirect. 715 if (RT->getDecl()->hasFlexibleArrayMember()) 716 return ABIArgInfo::getIndirect(0); 717 } 718 719 // If specified, structs and unions are always indirect. 720 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType()) 721 return ABIArgInfo::getIndirect(0); 722 723 // Small structures which are register sized are generally returned 724 // in a register. 725 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(), 726 callingConvention)) { 727 uint64_t Size = getContext().getTypeSize(RetTy); 728 729 // As a special-case, if the struct is a "single-element" struct, and 730 // the field is of type "float" or "double", return it in a 731 // floating-point register. (MSVC does not apply this special case.) 732 // We apply a similar transformation for pointer types to improve the 733 // quality of the generated IR. 734 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 735 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 736 || SeltTy->hasPointerRepresentation()) 737 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 738 739 // FIXME: We should be able to narrow this integer in cases with dead 740 // padding. 741 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 742 } 743 744 return ABIArgInfo::getIndirect(0); 745 } 746 747 // Treat an enum type as its underlying type. 748 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 749 RetTy = EnumTy->getDecl()->getIntegerType(); 750 751 return (RetTy->isPromotableIntegerType() ? 752 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 753} 754 755static bool isSSEVectorType(ASTContext &Context, QualType Ty) { 756 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 757} 758 759static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) { 760 const RecordType *RT = Ty->getAs<RecordType>(); 761 if (!RT) 762 return 0; 763 const RecordDecl *RD = RT->getDecl(); 764 765 // If this is a C++ record, check the bases first. 766 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 767 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 768 e = CXXRD->bases_end(); i != e; ++i) 769 if (!isRecordWithSSEVectorType(Context, i->getType())) 770 return false; 771 772 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 773 i != e; ++i) { 774 QualType FT = i->getType(); 775 776 if (isSSEVectorType(Context, FT)) 777 return true; 778 779 if (isRecordWithSSEVectorType(Context, FT)) 780 return true; 781 } 782 783 return false; 784} 785 786unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 787 unsigned Align) const { 788 // Otherwise, if the alignment is less than or equal to the minimum ABI 789 // alignment, just use the default; the backend will handle this. 790 if (Align <= MinABIStackAlignInBytes) 791 return 0; // Use default alignment. 792 793 // On non-Darwin, the stack type alignment is always 4. 794 if (!IsDarwinVectorABI) { 795 // Set explicit alignment, since we may need to realign the top. 796 return MinABIStackAlignInBytes; 797 } 798 799 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 800 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) || 801 isRecordWithSSEVectorType(getContext(), Ty))) 802 return 16; 803 804 return MinABIStackAlignInBytes; 805} 806 807ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 808 unsigned &FreeRegs) const { 809 if (!ByVal) { 810 if (FreeRegs) { 811 --FreeRegs; // Non byval indirects just use one pointer. 812 return ABIArgInfo::getIndirectInReg(0, false); 813 } 814 return ABIArgInfo::getIndirect(0, false); 815 } 816 817 // Compute the byval alignment. 818 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 819 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 820 if (StackAlign == 0) 821 return ABIArgInfo::getIndirect(4); 822 823 // If the stack alignment is less than the type alignment, realign the 824 // argument. 825 if (StackAlign < TypeAlign) 826 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, 827 /*Realign=*/true); 828 829 return ABIArgInfo::getIndirect(StackAlign); 830} 831 832X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 833 const Type *T = isSingleElementStruct(Ty, getContext()); 834 if (!T) 835 T = Ty.getTypePtr(); 836 837 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 838 BuiltinType::Kind K = BT->getKind(); 839 if (K == BuiltinType::Float || K == BuiltinType::Double) 840 return Float; 841 } 842 return Integer; 843} 844 845bool X86_32ABIInfo::shouldUseInReg(QualType Ty, unsigned &FreeRegs, 846 bool IsFastCall, bool &NeedsPadding) const { 847 NeedsPadding = false; 848 Class C = classify(Ty); 849 if (C == Float) 850 return false; 851 852 unsigned Size = getContext().getTypeSize(Ty); 853 unsigned SizeInRegs = (Size + 31) / 32; 854 855 if (SizeInRegs == 0) 856 return false; 857 858 if (SizeInRegs > FreeRegs) { 859 FreeRegs = 0; 860 return false; 861 } 862 863 FreeRegs -= SizeInRegs; 864 865 if (IsFastCall) { 866 if (Size > 32) 867 return false; 868 869 if (Ty->isIntegralOrEnumerationType()) 870 return true; 871 872 if (Ty->isPointerType()) 873 return true; 874 875 if (Ty->isReferenceType()) 876 return true; 877 878 if (FreeRegs) 879 NeedsPadding = true; 880 881 return false; 882 } 883 884 return true; 885} 886 887ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 888 unsigned &FreeRegs, 889 bool IsFastCall) const { 890 // FIXME: Set alignment on indirect arguments. 891 if (isAggregateTypeForABI(Ty)) { 892 if (const RecordType *RT = Ty->getAs<RecordType>()) { 893 if (IsWin32StructABI) 894 return getIndirectResult(Ty, true, FreeRegs); 895 896 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 897 return getIndirectResult(Ty, RAA == CGCXXABI::RAA_DirectInMemory, FreeRegs); 898 899 // Structures with flexible arrays are always indirect. 900 if (RT->getDecl()->hasFlexibleArrayMember()) 901 return getIndirectResult(Ty, true, FreeRegs); 902 } 903 904 // Ignore empty structs/unions. 905 if (isEmptyRecord(getContext(), Ty, true)) 906 return ABIArgInfo::getIgnore(); 907 908 llvm::LLVMContext &LLVMContext = getVMContext(); 909 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 910 bool NeedsPadding; 911 if (shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding)) { 912 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 913 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 914 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 915 return ABIArgInfo::getDirectInReg(Result); 916 } 917 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0; 918 919 // Expand small (<= 128-bit) record types when we know that the stack layout 920 // of those arguments will match the struct. This is important because the 921 // LLVM backend isn't smart enough to remove byval, which inhibits many 922 // optimizations. 923 if (getContext().getTypeSize(Ty) <= 4*32 && 924 canExpandIndirectArgument(Ty, getContext())) 925 return ABIArgInfo::getExpandWithPadding(IsFastCall, PaddingType); 926 927 return getIndirectResult(Ty, true, FreeRegs); 928 } 929 930 if (const VectorType *VT = Ty->getAs<VectorType>()) { 931 // On Darwin, some vectors are passed in memory, we handle this by passing 932 // it as an i8/i16/i32/i64. 933 if (IsDarwinVectorABI) { 934 uint64_t Size = getContext().getTypeSize(Ty); 935 if ((Size == 8 || Size == 16 || Size == 32) || 936 (Size == 64 && VT->getNumElements() == 1)) 937 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 938 Size)); 939 } 940 941 if (IsX86_MMXType(CGT.ConvertType(Ty))) 942 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 943 944 return ABIArgInfo::getDirect(); 945 } 946 947 948 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 949 Ty = EnumTy->getDecl()->getIntegerType(); 950 951 bool NeedsPadding; 952 bool InReg = shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding); 953 954 if (Ty->isPromotableIntegerType()) { 955 if (InReg) 956 return ABIArgInfo::getExtendInReg(); 957 return ABIArgInfo::getExtend(); 958 } 959 if (InReg) 960 return ABIArgInfo::getDirectInReg(); 961 return ABIArgInfo::getDirect(); 962} 963 964void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 965 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), 966 FI.getCallingConvention()); 967 968 unsigned CC = FI.getCallingConvention(); 969 bool IsFastCall = CC == llvm::CallingConv::X86_FastCall; 970 unsigned FreeRegs; 971 if (IsFastCall) 972 FreeRegs = 2; 973 else if (FI.getHasRegParm()) 974 FreeRegs = FI.getRegParm(); 975 else 976 FreeRegs = DefaultNumRegisterParameters; 977 978 // If the return value is indirect, then the hidden argument is consuming one 979 // integer register. 980 if (FI.getReturnInfo().isIndirect() && FreeRegs) { 981 --FreeRegs; 982 ABIArgInfo &Old = FI.getReturnInfo(); 983 Old = ABIArgInfo::getIndirectInReg(Old.getIndirectAlign(), 984 Old.getIndirectByVal(), 985 Old.getIndirectRealign()); 986 } 987 988 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 989 it != ie; ++it) 990 it->info = classifyArgumentType(it->type, FreeRegs, IsFastCall); 991} 992 993llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 994 CodeGenFunction &CGF) const { 995 llvm::Type *BPP = CGF.Int8PtrPtrTy; 996 997 CGBuilderTy &Builder = CGF.Builder; 998 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 999 "ap"); 1000 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 1001 1002 // Compute if the address needs to be aligned 1003 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity(); 1004 Align = getTypeStackAlignInBytes(Ty, Align); 1005 Align = std::max(Align, 4U); 1006 if (Align > 4) { 1007 // addr = (addr + align - 1) & -align; 1008 llvm::Value *Offset = 1009 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1); 1010 Addr = CGF.Builder.CreateGEP(Addr, Offset); 1011 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr, 1012 CGF.Int32Ty); 1013 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align); 1014 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask), 1015 Addr->getType(), 1016 "ap.cur.aligned"); 1017 } 1018 1019 llvm::Type *PTy = 1020 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 1021 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 1022 1023 uint64_t Offset = 1024 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align); 1025 llvm::Value *NextAddr = 1026 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 1027 "ap.next"); 1028 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 1029 1030 return AddrTyped; 1031} 1032 1033void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D, 1034 llvm::GlobalValue *GV, 1035 CodeGen::CodeGenModule &CGM) const { 1036 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1037 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 1038 // Get the LLVM function. 1039 llvm::Function *Fn = cast<llvm::Function>(GV); 1040 1041 // Now add the 'alignstack' attribute with a value of 16. 1042 llvm::AttrBuilder B; 1043 B.addStackAlignmentAttr(16); 1044 Fn->addAttributes(llvm::AttributeSet::FunctionIndex, 1045 llvm::AttributeSet::get(CGM.getLLVMContext(), 1046 llvm::AttributeSet::FunctionIndex, 1047 B)); 1048 } 1049 } 1050} 1051 1052bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 1053 CodeGen::CodeGenFunction &CGF, 1054 llvm::Value *Address) const { 1055 CodeGen::CGBuilderTy &Builder = CGF.Builder; 1056 1057 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 1058 1059 // 0-7 are the eight integer registers; the order is different 1060 // on Darwin (for EH), but the range is the same. 1061 // 8 is %eip. 1062 AssignToArrayRange(Builder, Address, Four8, 0, 8); 1063 1064 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 1065 // 12-16 are st(0..4). Not sure why we stop at 4. 1066 // These have size 16, which is sizeof(long double) on 1067 // platforms with 8-byte alignment for that type. 1068 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 1069 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 1070 1071 } else { 1072 // 9 is %eflags, which doesn't get a size on Darwin for some 1073 // reason. 1074 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9)); 1075 1076 // 11-16 are st(0..5). Not sure why we stop at 5. 1077 // These have size 12, which is sizeof(long double) on 1078 // platforms with 4-byte alignment for that type. 1079 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 1080 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 1081 } 1082 1083 return false; 1084} 1085 1086//===----------------------------------------------------------------------===// 1087// X86-64 ABI Implementation 1088//===----------------------------------------------------------------------===// 1089 1090 1091namespace { 1092/// X86_64ABIInfo - The X86_64 ABI information. 1093class X86_64ABIInfo : public ABIInfo { 1094 enum Class { 1095 Integer = 0, 1096 SSE, 1097 SSEUp, 1098 X87, 1099 X87Up, 1100 ComplexX87, 1101 NoClass, 1102 Memory 1103 }; 1104 1105 /// merge - Implement the X86_64 ABI merging algorithm. 1106 /// 1107 /// Merge an accumulating classification \arg Accum with a field 1108 /// classification \arg Field. 1109 /// 1110 /// \param Accum - The accumulating classification. This should 1111 /// always be either NoClass or the result of a previous merge 1112 /// call. In addition, this should never be Memory (the caller 1113 /// should just return Memory for the aggregate). 1114 static Class merge(Class Accum, Class Field); 1115 1116 /// postMerge - Implement the X86_64 ABI post merging algorithm. 1117 /// 1118 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 1119 /// final MEMORY or SSE classes when necessary. 1120 /// 1121 /// \param AggregateSize - The size of the current aggregate in 1122 /// the classification process. 1123 /// 1124 /// \param Lo - The classification for the parts of the type 1125 /// residing in the low word of the containing object. 1126 /// 1127 /// \param Hi - The classification for the parts of the type 1128 /// residing in the higher words of the containing object. 1129 /// 1130 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 1131 1132 /// classify - Determine the x86_64 register classes in which the 1133 /// given type T should be passed. 1134 /// 1135 /// \param Lo - The classification for the parts of the type 1136 /// residing in the low word of the containing object. 1137 /// 1138 /// \param Hi - The classification for the parts of the type 1139 /// residing in the high word of the containing object. 1140 /// 1141 /// \param OffsetBase - The bit offset of this type in the 1142 /// containing object. Some parameters are classified different 1143 /// depending on whether they straddle an eightbyte boundary. 1144 /// 1145 /// \param isNamedArg - Whether the argument in question is a "named" 1146 /// argument, as used in AMD64-ABI 3.5.7. 1147 /// 1148 /// If a word is unused its result will be NoClass; if a type should 1149 /// be passed in Memory then at least the classification of \arg Lo 1150 /// will be Memory. 1151 /// 1152 /// The \arg Lo class will be NoClass iff the argument is ignored. 1153 /// 1154 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 1155 /// also be ComplexX87. 1156 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 1157 bool isNamedArg) const; 1158 1159 llvm::Type *GetByteVectorType(QualType Ty) const; 1160 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 1161 unsigned IROffset, QualType SourceTy, 1162 unsigned SourceOffset) const; 1163 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 1164 unsigned IROffset, QualType SourceTy, 1165 unsigned SourceOffset) const; 1166 1167 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1168 /// such that the argument will be returned in memory. 1169 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 1170 1171 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1172 /// such that the argument will be passed in memory. 1173 /// 1174 /// \param freeIntRegs - The number of free integer registers remaining 1175 /// available. 1176 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 1177 1178 ABIArgInfo classifyReturnType(QualType RetTy) const; 1179 1180 ABIArgInfo classifyArgumentType(QualType Ty, 1181 unsigned freeIntRegs, 1182 unsigned &neededInt, 1183 unsigned &neededSSE, 1184 bool isNamedArg) const; 1185 1186 bool IsIllegalVectorType(QualType Ty) const; 1187 1188 /// The 0.98 ABI revision clarified a lot of ambiguities, 1189 /// unfortunately in ways that were not always consistent with 1190 /// certain previous compilers. In particular, platforms which 1191 /// required strict binary compatibility with older versions of GCC 1192 /// may need to exempt themselves. 1193 bool honorsRevision0_98() const { 1194 return !getTarget().getTriple().isOSDarwin(); 1195 } 1196 1197 bool HasAVX; 1198 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 1199 // 64-bit hardware. 1200 bool Has64BitPointers; 1201 1202public: 1203 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) : 1204 ABIInfo(CGT), HasAVX(hasavx), 1205 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 1206 } 1207 1208 bool isPassedUsingAVXType(QualType type) const { 1209 unsigned neededInt, neededSSE; 1210 // The freeIntRegs argument doesn't matter here. 1211 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 1212 /*isNamedArg*/true); 1213 if (info.isDirect()) { 1214 llvm::Type *ty = info.getCoerceToType(); 1215 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 1216 return (vectorTy->getBitWidth() > 128); 1217 } 1218 return false; 1219 } 1220 1221 virtual void computeInfo(CGFunctionInfo &FI) const; 1222 1223 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 1224 CodeGenFunction &CGF) const; 1225}; 1226 1227/// WinX86_64ABIInfo - The Windows X86_64 ABI information. 1228class WinX86_64ABIInfo : public ABIInfo { 1229 1230 ABIArgInfo classify(QualType Ty, bool IsReturnType) const; 1231 1232public: 1233 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 1234 1235 virtual void computeInfo(CGFunctionInfo &FI) const; 1236 1237 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 1238 CodeGenFunction &CGF) const; 1239}; 1240 1241class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 1242public: 1243 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 1244 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {} 1245 1246 const X86_64ABIInfo &getABIInfo() const { 1247 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 1248 } 1249 1250 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 1251 return 7; 1252 } 1253 1254 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1255 llvm::Value *Address) const { 1256 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 1257 1258 // 0-15 are the 16 integer registers. 1259 // 16 is %rip. 1260 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 1261 return false; 1262 } 1263 1264 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1265 StringRef Constraint, 1266 llvm::Type* Ty) const { 1267 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1268 } 1269 1270 bool isNoProtoCallVariadic(const CallArgList &args, 1271 const FunctionNoProtoType *fnType) const { 1272 // The default CC on x86-64 sets %al to the number of SSA 1273 // registers used, and GCC sets this when calling an unprototyped 1274 // function, so we override the default behavior. However, don't do 1275 // that when AVX types are involved: the ABI explicitly states it is 1276 // undefined, and it doesn't work in practice because of how the ABI 1277 // defines varargs anyway. 1278 if (fnType->getCallConv() == CC_C) { 1279 bool HasAVXType = false; 1280 for (CallArgList::const_iterator 1281 it = args.begin(), ie = args.end(); it != ie; ++it) { 1282 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 1283 HasAVXType = true; 1284 break; 1285 } 1286 } 1287 1288 if (!HasAVXType) 1289 return true; 1290 } 1291 1292 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 1293 } 1294 1295 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const { 1296 unsigned Sig = (0xeb << 0) | // jmp rel8 1297 (0x0a << 8) | // .+0x0c 1298 ('F' << 16) | 1299 ('T' << 24); 1300 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1301 } 1302 1303}; 1304 1305static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 1306 // If the argument does not end in .lib, automatically add the suffix. This 1307 // matches the behavior of MSVC. 1308 std::string ArgStr = Lib; 1309 if (Lib.size() <= 4 || 1310 Lib.substr(Lib.size() - 4).compare_lower(".lib") != 0) { 1311 ArgStr += ".lib"; 1312 } 1313 return ArgStr; 1314} 1315 1316class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 1317public: 1318 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 1319 bool d, bool p, bool w, unsigned RegParms) 1320 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {} 1321 1322 void getDependentLibraryOption(llvm::StringRef Lib, 1323 llvm::SmallString<24> &Opt) const { 1324 Opt = "/DEFAULTLIB:"; 1325 Opt += qualifyWindowsLibrary(Lib); 1326 } 1327 1328 void getDetectMismatchOption(llvm::StringRef Name, 1329 llvm::StringRef Value, 1330 llvm::SmallString<32> &Opt) const { 1331 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 1332 } 1333}; 1334 1335class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 1336public: 1337 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 1338 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {} 1339 1340 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 1341 return 7; 1342 } 1343 1344 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1345 llvm::Value *Address) const { 1346 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 1347 1348 // 0-15 are the 16 integer registers. 1349 // 16 is %rip. 1350 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 1351 return false; 1352 } 1353 1354 void getDependentLibraryOption(llvm::StringRef Lib, 1355 llvm::SmallString<24> &Opt) const { 1356 Opt = "/DEFAULTLIB:"; 1357 Opt += qualifyWindowsLibrary(Lib); 1358 } 1359 1360 void getDetectMismatchOption(llvm::StringRef Name, 1361 llvm::StringRef Value, 1362 llvm::SmallString<32> &Opt) const { 1363 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 1364 } 1365}; 1366 1367} 1368 1369void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 1370 Class &Hi) const { 1371 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 1372 // 1373 // (a) If one of the classes is Memory, the whole argument is passed in 1374 // memory. 1375 // 1376 // (b) If X87UP is not preceded by X87, the whole argument is passed in 1377 // memory. 1378 // 1379 // (c) If the size of the aggregate exceeds two eightbytes and the first 1380 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 1381 // argument is passed in memory. NOTE: This is necessary to keep the 1382 // ABI working for processors that don't support the __m256 type. 1383 // 1384 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 1385 // 1386 // Some of these are enforced by the merging logic. Others can arise 1387 // only with unions; for example: 1388 // union { _Complex double; unsigned; } 1389 // 1390 // Note that clauses (b) and (c) were added in 0.98. 1391 // 1392 if (Hi == Memory) 1393 Lo = Memory; 1394 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 1395 Lo = Memory; 1396 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 1397 Lo = Memory; 1398 if (Hi == SSEUp && Lo != SSE) 1399 Hi = SSE; 1400} 1401 1402X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 1403 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 1404 // classified recursively so that always two fields are 1405 // considered. The resulting class is calculated according to 1406 // the classes of the fields in the eightbyte: 1407 // 1408 // (a) If both classes are equal, this is the resulting class. 1409 // 1410 // (b) If one of the classes is NO_CLASS, the resulting class is 1411 // the other class. 1412 // 1413 // (c) If one of the classes is MEMORY, the result is the MEMORY 1414 // class. 1415 // 1416 // (d) If one of the classes is INTEGER, the result is the 1417 // INTEGER. 1418 // 1419 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 1420 // MEMORY is used as class. 1421 // 1422 // (f) Otherwise class SSE is used. 1423 1424 // Accum should never be memory (we should have returned) or 1425 // ComplexX87 (because this cannot be passed in a structure). 1426 assert((Accum != Memory && Accum != ComplexX87) && 1427 "Invalid accumulated classification during merge."); 1428 if (Accum == Field || Field == NoClass) 1429 return Accum; 1430 if (Field == Memory) 1431 return Memory; 1432 if (Accum == NoClass) 1433 return Field; 1434 if (Accum == Integer || Field == Integer) 1435 return Integer; 1436 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 1437 Accum == X87 || Accum == X87Up) 1438 return Memory; 1439 return SSE; 1440} 1441 1442void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 1443 Class &Lo, Class &Hi, bool isNamedArg) const { 1444 // FIXME: This code can be simplified by introducing a simple value class for 1445 // Class pairs with appropriate constructor methods for the various 1446 // situations. 1447 1448 // FIXME: Some of the split computations are wrong; unaligned vectors 1449 // shouldn't be passed in registers for example, so there is no chance they 1450 // can straddle an eightbyte. Verify & simplify. 1451 1452 Lo = Hi = NoClass; 1453 1454 Class &Current = OffsetBase < 64 ? Lo : Hi; 1455 Current = Memory; 1456 1457 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1458 BuiltinType::Kind k = BT->getKind(); 1459 1460 if (k == BuiltinType::Void) { 1461 Current = NoClass; 1462 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 1463 Lo = Integer; 1464 Hi = Integer; 1465 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 1466 Current = Integer; 1467 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) || 1468 (k == BuiltinType::LongDouble && 1469 getTarget().getTriple().isOSNaCl())) { 1470 Current = SSE; 1471 } else if (k == BuiltinType::LongDouble) { 1472 Lo = X87; 1473 Hi = X87Up; 1474 } 1475 // FIXME: _Decimal32 and _Decimal64 are SSE. 1476 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 1477 return; 1478 } 1479 1480 if (const EnumType *ET = Ty->getAs<EnumType>()) { 1481 // Classify the underlying integer type. 1482 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 1483 return; 1484 } 1485 1486 if (Ty->hasPointerRepresentation()) { 1487 Current = Integer; 1488 return; 1489 } 1490 1491 if (Ty->isMemberPointerType()) { 1492 if (Ty->isMemberFunctionPointerType() && Has64BitPointers) 1493 Lo = Hi = Integer; 1494 else 1495 Current = Integer; 1496 return; 1497 } 1498 1499 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1500 uint64_t Size = getContext().getTypeSize(VT); 1501 if (Size == 32) { 1502 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x 1503 // float> as integer. 1504 Current = Integer; 1505 1506 // If this type crosses an eightbyte boundary, it should be 1507 // split. 1508 uint64_t EB_Real = (OffsetBase) / 64; 1509 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64; 1510 if (EB_Real != EB_Imag) 1511 Hi = Lo; 1512 } else if (Size == 64) { 1513 // gcc passes <1 x double> in memory. :( 1514 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) 1515 return; 1516 1517 // gcc passes <1 x long long> as INTEGER. 1518 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) || 1519 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) || 1520 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) || 1521 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong)) 1522 Current = Integer; 1523 else 1524 Current = SSE; 1525 1526 // If this type crosses an eightbyte boundary, it should be 1527 // split. 1528 if (OffsetBase && OffsetBase != 64) 1529 Hi = Lo; 1530 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) { 1531 // Arguments of 256-bits are split into four eightbyte chunks. The 1532 // least significant one belongs to class SSE and all the others to class 1533 // SSEUP. The original Lo and Hi design considers that types can't be 1534 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 1535 // This design isn't correct for 256-bits, but since there're no cases 1536 // where the upper parts would need to be inspected, avoid adding 1537 // complexity and just consider Hi to match the 64-256 part. 1538 // 1539 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 1540 // registers if they are "named", i.e. not part of the "..." of a 1541 // variadic function. 1542 Lo = SSE; 1543 Hi = SSEUp; 1544 } 1545 return; 1546 } 1547 1548 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 1549 QualType ET = getContext().getCanonicalType(CT->getElementType()); 1550 1551 uint64_t Size = getContext().getTypeSize(Ty); 1552 if (ET->isIntegralOrEnumerationType()) { 1553 if (Size <= 64) 1554 Current = Integer; 1555 else if (Size <= 128) 1556 Lo = Hi = Integer; 1557 } else if (ET == getContext().FloatTy) 1558 Current = SSE; 1559 else if (ET == getContext().DoubleTy || 1560 (ET == getContext().LongDoubleTy && 1561 getTarget().getTriple().isOSNaCl())) 1562 Lo = Hi = SSE; 1563 else if (ET == getContext().LongDoubleTy) 1564 Current = ComplexX87; 1565 1566 // If this complex type crosses an eightbyte boundary then it 1567 // should be split. 1568 uint64_t EB_Real = (OffsetBase) / 64; 1569 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 1570 if (Hi == NoClass && EB_Real != EB_Imag) 1571 Hi = Lo; 1572 1573 return; 1574 } 1575 1576 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 1577 // Arrays are treated like structures. 1578 1579 uint64_t Size = getContext().getTypeSize(Ty); 1580 1581 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 1582 // than four eightbytes, ..., it has class MEMORY. 1583 if (Size > 256) 1584 return; 1585 1586 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 1587 // fields, it has class MEMORY. 1588 // 1589 // Only need to check alignment of array base. 1590 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 1591 return; 1592 1593 // Otherwise implement simplified merge. We could be smarter about 1594 // this, but it isn't worth it and would be harder to verify. 1595 Current = NoClass; 1596 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 1597 uint64_t ArraySize = AT->getSize().getZExtValue(); 1598 1599 // The only case a 256-bit wide vector could be used is when the array 1600 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 1601 // to work for sizes wider than 128, early check and fallback to memory. 1602 if (Size > 128 && EltSize != 256) 1603 return; 1604 1605 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 1606 Class FieldLo, FieldHi; 1607 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 1608 Lo = merge(Lo, FieldLo); 1609 Hi = merge(Hi, FieldHi); 1610 if (Lo == Memory || Hi == Memory) 1611 break; 1612 } 1613 1614 postMerge(Size, Lo, Hi); 1615 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 1616 return; 1617 } 1618 1619 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1620 uint64_t Size = getContext().getTypeSize(Ty); 1621 1622 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 1623 // than four eightbytes, ..., it has class MEMORY. 1624 if (Size > 256) 1625 return; 1626 1627 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 1628 // copy constructor or a non-trivial destructor, it is passed by invisible 1629 // reference. 1630 if (getRecordArgABI(RT, getCXXABI())) 1631 return; 1632 1633 const RecordDecl *RD = RT->getDecl(); 1634 1635 // Assume variable sized types are passed in memory. 1636 if (RD->hasFlexibleArrayMember()) 1637 return; 1638 1639 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 1640 1641 // Reset Lo class, this will be recomputed. 1642 Current = NoClass; 1643 1644 // If this is a C++ record, classify the bases first. 1645 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1646 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 1647 e = CXXRD->bases_end(); i != e; ++i) { 1648 assert(!i->isVirtual() && !i->getType()->isDependentType() && 1649 "Unexpected base class!"); 1650 const CXXRecordDecl *Base = 1651 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 1652 1653 // Classify this field. 1654 // 1655 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 1656 // single eightbyte, each is classified separately. Each eightbyte gets 1657 // initialized to class NO_CLASS. 1658 Class FieldLo, FieldHi; 1659 uint64_t Offset = 1660 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 1661 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 1662 Lo = merge(Lo, FieldLo); 1663 Hi = merge(Hi, FieldHi); 1664 if (Lo == Memory || Hi == Memory) 1665 break; 1666 } 1667 } 1668 1669 // Classify the fields one at a time, merging the results. 1670 unsigned idx = 0; 1671 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 1672 i != e; ++i, ++idx) { 1673 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 1674 bool BitField = i->isBitField(); 1675 1676 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 1677 // four eightbytes, or it contains unaligned fields, it has class MEMORY. 1678 // 1679 // The only case a 256-bit wide vector could be used is when the struct 1680 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 1681 // to work for sizes wider than 128, early check and fallback to memory. 1682 // 1683 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) { 1684 Lo = Memory; 1685 return; 1686 } 1687 // Note, skip this test for bit-fields, see below. 1688 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 1689 Lo = Memory; 1690 return; 1691 } 1692 1693 // Classify this field. 1694 // 1695 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 1696 // exceeds a single eightbyte, each is classified 1697 // separately. Each eightbyte gets initialized to class 1698 // NO_CLASS. 1699 Class FieldLo, FieldHi; 1700 1701 // Bit-fields require special handling, they do not force the 1702 // structure to be passed in memory even if unaligned, and 1703 // therefore they can straddle an eightbyte. 1704 if (BitField) { 1705 // Ignore padding bit-fields. 1706 if (i->isUnnamedBitfield()) 1707 continue; 1708 1709 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 1710 uint64_t Size = i->getBitWidthValue(getContext()); 1711 1712 uint64_t EB_Lo = Offset / 64; 1713 uint64_t EB_Hi = (Offset + Size - 1) / 64; 1714 1715 if (EB_Lo) { 1716 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 1717 FieldLo = NoClass; 1718 FieldHi = Integer; 1719 } else { 1720 FieldLo = Integer; 1721 FieldHi = EB_Hi ? Integer : NoClass; 1722 } 1723 } else 1724 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 1725 Lo = merge(Lo, FieldLo); 1726 Hi = merge(Hi, FieldHi); 1727 if (Lo == Memory || Hi == Memory) 1728 break; 1729 } 1730 1731 postMerge(Size, Lo, Hi); 1732 } 1733} 1734 1735ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 1736 // If this is a scalar LLVM value then assume LLVM will pass it in the right 1737 // place naturally. 1738 if (!isAggregateTypeForABI(Ty)) { 1739 // Treat an enum type as its underlying type. 1740 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1741 Ty = EnumTy->getDecl()->getIntegerType(); 1742 1743 return (Ty->isPromotableIntegerType() ? 1744 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 1745 } 1746 1747 return ABIArgInfo::getIndirect(0); 1748} 1749 1750bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 1751 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 1752 uint64_t Size = getContext().getTypeSize(VecTy); 1753 unsigned LargestVector = HasAVX ? 256 : 128; 1754 if (Size <= 64 || Size > LargestVector) 1755 return true; 1756 } 1757 1758 return false; 1759} 1760 1761ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 1762 unsigned freeIntRegs) const { 1763 // If this is a scalar LLVM value then assume LLVM will pass it in the right 1764 // place naturally. 1765 // 1766 // This assumption is optimistic, as there could be free registers available 1767 // when we need to pass this argument in memory, and LLVM could try to pass 1768 // the argument in the free register. This does not seem to happen currently, 1769 // but this code would be much safer if we could mark the argument with 1770 // 'onstack'. See PR12193. 1771 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) { 1772 // Treat an enum type as its underlying type. 1773 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1774 Ty = EnumTy->getDecl()->getIntegerType(); 1775 1776 return (Ty->isPromotableIntegerType() ? 1777 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 1778 } 1779 1780 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 1781 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 1782 1783 // Compute the byval alignment. We specify the alignment of the byval in all 1784 // cases so that the mid-level optimizer knows the alignment of the byval. 1785 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 1786 1787 // Attempt to avoid passing indirect results using byval when possible. This 1788 // is important for good codegen. 1789 // 1790 // We do this by coercing the value into a scalar type which the backend can 1791 // handle naturally (i.e., without using byval). 1792 // 1793 // For simplicity, we currently only do this when we have exhausted all of the 1794 // free integer registers. Doing this when there are free integer registers 1795 // would require more care, as we would have to ensure that the coerced value 1796 // did not claim the unused register. That would require either reording the 1797 // arguments to the function (so that any subsequent inreg values came first), 1798 // or only doing this optimization when there were no following arguments that 1799 // might be inreg. 1800 // 1801 // We currently expect it to be rare (particularly in well written code) for 1802 // arguments to be passed on the stack when there are still free integer 1803 // registers available (this would typically imply large structs being passed 1804 // by value), so this seems like a fair tradeoff for now. 1805 // 1806 // We can revisit this if the backend grows support for 'onstack' parameter 1807 // attributes. See PR12193. 1808 if (freeIntRegs == 0) { 1809 uint64_t Size = getContext().getTypeSize(Ty); 1810 1811 // If this type fits in an eightbyte, coerce it into the matching integral 1812 // type, which will end up on the stack (with alignment 8). 1813 if (Align == 8 && Size <= 64) 1814 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1815 Size)); 1816 } 1817 1818 return ABIArgInfo::getIndirect(Align); 1819} 1820 1821/// GetByteVectorType - The ABI specifies that a value should be passed in an 1822/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a 1823/// vector register. 1824llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 1825 llvm::Type *IRType = CGT.ConvertType(Ty); 1826 1827 // Wrapper structs that just contain vectors are passed just like vectors, 1828 // strip them off if present. 1829 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType); 1830 while (STy && STy->getNumElements() == 1) { 1831 IRType = STy->getElementType(0); 1832 STy = dyn_cast<llvm::StructType>(IRType); 1833 } 1834 1835 // If the preferred type is a 16-byte vector, prefer to pass it. 1836 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){ 1837 llvm::Type *EltTy = VT->getElementType(); 1838 unsigned BitWidth = VT->getBitWidth(); 1839 if ((BitWidth >= 128 && BitWidth <= 256) && 1840 (EltTy->isFloatTy() || EltTy->isDoubleTy() || 1841 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) || 1842 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) || 1843 EltTy->isIntegerTy(128))) 1844 return VT; 1845 } 1846 1847 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2); 1848} 1849 1850/// BitsContainNoUserData - Return true if the specified [start,end) bit range 1851/// is known to either be off the end of the specified type or being in 1852/// alignment padding. The user type specified is known to be at most 128 bits 1853/// in size, and have passed through X86_64ABIInfo::classify with a successful 1854/// classification that put one of the two halves in the INTEGER class. 1855/// 1856/// It is conservatively correct to return false. 1857static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 1858 unsigned EndBit, ASTContext &Context) { 1859 // If the bytes being queried are off the end of the type, there is no user 1860 // data hiding here. This handles analysis of builtins, vectors and other 1861 // types that don't contain interesting padding. 1862 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 1863 if (TySize <= StartBit) 1864 return true; 1865 1866 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 1867 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 1868 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 1869 1870 // Check each element to see if the element overlaps with the queried range. 1871 for (unsigned i = 0; i != NumElts; ++i) { 1872 // If the element is after the span we care about, then we're done.. 1873 unsigned EltOffset = i*EltSize; 1874 if (EltOffset >= EndBit) break; 1875 1876 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 1877 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 1878 EndBit-EltOffset, Context)) 1879 return false; 1880 } 1881 // If it overlaps no elements, then it is safe to process as padding. 1882 return true; 1883 } 1884 1885 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1886 const RecordDecl *RD = RT->getDecl(); 1887 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1888 1889 // If this is a C++ record, check the bases first. 1890 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1891 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 1892 e = CXXRD->bases_end(); i != e; ++i) { 1893 assert(!i->isVirtual() && !i->getType()->isDependentType() && 1894 "Unexpected base class!"); 1895 const CXXRecordDecl *Base = 1896 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 1897 1898 // If the base is after the span we care about, ignore it. 1899 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 1900 if (BaseOffset >= EndBit) continue; 1901 1902 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 1903 if (!BitsContainNoUserData(i->getType(), BaseStart, 1904 EndBit-BaseOffset, Context)) 1905 return false; 1906 } 1907 } 1908 1909 // Verify that no field has data that overlaps the region of interest. Yes 1910 // this could be sped up a lot by being smarter about queried fields, 1911 // however we're only looking at structs up to 16 bytes, so we don't care 1912 // much. 1913 unsigned idx = 0; 1914 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 1915 i != e; ++i, ++idx) { 1916 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 1917 1918 // If we found a field after the region we care about, then we're done. 1919 if (FieldOffset >= EndBit) break; 1920 1921 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 1922 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 1923 Context)) 1924 return false; 1925 } 1926 1927 // If nothing in this record overlapped the area of interest, then we're 1928 // clean. 1929 return true; 1930 } 1931 1932 return false; 1933} 1934 1935/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 1936/// float member at the specified offset. For example, {int,{float}} has a 1937/// float at offset 4. It is conservatively correct for this routine to return 1938/// false. 1939static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 1940 const llvm::DataLayout &TD) { 1941 // Base case if we find a float. 1942 if (IROffset == 0 && IRType->isFloatTy()) 1943 return true; 1944 1945 // If this is a struct, recurse into the field at the specified offset. 1946 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 1947 const llvm::StructLayout *SL = TD.getStructLayout(STy); 1948 unsigned Elt = SL->getElementContainingOffset(IROffset); 1949 IROffset -= SL->getElementOffset(Elt); 1950 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 1951 } 1952 1953 // If this is an array, recurse into the field at the specified offset. 1954 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 1955 llvm::Type *EltTy = ATy->getElementType(); 1956 unsigned EltSize = TD.getTypeAllocSize(EltTy); 1957 IROffset -= IROffset/EltSize*EltSize; 1958 return ContainsFloatAtOffset(EltTy, IROffset, TD); 1959 } 1960 1961 return false; 1962} 1963 1964 1965/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 1966/// low 8 bytes of an XMM register, corresponding to the SSE class. 1967llvm::Type *X86_64ABIInfo:: 1968GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 1969 QualType SourceTy, unsigned SourceOffset) const { 1970 // The only three choices we have are either double, <2 x float>, or float. We 1971 // pass as float if the last 4 bytes is just padding. This happens for 1972 // structs that contain 3 floats. 1973 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 1974 SourceOffset*8+64, getContext())) 1975 return llvm::Type::getFloatTy(getVMContext()); 1976 1977 // We want to pass as <2 x float> if the LLVM IR type contains a float at 1978 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 1979 // case. 1980 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 1981 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) 1982 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2); 1983 1984 return llvm::Type::getDoubleTy(getVMContext()); 1985} 1986 1987 1988/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 1989/// an 8-byte GPR. This means that we either have a scalar or we are talking 1990/// about the high or low part of an up-to-16-byte struct. This routine picks 1991/// the best LLVM IR type to represent this, which may be i64 or may be anything 1992/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 1993/// etc). 1994/// 1995/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 1996/// the source type. IROffset is an offset in bytes into the LLVM IR type that 1997/// the 8-byte value references. PrefType may be null. 1998/// 1999/// SourceTy is the source level type for the entire argument. SourceOffset is 2000/// an offset into this that we're processing (which is always either 0 or 8). 2001/// 2002llvm::Type *X86_64ABIInfo:: 2003GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 2004 QualType SourceTy, unsigned SourceOffset) const { 2005 // If we're dealing with an un-offset LLVM IR type, then it means that we're 2006 // returning an 8-byte unit starting with it. See if we can safely use it. 2007 if (IROffset == 0) { 2008 // Pointers and int64's always fill the 8-byte unit. 2009 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 2010 IRType->isIntegerTy(64)) 2011 return IRType; 2012 2013 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 2014 // goodness in the source type is just tail padding. This is allowed to 2015 // kick in for struct {double,int} on the int, but not on 2016 // struct{double,int,int} because we wouldn't return the second int. We 2017 // have to do this analysis on the source type because we can't depend on 2018 // unions being lowered a specific way etc. 2019 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 2020 IRType->isIntegerTy(32) || 2021 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 2022 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 2023 cast<llvm::IntegerType>(IRType)->getBitWidth(); 2024 2025 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 2026 SourceOffset*8+64, getContext())) 2027 return IRType; 2028 } 2029 } 2030 2031 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 2032 // If this is a struct, recurse into the field at the specified offset. 2033 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 2034 if (IROffset < SL->getSizeInBytes()) { 2035 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 2036 IROffset -= SL->getElementOffset(FieldIdx); 2037 2038 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 2039 SourceTy, SourceOffset); 2040 } 2041 } 2042 2043 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 2044 llvm::Type *EltTy = ATy->getElementType(); 2045 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 2046 unsigned EltOffset = IROffset/EltSize*EltSize; 2047 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 2048 SourceOffset); 2049 } 2050 2051 // Okay, we don't have any better idea of what to pass, so we pass this in an 2052 // integer register that isn't too big to fit the rest of the struct. 2053 unsigned TySizeInBytes = 2054 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 2055 2056 assert(TySizeInBytes != SourceOffset && "Empty field?"); 2057 2058 // It is always safe to classify this as an integer type up to i64 that 2059 // isn't larger than the structure. 2060 return llvm::IntegerType::get(getVMContext(), 2061 std::min(TySizeInBytes-SourceOffset, 8U)*8); 2062} 2063 2064 2065/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 2066/// be used as elements of a two register pair to pass or return, return a 2067/// first class aggregate to represent them. For example, if the low part of 2068/// a by-value argument should be passed as i32* and the high part as float, 2069/// return {i32*, float}. 2070static llvm::Type * 2071GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 2072 const llvm::DataLayout &TD) { 2073 // In order to correctly satisfy the ABI, we need to the high part to start 2074 // at offset 8. If the high and low parts we inferred are both 4-byte types 2075 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 2076 // the second element at offset 8. Check for this: 2077 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 2078 unsigned HiAlign = TD.getABITypeAlignment(Hi); 2079 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign); 2080 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 2081 2082 // To handle this, we have to increase the size of the low part so that the 2083 // second element will start at an 8 byte offset. We can't increase the size 2084 // of the second element because it might make us access off the end of the 2085 // struct. 2086 if (HiStart != 8) { 2087 // There are only two sorts of types the ABI generation code can produce for 2088 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32. 2089 // Promote these to a larger type. 2090 if (Lo->isFloatTy()) 2091 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 2092 else { 2093 assert(Lo->isIntegerTy() && "Invalid/unknown lo type"); 2094 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 2095 } 2096 } 2097 2098 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL); 2099 2100 2101 // Verify that the second element is at an 8-byte offset. 2102 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 2103 "Invalid x86-64 argument pair!"); 2104 return Result; 2105} 2106 2107ABIArgInfo X86_64ABIInfo:: 2108classifyReturnType(QualType RetTy) const { 2109 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 2110 // classification algorithm. 2111 X86_64ABIInfo::Class Lo, Hi; 2112 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 2113 2114 // Check some invariants. 2115 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 2116 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 2117 2118 llvm::Type *ResType = 0; 2119 switch (Lo) { 2120 case NoClass: 2121 if (Hi == NoClass) 2122 return ABIArgInfo::getIgnore(); 2123 // If the low part is just padding, it takes no register, leave ResType 2124 // null. 2125 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 2126 "Unknown missing lo part"); 2127 break; 2128 2129 case SSEUp: 2130 case X87Up: 2131 llvm_unreachable("Invalid classification for lo word."); 2132 2133 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 2134 // hidden argument. 2135 case Memory: 2136 return getIndirectReturnResult(RetTy); 2137 2138 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 2139 // available register of the sequence %rax, %rdx is used. 2140 case Integer: 2141 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 2142 2143 // If we have a sign or zero extended integer, make sure to return Extend 2144 // so that the parameter gets the right LLVM IR attributes. 2145 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 2146 // Treat an enum type as its underlying type. 2147 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 2148 RetTy = EnumTy->getDecl()->getIntegerType(); 2149 2150 if (RetTy->isIntegralOrEnumerationType() && 2151 RetTy->isPromotableIntegerType()) 2152 return ABIArgInfo::getExtend(); 2153 } 2154 break; 2155 2156 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 2157 // available SSE register of the sequence %xmm0, %xmm1 is used. 2158 case SSE: 2159 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 2160 break; 2161 2162 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 2163 // returned on the X87 stack in %st0 as 80-bit x87 number. 2164 case X87: 2165 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 2166 break; 2167 2168 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 2169 // part of the value is returned in %st0 and the imaginary part in 2170 // %st1. 2171 case ComplexX87: 2172 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 2173 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 2174 llvm::Type::getX86_FP80Ty(getVMContext()), 2175 NULL); 2176 break; 2177 } 2178 2179 llvm::Type *HighPart = 0; 2180 switch (Hi) { 2181 // Memory was handled previously and X87 should 2182 // never occur as a hi class. 2183 case Memory: 2184 case X87: 2185 llvm_unreachable("Invalid classification for hi word."); 2186 2187 case ComplexX87: // Previously handled. 2188 case NoClass: 2189 break; 2190 2191 case Integer: 2192 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 2193 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 2194 return ABIArgInfo::getDirect(HighPart, 8); 2195 break; 2196 case SSE: 2197 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 2198 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 2199 return ABIArgInfo::getDirect(HighPart, 8); 2200 break; 2201 2202 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 2203 // is passed in the next available eightbyte chunk if the last used 2204 // vector register. 2205 // 2206 // SSEUP should always be preceded by SSE, just widen. 2207 case SSEUp: 2208 assert(Lo == SSE && "Unexpected SSEUp classification."); 2209 ResType = GetByteVectorType(RetTy); 2210 break; 2211 2212 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 2213 // returned together with the previous X87 value in %st0. 2214 case X87Up: 2215 // If X87Up is preceded by X87, we don't need to do 2216 // anything. However, in some cases with unions it may not be 2217 // preceded by X87. In such situations we follow gcc and pass the 2218 // extra bits in an SSE reg. 2219 if (Lo != X87) { 2220 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 2221 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 2222 return ABIArgInfo::getDirect(HighPart, 8); 2223 } 2224 break; 2225 } 2226 2227 // If a high part was specified, merge it together with the low part. It is 2228 // known to pass in the high eightbyte of the result. We do this by forming a 2229 // first class struct aggregate with the high and low part: {low, high} 2230 if (HighPart) 2231 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 2232 2233 return ABIArgInfo::getDirect(ResType); 2234} 2235 2236ABIArgInfo X86_64ABIInfo::classifyArgumentType( 2237 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 2238 bool isNamedArg) 2239 const 2240{ 2241 X86_64ABIInfo::Class Lo, Hi; 2242 classify(Ty, 0, Lo, Hi, isNamedArg); 2243 2244 // Check some invariants. 2245 // FIXME: Enforce these by construction. 2246 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 2247 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 2248 2249 neededInt = 0; 2250 neededSSE = 0; 2251 llvm::Type *ResType = 0; 2252 switch (Lo) { 2253 case NoClass: 2254 if (Hi == NoClass) 2255 return ABIArgInfo::getIgnore(); 2256 // If the low part is just padding, it takes no register, leave ResType 2257 // null. 2258 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 2259 "Unknown missing lo part"); 2260 break; 2261 2262 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 2263 // on the stack. 2264 case Memory: 2265 2266 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 2267 // COMPLEX_X87, it is passed in memory. 2268 case X87: 2269 case ComplexX87: 2270 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 2271 ++neededInt; 2272 return getIndirectResult(Ty, freeIntRegs); 2273 2274 case SSEUp: 2275 case X87Up: 2276 llvm_unreachable("Invalid classification for lo word."); 2277 2278 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 2279 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 2280 // and %r9 is used. 2281 case Integer: 2282 ++neededInt; 2283 2284 // Pick an 8-byte type based on the preferred type. 2285 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 2286 2287 // If we have a sign or zero extended integer, make sure to return Extend 2288 // so that the parameter gets the right LLVM IR attributes. 2289 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 2290 // Treat an enum type as its underlying type. 2291 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2292 Ty = EnumTy->getDecl()->getIntegerType(); 2293 2294 if (Ty->isIntegralOrEnumerationType() && 2295 Ty->isPromotableIntegerType()) 2296 return ABIArgInfo::getExtend(); 2297 } 2298 2299 break; 2300 2301 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 2302 // available SSE register is used, the registers are taken in the 2303 // order from %xmm0 to %xmm7. 2304 case SSE: { 2305 llvm::Type *IRType = CGT.ConvertType(Ty); 2306 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 2307 ++neededSSE; 2308 break; 2309 } 2310 } 2311 2312 llvm::Type *HighPart = 0; 2313 switch (Hi) { 2314 // Memory was handled previously, ComplexX87 and X87 should 2315 // never occur as hi classes, and X87Up must be preceded by X87, 2316 // which is passed in memory. 2317 case Memory: 2318 case X87: 2319 case ComplexX87: 2320 llvm_unreachable("Invalid classification for hi word."); 2321 2322 case NoClass: break; 2323 2324 case Integer: 2325 ++neededInt; 2326 // Pick an 8-byte type based on the preferred type. 2327 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 2328 2329 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 2330 return ABIArgInfo::getDirect(HighPart, 8); 2331 break; 2332 2333 // X87Up generally doesn't occur here (long double is passed in 2334 // memory), except in situations involving unions. 2335 case X87Up: 2336 case SSE: 2337 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 2338 2339 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 2340 return ABIArgInfo::getDirect(HighPart, 8); 2341 2342 ++neededSSE; 2343 break; 2344 2345 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 2346 // eightbyte is passed in the upper half of the last used SSE 2347 // register. This only happens when 128-bit vectors are passed. 2348 case SSEUp: 2349 assert(Lo == SSE && "Unexpected SSEUp classification"); 2350 ResType = GetByteVectorType(Ty); 2351 break; 2352 } 2353 2354 // If a high part was specified, merge it together with the low part. It is 2355 // known to pass in the high eightbyte of the result. We do this by forming a 2356 // first class struct aggregate with the high and low part: {low, high} 2357 if (HighPart) 2358 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 2359 2360 return ABIArgInfo::getDirect(ResType); 2361} 2362 2363void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2364 2365 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 2366 2367 // Keep track of the number of assigned registers. 2368 unsigned freeIntRegs = 6, freeSSERegs = 8; 2369 2370 // If the return value is indirect, then the hidden argument is consuming one 2371 // integer register. 2372 if (FI.getReturnInfo().isIndirect()) 2373 --freeIntRegs; 2374 2375 bool isVariadic = FI.isVariadic(); 2376 unsigned numRequiredArgs = 0; 2377 if (isVariadic) 2378 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs(); 2379 2380 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 2381 // get assigned (in left-to-right order) for passing as follows... 2382 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2383 it != ie; ++it) { 2384 bool isNamedArg = true; 2385 if (isVariadic) 2386 isNamedArg = (it - FI.arg_begin()) < 2387 static_cast<signed>(numRequiredArgs); 2388 2389 unsigned neededInt, neededSSE; 2390 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt, 2391 neededSSE, isNamedArg); 2392 2393 // AMD64-ABI 3.2.3p3: If there are no registers available for any 2394 // eightbyte of an argument, the whole argument is passed on the 2395 // stack. If registers have already been assigned for some 2396 // eightbytes of such an argument, the assignments get reverted. 2397 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) { 2398 freeIntRegs -= neededInt; 2399 freeSSERegs -= neededSSE; 2400 } else { 2401 it->info = getIndirectResult(it->type, freeIntRegs); 2402 } 2403 } 2404} 2405 2406static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr, 2407 QualType Ty, 2408 CodeGenFunction &CGF) { 2409 llvm::Value *overflow_arg_area_p = 2410 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 2411 llvm::Value *overflow_arg_area = 2412 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 2413 2414 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 2415 // byte boundary if alignment needed by type exceeds 8 byte boundary. 2416 // It isn't stated explicitly in the standard, but in practice we use 2417 // alignment greater than 16 where necessary. 2418 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 2419 if (Align > 8) { 2420 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 2421 llvm::Value *Offset = 2422 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 2423 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset); 2424 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area, 2425 CGF.Int64Ty); 2426 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align); 2427 overflow_arg_area = 2428 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask), 2429 overflow_arg_area->getType(), 2430 "overflow_arg_area.align"); 2431 } 2432 2433 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 2434 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 2435 llvm::Value *Res = 2436 CGF.Builder.CreateBitCast(overflow_arg_area, 2437 llvm::PointerType::getUnqual(LTy)); 2438 2439 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 2440 // l->overflow_arg_area + sizeof(type). 2441 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 2442 // an 8 byte boundary. 2443 2444 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 2445 llvm::Value *Offset = 2446 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 2447 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 2448 "overflow_arg_area.next"); 2449 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 2450 2451 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 2452 return Res; 2453} 2454 2455llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2456 CodeGenFunction &CGF) const { 2457 // Assume that va_list type is correct; should be pointer to LLVM type: 2458 // struct { 2459 // i32 gp_offset; 2460 // i32 fp_offset; 2461 // i8* overflow_arg_area; 2462 // i8* reg_save_area; 2463 // }; 2464 unsigned neededInt, neededSSE; 2465 2466 Ty = CGF.getContext().getCanonicalType(Ty); 2467 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 2468 /*isNamedArg*/false); 2469 2470 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 2471 // in the registers. If not go to step 7. 2472 if (!neededInt && !neededSSE) 2473 return EmitVAArgFromMemory(VAListAddr, Ty, CGF); 2474 2475 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 2476 // general purpose registers needed to pass type and num_fp to hold 2477 // the number of floating point registers needed. 2478 2479 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 2480 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 2481 // l->fp_offset > 304 - num_fp * 16 go to step 7. 2482 // 2483 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 2484 // register save space). 2485 2486 llvm::Value *InRegs = 0; 2487 llvm::Value *gp_offset_p = 0, *gp_offset = 0; 2488 llvm::Value *fp_offset_p = 0, *fp_offset = 0; 2489 if (neededInt) { 2490 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 2491 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 2492 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 2493 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 2494 } 2495 2496 if (neededSSE) { 2497 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 2498 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 2499 llvm::Value *FitsInFP = 2500 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 2501 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 2502 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 2503 } 2504 2505 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 2506 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 2507 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 2508 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 2509 2510 // Emit code to load the value if it was passed in registers. 2511 2512 CGF.EmitBlock(InRegBlock); 2513 2514 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 2515 // an offset of l->gp_offset and/or l->fp_offset. This may require 2516 // copying to a temporary location in case the parameter is passed 2517 // in different register classes or requires an alignment greater 2518 // than 8 for general purpose registers and 16 for XMM registers. 2519 // 2520 // FIXME: This really results in shameful code when we end up needing to 2521 // collect arguments from different places; often what should result in a 2522 // simple assembling of a structure from scattered addresses has many more 2523 // loads than necessary. Can we clean this up? 2524 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 2525 llvm::Value *RegAddr = 2526 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3), 2527 "reg_save_area"); 2528 if (neededInt && neededSSE) { 2529 // FIXME: Cleanup. 2530 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 2531 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 2532 llvm::Value *Tmp = CGF.CreateMemTemp(Ty); 2533 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo()); 2534 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 2535 llvm::Type *TyLo = ST->getElementType(0); 2536 llvm::Type *TyHi = ST->getElementType(1); 2537 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 2538 "Unexpected ABI info for mixed regs"); 2539 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 2540 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 2541 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset); 2542 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2543 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr; 2544 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr; 2545 llvm::Value *V = 2546 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo)); 2547 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 2548 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi)); 2549 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 2550 2551 RegAddr = CGF.Builder.CreateBitCast(Tmp, 2552 llvm::PointerType::getUnqual(LTy)); 2553 } else if (neededInt) { 2554 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset); 2555 RegAddr = CGF.Builder.CreateBitCast(RegAddr, 2556 llvm::PointerType::getUnqual(LTy)); 2557 2558 // Copy to a temporary if necessary to ensure the appropriate alignment. 2559 std::pair<CharUnits, CharUnits> SizeAlign = 2560 CGF.getContext().getTypeInfoInChars(Ty); 2561 uint64_t TySize = SizeAlign.first.getQuantity(); 2562 unsigned TyAlign = SizeAlign.second.getQuantity(); 2563 if (TyAlign > 8) { 2564 llvm::Value *Tmp = CGF.CreateMemTemp(Ty); 2565 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false); 2566 RegAddr = Tmp; 2567 } 2568 } else if (neededSSE == 1) { 2569 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2570 RegAddr = CGF.Builder.CreateBitCast(RegAddr, 2571 llvm::PointerType::getUnqual(LTy)); 2572 } else { 2573 assert(neededSSE == 2 && "Invalid number of needed registers!"); 2574 // SSE registers are spaced 16 bytes apart in the register save 2575 // area, we need to collect the two eightbytes together. 2576 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2577 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16); 2578 llvm::Type *DoubleTy = CGF.DoubleTy; 2579 llvm::Type *DblPtrTy = 2580 llvm::PointerType::getUnqual(DoubleTy); 2581 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL); 2582 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty); 2583 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo()); 2584 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo, 2585 DblPtrTy)); 2586 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 2587 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi, 2588 DblPtrTy)); 2589 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 2590 RegAddr = CGF.Builder.CreateBitCast(Tmp, 2591 llvm::PointerType::getUnqual(LTy)); 2592 } 2593 2594 // AMD64-ABI 3.5.7p5: Step 5. Set: 2595 // l->gp_offset = l->gp_offset + num_gp * 8 2596 // l->fp_offset = l->fp_offset + num_fp * 16. 2597 if (neededInt) { 2598 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 2599 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 2600 gp_offset_p); 2601 } 2602 if (neededSSE) { 2603 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 2604 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 2605 fp_offset_p); 2606 } 2607 CGF.EmitBranch(ContBlock); 2608 2609 // Emit code to load the value if it was passed in memory. 2610 2611 CGF.EmitBlock(InMemBlock); 2612 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF); 2613 2614 // Return the appropriate result. 2615 2616 CGF.EmitBlock(ContBlock); 2617 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2, 2618 "vaarg.addr"); 2619 ResAddr->addIncoming(RegAddr, InRegBlock); 2620 ResAddr->addIncoming(MemAddr, InMemBlock); 2621 return ResAddr; 2622} 2623 2624ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const { 2625 2626 if (Ty->isVoidType()) 2627 return ABIArgInfo::getIgnore(); 2628 2629 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2630 Ty = EnumTy->getDecl()->getIntegerType(); 2631 2632 uint64_t Size = getContext().getTypeSize(Ty); 2633 2634 if (const RecordType *RT = Ty->getAs<RecordType>()) { 2635 if (IsReturnType) { 2636 if (isRecordReturnIndirect(RT, getCXXABI())) 2637 return ABIArgInfo::getIndirect(0, false); 2638 } else { 2639 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 2640 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 2641 } 2642 2643 if (RT->getDecl()->hasFlexibleArrayMember()) 2644 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2645 2646 // FIXME: mingw-w64-gcc emits 128-bit struct as i128 2647 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32) 2648 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2649 Size)); 2650 2651 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 2652 // not 1, 2, 4, or 8 bytes, must be passed by reference." 2653 if (Size <= 64 && 2654 (Size & (Size - 1)) == 0) 2655 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2656 Size)); 2657 2658 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2659 } 2660 2661 if (Ty->isPromotableIntegerType()) 2662 return ABIArgInfo::getExtend(); 2663 2664 return ABIArgInfo::getDirect(); 2665} 2666 2667void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2668 2669 QualType RetTy = FI.getReturnType(); 2670 FI.getReturnInfo() = classify(RetTy, true); 2671 2672 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2673 it != ie; ++it) 2674 it->info = classify(it->type, false); 2675} 2676 2677llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2678 CodeGenFunction &CGF) const { 2679 llvm::Type *BPP = CGF.Int8PtrPtrTy; 2680 2681 CGBuilderTy &Builder = CGF.Builder; 2682 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 2683 "ap"); 2684 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 2685 llvm::Type *PTy = 2686 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 2687 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 2688 2689 uint64_t Offset = 2690 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8); 2691 llvm::Value *NextAddr = 2692 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 2693 "ap.next"); 2694 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 2695 2696 return AddrTyped; 2697} 2698 2699namespace { 2700 2701class NaClX86_64ABIInfo : public ABIInfo { 2702 public: 2703 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 2704 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {} 2705 virtual void computeInfo(CGFunctionInfo &FI) const; 2706 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2707 CodeGenFunction &CGF) const; 2708 private: 2709 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv. 2710 X86_64ABIInfo NInfo; // Used for everything else. 2711}; 2712 2713class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2714 public: 2715 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 2716 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {} 2717}; 2718 2719} 2720 2721void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2722 if (FI.getASTCallingConvention() == CC_PnaclCall) 2723 PInfo.computeInfo(FI); 2724 else 2725 NInfo.computeInfo(FI); 2726} 2727 2728llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2729 CodeGenFunction &CGF) const { 2730 // Always use the native convention; calling pnacl-style varargs functions 2731 // is unuspported. 2732 return NInfo.EmitVAArg(VAListAddr, Ty, CGF); 2733} 2734 2735 2736// PowerPC-32 2737 2738namespace { 2739class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 2740public: 2741 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 2742 2743 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 2744 // This is recovered from gcc output. 2745 return 1; // r1 is the dedicated stack pointer 2746 } 2747 2748 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2749 llvm::Value *Address) const; 2750}; 2751 2752} 2753 2754bool 2755PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2756 llvm::Value *Address) const { 2757 // This is calculated from the LLVM and GCC tables and verified 2758 // against gcc output. AFAIK all ABIs use the same encoding. 2759 2760 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2761 2762 llvm::IntegerType *i8 = CGF.Int8Ty; 2763 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 2764 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 2765 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 2766 2767 // 0-31: r0-31, the 4-byte general-purpose registers 2768 AssignToArrayRange(Builder, Address, Four8, 0, 31); 2769 2770 // 32-63: fp0-31, the 8-byte floating-point registers 2771 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 2772 2773 // 64-76 are various 4-byte special-purpose registers: 2774 // 64: mq 2775 // 65: lr 2776 // 66: ctr 2777 // 67: ap 2778 // 68-75 cr0-7 2779 // 76: xer 2780 AssignToArrayRange(Builder, Address, Four8, 64, 76); 2781 2782 // 77-108: v0-31, the 16-byte vector registers 2783 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 2784 2785 // 109: vrsave 2786 // 110: vscr 2787 // 111: spe_acc 2788 // 112: spefscr 2789 // 113: sfp 2790 AssignToArrayRange(Builder, Address, Four8, 109, 113); 2791 2792 return false; 2793} 2794 2795// PowerPC-64 2796 2797namespace { 2798/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 2799class PPC64_SVR4_ABIInfo : public DefaultABIInfo { 2800 2801public: 2802 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 2803 2804 bool isPromotableTypeForABI(QualType Ty) const; 2805 2806 ABIArgInfo classifyReturnType(QualType RetTy) const; 2807 ABIArgInfo classifyArgumentType(QualType Ty) const; 2808 2809 // TODO: We can add more logic to computeInfo to improve performance. 2810 // Example: For aggregate arguments that fit in a register, we could 2811 // use getDirectInReg (as is done below for structs containing a single 2812 // floating-point value) to avoid pushing them to memory on function 2813 // entry. This would require changing the logic in PPCISelLowering 2814 // when lowering the parameters in the caller and args in the callee. 2815 virtual void computeInfo(CGFunctionInfo &FI) const { 2816 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 2817 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2818 it != ie; ++it) { 2819 // We rely on the default argument classification for the most part. 2820 // One exception: An aggregate containing a single floating-point 2821 // or vector item must be passed in a register if one is available. 2822 const Type *T = isSingleElementStruct(it->type, getContext()); 2823 if (T) { 2824 const BuiltinType *BT = T->getAs<BuiltinType>(); 2825 if (T->isVectorType() || (BT && BT->isFloatingPoint())) { 2826 QualType QT(T, 0); 2827 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 2828 continue; 2829 } 2830 } 2831 it->info = classifyArgumentType(it->type); 2832 } 2833 } 2834 2835 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, 2836 QualType Ty, 2837 CodeGenFunction &CGF) const; 2838}; 2839 2840class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 2841public: 2842 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT) 2843 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {} 2844 2845 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 2846 // This is recovered from gcc output. 2847 return 1; // r1 is the dedicated stack pointer 2848 } 2849 2850 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2851 llvm::Value *Address) const; 2852}; 2853 2854class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 2855public: 2856 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 2857 2858 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 2859 // This is recovered from gcc output. 2860 return 1; // r1 is the dedicated stack pointer 2861 } 2862 2863 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2864 llvm::Value *Address) const; 2865}; 2866 2867} 2868 2869// Return true if the ABI requires Ty to be passed sign- or zero- 2870// extended to 64 bits. 2871bool 2872PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 2873 // Treat an enum type as its underlying type. 2874 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2875 Ty = EnumTy->getDecl()->getIntegerType(); 2876 2877 // Promotable integer types are required to be promoted by the ABI. 2878 if (Ty->isPromotableIntegerType()) 2879 return true; 2880 2881 // In addition to the usual promotable integer types, we also need to 2882 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 2883 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 2884 switch (BT->getKind()) { 2885 case BuiltinType::Int: 2886 case BuiltinType::UInt: 2887 return true; 2888 default: 2889 break; 2890 } 2891 2892 return false; 2893} 2894 2895ABIArgInfo 2896PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 2897 if (Ty->isAnyComplexType()) 2898 return ABIArgInfo::getDirect(); 2899 2900 if (isAggregateTypeForABI(Ty)) { 2901 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 2902 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 2903 2904 return ABIArgInfo::getIndirect(0); 2905 } 2906 2907 return (isPromotableTypeForABI(Ty) ? 2908 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 2909} 2910 2911ABIArgInfo 2912PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 2913 if (RetTy->isVoidType()) 2914 return ABIArgInfo::getIgnore(); 2915 2916 if (RetTy->isAnyComplexType()) 2917 return ABIArgInfo::getDirect(); 2918 2919 if (isAggregateTypeForABI(RetTy)) 2920 return ABIArgInfo::getIndirect(0); 2921 2922 return (isPromotableTypeForABI(RetTy) ? 2923 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 2924} 2925 2926// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 2927llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr, 2928 QualType Ty, 2929 CodeGenFunction &CGF) const { 2930 llvm::Type *BP = CGF.Int8PtrTy; 2931 llvm::Type *BPP = CGF.Int8PtrPtrTy; 2932 2933 CGBuilderTy &Builder = CGF.Builder; 2934 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 2935 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 2936 2937 // Update the va_list pointer. The pointer should be bumped by the 2938 // size of the object. We can trust getTypeSize() except for a complex 2939 // type whose base type is smaller than a doubleword. For these, the 2940 // size of the object is 16 bytes; see below for further explanation. 2941 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8; 2942 QualType BaseTy; 2943 unsigned CplxBaseSize = 0; 2944 2945 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 2946 BaseTy = CTy->getElementType(); 2947 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8; 2948 if (CplxBaseSize < 8) 2949 SizeInBytes = 16; 2950 } 2951 2952 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8); 2953 llvm::Value *NextAddr = 2954 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), 2955 "ap.next"); 2956 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 2957 2958 // If we have a complex type and the base type is smaller than 8 bytes, 2959 // the ABI calls for the real and imaginary parts to be right-adjusted 2960 // in separate doublewords. However, Clang expects us to produce a 2961 // pointer to a structure with the two parts packed tightly. So generate 2962 // loads of the real and imaginary parts relative to the va_list pointer, 2963 // and store them to a temporary structure. 2964 if (CplxBaseSize && CplxBaseSize < 8) { 2965 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty); 2966 llvm::Value *ImagAddr = RealAddr; 2967 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize)); 2968 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize)); 2969 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy)); 2970 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy); 2971 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy); 2972 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal"); 2973 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag"); 2974 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty), 2975 "vacplx"); 2976 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real"); 2977 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag"); 2978 Builder.CreateStore(Real, RealPtr, false); 2979 Builder.CreateStore(Imag, ImagPtr, false); 2980 return Ptr; 2981 } 2982 2983 // If the argument is smaller than 8 bytes, it is right-adjusted in 2984 // its doubleword slot. Adjust the pointer to pick it up from the 2985 // correct offset. 2986 if (SizeInBytes < 8) { 2987 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty); 2988 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes)); 2989 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 2990 } 2991 2992 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 2993 return Builder.CreateBitCast(Addr, PTy); 2994} 2995 2996static bool 2997PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2998 llvm::Value *Address) { 2999 // This is calculated from the LLVM and GCC tables and verified 3000 // against gcc output. AFAIK all ABIs use the same encoding. 3001 3002 CodeGen::CGBuilderTy &Builder = CGF.Builder; 3003 3004 llvm::IntegerType *i8 = CGF.Int8Ty; 3005 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 3006 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 3007 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 3008 3009 // 0-31: r0-31, the 8-byte general-purpose registers 3010 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 3011 3012 // 32-63: fp0-31, the 8-byte floating-point registers 3013 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 3014 3015 // 64-76 are various 4-byte special-purpose registers: 3016 // 64: mq 3017 // 65: lr 3018 // 66: ctr 3019 // 67: ap 3020 // 68-75 cr0-7 3021 // 76: xer 3022 AssignToArrayRange(Builder, Address, Four8, 64, 76); 3023 3024 // 77-108: v0-31, the 16-byte vector registers 3025 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 3026 3027 // 109: vrsave 3028 // 110: vscr 3029 // 111: spe_acc 3030 // 112: spefscr 3031 // 113: sfp 3032 AssignToArrayRange(Builder, Address, Four8, 109, 113); 3033 3034 return false; 3035} 3036 3037bool 3038PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 3039 CodeGen::CodeGenFunction &CGF, 3040 llvm::Value *Address) const { 3041 3042 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 3043} 3044 3045bool 3046PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3047 llvm::Value *Address) const { 3048 3049 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 3050} 3051 3052//===----------------------------------------------------------------------===// 3053// ARM ABI Implementation 3054//===----------------------------------------------------------------------===// 3055 3056namespace { 3057 3058class ARMABIInfo : public ABIInfo { 3059public: 3060 enum ABIKind { 3061 APCS = 0, 3062 AAPCS = 1, 3063 AAPCS_VFP 3064 }; 3065 3066private: 3067 ABIKind Kind; 3068 3069public: 3070 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) { 3071 setRuntimeCC(); 3072 } 3073 3074 bool isEABI() const { 3075 StringRef Env = getTarget().getTriple().getEnvironmentName(); 3076 return (Env == "gnueabi" || Env == "eabi" || 3077 Env == "android" || Env == "androideabi"); 3078 } 3079 3080 ABIKind getABIKind() const { return Kind; } 3081 3082private: 3083 ABIArgInfo classifyReturnType(QualType RetTy) const; 3084 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs, 3085 unsigned &AllocatedVFP, 3086 bool &IsHA) const; 3087 bool isIllegalVectorType(QualType Ty) const; 3088 3089 virtual void computeInfo(CGFunctionInfo &FI) const; 3090 3091 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3092 CodeGenFunction &CGF) const; 3093 3094 llvm::CallingConv::ID getLLVMDefaultCC() const; 3095 llvm::CallingConv::ID getABIDefaultCC() const; 3096 void setRuntimeCC(); 3097}; 3098 3099class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 3100public: 3101 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 3102 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {} 3103 3104 const ARMABIInfo &getABIInfo() const { 3105 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 3106 } 3107 3108 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 3109 return 13; 3110 } 3111 3112 StringRef getARCRetainAutoreleasedReturnValueMarker() const { 3113 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue"; 3114 } 3115 3116 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3117 llvm::Value *Address) const { 3118 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 3119 3120 // 0-15 are the 16 integer registers. 3121 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 3122 return false; 3123 } 3124 3125 unsigned getSizeOfUnwindException() const { 3126 if (getABIInfo().isEABI()) return 88; 3127 return TargetCodeGenInfo::getSizeOfUnwindException(); 3128 } 3129 3130 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 3131 CodeGen::CodeGenModule &CGM) const { 3132 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 3133 if (!FD) 3134 return; 3135 3136 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 3137 if (!Attr) 3138 return; 3139 3140 const char *Kind; 3141 switch (Attr->getInterrupt()) { 3142 case ARMInterruptAttr::Generic: Kind = ""; break; 3143 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 3144 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 3145 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 3146 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 3147 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 3148 } 3149 3150 llvm::Function *Fn = cast<llvm::Function>(GV); 3151 3152 Fn->addFnAttr("interrupt", Kind); 3153 3154 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS) 3155 return; 3156 3157 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 3158 // however this is not necessarily true on taking any interrupt. Instruct 3159 // the backend to perform a realignment as part of the function prologue. 3160 llvm::AttrBuilder B; 3161 B.addStackAlignmentAttr(8); 3162 Fn->addAttributes(llvm::AttributeSet::FunctionIndex, 3163 llvm::AttributeSet::get(CGM.getLLVMContext(), 3164 llvm::AttributeSet::FunctionIndex, 3165 B)); 3166 } 3167 3168}; 3169 3170} 3171 3172void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 3173 // To correctly handle Homogeneous Aggregate, we need to keep track of the 3174 // VFP registers allocated so far. 3175 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive 3176 // VFP registers of the appropriate type unallocated then the argument is 3177 // allocated to the lowest-numbered sequence of such registers. 3178 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are 3179 // unallocated are marked as unavailable. 3180 unsigned AllocatedVFP = 0; 3181 int VFPRegs[16] = { 0 }; 3182 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3183 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3184 it != ie; ++it) { 3185 unsigned PreAllocation = AllocatedVFP; 3186 bool IsHA = false; 3187 // 6.1.2.3 There is one VFP co-processor register class using registers 3188 // s0-s15 (d0-d7) for passing arguments. 3189 const unsigned NumVFPs = 16; 3190 it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA); 3191 // If we do not have enough VFP registers for the HA, any VFP registers 3192 // that are unallocated are marked as unavailable. To achieve this, we add 3193 // padding of (NumVFPs - PreAllocation) floats. 3194 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) { 3195 llvm::Type *PaddingTy = llvm::ArrayType::get( 3196 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation); 3197 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy); 3198 } 3199 } 3200 3201 // Always honor user-specified calling convention. 3202 if (FI.getCallingConvention() != llvm::CallingConv::C) 3203 return; 3204 3205 llvm::CallingConv::ID cc = getRuntimeCC(); 3206 if (cc != llvm::CallingConv::C) 3207 FI.setEffectiveCallingConvention(cc); 3208} 3209 3210/// Return the default calling convention that LLVM will use. 3211llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 3212 // The default calling convention that LLVM will infer. 3213 if (getTarget().getTriple().getEnvironmentName()=="gnueabihf") 3214 return llvm::CallingConv::ARM_AAPCS_VFP; 3215 else if (isEABI()) 3216 return llvm::CallingConv::ARM_AAPCS; 3217 else 3218 return llvm::CallingConv::ARM_APCS; 3219} 3220 3221/// Return the calling convention that our ABI would like us to use 3222/// as the C calling convention. 3223llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 3224 switch (getABIKind()) { 3225 case APCS: return llvm::CallingConv::ARM_APCS; 3226 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 3227 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 3228 } 3229 llvm_unreachable("bad ABI kind"); 3230} 3231 3232void ARMABIInfo::setRuntimeCC() { 3233 assert(getRuntimeCC() == llvm::CallingConv::C); 3234 3235 // Don't muddy up the IR with a ton of explicit annotations if 3236 // they'd just match what LLVM will infer from the triple. 3237 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 3238 if (abiCC != getLLVMDefaultCC()) 3239 RuntimeCC = abiCC; 3240} 3241 3242/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous 3243/// aggregate. If HAMembers is non-null, the number of base elements 3244/// contained in the type is returned through it; this is used for the 3245/// recursive calls that check aggregate component types. 3246static bool isHomogeneousAggregate(QualType Ty, const Type *&Base, 3247 ASTContext &Context, 3248 uint64_t *HAMembers = 0) { 3249 uint64_t Members = 0; 3250 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3251 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members)) 3252 return false; 3253 Members *= AT->getSize().getZExtValue(); 3254 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 3255 const RecordDecl *RD = RT->getDecl(); 3256 if (RD->hasFlexibleArrayMember()) 3257 return false; 3258 3259 Members = 0; 3260 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3261 i != e; ++i) { 3262 const FieldDecl *FD = *i; 3263 uint64_t FldMembers; 3264 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers)) 3265 return false; 3266 3267 Members = (RD->isUnion() ? 3268 std::max(Members, FldMembers) : Members + FldMembers); 3269 } 3270 } else { 3271 Members = 1; 3272 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 3273 Members = 2; 3274 Ty = CT->getElementType(); 3275 } 3276 3277 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 3278 // double, or 64-bit or 128-bit vectors. 3279 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 3280 if (BT->getKind() != BuiltinType::Float && 3281 BT->getKind() != BuiltinType::Double && 3282 BT->getKind() != BuiltinType::LongDouble) 3283 return false; 3284 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 3285 unsigned VecSize = Context.getTypeSize(VT); 3286 if (VecSize != 64 && VecSize != 128) 3287 return false; 3288 } else { 3289 return false; 3290 } 3291 3292 // The base type must be the same for all members. Vector types of the 3293 // same total size are treated as being equivalent here. 3294 const Type *TyPtr = Ty.getTypePtr(); 3295 if (!Base) 3296 Base = TyPtr; 3297 if (Base != TyPtr && 3298 (!Base->isVectorType() || !TyPtr->isVectorType() || 3299 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr))) 3300 return false; 3301 } 3302 3303 // Homogeneous Aggregates can have at most 4 members of the base type. 3304 if (HAMembers) 3305 *HAMembers = Members; 3306 3307 return (Members > 0 && Members <= 4); 3308} 3309 3310/// markAllocatedVFPs - update VFPRegs according to the alignment and 3311/// number of VFP registers (unit is S register) requested. 3312static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP, 3313 unsigned Alignment, 3314 unsigned NumRequired) { 3315 // Early Exit. 3316 if (AllocatedVFP >= 16) 3317 return; 3318 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive 3319 // VFP registers of the appropriate type unallocated then the argument is 3320 // allocated to the lowest-numbered sequence of such registers. 3321 for (unsigned I = 0; I < 16; I += Alignment) { 3322 bool FoundSlot = true; 3323 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++) 3324 if (J >= 16 || VFPRegs[J]) { 3325 FoundSlot = false; 3326 break; 3327 } 3328 if (FoundSlot) { 3329 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++) 3330 VFPRegs[J] = 1; 3331 AllocatedVFP += NumRequired; 3332 return; 3333 } 3334 } 3335 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are 3336 // unallocated are marked as unavailable. 3337 for (unsigned I = 0; I < 16; I++) 3338 VFPRegs[I] = 1; 3339 AllocatedVFP = 17; // We do not have enough VFP registers. 3340} 3341 3342ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs, 3343 unsigned &AllocatedVFP, 3344 bool &IsHA) const { 3345 // We update number of allocated VFPs according to 3346 // 6.1.2.1 The following argument types are VFP CPRCs: 3347 // A single-precision floating-point type (including promoted 3348 // half-precision types); A double-precision floating-point type; 3349 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 3350 // with a Base Type of a single- or double-precision floating-point type, 3351 // 64-bit containerized vectors or 128-bit containerized vectors with one 3352 // to four Elements. 3353 3354 // Handle illegal vector types here. 3355 if (isIllegalVectorType(Ty)) { 3356 uint64_t Size = getContext().getTypeSize(Ty); 3357 if (Size <= 32) { 3358 llvm::Type *ResType = 3359 llvm::Type::getInt32Ty(getVMContext()); 3360 return ABIArgInfo::getDirect(ResType); 3361 } 3362 if (Size == 64) { 3363 llvm::Type *ResType = llvm::VectorType::get( 3364 llvm::Type::getInt32Ty(getVMContext()), 2); 3365 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2); 3366 return ABIArgInfo::getDirect(ResType); 3367 } 3368 if (Size == 128) { 3369 llvm::Type *ResType = llvm::VectorType::get( 3370 llvm::Type::getInt32Ty(getVMContext()), 4); 3371 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4); 3372 return ABIArgInfo::getDirect(ResType); 3373 } 3374 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3375 } 3376 // Update VFPRegs for legal vector types. 3377 if (const VectorType *VT = Ty->getAs<VectorType>()) { 3378 uint64_t Size = getContext().getTypeSize(VT); 3379 // Size of a legal vector should be power of 2 and above 64. 3380 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32); 3381 } 3382 // Update VFPRegs for floating point types. 3383 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 3384 if (BT->getKind() == BuiltinType::Half || 3385 BT->getKind() == BuiltinType::Float) 3386 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1); 3387 if (BT->getKind() == BuiltinType::Double || 3388 BT->getKind() == BuiltinType::LongDouble) 3389 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2); 3390 } 3391 3392 if (!isAggregateTypeForABI(Ty)) { 3393 // Treat an enum type as its underlying type. 3394 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3395 Ty = EnumTy->getDecl()->getIntegerType(); 3396 3397 return (Ty->isPromotableIntegerType() ? 3398 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3399 } 3400 3401 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3402 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 3403 3404 // Ignore empty records. 3405 if (isEmptyRecord(getContext(), Ty, true)) 3406 return ABIArgInfo::getIgnore(); 3407 3408 if (getABIKind() == ARMABIInfo::AAPCS_VFP) { 3409 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 3410 // into VFP registers. 3411 const Type *Base = 0; 3412 uint64_t Members = 0; 3413 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) { 3414 assert(Base && "Base class should be set for homogeneous aggregate"); 3415 // Base can be a floating-point or a vector. 3416 if (Base->isVectorType()) { 3417 // ElementSize is in number of floats. 3418 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4; 3419 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize, 3420 Members * ElementSize); 3421 } else if (Base->isSpecificBuiltinType(BuiltinType::Float)) 3422 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members); 3423 else { 3424 assert(Base->isSpecificBuiltinType(BuiltinType::Double) || 3425 Base->isSpecificBuiltinType(BuiltinType::LongDouble)); 3426 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2); 3427 } 3428 IsHA = true; 3429 return ABIArgInfo::getExpand(); 3430 } 3431 } 3432 3433 // Support byval for ARM. 3434 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 3435 // most 8-byte. We realign the indirect argument if type alignment is bigger 3436 // than ABI alignment. 3437 uint64_t ABIAlign = 4; 3438 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8; 3439 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 3440 getABIKind() == ARMABIInfo::AAPCS) 3441 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 3442 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 3443 return ABIArgInfo::getIndirect(0, /*ByVal=*/true, 3444 /*Realign=*/TyAlign > ABIAlign); 3445 } 3446 3447 // Otherwise, pass by coercing to a structure of the appropriate size. 3448 llvm::Type* ElemTy; 3449 unsigned SizeRegs; 3450 // FIXME: Try to match the types of the arguments more accurately where 3451 // we can. 3452 if (getContext().getTypeAlign(Ty) <= 32) { 3453 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 3454 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 3455 } else { 3456 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 3457 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 3458 } 3459 3460 llvm::Type *STy = 3461 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL); 3462 return ABIArgInfo::getDirect(STy); 3463} 3464 3465static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 3466 llvm::LLVMContext &VMContext) { 3467 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 3468 // is called integer-like if its size is less than or equal to one word, and 3469 // the offset of each of its addressable sub-fields is zero. 3470 3471 uint64_t Size = Context.getTypeSize(Ty); 3472 3473 // Check that the type fits in a word. 3474 if (Size > 32) 3475 return false; 3476 3477 // FIXME: Handle vector types! 3478 if (Ty->isVectorType()) 3479 return false; 3480 3481 // Float types are never treated as "integer like". 3482 if (Ty->isRealFloatingType()) 3483 return false; 3484 3485 // If this is a builtin or pointer type then it is ok. 3486 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 3487 return true; 3488 3489 // Small complex integer types are "integer like". 3490 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 3491 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 3492 3493 // Single element and zero sized arrays should be allowed, by the definition 3494 // above, but they are not. 3495 3496 // Otherwise, it must be a record type. 3497 const RecordType *RT = Ty->getAs<RecordType>(); 3498 if (!RT) return false; 3499 3500 // Ignore records with flexible arrays. 3501 const RecordDecl *RD = RT->getDecl(); 3502 if (RD->hasFlexibleArrayMember()) 3503 return false; 3504 3505 // Check that all sub-fields are at offset 0, and are themselves "integer 3506 // like". 3507 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3508 3509 bool HadField = false; 3510 unsigned idx = 0; 3511 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3512 i != e; ++i, ++idx) { 3513 const FieldDecl *FD = *i; 3514 3515 // Bit-fields are not addressable, we only need to verify they are "integer 3516 // like". We still have to disallow a subsequent non-bitfield, for example: 3517 // struct { int : 0; int x } 3518 // is non-integer like according to gcc. 3519 if (FD->isBitField()) { 3520 if (!RD->isUnion()) 3521 HadField = true; 3522 3523 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 3524 return false; 3525 3526 continue; 3527 } 3528 3529 // Check if this field is at offset 0. 3530 if (Layout.getFieldOffset(idx) != 0) 3531 return false; 3532 3533 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 3534 return false; 3535 3536 // Only allow at most one field in a structure. This doesn't match the 3537 // wording above, but follows gcc in situations with a field following an 3538 // empty structure. 3539 if (!RD->isUnion()) { 3540 if (HadField) 3541 return false; 3542 3543 HadField = true; 3544 } 3545 } 3546 3547 return true; 3548} 3549 3550ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const { 3551 if (RetTy->isVoidType()) 3552 return ABIArgInfo::getIgnore(); 3553 3554 // Large vector types should be returned via memory. 3555 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 3556 return ABIArgInfo::getIndirect(0); 3557 3558 if (!isAggregateTypeForABI(RetTy)) { 3559 // Treat an enum type as its underlying type. 3560 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3561 RetTy = EnumTy->getDecl()->getIntegerType(); 3562 3563 return (RetTy->isPromotableIntegerType() ? 3564 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3565 } 3566 3567 // Structures with either a non-trivial destructor or a non-trivial 3568 // copy constructor are always indirect. 3569 if (isRecordReturnIndirect(RetTy, getCXXABI())) 3570 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3571 3572 // Are we following APCS? 3573 if (getABIKind() == APCS) { 3574 if (isEmptyRecord(getContext(), RetTy, false)) 3575 return ABIArgInfo::getIgnore(); 3576 3577 // Complex types are all returned as packed integers. 3578 // 3579 // FIXME: Consider using 2 x vector types if the back end handles them 3580 // correctly. 3581 if (RetTy->isAnyComplexType()) 3582 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3583 getContext().getTypeSize(RetTy))); 3584 3585 // Integer like structures are returned in r0. 3586 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 3587 // Return in the smallest viable integer type. 3588 uint64_t Size = getContext().getTypeSize(RetTy); 3589 if (Size <= 8) 3590 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 3591 if (Size <= 16) 3592 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 3593 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 3594 } 3595 3596 // Otherwise return in memory. 3597 return ABIArgInfo::getIndirect(0); 3598 } 3599 3600 // Otherwise this is an AAPCS variant. 3601 3602 if (isEmptyRecord(getContext(), RetTy, true)) 3603 return ABIArgInfo::getIgnore(); 3604 3605 // Check for homogeneous aggregates with AAPCS-VFP. 3606 if (getABIKind() == AAPCS_VFP) { 3607 const Type *Base = 0; 3608 if (isHomogeneousAggregate(RetTy, Base, getContext())) { 3609 assert(Base && "Base class should be set for homogeneous aggregate"); 3610 // Homogeneous Aggregates are returned directly. 3611 return ABIArgInfo::getDirect(); 3612 } 3613 } 3614 3615 // Aggregates <= 4 bytes are returned in r0; other aggregates 3616 // are returned indirectly. 3617 uint64_t Size = getContext().getTypeSize(RetTy); 3618 if (Size <= 32) { 3619 // Return in the smallest viable integer type. 3620 if (Size <= 8) 3621 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 3622 if (Size <= 16) 3623 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 3624 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 3625 } 3626 3627 return ABIArgInfo::getIndirect(0); 3628} 3629 3630/// isIllegalVector - check whether Ty is an illegal vector type. 3631bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 3632 if (const VectorType *VT = Ty->getAs<VectorType>()) { 3633 // Check whether VT is legal. 3634 unsigned NumElements = VT->getNumElements(); 3635 uint64_t Size = getContext().getTypeSize(VT); 3636 // NumElements should be power of 2. 3637 if ((NumElements & (NumElements - 1)) != 0) 3638 return true; 3639 // Size should be greater than 32 bits. 3640 return Size <= 32; 3641 } 3642 return false; 3643} 3644 3645llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3646 CodeGenFunction &CGF) const { 3647 llvm::Type *BP = CGF.Int8PtrTy; 3648 llvm::Type *BPP = CGF.Int8PtrPtrTy; 3649 3650 CGBuilderTy &Builder = CGF.Builder; 3651 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 3652 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 3653 3654 if (isEmptyRecord(getContext(), Ty, true)) { 3655 // These are ignored for parameter passing purposes. 3656 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 3657 return Builder.CreateBitCast(Addr, PTy); 3658 } 3659 3660 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8; 3661 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 3662 bool IsIndirect = false; 3663 3664 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 3665 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 3666 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 3667 getABIKind() == ARMABIInfo::AAPCS) 3668 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 3669 else 3670 TyAlign = 4; 3671 // Use indirect if size of the illegal vector is bigger than 16 bytes. 3672 if (isIllegalVectorType(Ty) && Size > 16) { 3673 IsIndirect = true; 3674 Size = 4; 3675 TyAlign = 4; 3676 } 3677 3678 // Handle address alignment for ABI alignment > 4 bytes. 3679 if (TyAlign > 4) { 3680 assert((TyAlign & (TyAlign - 1)) == 0 && 3681 "Alignment is not power of 2!"); 3682 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 3683 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 3684 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 3685 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align"); 3686 } 3687 3688 uint64_t Offset = 3689 llvm::RoundUpToAlignment(Size, 4); 3690 llvm::Value *NextAddr = 3691 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 3692 "ap.next"); 3693 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 3694 3695 if (IsIndirect) 3696 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP)); 3697 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) { 3698 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur 3699 // may not be correctly aligned for the vector type. We create an aligned 3700 // temporary space and copy the content over from ap.cur to the temporary 3701 // space. This is necessary if the natural alignment of the type is greater 3702 // than the ABI alignment. 3703 llvm::Type *I8PtrTy = Builder.getInt8PtrTy(); 3704 CharUnits CharSize = getContext().getTypeSizeInChars(Ty); 3705 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty), 3706 "var.align"); 3707 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy); 3708 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy); 3709 Builder.CreateMemCpy(Dst, Src, 3710 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()), 3711 TyAlign, false); 3712 Addr = AlignedTemp; //The content is in aligned location. 3713 } 3714 llvm::Type *PTy = 3715 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 3716 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 3717 3718 return AddrTyped; 3719} 3720 3721namespace { 3722 3723class NaClARMABIInfo : public ABIInfo { 3724 public: 3725 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind) 3726 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {} 3727 virtual void computeInfo(CGFunctionInfo &FI) const; 3728 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3729 CodeGenFunction &CGF) const; 3730 private: 3731 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv. 3732 ARMABIInfo NInfo; // Used for everything else. 3733}; 3734 3735class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo { 3736 public: 3737 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind) 3738 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {} 3739}; 3740 3741} 3742 3743void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 3744 if (FI.getASTCallingConvention() == CC_PnaclCall) 3745 PInfo.computeInfo(FI); 3746 else 3747 static_cast<const ABIInfo&>(NInfo).computeInfo(FI); 3748} 3749 3750llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3751 CodeGenFunction &CGF) const { 3752 // Always use the native convention; calling pnacl-style varargs functions 3753 // is unsupported. 3754 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF); 3755} 3756 3757//===----------------------------------------------------------------------===// 3758// AArch64 ABI Implementation 3759//===----------------------------------------------------------------------===// 3760 3761namespace { 3762 3763class AArch64ABIInfo : public ABIInfo { 3764public: 3765 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 3766 3767private: 3768 // The AArch64 PCS is explicit about return types and argument types being 3769 // handled identically, so we don't need to draw a distinction between 3770 // Argument and Return classification. 3771 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs, 3772 int &FreeVFPRegs) const; 3773 3774 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt, 3775 llvm::Type *DirectTy = 0) const; 3776 3777 virtual void computeInfo(CGFunctionInfo &FI) const; 3778 3779 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3780 CodeGenFunction &CGF) const; 3781}; 3782 3783class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 3784public: 3785 AArch64TargetCodeGenInfo(CodeGenTypes &CGT) 3786 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {} 3787 3788 const AArch64ABIInfo &getABIInfo() const { 3789 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 3790 } 3791 3792 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 3793 return 31; 3794 } 3795 3796 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3797 llvm::Value *Address) const { 3798 // 0-31 are x0-x30 and sp: 8 bytes each 3799 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 3800 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31); 3801 3802 // 64-95 are v0-v31: 16 bytes each 3803 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 3804 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95); 3805 3806 return false; 3807 } 3808 3809}; 3810 3811} 3812 3813void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3814 int FreeIntRegs = 8, FreeVFPRegs = 8; 3815 3816 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(), 3817 FreeIntRegs, FreeVFPRegs); 3818 3819 FreeIntRegs = FreeVFPRegs = 8; 3820 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3821 it != ie; ++it) { 3822 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs); 3823 3824 } 3825} 3826 3827ABIArgInfo 3828AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, 3829 bool IsInt, llvm::Type *DirectTy) const { 3830 if (FreeRegs >= RegsNeeded) { 3831 FreeRegs -= RegsNeeded; 3832 return ABIArgInfo::getDirect(DirectTy); 3833 } 3834 3835 llvm::Type *Padding = 0; 3836 3837 // We need padding so that later arguments don't get filled in anyway. That 3838 // wouldn't happen if only ByVal arguments followed in the same category, but 3839 // a large structure will simply seem to be a pointer as far as LLVM is 3840 // concerned. 3841 if (FreeRegs > 0) { 3842 if (IsInt) 3843 Padding = llvm::Type::getInt64Ty(getVMContext()); 3844 else 3845 Padding = llvm::Type::getFloatTy(getVMContext()); 3846 3847 // Either [N x i64] or [N x float]. 3848 Padding = llvm::ArrayType::get(Padding, FreeRegs); 3849 FreeRegs = 0; 3850 } 3851 3852 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8, 3853 /*IsByVal=*/ true, /*Realign=*/ false, 3854 Padding); 3855} 3856 3857 3858ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty, 3859 int &FreeIntRegs, 3860 int &FreeVFPRegs) const { 3861 // Can only occurs for return, but harmless otherwise. 3862 if (Ty->isVoidType()) 3863 return ABIArgInfo::getIgnore(); 3864 3865 // Large vector types should be returned via memory. There's no such concept 3866 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're 3867 // classified they'd go into memory (see B.3). 3868 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) { 3869 if (FreeIntRegs > 0) 3870 --FreeIntRegs; 3871 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3872 } 3873 3874 // All non-aggregate LLVM types have a concrete ABI representation so they can 3875 // be passed directly. After this block we're guaranteed to be in a 3876 // complicated case. 3877 if (!isAggregateTypeForABI(Ty)) { 3878 // Treat an enum type as its underlying type. 3879 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3880 Ty = EnumTy->getDecl()->getIntegerType(); 3881 3882 if (Ty->isFloatingType() || Ty->isVectorType()) 3883 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false); 3884 3885 assert(getContext().getTypeSize(Ty) <= 128 && 3886 "unexpectedly large scalar type"); 3887 3888 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1; 3889 3890 // If the type may need padding registers to ensure "alignment", we must be 3891 // careful when this is accounted for. Increasing the effective size covers 3892 // all cases. 3893 if (getContext().getTypeAlign(Ty) == 128) 3894 RegsNeeded += FreeIntRegs % 2 != 0; 3895 3896 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true); 3897 } 3898 3899 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 3900 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect) 3901 --FreeIntRegs; 3902 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 3903 } 3904 3905 if (isEmptyRecord(getContext(), Ty, true)) { 3906 if (!getContext().getLangOpts().CPlusPlus) { 3907 // Empty structs outside C++ mode are a GNU extension, so no ABI can 3908 // possibly tell us what to do. It turns out (I believe) that GCC ignores 3909 // the object for parameter-passsing purposes. 3910 return ABIArgInfo::getIgnore(); 3911 } 3912 3913 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode 3914 // description of va_arg in the PCS require that an empty struct does 3915 // actually occupy space for parameter-passing. I'm hoping for a 3916 // clarification giving an explicit paragraph to point to in future. 3917 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true, 3918 llvm::Type::getInt8Ty(getVMContext())); 3919 } 3920 3921 // Homogeneous vector aggregates get passed in registers or on the stack. 3922 const Type *Base = 0; 3923 uint64_t NumMembers = 0; 3924 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) { 3925 assert(Base && "Base class should be set for homogeneous aggregate"); 3926 // Homogeneous aggregates are passed and returned directly. 3927 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers, 3928 /*IsInt=*/ false); 3929 } 3930 3931 uint64_t Size = getContext().getTypeSize(Ty); 3932 if (Size <= 128) { 3933 // Small structs can use the same direct type whether they're in registers 3934 // or on the stack. 3935 llvm::Type *BaseTy; 3936 unsigned NumBases; 3937 int SizeInRegs = (Size + 63) / 64; 3938 3939 if (getContext().getTypeAlign(Ty) == 128) { 3940 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128); 3941 NumBases = 1; 3942 3943 // If the type may need padding registers to ensure "alignment", we must 3944 // be careful when this is accounted for. Increasing the effective size 3945 // covers all cases. 3946 SizeInRegs += FreeIntRegs % 2 != 0; 3947 } else { 3948 BaseTy = llvm::Type::getInt64Ty(getVMContext()); 3949 NumBases = SizeInRegs; 3950 } 3951 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases); 3952 3953 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs, 3954 /*IsInt=*/ true, DirectTy); 3955 } 3956 3957 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In 3958 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere. 3959 --FreeIntRegs; 3960 return ABIArgInfo::getIndirect(0, /* byVal = */ false); 3961} 3962 3963llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3964 CodeGenFunction &CGF) const { 3965 // The AArch64 va_list type and handling is specified in the Procedure Call 3966 // Standard, section B.4: 3967 // 3968 // struct { 3969 // void *__stack; 3970 // void *__gr_top; 3971 // void *__vr_top; 3972 // int __gr_offs; 3973 // int __vr_offs; 3974 // }; 3975 3976 assert(!CGF.CGM.getDataLayout().isBigEndian() 3977 && "va_arg not implemented for big-endian AArch64"); 3978 3979 int FreeIntRegs = 8, FreeVFPRegs = 8; 3980 Ty = CGF.getContext().getCanonicalType(Ty); 3981 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs); 3982 3983 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 3984 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 3985 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 3986 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 3987 3988 llvm::Value *reg_offs_p = 0, *reg_offs = 0; 3989 int reg_top_index; 3990 int RegSize; 3991 if (FreeIntRegs < 8) { 3992 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs"); 3993 // 3 is the field number of __gr_offs 3994 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 3995 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 3996 reg_top_index = 1; // field number for __gr_top 3997 RegSize = 8 * (8 - FreeIntRegs); 3998 } else { 3999 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs"); 4000 // 4 is the field number of __vr_offs. 4001 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 4002 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 4003 reg_top_index = 2; // field number for __vr_top 4004 RegSize = 16 * (8 - FreeVFPRegs); 4005 } 4006 4007 //======================================= 4008 // Find out where argument was passed 4009 //======================================= 4010 4011 // If reg_offs >= 0 we're already using the stack for this type of 4012 // argument. We don't want to keep updating reg_offs (in case it overflows, 4013 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 4014 // whatever they get). 4015 llvm::Value *UsingStack = 0; 4016 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs, 4017 llvm::ConstantInt::get(CGF.Int32Ty, 0)); 4018 4019 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 4020 4021 // Otherwise, at least some kind of argument could go in these registers, the 4022 // quesiton is whether this particular type is too big. 4023 CGF.EmitBlock(MaybeRegBlock); 4024 4025 // Integer arguments may need to correct register alignment (for example a 4026 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 4027 // align __gr_offs to calculate the potential address. 4028 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) { 4029 int Align = getContext().getTypeAlign(Ty) / 8; 4030 4031 reg_offs = CGF.Builder.CreateAdd(reg_offs, 4032 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 4033 "align_regoffs"); 4034 reg_offs = CGF.Builder.CreateAnd(reg_offs, 4035 llvm::ConstantInt::get(CGF.Int32Ty, -Align), 4036 "aligned_regoffs"); 4037 } 4038 4039 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 4040 llvm::Value *NewOffset = 0; 4041 NewOffset = CGF.Builder.CreateAdd(reg_offs, 4042 llvm::ConstantInt::get(CGF.Int32Ty, RegSize), 4043 "new_reg_offs"); 4044 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 4045 4046 // Now we're in a position to decide whether this argument really was in 4047 // registers or not. 4048 llvm::Value *InRegs = 0; 4049 InRegs = CGF.Builder.CreateICmpSLE(NewOffset, 4050 llvm::ConstantInt::get(CGF.Int32Ty, 0), 4051 "inreg"); 4052 4053 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 4054 4055 //======================================= 4056 // Argument was in registers 4057 //======================================= 4058 4059 // Now we emit the code for if the argument was originally passed in 4060 // registers. First start the appropriate block: 4061 CGF.EmitBlock(InRegBlock); 4062 4063 llvm::Value *reg_top_p = 0, *reg_top = 0; 4064 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 4065 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 4066 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs); 4067 llvm::Value *RegAddr = 0; 4068 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 4069 4070 if (!AI.isDirect()) { 4071 // If it's been passed indirectly (actually a struct), whatever we find from 4072 // stored registers or on the stack will actually be a struct **. 4073 MemTy = llvm::PointerType::getUnqual(MemTy); 4074 } 4075 4076 const Type *Base = 0; 4077 uint64_t NumMembers; 4078 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers) 4079 && NumMembers > 1) { 4080 // Homogeneous aggregates passed in registers will have their elements split 4081 // and stored 16-bytes apart regardless of size (they're notionally in qN, 4082 // qN+1, ...). We reload and store into a temporary local variable 4083 // contiguously. 4084 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly"); 4085 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 4086 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 4087 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy); 4088 4089 for (unsigned i = 0; i < NumMembers; ++i) { 4090 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i); 4091 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset); 4092 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr, 4093 llvm::PointerType::getUnqual(BaseTy)); 4094 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i); 4095 4096 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 4097 CGF.Builder.CreateStore(Elem, StoreAddr); 4098 } 4099 4100 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy); 4101 } else { 4102 // Otherwise the object is contiguous in memory 4103 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy); 4104 } 4105 4106 CGF.EmitBranch(ContBlock); 4107 4108 //======================================= 4109 // Argument was on the stack 4110 //======================================= 4111 CGF.EmitBlock(OnStackBlock); 4112 4113 llvm::Value *stack_p = 0, *OnStackAddr = 0; 4114 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 4115 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack"); 4116 4117 // Again, stack arguments may need realigmnent. In this case both integer and 4118 // floating-point ones might be affected. 4119 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) { 4120 int Align = getContext().getTypeAlign(Ty) / 8; 4121 4122 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty); 4123 4124 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr, 4125 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 4126 "align_stack"); 4127 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr, 4128 llvm::ConstantInt::get(CGF.Int64Ty, -Align), 4129 "align_stack"); 4130 4131 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy); 4132 } 4133 4134 uint64_t StackSize; 4135 if (AI.isDirect()) 4136 StackSize = getContext().getTypeSize(Ty) / 8; 4137 else 4138 StackSize = 8; 4139 4140 // All stack slots are 8 bytes 4141 StackSize = llvm::RoundUpToAlignment(StackSize, 8); 4142 4143 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize); 4144 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, 4145 "new_stack"); 4146 4147 // Write the new value of __stack for the next call to va_arg 4148 CGF.Builder.CreateStore(NewStack, stack_p); 4149 4150 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy); 4151 4152 CGF.EmitBranch(ContBlock); 4153 4154 //======================================= 4155 // Tidy up 4156 //======================================= 4157 CGF.EmitBlock(ContBlock); 4158 4159 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr"); 4160 ResAddr->addIncoming(RegAddr, InRegBlock); 4161 ResAddr->addIncoming(OnStackAddr, OnStackBlock); 4162 4163 if (AI.isDirect()) 4164 return ResAddr; 4165 4166 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"); 4167} 4168 4169//===----------------------------------------------------------------------===// 4170// NVPTX ABI Implementation 4171//===----------------------------------------------------------------------===// 4172 4173namespace { 4174 4175class NVPTXABIInfo : public ABIInfo { 4176public: 4177 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 4178 4179 ABIArgInfo classifyReturnType(QualType RetTy) const; 4180 ABIArgInfo classifyArgumentType(QualType Ty) const; 4181 4182 virtual void computeInfo(CGFunctionInfo &FI) const; 4183 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4184 CodeGenFunction &CFG) const; 4185}; 4186 4187class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 4188public: 4189 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 4190 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {} 4191 4192 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4193 CodeGen::CodeGenModule &M) const; 4194private: 4195 static void addKernelMetadata(llvm::Function *F); 4196}; 4197 4198ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 4199 if (RetTy->isVoidType()) 4200 return ABIArgInfo::getIgnore(); 4201 if (isAggregateTypeForABI(RetTy)) 4202 return ABIArgInfo::getIndirect(0); 4203 return ABIArgInfo::getDirect(); 4204} 4205 4206ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 4207 if (isAggregateTypeForABI(Ty)) 4208 return ABIArgInfo::getIndirect(0); 4209 4210 return ABIArgInfo::getDirect(); 4211} 4212 4213void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 4214 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4215 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4216 it != ie; ++it) 4217 it->info = classifyArgumentType(it->type); 4218 4219 // Always honor user-specified calling convention. 4220 if (FI.getCallingConvention() != llvm::CallingConv::C) 4221 return; 4222 4223 FI.setEffectiveCallingConvention(getRuntimeCC()); 4224} 4225 4226llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4227 CodeGenFunction &CFG) const { 4228 llvm_unreachable("NVPTX does not support varargs"); 4229} 4230 4231void NVPTXTargetCodeGenInfo:: 4232SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4233 CodeGen::CodeGenModule &M) const{ 4234 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 4235 if (!FD) return; 4236 4237 llvm::Function *F = cast<llvm::Function>(GV); 4238 4239 // Perform special handling in OpenCL mode 4240 if (M.getLangOpts().OpenCL) { 4241 // Use OpenCL function attributes to check for kernel functions 4242 // By default, all functions are device functions 4243 if (FD->hasAttr<OpenCLKernelAttr>()) { 4244 // OpenCL __kernel functions get kernel metadata 4245 addKernelMetadata(F); 4246 // And kernel functions are not subject to inlining 4247 F->addFnAttr(llvm::Attribute::NoInline); 4248 } 4249 } 4250 4251 // Perform special handling in CUDA mode. 4252 if (M.getLangOpts().CUDA) { 4253 // CUDA __global__ functions get a kernel metadata entry. Since 4254 // __global__ functions cannot be called from the device, we do not 4255 // need to set the noinline attribute. 4256 if (FD->getAttr<CUDAGlobalAttr>()) 4257 addKernelMetadata(F); 4258 } 4259} 4260 4261void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) { 4262 llvm::Module *M = F->getParent(); 4263 llvm::LLVMContext &Ctx = M->getContext(); 4264 4265 // Get "nvvm.annotations" metadata node 4266 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 4267 4268 // Create !{<func-ref>, metadata !"kernel", i32 1} node 4269 llvm::SmallVector<llvm::Value *, 3> MDVals; 4270 MDVals.push_back(F); 4271 MDVals.push_back(llvm::MDString::get(Ctx, "kernel")); 4272 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1)); 4273 4274 // Append metadata to nvvm.annotations 4275 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 4276} 4277 4278} 4279 4280//===----------------------------------------------------------------------===// 4281// SystemZ ABI Implementation 4282//===----------------------------------------------------------------------===// 4283 4284namespace { 4285 4286class SystemZABIInfo : public ABIInfo { 4287public: 4288 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 4289 4290 bool isPromotableIntegerType(QualType Ty) const; 4291 bool isCompoundType(QualType Ty) const; 4292 bool isFPArgumentType(QualType Ty) const; 4293 4294 ABIArgInfo classifyReturnType(QualType RetTy) const; 4295 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 4296 4297 virtual void computeInfo(CGFunctionInfo &FI) const { 4298 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4299 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4300 it != ie; ++it) 4301 it->info = classifyArgumentType(it->type); 4302 } 4303 4304 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4305 CodeGenFunction &CGF) const; 4306}; 4307 4308class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 4309public: 4310 SystemZTargetCodeGenInfo(CodeGenTypes &CGT) 4311 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {} 4312}; 4313 4314} 4315 4316bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const { 4317 // Treat an enum type as its underlying type. 4318 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4319 Ty = EnumTy->getDecl()->getIntegerType(); 4320 4321 // Promotable integer types are required to be promoted by the ABI. 4322 if (Ty->isPromotableIntegerType()) 4323 return true; 4324 4325 // 32-bit values must also be promoted. 4326 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4327 switch (BT->getKind()) { 4328 case BuiltinType::Int: 4329 case BuiltinType::UInt: 4330 return true; 4331 default: 4332 return false; 4333 } 4334 return false; 4335} 4336 4337bool SystemZABIInfo::isCompoundType(QualType Ty) const { 4338 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty); 4339} 4340 4341bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 4342 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4343 switch (BT->getKind()) { 4344 case BuiltinType::Float: 4345 case BuiltinType::Double: 4346 return true; 4347 default: 4348 return false; 4349 } 4350 4351 if (const RecordType *RT = Ty->getAsStructureType()) { 4352 const RecordDecl *RD = RT->getDecl(); 4353 bool Found = false; 4354 4355 // If this is a C++ record, check the bases first. 4356 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 4357 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(), 4358 E = CXXRD->bases_end(); I != E; ++I) { 4359 QualType Base = I->getType(); 4360 4361 // Empty bases don't affect things either way. 4362 if (isEmptyRecord(getContext(), Base, true)) 4363 continue; 4364 4365 if (Found) 4366 return false; 4367 Found = isFPArgumentType(Base); 4368 if (!Found) 4369 return false; 4370 } 4371 4372 // Check the fields. 4373 for (RecordDecl::field_iterator I = RD->field_begin(), 4374 E = RD->field_end(); I != E; ++I) { 4375 const FieldDecl *FD = *I; 4376 4377 // Empty bitfields don't affect things either way. 4378 // Unlike isSingleElementStruct(), empty structure and array fields 4379 // do count. So do anonymous bitfields that aren't zero-sized. 4380 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0) 4381 return true; 4382 4383 // Unlike isSingleElementStruct(), arrays do not count. 4384 // Nested isFPArgumentType structures still do though. 4385 if (Found) 4386 return false; 4387 Found = isFPArgumentType(FD->getType()); 4388 if (!Found) 4389 return false; 4390 } 4391 4392 // Unlike isSingleElementStruct(), trailing padding is allowed. 4393 // An 8-byte aligned struct s { float f; } is passed as a double. 4394 return Found; 4395 } 4396 4397 return false; 4398} 4399 4400llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4401 CodeGenFunction &CGF) const { 4402 // Assume that va_list type is correct; should be pointer to LLVM type: 4403 // struct { 4404 // i64 __gpr; 4405 // i64 __fpr; 4406 // i8 *__overflow_arg_area; 4407 // i8 *__reg_save_area; 4408 // }; 4409 4410 // Every argument occupies 8 bytes and is passed by preference in either 4411 // GPRs or FPRs. 4412 Ty = CGF.getContext().getCanonicalType(Ty); 4413 ABIArgInfo AI = classifyArgumentType(Ty); 4414 bool InFPRs = isFPArgumentType(Ty); 4415 4416 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 4417 bool IsIndirect = AI.isIndirect(); 4418 unsigned UnpaddedBitSize; 4419 if (IsIndirect) { 4420 APTy = llvm::PointerType::getUnqual(APTy); 4421 UnpaddedBitSize = 64; 4422 } else 4423 UnpaddedBitSize = getContext().getTypeSize(Ty); 4424 unsigned PaddedBitSize = 64; 4425 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size."); 4426 4427 unsigned PaddedSize = PaddedBitSize / 8; 4428 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8; 4429 4430 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding; 4431 if (InFPRs) { 4432 MaxRegs = 4; // Maximum of 4 FPR arguments 4433 RegCountField = 1; // __fpr 4434 RegSaveIndex = 16; // save offset for f0 4435 RegPadding = 0; // floats are passed in the high bits of an FPR 4436 } else { 4437 MaxRegs = 5; // Maximum of 5 GPR arguments 4438 RegCountField = 0; // __gpr 4439 RegSaveIndex = 2; // save offset for r2 4440 RegPadding = Padding; // values are passed in the low bits of a GPR 4441 } 4442 4443 llvm::Value *RegCountPtr = 4444 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 4445 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 4446 llvm::Type *IndexTy = RegCount->getType(); 4447 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 4448 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 4449 "fits_in_regs"); 4450 4451 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4452 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 4453 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4454 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 4455 4456 // Emit code to load the value if it was passed in registers. 4457 CGF.EmitBlock(InRegBlock); 4458 4459 // Work out the address of an argument register. 4460 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize); 4461 llvm::Value *ScaledRegCount = 4462 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 4463 llvm::Value *RegBase = 4464 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding); 4465 llvm::Value *RegOffset = 4466 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 4467 llvm::Value *RegSaveAreaPtr = 4468 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 4469 llvm::Value *RegSaveArea = 4470 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 4471 llvm::Value *RawRegAddr = 4472 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr"); 4473 llvm::Value *RegAddr = 4474 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr"); 4475 4476 // Update the register count 4477 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 4478 llvm::Value *NewRegCount = 4479 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 4480 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 4481 CGF.EmitBranch(ContBlock); 4482 4483 // Emit code to load the value if it was passed in memory. 4484 CGF.EmitBlock(InMemBlock); 4485 4486 // Work out the address of a stack argument. 4487 llvm::Value *OverflowArgAreaPtr = 4488 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 4489 llvm::Value *OverflowArgArea = 4490 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"); 4491 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding); 4492 llvm::Value *RawMemAddr = 4493 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr"); 4494 llvm::Value *MemAddr = 4495 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr"); 4496 4497 // Update overflow_arg_area_ptr pointer 4498 llvm::Value *NewOverflowArgArea = 4499 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area"); 4500 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 4501 CGF.EmitBranch(ContBlock); 4502 4503 // Return the appropriate result. 4504 CGF.EmitBlock(ContBlock); 4505 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr"); 4506 ResAddr->addIncoming(RegAddr, InRegBlock); 4507 ResAddr->addIncoming(MemAddr, InMemBlock); 4508 4509 if (IsIndirect) 4510 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg"); 4511 4512 return ResAddr; 4513} 4514 4515bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 4516 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4517 assert(Triple.getArch() == llvm::Triple::x86); 4518 4519 switch (Opts.getStructReturnConvention()) { 4520 case CodeGenOptions::SRCK_Default: 4521 break; 4522 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 4523 return false; 4524 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 4525 return true; 4526 } 4527 4528 if (Triple.isOSDarwin()) 4529 return true; 4530 4531 switch (Triple.getOS()) { 4532 case llvm::Triple::Cygwin: 4533 case llvm::Triple::MinGW32: 4534 case llvm::Triple::AuroraUX: 4535 case llvm::Triple::DragonFly: 4536 case llvm::Triple::FreeBSD: 4537 case llvm::Triple::OpenBSD: 4538 case llvm::Triple::Bitrig: 4539 case llvm::Triple::Win32: 4540 return true; 4541 default: 4542 return false; 4543 } 4544} 4545 4546ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 4547 if (RetTy->isVoidType()) 4548 return ABIArgInfo::getIgnore(); 4549 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 4550 return ABIArgInfo::getIndirect(0); 4551 return (isPromotableIntegerType(RetTy) ? 4552 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4553} 4554 4555ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 4556 // Handle the generic C++ ABI. 4557 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4558 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 4559 4560 // Integers and enums are extended to full register width. 4561 if (isPromotableIntegerType(Ty)) 4562 return ABIArgInfo::getExtend(); 4563 4564 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 4565 uint64_t Size = getContext().getTypeSize(Ty); 4566 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 4567 return ABIArgInfo::getIndirect(0); 4568 4569 // Handle small structures. 4570 if (const RecordType *RT = Ty->getAs<RecordType>()) { 4571 // Structures with flexible arrays have variable length, so really 4572 // fail the size test above. 4573 const RecordDecl *RD = RT->getDecl(); 4574 if (RD->hasFlexibleArrayMember()) 4575 return ABIArgInfo::getIndirect(0); 4576 4577 // The structure is passed as an unextended integer, a float, or a double. 4578 llvm::Type *PassTy; 4579 if (isFPArgumentType(Ty)) { 4580 assert(Size == 32 || Size == 64); 4581 if (Size == 32) 4582 PassTy = llvm::Type::getFloatTy(getVMContext()); 4583 else 4584 PassTy = llvm::Type::getDoubleTy(getVMContext()); 4585 } else 4586 PassTy = llvm::IntegerType::get(getVMContext(), Size); 4587 return ABIArgInfo::getDirect(PassTy); 4588 } 4589 4590 // Non-structure compounds are passed indirectly. 4591 if (isCompoundType(Ty)) 4592 return ABIArgInfo::getIndirect(0); 4593 4594 return ABIArgInfo::getDirect(0); 4595} 4596 4597//===----------------------------------------------------------------------===// 4598// MSP430 ABI Implementation 4599//===----------------------------------------------------------------------===// 4600 4601namespace { 4602 4603class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 4604public: 4605 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 4606 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 4607 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4608 CodeGen::CodeGenModule &M) const; 4609}; 4610 4611} 4612 4613void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D, 4614 llvm::GlobalValue *GV, 4615 CodeGen::CodeGenModule &M) const { 4616 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 4617 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) { 4618 // Handle 'interrupt' attribute: 4619 llvm::Function *F = cast<llvm::Function>(GV); 4620 4621 // Step 1: Set ISR calling convention. 4622 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 4623 4624 // Step 2: Add attributes goodness. 4625 F->addFnAttr(llvm::Attribute::NoInline); 4626 4627 // Step 3: Emit ISR vector alias. 4628 unsigned Num = attr->getNumber() / 2; 4629 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage, 4630 "__isr_" + Twine(Num), 4631 GV, &M.getModule()); 4632 } 4633 } 4634} 4635 4636//===----------------------------------------------------------------------===// 4637// MIPS ABI Implementation. This works for both little-endian and 4638// big-endian variants. 4639//===----------------------------------------------------------------------===// 4640 4641namespace { 4642class MipsABIInfo : public ABIInfo { 4643 bool IsO32; 4644 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 4645 void CoerceToIntArgs(uint64_t TySize, 4646 SmallVectorImpl<llvm::Type *> &ArgList) const; 4647 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 4648 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 4649 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 4650public: 4651 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 4652 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 4653 StackAlignInBytes(IsO32 ? 8 : 16) {} 4654 4655 ABIArgInfo classifyReturnType(QualType RetTy) const; 4656 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 4657 virtual void computeInfo(CGFunctionInfo &FI) const; 4658 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4659 CodeGenFunction &CGF) const; 4660}; 4661 4662class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 4663 unsigned SizeOfUnwindException; 4664public: 4665 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 4666 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)), 4667 SizeOfUnwindException(IsO32 ? 24 : 32) {} 4668 4669 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 4670 return 29; 4671 } 4672 4673 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4674 CodeGen::CodeGenModule &CGM) const { 4675 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 4676 if (!FD) return; 4677 llvm::Function *Fn = cast<llvm::Function>(GV); 4678 if (FD->hasAttr<Mips16Attr>()) { 4679 Fn->addFnAttr("mips16"); 4680 } 4681 else if (FD->hasAttr<NoMips16Attr>()) { 4682 Fn->addFnAttr("nomips16"); 4683 } 4684 } 4685 4686 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4687 llvm::Value *Address) const; 4688 4689 unsigned getSizeOfUnwindException() const { 4690 return SizeOfUnwindException; 4691 } 4692}; 4693} 4694 4695void MipsABIInfo::CoerceToIntArgs(uint64_t TySize, 4696 SmallVectorImpl<llvm::Type *> &ArgList) const { 4697 llvm::IntegerType *IntTy = 4698 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 4699 4700 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 4701 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 4702 ArgList.push_back(IntTy); 4703 4704 // If necessary, add one more integer type to ArgList. 4705 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 4706 4707 if (R) 4708 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 4709} 4710 4711// In N32/64, an aligned double precision floating point field is passed in 4712// a register. 4713llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 4714 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 4715 4716 if (IsO32) { 4717 CoerceToIntArgs(TySize, ArgList); 4718 return llvm::StructType::get(getVMContext(), ArgList); 4719 } 4720 4721 if (Ty->isComplexType()) 4722 return CGT.ConvertType(Ty); 4723 4724 const RecordType *RT = Ty->getAs<RecordType>(); 4725 4726 // Unions/vectors are passed in integer registers. 4727 if (!RT || !RT->isStructureOrClassType()) { 4728 CoerceToIntArgs(TySize, ArgList); 4729 return llvm::StructType::get(getVMContext(), ArgList); 4730 } 4731 4732 const RecordDecl *RD = RT->getDecl(); 4733 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 4734 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 4735 4736 uint64_t LastOffset = 0; 4737 unsigned idx = 0; 4738 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 4739 4740 // Iterate over fields in the struct/class and check if there are any aligned 4741 // double fields. 4742 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 4743 i != e; ++i, ++idx) { 4744 const QualType Ty = i->getType(); 4745 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 4746 4747 if (!BT || BT->getKind() != BuiltinType::Double) 4748 continue; 4749 4750 uint64_t Offset = Layout.getFieldOffset(idx); 4751 if (Offset % 64) // Ignore doubles that are not aligned. 4752 continue; 4753 4754 // Add ((Offset - LastOffset) / 64) args of type i64. 4755 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 4756 ArgList.push_back(I64); 4757 4758 // Add double type. 4759 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 4760 LastOffset = Offset + 64; 4761 } 4762 4763 CoerceToIntArgs(TySize - LastOffset, IntArgList); 4764 ArgList.append(IntArgList.begin(), IntArgList.end()); 4765 4766 return llvm::StructType::get(getVMContext(), ArgList); 4767} 4768 4769llvm::Type *MipsABIInfo::getPaddingType(uint64_t Align, uint64_t Offset) const { 4770 assert((Offset % MinABIStackAlignInBytes) == 0); 4771 4772 if ((Align - 1) & Offset) 4773 return llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 4774 4775 return 0; 4776} 4777 4778ABIArgInfo 4779MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 4780 uint64_t OrigOffset = Offset; 4781 uint64_t TySize = getContext().getTypeSize(Ty); 4782 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 4783 4784 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 4785 (uint64_t)StackAlignInBytes); 4786 Offset = llvm::RoundUpToAlignment(Offset, Align); 4787 Offset += llvm::RoundUpToAlignment(TySize, Align * 8) / 8; 4788 4789 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 4790 // Ignore empty aggregates. 4791 if (TySize == 0) 4792 return ABIArgInfo::getIgnore(); 4793 4794 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 4795 Offset = OrigOffset + MinABIStackAlignInBytes; 4796 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 4797 } 4798 4799 // If we have reached here, aggregates are passed directly by coercing to 4800 // another structure type. Padding is inserted if the offset of the 4801 // aggregate is unaligned. 4802 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 4803 getPaddingType(Align, OrigOffset)); 4804 } 4805 4806 // Treat an enum type as its underlying type. 4807 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4808 Ty = EnumTy->getDecl()->getIntegerType(); 4809 4810 if (Ty->isPromotableIntegerType()) 4811 return ABIArgInfo::getExtend(); 4812 4813 return ABIArgInfo::getDirect(0, 0, 4814 IsO32 ? 0 : getPaddingType(Align, OrigOffset)); 4815} 4816 4817llvm::Type* 4818MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 4819 const RecordType *RT = RetTy->getAs<RecordType>(); 4820 SmallVector<llvm::Type*, 8> RTList; 4821 4822 if (RT && RT->isStructureOrClassType()) { 4823 const RecordDecl *RD = RT->getDecl(); 4824 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 4825 unsigned FieldCnt = Layout.getFieldCount(); 4826 4827 // N32/64 returns struct/classes in floating point registers if the 4828 // following conditions are met: 4829 // 1. The size of the struct/class is no larger than 128-bit. 4830 // 2. The struct/class has one or two fields all of which are floating 4831 // point types. 4832 // 3. The offset of the first field is zero (this follows what gcc does). 4833 // 4834 // Any other composite results are returned in integer registers. 4835 // 4836 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 4837 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 4838 for (; b != e; ++b) { 4839 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 4840 4841 if (!BT || !BT->isFloatingPoint()) 4842 break; 4843 4844 RTList.push_back(CGT.ConvertType(b->getType())); 4845 } 4846 4847 if (b == e) 4848 return llvm::StructType::get(getVMContext(), RTList, 4849 RD->hasAttr<PackedAttr>()); 4850 4851 RTList.clear(); 4852 } 4853 } 4854 4855 CoerceToIntArgs(Size, RTList); 4856 return llvm::StructType::get(getVMContext(), RTList); 4857} 4858 4859ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 4860 uint64_t Size = getContext().getTypeSize(RetTy); 4861 4862 if (RetTy->isVoidType() || Size == 0) 4863 return ABIArgInfo::getIgnore(); 4864 4865 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 4866 if (isRecordReturnIndirect(RetTy, getCXXABI())) 4867 return ABIArgInfo::getIndirect(0); 4868 4869 if (Size <= 128) { 4870 if (RetTy->isAnyComplexType()) 4871 return ABIArgInfo::getDirect(); 4872 4873 // O32 returns integer vectors in registers. 4874 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation()) 4875 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 4876 4877 if (!IsO32) 4878 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 4879 } 4880 4881 return ABIArgInfo::getIndirect(0); 4882 } 4883 4884 // Treat an enum type as its underlying type. 4885 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 4886 RetTy = EnumTy->getDecl()->getIntegerType(); 4887 4888 return (RetTy->isPromotableIntegerType() ? 4889 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4890} 4891 4892void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 4893 ABIArgInfo &RetInfo = FI.getReturnInfo(); 4894 RetInfo = classifyReturnType(FI.getReturnType()); 4895 4896 // Check if a pointer to an aggregate is passed as a hidden argument. 4897 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 4898 4899 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4900 it != ie; ++it) 4901 it->info = classifyArgumentType(it->type, Offset); 4902} 4903 4904llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4905 CodeGenFunction &CGF) const { 4906 llvm::Type *BP = CGF.Int8PtrTy; 4907 llvm::Type *BPP = CGF.Int8PtrPtrTy; 4908 4909 CGBuilderTy &Builder = CGF.Builder; 4910 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 4911 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 4912 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8; 4913 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 4914 llvm::Value *AddrTyped; 4915 unsigned PtrWidth = getTarget().getPointerWidth(0); 4916 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty; 4917 4918 if (TypeAlign > MinABIStackAlignInBytes) { 4919 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy); 4920 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1); 4921 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign); 4922 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc); 4923 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask); 4924 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy); 4925 } 4926 else 4927 AddrTyped = Builder.CreateBitCast(Addr, PTy); 4928 4929 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP); 4930 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes); 4931 uint64_t Offset = 4932 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign); 4933 llvm::Value *NextAddr = 4934 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset), 4935 "ap.next"); 4936 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 4937 4938 return AddrTyped; 4939} 4940 4941bool 4942MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4943 llvm::Value *Address) const { 4944 // This information comes from gcc's implementation, which seems to 4945 // as canonical as it gets. 4946 4947 // Everything on MIPS is 4 bytes. Double-precision FP registers 4948 // are aliased to pairs of single-precision FP registers. 4949 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 4950 4951 // 0-31 are the general purpose registers, $0 - $31. 4952 // 32-63 are the floating-point registers, $f0 - $f31. 4953 // 64 and 65 are the multiply/divide registers, $hi and $lo. 4954 // 66 is the (notional, I think) register for signal-handler return. 4955 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 4956 4957 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 4958 // They are one bit wide and ignored here. 4959 4960 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 4961 // (coprocessor 1 is the FP unit) 4962 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 4963 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 4964 // 176-181 are the DSP accumulator registers. 4965 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 4966 return false; 4967} 4968 4969//===----------------------------------------------------------------------===// 4970// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 4971// Currently subclassed only to implement custom OpenCL C function attribute 4972// handling. 4973//===----------------------------------------------------------------------===// 4974 4975namespace { 4976 4977class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 4978public: 4979 TCETargetCodeGenInfo(CodeGenTypes &CGT) 4980 : DefaultTargetCodeGenInfo(CGT) {} 4981 4982 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4983 CodeGen::CodeGenModule &M) const; 4984}; 4985 4986void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D, 4987 llvm::GlobalValue *GV, 4988 CodeGen::CodeGenModule &M) const { 4989 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 4990 if (!FD) return; 4991 4992 llvm::Function *F = cast<llvm::Function>(GV); 4993 4994 if (M.getLangOpts().OpenCL) { 4995 if (FD->hasAttr<OpenCLKernelAttr>()) { 4996 // OpenCL C Kernel functions are not subject to inlining 4997 F->addFnAttr(llvm::Attribute::NoInline); 4998 4999 if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) { 5000 5001 // Convert the reqd_work_group_size() attributes to metadata. 5002 llvm::LLVMContext &Context = F->getContext(); 5003 llvm::NamedMDNode *OpenCLMetadata = 5004 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info"); 5005 5006 SmallVector<llvm::Value*, 5> Operands; 5007 Operands.push_back(F); 5008 5009 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 5010 llvm::APInt(32, 5011 FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim()))); 5012 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 5013 llvm::APInt(32, 5014 FD->getAttr<ReqdWorkGroupSizeAttr>()->getYDim()))); 5015 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 5016 llvm::APInt(32, 5017 FD->getAttr<ReqdWorkGroupSizeAttr>()->getZDim()))); 5018 5019 // Add a boolean constant operand for "required" (true) or "hint" (false) 5020 // for implementing the work_group_size_hint attr later. Currently 5021 // always true as the hint is not yet implemented. 5022 Operands.push_back(llvm::ConstantInt::getTrue(Context)); 5023 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 5024 } 5025 } 5026 } 5027} 5028 5029} 5030 5031//===----------------------------------------------------------------------===// 5032// Hexagon ABI Implementation 5033//===----------------------------------------------------------------------===// 5034 5035namespace { 5036 5037class HexagonABIInfo : public ABIInfo { 5038 5039 5040public: 5041 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 5042 5043private: 5044 5045 ABIArgInfo classifyReturnType(QualType RetTy) const; 5046 ABIArgInfo classifyArgumentType(QualType RetTy) const; 5047 5048 virtual void computeInfo(CGFunctionInfo &FI) const; 5049 5050 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5051 CodeGenFunction &CGF) const; 5052}; 5053 5054class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 5055public: 5056 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 5057 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {} 5058 5059 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 5060 return 29; 5061 } 5062}; 5063 5064} 5065 5066void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 5067 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 5068 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 5069 it != ie; ++it) 5070 it->info = classifyArgumentType(it->type); 5071} 5072 5073ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const { 5074 if (!isAggregateTypeForABI(Ty)) { 5075 // Treat an enum type as its underlying type. 5076 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5077 Ty = EnumTy->getDecl()->getIntegerType(); 5078 5079 return (Ty->isPromotableIntegerType() ? 5080 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 5081 } 5082 5083 // Ignore empty records. 5084 if (isEmptyRecord(getContext(), Ty, true)) 5085 return ABIArgInfo::getIgnore(); 5086 5087 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5088 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 5089 5090 uint64_t Size = getContext().getTypeSize(Ty); 5091 if (Size > 64) 5092 return ABIArgInfo::getIndirect(0, /*ByVal=*/true); 5093 // Pass in the smallest viable integer type. 5094 else if (Size > 32) 5095 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 5096 else if (Size > 16) 5097 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 5098 else if (Size > 8) 5099 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 5100 else 5101 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5102} 5103 5104ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 5105 if (RetTy->isVoidType()) 5106 return ABIArgInfo::getIgnore(); 5107 5108 // Large vector types should be returned via memory. 5109 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64) 5110 return ABIArgInfo::getIndirect(0); 5111 5112 if (!isAggregateTypeForABI(RetTy)) { 5113 // Treat an enum type as its underlying type. 5114 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5115 RetTy = EnumTy->getDecl()->getIntegerType(); 5116 5117 return (RetTy->isPromotableIntegerType() ? 5118 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 5119 } 5120 5121 // Structures with either a non-trivial destructor or a non-trivial 5122 // copy constructor are always indirect. 5123 if (isRecordReturnIndirect(RetTy, getCXXABI())) 5124 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 5125 5126 if (isEmptyRecord(getContext(), RetTy, true)) 5127 return ABIArgInfo::getIgnore(); 5128 5129 // Aggregates <= 8 bytes are returned in r0; other aggregates 5130 // are returned indirectly. 5131 uint64_t Size = getContext().getTypeSize(RetTy); 5132 if (Size <= 64) { 5133 // Return in the smallest viable integer type. 5134 if (Size <= 8) 5135 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5136 if (Size <= 16) 5137 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 5138 if (Size <= 32) 5139 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 5140 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 5141 } 5142 5143 return ABIArgInfo::getIndirect(0, /*ByVal=*/true); 5144} 5145 5146llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5147 CodeGenFunction &CGF) const { 5148 // FIXME: Need to handle alignment 5149 llvm::Type *BPP = CGF.Int8PtrPtrTy; 5150 5151 CGBuilderTy &Builder = CGF.Builder; 5152 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 5153 "ap"); 5154 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 5155 llvm::Type *PTy = 5156 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 5157 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 5158 5159 uint64_t Offset = 5160 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4); 5161 llvm::Value *NextAddr = 5162 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 5163 "ap.next"); 5164 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 5165 5166 return AddrTyped; 5167} 5168 5169 5170//===----------------------------------------------------------------------===// 5171// SPARC v9 ABI Implementation. 5172// Based on the SPARC Compliance Definition version 2.4.1. 5173// 5174// Function arguments a mapped to a nominal "parameter array" and promoted to 5175// registers depending on their type. Each argument occupies 8 or 16 bytes in 5176// the array, structs larger than 16 bytes are passed indirectly. 5177// 5178// One case requires special care: 5179// 5180// struct mixed { 5181// int i; 5182// float f; 5183// }; 5184// 5185// When a struct mixed is passed by value, it only occupies 8 bytes in the 5186// parameter array, but the int is passed in an integer register, and the float 5187// is passed in a floating point register. This is represented as two arguments 5188// with the LLVM IR inreg attribute: 5189// 5190// declare void f(i32 inreg %i, float inreg %f) 5191// 5192// The code generator will only allocate 4 bytes from the parameter array for 5193// the inreg arguments. All other arguments are allocated a multiple of 8 5194// bytes. 5195// 5196namespace { 5197class SparcV9ABIInfo : public ABIInfo { 5198public: 5199 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 5200 5201private: 5202 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 5203 virtual void computeInfo(CGFunctionInfo &FI) const; 5204 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5205 CodeGenFunction &CGF) const; 5206 5207 // Coercion type builder for structs passed in registers. The coercion type 5208 // serves two purposes: 5209 // 5210 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 5211 // in registers. 5212 // 2. Expose aligned floating point elements as first-level elements, so the 5213 // code generator knows to pass them in floating point registers. 5214 // 5215 // We also compute the InReg flag which indicates that the struct contains 5216 // aligned 32-bit floats. 5217 // 5218 struct CoerceBuilder { 5219 llvm::LLVMContext &Context; 5220 const llvm::DataLayout &DL; 5221 SmallVector<llvm::Type*, 8> Elems; 5222 uint64_t Size; 5223 bool InReg; 5224 5225 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 5226 : Context(c), DL(dl), Size(0), InReg(false) {} 5227 5228 // Pad Elems with integers until Size is ToSize. 5229 void pad(uint64_t ToSize) { 5230 assert(ToSize >= Size && "Cannot remove elements"); 5231 if (ToSize == Size) 5232 return; 5233 5234 // Finish the current 64-bit word. 5235 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64); 5236 if (Aligned > Size && Aligned <= ToSize) { 5237 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 5238 Size = Aligned; 5239 } 5240 5241 // Add whole 64-bit words. 5242 while (Size + 64 <= ToSize) { 5243 Elems.push_back(llvm::Type::getInt64Ty(Context)); 5244 Size += 64; 5245 } 5246 5247 // Final in-word padding. 5248 if (Size < ToSize) { 5249 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 5250 Size = ToSize; 5251 } 5252 } 5253 5254 // Add a floating point element at Offset. 5255 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 5256 // Unaligned floats are treated as integers. 5257 if (Offset % Bits) 5258 return; 5259 // The InReg flag is only required if there are any floats < 64 bits. 5260 if (Bits < 64) 5261 InReg = true; 5262 pad(Offset); 5263 Elems.push_back(Ty); 5264 Size = Offset + Bits; 5265 } 5266 5267 // Add a struct type to the coercion type, starting at Offset (in bits). 5268 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 5269 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 5270 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 5271 llvm::Type *ElemTy = StrTy->getElementType(i); 5272 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 5273 switch (ElemTy->getTypeID()) { 5274 case llvm::Type::StructTyID: 5275 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 5276 break; 5277 case llvm::Type::FloatTyID: 5278 addFloat(ElemOffset, ElemTy, 32); 5279 break; 5280 case llvm::Type::DoubleTyID: 5281 addFloat(ElemOffset, ElemTy, 64); 5282 break; 5283 case llvm::Type::FP128TyID: 5284 addFloat(ElemOffset, ElemTy, 128); 5285 break; 5286 case llvm::Type::PointerTyID: 5287 if (ElemOffset % 64 == 0) { 5288 pad(ElemOffset); 5289 Elems.push_back(ElemTy); 5290 Size += 64; 5291 } 5292 break; 5293 default: 5294 break; 5295 } 5296 } 5297 } 5298 5299 // Check if Ty is a usable substitute for the coercion type. 5300 bool isUsableType(llvm::StructType *Ty) const { 5301 if (Ty->getNumElements() != Elems.size()) 5302 return false; 5303 for (unsigned i = 0, e = Elems.size(); i != e; ++i) 5304 if (Elems[i] != Ty->getElementType(i)) 5305 return false; 5306 return true; 5307 } 5308 5309 // Get the coercion type as a literal struct type. 5310 llvm::Type *getType() const { 5311 if (Elems.size() == 1) 5312 return Elems.front(); 5313 else 5314 return llvm::StructType::get(Context, Elems); 5315 } 5316 }; 5317}; 5318} // end anonymous namespace 5319 5320ABIArgInfo 5321SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 5322 if (Ty->isVoidType()) 5323 return ABIArgInfo::getIgnore(); 5324 5325 uint64_t Size = getContext().getTypeSize(Ty); 5326 5327 // Anything too big to fit in registers is passed with an explicit indirect 5328 // pointer / sret pointer. 5329 if (Size > SizeLimit) 5330 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 5331 5332 // Treat an enum type as its underlying type. 5333 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5334 Ty = EnumTy->getDecl()->getIntegerType(); 5335 5336 // Integer types smaller than a register are extended. 5337 if (Size < 64 && Ty->isIntegerType()) 5338 return ABIArgInfo::getExtend(); 5339 5340 // Other non-aggregates go in registers. 5341 if (!isAggregateTypeForABI(Ty)) 5342 return ABIArgInfo::getDirect(); 5343 5344 // This is a small aggregate type that should be passed in registers. 5345 // Build a coercion type from the LLVM struct type. 5346 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 5347 if (!StrTy) 5348 return ABIArgInfo::getDirect(); 5349 5350 CoerceBuilder CB(getVMContext(), getDataLayout()); 5351 CB.addStruct(0, StrTy); 5352 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64)); 5353 5354 // Try to use the original type for coercion. 5355 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 5356 5357 if (CB.InReg) 5358 return ABIArgInfo::getDirectInReg(CoerceTy); 5359 else 5360 return ABIArgInfo::getDirect(CoerceTy); 5361} 5362 5363llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5364 CodeGenFunction &CGF) const { 5365 ABIArgInfo AI = classifyType(Ty, 16 * 8); 5366 llvm::Type *ArgTy = CGT.ConvertType(Ty); 5367 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 5368 AI.setCoerceToType(ArgTy); 5369 5370 llvm::Type *BPP = CGF.Int8PtrPtrTy; 5371 CGBuilderTy &Builder = CGF.Builder; 5372 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 5373 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 5374 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 5375 llvm::Value *ArgAddr; 5376 unsigned Stride; 5377 5378 switch (AI.getKind()) { 5379 case ABIArgInfo::Expand: 5380 llvm_unreachable("Unsupported ABI kind for va_arg"); 5381 5382 case ABIArgInfo::Extend: 5383 Stride = 8; 5384 ArgAddr = Builder 5385 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy), 5386 "extend"); 5387 break; 5388 5389 case ABIArgInfo::Direct: 5390 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 5391 ArgAddr = Addr; 5392 break; 5393 5394 case ABIArgInfo::Indirect: 5395 Stride = 8; 5396 ArgAddr = Builder.CreateBitCast(Addr, 5397 llvm::PointerType::getUnqual(ArgPtrTy), 5398 "indirect"); 5399 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg"); 5400 break; 5401 5402 case ABIArgInfo::Ignore: 5403 return llvm::UndefValue::get(ArgPtrTy); 5404 } 5405 5406 // Update VAList. 5407 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next"); 5408 Builder.CreateStore(Addr, VAListAddrAsBPP); 5409 5410 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr"); 5411} 5412 5413void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 5414 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 5415 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 5416 it != ie; ++it) 5417 it->info = classifyType(it->type, 16 * 8); 5418} 5419 5420namespace { 5421class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 5422public: 5423 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 5424 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {} 5425}; 5426} // end anonymous namespace 5427 5428 5429//===----------------------------------------------------------------------===// 5430// Xcore ABI Implementation 5431//===----------------------------------------------------------------------===// 5432namespace { 5433class XCoreABIInfo : public DefaultABIInfo { 5434public: 5435 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 5436 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5437 CodeGenFunction &CGF) const; 5438}; 5439 5440class XcoreTargetCodeGenInfo : public TargetCodeGenInfo { 5441public: 5442 XcoreTargetCodeGenInfo(CodeGenTypes &CGT) 5443 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {} 5444}; 5445} // End anonymous namespace. 5446 5447llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5448 CodeGenFunction &CGF) const { 5449 CGBuilderTy &Builder = CGF.Builder; 5450 5451 // Get the VAList. 5452 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, 5453 CGF.Int8PtrPtrTy); 5454 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP); 5455 5456 // Handle the argument. 5457 ABIArgInfo AI = classifyArgumentType(Ty); 5458 llvm::Type *ArgTy = CGT.ConvertType(Ty); 5459 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 5460 AI.setCoerceToType(ArgTy); 5461 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 5462 llvm::Value *Val; 5463 uint64_t ArgSize = 0; 5464 switch (AI.getKind()) { 5465 case ABIArgInfo::Expand: 5466 llvm_unreachable("Unsupported ABI kind for va_arg"); 5467 case ABIArgInfo::Ignore: 5468 Val = llvm::UndefValue::get(ArgPtrTy); 5469 ArgSize = 0; 5470 break; 5471 case ABIArgInfo::Extend: 5472 case ABIArgInfo::Direct: 5473 Val = Builder.CreatePointerCast(AP, ArgPtrTy); 5474 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 5475 if (ArgSize < 4) 5476 ArgSize = 4; 5477 break; 5478 case ABIArgInfo::Indirect: 5479 llvm::Value *ArgAddr; 5480 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy)); 5481 ArgAddr = Builder.CreateLoad(ArgAddr); 5482 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy); 5483 ArgSize = 4; 5484 break; 5485 } 5486 5487 // Increment the VAList. 5488 if (ArgSize) { 5489 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize); 5490 Builder.CreateStore(APN, VAListAddrAsBPP); 5491 } 5492 return Val; 5493} 5494 5495//===----------------------------------------------------------------------===// 5496// Driver code 5497//===----------------------------------------------------------------------===// 5498 5499const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 5500 if (TheTargetCodeGenInfo) 5501 return *TheTargetCodeGenInfo; 5502 5503 const llvm::Triple &Triple = getTarget().getTriple(); 5504 switch (Triple.getArch()) { 5505 default: 5506 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types)); 5507 5508 case llvm::Triple::le32: 5509 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types)); 5510 case llvm::Triple::mips: 5511 case llvm::Triple::mipsel: 5512 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true)); 5513 5514 case llvm::Triple::mips64: 5515 case llvm::Triple::mips64el: 5516 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false)); 5517 5518 case llvm::Triple::aarch64: 5519 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types)); 5520 5521 case llvm::Triple::arm: 5522 case llvm::Triple::thumb: 5523 { 5524 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 5525 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0) 5526 Kind = ARMABIInfo::APCS; 5527 else if (CodeGenOpts.FloatABI == "hard" || 5528 (CodeGenOpts.FloatABI != "soft" && 5529 Triple.getEnvironment() == llvm::Triple::GNUEABIHF)) 5530 Kind = ARMABIInfo::AAPCS_VFP; 5531 5532 switch (Triple.getOS()) { 5533 case llvm::Triple::NaCl: 5534 return *(TheTargetCodeGenInfo = 5535 new NaClARMTargetCodeGenInfo(Types, Kind)); 5536 default: 5537 return *(TheTargetCodeGenInfo = 5538 new ARMTargetCodeGenInfo(Types, Kind)); 5539 } 5540 } 5541 5542 case llvm::Triple::ppc: 5543 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types)); 5544 case llvm::Triple::ppc64: 5545 if (Triple.isOSBinFormatELF()) 5546 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types)); 5547 else 5548 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types)); 5549 case llvm::Triple::ppc64le: 5550 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 5551 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types)); 5552 5553 case llvm::Triple::nvptx: 5554 case llvm::Triple::nvptx64: 5555 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types)); 5556 5557 case llvm::Triple::msp430: 5558 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types)); 5559 5560 case llvm::Triple::systemz: 5561 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types)); 5562 5563 case llvm::Triple::tce: 5564 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types)); 5565 5566 case llvm::Triple::x86: { 5567 bool IsDarwinVectorABI = Triple.isOSDarwin(); 5568 bool IsSmallStructInRegABI = 5569 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 5570 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32); 5571 5572 if (Triple.getOS() == llvm::Triple::Win32) { 5573 return *(TheTargetCodeGenInfo = 5574 new WinX86_32TargetCodeGenInfo(Types, 5575 IsDarwinVectorABI, IsSmallStructInRegABI, 5576 IsWin32FloatStructABI, 5577 CodeGenOpts.NumRegisterParameters)); 5578 } else { 5579 return *(TheTargetCodeGenInfo = 5580 new X86_32TargetCodeGenInfo(Types, 5581 IsDarwinVectorABI, IsSmallStructInRegABI, 5582 IsWin32FloatStructABI, 5583 CodeGenOpts.NumRegisterParameters)); 5584 } 5585 } 5586 5587 case llvm::Triple::x86_64: { 5588 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0; 5589 5590 switch (Triple.getOS()) { 5591 case llvm::Triple::Win32: 5592 case llvm::Triple::MinGW32: 5593 case llvm::Triple::Cygwin: 5594 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types)); 5595 case llvm::Triple::NaCl: 5596 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types, 5597 HasAVX)); 5598 default: 5599 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types, 5600 HasAVX)); 5601 } 5602 } 5603 case llvm::Triple::hexagon: 5604 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types)); 5605 case llvm::Triple::sparcv9: 5606 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types)); 5607 case llvm::Triple::xcore: 5608 return *(TheTargetCodeGenInfo = new XcoreTargetCodeGenInfo(Types)); 5609 5610 } 5611} 5612