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