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