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