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