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