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/ADT/Triple.h" 21 #include "llvm/IR/DataLayout.h" 22 #include "llvm/IR/Type.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::DataLayout &ABIInfo::getDataLayout() const { 55 return CGT.getDataLayout(); 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->hasNonTrivialCopyConstructor(); 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 // Treat complex types as the element type. 270 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 271 Ty = CTy->getElementType(); 272 273 // Check for a type which we know has a simple scalar argument-passing 274 // convention without any padding. (We're specifically looking for 32 275 // and 64-bit integer and integer-equivalents, float, and double.) 276 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 277 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 278 return false; 279 280 uint64_t Size = Context.getTypeSize(Ty); 281 return Size == 32 || Size == 64; 282 } 283 284 /// canExpandIndirectArgument - Test whether an argument type which is to be 285 /// passed indirectly (on the stack) would have the equivalent layout if it was 286 /// expanded into separate arguments. If so, we prefer to do the latter to avoid 287 /// inhibiting optimizations. 288 /// 289 // FIXME: This predicate is missing many cases, currently it just follows 290 // llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We 291 // should probably make this smarter, or better yet make the LLVM backend 292 // capable of handling it. 293 static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) { 294 // We can only expand structure types. 295 const RecordType *RT = Ty->getAs<RecordType>(); 296 if (!RT) 297 return false; 298 299 // We can only expand (C) structures. 300 // 301 // FIXME: This needs to be generalized to handle classes as well. 302 const RecordDecl *RD = RT->getDecl(); 303 if (!RD->isStruct() || isa<CXXRecordDecl>(RD)) 304 return false; 305 306 uint64_t Size = 0; 307 308 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 309 i != e; ++i) { 310 const FieldDecl *FD = *i; 311 312 if (!is32Or64BitBasicType(FD->getType(), Context)) 313 return false; 314 315 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 316 // how to expand them yet, and the predicate for telling if a bitfield still 317 // counts as "basic" is more complicated than what we were doing previously. 318 if (FD->isBitField()) 319 return false; 320 321 Size += Context.getTypeSize(FD->getType()); 322 } 323 324 // Make sure there are not any holes in the struct. 325 if (Size != Context.getTypeSize(Ty)) 326 return false; 327 328 return true; 329 } 330 331 namespace { 332 /// DefaultABIInfo - The default implementation for ABI specific 333 /// details. This implementation provides information which results in 334 /// self-consistent and sensible LLVM IR generation, but does not 335 /// conform to any particular ABI. 336 class DefaultABIInfo : public ABIInfo { 337 public: 338 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 339 340 ABIArgInfo classifyReturnType(QualType RetTy) const; 341 ABIArgInfo classifyArgumentType(QualType RetTy) const; 342 343 virtual void computeInfo(CGFunctionInfo &FI) const { 344 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 345 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 346 it != ie; ++it) 347 it->info = classifyArgumentType(it->type); 348 } 349 350 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 351 CodeGenFunction &CGF) const; 352 }; 353 354 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 355 public: 356 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 357 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 358 }; 359 360 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 361 CodeGenFunction &CGF) const { 362 return 0; 363 } 364 365 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 366 if (isAggregateTypeForABI(Ty)) { 367 // Records with non trivial destructors/constructors should not be passed 368 // by value. 369 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) 370 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 371 372 return ABIArgInfo::getIndirect(0); 373 } 374 375 // Treat an enum type as its underlying type. 376 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 377 Ty = EnumTy->getDecl()->getIntegerType(); 378 379 return (Ty->isPromotableIntegerType() ? 380 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 381 } 382 383 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 384 if (RetTy->isVoidType()) 385 return ABIArgInfo::getIgnore(); 386 387 if (isAggregateTypeForABI(RetTy)) 388 return ABIArgInfo::getIndirect(0); 389 390 // Treat an enum type as its underlying type. 391 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 392 RetTy = EnumTy->getDecl()->getIntegerType(); 393 394 return (RetTy->isPromotableIntegerType() ? 395 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 396 } 397 398 //===----------------------------------------------------------------------===// 399 // le32/PNaCl bitcode ABI Implementation 400 //===----------------------------------------------------------------------===// 401 402 class PNaClABIInfo : public ABIInfo { 403 public: 404 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 405 406 ABIArgInfo classifyReturnType(QualType RetTy) const; 407 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &FreeRegs) const; 408 409 virtual void computeInfo(CGFunctionInfo &FI) const; 410 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 411 CodeGenFunction &CGF) const; 412 }; 413 414 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 415 public: 416 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 417 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {} 418 }; 419 420 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 421 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 422 423 unsigned FreeRegs = FI.getHasRegParm() ? FI.getRegParm() : 0; 424 425 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 426 it != ie; ++it) 427 it->info = classifyArgumentType(it->type, FreeRegs); 428 } 429 430 llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 431 CodeGenFunction &CGF) const { 432 return 0; 433 } 434 435 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty, 436 unsigned &FreeRegs) const { 437 if (isAggregateTypeForABI(Ty)) { 438 // Records with non trivial destructors/constructors should not be passed 439 // by value. 440 FreeRegs = 0; 441 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) 442 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 443 444 return ABIArgInfo::getIndirect(0); 445 } 446 447 // Treat an enum type as its underlying type. 448 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 449 Ty = EnumTy->getDecl()->getIntegerType(); 450 451 ABIArgInfo BaseInfo = (Ty->isPromotableIntegerType() ? 452 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 453 454 // Regparm regs hold 32 bits. 455 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 456 if (SizeInRegs == 0) return BaseInfo; 457 if (SizeInRegs > FreeRegs) { 458 FreeRegs = 0; 459 return BaseInfo; 460 } 461 FreeRegs -= SizeInRegs; 462 return BaseInfo.isDirect() ? 463 ABIArgInfo::getDirectInReg(BaseInfo.getCoerceToType()) : 464 ABIArgInfo::getExtendInReg(BaseInfo.getCoerceToType()); 465 } 466 467 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 468 if (RetTy->isVoidType()) 469 return ABIArgInfo::getIgnore(); 470 471 if (isAggregateTypeForABI(RetTy)) 472 return ABIArgInfo::getIndirect(0); 473 474 // Treat an enum type as its underlying type. 475 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 476 RetTy = EnumTy->getDecl()->getIntegerType(); 477 478 return (RetTy->isPromotableIntegerType() ? 479 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 480 } 481 482 /// UseX86_MMXType - Return true if this is an MMX type that should use the 483 /// special x86_mmx type. 484 bool UseX86_MMXType(llvm::Type *IRType) { 485 // If the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>, use the 486 // special x86_mmx type. 487 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 488 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 489 IRType->getScalarSizeInBits() != 64; 490 } 491 492 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 493 StringRef Constraint, 494 llvm::Type* Ty) { 495 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) 496 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 497 return Ty; 498 } 499 500 //===----------------------------------------------------------------------===// 501 // X86-32 ABI Implementation 502 //===----------------------------------------------------------------------===// 503 504 /// X86_32ABIInfo - The X86-32 ABI information. 505 class X86_32ABIInfo : public ABIInfo { 506 enum Class { 507 Integer, 508 Float 509 }; 510 511 static const unsigned MinABIStackAlignInBytes = 4; 512 513 bool IsDarwinVectorABI; 514 bool IsSmallStructInRegABI; 515 bool IsMMXDisabled; 516 bool IsWin32FloatStructABI; 517 unsigned DefaultNumRegisterParameters; 518 519 static bool isRegisterSize(unsigned Size) { 520 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 521 } 522 523 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context, 524 unsigned callingConvention); 525 526 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 527 /// such that the argument will be passed in memory. 528 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, 529 unsigned &FreeRegs) const; 530 531 /// \brief Return the alignment to use for the given type on the stack. 532 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 533 534 Class classify(QualType Ty) const; 535 ABIArgInfo classifyReturnType(QualType RetTy, 536 unsigned callingConvention) const; 537 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &FreeRegs, 538 bool IsFastCall) const; 539 bool shouldUseInReg(QualType Ty, unsigned &FreeRegs, 540 bool IsFastCall, bool &NeedsPadding) const; 541 542 public: 543 544 virtual void computeInfo(CGFunctionInfo &FI) const; 545 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 546 CodeGenFunction &CGF) const; 547 548 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool m, bool w, 549 unsigned r) 550 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p), 551 IsMMXDisabled(m), IsWin32FloatStructABI(w), 552 DefaultNumRegisterParameters(r) {} 553 }; 554 555 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 556 public: 557 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 558 bool d, bool p, bool m, bool w, unsigned r) 559 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, m, w, r)) {} 560 561 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 562 CodeGen::CodeGenModule &CGM) const; 563 564 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 565 // Darwin uses different dwarf register numbers for EH. 566 if (CGM.isTargetDarwin()) return 5; 567 568 return 4; 569 } 570 571 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 572 llvm::Value *Address) const; 573 574 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 575 StringRef Constraint, 576 llvm::Type* Ty) const { 577 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 578 } 579 580 }; 581 582 } 583 584 /// shouldReturnTypeInRegister - Determine if the given type should be 585 /// passed in a register (for the Darwin ABI). 586 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 587 ASTContext &Context, 588 unsigned callingConvention) { 589 uint64_t Size = Context.getTypeSize(Ty); 590 591 // Type must be register sized. 592 if (!isRegisterSize(Size)) 593 return false; 594 595 if (Ty->isVectorType()) { 596 // 64- and 128- bit vectors inside structures are not returned in 597 // registers. 598 if (Size == 64 || Size == 128) 599 return false; 600 601 return true; 602 } 603 604 // If this is a builtin, pointer, enum, complex type, member pointer, or 605 // member function pointer it is ok. 606 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 607 Ty->isAnyComplexType() || Ty->isEnumeralType() || 608 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 609 return true; 610 611 // Arrays are treated like records. 612 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 613 return shouldReturnTypeInRegister(AT->getElementType(), Context, 614 callingConvention); 615 616 // Otherwise, it must be a record type. 617 const RecordType *RT = Ty->getAs<RecordType>(); 618 if (!RT) return false; 619 620 // FIXME: Traverse bases here too. 621 622 // For thiscall conventions, structures will never be returned in 623 // a register. This is for compatibility with the MSVC ABI 624 if (callingConvention == llvm::CallingConv::X86_ThisCall && 625 RT->isStructureType()) { 626 return false; 627 } 628 629 // Structure types are passed in register if all fields would be 630 // passed in a register. 631 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(), 632 e = RT->getDecl()->field_end(); i != e; ++i) { 633 const FieldDecl *FD = *i; 634 635 // Empty fields are ignored. 636 if (isEmptyField(Context, FD, true)) 637 continue; 638 639 // Check fields recursively. 640 if (!shouldReturnTypeInRegister(FD->getType(), Context, 641 callingConvention)) 642 return false; 643 } 644 return true; 645 } 646 647 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 648 unsigned callingConvention) const { 649 if (RetTy->isVoidType()) 650 return ABIArgInfo::getIgnore(); 651 652 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 653 // On Darwin, some vectors are returned in registers. 654 if (IsDarwinVectorABI) { 655 uint64_t Size = getContext().getTypeSize(RetTy); 656 657 // 128-bit vectors are a special case; they are returned in 658 // registers and we need to make sure to pick a type the LLVM 659 // backend will like. 660 if (Size == 128) 661 return ABIArgInfo::getDirect(llvm::VectorType::get( 662 llvm::Type::getInt64Ty(getVMContext()), 2)); 663 664 // Always return in register if it fits in a general purpose 665 // register, or if it is 64 bits and has a single element. 666 if ((Size == 8 || Size == 16 || Size == 32) || 667 (Size == 64 && VT->getNumElements() == 1)) 668 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 669 Size)); 670 671 return ABIArgInfo::getIndirect(0); 672 } 673 674 return ABIArgInfo::getDirect(); 675 } 676 677 if (isAggregateTypeForABI(RetTy)) { 678 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 679 // Structures with either a non-trivial destructor or a non-trivial 680 // copy constructor are always indirect. 681 if (hasNonTrivialDestructorOrCopyConstructor(RT)) 682 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 683 684 // Structures with flexible arrays are always indirect. 685 if (RT->getDecl()->hasFlexibleArrayMember()) 686 return ABIArgInfo::getIndirect(0); 687 } 688 689 // If specified, structs and unions are always indirect. 690 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType()) 691 return ABIArgInfo::getIndirect(0); 692 693 // Small structures which are register sized are generally returned 694 // in a register. 695 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(), 696 callingConvention)) { 697 uint64_t Size = getContext().getTypeSize(RetTy); 698 699 // As a special-case, if the struct is a "single-element" struct, and 700 // the field is of type "float" or "double", return it in a 701 // floating-point register. (MSVC does not apply this special case.) 702 // We apply a similar transformation for pointer types to improve the 703 // quality of the generated IR. 704 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 705 if ((!IsWin32FloatStructABI && SeltTy->isRealFloatingType()) 706 || SeltTy->hasPointerRepresentation()) 707 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 708 709 // FIXME: We should be able to narrow this integer in cases with dead 710 // padding. 711 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 712 } 713 714 return ABIArgInfo::getIndirect(0); 715 } 716 717 // Treat an enum type as its underlying type. 718 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 719 RetTy = EnumTy->getDecl()->getIntegerType(); 720 721 return (RetTy->isPromotableIntegerType() ? 722 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 723 } 724 725 static bool isSSEVectorType(ASTContext &Context, QualType Ty) { 726 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 727 } 728 729 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) { 730 const RecordType *RT = Ty->getAs<RecordType>(); 731 if (!RT) 732 return 0; 733 const RecordDecl *RD = RT->getDecl(); 734 735 // If this is a C++ record, check the bases first. 736 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 737 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 738 e = CXXRD->bases_end(); i != e; ++i) 739 if (!isRecordWithSSEVectorType(Context, i->getType())) 740 return false; 741 742 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 743 i != e; ++i) { 744 QualType FT = i->getType(); 745 746 if (isSSEVectorType(Context, FT)) 747 return true; 748 749 if (isRecordWithSSEVectorType(Context, FT)) 750 return true; 751 } 752 753 return false; 754 } 755 756 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 757 unsigned Align) const { 758 // Otherwise, if the alignment is less than or equal to the minimum ABI 759 // alignment, just use the default; the backend will handle this. 760 if (Align <= MinABIStackAlignInBytes) 761 return 0; // Use default alignment. 762 763 // On non-Darwin, the stack type alignment is always 4. 764 if (!IsDarwinVectorABI) { 765 // Set explicit alignment, since we may need to realign the top. 766 return MinABIStackAlignInBytes; 767 } 768 769 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 770 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) || 771 isRecordWithSSEVectorType(getContext(), Ty))) 772 return 16; 773 774 return MinABIStackAlignInBytes; 775 } 776 777 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 778 unsigned &FreeRegs) const { 779 if (!ByVal) { 780 if (FreeRegs) { 781 --FreeRegs; // Non byval indirects just use one pointer. 782 return ABIArgInfo::getIndirectInReg(0, false); 783 } 784 return ABIArgInfo::getIndirect(0, false); 785 } 786 787 // Compute the byval alignment. 788 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 789 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 790 if (StackAlign == 0) 791 return ABIArgInfo::getIndirect(4); 792 793 // If the stack alignment is less than the type alignment, realign the 794 // argument. 795 if (StackAlign < TypeAlign) 796 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, 797 /*Realign=*/true); 798 799 return ABIArgInfo::getIndirect(StackAlign); 800 } 801 802 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 803 const Type *T = isSingleElementStruct(Ty, getContext()); 804 if (!T) 805 T = Ty.getTypePtr(); 806 807 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 808 BuiltinType::Kind K = BT->getKind(); 809 if (K == BuiltinType::Float || K == BuiltinType::Double) 810 return Float; 811 } 812 return Integer; 813 } 814 815 bool X86_32ABIInfo::shouldUseInReg(QualType Ty, unsigned &FreeRegs, 816 bool IsFastCall, bool &NeedsPadding) const { 817 NeedsPadding = false; 818 Class C = classify(Ty); 819 if (C == Float) 820 return false; 821 822 unsigned Size = getContext().getTypeSize(Ty); 823 unsigned SizeInRegs = (Size + 31) / 32; 824 825 if (SizeInRegs == 0) 826 return false; 827 828 if (SizeInRegs > FreeRegs) { 829 FreeRegs = 0; 830 return false; 831 } 832 833 FreeRegs -= SizeInRegs; 834 835 if (IsFastCall) { 836 if (Size > 32) 837 return false; 838 839 if (Ty->isIntegralOrEnumerationType()) 840 return true; 841 842 if (Ty->isPointerType()) 843 return true; 844 845 if (Ty->isReferenceType()) 846 return true; 847 848 if (FreeRegs) 849 NeedsPadding = true; 850 851 return false; 852 } 853 854 return true; 855 } 856 857 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 858 unsigned &FreeRegs, 859 bool IsFastCall) const { 860 // FIXME: Set alignment on indirect arguments. 861 if (isAggregateTypeForABI(Ty)) { 862 // Structures with flexible arrays are always indirect. 863 if (const RecordType *RT = Ty->getAs<RecordType>()) { 864 // Structures with either a non-trivial destructor or a non-trivial 865 // copy constructor are always indirect. 866 if (hasNonTrivialDestructorOrCopyConstructor(RT)) 867 return getIndirectResult(Ty, false, FreeRegs); 868 869 if (RT->getDecl()->hasFlexibleArrayMember()) 870 return getIndirectResult(Ty, true, FreeRegs); 871 } 872 873 // Ignore empty structs/unions. 874 if (isEmptyRecord(getContext(), Ty, true)) 875 return ABIArgInfo::getIgnore(); 876 877 llvm::LLVMContext &LLVMContext = getVMContext(); 878 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 879 bool NeedsPadding; 880 if (shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding)) { 881 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 882 SmallVector<llvm::Type*, 3> Elements; 883 for (unsigned I = 0; I < SizeInRegs; ++I) 884 Elements.push_back(Int32); 885 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 886 return ABIArgInfo::getDirectInReg(Result); 887 } 888 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0; 889 890 // Expand small (<= 128-bit) record types when we know that the stack layout 891 // of those arguments will match the struct. This is important because the 892 // LLVM backend isn't smart enough to remove byval, which inhibits many 893 // optimizations. 894 if (getContext().getTypeSize(Ty) <= 4*32 && 895 canExpandIndirectArgument(Ty, getContext())) 896 return ABIArgInfo::getExpandWithPadding(IsFastCall, PaddingType); 897 898 return getIndirectResult(Ty, true, FreeRegs); 899 } 900 901 if (const VectorType *VT = Ty->getAs<VectorType>()) { 902 // On Darwin, some vectors are passed in memory, we handle this by passing 903 // it as an i8/i16/i32/i64. 904 if (IsDarwinVectorABI) { 905 uint64_t Size = getContext().getTypeSize(Ty); 906 if ((Size == 8 || Size == 16 || Size == 32) || 907 (Size == 64 && VT->getNumElements() == 1)) 908 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 909 Size)); 910 } 911 912 llvm::Type *IRType = CGT.ConvertType(Ty); 913 if (UseX86_MMXType(IRType)) { 914 if (IsMMXDisabled) 915 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 916 64)); 917 ABIArgInfo AAI = ABIArgInfo::getDirect(IRType); 918 AAI.setCoerceToType(llvm::Type::getX86_MMXTy(getVMContext())); 919 return AAI; 920 } 921 922 return ABIArgInfo::getDirect(); 923 } 924 925 926 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 927 Ty = EnumTy->getDecl()->getIntegerType(); 928 929 bool NeedsPadding; 930 bool InReg = shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding); 931 932 if (Ty->isPromotableIntegerType()) { 933 if (InReg) 934 return ABIArgInfo::getExtendInReg(); 935 return ABIArgInfo::getExtend(); 936 } 937 if (InReg) 938 return ABIArgInfo::getDirectInReg(); 939 return ABIArgInfo::getDirect(); 940 } 941 942 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 943 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), 944 FI.getCallingConvention()); 945 946 unsigned CC = FI.getCallingConvention(); 947 bool IsFastCall = CC == llvm::CallingConv::X86_FastCall; 948 unsigned FreeRegs; 949 if (IsFastCall) 950 FreeRegs = 2; 951 else if (FI.getHasRegParm()) 952 FreeRegs = FI.getRegParm(); 953 else 954 FreeRegs = DefaultNumRegisterParameters; 955 956 // If the return value is indirect, then the hidden argument is consuming one 957 // integer register. 958 if (FI.getReturnInfo().isIndirect() && FreeRegs) { 959 --FreeRegs; 960 ABIArgInfo &Old = FI.getReturnInfo(); 961 Old = ABIArgInfo::getIndirectInReg(Old.getIndirectAlign(), 962 Old.getIndirectByVal(), 963 Old.getIndirectRealign()); 964 } 965 966 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 967 it != ie; ++it) 968 it->info = classifyArgumentType(it->type, FreeRegs, IsFastCall); 969 } 970 971 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 972 CodeGenFunction &CGF) const { 973 llvm::Type *BPP = CGF.Int8PtrPtrTy; 974 975 CGBuilderTy &Builder = CGF.Builder; 976 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 977 "ap"); 978 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 979 980 // Compute if the address needs to be aligned 981 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity(); 982 Align = getTypeStackAlignInBytes(Ty, Align); 983 Align = std::max(Align, 4U); 984 if (Align > 4) { 985 // addr = (addr + align - 1) & -align; 986 llvm::Value *Offset = 987 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1); 988 Addr = CGF.Builder.CreateGEP(Addr, Offset); 989 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr, 990 CGF.Int32Ty); 991 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align); 992 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask), 993 Addr->getType(), 994 "ap.cur.aligned"); 995 } 996 997 llvm::Type *PTy = 998 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 999 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 1000 1001 uint64_t Offset = 1002 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align); 1003 llvm::Value *NextAddr = 1004 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 1005 "ap.next"); 1006 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 1007 1008 return AddrTyped; 1009 } 1010 1011 void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D, 1012 llvm::GlobalValue *GV, 1013 CodeGen::CodeGenModule &CGM) const { 1014 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1015 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 1016 // Get the LLVM function. 1017 llvm::Function *Fn = cast<llvm::Function>(GV); 1018 1019 // Now add the 'alignstack' attribute with a value of 16. 1020 llvm::AttrBuilder B; 1021 B.addStackAlignmentAttr(16); 1022 Fn->addAttributes(llvm::AttributeSet::FunctionIndex, 1023 llvm::AttributeSet::get(CGM.getLLVMContext(), 1024 llvm::AttributeSet::FunctionIndex, 1025 B)); 1026 } 1027 } 1028 } 1029 1030 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 1031 CodeGen::CodeGenFunction &CGF, 1032 llvm::Value *Address) const { 1033 CodeGen::CGBuilderTy &Builder = CGF.Builder; 1034 1035 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 1036 1037 // 0-7 are the eight integer registers; the order is different 1038 // on Darwin (for EH), but the range is the same. 1039 // 8 is %eip. 1040 AssignToArrayRange(Builder, Address, Four8, 0, 8); 1041 1042 if (CGF.CGM.isTargetDarwin()) { 1043 // 12-16 are st(0..4). Not sure why we stop at 4. 1044 // These have size 16, which is sizeof(long double) on 1045 // platforms with 8-byte alignment for that type. 1046 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 1047 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 1048 1049 } else { 1050 // 9 is %eflags, which doesn't get a size on Darwin for some 1051 // reason. 1052 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9)); 1053 1054 // 11-16 are st(0..5). Not sure why we stop at 5. 1055 // These have size 12, which is sizeof(long double) on 1056 // platforms with 4-byte alignment for that type. 1057 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 1058 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 1059 } 1060 1061 return false; 1062 } 1063 1064 //===----------------------------------------------------------------------===// 1065 // X86-64 ABI Implementation 1066 //===----------------------------------------------------------------------===// 1067 1068 1069 namespace { 1070 /// X86_64ABIInfo - The X86_64 ABI information. 1071 class X86_64ABIInfo : public ABIInfo { 1072 enum Class { 1073 Integer = 0, 1074 SSE, 1075 SSEUp, 1076 X87, 1077 X87Up, 1078 ComplexX87, 1079 NoClass, 1080 Memory 1081 }; 1082 1083 /// merge - Implement the X86_64 ABI merging algorithm. 1084 /// 1085 /// Merge an accumulating classification \arg Accum with a field 1086 /// classification \arg Field. 1087 /// 1088 /// \param Accum - The accumulating classification. This should 1089 /// always be either NoClass or the result of a previous merge 1090 /// call. In addition, this should never be Memory (the caller 1091 /// should just return Memory for the aggregate). 1092 static Class merge(Class Accum, Class Field); 1093 1094 /// postMerge - Implement the X86_64 ABI post merging algorithm. 1095 /// 1096 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 1097 /// final MEMORY or SSE classes when necessary. 1098 /// 1099 /// \param AggregateSize - The size of the current aggregate in 1100 /// the classification process. 1101 /// 1102 /// \param Lo - The classification for the parts of the type 1103 /// residing in the low word of the containing object. 1104 /// 1105 /// \param Hi - The classification for the parts of the type 1106 /// residing in the higher words of the containing object. 1107 /// 1108 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 1109 1110 /// classify - Determine the x86_64 register classes in which the 1111 /// given type T should be passed. 1112 /// 1113 /// \param Lo - The classification for the parts of the type 1114 /// residing in the low word of the containing object. 1115 /// 1116 /// \param Hi - The classification for the parts of the type 1117 /// residing in the high word of the containing object. 1118 /// 1119 /// \param OffsetBase - The bit offset of this type in the 1120 /// containing object. Some parameters are classified different 1121 /// depending on whether they straddle an eightbyte boundary. 1122 /// 1123 /// If a word is unused its result will be NoClass; if a type should 1124 /// be passed in Memory then at least the classification of \arg Lo 1125 /// will be Memory. 1126 /// 1127 /// The \arg Lo class will be NoClass iff the argument is ignored. 1128 /// 1129 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 1130 /// also be ComplexX87. 1131 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi) const; 1132 1133 llvm::Type *GetByteVectorType(QualType Ty) const; 1134 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 1135 unsigned IROffset, QualType SourceTy, 1136 unsigned SourceOffset) const; 1137 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 1138 unsigned IROffset, QualType SourceTy, 1139 unsigned SourceOffset) const; 1140 1141 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1142 /// such that the argument will be returned in memory. 1143 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 1144 1145 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1146 /// such that the argument will be passed in memory. 1147 /// 1148 /// \param freeIntRegs - The number of free integer registers remaining 1149 /// available. 1150 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 1151 1152 ABIArgInfo classifyReturnType(QualType RetTy) const; 1153 1154 ABIArgInfo classifyArgumentType(QualType Ty, 1155 unsigned freeIntRegs, 1156 unsigned &neededInt, 1157 unsigned &neededSSE) const; 1158 1159 bool IsIllegalVectorType(QualType Ty) const; 1160 1161 /// The 0.98 ABI revision clarified a lot of ambiguities, 1162 /// unfortunately in ways that were not always consistent with 1163 /// certain previous compilers. In particular, platforms which 1164 /// required strict binary compatibility with older versions of GCC 1165 /// may need to exempt themselves. 1166 bool honorsRevision0_98() const { 1167 return !getContext().getTargetInfo().getTriple().isOSDarwin(); 1168 } 1169 1170 bool HasAVX; 1171 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 1172 // 64-bit hardware. 1173 bool Has64BitPointers; 1174 1175 public: 1176 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) : 1177 ABIInfo(CGT), HasAVX(hasavx), 1178 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 1179 } 1180 1181 bool isPassedUsingAVXType(QualType type) const { 1182 unsigned neededInt, neededSSE; 1183 // The freeIntRegs argument doesn't matter here. 1184 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE); 1185 if (info.isDirect()) { 1186 llvm::Type *ty = info.getCoerceToType(); 1187 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 1188 return (vectorTy->getBitWidth() > 128); 1189 } 1190 return false; 1191 } 1192 1193 virtual void computeInfo(CGFunctionInfo &FI) const; 1194 1195 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 1196 CodeGenFunction &CGF) const; 1197 }; 1198 1199 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 1200 class WinX86_64ABIInfo : public ABIInfo { 1201 1202 ABIArgInfo classify(QualType Ty) const; 1203 1204 public: 1205 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 1206 1207 virtual void computeInfo(CGFunctionInfo &FI) const; 1208 1209 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 1210 CodeGenFunction &CGF) const; 1211 }; 1212 1213 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 1214 public: 1215 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 1216 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {} 1217 1218 const X86_64ABIInfo &getABIInfo() const { 1219 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 1220 } 1221 1222 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 1223 return 7; 1224 } 1225 1226 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1227 llvm::Value *Address) const { 1228 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 1229 1230 // 0-15 are the 16 integer registers. 1231 // 16 is %rip. 1232 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 1233 return false; 1234 } 1235 1236 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1237 StringRef Constraint, 1238 llvm::Type* Ty) const { 1239 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1240 } 1241 1242 bool isNoProtoCallVariadic(const CallArgList &args, 1243 const FunctionNoProtoType *fnType) const { 1244 // The default CC on x86-64 sets %al to the number of SSA 1245 // registers used, and GCC sets this when calling an unprototyped 1246 // function, so we override the default behavior. However, don't do 1247 // that when AVX types are involved: the ABI explicitly states it is 1248 // undefined, and it doesn't work in practice because of how the ABI 1249 // defines varargs anyway. 1250 if (fnType->getCallConv() == CC_Default || fnType->getCallConv() == CC_C) { 1251 bool HasAVXType = false; 1252 for (CallArgList::const_iterator 1253 it = args.begin(), ie = args.end(); it != ie; ++it) { 1254 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 1255 HasAVXType = true; 1256 break; 1257 } 1258 } 1259 1260 if (!HasAVXType) 1261 return true; 1262 } 1263 1264 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 1265 } 1266 1267 }; 1268 1269 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 1270 public: 1271 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 1272 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {} 1273 1274 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 1275 return 7; 1276 } 1277 1278 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1279 llvm::Value *Address) const { 1280 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 1281 1282 // 0-15 are the 16 integer registers. 1283 // 16 is %rip. 1284 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 1285 return false; 1286 } 1287 }; 1288 1289 } 1290 1291 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 1292 Class &Hi) const { 1293 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 1294 // 1295 // (a) If one of the classes is Memory, the whole argument is passed in 1296 // memory. 1297 // 1298 // (b) If X87UP is not preceded by X87, the whole argument is passed in 1299 // memory. 1300 // 1301 // (c) If the size of the aggregate exceeds two eightbytes and the first 1302 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 1303 // argument is passed in memory. NOTE: This is necessary to keep the 1304 // ABI working for processors that don't support the __m256 type. 1305 // 1306 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 1307 // 1308 // Some of these are enforced by the merging logic. Others can arise 1309 // only with unions; for example: 1310 // union { _Complex double; unsigned; } 1311 // 1312 // Note that clauses (b) and (c) were added in 0.98. 1313 // 1314 if (Hi == Memory) 1315 Lo = Memory; 1316 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 1317 Lo = Memory; 1318 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 1319 Lo = Memory; 1320 if (Hi == SSEUp && Lo != SSE) 1321 Hi = SSE; 1322 } 1323 1324 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 1325 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 1326 // classified recursively so that always two fields are 1327 // considered. The resulting class is calculated according to 1328 // the classes of the fields in the eightbyte: 1329 // 1330 // (a) If both classes are equal, this is the resulting class. 1331 // 1332 // (b) If one of the classes is NO_CLASS, the resulting class is 1333 // the other class. 1334 // 1335 // (c) If one of the classes is MEMORY, the result is the MEMORY 1336 // class. 1337 // 1338 // (d) If one of the classes is INTEGER, the result is the 1339 // INTEGER. 1340 // 1341 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 1342 // MEMORY is used as class. 1343 // 1344 // (f) Otherwise class SSE is used. 1345 1346 // Accum should never be memory (we should have returned) or 1347 // ComplexX87 (because this cannot be passed in a structure). 1348 assert((Accum != Memory && Accum != ComplexX87) && 1349 "Invalid accumulated classification during merge."); 1350 if (Accum == Field || Field == NoClass) 1351 return Accum; 1352 if (Field == Memory) 1353 return Memory; 1354 if (Accum == NoClass) 1355 return Field; 1356 if (Accum == Integer || Field == Integer) 1357 return Integer; 1358 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 1359 Accum == X87 || Accum == X87Up) 1360 return Memory; 1361 return SSE; 1362 } 1363 1364 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 1365 Class &Lo, Class &Hi) const { 1366 // FIXME: This code can be simplified by introducing a simple value class for 1367 // Class pairs with appropriate constructor methods for the various 1368 // situations. 1369 1370 // FIXME: Some of the split computations are wrong; unaligned vectors 1371 // shouldn't be passed in registers for example, so there is no chance they 1372 // can straddle an eightbyte. Verify & simplify. 1373 1374 Lo = Hi = NoClass; 1375 1376 Class &Current = OffsetBase < 64 ? Lo : Hi; 1377 Current = Memory; 1378 1379 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1380 BuiltinType::Kind k = BT->getKind(); 1381 1382 if (k == BuiltinType::Void) { 1383 Current = NoClass; 1384 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 1385 Lo = Integer; 1386 Hi = Integer; 1387 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 1388 Current = Integer; 1389 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) || 1390 (k == BuiltinType::LongDouble && 1391 getContext().getTargetInfo().getTriple().getOS() == 1392 llvm::Triple::NaCl)) { 1393 Current = SSE; 1394 } else if (k == BuiltinType::LongDouble) { 1395 Lo = X87; 1396 Hi = X87Up; 1397 } 1398 // FIXME: _Decimal32 and _Decimal64 are SSE. 1399 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 1400 return; 1401 } 1402 1403 if (const EnumType *ET = Ty->getAs<EnumType>()) { 1404 // Classify the underlying integer type. 1405 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi); 1406 return; 1407 } 1408 1409 if (Ty->hasPointerRepresentation()) { 1410 Current = Integer; 1411 return; 1412 } 1413 1414 if (Ty->isMemberPointerType()) { 1415 if (Ty->isMemberFunctionPointerType() && Has64BitPointers) 1416 Lo = Hi = Integer; 1417 else 1418 Current = Integer; 1419 return; 1420 } 1421 1422 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1423 uint64_t Size = getContext().getTypeSize(VT); 1424 if (Size == 32) { 1425 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x 1426 // float> as integer. 1427 Current = Integer; 1428 1429 // If this type crosses an eightbyte boundary, it should be 1430 // split. 1431 uint64_t EB_Real = (OffsetBase) / 64; 1432 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64; 1433 if (EB_Real != EB_Imag) 1434 Hi = Lo; 1435 } else if (Size == 64) { 1436 // gcc passes <1 x double> in memory. :( 1437 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) 1438 return; 1439 1440 // gcc passes <1 x long long> as INTEGER. 1441 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) || 1442 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) || 1443 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) || 1444 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong)) 1445 Current = Integer; 1446 else 1447 Current = SSE; 1448 1449 // If this type crosses an eightbyte boundary, it should be 1450 // split. 1451 if (OffsetBase && OffsetBase != 64) 1452 Hi = Lo; 1453 } else if (Size == 128 || (HasAVX && Size == 256)) { 1454 // Arguments of 256-bits are split into four eightbyte chunks. The 1455 // least significant one belongs to class SSE and all the others to class 1456 // SSEUP. The original Lo and Hi design considers that types can't be 1457 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 1458 // This design isn't correct for 256-bits, but since there're no cases 1459 // where the upper parts would need to be inspected, avoid adding 1460 // complexity and just consider Hi to match the 64-256 part. 1461 Lo = SSE; 1462 Hi = SSEUp; 1463 } 1464 return; 1465 } 1466 1467 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 1468 QualType ET = getContext().getCanonicalType(CT->getElementType()); 1469 1470 uint64_t Size = getContext().getTypeSize(Ty); 1471 if (ET->isIntegralOrEnumerationType()) { 1472 if (Size <= 64) 1473 Current = Integer; 1474 else if (Size <= 128) 1475 Lo = Hi = Integer; 1476 } else if (ET == getContext().FloatTy) 1477 Current = SSE; 1478 else if (ET == getContext().DoubleTy || 1479 (ET == getContext().LongDoubleTy && 1480 getContext().getTargetInfo().getTriple().getOS() == 1481 llvm::Triple::NaCl)) 1482 Lo = Hi = SSE; 1483 else if (ET == getContext().LongDoubleTy) 1484 Current = ComplexX87; 1485 1486 // If this complex type crosses an eightbyte boundary then it 1487 // should be split. 1488 uint64_t EB_Real = (OffsetBase) / 64; 1489 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 1490 if (Hi == NoClass && EB_Real != EB_Imag) 1491 Hi = Lo; 1492 1493 return; 1494 } 1495 1496 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 1497 // Arrays are treated like structures. 1498 1499 uint64_t Size = getContext().getTypeSize(Ty); 1500 1501 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 1502 // than four eightbytes, ..., it has class MEMORY. 1503 if (Size > 256) 1504 return; 1505 1506 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 1507 // fields, it has class MEMORY. 1508 // 1509 // Only need to check alignment of array base. 1510 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 1511 return; 1512 1513 // Otherwise implement simplified merge. We could be smarter about 1514 // this, but it isn't worth it and would be harder to verify. 1515 Current = NoClass; 1516 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 1517 uint64_t ArraySize = AT->getSize().getZExtValue(); 1518 1519 // The only case a 256-bit wide vector could be used is when the array 1520 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 1521 // to work for sizes wider than 128, early check and fallback to memory. 1522 if (Size > 128 && EltSize != 256) 1523 return; 1524 1525 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 1526 Class FieldLo, FieldHi; 1527 classify(AT->getElementType(), Offset, FieldLo, FieldHi); 1528 Lo = merge(Lo, FieldLo); 1529 Hi = merge(Hi, FieldHi); 1530 if (Lo == Memory || Hi == Memory) 1531 break; 1532 } 1533 1534 postMerge(Size, Lo, Hi); 1535 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 1536 return; 1537 } 1538 1539 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1540 uint64_t Size = getContext().getTypeSize(Ty); 1541 1542 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 1543 // than four eightbytes, ..., it has class MEMORY. 1544 if (Size > 256) 1545 return; 1546 1547 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 1548 // copy constructor or a non-trivial destructor, it is passed by invisible 1549 // reference. 1550 if (hasNonTrivialDestructorOrCopyConstructor(RT)) 1551 return; 1552 1553 const RecordDecl *RD = RT->getDecl(); 1554 1555 // Assume variable sized types are passed in memory. 1556 if (RD->hasFlexibleArrayMember()) 1557 return; 1558 1559 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 1560 1561 // Reset Lo class, this will be recomputed. 1562 Current = NoClass; 1563 1564 // If this is a C++ record, classify the bases first. 1565 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1566 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 1567 e = CXXRD->bases_end(); i != e; ++i) { 1568 assert(!i->isVirtual() && !i->getType()->isDependentType() && 1569 "Unexpected base class!"); 1570 const CXXRecordDecl *Base = 1571 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 1572 1573 // Classify this field. 1574 // 1575 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 1576 // single eightbyte, each is classified separately. Each eightbyte gets 1577 // initialized to class NO_CLASS. 1578 Class FieldLo, FieldHi; 1579 uint64_t Offset = 1580 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 1581 classify(i->getType(), Offset, FieldLo, FieldHi); 1582 Lo = merge(Lo, FieldLo); 1583 Hi = merge(Hi, FieldHi); 1584 if (Lo == Memory || Hi == Memory) 1585 break; 1586 } 1587 } 1588 1589 // Classify the fields one at a time, merging the results. 1590 unsigned idx = 0; 1591 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 1592 i != e; ++i, ++idx) { 1593 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 1594 bool BitField = i->isBitField(); 1595 1596 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 1597 // four eightbytes, or it contains unaligned fields, it has class MEMORY. 1598 // 1599 // The only case a 256-bit wide vector could be used is when the struct 1600 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 1601 // to work for sizes wider than 128, early check and fallback to memory. 1602 // 1603 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) { 1604 Lo = Memory; 1605 return; 1606 } 1607 // Note, skip this test for bit-fields, see below. 1608 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 1609 Lo = Memory; 1610 return; 1611 } 1612 1613 // Classify this field. 1614 // 1615 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 1616 // exceeds a single eightbyte, each is classified 1617 // separately. Each eightbyte gets initialized to class 1618 // NO_CLASS. 1619 Class FieldLo, FieldHi; 1620 1621 // Bit-fields require special handling, they do not force the 1622 // structure to be passed in memory even if unaligned, and 1623 // therefore they can straddle an eightbyte. 1624 if (BitField) { 1625 // Ignore padding bit-fields. 1626 if (i->isUnnamedBitfield()) 1627 continue; 1628 1629 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 1630 uint64_t Size = i->getBitWidthValue(getContext()); 1631 1632 uint64_t EB_Lo = Offset / 64; 1633 uint64_t EB_Hi = (Offset + Size - 1) / 64; 1634 FieldLo = FieldHi = NoClass; 1635 if (EB_Lo) { 1636 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 1637 FieldLo = NoClass; 1638 FieldHi = Integer; 1639 } else { 1640 FieldLo = Integer; 1641 FieldHi = EB_Hi ? Integer : NoClass; 1642 } 1643 } else 1644 classify(i->getType(), Offset, FieldLo, FieldHi); 1645 Lo = merge(Lo, FieldLo); 1646 Hi = merge(Hi, FieldHi); 1647 if (Lo == Memory || Hi == Memory) 1648 break; 1649 } 1650 1651 postMerge(Size, Lo, Hi); 1652 } 1653 } 1654 1655 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 1656 // If this is a scalar LLVM value then assume LLVM will pass it in the right 1657 // place naturally. 1658 if (!isAggregateTypeForABI(Ty)) { 1659 // Treat an enum type as its underlying type. 1660 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1661 Ty = EnumTy->getDecl()->getIntegerType(); 1662 1663 return (Ty->isPromotableIntegerType() ? 1664 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 1665 } 1666 1667 return ABIArgInfo::getIndirect(0); 1668 } 1669 1670 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 1671 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 1672 uint64_t Size = getContext().getTypeSize(VecTy); 1673 unsigned LargestVector = HasAVX ? 256 : 128; 1674 if (Size <= 64 || Size > LargestVector) 1675 return true; 1676 } 1677 1678 return false; 1679 } 1680 1681 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 1682 unsigned freeIntRegs) const { 1683 // If this is a scalar LLVM value then assume LLVM will pass it in the right 1684 // place naturally. 1685 // 1686 // This assumption is optimistic, as there could be free registers available 1687 // when we need to pass this argument in memory, and LLVM could try to pass 1688 // the argument in the free register. This does not seem to happen currently, 1689 // but this code would be much safer if we could mark the argument with 1690 // 'onstack'. See PR12193. 1691 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) { 1692 // Treat an enum type as its underlying type. 1693 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1694 Ty = EnumTy->getDecl()->getIntegerType(); 1695 1696 return (Ty->isPromotableIntegerType() ? 1697 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 1698 } 1699 1700 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) 1701 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 1702 1703 // Compute the byval alignment. We specify the alignment of the byval in all 1704 // cases so that the mid-level optimizer knows the alignment of the byval. 1705 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 1706 1707 // Attempt to avoid passing indirect results using byval when possible. This 1708 // is important for good codegen. 1709 // 1710 // We do this by coercing the value into a scalar type which the backend can 1711 // handle naturally (i.e., without using byval). 1712 // 1713 // For simplicity, we currently only do this when we have exhausted all of the 1714 // free integer registers. Doing this when there are free integer registers 1715 // would require more care, as we would have to ensure that the coerced value 1716 // did not claim the unused register. That would require either reording the 1717 // arguments to the function (so that any subsequent inreg values came first), 1718 // or only doing this optimization when there were no following arguments that 1719 // might be inreg. 1720 // 1721 // We currently expect it to be rare (particularly in well written code) for 1722 // arguments to be passed on the stack when there are still free integer 1723 // registers available (this would typically imply large structs being passed 1724 // by value), so this seems like a fair tradeoff for now. 1725 // 1726 // We can revisit this if the backend grows support for 'onstack' parameter 1727 // attributes. See PR12193. 1728 if (freeIntRegs == 0) { 1729 uint64_t Size = getContext().getTypeSize(Ty); 1730 1731 // If this type fits in an eightbyte, coerce it into the matching integral 1732 // type, which will end up on the stack (with alignment 8). 1733 if (Align == 8 && Size <= 64) 1734 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1735 Size)); 1736 } 1737 1738 return ABIArgInfo::getIndirect(Align); 1739 } 1740 1741 /// GetByteVectorType - The ABI specifies that a value should be passed in an 1742 /// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a 1743 /// vector register. 1744 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 1745 llvm::Type *IRType = CGT.ConvertType(Ty); 1746 1747 // Wrapper structs that just contain vectors are passed just like vectors, 1748 // strip them off if present. 1749 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType); 1750 while (STy && STy->getNumElements() == 1) { 1751 IRType = STy->getElementType(0); 1752 STy = dyn_cast<llvm::StructType>(IRType); 1753 } 1754 1755 // If the preferred type is a 16-byte vector, prefer to pass it. 1756 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){ 1757 llvm::Type *EltTy = VT->getElementType(); 1758 unsigned BitWidth = VT->getBitWidth(); 1759 if ((BitWidth >= 128 && BitWidth <= 256) && 1760 (EltTy->isFloatTy() || EltTy->isDoubleTy() || 1761 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) || 1762 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) || 1763 EltTy->isIntegerTy(128))) 1764 return VT; 1765 } 1766 1767 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2); 1768 } 1769 1770 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 1771 /// is known to either be off the end of the specified type or being in 1772 /// alignment padding. The user type specified is known to be at most 128 bits 1773 /// in size, and have passed through X86_64ABIInfo::classify with a successful 1774 /// classification that put one of the two halves in the INTEGER class. 1775 /// 1776 /// It is conservatively correct to return false. 1777 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 1778 unsigned EndBit, ASTContext &Context) { 1779 // If the bytes being queried are off the end of the type, there is no user 1780 // data hiding here. This handles analysis of builtins, vectors and other 1781 // types that don't contain interesting padding. 1782 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 1783 if (TySize <= StartBit) 1784 return true; 1785 1786 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 1787 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 1788 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 1789 1790 // Check each element to see if the element overlaps with the queried range. 1791 for (unsigned i = 0; i != NumElts; ++i) { 1792 // If the element is after the span we care about, then we're done.. 1793 unsigned EltOffset = i*EltSize; 1794 if (EltOffset >= EndBit) break; 1795 1796 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 1797 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 1798 EndBit-EltOffset, Context)) 1799 return false; 1800 } 1801 // If it overlaps no elements, then it is safe to process as padding. 1802 return true; 1803 } 1804 1805 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1806 const RecordDecl *RD = RT->getDecl(); 1807 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1808 1809 // If this is a C++ record, check the bases first. 1810 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1811 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 1812 e = CXXRD->bases_end(); i != e; ++i) { 1813 assert(!i->isVirtual() && !i->getType()->isDependentType() && 1814 "Unexpected base class!"); 1815 const CXXRecordDecl *Base = 1816 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 1817 1818 // If the base is after the span we care about, ignore it. 1819 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 1820 if (BaseOffset >= EndBit) continue; 1821 1822 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 1823 if (!BitsContainNoUserData(i->getType(), BaseStart, 1824 EndBit-BaseOffset, Context)) 1825 return false; 1826 } 1827 } 1828 1829 // Verify that no field has data that overlaps the region of interest. Yes 1830 // this could be sped up a lot by being smarter about queried fields, 1831 // however we're only looking at structs up to 16 bytes, so we don't care 1832 // much. 1833 unsigned idx = 0; 1834 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 1835 i != e; ++i, ++idx) { 1836 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 1837 1838 // If we found a field after the region we care about, then we're done. 1839 if (FieldOffset >= EndBit) break; 1840 1841 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 1842 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 1843 Context)) 1844 return false; 1845 } 1846 1847 // If nothing in this record overlapped the area of interest, then we're 1848 // clean. 1849 return true; 1850 } 1851 1852 return false; 1853 } 1854 1855 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 1856 /// float member at the specified offset. For example, {int,{float}} has a 1857 /// float at offset 4. It is conservatively correct for this routine to return 1858 /// false. 1859 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 1860 const llvm::DataLayout &TD) { 1861 // Base case if we find a float. 1862 if (IROffset == 0 && IRType->isFloatTy()) 1863 return true; 1864 1865 // If this is a struct, recurse into the field at the specified offset. 1866 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 1867 const llvm::StructLayout *SL = TD.getStructLayout(STy); 1868 unsigned Elt = SL->getElementContainingOffset(IROffset); 1869 IROffset -= SL->getElementOffset(Elt); 1870 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 1871 } 1872 1873 // If this is an array, recurse into the field at the specified offset. 1874 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 1875 llvm::Type *EltTy = ATy->getElementType(); 1876 unsigned EltSize = TD.getTypeAllocSize(EltTy); 1877 IROffset -= IROffset/EltSize*EltSize; 1878 return ContainsFloatAtOffset(EltTy, IROffset, TD); 1879 } 1880 1881 return false; 1882 } 1883 1884 1885 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 1886 /// low 8 bytes of an XMM register, corresponding to the SSE class. 1887 llvm::Type *X86_64ABIInfo:: 1888 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 1889 QualType SourceTy, unsigned SourceOffset) const { 1890 // The only three choices we have are either double, <2 x float>, or float. We 1891 // pass as float if the last 4 bytes is just padding. This happens for 1892 // structs that contain 3 floats. 1893 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 1894 SourceOffset*8+64, getContext())) 1895 return llvm::Type::getFloatTy(getVMContext()); 1896 1897 // We want to pass as <2 x float> if the LLVM IR type contains a float at 1898 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 1899 // case. 1900 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 1901 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) 1902 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2); 1903 1904 return llvm::Type::getDoubleTy(getVMContext()); 1905 } 1906 1907 1908 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 1909 /// an 8-byte GPR. This means that we either have a scalar or we are talking 1910 /// about the high or low part of an up-to-16-byte struct. This routine picks 1911 /// the best LLVM IR type to represent this, which may be i64 or may be anything 1912 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 1913 /// etc). 1914 /// 1915 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 1916 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 1917 /// the 8-byte value references. PrefType may be null. 1918 /// 1919 /// SourceTy is the source level type for the entire argument. SourceOffset is 1920 /// an offset into this that we're processing (which is always either 0 or 8). 1921 /// 1922 llvm::Type *X86_64ABIInfo:: 1923 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 1924 QualType SourceTy, unsigned SourceOffset) const { 1925 // If we're dealing with an un-offset LLVM IR type, then it means that we're 1926 // returning an 8-byte unit starting with it. See if we can safely use it. 1927 if (IROffset == 0) { 1928 // Pointers and int64's always fill the 8-byte unit. 1929 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 1930 IRType->isIntegerTy(64)) 1931 return IRType; 1932 1933 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 1934 // goodness in the source type is just tail padding. This is allowed to 1935 // kick in for struct {double,int} on the int, but not on 1936 // struct{double,int,int} because we wouldn't return the second int. We 1937 // have to do this analysis on the source type because we can't depend on 1938 // unions being lowered a specific way etc. 1939 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 1940 IRType->isIntegerTy(32) || 1941 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 1942 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 1943 cast<llvm::IntegerType>(IRType)->getBitWidth(); 1944 1945 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 1946 SourceOffset*8+64, getContext())) 1947 return IRType; 1948 } 1949 } 1950 1951 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 1952 // If this is a struct, recurse into the field at the specified offset. 1953 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 1954 if (IROffset < SL->getSizeInBytes()) { 1955 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 1956 IROffset -= SL->getElementOffset(FieldIdx); 1957 1958 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 1959 SourceTy, SourceOffset); 1960 } 1961 } 1962 1963 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 1964 llvm::Type *EltTy = ATy->getElementType(); 1965 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 1966 unsigned EltOffset = IROffset/EltSize*EltSize; 1967 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 1968 SourceOffset); 1969 } 1970 1971 // Okay, we don't have any better idea of what to pass, so we pass this in an 1972 // integer register that isn't too big to fit the rest of the struct. 1973 unsigned TySizeInBytes = 1974 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 1975 1976 assert(TySizeInBytes != SourceOffset && "Empty field?"); 1977 1978 // It is always safe to classify this as an integer type up to i64 that 1979 // isn't larger than the structure. 1980 return llvm::IntegerType::get(getVMContext(), 1981 std::min(TySizeInBytes-SourceOffset, 8U)*8); 1982 } 1983 1984 1985 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 1986 /// be used as elements of a two register pair to pass or return, return a 1987 /// first class aggregate to represent them. For example, if the low part of 1988 /// a by-value argument should be passed as i32* and the high part as float, 1989 /// return {i32*, float}. 1990 static llvm::Type * 1991 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 1992 const llvm::DataLayout &TD) { 1993 // In order to correctly satisfy the ABI, we need to the high part to start 1994 // at offset 8. If the high and low parts we inferred are both 4-byte types 1995 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 1996 // the second element at offset 8. Check for this: 1997 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 1998 unsigned HiAlign = TD.getABITypeAlignment(Hi); 1999 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign); 2000 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 2001 2002 // To handle this, we have to increase the size of the low part so that the 2003 // second element will start at an 8 byte offset. We can't increase the size 2004 // of the second element because it might make us access off the end of the 2005 // struct. 2006 if (HiStart != 8) { 2007 // There are only two sorts of types the ABI generation code can produce for 2008 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32. 2009 // Promote these to a larger type. 2010 if (Lo->isFloatTy()) 2011 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 2012 else { 2013 assert(Lo->isIntegerTy() && "Invalid/unknown lo type"); 2014 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 2015 } 2016 } 2017 2018 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL); 2019 2020 2021 // Verify that the second element is at an 8-byte offset. 2022 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 2023 "Invalid x86-64 argument pair!"); 2024 return Result; 2025 } 2026 2027 ABIArgInfo X86_64ABIInfo:: 2028 classifyReturnType(QualType RetTy) const { 2029 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 2030 // classification algorithm. 2031 X86_64ABIInfo::Class Lo, Hi; 2032 classify(RetTy, 0, Lo, Hi); 2033 2034 // Check some invariants. 2035 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 2036 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 2037 2038 llvm::Type *ResType = 0; 2039 switch (Lo) { 2040 case NoClass: 2041 if (Hi == NoClass) 2042 return ABIArgInfo::getIgnore(); 2043 // If the low part is just padding, it takes no register, leave ResType 2044 // null. 2045 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 2046 "Unknown missing lo part"); 2047 break; 2048 2049 case SSEUp: 2050 case X87Up: 2051 llvm_unreachable("Invalid classification for lo word."); 2052 2053 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 2054 // hidden argument. 2055 case Memory: 2056 return getIndirectReturnResult(RetTy); 2057 2058 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 2059 // available register of the sequence %rax, %rdx is used. 2060 case Integer: 2061 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 2062 2063 // If we have a sign or zero extended integer, make sure to return Extend 2064 // so that the parameter gets the right LLVM IR attributes. 2065 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 2066 // Treat an enum type as its underlying type. 2067 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 2068 RetTy = EnumTy->getDecl()->getIntegerType(); 2069 2070 if (RetTy->isIntegralOrEnumerationType() && 2071 RetTy->isPromotableIntegerType()) 2072 return ABIArgInfo::getExtend(); 2073 } 2074 break; 2075 2076 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 2077 // available SSE register of the sequence %xmm0, %xmm1 is used. 2078 case SSE: 2079 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 2080 break; 2081 2082 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 2083 // returned on the X87 stack in %st0 as 80-bit x87 number. 2084 case X87: 2085 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 2086 break; 2087 2088 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 2089 // part of the value is returned in %st0 and the imaginary part in 2090 // %st1. 2091 case ComplexX87: 2092 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 2093 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 2094 llvm::Type::getX86_FP80Ty(getVMContext()), 2095 NULL); 2096 break; 2097 } 2098 2099 llvm::Type *HighPart = 0; 2100 switch (Hi) { 2101 // Memory was handled previously and X87 should 2102 // never occur as a hi class. 2103 case Memory: 2104 case X87: 2105 llvm_unreachable("Invalid classification for hi word."); 2106 2107 case ComplexX87: // Previously handled. 2108 case NoClass: 2109 break; 2110 2111 case Integer: 2112 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 2113 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 2114 return ABIArgInfo::getDirect(HighPart, 8); 2115 break; 2116 case SSE: 2117 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 2118 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 2119 return ABIArgInfo::getDirect(HighPart, 8); 2120 break; 2121 2122 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 2123 // is passed in the next available eightbyte chunk if the last used 2124 // vector register. 2125 // 2126 // SSEUP should always be preceded by SSE, just widen. 2127 case SSEUp: 2128 assert(Lo == SSE && "Unexpected SSEUp classification."); 2129 ResType = GetByteVectorType(RetTy); 2130 break; 2131 2132 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 2133 // returned together with the previous X87 value in %st0. 2134 case X87Up: 2135 // If X87Up is preceded by X87, we don't need to do 2136 // anything. However, in some cases with unions it may not be 2137 // preceded by X87. In such situations we follow gcc and pass the 2138 // extra bits in an SSE reg. 2139 if (Lo != X87) { 2140 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 2141 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 2142 return ABIArgInfo::getDirect(HighPart, 8); 2143 } 2144 break; 2145 } 2146 2147 // If a high part was specified, merge it together with the low part. It is 2148 // known to pass in the high eightbyte of the result. We do this by forming a 2149 // first class struct aggregate with the high and low part: {low, high} 2150 if (HighPart) 2151 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 2152 2153 return ABIArgInfo::getDirect(ResType); 2154 } 2155 2156 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 2157 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE) 2158 const 2159 { 2160 X86_64ABIInfo::Class Lo, Hi; 2161 classify(Ty, 0, Lo, Hi); 2162 2163 // Check some invariants. 2164 // FIXME: Enforce these by construction. 2165 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 2166 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 2167 2168 neededInt = 0; 2169 neededSSE = 0; 2170 llvm::Type *ResType = 0; 2171 switch (Lo) { 2172 case NoClass: 2173 if (Hi == NoClass) 2174 return ABIArgInfo::getIgnore(); 2175 // If the low part is just padding, it takes no register, leave ResType 2176 // null. 2177 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 2178 "Unknown missing lo part"); 2179 break; 2180 2181 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 2182 // on the stack. 2183 case Memory: 2184 2185 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 2186 // COMPLEX_X87, it is passed in memory. 2187 case X87: 2188 case ComplexX87: 2189 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) 2190 ++neededInt; 2191 return getIndirectResult(Ty, freeIntRegs); 2192 2193 case SSEUp: 2194 case X87Up: 2195 llvm_unreachable("Invalid classification for lo word."); 2196 2197 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 2198 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 2199 // and %r9 is used. 2200 case Integer: 2201 ++neededInt; 2202 2203 // Pick an 8-byte type based on the preferred type. 2204 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 2205 2206 // If we have a sign or zero extended integer, make sure to return Extend 2207 // so that the parameter gets the right LLVM IR attributes. 2208 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 2209 // Treat an enum type as its underlying type. 2210 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2211 Ty = EnumTy->getDecl()->getIntegerType(); 2212 2213 if (Ty->isIntegralOrEnumerationType() && 2214 Ty->isPromotableIntegerType()) 2215 return ABIArgInfo::getExtend(); 2216 } 2217 2218 break; 2219 2220 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 2221 // available SSE register is used, the registers are taken in the 2222 // order from %xmm0 to %xmm7. 2223 case SSE: { 2224 llvm::Type *IRType = CGT.ConvertType(Ty); 2225 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 2226 ++neededSSE; 2227 break; 2228 } 2229 } 2230 2231 llvm::Type *HighPart = 0; 2232 switch (Hi) { 2233 // Memory was handled previously, ComplexX87 and X87 should 2234 // never occur as hi classes, and X87Up must be preceded by X87, 2235 // which is passed in memory. 2236 case Memory: 2237 case X87: 2238 case ComplexX87: 2239 llvm_unreachable("Invalid classification for hi word."); 2240 2241 case NoClass: break; 2242 2243 case Integer: 2244 ++neededInt; 2245 // Pick an 8-byte type based on the preferred type. 2246 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 2247 2248 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 2249 return ABIArgInfo::getDirect(HighPart, 8); 2250 break; 2251 2252 // X87Up generally doesn't occur here (long double is passed in 2253 // memory), except in situations involving unions. 2254 case X87Up: 2255 case SSE: 2256 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 2257 2258 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 2259 return ABIArgInfo::getDirect(HighPart, 8); 2260 2261 ++neededSSE; 2262 break; 2263 2264 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 2265 // eightbyte is passed in the upper half of the last used SSE 2266 // register. This only happens when 128-bit vectors are passed. 2267 case SSEUp: 2268 assert(Lo == SSE && "Unexpected SSEUp classification"); 2269 ResType = GetByteVectorType(Ty); 2270 break; 2271 } 2272 2273 // If a high part was specified, merge it together with the low part. It is 2274 // known to pass in the high eightbyte of the result. We do this by forming a 2275 // first class struct aggregate with the high and low part: {low, high} 2276 if (HighPart) 2277 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 2278 2279 return ABIArgInfo::getDirect(ResType); 2280 } 2281 2282 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2283 2284 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 2285 2286 // Keep track of the number of assigned registers. 2287 unsigned freeIntRegs = 6, freeSSERegs = 8; 2288 2289 // If the return value is indirect, then the hidden argument is consuming one 2290 // integer register. 2291 if (FI.getReturnInfo().isIndirect()) 2292 --freeIntRegs; 2293 2294 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 2295 // get assigned (in left-to-right order) for passing as follows... 2296 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2297 it != ie; ++it) { 2298 unsigned neededInt, neededSSE; 2299 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt, 2300 neededSSE); 2301 2302 // AMD64-ABI 3.2.3p3: If there are no registers available for any 2303 // eightbyte of an argument, the whole argument is passed on the 2304 // stack. If registers have already been assigned for some 2305 // eightbytes of such an argument, the assignments get reverted. 2306 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) { 2307 freeIntRegs -= neededInt; 2308 freeSSERegs -= neededSSE; 2309 } else { 2310 it->info = getIndirectResult(it->type, freeIntRegs); 2311 } 2312 } 2313 } 2314 2315 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr, 2316 QualType Ty, 2317 CodeGenFunction &CGF) { 2318 llvm::Value *overflow_arg_area_p = 2319 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 2320 llvm::Value *overflow_arg_area = 2321 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 2322 2323 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 2324 // byte boundary if alignment needed by type exceeds 8 byte boundary. 2325 // It isn't stated explicitly in the standard, but in practice we use 2326 // alignment greater than 16 where necessary. 2327 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 2328 if (Align > 8) { 2329 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 2330 llvm::Value *Offset = 2331 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 2332 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset); 2333 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area, 2334 CGF.Int64Ty); 2335 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align); 2336 overflow_arg_area = 2337 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask), 2338 overflow_arg_area->getType(), 2339 "overflow_arg_area.align"); 2340 } 2341 2342 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 2343 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 2344 llvm::Value *Res = 2345 CGF.Builder.CreateBitCast(overflow_arg_area, 2346 llvm::PointerType::getUnqual(LTy)); 2347 2348 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 2349 // l->overflow_arg_area + sizeof(type). 2350 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 2351 // an 8 byte boundary. 2352 2353 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 2354 llvm::Value *Offset = 2355 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 2356 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 2357 "overflow_arg_area.next"); 2358 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 2359 2360 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 2361 return Res; 2362 } 2363 2364 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2365 CodeGenFunction &CGF) const { 2366 // Assume that va_list type is correct; should be pointer to LLVM type: 2367 // struct { 2368 // i32 gp_offset; 2369 // i32 fp_offset; 2370 // i8* overflow_arg_area; 2371 // i8* reg_save_area; 2372 // }; 2373 unsigned neededInt, neededSSE; 2374 2375 Ty = CGF.getContext().getCanonicalType(Ty); 2376 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE); 2377 2378 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 2379 // in the registers. If not go to step 7. 2380 if (!neededInt && !neededSSE) 2381 return EmitVAArgFromMemory(VAListAddr, Ty, CGF); 2382 2383 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 2384 // general purpose registers needed to pass type and num_fp to hold 2385 // the number of floating point registers needed. 2386 2387 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 2388 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 2389 // l->fp_offset > 304 - num_fp * 16 go to step 7. 2390 // 2391 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 2392 // register save space). 2393 2394 llvm::Value *InRegs = 0; 2395 llvm::Value *gp_offset_p = 0, *gp_offset = 0; 2396 llvm::Value *fp_offset_p = 0, *fp_offset = 0; 2397 if (neededInt) { 2398 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 2399 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 2400 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 2401 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 2402 } 2403 2404 if (neededSSE) { 2405 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 2406 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 2407 llvm::Value *FitsInFP = 2408 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 2409 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 2410 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 2411 } 2412 2413 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 2414 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 2415 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 2416 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 2417 2418 // Emit code to load the value if it was passed in registers. 2419 2420 CGF.EmitBlock(InRegBlock); 2421 2422 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 2423 // an offset of l->gp_offset and/or l->fp_offset. This may require 2424 // copying to a temporary location in case the parameter is passed 2425 // in different register classes or requires an alignment greater 2426 // than 8 for general purpose registers and 16 for XMM registers. 2427 // 2428 // FIXME: This really results in shameful code when we end up needing to 2429 // collect arguments from different places; often what should result in a 2430 // simple assembling of a structure from scattered addresses has many more 2431 // loads than necessary. Can we clean this up? 2432 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 2433 llvm::Value *RegAddr = 2434 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3), 2435 "reg_save_area"); 2436 if (neededInt && neededSSE) { 2437 // FIXME: Cleanup. 2438 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 2439 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 2440 llvm::Value *Tmp = CGF.CreateTempAlloca(ST); 2441 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 2442 llvm::Type *TyLo = ST->getElementType(0); 2443 llvm::Type *TyHi = ST->getElementType(1); 2444 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 2445 "Unexpected ABI info for mixed regs"); 2446 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 2447 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 2448 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset); 2449 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2450 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr; 2451 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr; 2452 llvm::Value *V = 2453 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo)); 2454 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 2455 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi)); 2456 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 2457 2458 RegAddr = CGF.Builder.CreateBitCast(Tmp, 2459 llvm::PointerType::getUnqual(LTy)); 2460 } else if (neededInt) { 2461 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset); 2462 RegAddr = CGF.Builder.CreateBitCast(RegAddr, 2463 llvm::PointerType::getUnqual(LTy)); 2464 } else if (neededSSE == 1) { 2465 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2466 RegAddr = CGF.Builder.CreateBitCast(RegAddr, 2467 llvm::PointerType::getUnqual(LTy)); 2468 } else { 2469 assert(neededSSE == 2 && "Invalid number of needed registers!"); 2470 // SSE registers are spaced 16 bytes apart in the register save 2471 // area, we need to collect the two eightbytes together. 2472 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2473 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16); 2474 llvm::Type *DoubleTy = CGF.DoubleTy; 2475 llvm::Type *DblPtrTy = 2476 llvm::PointerType::getUnqual(DoubleTy); 2477 llvm::StructType *ST = llvm::StructType::get(DoubleTy, 2478 DoubleTy, NULL); 2479 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST); 2480 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo, 2481 DblPtrTy)); 2482 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 2483 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi, 2484 DblPtrTy)); 2485 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 2486 RegAddr = CGF.Builder.CreateBitCast(Tmp, 2487 llvm::PointerType::getUnqual(LTy)); 2488 } 2489 2490 // AMD64-ABI 3.5.7p5: Step 5. Set: 2491 // l->gp_offset = l->gp_offset + num_gp * 8 2492 // l->fp_offset = l->fp_offset + num_fp * 16. 2493 if (neededInt) { 2494 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 2495 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 2496 gp_offset_p); 2497 } 2498 if (neededSSE) { 2499 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 2500 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 2501 fp_offset_p); 2502 } 2503 CGF.EmitBranch(ContBlock); 2504 2505 // Emit code to load the value if it was passed in memory. 2506 2507 CGF.EmitBlock(InMemBlock); 2508 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF); 2509 2510 // Return the appropriate result. 2511 2512 CGF.EmitBlock(ContBlock); 2513 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2, 2514 "vaarg.addr"); 2515 ResAddr->addIncoming(RegAddr, InRegBlock); 2516 ResAddr->addIncoming(MemAddr, InMemBlock); 2517 return ResAddr; 2518 } 2519 2520 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty) const { 2521 2522 if (Ty->isVoidType()) 2523 return ABIArgInfo::getIgnore(); 2524 2525 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2526 Ty = EnumTy->getDecl()->getIntegerType(); 2527 2528 uint64_t Size = getContext().getTypeSize(Ty); 2529 2530 if (const RecordType *RT = Ty->getAs<RecordType>()) { 2531 if (hasNonTrivialDestructorOrCopyConstructor(RT) || 2532 RT->getDecl()->hasFlexibleArrayMember()) 2533 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2534 2535 // FIXME: mingw-w64-gcc emits 128-bit struct as i128 2536 if (Size == 128 && 2537 getContext().getTargetInfo().getTriple().getOS() 2538 == llvm::Triple::MinGW32) 2539 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2540 Size)); 2541 2542 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 2543 // not 1, 2, 4, or 8 bytes, must be passed by reference." 2544 if (Size <= 64 && 2545 (Size & (Size - 1)) == 0) 2546 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2547 Size)); 2548 2549 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2550 } 2551 2552 if (Ty->isPromotableIntegerType()) 2553 return ABIArgInfo::getExtend(); 2554 2555 return ABIArgInfo::getDirect(); 2556 } 2557 2558 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2559 2560 QualType RetTy = FI.getReturnType(); 2561 FI.getReturnInfo() = classify(RetTy); 2562 2563 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2564 it != ie; ++it) 2565 it->info = classify(it->type); 2566 } 2567 2568 llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2569 CodeGenFunction &CGF) const { 2570 llvm::Type *BPP = CGF.Int8PtrPtrTy; 2571 2572 CGBuilderTy &Builder = CGF.Builder; 2573 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 2574 "ap"); 2575 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 2576 llvm::Type *PTy = 2577 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 2578 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 2579 2580 uint64_t Offset = 2581 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8); 2582 llvm::Value *NextAddr = 2583 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 2584 "ap.next"); 2585 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 2586 2587 return AddrTyped; 2588 } 2589 2590 namespace { 2591 2592 class NaClX86_64ABIInfo : public ABIInfo { 2593 public: 2594 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 2595 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {} 2596 virtual void computeInfo(CGFunctionInfo &FI) const; 2597 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2598 CodeGenFunction &CGF) const; 2599 private: 2600 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv. 2601 X86_64ABIInfo NInfo; // Used for everything else. 2602 }; 2603 2604 class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2605 public: 2606 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 2607 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {} 2608 }; 2609 2610 } 2611 2612 void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2613 if (FI.getASTCallingConvention() == CC_PnaclCall) 2614 PInfo.computeInfo(FI); 2615 else 2616 NInfo.computeInfo(FI); 2617 } 2618 2619 llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2620 CodeGenFunction &CGF) const { 2621 // Always use the native convention; calling pnacl-style varargs functions 2622 // is unuspported. 2623 return NInfo.EmitVAArg(VAListAddr, Ty, CGF); 2624 } 2625 2626 2627 // PowerPC-32 2628 2629 namespace { 2630 class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 2631 public: 2632 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 2633 2634 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 2635 // This is recovered from gcc output. 2636 return 1; // r1 is the dedicated stack pointer 2637 } 2638 2639 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2640 llvm::Value *Address) const; 2641 }; 2642 2643 } 2644 2645 bool 2646 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2647 llvm::Value *Address) const { 2648 // This is calculated from the LLVM and GCC tables and verified 2649 // against gcc output. AFAIK all ABIs use the same encoding. 2650 2651 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2652 2653 llvm::IntegerType *i8 = CGF.Int8Ty; 2654 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 2655 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 2656 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 2657 2658 // 0-31: r0-31, the 4-byte general-purpose registers 2659 AssignToArrayRange(Builder, Address, Four8, 0, 31); 2660 2661 // 32-63: fp0-31, the 8-byte floating-point registers 2662 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 2663 2664 // 64-76 are various 4-byte special-purpose registers: 2665 // 64: mq 2666 // 65: lr 2667 // 66: ctr 2668 // 67: ap 2669 // 68-75 cr0-7 2670 // 76: xer 2671 AssignToArrayRange(Builder, Address, Four8, 64, 76); 2672 2673 // 77-108: v0-31, the 16-byte vector registers 2674 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 2675 2676 // 109: vrsave 2677 // 110: vscr 2678 // 111: spe_acc 2679 // 112: spefscr 2680 // 113: sfp 2681 AssignToArrayRange(Builder, Address, Four8, 109, 113); 2682 2683 return false; 2684 } 2685 2686 // PowerPC-64 2687 2688 namespace { 2689 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 2690 class PPC64_SVR4_ABIInfo : public DefaultABIInfo { 2691 2692 public: 2693 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 2694 2695 bool isPromotableTypeForABI(QualType Ty) const; 2696 2697 ABIArgInfo classifyReturnType(QualType RetTy) const; 2698 ABIArgInfo classifyArgumentType(QualType Ty) const; 2699 2700 // TODO: We can add more logic to computeInfo to improve performance. 2701 // Example: For aggregate arguments that fit in a register, we could 2702 // use getDirectInReg (as is done below for structs containing a single 2703 // floating-point value) to avoid pushing them to memory on function 2704 // entry. This would require changing the logic in PPCISelLowering 2705 // when lowering the parameters in the caller and args in the callee. 2706 virtual void computeInfo(CGFunctionInfo &FI) const { 2707 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 2708 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2709 it != ie; ++it) { 2710 // We rely on the default argument classification for the most part. 2711 // One exception: An aggregate containing a single floating-point 2712 // item must be passed in a register if one is available. 2713 const Type *T = isSingleElementStruct(it->type, getContext()); 2714 if (T) { 2715 const BuiltinType *BT = T->getAs<BuiltinType>(); 2716 if (BT && BT->isFloatingPoint()) { 2717 QualType QT(T, 0); 2718 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 2719 continue; 2720 } 2721 } 2722 it->info = classifyArgumentType(it->type); 2723 } 2724 } 2725 2726 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, 2727 QualType Ty, 2728 CodeGenFunction &CGF) const; 2729 }; 2730 2731 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 2732 public: 2733 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT) 2734 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {} 2735 2736 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 2737 // This is recovered from gcc output. 2738 return 1; // r1 is the dedicated stack pointer 2739 } 2740 2741 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2742 llvm::Value *Address) const; 2743 }; 2744 2745 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 2746 public: 2747 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 2748 2749 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 2750 // This is recovered from gcc output. 2751 return 1; // r1 is the dedicated stack pointer 2752 } 2753 2754 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2755 llvm::Value *Address) const; 2756 }; 2757 2758 } 2759 2760 // Return true if the ABI requires Ty to be passed sign- or zero- 2761 // extended to 64 bits. 2762 bool 2763 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 2764 // Treat an enum type as its underlying type. 2765 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2766 Ty = EnumTy->getDecl()->getIntegerType(); 2767 2768 // Promotable integer types are required to be promoted by the ABI. 2769 if (Ty->isPromotableIntegerType()) 2770 return true; 2771 2772 // In addition to the usual promotable integer types, we also need to 2773 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 2774 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 2775 switch (BT->getKind()) { 2776 case BuiltinType::Int: 2777 case BuiltinType::UInt: 2778 return true; 2779 default: 2780 break; 2781 } 2782 2783 return false; 2784 } 2785 2786 ABIArgInfo 2787 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 2788 if (Ty->isAnyComplexType()) 2789 return ABIArgInfo::getDirect(); 2790 2791 if (isAggregateTypeForABI(Ty)) { 2792 // Records with non trivial destructors/constructors should not be passed 2793 // by value. 2794 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) 2795 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2796 2797 return ABIArgInfo::getIndirect(0); 2798 } 2799 2800 return (isPromotableTypeForABI(Ty) ? 2801 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 2802 } 2803 2804 ABIArgInfo 2805 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 2806 if (RetTy->isVoidType()) 2807 return ABIArgInfo::getIgnore(); 2808 2809 if (RetTy->isAnyComplexType()) 2810 return ABIArgInfo::getDirect(); 2811 2812 if (isAggregateTypeForABI(RetTy)) 2813 return ABIArgInfo::getIndirect(0); 2814 2815 return (isPromotableTypeForABI(RetTy) ? 2816 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 2817 } 2818 2819 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 2820 llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr, 2821 QualType Ty, 2822 CodeGenFunction &CGF) const { 2823 llvm::Type *BP = CGF.Int8PtrTy; 2824 llvm::Type *BPP = CGF.Int8PtrPtrTy; 2825 2826 CGBuilderTy &Builder = CGF.Builder; 2827 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 2828 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 2829 2830 // Update the va_list pointer. The pointer should be bumped by the 2831 // size of the object. We can trust getTypeSize() except for a complex 2832 // type whose base type is smaller than a doubleword. For these, the 2833 // size of the object is 16 bytes; see below for further explanation. 2834 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8; 2835 QualType BaseTy; 2836 unsigned CplxBaseSize = 0; 2837 2838 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 2839 BaseTy = CTy->getElementType(); 2840 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8; 2841 if (CplxBaseSize < 8) 2842 SizeInBytes = 16; 2843 } 2844 2845 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8); 2846 llvm::Value *NextAddr = 2847 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), 2848 "ap.next"); 2849 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 2850 2851 // If we have a complex type and the base type is smaller than 8 bytes, 2852 // the ABI calls for the real and imaginary parts to be right-adjusted 2853 // in separate doublewords. However, Clang expects us to produce a 2854 // pointer to a structure with the two parts packed tightly. So generate 2855 // loads of the real and imaginary parts relative to the va_list pointer, 2856 // and store them to a temporary structure. 2857 if (CplxBaseSize && CplxBaseSize < 8) { 2858 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty); 2859 llvm::Value *ImagAddr = RealAddr; 2860 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize)); 2861 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize)); 2862 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy)); 2863 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy); 2864 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy); 2865 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal"); 2866 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag"); 2867 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty), 2868 "vacplx"); 2869 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real"); 2870 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag"); 2871 Builder.CreateStore(Real, RealPtr, false); 2872 Builder.CreateStore(Imag, ImagPtr, false); 2873 return Ptr; 2874 } 2875 2876 // If the argument is smaller than 8 bytes, it is right-adjusted in 2877 // its doubleword slot. Adjust the pointer to pick it up from the 2878 // correct offset. 2879 if (SizeInBytes < 8) { 2880 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty); 2881 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes)); 2882 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 2883 } 2884 2885 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 2886 return Builder.CreateBitCast(Addr, PTy); 2887 } 2888 2889 static bool 2890 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2891 llvm::Value *Address) { 2892 // This is calculated from the LLVM and GCC tables and verified 2893 // against gcc output. AFAIK all ABIs use the same encoding. 2894 2895 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2896 2897 llvm::IntegerType *i8 = CGF.Int8Ty; 2898 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 2899 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 2900 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 2901 2902 // 0-31: r0-31, the 8-byte general-purpose registers 2903 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 2904 2905 // 32-63: fp0-31, the 8-byte floating-point registers 2906 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 2907 2908 // 64-76 are various 4-byte special-purpose registers: 2909 // 64: mq 2910 // 65: lr 2911 // 66: ctr 2912 // 67: ap 2913 // 68-75 cr0-7 2914 // 76: xer 2915 AssignToArrayRange(Builder, Address, Four8, 64, 76); 2916 2917 // 77-108: v0-31, the 16-byte vector registers 2918 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 2919 2920 // 109: vrsave 2921 // 110: vscr 2922 // 111: spe_acc 2923 // 112: spefscr 2924 // 113: sfp 2925 AssignToArrayRange(Builder, Address, Four8, 109, 113); 2926 2927 return false; 2928 } 2929 2930 bool 2931 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 2932 CodeGen::CodeGenFunction &CGF, 2933 llvm::Value *Address) const { 2934 2935 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 2936 } 2937 2938 bool 2939 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2940 llvm::Value *Address) const { 2941 2942 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 2943 } 2944 2945 //===----------------------------------------------------------------------===// 2946 // ARM ABI Implementation 2947 //===----------------------------------------------------------------------===// 2948 2949 namespace { 2950 2951 class ARMABIInfo : public ABIInfo { 2952 public: 2953 enum ABIKind { 2954 APCS = 0, 2955 AAPCS = 1, 2956 AAPCS_VFP 2957 }; 2958 2959 private: 2960 ABIKind Kind; 2961 2962 public: 2963 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {} 2964 2965 bool isEABI() const { 2966 StringRef Env = 2967 getContext().getTargetInfo().getTriple().getEnvironmentName(); 2968 return (Env == "gnueabi" || Env == "eabi" || 2969 Env == "android" || Env == "androideabi"); 2970 } 2971 2972 private: 2973 ABIKind getABIKind() const { return Kind; } 2974 2975 ABIArgInfo classifyReturnType(QualType RetTy) const; 2976 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs, 2977 unsigned &AllocatedVFP, 2978 bool &IsHA) const; 2979 bool isIllegalVectorType(QualType Ty) const; 2980 2981 virtual void computeInfo(CGFunctionInfo &FI) const; 2982 2983 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2984 CodeGenFunction &CGF) const; 2985 }; 2986 2987 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 2988 public: 2989 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 2990 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {} 2991 2992 const ARMABIInfo &getABIInfo() const { 2993 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2994 } 2995 2996 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 2997 return 13; 2998 } 2999 3000 StringRef getARCRetainAutoreleasedReturnValueMarker() const { 3001 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue"; 3002 } 3003 3004 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3005 llvm::Value *Address) const { 3006 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 3007 3008 // 0-15 are the 16 integer registers. 3009 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 3010 return false; 3011 } 3012 3013 unsigned getSizeOfUnwindException() const { 3014 if (getABIInfo().isEABI()) return 88; 3015 return TargetCodeGenInfo::getSizeOfUnwindException(); 3016 } 3017 }; 3018 3019 } 3020 3021 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 3022 // To correctly handle Homogeneous Aggregate, we need to keep track of the 3023 // VFP registers allocated so far. 3024 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive 3025 // VFP registers of the appropriate type unallocated then the argument is 3026 // allocated to the lowest-numbered sequence of such registers. 3027 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are 3028 // unallocated are marked as unavailable. 3029 unsigned AllocatedVFP = 0; 3030 int VFPRegs[16] = { 0 }; 3031 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3032 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3033 it != ie; ++it) { 3034 unsigned PreAllocation = AllocatedVFP; 3035 bool IsHA = false; 3036 // 6.1.2.3 There is one VFP co-processor register class using registers 3037 // s0-s15 (d0-d7) for passing arguments. 3038 const unsigned NumVFPs = 16; 3039 it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA); 3040 // If we do not have enough VFP registers for the HA, any VFP registers 3041 // that are unallocated are marked as unavailable. To achieve this, we add 3042 // padding of (NumVFPs - PreAllocation) floats. 3043 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) { 3044 llvm::Type *PaddingTy = llvm::ArrayType::get( 3045 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation); 3046 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy); 3047 } 3048 } 3049 3050 // Always honor user-specified calling convention. 3051 if (FI.getCallingConvention() != llvm::CallingConv::C) 3052 return; 3053 3054 // Calling convention as default by an ABI. 3055 llvm::CallingConv::ID DefaultCC; 3056 if (getContext().getTargetInfo().getTriple().getEnvironmentName()=="gnueabihf") 3057 DefaultCC = llvm::CallingConv::ARM_AAPCS_VFP; 3058 else if (isEABI()) 3059 DefaultCC = llvm::CallingConv::ARM_AAPCS; 3060 else 3061 DefaultCC = llvm::CallingConv::ARM_APCS; 3062 3063 // If user did not ask for specific calling convention explicitly (e.g. via 3064 // pcs attribute), set effective calling convention if it's different than ABI 3065 // default. 3066 switch (getABIKind()) { 3067 case APCS: 3068 if (DefaultCC != llvm::CallingConv::ARM_APCS) 3069 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_APCS); 3070 break; 3071 case AAPCS: 3072 if (DefaultCC != llvm::CallingConv::ARM_AAPCS) 3073 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS); 3074 break; 3075 case AAPCS_VFP: 3076 if (DefaultCC != llvm::CallingConv::ARM_AAPCS_VFP) 3077 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS_VFP); 3078 break; 3079 } 3080 } 3081 3082 /// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous 3083 /// aggregate. If HAMembers is non-null, the number of base elements 3084 /// contained in the type is returned through it; this is used for the 3085 /// recursive calls that check aggregate component types. 3086 static bool isHomogeneousAggregate(QualType Ty, const Type *&Base, 3087 ASTContext &Context, 3088 uint64_t *HAMembers = 0) { 3089 uint64_t Members = 0; 3090 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3091 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members)) 3092 return false; 3093 Members *= AT->getSize().getZExtValue(); 3094 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 3095 const RecordDecl *RD = RT->getDecl(); 3096 if (RD->hasFlexibleArrayMember()) 3097 return false; 3098 3099 Members = 0; 3100 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3101 i != e; ++i) { 3102 const FieldDecl *FD = *i; 3103 uint64_t FldMembers; 3104 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers)) 3105 return false; 3106 3107 Members = (RD->isUnion() ? 3108 std::max(Members, FldMembers) : Members + FldMembers); 3109 } 3110 } else { 3111 Members = 1; 3112 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 3113 Members = 2; 3114 Ty = CT->getElementType(); 3115 } 3116 3117 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 3118 // double, or 64-bit or 128-bit vectors. 3119 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 3120 if (BT->getKind() != BuiltinType::Float && 3121 BT->getKind() != BuiltinType::Double && 3122 BT->getKind() != BuiltinType::LongDouble) 3123 return false; 3124 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 3125 unsigned VecSize = Context.getTypeSize(VT); 3126 if (VecSize != 64 && VecSize != 128) 3127 return false; 3128 } else { 3129 return false; 3130 } 3131 3132 // The base type must be the same for all members. Vector types of the 3133 // same total size are treated as being equivalent here. 3134 const Type *TyPtr = Ty.getTypePtr(); 3135 if (!Base) 3136 Base = TyPtr; 3137 if (Base != TyPtr && 3138 (!Base->isVectorType() || !TyPtr->isVectorType() || 3139 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr))) 3140 return false; 3141 } 3142 3143 // Homogeneous Aggregates can have at most 4 members of the base type. 3144 if (HAMembers) 3145 *HAMembers = Members; 3146 3147 return (Members > 0 && Members <= 4); 3148 } 3149 3150 /// markAllocatedVFPs - update VFPRegs according to the alignment and 3151 /// number of VFP registers (unit is S register) requested. 3152 static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP, 3153 unsigned Alignment, 3154 unsigned NumRequired) { 3155 // Early Exit. 3156 if (AllocatedVFP >= 16) 3157 return; 3158 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive 3159 // VFP registers of the appropriate type unallocated then the argument is 3160 // allocated to the lowest-numbered sequence of such registers. 3161 for (unsigned I = 0; I < 16; I += Alignment) { 3162 bool FoundSlot = true; 3163 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++) 3164 if (J >= 16 || VFPRegs[J]) { 3165 FoundSlot = false; 3166 break; 3167 } 3168 if (FoundSlot) { 3169 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++) 3170 VFPRegs[J] = 1; 3171 AllocatedVFP += NumRequired; 3172 return; 3173 } 3174 } 3175 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are 3176 // unallocated are marked as unavailable. 3177 for (unsigned I = 0; I < 16; I++) 3178 VFPRegs[I] = 1; 3179 AllocatedVFP = 17; // We do not have enough VFP registers. 3180 } 3181 3182 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs, 3183 unsigned &AllocatedVFP, 3184 bool &IsHA) const { 3185 // We update number of allocated VFPs according to 3186 // 6.1.2.1 The following argument types are VFP CPRCs: 3187 // A single-precision floating-point type (including promoted 3188 // half-precision types); A double-precision floating-point type; 3189 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 3190 // with a Base Type of a single- or double-precision floating-point type, 3191 // 64-bit containerized vectors or 128-bit containerized vectors with one 3192 // to four Elements. 3193 3194 // Handle illegal vector types here. 3195 if (isIllegalVectorType(Ty)) { 3196 uint64_t Size = getContext().getTypeSize(Ty); 3197 if (Size <= 32) { 3198 llvm::Type *ResType = 3199 llvm::Type::getInt32Ty(getVMContext()); 3200 return ABIArgInfo::getDirect(ResType); 3201 } 3202 if (Size == 64) { 3203 llvm::Type *ResType = llvm::VectorType::get( 3204 llvm::Type::getInt32Ty(getVMContext()), 2); 3205 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2); 3206 return ABIArgInfo::getDirect(ResType); 3207 } 3208 if (Size == 128) { 3209 llvm::Type *ResType = llvm::VectorType::get( 3210 llvm::Type::getInt32Ty(getVMContext()), 4); 3211 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4); 3212 return ABIArgInfo::getDirect(ResType); 3213 } 3214 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3215 } 3216 // Update VFPRegs for legal vector types. 3217 if (const VectorType *VT = Ty->getAs<VectorType>()) { 3218 uint64_t Size = getContext().getTypeSize(VT); 3219 // Size of a legal vector should be power of 2 and above 64. 3220 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32); 3221 } 3222 // Update VFPRegs for floating point types. 3223 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 3224 if (BT->getKind() == BuiltinType::Half || 3225 BT->getKind() == BuiltinType::Float) 3226 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1); 3227 if (BT->getKind() == BuiltinType::Double || 3228 BT->getKind() == BuiltinType::LongDouble) 3229 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2); 3230 } 3231 3232 if (!isAggregateTypeForABI(Ty)) { 3233 // Treat an enum type as its underlying type. 3234 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3235 Ty = EnumTy->getDecl()->getIntegerType(); 3236 3237 return (Ty->isPromotableIntegerType() ? 3238 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3239 } 3240 3241 // Ignore empty records. 3242 if (isEmptyRecord(getContext(), Ty, true)) 3243 return ABIArgInfo::getIgnore(); 3244 3245 // Structures with either a non-trivial destructor or a non-trivial 3246 // copy constructor are always indirect. 3247 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) 3248 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3249 3250 if (getABIKind() == ARMABIInfo::AAPCS_VFP) { 3251 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 3252 // into VFP registers. 3253 const Type *Base = 0; 3254 uint64_t Members = 0; 3255 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) { 3256 assert(Base && "Base class should be set for homogeneous aggregate"); 3257 // Base can be a floating-point or a vector. 3258 if (Base->isVectorType()) { 3259 // ElementSize is in number of floats. 3260 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4; 3261 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize, 3262 Members * ElementSize); 3263 } else if (Base->isSpecificBuiltinType(BuiltinType::Float)) 3264 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members); 3265 else { 3266 assert(Base->isSpecificBuiltinType(BuiltinType::Double) || 3267 Base->isSpecificBuiltinType(BuiltinType::LongDouble)); 3268 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2); 3269 } 3270 IsHA = true; 3271 return ABIArgInfo::getExpand(); 3272 } 3273 } 3274 3275 // Support byval for ARM. 3276 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 3277 // most 8-byte. We realign the indirect argument if type alignment is bigger 3278 // than ABI alignment. 3279 uint64_t ABIAlign = 4; 3280 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8; 3281 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 3282 getABIKind() == ARMABIInfo::AAPCS) 3283 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 3284 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 3285 return ABIArgInfo::getIndirect(0, /*ByVal=*/true, 3286 /*Realign=*/TyAlign > ABIAlign); 3287 } 3288 3289 // Otherwise, pass by coercing to a structure of the appropriate size. 3290 llvm::Type* ElemTy; 3291 unsigned SizeRegs; 3292 // FIXME: Try to match the types of the arguments more accurately where 3293 // we can. 3294 if (getContext().getTypeAlign(Ty) <= 32) { 3295 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 3296 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 3297 } else { 3298 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 3299 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 3300 } 3301 3302 llvm::Type *STy = 3303 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL); 3304 return ABIArgInfo::getDirect(STy); 3305 } 3306 3307 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 3308 llvm::LLVMContext &VMContext) { 3309 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 3310 // is called integer-like if its size is less than or equal to one word, and 3311 // the offset of each of its addressable sub-fields is zero. 3312 3313 uint64_t Size = Context.getTypeSize(Ty); 3314 3315 // Check that the type fits in a word. 3316 if (Size > 32) 3317 return false; 3318 3319 // FIXME: Handle vector types! 3320 if (Ty->isVectorType()) 3321 return false; 3322 3323 // Float types are never treated as "integer like". 3324 if (Ty->isRealFloatingType()) 3325 return false; 3326 3327 // If this is a builtin or pointer type then it is ok. 3328 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 3329 return true; 3330 3331 // Small complex integer types are "integer like". 3332 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 3333 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 3334 3335 // Single element and zero sized arrays should be allowed, by the definition 3336 // above, but they are not. 3337 3338 // Otherwise, it must be a record type. 3339 const RecordType *RT = Ty->getAs<RecordType>(); 3340 if (!RT) return false; 3341 3342 // Ignore records with flexible arrays. 3343 const RecordDecl *RD = RT->getDecl(); 3344 if (RD->hasFlexibleArrayMember()) 3345 return false; 3346 3347 // Check that all sub-fields are at offset 0, and are themselves "integer 3348 // like". 3349 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3350 3351 bool HadField = false; 3352 unsigned idx = 0; 3353 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3354 i != e; ++i, ++idx) { 3355 const FieldDecl *FD = *i; 3356 3357 // Bit-fields are not addressable, we only need to verify they are "integer 3358 // like". We still have to disallow a subsequent non-bitfield, for example: 3359 // struct { int : 0; int x } 3360 // is non-integer like according to gcc. 3361 if (FD->isBitField()) { 3362 if (!RD->isUnion()) 3363 HadField = true; 3364 3365 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 3366 return false; 3367 3368 continue; 3369 } 3370 3371 // Check if this field is at offset 0. 3372 if (Layout.getFieldOffset(idx) != 0) 3373 return false; 3374 3375 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 3376 return false; 3377 3378 // Only allow at most one field in a structure. This doesn't match the 3379 // wording above, but follows gcc in situations with a field following an 3380 // empty structure. 3381 if (!RD->isUnion()) { 3382 if (HadField) 3383 return false; 3384 3385 HadField = true; 3386 } 3387 } 3388 3389 return true; 3390 } 3391 3392 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const { 3393 if (RetTy->isVoidType()) 3394 return ABIArgInfo::getIgnore(); 3395 3396 // Large vector types should be returned via memory. 3397 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 3398 return ABIArgInfo::getIndirect(0); 3399 3400 if (!isAggregateTypeForABI(RetTy)) { 3401 // Treat an enum type as its underlying type. 3402 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3403 RetTy = EnumTy->getDecl()->getIntegerType(); 3404 3405 return (RetTy->isPromotableIntegerType() ? 3406 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3407 } 3408 3409 // Structures with either a non-trivial destructor or a non-trivial 3410 // copy constructor are always indirect. 3411 if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy)) 3412 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3413 3414 // Are we following APCS? 3415 if (getABIKind() == APCS) { 3416 if (isEmptyRecord(getContext(), RetTy, false)) 3417 return ABIArgInfo::getIgnore(); 3418 3419 // Complex types are all returned as packed integers. 3420 // 3421 // FIXME: Consider using 2 x vector types if the back end handles them 3422 // correctly. 3423 if (RetTy->isAnyComplexType()) 3424 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3425 getContext().getTypeSize(RetTy))); 3426 3427 // Integer like structures are returned in r0. 3428 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 3429 // Return in the smallest viable integer type. 3430 uint64_t Size = getContext().getTypeSize(RetTy); 3431 if (Size <= 8) 3432 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 3433 if (Size <= 16) 3434 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 3435 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 3436 } 3437 3438 // Otherwise return in memory. 3439 return ABIArgInfo::getIndirect(0); 3440 } 3441 3442 // Otherwise this is an AAPCS variant. 3443 3444 if (isEmptyRecord(getContext(), RetTy, true)) 3445 return ABIArgInfo::getIgnore(); 3446 3447 // Check for homogeneous aggregates with AAPCS-VFP. 3448 if (getABIKind() == AAPCS_VFP) { 3449 const Type *Base = 0; 3450 if (isHomogeneousAggregate(RetTy, Base, getContext())) { 3451 assert(Base && "Base class should be set for homogeneous aggregate"); 3452 // Homogeneous Aggregates are returned directly. 3453 return ABIArgInfo::getDirect(); 3454 } 3455 } 3456 3457 // Aggregates <= 4 bytes are returned in r0; other aggregates 3458 // are returned indirectly. 3459 uint64_t Size = getContext().getTypeSize(RetTy); 3460 if (Size <= 32) { 3461 // Return in the smallest viable integer type. 3462 if (Size <= 8) 3463 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 3464 if (Size <= 16) 3465 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 3466 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 3467 } 3468 3469 return ABIArgInfo::getIndirect(0); 3470 } 3471 3472 /// isIllegalVector - check whether Ty is an illegal vector type. 3473 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 3474 if (const VectorType *VT = Ty->getAs<VectorType>()) { 3475 // Check whether VT is legal. 3476 unsigned NumElements = VT->getNumElements(); 3477 uint64_t Size = getContext().getTypeSize(VT); 3478 // NumElements should be power of 2. 3479 if ((NumElements & (NumElements - 1)) != 0) 3480 return true; 3481 // Size should be greater than 32 bits. 3482 return Size <= 32; 3483 } 3484 return false; 3485 } 3486 3487 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3488 CodeGenFunction &CGF) const { 3489 llvm::Type *BP = CGF.Int8PtrTy; 3490 llvm::Type *BPP = CGF.Int8PtrPtrTy; 3491 3492 CGBuilderTy &Builder = CGF.Builder; 3493 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 3494 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 3495 3496 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8; 3497 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 3498 bool IsIndirect = false; 3499 3500 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 3501 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 3502 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 3503 getABIKind() == ARMABIInfo::AAPCS) 3504 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 3505 else 3506 TyAlign = 4; 3507 // Use indirect if size of the illegal vector is bigger than 16 bytes. 3508 if (isIllegalVectorType(Ty) && Size > 16) { 3509 IsIndirect = true; 3510 Size = 4; 3511 TyAlign = 4; 3512 } 3513 3514 // Handle address alignment for ABI alignment > 4 bytes. 3515 if (TyAlign > 4) { 3516 assert((TyAlign & (TyAlign - 1)) == 0 && 3517 "Alignment is not power of 2!"); 3518 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 3519 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 3520 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 3521 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align"); 3522 } 3523 3524 uint64_t Offset = 3525 llvm::RoundUpToAlignment(Size, 4); 3526 llvm::Value *NextAddr = 3527 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 3528 "ap.next"); 3529 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 3530 3531 if (IsIndirect) 3532 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP)); 3533 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) { 3534 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur 3535 // may not be correctly aligned for the vector type. We create an aligned 3536 // temporary space and copy the content over from ap.cur to the temporary 3537 // space. This is necessary if the natural alignment of the type is greater 3538 // than the ABI alignment. 3539 llvm::Type *I8PtrTy = Builder.getInt8PtrTy(); 3540 CharUnits CharSize = getContext().getTypeSizeInChars(Ty); 3541 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty), 3542 "var.align"); 3543 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy); 3544 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy); 3545 Builder.CreateMemCpy(Dst, Src, 3546 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()), 3547 TyAlign, false); 3548 Addr = AlignedTemp; //The content is in aligned location. 3549 } 3550 llvm::Type *PTy = 3551 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 3552 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 3553 3554 return AddrTyped; 3555 } 3556 3557 namespace { 3558 3559 class NaClARMABIInfo : public ABIInfo { 3560 public: 3561 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind) 3562 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {} 3563 virtual void computeInfo(CGFunctionInfo &FI) const; 3564 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3565 CodeGenFunction &CGF) const; 3566 private: 3567 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv. 3568 ARMABIInfo NInfo; // Used for everything else. 3569 }; 3570 3571 class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo { 3572 public: 3573 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind) 3574 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {} 3575 }; 3576 3577 } 3578 3579 void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 3580 if (FI.getASTCallingConvention() == CC_PnaclCall) 3581 PInfo.computeInfo(FI); 3582 else 3583 static_cast<const ABIInfo&>(NInfo).computeInfo(FI); 3584 } 3585 3586 llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3587 CodeGenFunction &CGF) const { 3588 // Always use the native convention; calling pnacl-style varargs functions 3589 // is unsupported. 3590 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF); 3591 } 3592 3593 //===----------------------------------------------------------------------===// 3594 // NVPTX ABI Implementation 3595 //===----------------------------------------------------------------------===// 3596 3597 namespace { 3598 3599 class NVPTXABIInfo : public ABIInfo { 3600 public: 3601 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 3602 3603 ABIArgInfo classifyReturnType(QualType RetTy) const; 3604 ABIArgInfo classifyArgumentType(QualType Ty) const; 3605 3606 virtual void computeInfo(CGFunctionInfo &FI) const; 3607 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3608 CodeGenFunction &CFG) const; 3609 }; 3610 3611 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 3612 public: 3613 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 3614 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {} 3615 3616 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 3617 CodeGen::CodeGenModule &M) const; 3618 }; 3619 3620 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 3621 if (RetTy->isVoidType()) 3622 return ABIArgInfo::getIgnore(); 3623 if (isAggregateTypeForABI(RetTy)) 3624 return ABIArgInfo::getIndirect(0); 3625 return ABIArgInfo::getDirect(); 3626 } 3627 3628 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 3629 if (isAggregateTypeForABI(Ty)) 3630 return ABIArgInfo::getIndirect(0); 3631 3632 return ABIArgInfo::getDirect(); 3633 } 3634 3635 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 3636 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3637 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3638 it != ie; ++it) 3639 it->info = classifyArgumentType(it->type); 3640 3641 // Always honor user-specified calling convention. 3642 if (FI.getCallingConvention() != llvm::CallingConv::C) 3643 return; 3644 3645 // Calling convention as default by an ABI. 3646 // We're still using the PTX_Kernel/PTX_Device calling conventions here, 3647 // but we should switch to NVVM metadata later on. 3648 llvm::CallingConv::ID DefaultCC; 3649 const LangOptions &LangOpts = getContext().getLangOpts(); 3650 if (LangOpts.OpenCL || LangOpts.CUDA) { 3651 // If we are in OpenCL or CUDA mode, then default to device functions 3652 DefaultCC = llvm::CallingConv::PTX_Device; 3653 } else { 3654 // If we are in standard C/C++ mode, use the triple to decide on the default 3655 StringRef Env = 3656 getContext().getTargetInfo().getTriple().getEnvironmentName(); 3657 if (Env == "device") 3658 DefaultCC = llvm::CallingConv::PTX_Device; 3659 else 3660 DefaultCC = llvm::CallingConv::PTX_Kernel; 3661 } 3662 FI.setEffectiveCallingConvention(DefaultCC); 3663 3664 } 3665 3666 llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3667 CodeGenFunction &CFG) const { 3668 llvm_unreachable("NVPTX does not support varargs"); 3669 } 3670 3671 void NVPTXTargetCodeGenInfo:: 3672 SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 3673 CodeGen::CodeGenModule &M) const{ 3674 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 3675 if (!FD) return; 3676 3677 llvm::Function *F = cast<llvm::Function>(GV); 3678 3679 // Perform special handling in OpenCL mode 3680 if (M.getLangOpts().OpenCL) { 3681 // Use OpenCL function attributes to set proper calling conventions 3682 // By default, all functions are device functions 3683 if (FD->hasAttr<OpenCLKernelAttr>()) { 3684 // OpenCL __kernel functions get a kernel calling convention 3685 F->setCallingConv(llvm::CallingConv::PTX_Kernel); 3686 // And kernel functions are not subject to inlining 3687 F->addFnAttr(llvm::Attribute::NoInline); 3688 } 3689 } 3690 3691 // Perform special handling in CUDA mode. 3692 if (M.getLangOpts().CUDA) { 3693 // CUDA __global__ functions get a kernel calling convention. Since 3694 // __global__ functions cannot be called from the device, we do not 3695 // need to set the noinline attribute. 3696 if (FD->getAttr<CUDAGlobalAttr>()) 3697 F->setCallingConv(llvm::CallingConv::PTX_Kernel); 3698 } 3699 } 3700 3701 } 3702 3703 //===----------------------------------------------------------------------===// 3704 // MBlaze ABI Implementation 3705 //===----------------------------------------------------------------------===// 3706 3707 namespace { 3708 3709 class MBlazeABIInfo : public ABIInfo { 3710 public: 3711 MBlazeABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 3712 3713 bool isPromotableIntegerType(QualType Ty) const; 3714 3715 ABIArgInfo classifyReturnType(QualType RetTy) const; 3716 ABIArgInfo classifyArgumentType(QualType RetTy) const; 3717 3718 virtual void computeInfo(CGFunctionInfo &FI) const { 3719 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3720 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3721 it != ie; ++it) 3722 it->info = classifyArgumentType(it->type); 3723 } 3724 3725 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3726 CodeGenFunction &CGF) const; 3727 }; 3728 3729 class MBlazeTargetCodeGenInfo : public TargetCodeGenInfo { 3730 public: 3731 MBlazeTargetCodeGenInfo(CodeGenTypes &CGT) 3732 : TargetCodeGenInfo(new MBlazeABIInfo(CGT)) {} 3733 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 3734 CodeGen::CodeGenModule &M) const; 3735 }; 3736 3737 } 3738 3739 bool MBlazeABIInfo::isPromotableIntegerType(QualType Ty) const { 3740 // MBlaze ABI requires all 8 and 16 bit quantities to be extended. 3741 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 3742 switch (BT->getKind()) { 3743 case BuiltinType::Bool: 3744 case BuiltinType::Char_S: 3745 case BuiltinType::Char_U: 3746 case BuiltinType::SChar: 3747 case BuiltinType::UChar: 3748 case BuiltinType::Short: 3749 case BuiltinType::UShort: 3750 return true; 3751 default: 3752 return false; 3753 } 3754 return false; 3755 } 3756 3757 llvm::Value *MBlazeABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3758 CodeGenFunction &CGF) const { 3759 // FIXME: Implement 3760 return 0; 3761 } 3762 3763 3764 ABIArgInfo MBlazeABIInfo::classifyReturnType(QualType RetTy) const { 3765 if (RetTy->isVoidType()) 3766 return ABIArgInfo::getIgnore(); 3767 if (isAggregateTypeForABI(RetTy)) 3768 return ABIArgInfo::getIndirect(0); 3769 3770 return (isPromotableIntegerType(RetTy) ? 3771 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3772 } 3773 3774 ABIArgInfo MBlazeABIInfo::classifyArgumentType(QualType Ty) const { 3775 if (isAggregateTypeForABI(Ty)) 3776 return ABIArgInfo::getIndirect(0); 3777 3778 return (isPromotableIntegerType(Ty) ? 3779 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3780 } 3781 3782 void MBlazeTargetCodeGenInfo::SetTargetAttributes(const Decl *D, 3783 llvm::GlobalValue *GV, 3784 CodeGen::CodeGenModule &M) 3785 const { 3786 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 3787 if (!FD) return; 3788 3789 llvm::CallingConv::ID CC = llvm::CallingConv::C; 3790 if (FD->hasAttr<MBlazeInterruptHandlerAttr>()) 3791 CC = llvm::CallingConv::MBLAZE_INTR; 3792 else if (FD->hasAttr<MBlazeSaveVolatilesAttr>()) 3793 CC = llvm::CallingConv::MBLAZE_SVOL; 3794 3795 if (CC != llvm::CallingConv::C) { 3796 // Handle 'interrupt_handler' attribute: 3797 llvm::Function *F = cast<llvm::Function>(GV); 3798 3799 // Step 1: Set ISR calling convention. 3800 F->setCallingConv(CC); 3801 3802 // Step 2: Add attributes goodness. 3803 F->addFnAttr(llvm::Attribute::NoInline); 3804 } 3805 3806 // Step 3: Emit _interrupt_handler alias. 3807 if (CC == llvm::CallingConv::MBLAZE_INTR) 3808 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage, 3809 "_interrupt_handler", GV, &M.getModule()); 3810 } 3811 3812 3813 //===----------------------------------------------------------------------===// 3814 // MSP430 ABI Implementation 3815 //===----------------------------------------------------------------------===// 3816 3817 namespace { 3818 3819 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 3820 public: 3821 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 3822 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 3823 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 3824 CodeGen::CodeGenModule &M) const; 3825 }; 3826 3827 } 3828 3829 void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D, 3830 llvm::GlobalValue *GV, 3831 CodeGen::CodeGenModule &M) const { 3832 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 3833 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) { 3834 // Handle 'interrupt' attribute: 3835 llvm::Function *F = cast<llvm::Function>(GV); 3836 3837 // Step 1: Set ISR calling convention. 3838 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 3839 3840 // Step 2: Add attributes goodness. 3841 F->addFnAttr(llvm::Attribute::NoInline); 3842 3843 // Step 3: Emit ISR vector alias. 3844 unsigned Num = attr->getNumber() / 2; 3845 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage, 3846 "__isr_" + Twine(Num), 3847 GV, &M.getModule()); 3848 } 3849 } 3850 } 3851 3852 //===----------------------------------------------------------------------===// 3853 // MIPS ABI Implementation. This works for both little-endian and 3854 // big-endian variants. 3855 //===----------------------------------------------------------------------===// 3856 3857 namespace { 3858 class MipsABIInfo : public ABIInfo { 3859 bool IsO32; 3860 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 3861 void CoerceToIntArgs(uint64_t TySize, 3862 SmallVector<llvm::Type*, 8> &ArgList) const; 3863 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 3864 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 3865 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 3866 public: 3867 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 3868 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 3869 StackAlignInBytes(IsO32 ? 8 : 16) {} 3870 3871 ABIArgInfo classifyReturnType(QualType RetTy) const; 3872 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 3873 virtual void computeInfo(CGFunctionInfo &FI) const; 3874 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3875 CodeGenFunction &CGF) const; 3876 }; 3877 3878 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 3879 unsigned SizeOfUnwindException; 3880 public: 3881 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 3882 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)), 3883 SizeOfUnwindException(IsO32 ? 24 : 32) {} 3884 3885 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 3886 return 29; 3887 } 3888 3889 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 3890 CodeGen::CodeGenModule &CGM) const { 3891 // 3892 // can fill this in when new attribute work in llvm is done. 3893 // attributes mips16 and nomips16 need to be handled here. 3894 // 3895 } 3896 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3897 llvm::Value *Address) const; 3898 3899 unsigned getSizeOfUnwindException() const { 3900 return SizeOfUnwindException; 3901 } 3902 }; 3903 } 3904 3905 void MipsABIInfo::CoerceToIntArgs(uint64_t TySize, 3906 SmallVector<llvm::Type*, 8> &ArgList) const { 3907 llvm::IntegerType *IntTy = 3908 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 3909 3910 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 3911 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 3912 ArgList.push_back(IntTy); 3913 3914 // If necessary, add one more integer type to ArgList. 3915 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 3916 3917 if (R) 3918 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 3919 } 3920 3921 // In N32/64, an aligned double precision floating point field is passed in 3922 // a register. 3923 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 3924 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 3925 3926 if (IsO32) { 3927 CoerceToIntArgs(TySize, ArgList); 3928 return llvm::StructType::get(getVMContext(), ArgList); 3929 } 3930 3931 if (Ty->isComplexType()) 3932 return CGT.ConvertType(Ty); 3933 3934 const RecordType *RT = Ty->getAs<RecordType>(); 3935 3936 // Unions/vectors are passed in integer registers. 3937 if (!RT || !RT->isStructureOrClassType()) { 3938 CoerceToIntArgs(TySize, ArgList); 3939 return llvm::StructType::get(getVMContext(), ArgList); 3940 } 3941 3942 const RecordDecl *RD = RT->getDecl(); 3943 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 3944 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 3945 3946 uint64_t LastOffset = 0; 3947 unsigned idx = 0; 3948 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 3949 3950 // Iterate over fields in the struct/class and check if there are any aligned 3951 // double fields. 3952 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3953 i != e; ++i, ++idx) { 3954 const QualType Ty = i->getType(); 3955 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 3956 3957 if (!BT || BT->getKind() != BuiltinType::Double) 3958 continue; 3959 3960 uint64_t Offset = Layout.getFieldOffset(idx); 3961 if (Offset % 64) // Ignore doubles that are not aligned. 3962 continue; 3963 3964 // Add ((Offset - LastOffset) / 64) args of type i64. 3965 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 3966 ArgList.push_back(I64); 3967 3968 // Add double type. 3969 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 3970 LastOffset = Offset + 64; 3971 } 3972 3973 CoerceToIntArgs(TySize - LastOffset, IntArgList); 3974 ArgList.append(IntArgList.begin(), IntArgList.end()); 3975 3976 return llvm::StructType::get(getVMContext(), ArgList); 3977 } 3978 3979 llvm::Type *MipsABIInfo::getPaddingType(uint64_t Align, uint64_t Offset) const { 3980 assert((Offset % MinABIStackAlignInBytes) == 0); 3981 3982 if ((Align - 1) & Offset) 3983 return llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 3984 3985 return 0; 3986 } 3987 3988 ABIArgInfo 3989 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 3990 uint64_t OrigOffset = Offset; 3991 uint64_t TySize = getContext().getTypeSize(Ty); 3992 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 3993 3994 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 3995 (uint64_t)StackAlignInBytes); 3996 Offset = llvm::RoundUpToAlignment(Offset, Align); 3997 Offset += llvm::RoundUpToAlignment(TySize, Align * 8) / 8; 3998 3999 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 4000 // Ignore empty aggregates. 4001 if (TySize == 0) 4002 return ABIArgInfo::getIgnore(); 4003 4004 // Records with non trivial destructors/constructors should not be passed 4005 // by value. 4006 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) { 4007 Offset = OrigOffset + MinABIStackAlignInBytes; 4008 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4009 } 4010 4011 // If we have reached here, aggregates are passed directly by coercing to 4012 // another structure type. Padding is inserted if the offset of the 4013 // aggregate is unaligned. 4014 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 4015 getPaddingType(Align, OrigOffset)); 4016 } 4017 4018 // Treat an enum type as its underlying type. 4019 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4020 Ty = EnumTy->getDecl()->getIntegerType(); 4021 4022 if (Ty->isPromotableIntegerType()) 4023 return ABIArgInfo::getExtend(); 4024 4025 return ABIArgInfo::getDirect(0, 0, 4026 IsO32 ? 0 : getPaddingType(Align, OrigOffset)); 4027 } 4028 4029 llvm::Type* 4030 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 4031 const RecordType *RT = RetTy->getAs<RecordType>(); 4032 SmallVector<llvm::Type*, 8> RTList; 4033 4034 if (RT && RT->isStructureOrClassType()) { 4035 const RecordDecl *RD = RT->getDecl(); 4036 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 4037 unsigned FieldCnt = Layout.getFieldCount(); 4038 4039 // N32/64 returns struct/classes in floating point registers if the 4040 // following conditions are met: 4041 // 1. The size of the struct/class is no larger than 128-bit. 4042 // 2. The struct/class has one or two fields all of which are floating 4043 // point types. 4044 // 3. The offset of the first field is zero (this follows what gcc does). 4045 // 4046 // Any other composite results are returned in integer registers. 4047 // 4048 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 4049 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 4050 for (; b != e; ++b) { 4051 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 4052 4053 if (!BT || !BT->isFloatingPoint()) 4054 break; 4055 4056 RTList.push_back(CGT.ConvertType(b->getType())); 4057 } 4058 4059 if (b == e) 4060 return llvm::StructType::get(getVMContext(), RTList, 4061 RD->hasAttr<PackedAttr>()); 4062 4063 RTList.clear(); 4064 } 4065 } 4066 4067 CoerceToIntArgs(Size, RTList); 4068 return llvm::StructType::get(getVMContext(), RTList); 4069 } 4070 4071 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 4072 uint64_t Size = getContext().getTypeSize(RetTy); 4073 4074 if (RetTy->isVoidType() || Size == 0) 4075 return ABIArgInfo::getIgnore(); 4076 4077 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 4078 if (Size <= 128) { 4079 if (RetTy->isAnyComplexType()) 4080 return ABIArgInfo::getDirect(); 4081 4082 // O32 returns integer vectors in registers. 4083 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation()) 4084 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 4085 4086 if (!IsO32 && !isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy)) 4087 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 4088 } 4089 4090 return ABIArgInfo::getIndirect(0); 4091 } 4092 4093 // Treat an enum type as its underlying type. 4094 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 4095 RetTy = EnumTy->getDecl()->getIntegerType(); 4096 4097 return (RetTy->isPromotableIntegerType() ? 4098 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4099 } 4100 4101 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 4102 ABIArgInfo &RetInfo = FI.getReturnInfo(); 4103 RetInfo = classifyReturnType(FI.getReturnType()); 4104 4105 // Check if a pointer to an aggregate is passed as a hidden argument. 4106 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 4107 4108 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4109 it != ie; ++it) 4110 it->info = classifyArgumentType(it->type, Offset); 4111 } 4112 4113 llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4114 CodeGenFunction &CGF) const { 4115 llvm::Type *BP = CGF.Int8PtrTy; 4116 llvm::Type *BPP = CGF.Int8PtrPtrTy; 4117 4118 CGBuilderTy &Builder = CGF.Builder; 4119 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 4120 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 4121 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8; 4122 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 4123 llvm::Value *AddrTyped; 4124 unsigned PtrWidth = getContext().getTargetInfo().getPointerWidth(0); 4125 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty; 4126 4127 if (TypeAlign > MinABIStackAlignInBytes) { 4128 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy); 4129 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1); 4130 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign); 4131 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc); 4132 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask); 4133 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy); 4134 } 4135 else 4136 AddrTyped = Builder.CreateBitCast(Addr, PTy); 4137 4138 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP); 4139 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes); 4140 uint64_t Offset = 4141 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign); 4142 llvm::Value *NextAddr = 4143 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset), 4144 "ap.next"); 4145 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 4146 4147 return AddrTyped; 4148 } 4149 4150 bool 4151 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4152 llvm::Value *Address) const { 4153 // This information comes from gcc's implementation, which seems to 4154 // as canonical as it gets. 4155 4156 // Everything on MIPS is 4 bytes. Double-precision FP registers 4157 // are aliased to pairs of single-precision FP registers. 4158 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 4159 4160 // 0-31 are the general purpose registers, $0 - $31. 4161 // 32-63 are the floating-point registers, $f0 - $f31. 4162 // 64 and 65 are the multiply/divide registers, $hi and $lo. 4163 // 66 is the (notional, I think) register for signal-handler return. 4164 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 4165 4166 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 4167 // They are one bit wide and ignored here. 4168 4169 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 4170 // (coprocessor 1 is the FP unit) 4171 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 4172 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 4173 // 176-181 are the DSP accumulator registers. 4174 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 4175 return false; 4176 } 4177 4178 //===----------------------------------------------------------------------===// 4179 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 4180 // Currently subclassed only to implement custom OpenCL C function attribute 4181 // handling. 4182 //===----------------------------------------------------------------------===// 4183 4184 namespace { 4185 4186 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 4187 public: 4188 TCETargetCodeGenInfo(CodeGenTypes &CGT) 4189 : DefaultTargetCodeGenInfo(CGT) {} 4190 4191 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4192 CodeGen::CodeGenModule &M) const; 4193 }; 4194 4195 void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D, 4196 llvm::GlobalValue *GV, 4197 CodeGen::CodeGenModule &M) const { 4198 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 4199 if (!FD) return; 4200 4201 llvm::Function *F = cast<llvm::Function>(GV); 4202 4203 if (M.getLangOpts().OpenCL) { 4204 if (FD->hasAttr<OpenCLKernelAttr>()) { 4205 // OpenCL C Kernel functions are not subject to inlining 4206 F->addFnAttr(llvm::Attribute::NoInline); 4207 4208 if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) { 4209 4210 // Convert the reqd_work_group_size() attributes to metadata. 4211 llvm::LLVMContext &Context = F->getContext(); 4212 llvm::NamedMDNode *OpenCLMetadata = 4213 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info"); 4214 4215 SmallVector<llvm::Value*, 5> Operands; 4216 Operands.push_back(F); 4217 4218 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 4219 llvm::APInt(32, 4220 FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim()))); 4221 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 4222 llvm::APInt(32, 4223 FD->getAttr<ReqdWorkGroupSizeAttr>()->getYDim()))); 4224 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 4225 llvm::APInt(32, 4226 FD->getAttr<ReqdWorkGroupSizeAttr>()->getZDim()))); 4227 4228 // Add a boolean constant operand for "required" (true) or "hint" (false) 4229 // for implementing the work_group_size_hint attr later. Currently 4230 // always true as the hint is not yet implemented. 4231 Operands.push_back(llvm::ConstantInt::getTrue(Context)); 4232 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 4233 } 4234 } 4235 } 4236 } 4237 4238 } 4239 4240 //===----------------------------------------------------------------------===// 4241 // Hexagon ABI Implementation 4242 //===----------------------------------------------------------------------===// 4243 4244 namespace { 4245 4246 class HexagonABIInfo : public ABIInfo { 4247 4248 4249 public: 4250 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 4251 4252 private: 4253 4254 ABIArgInfo classifyReturnType(QualType RetTy) const; 4255 ABIArgInfo classifyArgumentType(QualType RetTy) const; 4256 4257 virtual void computeInfo(CGFunctionInfo &FI) const; 4258 4259 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4260 CodeGenFunction &CGF) const; 4261 }; 4262 4263 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 4264 public: 4265 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 4266 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {} 4267 4268 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 4269 return 29; 4270 } 4271 }; 4272 4273 } 4274 4275 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 4276 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4277 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4278 it != ie; ++it) 4279 it->info = classifyArgumentType(it->type); 4280 } 4281 4282 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const { 4283 if (!isAggregateTypeForABI(Ty)) { 4284 // Treat an enum type as its underlying type. 4285 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4286 Ty = EnumTy->getDecl()->getIntegerType(); 4287 4288 return (Ty->isPromotableIntegerType() ? 4289 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4290 } 4291 4292 // Ignore empty records. 4293 if (isEmptyRecord(getContext(), Ty, true)) 4294 return ABIArgInfo::getIgnore(); 4295 4296 // Structures with either a non-trivial destructor or a non-trivial 4297 // copy constructor are always indirect. 4298 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) 4299 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4300 4301 uint64_t Size = getContext().getTypeSize(Ty); 4302 if (Size > 64) 4303 return ABIArgInfo::getIndirect(0, /*ByVal=*/true); 4304 // Pass in the smallest viable integer type. 4305 else if (Size > 32) 4306 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 4307 else if (Size > 16) 4308 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 4309 else if (Size > 8) 4310 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 4311 else 4312 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 4313 } 4314 4315 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 4316 if (RetTy->isVoidType()) 4317 return ABIArgInfo::getIgnore(); 4318 4319 // Large vector types should be returned via memory. 4320 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64) 4321 return ABIArgInfo::getIndirect(0); 4322 4323 if (!isAggregateTypeForABI(RetTy)) { 4324 // Treat an enum type as its underlying type. 4325 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 4326 RetTy = EnumTy->getDecl()->getIntegerType(); 4327 4328 return (RetTy->isPromotableIntegerType() ? 4329 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4330 } 4331 4332 // Structures with either a non-trivial destructor or a non-trivial 4333 // copy constructor are always indirect. 4334 if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy)) 4335 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4336 4337 if (isEmptyRecord(getContext(), RetTy, true)) 4338 return ABIArgInfo::getIgnore(); 4339 4340 // Aggregates <= 8 bytes are returned in r0; other aggregates 4341 // are returned indirectly. 4342 uint64_t Size = getContext().getTypeSize(RetTy); 4343 if (Size <= 64) { 4344 // Return in the smallest viable integer type. 4345 if (Size <= 8) 4346 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 4347 if (Size <= 16) 4348 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 4349 if (Size <= 32) 4350 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 4351 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 4352 } 4353 4354 return ABIArgInfo::getIndirect(0, /*ByVal=*/true); 4355 } 4356 4357 llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4358 CodeGenFunction &CGF) const { 4359 // FIXME: Need to handle alignment 4360 llvm::Type *BPP = CGF.Int8PtrPtrTy; 4361 4362 CGBuilderTy &Builder = CGF.Builder; 4363 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 4364 "ap"); 4365 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 4366 llvm::Type *PTy = 4367 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 4368 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 4369 4370 uint64_t Offset = 4371 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4); 4372 llvm::Value *NextAddr = 4373 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 4374 "ap.next"); 4375 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 4376 4377 return AddrTyped; 4378 } 4379 4380 4381 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 4382 if (TheTargetCodeGenInfo) 4383 return *TheTargetCodeGenInfo; 4384 4385 const llvm::Triple &Triple = getContext().getTargetInfo().getTriple(); 4386 switch (Triple.getArch()) { 4387 default: 4388 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types)); 4389 4390 case llvm::Triple::le32: 4391 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types)); 4392 case llvm::Triple::mips: 4393 case llvm::Triple::mipsel: 4394 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true)); 4395 4396 case llvm::Triple::mips64: 4397 case llvm::Triple::mips64el: 4398 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false)); 4399 4400 case llvm::Triple::arm: 4401 case llvm::Triple::thumb: 4402 { 4403 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 4404 if (strcmp(getContext().getTargetInfo().getABI(), "apcs-gnu") == 0) 4405 Kind = ARMABIInfo::APCS; 4406 else if (CodeGenOpts.FloatABI == "hard" || 4407 (CodeGenOpts.FloatABI != "soft" && Triple.getEnvironment()==llvm::Triple::GNUEABIHF)) 4408 Kind = ARMABIInfo::AAPCS_VFP; 4409 4410 switch (Triple.getOS()) { 4411 case llvm::Triple::NaCl: 4412 return *(TheTargetCodeGenInfo = 4413 new NaClARMTargetCodeGenInfo(Types, Kind)); 4414 default: 4415 return *(TheTargetCodeGenInfo = 4416 new ARMTargetCodeGenInfo(Types, Kind)); 4417 } 4418 } 4419 4420 case llvm::Triple::ppc: 4421 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types)); 4422 case llvm::Triple::ppc64: 4423 if (Triple.isOSBinFormatELF()) 4424 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types)); 4425 else 4426 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types)); 4427 4428 case llvm::Triple::nvptx: 4429 case llvm::Triple::nvptx64: 4430 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types)); 4431 4432 case llvm::Triple::mblaze: 4433 return *(TheTargetCodeGenInfo = new MBlazeTargetCodeGenInfo(Types)); 4434 4435 case llvm::Triple::msp430: 4436 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types)); 4437 4438 case llvm::Triple::tce: 4439 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types)); 4440 4441 case llvm::Triple::x86: { 4442 bool DisableMMX = strcmp(getContext().getTargetInfo().getABI(), "no-mmx") == 0; 4443 4444 if (Triple.isOSDarwin()) 4445 return *(TheTargetCodeGenInfo = 4446 new X86_32TargetCodeGenInfo(Types, true, true, DisableMMX, false, 4447 CodeGenOpts.NumRegisterParameters)); 4448 4449 switch (Triple.getOS()) { 4450 case llvm::Triple::Cygwin: 4451 case llvm::Triple::MinGW32: 4452 case llvm::Triple::AuroraUX: 4453 case llvm::Triple::DragonFly: 4454 case llvm::Triple::FreeBSD: 4455 case llvm::Triple::OpenBSD: 4456 case llvm::Triple::Bitrig: 4457 return *(TheTargetCodeGenInfo = 4458 new X86_32TargetCodeGenInfo(Types, false, true, DisableMMX, 4459 false, 4460 CodeGenOpts.NumRegisterParameters)); 4461 4462 case llvm::Triple::Win32: 4463 return *(TheTargetCodeGenInfo = 4464 new X86_32TargetCodeGenInfo(Types, false, true, DisableMMX, true, 4465 CodeGenOpts.NumRegisterParameters)); 4466 4467 default: 4468 return *(TheTargetCodeGenInfo = 4469 new X86_32TargetCodeGenInfo(Types, false, false, DisableMMX, 4470 false, 4471 CodeGenOpts.NumRegisterParameters)); 4472 } 4473 } 4474 4475 case llvm::Triple::x86_64: { 4476 bool HasAVX = strcmp(getContext().getTargetInfo().getABI(), "avx") == 0; 4477 4478 switch (Triple.getOS()) { 4479 case llvm::Triple::Win32: 4480 case llvm::Triple::MinGW32: 4481 case llvm::Triple::Cygwin: 4482 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types)); 4483 case llvm::Triple::NaCl: 4484 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types, HasAVX)); 4485 default: 4486 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types, 4487 HasAVX)); 4488 } 4489 } 4490 case llvm::Triple::hexagon: 4491 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types)); 4492 } 4493 } 4494