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 "CodeGenFunction.h" 18 #include "clang/AST/RecordLayout.h" 19 #include "clang/Frontend/CodeGenOptions.h" 20 #include "llvm/Type.h" 21 #include "llvm/Target/TargetData.h" 22 #include "llvm/ADT/Triple.h" 23 #include "llvm/Support/raw_ostream.h" 24 using namespace clang; 25 using namespace CodeGen; 26 27 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 28 llvm::Value *Array, 29 llvm::Value *Value, 30 unsigned FirstIndex, 31 unsigned LastIndex) { 32 // Alternatively, we could emit this as a loop in the source. 33 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 34 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I); 35 Builder.CreateStore(Value, Cell); 36 } 37 } 38 39 static bool isAggregateTypeForABI(QualType T) { 40 return CodeGenFunction::hasAggregateLLVMType(T) || 41 T->isMemberFunctionPointerType(); 42 } 43 44 ABIInfo::~ABIInfo() {} 45 46 ASTContext &ABIInfo::getContext() const { 47 return CGT.getContext(); 48 } 49 50 llvm::LLVMContext &ABIInfo::getVMContext() const { 51 return CGT.getLLVMContext(); 52 } 53 54 const llvm::TargetData &ABIInfo::getTargetData() const { 55 return CGT.getTargetData(); 56 } 57 58 59 void ABIArgInfo::dump() const { 60 raw_ostream &OS = llvm::errs(); 61 OS << "(ABIArgInfo Kind="; 62 switch (TheKind) { 63 case Direct: 64 OS << "Direct Type="; 65 if (llvm::Type *Ty = getCoerceToType()) 66 Ty->print(OS); 67 else 68 OS << "null"; 69 break; 70 case Extend: 71 OS << "Extend"; 72 break; 73 case Ignore: 74 OS << "Ignore"; 75 break; 76 case Indirect: 77 OS << "Indirect Align=" << getIndirectAlign() 78 << " ByVal=" << getIndirectByVal() 79 << " Realign=" << getIndirectRealign(); 80 break; 81 case Expand: 82 OS << "Expand"; 83 break; 84 } 85 OS << ")\n"; 86 } 87 88 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; } 89 90 // If someone can figure out a general rule for this, that would be great. 91 // It's probably just doomed to be platform-dependent, though. 92 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 93 // Verified for: 94 // x86-64 FreeBSD, Linux, Darwin 95 // x86-32 FreeBSD, Linux, Darwin 96 // PowerPC Linux, Darwin 97 // ARM Darwin (*not* EABI) 98 return 32; 99 } 100 101 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 102 const FunctionNoProtoType *fnType) const { 103 // The following conventions are known to require this to be false: 104 // x86_stdcall 105 // MIPS 106 // For everything else, we just prefer false unless we opt out. 107 return false; 108 } 109 110 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 111 112 /// isEmptyField - Return true iff a the field is "empty", that is it 113 /// is an unnamed bit-field or an (array of) empty record(s). 114 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 115 bool AllowArrays) { 116 if (FD->isUnnamedBitfield()) 117 return true; 118 119 QualType FT = FD->getType(); 120 121 // Constant arrays of empty records count as empty, strip them off. 122 // Constant arrays of zero length always count as empty. 123 if (AllowArrays) 124 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 125 if (AT->getSize() == 0) 126 return true; 127 FT = AT->getElementType(); 128 } 129 130 const RecordType *RT = FT->getAs<RecordType>(); 131 if (!RT) 132 return false; 133 134 // C++ record fields are never empty, at least in the Itanium ABI. 135 // 136 // FIXME: We should use a predicate for whether this behavior is true in the 137 // current ABI. 138 if (isa<CXXRecordDecl>(RT->getDecl())) 139 return false; 140 141 return isEmptyRecord(Context, FT, AllowArrays); 142 } 143 144 /// isEmptyRecord - Return true iff a structure contains only empty 145 /// fields. Note that a structure with a flexible array member is not 146 /// considered empty. 147 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 148 const RecordType *RT = T->getAs<RecordType>(); 149 if (!RT) 150 return 0; 151 const RecordDecl *RD = RT->getDecl(); 152 if (RD->hasFlexibleArrayMember()) 153 return false; 154 155 // If this is a C++ record, check the bases first. 156 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 157 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 158 e = CXXRD->bases_end(); i != e; ++i) 159 if (!isEmptyRecord(Context, i->getType(), true)) 160 return false; 161 162 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 163 i != e; ++i) 164 if (!isEmptyField(Context, *i, AllowArrays)) 165 return false; 166 return true; 167 } 168 169 /// hasNonTrivialDestructorOrCopyConstructor - Determine if a type has either 170 /// a non-trivial destructor or a non-trivial copy constructor. 171 static bool hasNonTrivialDestructorOrCopyConstructor(const RecordType *RT) { 172 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 173 if (!RD) 174 return false; 175 176 return !RD->hasTrivialDestructor() || !RD->hasTrivialCopyConstructor(); 177 } 178 179 /// isRecordWithNonTrivialDestructorOrCopyConstructor - Determine if a type is 180 /// a record type with either a non-trivial destructor or a non-trivial copy 181 /// constructor. 182 static bool isRecordWithNonTrivialDestructorOrCopyConstructor(QualType T) { 183 const RecordType *RT = T->getAs<RecordType>(); 184 if (!RT) 185 return false; 186 187 return hasNonTrivialDestructorOrCopyConstructor(RT); 188 } 189 190 /// isSingleElementStruct - Determine if a structure is a "single 191 /// element struct", i.e. it has exactly one non-empty field or 192 /// exactly one field which is itself a single element 193 /// struct. Structures with flexible array members are never 194 /// considered single element structs. 195 /// 196 /// \return The field declaration for the single non-empty field, if 197 /// it exists. 198 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 199 const RecordType *RT = T->getAsStructureType(); 200 if (!RT) 201 return 0; 202 203 const RecordDecl *RD = RT->getDecl(); 204 if (RD->hasFlexibleArrayMember()) 205 return 0; 206 207 const Type *Found = 0; 208 209 // If this is a C++ record, check the bases first. 210 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 211 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 212 e = CXXRD->bases_end(); i != e; ++i) { 213 // Ignore empty records. 214 if (isEmptyRecord(Context, i->getType(), true)) 215 continue; 216 217 // If we already found an element then this isn't a single-element struct. 218 if (Found) 219 return 0; 220 221 // If this is non-empty and not a single element struct, the composite 222 // cannot be a single element struct. 223 Found = isSingleElementStruct(i->getType(), Context); 224 if (!Found) 225 return 0; 226 } 227 } 228 229 // Check for single element. 230 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 231 i != e; ++i) { 232 const FieldDecl *FD = *i; 233 QualType FT = FD->getType(); 234 235 // Ignore empty fields. 236 if (isEmptyField(Context, FD, true)) 237 continue; 238 239 // If we already found an element then this isn't a single-element 240 // struct. 241 if (Found) 242 return 0; 243 244 // Treat single element arrays as the element. 245 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 246 if (AT->getSize().getZExtValue() != 1) 247 break; 248 FT = AT->getElementType(); 249 } 250 251 if (!isAggregateTypeForABI(FT)) { 252 Found = FT.getTypePtr(); 253 } else { 254 Found = isSingleElementStruct(FT, Context); 255 if (!Found) 256 return 0; 257 } 258 } 259 260 // We don't consider a struct a single-element struct if it has 261 // padding beyond the element type. 262 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 263 return 0; 264 265 return Found; 266 } 267 268 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 269 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 270 !Ty->isAnyComplexType() && !Ty->isEnumeralType() && 271 !Ty->isBlockPointerType()) 272 return false; 273 274 uint64_t Size = Context.getTypeSize(Ty); 275 return Size == 32 || Size == 64; 276 } 277 278 /// canExpandIndirectArgument - Test whether an argument type which is to be 279 /// passed indirectly (on the stack) would have the equivalent layout if it was 280 /// expanded into separate arguments. If so, we prefer to do the latter to avoid 281 /// inhibiting optimizations. 282 /// 283 // FIXME: This predicate is missing many cases, currently it just follows 284 // llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We 285 // should probably make this smarter, or better yet make the LLVM backend 286 // capable of handling it. 287 static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) { 288 // We can only expand structure types. 289 const RecordType *RT = Ty->getAs<RecordType>(); 290 if (!RT) 291 return false; 292 293 // We can only expand (C) structures. 294 // 295 // FIXME: This needs to be generalized to handle classes as well. 296 const RecordDecl *RD = RT->getDecl(); 297 if (!RD->isStruct() || isa<CXXRecordDecl>(RD)) 298 return false; 299 300 uint64_t Size = 0; 301 302 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 303 i != e; ++i) { 304 const FieldDecl *FD = *i; 305 306 if (!is32Or64BitBasicType(FD->getType(), Context)) 307 return false; 308 309 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 310 // how to expand them yet, and the predicate for telling if a bitfield still 311 // counts as "basic" is more complicated than what we were doing previously. 312 if (FD->isBitField()) 313 return false; 314 315 Size += Context.getTypeSize(FD->getType()); 316 } 317 318 // Make sure there are not any holes in the struct. 319 if (Size != Context.getTypeSize(Ty)) 320 return false; 321 322 return true; 323 } 324 325 namespace { 326 /// DefaultABIInfo - The default implementation for ABI specific 327 /// details. This implementation provides information which results in 328 /// self-consistent and sensible LLVM IR generation, but does not 329 /// conform to any particular ABI. 330 class DefaultABIInfo : public ABIInfo { 331 public: 332 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 333 334 ABIArgInfo classifyReturnType(QualType RetTy) const; 335 ABIArgInfo classifyArgumentType(QualType RetTy) const; 336 337 virtual void computeInfo(CGFunctionInfo &FI) const { 338 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 339 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 340 it != ie; ++it) 341 it->info = classifyArgumentType(it->type); 342 } 343 344 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 345 CodeGenFunction &CGF) const; 346 }; 347 348 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 349 public: 350 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 351 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 352 }; 353 354 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 355 CodeGenFunction &CGF) const { 356 return 0; 357 } 358 359 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 360 if (isAggregateTypeForABI(Ty)) { 361 // Records with non trivial destructors/constructors should not be passed 362 // by value. 363 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) 364 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 365 366 return ABIArgInfo::getIndirect(0); 367 } 368 369 // Treat an enum type as its underlying type. 370 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 371 Ty = EnumTy->getDecl()->getIntegerType(); 372 373 return (Ty->isPromotableIntegerType() ? 374 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 375 } 376 377 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 378 if (RetTy->isVoidType()) 379 return ABIArgInfo::getIgnore(); 380 381 if (isAggregateTypeForABI(RetTy)) 382 return ABIArgInfo::getIndirect(0); 383 384 // Treat an enum type as its underlying type. 385 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 386 RetTy = EnumTy->getDecl()->getIntegerType(); 387 388 return (RetTy->isPromotableIntegerType() ? 389 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 390 } 391 392 /// UseX86_MMXType - Return true if this is an MMX type that should use the 393 /// special x86_mmx type. 394 bool UseX86_MMXType(llvm::Type *IRType) { 395 // If the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>, use the 396 // special x86_mmx type. 397 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 398 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 399 IRType->getScalarSizeInBits() != 64; 400 } 401 402 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 403 StringRef Constraint, 404 llvm::Type* Ty) { 405 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) 406 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 407 return Ty; 408 } 409 410 //===----------------------------------------------------------------------===// 411 // X86-32 ABI Implementation 412 //===----------------------------------------------------------------------===// 413 414 /// X86_32ABIInfo - The X86-32 ABI information. 415 class X86_32ABIInfo : public ABIInfo { 416 static const unsigned MinABIStackAlignInBytes = 4; 417 418 bool IsDarwinVectorABI; 419 bool IsSmallStructInRegABI; 420 bool IsMMXDisabled; 421 bool IsWin32FloatStructABI; 422 423 static bool isRegisterSize(unsigned Size) { 424 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 425 } 426 427 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context); 428 429 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 430 /// such that the argument will be passed in memory. 431 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal = true) const; 432 433 /// \brief Return the alignment to use for the given type on the stack. 434 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 435 436 public: 437 438 ABIArgInfo classifyReturnType(QualType RetTy) const; 439 ABIArgInfo classifyArgumentType(QualType RetTy) const; 440 441 virtual void computeInfo(CGFunctionInfo &FI) const { 442 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 443 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 444 it != ie; ++it) 445 it->info = classifyArgumentType(it->type); 446 } 447 448 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 449 CodeGenFunction &CGF) const; 450 451 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool m, bool w) 452 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p), 453 IsMMXDisabled(m), IsWin32FloatStructABI(w) {} 454 }; 455 456 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 457 public: 458 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 459 bool d, bool p, bool m, bool w) 460 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, m, w)) {} 461 462 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 463 CodeGen::CodeGenModule &CGM) const; 464 465 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 466 // Darwin uses different dwarf register numbers for EH. 467 if (CGM.isTargetDarwin()) return 5; 468 469 return 4; 470 } 471 472 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 473 llvm::Value *Address) const; 474 475 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 476 StringRef Constraint, 477 llvm::Type* Ty) const { 478 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 479 } 480 481 }; 482 483 } 484 485 /// shouldReturnTypeInRegister - Determine if the given type should be 486 /// passed in a register (for the Darwin ABI). 487 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 488 ASTContext &Context) { 489 uint64_t Size = Context.getTypeSize(Ty); 490 491 // Type must be register sized. 492 if (!isRegisterSize(Size)) 493 return false; 494 495 if (Ty->isVectorType()) { 496 // 64- and 128- bit vectors inside structures are not returned in 497 // registers. 498 if (Size == 64 || Size == 128) 499 return false; 500 501 return true; 502 } 503 504 // If this is a builtin, pointer, enum, complex type, member pointer, or 505 // member function pointer it is ok. 506 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 507 Ty->isAnyComplexType() || Ty->isEnumeralType() || 508 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 509 return true; 510 511 // Arrays are treated like records. 512 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 513 return shouldReturnTypeInRegister(AT->getElementType(), Context); 514 515 // Otherwise, it must be a record type. 516 const RecordType *RT = Ty->getAs<RecordType>(); 517 if (!RT) return false; 518 519 // FIXME: Traverse bases here too. 520 521 // Structure types are passed in register if all fields would be 522 // passed in a register. 523 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(), 524 e = RT->getDecl()->field_end(); i != e; ++i) { 525 const FieldDecl *FD = *i; 526 527 // Empty fields are ignored. 528 if (isEmptyField(Context, FD, true)) 529 continue; 530 531 // Check fields recursively. 532 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 533 return false; 534 } 535 536 return true; 537 } 538 539 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy) const { 540 if (RetTy->isVoidType()) 541 return ABIArgInfo::getIgnore(); 542 543 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 544 // On Darwin, some vectors are returned in registers. 545 if (IsDarwinVectorABI) { 546 uint64_t Size = getContext().getTypeSize(RetTy); 547 548 // 128-bit vectors are a special case; they are returned in 549 // registers and we need to make sure to pick a type the LLVM 550 // backend will like. 551 if (Size == 128) 552 return ABIArgInfo::getDirect(llvm::VectorType::get( 553 llvm::Type::getInt64Ty(getVMContext()), 2)); 554 555 // Always return in register if it fits in a general purpose 556 // register, or if it is 64 bits and has a single element. 557 if ((Size == 8 || Size == 16 || Size == 32) || 558 (Size == 64 && VT->getNumElements() == 1)) 559 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 560 Size)); 561 562 return ABIArgInfo::getIndirect(0); 563 } 564 565 return ABIArgInfo::getDirect(); 566 } 567 568 if (isAggregateTypeForABI(RetTy)) { 569 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 570 // Structures with either a non-trivial destructor or a non-trivial 571 // copy constructor are always indirect. 572 if (hasNonTrivialDestructorOrCopyConstructor(RT)) 573 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 574 575 // Structures with flexible arrays are always indirect. 576 if (RT->getDecl()->hasFlexibleArrayMember()) 577 return ABIArgInfo::getIndirect(0); 578 } 579 580 // If specified, structs and unions are always indirect. 581 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType()) 582 return ABIArgInfo::getIndirect(0); 583 584 // Small structures which are register sized are generally returned 585 // in a register. 586 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext())) { 587 uint64_t Size = getContext().getTypeSize(RetTy); 588 589 // As a special-case, if the struct is a "single-element" struct, and 590 // the field is of type "float" or "double", return it in a 591 // floating-point register. (MSVC does not apply this special case.) 592 // We apply a similar transformation for pointer types to improve the 593 // quality of the generated IR. 594 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 595 if ((!IsWin32FloatStructABI && SeltTy->isRealFloatingType()) 596 || SeltTy->hasPointerRepresentation()) 597 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 598 599 // FIXME: We should be able to narrow this integer in cases with dead 600 // padding. 601 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 602 } 603 604 return ABIArgInfo::getIndirect(0); 605 } 606 607 // Treat an enum type as its underlying type. 608 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 609 RetTy = EnumTy->getDecl()->getIntegerType(); 610 611 return (RetTy->isPromotableIntegerType() ? 612 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 613 } 614 615 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) { 616 const RecordType *RT = Ty->getAs<RecordType>(); 617 if (!RT) 618 return 0; 619 const RecordDecl *RD = RT->getDecl(); 620 621 // If this is a C++ record, check the bases first. 622 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 623 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 624 e = CXXRD->bases_end(); i != e; ++i) 625 if (!isRecordWithSSEVectorType(Context, i->getType())) 626 return false; 627 628 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 629 i != e; ++i) { 630 QualType FT = i->getType(); 631 632 if (FT->getAs<VectorType>() && Context.getTypeSize(FT) == 128) 633 return true; 634 635 if (isRecordWithSSEVectorType(Context, FT)) 636 return true; 637 } 638 639 return false; 640 } 641 642 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 643 unsigned Align) const { 644 // Otherwise, if the alignment is less than or equal to the minimum ABI 645 // alignment, just use the default; the backend will handle this. 646 if (Align <= MinABIStackAlignInBytes) 647 return 0; // Use default alignment. 648 649 // On non-Darwin, the stack type alignment is always 4. 650 if (!IsDarwinVectorABI) { 651 // Set explicit alignment, since we may need to realign the top. 652 return MinABIStackAlignInBytes; 653 } 654 655 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 656 if (Align >= 16 && isRecordWithSSEVectorType(getContext(), Ty)) 657 return 16; 658 659 return MinABIStackAlignInBytes; 660 } 661 662 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal) const { 663 if (!ByVal) 664 return ABIArgInfo::getIndirect(0, false); 665 666 // Compute the byval alignment. 667 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 668 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 669 if (StackAlign == 0) 670 return ABIArgInfo::getIndirect(4); 671 672 // If the stack alignment is less than the type alignment, realign the 673 // argument. 674 if (StackAlign < TypeAlign) 675 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, 676 /*Realign=*/true); 677 678 return ABIArgInfo::getIndirect(StackAlign); 679 } 680 681 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty) const { 682 // FIXME: Set alignment on indirect arguments. 683 if (isAggregateTypeForABI(Ty)) { 684 // Structures with flexible arrays are always indirect. 685 if (const RecordType *RT = Ty->getAs<RecordType>()) { 686 // Structures with either a non-trivial destructor or a non-trivial 687 // copy constructor are always indirect. 688 if (hasNonTrivialDestructorOrCopyConstructor(RT)) 689 return getIndirectResult(Ty, /*ByVal=*/false); 690 691 if (RT->getDecl()->hasFlexibleArrayMember()) 692 return getIndirectResult(Ty); 693 } 694 695 // Ignore empty structs/unions. 696 if (isEmptyRecord(getContext(), Ty, true)) 697 return ABIArgInfo::getIgnore(); 698 699 // Expand small (<= 128-bit) record types when we know that the stack layout 700 // of those arguments will match the struct. This is important because the 701 // LLVM backend isn't smart enough to remove byval, which inhibits many 702 // optimizations. 703 if (getContext().getTypeSize(Ty) <= 4*32 && 704 canExpandIndirectArgument(Ty, getContext())) 705 return ABIArgInfo::getExpand(); 706 707 return getIndirectResult(Ty); 708 } 709 710 if (const VectorType *VT = Ty->getAs<VectorType>()) { 711 // On Darwin, some vectors are passed in memory, we handle this by passing 712 // it as an i8/i16/i32/i64. 713 if (IsDarwinVectorABI) { 714 uint64_t Size = getContext().getTypeSize(Ty); 715 if ((Size == 8 || Size == 16 || Size == 32) || 716 (Size == 64 && VT->getNumElements() == 1)) 717 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 718 Size)); 719 } 720 721 llvm::Type *IRType = CGT.ConvertType(Ty); 722 if (UseX86_MMXType(IRType)) { 723 if (IsMMXDisabled) 724 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 725 64)); 726 ABIArgInfo AAI = ABIArgInfo::getDirect(IRType); 727 AAI.setCoerceToType(llvm::Type::getX86_MMXTy(getVMContext())); 728 return AAI; 729 } 730 731 return ABIArgInfo::getDirect(); 732 } 733 734 735 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 736 Ty = EnumTy->getDecl()->getIntegerType(); 737 738 return (Ty->isPromotableIntegerType() ? 739 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 740 } 741 742 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 743 CodeGenFunction &CGF) const { 744 llvm::Type *BPP = CGF.Int8PtrPtrTy; 745 746 CGBuilderTy &Builder = CGF.Builder; 747 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 748 "ap"); 749 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 750 751 // Compute if the address needs to be aligned 752 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity(); 753 Align = getTypeStackAlignInBytes(Ty, Align); 754 Align = std::max(Align, 4U); 755 if (Align > 4) { 756 // addr = (addr + align - 1) & -align; 757 llvm::Value *Offset = 758 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1); 759 Addr = CGF.Builder.CreateGEP(Addr, Offset); 760 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr, 761 CGF.Int32Ty); 762 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align); 763 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask), 764 Addr->getType(), 765 "ap.cur.aligned"); 766 } 767 768 llvm::Type *PTy = 769 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 770 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 771 772 uint64_t Offset = 773 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align); 774 llvm::Value *NextAddr = 775 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 776 "ap.next"); 777 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 778 779 return AddrTyped; 780 } 781 782 void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D, 783 llvm::GlobalValue *GV, 784 CodeGen::CodeGenModule &CGM) const { 785 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 786 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 787 // Get the LLVM function. 788 llvm::Function *Fn = cast<llvm::Function>(GV); 789 790 // Now add the 'alignstack' attribute with a value of 16. 791 Fn->addFnAttr(llvm::Attribute::constructStackAlignmentFromInt(16)); 792 } 793 } 794 } 795 796 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 797 CodeGen::CodeGenFunction &CGF, 798 llvm::Value *Address) const { 799 CodeGen::CGBuilderTy &Builder = CGF.Builder; 800 801 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 802 803 // 0-7 are the eight integer registers; the order is different 804 // on Darwin (for EH), but the range is the same. 805 // 8 is %eip. 806 AssignToArrayRange(Builder, Address, Four8, 0, 8); 807 808 if (CGF.CGM.isTargetDarwin()) { 809 // 12-16 are st(0..4). Not sure why we stop at 4. 810 // These have size 16, which is sizeof(long double) on 811 // platforms with 8-byte alignment for that type. 812 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 813 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 814 815 } else { 816 // 9 is %eflags, which doesn't get a size on Darwin for some 817 // reason. 818 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9)); 819 820 // 11-16 are st(0..5). Not sure why we stop at 5. 821 // These have size 12, which is sizeof(long double) on 822 // platforms with 4-byte alignment for that type. 823 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 824 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 825 } 826 827 return false; 828 } 829 830 //===----------------------------------------------------------------------===// 831 // X86-64 ABI Implementation 832 //===----------------------------------------------------------------------===// 833 834 835 namespace { 836 /// X86_64ABIInfo - The X86_64 ABI information. 837 class X86_64ABIInfo : public ABIInfo { 838 enum Class { 839 Integer = 0, 840 SSE, 841 SSEUp, 842 X87, 843 X87Up, 844 ComplexX87, 845 NoClass, 846 Memory 847 }; 848 849 /// merge - Implement the X86_64 ABI merging algorithm. 850 /// 851 /// Merge an accumulating classification \arg Accum with a field 852 /// classification \arg Field. 853 /// 854 /// \param Accum - The accumulating classification. This should 855 /// always be either NoClass or the result of a previous merge 856 /// call. In addition, this should never be Memory (the caller 857 /// should just return Memory for the aggregate). 858 static Class merge(Class Accum, Class Field); 859 860 /// postMerge - Implement the X86_64 ABI post merging algorithm. 861 /// 862 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 863 /// final MEMORY or SSE classes when necessary. 864 /// 865 /// \param AggregateSize - The size of the current aggregate in 866 /// the classification process. 867 /// 868 /// \param Lo - The classification for the parts of the type 869 /// residing in the low word of the containing object. 870 /// 871 /// \param Hi - The classification for the parts of the type 872 /// residing in the higher words of the containing object. 873 /// 874 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 875 876 /// classify - Determine the x86_64 register classes in which the 877 /// given type T should be passed. 878 /// 879 /// \param Lo - The classification for the parts of the type 880 /// residing in the low word of the containing object. 881 /// 882 /// \param Hi - The classification for the parts of the type 883 /// residing in the high word of the containing object. 884 /// 885 /// \param OffsetBase - The bit offset of this type in the 886 /// containing object. Some parameters are classified different 887 /// depending on whether they straddle an eightbyte boundary. 888 /// 889 /// If a word is unused its result will be NoClass; if a type should 890 /// be passed in Memory then at least the classification of \arg Lo 891 /// will be Memory. 892 /// 893 /// The \arg Lo class will be NoClass iff the argument is ignored. 894 /// 895 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 896 /// also be ComplexX87. 897 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi) const; 898 899 llvm::Type *GetByteVectorType(QualType Ty) const; 900 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 901 unsigned IROffset, QualType SourceTy, 902 unsigned SourceOffset) const; 903 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 904 unsigned IROffset, QualType SourceTy, 905 unsigned SourceOffset) const; 906 907 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 908 /// such that the argument will be returned in memory. 909 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 910 911 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 912 /// such that the argument will be passed in memory. 913 ABIArgInfo getIndirectResult(QualType Ty) const; 914 915 ABIArgInfo classifyReturnType(QualType RetTy) const; 916 917 ABIArgInfo classifyArgumentType(QualType Ty, 918 unsigned &neededInt, 919 unsigned &neededSSE) const; 920 921 bool IsIllegalVectorType(QualType Ty) const; 922 923 /// The 0.98 ABI revision clarified a lot of ambiguities, 924 /// unfortunately in ways that were not always consistent with 925 /// certain previous compilers. In particular, platforms which 926 /// required strict binary compatibility with older versions of GCC 927 /// may need to exempt themselves. 928 bool honorsRevision0_98() const { 929 return !getContext().getTargetInfo().getTriple().isOSDarwin(); 930 } 931 932 bool HasAVX; 933 934 public: 935 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) : 936 ABIInfo(CGT), HasAVX(hasavx) {} 937 938 bool isPassedUsingAVXType(QualType type) const { 939 unsigned neededInt, neededSSE; 940 ABIArgInfo info = classifyArgumentType(type, neededInt, neededSSE); 941 if (info.isDirect()) { 942 llvm::Type *ty = info.getCoerceToType(); 943 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 944 return (vectorTy->getBitWidth() > 128); 945 } 946 return false; 947 } 948 949 virtual void computeInfo(CGFunctionInfo &FI) const; 950 951 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 952 CodeGenFunction &CGF) const; 953 }; 954 955 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 956 class WinX86_64ABIInfo : public ABIInfo { 957 958 ABIArgInfo classify(QualType Ty) const; 959 960 public: 961 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 962 963 virtual void computeInfo(CGFunctionInfo &FI) const; 964 965 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 966 CodeGenFunction &CGF) const; 967 }; 968 969 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 970 public: 971 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 972 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {} 973 974 const X86_64ABIInfo &getABIInfo() const { 975 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 976 } 977 978 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 979 return 7; 980 } 981 982 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 983 llvm::Value *Address) const { 984 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 985 986 // 0-15 are the 16 integer registers. 987 // 16 is %rip. 988 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 989 return false; 990 } 991 992 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 993 StringRef Constraint, 994 llvm::Type* Ty) const { 995 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 996 } 997 998 bool isNoProtoCallVariadic(const CallArgList &args, 999 const FunctionNoProtoType *fnType) const { 1000 // The default CC on x86-64 sets %al to the number of SSA 1001 // registers used, and GCC sets this when calling an unprototyped 1002 // function, so we override the default behavior. However, don't do 1003 // that when AVX types are involved: the ABI explicitly states it is 1004 // undefined, and it doesn't work in practice because of how the ABI 1005 // defines varargs anyway. 1006 if (fnType->getCallConv() == CC_Default || fnType->getCallConv() == CC_C) { 1007 bool HasAVXType = false; 1008 for (CallArgList::const_iterator 1009 it = args.begin(), ie = args.end(); it != ie; ++it) { 1010 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 1011 HasAVXType = true; 1012 break; 1013 } 1014 } 1015 1016 if (!HasAVXType) 1017 return true; 1018 } 1019 1020 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 1021 } 1022 1023 }; 1024 1025 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 1026 public: 1027 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 1028 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {} 1029 1030 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 1031 return 7; 1032 } 1033 1034 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1035 llvm::Value *Address) const { 1036 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 1037 1038 // 0-15 are the 16 integer registers. 1039 // 16 is %rip. 1040 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 1041 return false; 1042 } 1043 }; 1044 1045 } 1046 1047 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 1048 Class &Hi) const { 1049 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 1050 // 1051 // (a) If one of the classes is Memory, the whole argument is passed in 1052 // memory. 1053 // 1054 // (b) If X87UP is not preceded by X87, the whole argument is passed in 1055 // memory. 1056 // 1057 // (c) If the size of the aggregate exceeds two eightbytes and the first 1058 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 1059 // argument is passed in memory. NOTE: This is necessary to keep the 1060 // ABI working for processors that don't support the __m256 type. 1061 // 1062 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 1063 // 1064 // Some of these are enforced by the merging logic. Others can arise 1065 // only with unions; for example: 1066 // union { _Complex double; unsigned; } 1067 // 1068 // Note that clauses (b) and (c) were added in 0.98. 1069 // 1070 if (Hi == Memory) 1071 Lo = Memory; 1072 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 1073 Lo = Memory; 1074 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 1075 Lo = Memory; 1076 if (Hi == SSEUp && Lo != SSE) 1077 Hi = SSE; 1078 } 1079 1080 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 1081 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 1082 // classified recursively so that always two fields are 1083 // considered. The resulting class is calculated according to 1084 // the classes of the fields in the eightbyte: 1085 // 1086 // (a) If both classes are equal, this is the resulting class. 1087 // 1088 // (b) If one of the classes is NO_CLASS, the resulting class is 1089 // the other class. 1090 // 1091 // (c) If one of the classes is MEMORY, the result is the MEMORY 1092 // class. 1093 // 1094 // (d) If one of the classes is INTEGER, the result is the 1095 // INTEGER. 1096 // 1097 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 1098 // MEMORY is used as class. 1099 // 1100 // (f) Otherwise class SSE is used. 1101 1102 // Accum should never be memory (we should have returned) or 1103 // ComplexX87 (because this cannot be passed in a structure). 1104 assert((Accum != Memory && Accum != ComplexX87) && 1105 "Invalid accumulated classification during merge."); 1106 if (Accum == Field || Field == NoClass) 1107 return Accum; 1108 if (Field == Memory) 1109 return Memory; 1110 if (Accum == NoClass) 1111 return Field; 1112 if (Accum == Integer || Field == Integer) 1113 return Integer; 1114 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 1115 Accum == X87 || Accum == X87Up) 1116 return Memory; 1117 return SSE; 1118 } 1119 1120 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 1121 Class &Lo, Class &Hi) const { 1122 // FIXME: This code can be simplified by introducing a simple value class for 1123 // Class pairs with appropriate constructor methods for the various 1124 // situations. 1125 1126 // FIXME: Some of the split computations are wrong; unaligned vectors 1127 // shouldn't be passed in registers for example, so there is no chance they 1128 // can straddle an eightbyte. Verify & simplify. 1129 1130 Lo = Hi = NoClass; 1131 1132 Class &Current = OffsetBase < 64 ? Lo : Hi; 1133 Current = Memory; 1134 1135 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1136 BuiltinType::Kind k = BT->getKind(); 1137 1138 if (k == BuiltinType::Void) { 1139 Current = NoClass; 1140 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 1141 Lo = Integer; 1142 Hi = Integer; 1143 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 1144 Current = Integer; 1145 } else if (k == BuiltinType::Float || k == BuiltinType::Double) { 1146 Current = SSE; 1147 } else if (k == BuiltinType::LongDouble) { 1148 Lo = X87; 1149 Hi = X87Up; 1150 } 1151 // FIXME: _Decimal32 and _Decimal64 are SSE. 1152 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 1153 return; 1154 } 1155 1156 if (const EnumType *ET = Ty->getAs<EnumType>()) { 1157 // Classify the underlying integer type. 1158 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi); 1159 return; 1160 } 1161 1162 if (Ty->hasPointerRepresentation()) { 1163 Current = Integer; 1164 return; 1165 } 1166 1167 if (Ty->isMemberPointerType()) { 1168 if (Ty->isMemberFunctionPointerType()) 1169 Lo = Hi = Integer; 1170 else 1171 Current = Integer; 1172 return; 1173 } 1174 1175 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1176 uint64_t Size = getContext().getTypeSize(VT); 1177 if (Size == 32) { 1178 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x 1179 // float> as integer. 1180 Current = Integer; 1181 1182 // If this type crosses an eightbyte boundary, it should be 1183 // split. 1184 uint64_t EB_Real = (OffsetBase) / 64; 1185 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64; 1186 if (EB_Real != EB_Imag) 1187 Hi = Lo; 1188 } else if (Size == 64) { 1189 // gcc passes <1 x double> in memory. :( 1190 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) 1191 return; 1192 1193 // gcc passes <1 x long long> as INTEGER. 1194 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) || 1195 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) || 1196 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) || 1197 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong)) 1198 Current = Integer; 1199 else 1200 Current = SSE; 1201 1202 // If this type crosses an eightbyte boundary, it should be 1203 // split. 1204 if (OffsetBase && OffsetBase != 64) 1205 Hi = Lo; 1206 } else if (Size == 128 || (HasAVX && Size == 256)) { 1207 // Arguments of 256-bits are split into four eightbyte chunks. The 1208 // least significant one belongs to class SSE and all the others to class 1209 // SSEUP. The original Lo and Hi design considers that types can't be 1210 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 1211 // This design isn't correct for 256-bits, but since there're no cases 1212 // where the upper parts would need to be inspected, avoid adding 1213 // complexity and just consider Hi to match the 64-256 part. 1214 Lo = SSE; 1215 Hi = SSEUp; 1216 } 1217 return; 1218 } 1219 1220 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 1221 QualType ET = getContext().getCanonicalType(CT->getElementType()); 1222 1223 uint64_t Size = getContext().getTypeSize(Ty); 1224 if (ET->isIntegralOrEnumerationType()) { 1225 if (Size <= 64) 1226 Current = Integer; 1227 else if (Size <= 128) 1228 Lo = Hi = Integer; 1229 } else if (ET == getContext().FloatTy) 1230 Current = SSE; 1231 else if (ET == getContext().DoubleTy) 1232 Lo = Hi = SSE; 1233 else if (ET == getContext().LongDoubleTy) 1234 Current = ComplexX87; 1235 1236 // If this complex type crosses an eightbyte boundary then it 1237 // should be split. 1238 uint64_t EB_Real = (OffsetBase) / 64; 1239 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 1240 if (Hi == NoClass && EB_Real != EB_Imag) 1241 Hi = Lo; 1242 1243 return; 1244 } 1245 1246 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 1247 // Arrays are treated like structures. 1248 1249 uint64_t Size = getContext().getTypeSize(Ty); 1250 1251 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 1252 // than four eightbytes, ..., it has class MEMORY. 1253 if (Size > 256) 1254 return; 1255 1256 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 1257 // fields, it has class MEMORY. 1258 // 1259 // Only need to check alignment of array base. 1260 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 1261 return; 1262 1263 // Otherwise implement simplified merge. We could be smarter about 1264 // this, but it isn't worth it and would be harder to verify. 1265 Current = NoClass; 1266 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 1267 uint64_t ArraySize = AT->getSize().getZExtValue(); 1268 1269 // The only case a 256-bit wide vector could be used is when the array 1270 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 1271 // to work for sizes wider than 128, early check and fallback to memory. 1272 if (Size > 128 && EltSize != 256) 1273 return; 1274 1275 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 1276 Class FieldLo, FieldHi; 1277 classify(AT->getElementType(), Offset, FieldLo, FieldHi); 1278 Lo = merge(Lo, FieldLo); 1279 Hi = merge(Hi, FieldHi); 1280 if (Lo == Memory || Hi == Memory) 1281 break; 1282 } 1283 1284 postMerge(Size, Lo, Hi); 1285 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 1286 return; 1287 } 1288 1289 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1290 uint64_t Size = getContext().getTypeSize(Ty); 1291 1292 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 1293 // than four eightbytes, ..., it has class MEMORY. 1294 if (Size > 256) 1295 return; 1296 1297 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 1298 // copy constructor or a non-trivial destructor, it is passed by invisible 1299 // reference. 1300 if (hasNonTrivialDestructorOrCopyConstructor(RT)) 1301 return; 1302 1303 const RecordDecl *RD = RT->getDecl(); 1304 1305 // Assume variable sized types are passed in memory. 1306 if (RD->hasFlexibleArrayMember()) 1307 return; 1308 1309 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 1310 1311 // Reset Lo class, this will be recomputed. 1312 Current = NoClass; 1313 1314 // If this is a C++ record, classify the bases first. 1315 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1316 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 1317 e = CXXRD->bases_end(); i != e; ++i) { 1318 assert(!i->isVirtual() && !i->getType()->isDependentType() && 1319 "Unexpected base class!"); 1320 const CXXRecordDecl *Base = 1321 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 1322 1323 // Classify this field. 1324 // 1325 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 1326 // single eightbyte, each is classified separately. Each eightbyte gets 1327 // initialized to class NO_CLASS. 1328 Class FieldLo, FieldHi; 1329 uint64_t Offset = OffsetBase + Layout.getBaseClassOffsetInBits(Base); 1330 classify(i->getType(), Offset, FieldLo, FieldHi); 1331 Lo = merge(Lo, FieldLo); 1332 Hi = merge(Hi, FieldHi); 1333 if (Lo == Memory || Hi == Memory) 1334 break; 1335 } 1336 } 1337 1338 // Classify the fields one at a time, merging the results. 1339 unsigned idx = 0; 1340 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 1341 i != e; ++i, ++idx) { 1342 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 1343 bool BitField = i->isBitField(); 1344 1345 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 1346 // four eightbytes, or it contains unaligned fields, it has class MEMORY. 1347 // 1348 // The only case a 256-bit wide vector could be used is when the struct 1349 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 1350 // to work for sizes wider than 128, early check and fallback to memory. 1351 // 1352 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) { 1353 Lo = Memory; 1354 return; 1355 } 1356 // Note, skip this test for bit-fields, see below. 1357 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 1358 Lo = Memory; 1359 return; 1360 } 1361 1362 // Classify this field. 1363 // 1364 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 1365 // exceeds a single eightbyte, each is classified 1366 // separately. Each eightbyte gets initialized to class 1367 // NO_CLASS. 1368 Class FieldLo, FieldHi; 1369 1370 // Bit-fields require special handling, they do not force the 1371 // structure to be passed in memory even if unaligned, and 1372 // therefore they can straddle an eightbyte. 1373 if (BitField) { 1374 // Ignore padding bit-fields. 1375 if (i->isUnnamedBitfield()) 1376 continue; 1377 1378 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 1379 uint64_t Size = i->getBitWidthValue(getContext()); 1380 1381 uint64_t EB_Lo = Offset / 64; 1382 uint64_t EB_Hi = (Offset + Size - 1) / 64; 1383 FieldLo = FieldHi = NoClass; 1384 if (EB_Lo) { 1385 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 1386 FieldLo = NoClass; 1387 FieldHi = Integer; 1388 } else { 1389 FieldLo = Integer; 1390 FieldHi = EB_Hi ? Integer : NoClass; 1391 } 1392 } else 1393 classify(i->getType(), Offset, FieldLo, FieldHi); 1394 Lo = merge(Lo, FieldLo); 1395 Hi = merge(Hi, FieldHi); 1396 if (Lo == Memory || Hi == Memory) 1397 break; 1398 } 1399 1400 postMerge(Size, Lo, Hi); 1401 } 1402 } 1403 1404 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 1405 // If this is a scalar LLVM value then assume LLVM will pass it in the right 1406 // place naturally. 1407 if (!isAggregateTypeForABI(Ty)) { 1408 // Treat an enum type as its underlying type. 1409 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1410 Ty = EnumTy->getDecl()->getIntegerType(); 1411 1412 return (Ty->isPromotableIntegerType() ? 1413 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 1414 } 1415 1416 return ABIArgInfo::getIndirect(0); 1417 } 1418 1419 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 1420 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 1421 uint64_t Size = getContext().getTypeSize(VecTy); 1422 unsigned LargestVector = HasAVX ? 256 : 128; 1423 if (Size <= 64 || Size > LargestVector) 1424 return true; 1425 } 1426 1427 return false; 1428 } 1429 1430 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty) const { 1431 // If this is a scalar LLVM value then assume LLVM will pass it in the right 1432 // place naturally. 1433 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) { 1434 // Treat an enum type as its underlying type. 1435 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1436 Ty = EnumTy->getDecl()->getIntegerType(); 1437 1438 return (Ty->isPromotableIntegerType() ? 1439 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 1440 } 1441 1442 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) 1443 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 1444 1445 // Compute the byval alignment. We specify the alignment of the byval in all 1446 // cases so that the mid-level optimizer knows the alignment of the byval. 1447 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 1448 return ABIArgInfo::getIndirect(Align); 1449 } 1450 1451 /// GetByteVectorType - The ABI specifies that a value should be passed in an 1452 /// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a 1453 /// vector register. 1454 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 1455 llvm::Type *IRType = CGT.ConvertType(Ty); 1456 1457 // Wrapper structs that just contain vectors are passed just like vectors, 1458 // strip them off if present. 1459 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType); 1460 while (STy && STy->getNumElements() == 1) { 1461 IRType = STy->getElementType(0); 1462 STy = dyn_cast<llvm::StructType>(IRType); 1463 } 1464 1465 // If the preferred type is a 16-byte vector, prefer to pass it. 1466 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){ 1467 llvm::Type *EltTy = VT->getElementType(); 1468 unsigned BitWidth = VT->getBitWidth(); 1469 if ((BitWidth >= 128 && BitWidth <= 256) && 1470 (EltTy->isFloatTy() || EltTy->isDoubleTy() || 1471 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) || 1472 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) || 1473 EltTy->isIntegerTy(128))) 1474 return VT; 1475 } 1476 1477 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2); 1478 } 1479 1480 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 1481 /// is known to either be off the end of the specified type or being in 1482 /// alignment padding. The user type specified is known to be at most 128 bits 1483 /// in size, and have passed through X86_64ABIInfo::classify with a successful 1484 /// classification that put one of the two halves in the INTEGER class. 1485 /// 1486 /// It is conservatively correct to return false. 1487 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 1488 unsigned EndBit, ASTContext &Context) { 1489 // If the bytes being queried are off the end of the type, there is no user 1490 // data hiding here. This handles analysis of builtins, vectors and other 1491 // types that don't contain interesting padding. 1492 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 1493 if (TySize <= StartBit) 1494 return true; 1495 1496 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 1497 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 1498 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 1499 1500 // Check each element to see if the element overlaps with the queried range. 1501 for (unsigned i = 0; i != NumElts; ++i) { 1502 // If the element is after the span we care about, then we're done.. 1503 unsigned EltOffset = i*EltSize; 1504 if (EltOffset >= EndBit) break; 1505 1506 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 1507 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 1508 EndBit-EltOffset, Context)) 1509 return false; 1510 } 1511 // If it overlaps no elements, then it is safe to process as padding. 1512 return true; 1513 } 1514 1515 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1516 const RecordDecl *RD = RT->getDecl(); 1517 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1518 1519 // If this is a C++ record, check the bases first. 1520 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1521 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 1522 e = CXXRD->bases_end(); i != e; ++i) { 1523 assert(!i->isVirtual() && !i->getType()->isDependentType() && 1524 "Unexpected base class!"); 1525 const CXXRecordDecl *Base = 1526 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 1527 1528 // If the base is after the span we care about, ignore it. 1529 unsigned BaseOffset = (unsigned)Layout.getBaseClassOffsetInBits(Base); 1530 if (BaseOffset >= EndBit) continue; 1531 1532 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 1533 if (!BitsContainNoUserData(i->getType(), BaseStart, 1534 EndBit-BaseOffset, Context)) 1535 return false; 1536 } 1537 } 1538 1539 // Verify that no field has data that overlaps the region of interest. Yes 1540 // this could be sped up a lot by being smarter about queried fields, 1541 // however we're only looking at structs up to 16 bytes, so we don't care 1542 // much. 1543 unsigned idx = 0; 1544 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 1545 i != e; ++i, ++idx) { 1546 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 1547 1548 // If we found a field after the region we care about, then we're done. 1549 if (FieldOffset >= EndBit) break; 1550 1551 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 1552 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 1553 Context)) 1554 return false; 1555 } 1556 1557 // If nothing in this record overlapped the area of interest, then we're 1558 // clean. 1559 return true; 1560 } 1561 1562 return false; 1563 } 1564 1565 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 1566 /// float member at the specified offset. For example, {int,{float}} has a 1567 /// float at offset 4. It is conservatively correct for this routine to return 1568 /// false. 1569 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 1570 const llvm::TargetData &TD) { 1571 // Base case if we find a float. 1572 if (IROffset == 0 && IRType->isFloatTy()) 1573 return true; 1574 1575 // If this is a struct, recurse into the field at the specified offset. 1576 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 1577 const llvm::StructLayout *SL = TD.getStructLayout(STy); 1578 unsigned Elt = SL->getElementContainingOffset(IROffset); 1579 IROffset -= SL->getElementOffset(Elt); 1580 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 1581 } 1582 1583 // If this is an array, recurse into the field at the specified offset. 1584 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 1585 llvm::Type *EltTy = ATy->getElementType(); 1586 unsigned EltSize = TD.getTypeAllocSize(EltTy); 1587 IROffset -= IROffset/EltSize*EltSize; 1588 return ContainsFloatAtOffset(EltTy, IROffset, TD); 1589 } 1590 1591 return false; 1592 } 1593 1594 1595 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 1596 /// low 8 bytes of an XMM register, corresponding to the SSE class. 1597 llvm::Type *X86_64ABIInfo:: 1598 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 1599 QualType SourceTy, unsigned SourceOffset) const { 1600 // The only three choices we have are either double, <2 x float>, or float. We 1601 // pass as float if the last 4 bytes is just padding. This happens for 1602 // structs that contain 3 floats. 1603 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 1604 SourceOffset*8+64, getContext())) 1605 return llvm::Type::getFloatTy(getVMContext()); 1606 1607 // We want to pass as <2 x float> if the LLVM IR type contains a float at 1608 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 1609 // case. 1610 if (ContainsFloatAtOffset(IRType, IROffset, getTargetData()) && 1611 ContainsFloatAtOffset(IRType, IROffset+4, getTargetData())) 1612 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2); 1613 1614 return llvm::Type::getDoubleTy(getVMContext()); 1615 } 1616 1617 1618 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 1619 /// an 8-byte GPR. This means that we either have a scalar or we are talking 1620 /// about the high or low part of an up-to-16-byte struct. This routine picks 1621 /// the best LLVM IR type to represent this, which may be i64 or may be anything 1622 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 1623 /// etc). 1624 /// 1625 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 1626 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 1627 /// the 8-byte value references. PrefType may be null. 1628 /// 1629 /// SourceTy is the source level type for the entire argument. SourceOffset is 1630 /// an offset into this that we're processing (which is always either 0 or 8). 1631 /// 1632 llvm::Type *X86_64ABIInfo:: 1633 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 1634 QualType SourceTy, unsigned SourceOffset) const { 1635 // If we're dealing with an un-offset LLVM IR type, then it means that we're 1636 // returning an 8-byte unit starting with it. See if we can safely use it. 1637 if (IROffset == 0) { 1638 // Pointers and int64's always fill the 8-byte unit. 1639 if (isa<llvm::PointerType>(IRType) || IRType->isIntegerTy(64)) 1640 return IRType; 1641 1642 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 1643 // goodness in the source type is just tail padding. This is allowed to 1644 // kick in for struct {double,int} on the int, but not on 1645 // struct{double,int,int} because we wouldn't return the second int. We 1646 // have to do this analysis on the source type because we can't depend on 1647 // unions being lowered a specific way etc. 1648 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 1649 IRType->isIntegerTy(32)) { 1650 unsigned BitWidth = cast<llvm::IntegerType>(IRType)->getBitWidth(); 1651 1652 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 1653 SourceOffset*8+64, getContext())) 1654 return IRType; 1655 } 1656 } 1657 1658 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 1659 // If this is a struct, recurse into the field at the specified offset. 1660 const llvm::StructLayout *SL = getTargetData().getStructLayout(STy); 1661 if (IROffset < SL->getSizeInBytes()) { 1662 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 1663 IROffset -= SL->getElementOffset(FieldIdx); 1664 1665 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 1666 SourceTy, SourceOffset); 1667 } 1668 } 1669 1670 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 1671 llvm::Type *EltTy = ATy->getElementType(); 1672 unsigned EltSize = getTargetData().getTypeAllocSize(EltTy); 1673 unsigned EltOffset = IROffset/EltSize*EltSize; 1674 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 1675 SourceOffset); 1676 } 1677 1678 // Okay, we don't have any better idea of what to pass, so we pass this in an 1679 // integer register that isn't too big to fit the rest of the struct. 1680 unsigned TySizeInBytes = 1681 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 1682 1683 assert(TySizeInBytes != SourceOffset && "Empty field?"); 1684 1685 // It is always safe to classify this as an integer type up to i64 that 1686 // isn't larger than the structure. 1687 return llvm::IntegerType::get(getVMContext(), 1688 std::min(TySizeInBytes-SourceOffset, 8U)*8); 1689 } 1690 1691 1692 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 1693 /// be used as elements of a two register pair to pass or return, return a 1694 /// first class aggregate to represent them. For example, if the low part of 1695 /// a by-value argument should be passed as i32* and the high part as float, 1696 /// return {i32*, float}. 1697 static llvm::Type * 1698 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 1699 const llvm::TargetData &TD) { 1700 // In order to correctly satisfy the ABI, we need to the high part to start 1701 // at offset 8. If the high and low parts we inferred are both 4-byte types 1702 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 1703 // the second element at offset 8. Check for this: 1704 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 1705 unsigned HiAlign = TD.getABITypeAlignment(Hi); 1706 unsigned HiStart = llvm::TargetData::RoundUpAlignment(LoSize, HiAlign); 1707 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 1708 1709 // To handle this, we have to increase the size of the low part so that the 1710 // second element will start at an 8 byte offset. We can't increase the size 1711 // of the second element because it might make us access off the end of the 1712 // struct. 1713 if (HiStart != 8) { 1714 // There are only two sorts of types the ABI generation code can produce for 1715 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32. 1716 // Promote these to a larger type. 1717 if (Lo->isFloatTy()) 1718 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 1719 else { 1720 assert(Lo->isIntegerTy() && "Invalid/unknown lo type"); 1721 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 1722 } 1723 } 1724 1725 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL); 1726 1727 1728 // Verify that the second element is at an 8-byte offset. 1729 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 1730 "Invalid x86-64 argument pair!"); 1731 return Result; 1732 } 1733 1734 ABIArgInfo X86_64ABIInfo:: 1735 classifyReturnType(QualType RetTy) const { 1736 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 1737 // classification algorithm. 1738 X86_64ABIInfo::Class Lo, Hi; 1739 classify(RetTy, 0, Lo, Hi); 1740 1741 // Check some invariants. 1742 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 1743 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 1744 1745 llvm::Type *ResType = 0; 1746 switch (Lo) { 1747 case NoClass: 1748 if (Hi == NoClass) 1749 return ABIArgInfo::getIgnore(); 1750 // If the low part is just padding, it takes no register, leave ResType 1751 // null. 1752 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 1753 "Unknown missing lo part"); 1754 break; 1755 1756 case SSEUp: 1757 case X87Up: 1758 llvm_unreachable("Invalid classification for lo word."); 1759 1760 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 1761 // hidden argument. 1762 case Memory: 1763 return getIndirectReturnResult(RetTy); 1764 1765 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 1766 // available register of the sequence %rax, %rdx is used. 1767 case Integer: 1768 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 1769 1770 // If we have a sign or zero extended integer, make sure to return Extend 1771 // so that the parameter gets the right LLVM IR attributes. 1772 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 1773 // Treat an enum type as its underlying type. 1774 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1775 RetTy = EnumTy->getDecl()->getIntegerType(); 1776 1777 if (RetTy->isIntegralOrEnumerationType() && 1778 RetTy->isPromotableIntegerType()) 1779 return ABIArgInfo::getExtend(); 1780 } 1781 break; 1782 1783 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 1784 // available SSE register of the sequence %xmm0, %xmm1 is used. 1785 case SSE: 1786 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 1787 break; 1788 1789 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 1790 // returned on the X87 stack in %st0 as 80-bit x87 number. 1791 case X87: 1792 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 1793 break; 1794 1795 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 1796 // part of the value is returned in %st0 and the imaginary part in 1797 // %st1. 1798 case ComplexX87: 1799 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 1800 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 1801 llvm::Type::getX86_FP80Ty(getVMContext()), 1802 NULL); 1803 break; 1804 } 1805 1806 llvm::Type *HighPart = 0; 1807 switch (Hi) { 1808 // Memory was handled previously and X87 should 1809 // never occur as a hi class. 1810 case Memory: 1811 case X87: 1812 llvm_unreachable("Invalid classification for hi word."); 1813 1814 case ComplexX87: // Previously handled. 1815 case NoClass: 1816 break; 1817 1818 case Integer: 1819 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 1820 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 1821 return ABIArgInfo::getDirect(HighPart, 8); 1822 break; 1823 case SSE: 1824 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 1825 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 1826 return ABIArgInfo::getDirect(HighPart, 8); 1827 break; 1828 1829 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 1830 // is passed in the next available eightbyte chunk if the last used 1831 // vector register. 1832 // 1833 // SSEUP should always be preceded by SSE, just widen. 1834 case SSEUp: 1835 assert(Lo == SSE && "Unexpected SSEUp classification."); 1836 ResType = GetByteVectorType(RetTy); 1837 break; 1838 1839 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 1840 // returned together with the previous X87 value in %st0. 1841 case X87Up: 1842 // If X87Up is preceded by X87, we don't need to do 1843 // anything. However, in some cases with unions it may not be 1844 // preceded by X87. In such situations we follow gcc and pass the 1845 // extra bits in an SSE reg. 1846 if (Lo != X87) { 1847 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 1848 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 1849 return ABIArgInfo::getDirect(HighPart, 8); 1850 } 1851 break; 1852 } 1853 1854 // If a high part was specified, merge it together with the low part. It is 1855 // known to pass in the high eightbyte of the result. We do this by forming a 1856 // first class struct aggregate with the high and low part: {low, high} 1857 if (HighPart) 1858 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getTargetData()); 1859 1860 return ABIArgInfo::getDirect(ResType); 1861 } 1862 1863 ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned &neededInt, 1864 unsigned &neededSSE) const { 1865 X86_64ABIInfo::Class Lo, Hi; 1866 classify(Ty, 0, Lo, Hi); 1867 1868 // Check some invariants. 1869 // FIXME: Enforce these by construction. 1870 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 1871 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 1872 1873 neededInt = 0; 1874 neededSSE = 0; 1875 llvm::Type *ResType = 0; 1876 switch (Lo) { 1877 case NoClass: 1878 if (Hi == NoClass) 1879 return ABIArgInfo::getIgnore(); 1880 // If the low part is just padding, it takes no register, leave ResType 1881 // null. 1882 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 1883 "Unknown missing lo part"); 1884 break; 1885 1886 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 1887 // on the stack. 1888 case Memory: 1889 1890 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 1891 // COMPLEX_X87, it is passed in memory. 1892 case X87: 1893 case ComplexX87: 1894 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) 1895 ++neededInt; 1896 return getIndirectResult(Ty); 1897 1898 case SSEUp: 1899 case X87Up: 1900 llvm_unreachable("Invalid classification for lo word."); 1901 1902 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 1903 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 1904 // and %r9 is used. 1905 case Integer: 1906 ++neededInt; 1907 1908 // Pick an 8-byte type based on the preferred type. 1909 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 1910 1911 // If we have a sign or zero extended integer, make sure to return Extend 1912 // so that the parameter gets the right LLVM IR attributes. 1913 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 1914 // Treat an enum type as its underlying type. 1915 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1916 Ty = EnumTy->getDecl()->getIntegerType(); 1917 1918 if (Ty->isIntegralOrEnumerationType() && 1919 Ty->isPromotableIntegerType()) 1920 return ABIArgInfo::getExtend(); 1921 } 1922 1923 break; 1924 1925 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 1926 // available SSE register is used, the registers are taken in the 1927 // order from %xmm0 to %xmm7. 1928 case SSE: { 1929 llvm::Type *IRType = CGT.ConvertType(Ty); 1930 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 1931 ++neededSSE; 1932 break; 1933 } 1934 } 1935 1936 llvm::Type *HighPart = 0; 1937 switch (Hi) { 1938 // Memory was handled previously, ComplexX87 and X87 should 1939 // never occur as hi classes, and X87Up must be preceded by X87, 1940 // which is passed in memory. 1941 case Memory: 1942 case X87: 1943 case ComplexX87: 1944 llvm_unreachable("Invalid classification for hi word."); 1945 1946 case NoClass: break; 1947 1948 case Integer: 1949 ++neededInt; 1950 // Pick an 8-byte type based on the preferred type. 1951 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 1952 1953 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 1954 return ABIArgInfo::getDirect(HighPart, 8); 1955 break; 1956 1957 // X87Up generally doesn't occur here (long double is passed in 1958 // memory), except in situations involving unions. 1959 case X87Up: 1960 case SSE: 1961 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 1962 1963 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 1964 return ABIArgInfo::getDirect(HighPart, 8); 1965 1966 ++neededSSE; 1967 break; 1968 1969 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 1970 // eightbyte is passed in the upper half of the last used SSE 1971 // register. This only happens when 128-bit vectors are passed. 1972 case SSEUp: 1973 assert(Lo == SSE && "Unexpected SSEUp classification"); 1974 ResType = GetByteVectorType(Ty); 1975 break; 1976 } 1977 1978 // If a high part was specified, merge it together with the low part. It is 1979 // known to pass in the high eightbyte of the result. We do this by forming a 1980 // first class struct aggregate with the high and low part: {low, high} 1981 if (HighPart) 1982 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getTargetData()); 1983 1984 return ABIArgInfo::getDirect(ResType); 1985 } 1986 1987 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1988 1989 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 1990 1991 // Keep track of the number of assigned registers. 1992 unsigned freeIntRegs = 6, freeSSERegs = 8; 1993 1994 // If the return value is indirect, then the hidden argument is consuming one 1995 // integer register. 1996 if (FI.getReturnInfo().isIndirect()) 1997 --freeIntRegs; 1998 1999 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 2000 // get assigned (in left-to-right order) for passing as follows... 2001 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2002 it != ie; ++it) { 2003 unsigned neededInt, neededSSE; 2004 it->info = classifyArgumentType(it->type, neededInt, neededSSE); 2005 2006 // AMD64-ABI 3.2.3p3: If there are no registers available for any 2007 // eightbyte of an argument, the whole argument is passed on the 2008 // stack. If registers have already been assigned for some 2009 // eightbytes of such an argument, the assignments get reverted. 2010 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) { 2011 freeIntRegs -= neededInt; 2012 freeSSERegs -= neededSSE; 2013 } else { 2014 it->info = getIndirectResult(it->type); 2015 } 2016 } 2017 } 2018 2019 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr, 2020 QualType Ty, 2021 CodeGenFunction &CGF) { 2022 llvm::Value *overflow_arg_area_p = 2023 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 2024 llvm::Value *overflow_arg_area = 2025 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 2026 2027 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 2028 // byte boundary if alignment needed by type exceeds 8 byte boundary. 2029 // It isn't stated explicitly in the standard, but in practice we use 2030 // alignment greater than 16 where necessary. 2031 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 2032 if (Align > 8) { 2033 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 2034 llvm::Value *Offset = 2035 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 2036 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset); 2037 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area, 2038 CGF.Int64Ty); 2039 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align); 2040 overflow_arg_area = 2041 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask), 2042 overflow_arg_area->getType(), 2043 "overflow_arg_area.align"); 2044 } 2045 2046 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 2047 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 2048 llvm::Value *Res = 2049 CGF.Builder.CreateBitCast(overflow_arg_area, 2050 llvm::PointerType::getUnqual(LTy)); 2051 2052 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 2053 // l->overflow_arg_area + sizeof(type). 2054 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 2055 // an 8 byte boundary. 2056 2057 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 2058 llvm::Value *Offset = 2059 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 2060 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 2061 "overflow_arg_area.next"); 2062 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 2063 2064 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 2065 return Res; 2066 } 2067 2068 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2069 CodeGenFunction &CGF) const { 2070 // Assume that va_list type is correct; should be pointer to LLVM type: 2071 // struct { 2072 // i32 gp_offset; 2073 // i32 fp_offset; 2074 // i8* overflow_arg_area; 2075 // i8* reg_save_area; 2076 // }; 2077 unsigned neededInt, neededSSE; 2078 2079 Ty = CGF.getContext().getCanonicalType(Ty); 2080 ABIArgInfo AI = classifyArgumentType(Ty, neededInt, neededSSE); 2081 2082 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 2083 // in the registers. If not go to step 7. 2084 if (!neededInt && !neededSSE) 2085 return EmitVAArgFromMemory(VAListAddr, Ty, CGF); 2086 2087 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 2088 // general purpose registers needed to pass type and num_fp to hold 2089 // the number of floating point registers needed. 2090 2091 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 2092 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 2093 // l->fp_offset > 304 - num_fp * 16 go to step 7. 2094 // 2095 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 2096 // register save space). 2097 2098 llvm::Value *InRegs = 0; 2099 llvm::Value *gp_offset_p = 0, *gp_offset = 0; 2100 llvm::Value *fp_offset_p = 0, *fp_offset = 0; 2101 if (neededInt) { 2102 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 2103 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 2104 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 2105 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 2106 } 2107 2108 if (neededSSE) { 2109 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 2110 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 2111 llvm::Value *FitsInFP = 2112 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 2113 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 2114 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 2115 } 2116 2117 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 2118 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 2119 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 2120 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 2121 2122 // Emit code to load the value if it was passed in registers. 2123 2124 CGF.EmitBlock(InRegBlock); 2125 2126 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 2127 // an offset of l->gp_offset and/or l->fp_offset. This may require 2128 // copying to a temporary location in case the parameter is passed 2129 // in different register classes or requires an alignment greater 2130 // than 8 for general purpose registers and 16 for XMM registers. 2131 // 2132 // FIXME: This really results in shameful code when we end up needing to 2133 // collect arguments from different places; often what should result in a 2134 // simple assembling of a structure from scattered addresses has many more 2135 // loads than necessary. Can we clean this up? 2136 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 2137 llvm::Value *RegAddr = 2138 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3), 2139 "reg_save_area"); 2140 if (neededInt && neededSSE) { 2141 // FIXME: Cleanup. 2142 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 2143 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 2144 llvm::Value *Tmp = CGF.CreateTempAlloca(ST); 2145 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 2146 llvm::Type *TyLo = ST->getElementType(0); 2147 llvm::Type *TyHi = ST->getElementType(1); 2148 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 2149 "Unexpected ABI info for mixed regs"); 2150 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 2151 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 2152 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset); 2153 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2154 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr; 2155 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr; 2156 llvm::Value *V = 2157 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo)); 2158 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 2159 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi)); 2160 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 2161 2162 RegAddr = CGF.Builder.CreateBitCast(Tmp, 2163 llvm::PointerType::getUnqual(LTy)); 2164 } else if (neededInt) { 2165 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset); 2166 RegAddr = CGF.Builder.CreateBitCast(RegAddr, 2167 llvm::PointerType::getUnqual(LTy)); 2168 } else if (neededSSE == 1) { 2169 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2170 RegAddr = CGF.Builder.CreateBitCast(RegAddr, 2171 llvm::PointerType::getUnqual(LTy)); 2172 } else { 2173 assert(neededSSE == 2 && "Invalid number of needed registers!"); 2174 // SSE registers are spaced 16 bytes apart in the register save 2175 // area, we need to collect the two eightbytes together. 2176 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2177 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16); 2178 llvm::Type *DoubleTy = CGF.DoubleTy; 2179 llvm::Type *DblPtrTy = 2180 llvm::PointerType::getUnqual(DoubleTy); 2181 llvm::StructType *ST = llvm::StructType::get(DoubleTy, 2182 DoubleTy, NULL); 2183 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST); 2184 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo, 2185 DblPtrTy)); 2186 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 2187 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi, 2188 DblPtrTy)); 2189 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 2190 RegAddr = CGF.Builder.CreateBitCast(Tmp, 2191 llvm::PointerType::getUnqual(LTy)); 2192 } 2193 2194 // AMD64-ABI 3.5.7p5: Step 5. Set: 2195 // l->gp_offset = l->gp_offset + num_gp * 8 2196 // l->fp_offset = l->fp_offset + num_fp * 16. 2197 if (neededInt) { 2198 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 2199 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 2200 gp_offset_p); 2201 } 2202 if (neededSSE) { 2203 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 2204 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 2205 fp_offset_p); 2206 } 2207 CGF.EmitBranch(ContBlock); 2208 2209 // Emit code to load the value if it was passed in memory. 2210 2211 CGF.EmitBlock(InMemBlock); 2212 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF); 2213 2214 // Return the appropriate result. 2215 2216 CGF.EmitBlock(ContBlock); 2217 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2, 2218 "vaarg.addr"); 2219 ResAddr->addIncoming(RegAddr, InRegBlock); 2220 ResAddr->addIncoming(MemAddr, InMemBlock); 2221 return ResAddr; 2222 } 2223 2224 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty) const { 2225 2226 if (Ty->isVoidType()) 2227 return ABIArgInfo::getIgnore(); 2228 2229 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2230 Ty = EnumTy->getDecl()->getIntegerType(); 2231 2232 uint64_t Size = getContext().getTypeSize(Ty); 2233 2234 if (const RecordType *RT = Ty->getAs<RecordType>()) { 2235 if (hasNonTrivialDestructorOrCopyConstructor(RT) || 2236 RT->getDecl()->hasFlexibleArrayMember()) 2237 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2238 2239 // FIXME: mingw-w64-gcc emits 128-bit struct as i128 2240 if (Size == 128 && 2241 getContext().getTargetInfo().getTriple().getOS() 2242 == llvm::Triple::MinGW32) 2243 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2244 Size)); 2245 2246 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 2247 // not 1, 2, 4, or 8 bytes, must be passed by reference." 2248 if (Size <= 64 && 2249 (Size & (Size - 1)) == 0) 2250 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2251 Size)); 2252 2253 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2254 } 2255 2256 if (Ty->isPromotableIntegerType()) 2257 return ABIArgInfo::getExtend(); 2258 2259 return ABIArgInfo::getDirect(); 2260 } 2261 2262 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2263 2264 QualType RetTy = FI.getReturnType(); 2265 FI.getReturnInfo() = classify(RetTy); 2266 2267 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2268 it != ie; ++it) 2269 it->info = classify(it->type); 2270 } 2271 2272 llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2273 CodeGenFunction &CGF) const { 2274 llvm::Type *BPP = CGF.Int8PtrPtrTy; 2275 2276 CGBuilderTy &Builder = CGF.Builder; 2277 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 2278 "ap"); 2279 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 2280 llvm::Type *PTy = 2281 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 2282 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 2283 2284 uint64_t Offset = 2285 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8); 2286 llvm::Value *NextAddr = 2287 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 2288 "ap.next"); 2289 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 2290 2291 return AddrTyped; 2292 } 2293 2294 // PowerPC-32 2295 2296 namespace { 2297 class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 2298 public: 2299 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 2300 2301 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 2302 // This is recovered from gcc output. 2303 return 1; // r1 is the dedicated stack pointer 2304 } 2305 2306 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2307 llvm::Value *Address) const; 2308 }; 2309 2310 } 2311 2312 bool 2313 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2314 llvm::Value *Address) const { 2315 // This is calculated from the LLVM and GCC tables and verified 2316 // against gcc output. AFAIK all ABIs use the same encoding. 2317 2318 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2319 2320 llvm::IntegerType *i8 = CGF.Int8Ty; 2321 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 2322 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 2323 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 2324 2325 // 0-31: r0-31, the 4-byte general-purpose registers 2326 AssignToArrayRange(Builder, Address, Four8, 0, 31); 2327 2328 // 32-63: fp0-31, the 8-byte floating-point registers 2329 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 2330 2331 // 64-76 are various 4-byte special-purpose registers: 2332 // 64: mq 2333 // 65: lr 2334 // 66: ctr 2335 // 67: ap 2336 // 68-75 cr0-7 2337 // 76: xer 2338 AssignToArrayRange(Builder, Address, Four8, 64, 76); 2339 2340 // 77-108: v0-31, the 16-byte vector registers 2341 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 2342 2343 // 109: vrsave 2344 // 110: vscr 2345 // 111: spe_acc 2346 // 112: spefscr 2347 // 113: sfp 2348 AssignToArrayRange(Builder, Address, Four8, 109, 113); 2349 2350 return false; 2351 } 2352 2353 2354 //===----------------------------------------------------------------------===// 2355 // ARM ABI Implementation 2356 //===----------------------------------------------------------------------===// 2357 2358 namespace { 2359 2360 class ARMABIInfo : public ABIInfo { 2361 public: 2362 enum ABIKind { 2363 APCS = 0, 2364 AAPCS = 1, 2365 AAPCS_VFP 2366 }; 2367 2368 private: 2369 ABIKind Kind; 2370 2371 public: 2372 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {} 2373 2374 bool isEABI() const { 2375 StringRef Env = 2376 getContext().getTargetInfo().getTriple().getEnvironmentName(); 2377 return (Env == "gnueabi" || Env == "eabi" || Env == "androideabi"); 2378 } 2379 2380 private: 2381 ABIKind getABIKind() const { return Kind; } 2382 2383 ABIArgInfo classifyReturnType(QualType RetTy) const; 2384 ABIArgInfo classifyArgumentType(QualType RetTy) const; 2385 2386 virtual void computeInfo(CGFunctionInfo &FI) const; 2387 2388 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2389 CodeGenFunction &CGF) const; 2390 }; 2391 2392 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 2393 public: 2394 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 2395 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {} 2396 2397 const ARMABIInfo &getABIInfo() const { 2398 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2399 } 2400 2401 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 2402 return 13; 2403 } 2404 2405 StringRef getARCRetainAutoreleasedReturnValueMarker() const { 2406 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue"; 2407 } 2408 2409 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2410 llvm::Value *Address) const { 2411 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2412 2413 // 0-15 are the 16 integer registers. 2414 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 2415 return false; 2416 } 2417 2418 unsigned getSizeOfUnwindException() const { 2419 if (getABIInfo().isEABI()) return 88; 2420 return TargetCodeGenInfo::getSizeOfUnwindException(); 2421 } 2422 }; 2423 2424 } 2425 2426 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 2427 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 2428 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2429 it != ie; ++it) 2430 it->info = classifyArgumentType(it->type); 2431 2432 // Always honor user-specified calling convention. 2433 if (FI.getCallingConvention() != llvm::CallingConv::C) 2434 return; 2435 2436 // Calling convention as default by an ABI. 2437 llvm::CallingConv::ID DefaultCC; 2438 if (isEABI()) 2439 DefaultCC = llvm::CallingConv::ARM_AAPCS; 2440 else 2441 DefaultCC = llvm::CallingConv::ARM_APCS; 2442 2443 // If user did not ask for specific calling convention explicitly (e.g. via 2444 // pcs attribute), set effective calling convention if it's different than ABI 2445 // default. 2446 switch (getABIKind()) { 2447 case APCS: 2448 if (DefaultCC != llvm::CallingConv::ARM_APCS) 2449 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_APCS); 2450 break; 2451 case AAPCS: 2452 if (DefaultCC != llvm::CallingConv::ARM_AAPCS) 2453 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS); 2454 break; 2455 case AAPCS_VFP: 2456 if (DefaultCC != llvm::CallingConv::ARM_AAPCS_VFP) 2457 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS_VFP); 2458 break; 2459 } 2460 } 2461 2462 /// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous 2463 /// aggregate. If HAMembers is non-null, the number of base elements 2464 /// contained in the type is returned through it; this is used for the 2465 /// recursive calls that check aggregate component types. 2466 static bool isHomogeneousAggregate(QualType Ty, const Type *&Base, 2467 ASTContext &Context, 2468 uint64_t *HAMembers = 0) { 2469 uint64_t Members; 2470 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 2471 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members)) 2472 return false; 2473 Members *= AT->getSize().getZExtValue(); 2474 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 2475 const RecordDecl *RD = RT->getDecl(); 2476 if (RD->isUnion() || RD->hasFlexibleArrayMember()) 2477 return false; 2478 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 2479 if (!CXXRD->isAggregate()) 2480 return false; 2481 } 2482 Members = 0; 2483 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 2484 i != e; ++i) { 2485 const FieldDecl *FD = *i; 2486 uint64_t FldMembers; 2487 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers)) 2488 return false; 2489 Members += FldMembers; 2490 } 2491 } else { 2492 Members = 1; 2493 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2494 Members = 2; 2495 Ty = CT->getElementType(); 2496 } 2497 2498 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 2499 // double, or 64-bit or 128-bit vectors. 2500 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2501 if (BT->getKind() != BuiltinType::Float && 2502 BT->getKind() != BuiltinType::Double) 2503 return false; 2504 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 2505 unsigned VecSize = Context.getTypeSize(VT); 2506 if (VecSize != 64 && VecSize != 128) 2507 return false; 2508 } else { 2509 return false; 2510 } 2511 2512 // The base type must be the same for all members. Vector types of the 2513 // same total size are treated as being equivalent here. 2514 const Type *TyPtr = Ty.getTypePtr(); 2515 if (!Base) 2516 Base = TyPtr; 2517 if (Base != TyPtr && 2518 (!Base->isVectorType() || !TyPtr->isVectorType() || 2519 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr))) 2520 return false; 2521 } 2522 2523 // Homogeneous Aggregates can have at most 4 members of the base type. 2524 if (HAMembers) 2525 *HAMembers = Members; 2526 return (Members <= 4); 2527 } 2528 2529 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty) const { 2530 if (!isAggregateTypeForABI(Ty)) { 2531 // Treat an enum type as its underlying type. 2532 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2533 Ty = EnumTy->getDecl()->getIntegerType(); 2534 2535 return (Ty->isPromotableIntegerType() ? 2536 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 2537 } 2538 2539 // Ignore empty records. 2540 if (isEmptyRecord(getContext(), Ty, true)) 2541 return ABIArgInfo::getIgnore(); 2542 2543 // Structures with either a non-trivial destructor or a non-trivial 2544 // copy constructor are always indirect. 2545 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) 2546 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2547 2548 if (getABIKind() == ARMABIInfo::AAPCS_VFP) { 2549 // Homogeneous Aggregates need to be expanded. 2550 const Type *Base = 0; 2551 if (isHomogeneousAggregate(Ty, Base, getContext())) 2552 return ABIArgInfo::getExpand(); 2553 } 2554 2555 // Otherwise, pass by coercing to a structure of the appropriate size. 2556 // 2557 // FIXME: This is kind of nasty... but there isn't much choice because the ARM 2558 // backend doesn't support byval. 2559 // FIXME: This doesn't handle alignment > 64 bits. 2560 llvm::Type* ElemTy; 2561 unsigned SizeRegs; 2562 if (getContext().getTypeAlign(Ty) > 32) { 2563 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 2564 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 2565 } else { 2566 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 2567 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 2568 } 2569 2570 llvm::Type *STy = 2571 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL); 2572 return ABIArgInfo::getDirect(STy); 2573 } 2574 2575 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 2576 llvm::LLVMContext &VMContext) { 2577 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 2578 // is called integer-like if its size is less than or equal to one word, and 2579 // the offset of each of its addressable sub-fields is zero. 2580 2581 uint64_t Size = Context.getTypeSize(Ty); 2582 2583 // Check that the type fits in a word. 2584 if (Size > 32) 2585 return false; 2586 2587 // FIXME: Handle vector types! 2588 if (Ty->isVectorType()) 2589 return false; 2590 2591 // Float types are never treated as "integer like". 2592 if (Ty->isRealFloatingType()) 2593 return false; 2594 2595 // If this is a builtin or pointer type then it is ok. 2596 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 2597 return true; 2598 2599 // Small complex integer types are "integer like". 2600 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 2601 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 2602 2603 // Single element and zero sized arrays should be allowed, by the definition 2604 // above, but they are not. 2605 2606 // Otherwise, it must be a record type. 2607 const RecordType *RT = Ty->getAs<RecordType>(); 2608 if (!RT) return false; 2609 2610 // Ignore records with flexible arrays. 2611 const RecordDecl *RD = RT->getDecl(); 2612 if (RD->hasFlexibleArrayMember()) 2613 return false; 2614 2615 // Check that all sub-fields are at offset 0, and are themselves "integer 2616 // like". 2617 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 2618 2619 bool HadField = false; 2620 unsigned idx = 0; 2621 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 2622 i != e; ++i, ++idx) { 2623 const FieldDecl *FD = *i; 2624 2625 // Bit-fields are not addressable, we only need to verify they are "integer 2626 // like". We still have to disallow a subsequent non-bitfield, for example: 2627 // struct { int : 0; int x } 2628 // is non-integer like according to gcc. 2629 if (FD->isBitField()) { 2630 if (!RD->isUnion()) 2631 HadField = true; 2632 2633 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 2634 return false; 2635 2636 continue; 2637 } 2638 2639 // Check if this field is at offset 0. 2640 if (Layout.getFieldOffset(idx) != 0) 2641 return false; 2642 2643 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 2644 return false; 2645 2646 // Only allow at most one field in a structure. This doesn't match the 2647 // wording above, but follows gcc in situations with a field following an 2648 // empty structure. 2649 if (!RD->isUnion()) { 2650 if (HadField) 2651 return false; 2652 2653 HadField = true; 2654 } 2655 } 2656 2657 return true; 2658 } 2659 2660 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const { 2661 if (RetTy->isVoidType()) 2662 return ABIArgInfo::getIgnore(); 2663 2664 // Large vector types should be returned via memory. 2665 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 2666 return ABIArgInfo::getIndirect(0); 2667 2668 if (!isAggregateTypeForABI(RetTy)) { 2669 // Treat an enum type as its underlying type. 2670 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 2671 RetTy = EnumTy->getDecl()->getIntegerType(); 2672 2673 return (RetTy->isPromotableIntegerType() ? 2674 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 2675 } 2676 2677 // Structures with either a non-trivial destructor or a non-trivial 2678 // copy constructor are always indirect. 2679 if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy)) 2680 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2681 2682 // Are we following APCS? 2683 if (getABIKind() == APCS) { 2684 if (isEmptyRecord(getContext(), RetTy, false)) 2685 return ABIArgInfo::getIgnore(); 2686 2687 // Complex types are all returned as packed integers. 2688 // 2689 // FIXME: Consider using 2 x vector types if the back end handles them 2690 // correctly. 2691 if (RetTy->isAnyComplexType()) 2692 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2693 getContext().getTypeSize(RetTy))); 2694 2695 // Integer like structures are returned in r0. 2696 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 2697 // Return in the smallest viable integer type. 2698 uint64_t Size = getContext().getTypeSize(RetTy); 2699 if (Size <= 8) 2700 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 2701 if (Size <= 16) 2702 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 2703 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 2704 } 2705 2706 // Otherwise return in memory. 2707 return ABIArgInfo::getIndirect(0); 2708 } 2709 2710 // Otherwise this is an AAPCS variant. 2711 2712 if (isEmptyRecord(getContext(), RetTy, true)) 2713 return ABIArgInfo::getIgnore(); 2714 2715 // Check for homogeneous aggregates with AAPCS-VFP. 2716 if (getABIKind() == AAPCS_VFP) { 2717 const Type *Base = 0; 2718 if (isHomogeneousAggregate(RetTy, Base, getContext())) 2719 // Homogeneous Aggregates are returned directly. 2720 return ABIArgInfo::getDirect(); 2721 } 2722 2723 // Aggregates <= 4 bytes are returned in r0; other aggregates 2724 // are returned indirectly. 2725 uint64_t Size = getContext().getTypeSize(RetTy); 2726 if (Size <= 32) { 2727 // Return in the smallest viable integer type. 2728 if (Size <= 8) 2729 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 2730 if (Size <= 16) 2731 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 2732 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 2733 } 2734 2735 return ABIArgInfo::getIndirect(0); 2736 } 2737 2738 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2739 CodeGenFunction &CGF) const { 2740 llvm::Type *BP = CGF.Int8PtrTy; 2741 llvm::Type *BPP = CGF.Int8PtrPtrTy; 2742 2743 CGBuilderTy &Builder = CGF.Builder; 2744 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 2745 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 2746 // Handle address alignment for type alignment > 32 bits 2747 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 2748 if (TyAlign > 4) { 2749 assert((TyAlign & (TyAlign - 1)) == 0 && 2750 "Alignment is not power of 2!"); 2751 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 2752 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 2753 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 2754 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 2755 } 2756 llvm::Type *PTy = 2757 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 2758 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 2759 2760 uint64_t Offset = 2761 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4); 2762 llvm::Value *NextAddr = 2763 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 2764 "ap.next"); 2765 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 2766 2767 return AddrTyped; 2768 } 2769 2770 //===----------------------------------------------------------------------===// 2771 // PTX ABI Implementation 2772 //===----------------------------------------------------------------------===// 2773 2774 namespace { 2775 2776 class PTXABIInfo : public ABIInfo { 2777 public: 2778 PTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 2779 2780 ABIArgInfo classifyReturnType(QualType RetTy) const; 2781 ABIArgInfo classifyArgumentType(QualType Ty) const; 2782 2783 virtual void computeInfo(CGFunctionInfo &FI) const; 2784 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2785 CodeGenFunction &CFG) const; 2786 }; 2787 2788 class PTXTargetCodeGenInfo : public TargetCodeGenInfo { 2789 public: 2790 PTXTargetCodeGenInfo(CodeGenTypes &CGT) 2791 : TargetCodeGenInfo(new PTXABIInfo(CGT)) {} 2792 2793 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2794 CodeGen::CodeGenModule &M) const; 2795 }; 2796 2797 ABIArgInfo PTXABIInfo::classifyReturnType(QualType RetTy) const { 2798 if (RetTy->isVoidType()) 2799 return ABIArgInfo::getIgnore(); 2800 if (isAggregateTypeForABI(RetTy)) 2801 return ABIArgInfo::getIndirect(0); 2802 return ABIArgInfo::getDirect(); 2803 } 2804 2805 ABIArgInfo PTXABIInfo::classifyArgumentType(QualType Ty) const { 2806 if (isAggregateTypeForABI(Ty)) 2807 return ABIArgInfo::getIndirect(0); 2808 2809 return ABIArgInfo::getDirect(); 2810 } 2811 2812 void PTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 2813 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 2814 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2815 it != ie; ++it) 2816 it->info = classifyArgumentType(it->type); 2817 2818 // Always honor user-specified calling convention. 2819 if (FI.getCallingConvention() != llvm::CallingConv::C) 2820 return; 2821 2822 // Calling convention as default by an ABI. 2823 llvm::CallingConv::ID DefaultCC; 2824 const LangOptions &LangOpts = getContext().getLangOptions(); 2825 if (LangOpts.OpenCL || LangOpts.CUDA) { 2826 // If we are in OpenCL or CUDA mode, then default to device functions 2827 DefaultCC = llvm::CallingConv::PTX_Device; 2828 } else { 2829 // If we are in standard C/C++ mode, use the triple to decide on the default 2830 StringRef Env = 2831 getContext().getTargetInfo().getTriple().getEnvironmentName(); 2832 if (Env == "device") 2833 DefaultCC = llvm::CallingConv::PTX_Device; 2834 else 2835 DefaultCC = llvm::CallingConv::PTX_Kernel; 2836 } 2837 FI.setEffectiveCallingConvention(DefaultCC); 2838 2839 } 2840 2841 llvm::Value *PTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2842 CodeGenFunction &CFG) const { 2843 llvm_unreachable("PTX does not support varargs"); 2844 } 2845 2846 void PTXTargetCodeGenInfo::SetTargetAttributes(const Decl *D, 2847 llvm::GlobalValue *GV, 2848 CodeGen::CodeGenModule &M) const{ 2849 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 2850 if (!FD) return; 2851 2852 llvm::Function *F = cast<llvm::Function>(GV); 2853 2854 // Perform special handling in OpenCL mode 2855 if (M.getLangOptions().OpenCL) { 2856 // Use OpenCL function attributes to set proper calling conventions 2857 // By default, all functions are device functions 2858 if (FD->hasAttr<OpenCLKernelAttr>()) { 2859 // OpenCL __kernel functions get a kernel calling convention 2860 F->setCallingConv(llvm::CallingConv::PTX_Kernel); 2861 // And kernel functions are not subject to inlining 2862 F->addFnAttr(llvm::Attribute::NoInline); 2863 } 2864 } 2865 2866 // Perform special handling in CUDA mode. 2867 if (M.getLangOptions().CUDA) { 2868 // CUDA __global__ functions get a kernel calling convention. Since 2869 // __global__ functions cannot be called from the device, we do not 2870 // need to set the noinline attribute. 2871 if (FD->getAttr<CUDAGlobalAttr>()) 2872 F->setCallingConv(llvm::CallingConv::PTX_Kernel); 2873 } 2874 } 2875 2876 } 2877 2878 //===----------------------------------------------------------------------===// 2879 // MBlaze ABI Implementation 2880 //===----------------------------------------------------------------------===// 2881 2882 namespace { 2883 2884 class MBlazeABIInfo : public ABIInfo { 2885 public: 2886 MBlazeABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 2887 2888 bool isPromotableIntegerType(QualType Ty) const; 2889 2890 ABIArgInfo classifyReturnType(QualType RetTy) const; 2891 ABIArgInfo classifyArgumentType(QualType RetTy) const; 2892 2893 virtual void computeInfo(CGFunctionInfo &FI) const { 2894 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 2895 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2896 it != ie; ++it) 2897 it->info = classifyArgumentType(it->type); 2898 } 2899 2900 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2901 CodeGenFunction &CGF) const; 2902 }; 2903 2904 class MBlazeTargetCodeGenInfo : public TargetCodeGenInfo { 2905 public: 2906 MBlazeTargetCodeGenInfo(CodeGenTypes &CGT) 2907 : TargetCodeGenInfo(new MBlazeABIInfo(CGT)) {} 2908 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2909 CodeGen::CodeGenModule &M) const; 2910 }; 2911 2912 } 2913 2914 bool MBlazeABIInfo::isPromotableIntegerType(QualType Ty) const { 2915 // MBlaze ABI requires all 8 and 16 bit quantities to be extended. 2916 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 2917 switch (BT->getKind()) { 2918 case BuiltinType::Bool: 2919 case BuiltinType::Char_S: 2920 case BuiltinType::Char_U: 2921 case BuiltinType::SChar: 2922 case BuiltinType::UChar: 2923 case BuiltinType::Short: 2924 case BuiltinType::UShort: 2925 return true; 2926 default: 2927 return false; 2928 } 2929 return false; 2930 } 2931 2932 llvm::Value *MBlazeABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2933 CodeGenFunction &CGF) const { 2934 // FIXME: Implement 2935 return 0; 2936 } 2937 2938 2939 ABIArgInfo MBlazeABIInfo::classifyReturnType(QualType RetTy) const { 2940 if (RetTy->isVoidType()) 2941 return ABIArgInfo::getIgnore(); 2942 if (isAggregateTypeForABI(RetTy)) 2943 return ABIArgInfo::getIndirect(0); 2944 2945 return (isPromotableIntegerType(RetTy) ? 2946 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 2947 } 2948 2949 ABIArgInfo MBlazeABIInfo::classifyArgumentType(QualType Ty) const { 2950 if (isAggregateTypeForABI(Ty)) 2951 return ABIArgInfo::getIndirect(0); 2952 2953 return (isPromotableIntegerType(Ty) ? 2954 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 2955 } 2956 2957 void MBlazeTargetCodeGenInfo::SetTargetAttributes(const Decl *D, 2958 llvm::GlobalValue *GV, 2959 CodeGen::CodeGenModule &M) 2960 const { 2961 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 2962 if (!FD) return; 2963 2964 llvm::CallingConv::ID CC = llvm::CallingConv::C; 2965 if (FD->hasAttr<MBlazeInterruptHandlerAttr>()) 2966 CC = llvm::CallingConv::MBLAZE_INTR; 2967 else if (FD->hasAttr<MBlazeSaveVolatilesAttr>()) 2968 CC = llvm::CallingConv::MBLAZE_SVOL; 2969 2970 if (CC != llvm::CallingConv::C) { 2971 // Handle 'interrupt_handler' attribute: 2972 llvm::Function *F = cast<llvm::Function>(GV); 2973 2974 // Step 1: Set ISR calling convention. 2975 F->setCallingConv(CC); 2976 2977 // Step 2: Add attributes goodness. 2978 F->addFnAttr(llvm::Attribute::NoInline); 2979 } 2980 2981 // Step 3: Emit _interrupt_handler alias. 2982 if (CC == llvm::CallingConv::MBLAZE_INTR) 2983 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage, 2984 "_interrupt_handler", GV, &M.getModule()); 2985 } 2986 2987 2988 //===----------------------------------------------------------------------===// 2989 // MSP430 ABI Implementation 2990 //===----------------------------------------------------------------------===// 2991 2992 namespace { 2993 2994 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 2995 public: 2996 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 2997 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 2998 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2999 CodeGen::CodeGenModule &M) const; 3000 }; 3001 3002 } 3003 3004 void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D, 3005 llvm::GlobalValue *GV, 3006 CodeGen::CodeGenModule &M) const { 3007 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 3008 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) { 3009 // Handle 'interrupt' attribute: 3010 llvm::Function *F = cast<llvm::Function>(GV); 3011 3012 // Step 1: Set ISR calling convention. 3013 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 3014 3015 // Step 2: Add attributes goodness. 3016 F->addFnAttr(llvm::Attribute::NoInline); 3017 3018 // Step 3: Emit ISR vector alias. 3019 unsigned Num = attr->getNumber() + 0xffe0; 3020 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage, 3021 "vector_" + Twine::utohexstr(Num), 3022 GV, &M.getModule()); 3023 } 3024 } 3025 } 3026 3027 //===----------------------------------------------------------------------===// 3028 // MIPS ABI Implementation. This works for both little-endian and 3029 // big-endian variants. 3030 //===----------------------------------------------------------------------===// 3031 3032 namespace { 3033 class MipsABIInfo : public ABIInfo { 3034 bool IsO32; 3035 unsigned MinABIStackAlignInBytes; 3036 llvm::Type* HandleAggregates(QualType Ty) const; 3037 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 3038 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 3039 public: 3040 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 3041 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8) {} 3042 3043 ABIArgInfo classifyReturnType(QualType RetTy) const; 3044 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 3045 virtual void computeInfo(CGFunctionInfo &FI) const; 3046 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3047 CodeGenFunction &CGF) const; 3048 }; 3049 3050 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 3051 unsigned SizeOfUnwindException; 3052 public: 3053 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 3054 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)), 3055 SizeOfUnwindException(IsO32 ? 24 : 32) {} 3056 3057 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 3058 return 29; 3059 } 3060 3061 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3062 llvm::Value *Address) const; 3063 3064 unsigned getSizeOfUnwindException() const { 3065 return SizeOfUnwindException; 3066 } 3067 }; 3068 } 3069 3070 // In N32/64, an aligned double precision floating point field is passed in 3071 // a register. 3072 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty) const { 3073 if (IsO32) 3074 return 0; 3075 3076 if (Ty->isComplexType()) 3077 return CGT.ConvertType(Ty); 3078 3079 const RecordType *RT = Ty->getAs<RecordType>(); 3080 3081 // Unions are passed in integer registers. 3082 if (!RT || !RT->isStructureOrClassType()) 3083 return 0; 3084 3085 const RecordDecl *RD = RT->getDecl(); 3086 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 3087 uint64_t StructSize = getContext().getTypeSize(Ty); 3088 assert(!(StructSize % 8) && "Size of structure must be multiple of 8."); 3089 3090 uint64_t LastOffset = 0; 3091 unsigned idx = 0; 3092 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 3093 SmallVector<llvm::Type*, 8> ArgList; 3094 3095 // Iterate over fields in the struct/class and check if there are any aligned 3096 // double fields. 3097 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3098 i != e; ++i, ++idx) { 3099 const QualType Ty = (*i)->getType(); 3100 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 3101 3102 if (!BT || BT->getKind() != BuiltinType::Double) 3103 continue; 3104 3105 uint64_t Offset = Layout.getFieldOffset(idx); 3106 if (Offset % 64) // Ignore doubles that are not aligned. 3107 continue; 3108 3109 // Add ((Offset - LastOffset) / 64) args of type i64. 3110 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 3111 ArgList.push_back(I64); 3112 3113 // Add double type. 3114 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 3115 LastOffset = Offset + 64; 3116 } 3117 3118 // This struct/class doesn't have an aligned double field. 3119 if (!LastOffset) 3120 return 0; 3121 3122 // Add ((StructSize - LastOffset) / 64) args of type i64. 3123 for (unsigned N = (StructSize - LastOffset) / 64; N; --N) 3124 ArgList.push_back(I64); 3125 3126 // If the size of the remainder is not zero, add one more integer type to 3127 // ArgList. 3128 unsigned R = (StructSize - LastOffset) % 64; 3129 if (R) 3130 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 3131 3132 return llvm::StructType::get(getVMContext(), ArgList); 3133 } 3134 3135 llvm::Type *MipsABIInfo::getPaddingType(uint64_t Align, uint64_t Offset) const { 3136 // Padding is inserted only for N32/64. 3137 if (IsO32) 3138 return 0; 3139 3140 assert(Align <= 16 && "Alignment larger than 16 not handled."); 3141 return (Align == 16 && Offset & 0xf) ? 3142 llvm::IntegerType::get(getVMContext(), 64) : 0; 3143 } 3144 3145 ABIArgInfo 3146 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 3147 uint64_t OrigOffset = Offset; 3148 uint64_t TySize = 3149 llvm::RoundUpToAlignment(getContext().getTypeSize(Ty), 64) / 8; 3150 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 3151 Offset = llvm::RoundUpToAlignment(Offset, std::max(Align, (uint64_t)8)); 3152 Offset += TySize; 3153 3154 if (isAggregateTypeForABI(Ty)) { 3155 // Ignore empty aggregates. 3156 if (TySize == 0) 3157 return ABIArgInfo::getIgnore(); 3158 3159 // Records with non trivial destructors/constructors should not be passed 3160 // by value. 3161 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) { 3162 Offset = OrigOffset + 8; 3163 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3164 } 3165 3166 // If we have reached here, aggregates are passed either indirectly via a 3167 // byval pointer or directly by coercing to another structure type. In the 3168 // latter case, padding is inserted if the offset of the aggregate is 3169 // unaligned. 3170 llvm::Type *ResType = HandleAggregates(Ty); 3171 3172 if (!ResType) 3173 return ABIArgInfo::getIndirect(0); 3174 3175 return ABIArgInfo::getDirect(ResType, 0, getPaddingType(Align, OrigOffset)); 3176 } 3177 3178 // Treat an enum type as its underlying type. 3179 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3180 Ty = EnumTy->getDecl()->getIntegerType(); 3181 3182 if (Ty->isPromotableIntegerType()) 3183 return ABIArgInfo::getExtend(); 3184 3185 return ABIArgInfo::getDirect(0, 0, getPaddingType(Align, OrigOffset)); 3186 } 3187 3188 llvm::Type* 3189 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 3190 const RecordType *RT = RetTy->getAs<RecordType>(); 3191 SmallVector<llvm::Type*, 2> RTList; 3192 3193 if (RT && RT->isStructureOrClassType()) { 3194 const RecordDecl *RD = RT->getDecl(); 3195 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 3196 unsigned FieldCnt = Layout.getFieldCount(); 3197 3198 // N32/64 returns struct/classes in floating point registers if the 3199 // following conditions are met: 3200 // 1. The size of the struct/class is no larger than 128-bit. 3201 // 2. The struct/class has one or two fields all of which are floating 3202 // point types. 3203 // 3. The offset of the first field is zero (this follows what gcc does). 3204 // 3205 // Any other composite results are returned in integer registers. 3206 // 3207 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 3208 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 3209 for (; b != e; ++b) { 3210 const BuiltinType *BT = (*b)->getType()->getAs<BuiltinType>(); 3211 3212 if (!BT || !BT->isFloatingPoint()) 3213 break; 3214 3215 RTList.push_back(CGT.ConvertType((*b)->getType())); 3216 } 3217 3218 if (b == e) 3219 return llvm::StructType::get(getVMContext(), RTList, 3220 RD->hasAttr<PackedAttr>()); 3221 3222 RTList.clear(); 3223 } 3224 } 3225 3226 RTList.push_back(llvm::IntegerType::get(getVMContext(), 3227 std::min(Size, (uint64_t)64))); 3228 if (Size > 64) 3229 RTList.push_back(llvm::IntegerType::get(getVMContext(), Size - 64)); 3230 3231 return llvm::StructType::get(getVMContext(), RTList); 3232 } 3233 3234 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 3235 uint64_t Size = getContext().getTypeSize(RetTy); 3236 3237 if (RetTy->isVoidType() || Size == 0) 3238 return ABIArgInfo::getIgnore(); 3239 3240 if (isAggregateTypeForABI(RetTy)) { 3241 if (Size <= 128) { 3242 if (RetTy->isAnyComplexType()) 3243 return ABIArgInfo::getDirect(); 3244 3245 if (!IsO32 && !isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy)) 3246 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 3247 } 3248 3249 return ABIArgInfo::getIndirect(0); 3250 } 3251 3252 // Treat an enum type as its underlying type. 3253 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3254 RetTy = EnumTy->getDecl()->getIntegerType(); 3255 3256 return (RetTy->isPromotableIntegerType() ? 3257 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3258 } 3259 3260 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 3261 ABIArgInfo &RetInfo = FI.getReturnInfo(); 3262 RetInfo = classifyReturnType(FI.getReturnType()); 3263 3264 // Check if a pointer to an aggregate is passed as a hidden argument. 3265 uint64_t Offset = RetInfo.isIndirect() ? 8 : 0; 3266 3267 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3268 it != ie; ++it) 3269 it->info = classifyArgumentType(it->type, Offset); 3270 } 3271 3272 llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3273 CodeGenFunction &CGF) const { 3274 llvm::Type *BP = CGF.Int8PtrTy; 3275 llvm::Type *BPP = CGF.Int8PtrPtrTy; 3276 3277 CGBuilderTy &Builder = CGF.Builder; 3278 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 3279 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 3280 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8; 3281 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 3282 llvm::Value *AddrTyped; 3283 unsigned PtrWidth = getContext().getTargetInfo().getPointerWidth(0); 3284 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty; 3285 3286 if (TypeAlign > MinABIStackAlignInBytes) { 3287 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy); 3288 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1); 3289 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign); 3290 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc); 3291 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask); 3292 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy); 3293 } 3294 else 3295 AddrTyped = Builder.CreateBitCast(Addr, PTy); 3296 3297 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP); 3298 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes); 3299 uint64_t Offset = 3300 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign); 3301 llvm::Value *NextAddr = 3302 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset), 3303 "ap.next"); 3304 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 3305 3306 return AddrTyped; 3307 } 3308 3309 bool 3310 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3311 llvm::Value *Address) const { 3312 // This information comes from gcc's implementation, which seems to 3313 // as canonical as it gets. 3314 3315 // Everything on MIPS is 4 bytes. Double-precision FP registers 3316 // are aliased to pairs of single-precision FP registers. 3317 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 3318 3319 // 0-31 are the general purpose registers, $0 - $31. 3320 // 32-63 are the floating-point registers, $f0 - $f31. 3321 // 64 and 65 are the multiply/divide registers, $hi and $lo. 3322 // 66 is the (notional, I think) register for signal-handler return. 3323 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 3324 3325 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 3326 // They are one bit wide and ignored here. 3327 3328 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 3329 // (coprocessor 1 is the FP unit) 3330 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 3331 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 3332 // 176-181 are the DSP accumulator registers. 3333 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 3334 return false; 3335 } 3336 3337 //===----------------------------------------------------------------------===// 3338 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 3339 // Currently subclassed only to implement custom OpenCL C function attribute 3340 // handling. 3341 //===----------------------------------------------------------------------===// 3342 3343 namespace { 3344 3345 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 3346 public: 3347 TCETargetCodeGenInfo(CodeGenTypes &CGT) 3348 : DefaultTargetCodeGenInfo(CGT) {} 3349 3350 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 3351 CodeGen::CodeGenModule &M) const; 3352 }; 3353 3354 void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D, 3355 llvm::GlobalValue *GV, 3356 CodeGen::CodeGenModule &M) const { 3357 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 3358 if (!FD) return; 3359 3360 llvm::Function *F = cast<llvm::Function>(GV); 3361 3362 if (M.getLangOptions().OpenCL) { 3363 if (FD->hasAttr<OpenCLKernelAttr>()) { 3364 // OpenCL C Kernel functions are not subject to inlining 3365 F->addFnAttr(llvm::Attribute::NoInline); 3366 3367 if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) { 3368 3369 // Convert the reqd_work_group_size() attributes to metadata. 3370 llvm::LLVMContext &Context = F->getContext(); 3371 llvm::NamedMDNode *OpenCLMetadata = 3372 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info"); 3373 3374 SmallVector<llvm::Value*, 5> Operands; 3375 Operands.push_back(F); 3376 3377 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 3378 llvm::APInt(32, 3379 FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim()))); 3380 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 3381 llvm::APInt(32, 3382 FD->getAttr<ReqdWorkGroupSizeAttr>()->getYDim()))); 3383 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 3384 llvm::APInt(32, 3385 FD->getAttr<ReqdWorkGroupSizeAttr>()->getZDim()))); 3386 3387 // Add a boolean constant operand for "required" (true) or "hint" (false) 3388 // for implementing the work_group_size_hint attr later. Currently 3389 // always true as the hint is not yet implemented. 3390 Operands.push_back(llvm::ConstantInt::getTrue(Context)); 3391 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 3392 } 3393 } 3394 } 3395 } 3396 3397 } 3398 3399 //===----------------------------------------------------------------------===// 3400 // Hexagon ABI Implementation 3401 //===----------------------------------------------------------------------===// 3402 3403 namespace { 3404 3405 class HexagonABIInfo : public ABIInfo { 3406 3407 3408 public: 3409 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 3410 3411 private: 3412 3413 ABIArgInfo classifyReturnType(QualType RetTy) const; 3414 ABIArgInfo classifyArgumentType(QualType RetTy) const; 3415 3416 virtual void computeInfo(CGFunctionInfo &FI) const; 3417 3418 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3419 CodeGenFunction &CGF) const; 3420 }; 3421 3422 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 3423 public: 3424 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 3425 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {} 3426 3427 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 3428 return 29; 3429 } 3430 }; 3431 3432 } 3433 3434 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 3435 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3436 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3437 it != ie; ++it) 3438 it->info = classifyArgumentType(it->type); 3439 } 3440 3441 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const { 3442 if (!isAggregateTypeForABI(Ty)) { 3443 // Treat an enum type as its underlying type. 3444 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3445 Ty = EnumTy->getDecl()->getIntegerType(); 3446 3447 return (Ty->isPromotableIntegerType() ? 3448 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3449 } 3450 3451 // Ignore empty records. 3452 if (isEmptyRecord(getContext(), Ty, true)) 3453 return ABIArgInfo::getIgnore(); 3454 3455 // Structures with either a non-trivial destructor or a non-trivial 3456 // copy constructor are always indirect. 3457 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) 3458 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3459 3460 uint64_t Size = getContext().getTypeSize(Ty); 3461 if (Size > 64) 3462 return ABIArgInfo::getIndirect(0, /*ByVal=*/true); 3463 // Pass in the smallest viable integer type. 3464 else if (Size > 32) 3465 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 3466 else if (Size > 16) 3467 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 3468 else if (Size > 8) 3469 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 3470 else 3471 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 3472 } 3473 3474 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 3475 if (RetTy->isVoidType()) 3476 return ABIArgInfo::getIgnore(); 3477 3478 // Large vector types should be returned via memory. 3479 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64) 3480 return ABIArgInfo::getIndirect(0); 3481 3482 if (!isAggregateTypeForABI(RetTy)) { 3483 // Treat an enum type as its underlying type. 3484 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3485 RetTy = EnumTy->getDecl()->getIntegerType(); 3486 3487 return (RetTy->isPromotableIntegerType() ? 3488 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3489 } 3490 3491 // Structures with either a non-trivial destructor or a non-trivial 3492 // copy constructor are always indirect. 3493 if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy)) 3494 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3495 3496 if (isEmptyRecord(getContext(), RetTy, true)) 3497 return ABIArgInfo::getIgnore(); 3498 3499 // Aggregates <= 8 bytes are returned in r0; other aggregates 3500 // are returned indirectly. 3501 uint64_t Size = getContext().getTypeSize(RetTy); 3502 if (Size <= 64) { 3503 // Return in the smallest viable integer type. 3504 if (Size <= 8) 3505 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 3506 if (Size <= 16) 3507 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 3508 if (Size <= 32) 3509 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 3510 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 3511 } 3512 3513 return ABIArgInfo::getIndirect(0, /*ByVal=*/true); 3514 } 3515 3516 llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3517 CodeGenFunction &CGF) const { 3518 // FIXME: Need to handle alignment 3519 llvm::Type *BPP = CGF.Int8PtrPtrTy; 3520 3521 CGBuilderTy &Builder = CGF.Builder; 3522 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 3523 "ap"); 3524 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 3525 llvm::Type *PTy = 3526 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 3527 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 3528 3529 uint64_t Offset = 3530 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4); 3531 llvm::Value *NextAddr = 3532 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 3533 "ap.next"); 3534 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 3535 3536 return AddrTyped; 3537 } 3538 3539 3540 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 3541 if (TheTargetCodeGenInfo) 3542 return *TheTargetCodeGenInfo; 3543 3544 const llvm::Triple &Triple = getContext().getTargetInfo().getTriple(); 3545 switch (Triple.getArch()) { 3546 default: 3547 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types)); 3548 3549 case llvm::Triple::mips: 3550 case llvm::Triple::mipsel: 3551 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true)); 3552 3553 case llvm::Triple::mips64: 3554 case llvm::Triple::mips64el: 3555 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false)); 3556 3557 case llvm::Triple::arm: 3558 case llvm::Triple::thumb: 3559 { 3560 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 3561 3562 if (strcmp(getContext().getTargetInfo().getABI(), "apcs-gnu") == 0) 3563 Kind = ARMABIInfo::APCS; 3564 else if (CodeGenOpts.FloatABI == "hard") 3565 Kind = ARMABIInfo::AAPCS_VFP; 3566 3567 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind)); 3568 } 3569 3570 case llvm::Triple::ppc: 3571 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types)); 3572 3573 case llvm::Triple::ptx32: 3574 case llvm::Triple::ptx64: 3575 return *(TheTargetCodeGenInfo = new PTXTargetCodeGenInfo(Types)); 3576 3577 case llvm::Triple::mblaze: 3578 return *(TheTargetCodeGenInfo = new MBlazeTargetCodeGenInfo(Types)); 3579 3580 case llvm::Triple::msp430: 3581 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types)); 3582 3583 case llvm::Triple::tce: 3584 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types)); 3585 3586 case llvm::Triple::x86: { 3587 bool DisableMMX = strcmp(getContext().getTargetInfo().getABI(), "no-mmx") == 0; 3588 3589 if (Triple.isOSDarwin()) 3590 return *(TheTargetCodeGenInfo = 3591 new X86_32TargetCodeGenInfo( 3592 Types, true, true, DisableMMX, false)); 3593 3594 switch (Triple.getOS()) { 3595 case llvm::Triple::Cygwin: 3596 case llvm::Triple::MinGW32: 3597 case llvm::Triple::AuroraUX: 3598 case llvm::Triple::DragonFly: 3599 case llvm::Triple::FreeBSD: 3600 case llvm::Triple::OpenBSD: 3601 return *(TheTargetCodeGenInfo = 3602 new X86_32TargetCodeGenInfo( 3603 Types, false, true, DisableMMX, false)); 3604 3605 case llvm::Triple::Win32: 3606 return *(TheTargetCodeGenInfo = 3607 new X86_32TargetCodeGenInfo( 3608 Types, false, true, DisableMMX, true)); 3609 3610 default: 3611 return *(TheTargetCodeGenInfo = 3612 new X86_32TargetCodeGenInfo( 3613 Types, false, false, DisableMMX, false)); 3614 } 3615 } 3616 3617 case llvm::Triple::x86_64: { 3618 bool HasAVX = strcmp(getContext().getTargetInfo().getABI(), "avx") == 0; 3619 3620 switch (Triple.getOS()) { 3621 case llvm::Triple::Win32: 3622 case llvm::Triple::MinGW32: 3623 case llvm::Triple::Cygwin: 3624 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types)); 3625 default: 3626 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types, 3627 HasAVX)); 3628 } 3629 } 3630 case llvm::Triple::hexagon: 3631 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types)); 3632 } 3633 } 3634