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