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