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