1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // These classes wrap the information about a call or function 10 // definition used to handle ABI compliancy. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TargetInfo.h" 15 #include "ABIInfo.h" 16 #include "CGBlocks.h" 17 #include "CGCXXABI.h" 18 #include "CGValue.h" 19 #include "CodeGenFunction.h" 20 #include "clang/AST/Attr.h" 21 #include "clang/AST/RecordLayout.h" 22 #include "clang/Basic/CodeGenOptions.h" 23 #include "clang/Basic/DiagnosticFrontend.h" 24 #include "clang/Basic/Builtins.h" 25 #include "clang/CodeGen/CGFunctionInfo.h" 26 #include "clang/CodeGen/SwiftCallingConv.h" 27 #include "llvm/ADT/SmallBitVector.h" 28 #include "llvm/ADT/StringExtras.h" 29 #include "llvm/ADT/StringSwitch.h" 30 #include "llvm/ADT/Triple.h" 31 #include "llvm/ADT/Twine.h" 32 #include "llvm/IR/DataLayout.h" 33 #include "llvm/IR/IntrinsicsNVPTX.h" 34 #include "llvm/IR/IntrinsicsS390.h" 35 #include "llvm/IR/Type.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include <algorithm> // std::sort 38 39 using namespace clang; 40 using namespace CodeGen; 41 42 // Helper for coercing an aggregate argument or return value into an integer 43 // array of the same size (including padding) and alignment. This alternate 44 // coercion happens only for the RenderScript ABI and can be removed after 45 // runtimes that rely on it are no longer supported. 46 // 47 // RenderScript assumes that the size of the argument / return value in the IR 48 // is the same as the size of the corresponding qualified type. This helper 49 // coerces the aggregate type into an array of the same size (including 50 // padding). This coercion is used in lieu of expansion of struct members or 51 // other canonical coercions that return a coerced-type of larger size. 52 // 53 // Ty - The argument / return value type 54 // Context - The associated ASTContext 55 // LLVMContext - The associated LLVMContext 56 static ABIArgInfo coerceToIntArray(QualType Ty, 57 ASTContext &Context, 58 llvm::LLVMContext &LLVMContext) { 59 // Alignment and Size are measured in bits. 60 const uint64_t Size = Context.getTypeSize(Ty); 61 const uint64_t Alignment = Context.getTypeAlign(Ty); 62 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment); 63 const uint64_t NumElements = (Size + Alignment - 1) / Alignment; 64 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 65 } 66 67 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 68 llvm::Value *Array, 69 llvm::Value *Value, 70 unsigned FirstIndex, 71 unsigned LastIndex) { 72 // Alternatively, we could emit this as a loop in the source. 73 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 74 llvm::Value *Cell = 75 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I); 76 Builder.CreateAlignedStore(Value, Cell, CharUnits::One()); 77 } 78 } 79 80 static bool isAggregateTypeForABI(QualType T) { 81 return !CodeGenFunction::hasScalarEvaluationKind(T) || 82 T->isMemberFunctionPointerType(); 83 } 84 85 ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal, 86 bool Realign, 87 llvm::Type *Padding) const { 88 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal, 89 Realign, Padding); 90 } 91 92 ABIArgInfo 93 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const { 94 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty), 95 /*ByVal*/ false, Realign); 96 } 97 98 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 99 QualType Ty) const { 100 return Address::invalid(); 101 } 102 103 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 104 if (Ty->isPromotableIntegerType()) 105 return true; 106 107 if (const auto *EIT = Ty->getAs<ExtIntType>()) 108 if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy)) 109 return true; 110 111 return false; 112 } 113 114 ABIInfo::~ABIInfo() {} 115 116 /// Does the given lowering require more than the given number of 117 /// registers when expanded? 118 /// 119 /// This is intended to be the basis of a reasonable basic implementation 120 /// of should{Pass,Return}IndirectlyForSwift. 121 /// 122 /// For most targets, a limit of four total registers is reasonable; this 123 /// limits the amount of code required in order to move around the value 124 /// in case it wasn't produced immediately prior to the call by the caller 125 /// (or wasn't produced in exactly the right registers) or isn't used 126 /// immediately within the callee. But some targets may need to further 127 /// limit the register count due to an inability to support that many 128 /// return registers. 129 static bool occupiesMoreThan(CodeGenTypes &cgt, 130 ArrayRef<llvm::Type*> scalarTypes, 131 unsigned maxAllRegisters) { 132 unsigned intCount = 0, fpCount = 0; 133 for (llvm::Type *type : scalarTypes) { 134 if (type->isPointerTy()) { 135 intCount++; 136 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) { 137 auto ptrWidth = cgt.getTarget().getPointerWidth(0); 138 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth; 139 } else { 140 assert(type->isVectorTy() || type->isFloatingPointTy()); 141 fpCount++; 142 } 143 } 144 145 return (intCount + fpCount > maxAllRegisters); 146 } 147 148 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 149 llvm::Type *eltTy, 150 unsigned numElts) const { 151 // The default implementation of this assumes that the target guarantees 152 // 128-bit SIMD support but nothing more. 153 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16); 154 } 155 156 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 157 CGCXXABI &CXXABI) { 158 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 159 if (!RD) { 160 if (!RT->getDecl()->canPassInRegisters()) 161 return CGCXXABI::RAA_Indirect; 162 return CGCXXABI::RAA_Default; 163 } 164 return CXXABI.getRecordArgABI(RD); 165 } 166 167 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 168 CGCXXABI &CXXABI) { 169 const RecordType *RT = T->getAs<RecordType>(); 170 if (!RT) 171 return CGCXXABI::RAA_Default; 172 return getRecordArgABI(RT, CXXABI); 173 } 174 175 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, 176 const ABIInfo &Info) { 177 QualType Ty = FI.getReturnType(); 178 179 if (const auto *RT = Ty->getAs<RecordType>()) 180 if (!isa<CXXRecordDecl>(RT->getDecl()) && 181 !RT->getDecl()->canPassInRegisters()) { 182 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty); 183 return true; 184 } 185 186 return CXXABI.classifyReturnType(FI); 187 } 188 189 /// Pass transparent unions as if they were the type of the first element. Sema 190 /// should ensure that all elements of the union have the same "machine type". 191 static QualType useFirstFieldIfTransparentUnion(QualType Ty) { 192 if (const RecordType *UT = Ty->getAsUnionType()) { 193 const RecordDecl *UD = UT->getDecl(); 194 if (UD->hasAttr<TransparentUnionAttr>()) { 195 assert(!UD->field_empty() && "sema created an empty transparent union"); 196 return UD->field_begin()->getType(); 197 } 198 } 199 return Ty; 200 } 201 202 CGCXXABI &ABIInfo::getCXXABI() const { 203 return CGT.getCXXABI(); 204 } 205 206 ASTContext &ABIInfo::getContext() const { 207 return CGT.getContext(); 208 } 209 210 llvm::LLVMContext &ABIInfo::getVMContext() const { 211 return CGT.getLLVMContext(); 212 } 213 214 const llvm::DataLayout &ABIInfo::getDataLayout() const { 215 return CGT.getDataLayout(); 216 } 217 218 const TargetInfo &ABIInfo::getTarget() const { 219 return CGT.getTarget(); 220 } 221 222 const CodeGenOptions &ABIInfo::getCodeGenOpts() const { 223 return CGT.getCodeGenOpts(); 224 } 225 226 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); } 227 228 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 229 return false; 230 } 231 232 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 233 uint64_t Members) const { 234 return false; 235 } 236 237 LLVM_DUMP_METHOD void ABIArgInfo::dump() const { 238 raw_ostream &OS = llvm::errs(); 239 OS << "(ABIArgInfo Kind="; 240 switch (TheKind) { 241 case Direct: 242 OS << "Direct Type="; 243 if (llvm::Type *Ty = getCoerceToType()) 244 Ty->print(OS); 245 else 246 OS << "null"; 247 break; 248 case Extend: 249 OS << "Extend"; 250 break; 251 case Ignore: 252 OS << "Ignore"; 253 break; 254 case InAlloca: 255 OS << "InAlloca Offset=" << getInAllocaFieldIndex(); 256 break; 257 case Indirect: 258 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 259 << " ByVal=" << getIndirectByVal() 260 << " Realign=" << getIndirectRealign(); 261 break; 262 case IndirectAliased: 263 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 264 << " AadrSpace=" << getIndirectAddrSpace() 265 << " Realign=" << getIndirectRealign(); 266 break; 267 case Expand: 268 OS << "Expand"; 269 break; 270 case CoerceAndExpand: 271 OS << "CoerceAndExpand Type="; 272 getCoerceAndExpandType()->print(OS); 273 break; 274 } 275 OS << ")\n"; 276 } 277 278 // Dynamically round a pointer up to a multiple of the given alignment. 279 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF, 280 llvm::Value *Ptr, 281 CharUnits Align) { 282 llvm::Value *PtrAsInt = Ptr; 283 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align; 284 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy); 285 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt, 286 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1)); 287 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt, 288 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity())); 289 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt, 290 Ptr->getType(), 291 Ptr->getName() + ".aligned"); 292 return PtrAsInt; 293 } 294 295 /// Emit va_arg for a platform using the common void* representation, 296 /// where arguments are simply emitted in an array of slots on the stack. 297 /// 298 /// This version implements the core direct-value passing rules. 299 /// 300 /// \param SlotSize - The size and alignment of a stack slot. 301 /// Each argument will be allocated to a multiple of this number of 302 /// slots, and all the slots will be aligned to this value. 303 /// \param AllowHigherAlign - The slot alignment is not a cap; 304 /// an argument type with an alignment greater than the slot size 305 /// will be emitted on a higher-alignment address, potentially 306 /// leaving one or more empty slots behind as padding. If this 307 /// is false, the returned address might be less-aligned than 308 /// DirectAlign. 309 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, 310 Address VAListAddr, 311 llvm::Type *DirectTy, 312 CharUnits DirectSize, 313 CharUnits DirectAlign, 314 CharUnits SlotSize, 315 bool AllowHigherAlign) { 316 // Cast the element type to i8* if necessary. Some platforms define 317 // va_list as a struct containing an i8* instead of just an i8*. 318 if (VAListAddr.getElementType() != CGF.Int8PtrTy) 319 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy); 320 321 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur"); 322 323 // If the CC aligns values higher than the slot size, do so if needed. 324 Address Addr = Address::invalid(); 325 if (AllowHigherAlign && DirectAlign > SlotSize) { 326 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), 327 DirectAlign); 328 } else { 329 Addr = Address(Ptr, SlotSize); 330 } 331 332 // Advance the pointer past the argument, then store that back. 333 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize); 334 Address NextPtr = 335 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next"); 336 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 337 338 // If the argument is smaller than a slot, and this is a big-endian 339 // target, the argument will be right-adjusted in its slot. 340 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() && 341 !DirectTy->isStructTy()) { 342 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize); 343 } 344 345 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy); 346 return Addr; 347 } 348 349 /// Emit va_arg for a platform using the common void* representation, 350 /// where arguments are simply emitted in an array of slots on the stack. 351 /// 352 /// \param IsIndirect - Values of this type are passed indirectly. 353 /// \param ValueInfo - The size and alignment of this type, generally 354 /// computed with getContext().getTypeInfoInChars(ValueTy). 355 /// \param SlotSizeAndAlign - The size and alignment of a stack slot. 356 /// Each argument will be allocated to a multiple of this number of 357 /// slots, and all the slots will be aligned to this value. 358 /// \param AllowHigherAlign - The slot alignment is not a cap; 359 /// an argument type with an alignment greater than the slot size 360 /// will be emitted on a higher-alignment address, potentially 361 /// leaving one or more empty slots behind as padding. 362 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, 363 QualType ValueTy, bool IsIndirect, 364 TypeInfoChars ValueInfo, 365 CharUnits SlotSizeAndAlign, 366 bool AllowHigherAlign) { 367 // The size and alignment of the value that was passed directly. 368 CharUnits DirectSize, DirectAlign; 369 if (IsIndirect) { 370 DirectSize = CGF.getPointerSize(); 371 DirectAlign = CGF.getPointerAlign(); 372 } else { 373 DirectSize = ValueInfo.Width; 374 DirectAlign = ValueInfo.Align; 375 } 376 377 // Cast the address we've calculated to the right type. 378 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy); 379 if (IsIndirect) 380 DirectTy = DirectTy->getPointerTo(0); 381 382 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, 383 DirectSize, DirectAlign, 384 SlotSizeAndAlign, 385 AllowHigherAlign); 386 387 if (IsIndirect) { 388 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align); 389 } 390 391 return Addr; 392 393 } 394 395 static Address emitMergePHI(CodeGenFunction &CGF, 396 Address Addr1, llvm::BasicBlock *Block1, 397 Address Addr2, llvm::BasicBlock *Block2, 398 const llvm::Twine &Name = "") { 399 assert(Addr1.getType() == Addr2.getType()); 400 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); 401 PHI->addIncoming(Addr1.getPointer(), Block1); 402 PHI->addIncoming(Addr2.getPointer(), Block2); 403 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); 404 return Address(PHI, Align); 405 } 406 407 TargetCodeGenInfo::~TargetCodeGenInfo() = default; 408 409 // If someone can figure out a general rule for this, that would be great. 410 // It's probably just doomed to be platform-dependent, though. 411 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 412 // Verified for: 413 // x86-64 FreeBSD, Linux, Darwin 414 // x86-32 FreeBSD, Linux, Darwin 415 // PowerPC Linux, Darwin 416 // ARM Darwin (*not* EABI) 417 // AArch64 Linux 418 return 32; 419 } 420 421 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 422 const FunctionNoProtoType *fnType) const { 423 // The following conventions are known to require this to be false: 424 // x86_stdcall 425 // MIPS 426 // For everything else, we just prefer false unless we opt out. 427 return false; 428 } 429 430 void 431 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 432 llvm::SmallString<24> &Opt) const { 433 // This assumes the user is passing a library name like "rt" instead of a 434 // filename like "librt.a/so", and that they don't care whether it's static or 435 // dynamic. 436 Opt = "-l"; 437 Opt += Lib; 438 } 439 440 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { 441 // OpenCL kernels are called via an explicit runtime API with arguments 442 // set with clSetKernelArg(), not as normal sub-functions. 443 // Return SPIR_KERNEL by default as the kernel calling convention to 444 // ensure the fingerprint is fixed such way that each OpenCL argument 445 // gets one matching argument in the produced kernel function argument 446 // list to enable feasible implementation of clSetKernelArg() with 447 // aggregates etc. In case we would use the default C calling conv here, 448 // clSetKernelArg() might break depending on the target-specific 449 // conventions; different targets might split structs passed as values 450 // to multiple function arguments etc. 451 return llvm::CallingConv::SPIR_KERNEL; 452 } 453 454 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, 455 llvm::PointerType *T, QualType QT) const { 456 return llvm::ConstantPointerNull::get(T); 457 } 458 459 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 460 const VarDecl *D) const { 461 assert(!CGM.getLangOpts().OpenCL && 462 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 463 "Address space agnostic languages only"); 464 return D ? D->getType().getAddressSpace() : LangAS::Default; 465 } 466 467 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( 468 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, 469 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { 470 // Since target may map different address spaces in AST to the same address 471 // space, an address space conversion may end up as a bitcast. 472 if (auto *C = dyn_cast<llvm::Constant>(Src)) 473 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); 474 // Try to preserve the source's name to make IR more readable. 475 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 476 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : ""); 477 } 478 479 llvm::Constant * 480 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, 481 LangAS SrcAddr, LangAS DestAddr, 482 llvm::Type *DestTy) const { 483 // Since target may map different address spaces in AST to the same address 484 // space, an address space conversion may end up as a bitcast. 485 return llvm::ConstantExpr::getPointerCast(Src, DestTy); 486 } 487 488 llvm::SyncScope::ID 489 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 490 SyncScope Scope, 491 llvm::AtomicOrdering Ordering, 492 llvm::LLVMContext &Ctx) const { 493 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ 494 } 495 496 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 497 498 /// isEmptyField - Return true iff a the field is "empty", that is it 499 /// is an unnamed bit-field or an (array of) empty record(s). 500 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 501 bool AllowArrays) { 502 if (FD->isUnnamedBitfield()) 503 return true; 504 505 QualType FT = FD->getType(); 506 507 // Constant arrays of empty records count as empty, strip them off. 508 // Constant arrays of zero length always count as empty. 509 bool WasArray = false; 510 if (AllowArrays) 511 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 512 if (AT->getSize() == 0) 513 return true; 514 FT = AT->getElementType(); 515 // The [[no_unique_address]] special case below does not apply to 516 // arrays of C++ empty records, so we need to remember this fact. 517 WasArray = true; 518 } 519 520 const RecordType *RT = FT->getAs<RecordType>(); 521 if (!RT) 522 return false; 523 524 // C++ record fields are never empty, at least in the Itanium ABI. 525 // 526 // FIXME: We should use a predicate for whether this behavior is true in the 527 // current ABI. 528 // 529 // The exception to the above rule are fields marked with the 530 // [[no_unique_address]] attribute (since C++20). Those do count as empty 531 // according to the Itanium ABI. The exception applies only to records, 532 // not arrays of records, so we must also check whether we stripped off an 533 // array type above. 534 if (isa<CXXRecordDecl>(RT->getDecl()) && 535 (WasArray || !FD->hasAttr<NoUniqueAddressAttr>())) 536 return false; 537 538 return isEmptyRecord(Context, FT, AllowArrays); 539 } 540 541 /// isEmptyRecord - Return true iff a structure contains only empty 542 /// fields. Note that a structure with a flexible array member is not 543 /// considered empty. 544 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 545 const RecordType *RT = T->getAs<RecordType>(); 546 if (!RT) 547 return false; 548 const RecordDecl *RD = RT->getDecl(); 549 if (RD->hasFlexibleArrayMember()) 550 return false; 551 552 // If this is a C++ record, check the bases first. 553 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 554 for (const auto &I : CXXRD->bases()) 555 if (!isEmptyRecord(Context, I.getType(), true)) 556 return false; 557 558 for (const auto *I : RD->fields()) 559 if (!isEmptyField(Context, I, AllowArrays)) 560 return false; 561 return true; 562 } 563 564 /// isSingleElementStruct - Determine if a structure is a "single 565 /// element struct", i.e. it has exactly one non-empty field or 566 /// exactly one field which is itself a single element 567 /// struct. Structures with flexible array members are never 568 /// considered single element structs. 569 /// 570 /// \return The field declaration for the single non-empty field, if 571 /// it exists. 572 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 573 const RecordType *RT = T->getAs<RecordType>(); 574 if (!RT) 575 return nullptr; 576 577 const RecordDecl *RD = RT->getDecl(); 578 if (RD->hasFlexibleArrayMember()) 579 return nullptr; 580 581 const Type *Found = nullptr; 582 583 // If this is a C++ record, check the bases first. 584 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 585 for (const auto &I : CXXRD->bases()) { 586 // Ignore empty records. 587 if (isEmptyRecord(Context, I.getType(), true)) 588 continue; 589 590 // If we already found an element then this isn't a single-element struct. 591 if (Found) 592 return nullptr; 593 594 // If this is non-empty and not a single element struct, the composite 595 // cannot be a single element struct. 596 Found = isSingleElementStruct(I.getType(), Context); 597 if (!Found) 598 return nullptr; 599 } 600 } 601 602 // Check for single element. 603 for (const auto *FD : RD->fields()) { 604 QualType FT = FD->getType(); 605 606 // Ignore empty fields. 607 if (isEmptyField(Context, FD, true)) 608 continue; 609 610 // If we already found an element then this isn't a single-element 611 // struct. 612 if (Found) 613 return nullptr; 614 615 // Treat single element arrays as the element. 616 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 617 if (AT->getSize().getZExtValue() != 1) 618 break; 619 FT = AT->getElementType(); 620 } 621 622 if (!isAggregateTypeForABI(FT)) { 623 Found = FT.getTypePtr(); 624 } else { 625 Found = isSingleElementStruct(FT, Context); 626 if (!Found) 627 return nullptr; 628 } 629 } 630 631 // We don't consider a struct a single-element struct if it has 632 // padding beyond the element type. 633 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 634 return nullptr; 635 636 return Found; 637 } 638 639 namespace { 640 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, 641 const ABIArgInfo &AI) { 642 // This default implementation defers to the llvm backend's va_arg 643 // instruction. It can handle only passing arguments directly 644 // (typically only handled in the backend for primitive types), or 645 // aggregates passed indirectly by pointer (NOTE: if the "byval" 646 // flag has ABI impact in the callee, this implementation cannot 647 // work.) 648 649 // Only a few cases are covered here at the moment -- those needed 650 // by the default abi. 651 llvm::Value *Val; 652 653 if (AI.isIndirect()) { 654 assert(!AI.getPaddingType() && 655 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 656 assert( 657 !AI.getIndirectRealign() && 658 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); 659 660 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); 661 CharUnits TyAlignForABI = TyInfo.Align; 662 663 llvm::Type *BaseTy = 664 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 665 llvm::Value *Addr = 666 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); 667 return Address(Addr, TyAlignForABI); 668 } else { 669 assert((AI.isDirect() || AI.isExtend()) && 670 "Unexpected ArgInfo Kind in generic VAArg emitter!"); 671 672 assert(!AI.getInReg() && 673 "Unexpected InReg seen in arginfo in generic VAArg emitter!"); 674 assert(!AI.getPaddingType() && 675 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 676 assert(!AI.getDirectOffset() && 677 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); 678 assert(!AI.getCoerceToType() && 679 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); 680 681 Address Temp = CGF.CreateMemTemp(Ty, "varet"); 682 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); 683 CGF.Builder.CreateStore(Val, Temp); 684 return Temp; 685 } 686 } 687 688 /// DefaultABIInfo - The default implementation for ABI specific 689 /// details. This implementation provides information which results in 690 /// self-consistent and sensible LLVM IR generation, but does not 691 /// conform to any particular ABI. 692 class DefaultABIInfo : public ABIInfo { 693 public: 694 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 695 696 ABIArgInfo classifyReturnType(QualType RetTy) const; 697 ABIArgInfo classifyArgumentType(QualType RetTy) const; 698 699 void computeInfo(CGFunctionInfo &FI) const override { 700 if (!getCXXABI().classifyReturnType(FI)) 701 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 702 for (auto &I : FI.arguments()) 703 I.info = classifyArgumentType(I.type); 704 } 705 706 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 707 QualType Ty) const override { 708 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 709 } 710 }; 711 712 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 713 public: 714 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 715 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 716 }; 717 718 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 719 Ty = useFirstFieldIfTransparentUnion(Ty); 720 721 if (isAggregateTypeForABI(Ty)) { 722 // Records with non-trivial destructors/copy-constructors should not be 723 // passed by value. 724 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 725 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 726 727 return getNaturalAlignIndirect(Ty); 728 } 729 730 // Treat an enum type as its underlying type. 731 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 732 Ty = EnumTy->getDecl()->getIntegerType(); 733 734 ASTContext &Context = getContext(); 735 if (const auto *EIT = Ty->getAs<ExtIntType>()) 736 if (EIT->getNumBits() > 737 Context.getTypeSize(Context.getTargetInfo().hasInt128Type() 738 ? Context.Int128Ty 739 : Context.LongLongTy)) 740 return getNaturalAlignIndirect(Ty); 741 742 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 743 : ABIArgInfo::getDirect()); 744 } 745 746 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 747 if (RetTy->isVoidType()) 748 return ABIArgInfo::getIgnore(); 749 750 if (isAggregateTypeForABI(RetTy)) 751 return getNaturalAlignIndirect(RetTy); 752 753 // Treat an enum type as its underlying type. 754 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 755 RetTy = EnumTy->getDecl()->getIntegerType(); 756 757 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 758 if (EIT->getNumBits() > 759 getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type() 760 ? getContext().Int128Ty 761 : getContext().LongLongTy)) 762 return getNaturalAlignIndirect(RetTy); 763 764 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 765 : ABIArgInfo::getDirect()); 766 } 767 768 //===----------------------------------------------------------------------===// 769 // WebAssembly ABI Implementation 770 // 771 // This is a very simple ABI that relies a lot on DefaultABIInfo. 772 //===----------------------------------------------------------------------===// 773 774 class WebAssemblyABIInfo final : public SwiftABIInfo { 775 public: 776 enum ABIKind { 777 MVP = 0, 778 ExperimentalMV = 1, 779 }; 780 781 private: 782 DefaultABIInfo defaultInfo; 783 ABIKind Kind; 784 785 public: 786 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind) 787 : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {} 788 789 private: 790 ABIArgInfo classifyReturnType(QualType RetTy) const; 791 ABIArgInfo classifyArgumentType(QualType Ty) const; 792 793 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 794 // non-virtual, but computeInfo and EmitVAArg are virtual, so we 795 // overload them. 796 void computeInfo(CGFunctionInfo &FI) const override { 797 if (!getCXXABI().classifyReturnType(FI)) 798 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 799 for (auto &Arg : FI.arguments()) 800 Arg.info = classifyArgumentType(Arg.type); 801 } 802 803 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 804 QualType Ty) const override; 805 806 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 807 bool asReturnValue) const override { 808 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 809 } 810 811 bool isSwiftErrorInRegister() const override { 812 return false; 813 } 814 }; 815 816 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { 817 public: 818 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 819 WebAssemblyABIInfo::ABIKind K) 820 : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {} 821 822 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 823 CodeGen::CodeGenModule &CGM) const override { 824 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 825 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 826 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 827 llvm::Function *Fn = cast<llvm::Function>(GV); 828 llvm::AttrBuilder B; 829 B.addAttribute("wasm-import-module", Attr->getImportModule()); 830 Fn->addFnAttrs(B); 831 } 832 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { 833 llvm::Function *Fn = cast<llvm::Function>(GV); 834 llvm::AttrBuilder B; 835 B.addAttribute("wasm-import-name", Attr->getImportName()); 836 Fn->addFnAttrs(B); 837 } 838 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) { 839 llvm::Function *Fn = cast<llvm::Function>(GV); 840 llvm::AttrBuilder B; 841 B.addAttribute("wasm-export-name", Attr->getExportName()); 842 Fn->addFnAttrs(B); 843 } 844 } 845 846 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 847 llvm::Function *Fn = cast<llvm::Function>(GV); 848 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) 849 Fn->addFnAttr("no-prototype"); 850 } 851 } 852 }; 853 854 /// Classify argument of given type \p Ty. 855 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { 856 Ty = useFirstFieldIfTransparentUnion(Ty); 857 858 if (isAggregateTypeForABI(Ty)) { 859 // Records with non-trivial destructors/copy-constructors should not be 860 // passed by value. 861 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 862 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 863 // Ignore empty structs/unions. 864 if (isEmptyRecord(getContext(), Ty, true)) 865 return ABIArgInfo::getIgnore(); 866 // Lower single-element structs to just pass a regular value. TODO: We 867 // could do reasonable-size multiple-element structs too, using getExpand(), 868 // though watch out for things like bitfields. 869 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 870 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 871 // For the experimental multivalue ABI, fully expand all other aggregates 872 if (Kind == ABIKind::ExperimentalMV) { 873 const RecordType *RT = Ty->getAs<RecordType>(); 874 assert(RT); 875 bool HasBitField = false; 876 for (auto *Field : RT->getDecl()->fields()) { 877 if (Field->isBitField()) { 878 HasBitField = true; 879 break; 880 } 881 } 882 if (!HasBitField) 883 return ABIArgInfo::getExpand(); 884 } 885 } 886 887 // Otherwise just do the default thing. 888 return defaultInfo.classifyArgumentType(Ty); 889 } 890 891 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { 892 if (isAggregateTypeForABI(RetTy)) { 893 // Records with non-trivial destructors/copy-constructors should not be 894 // returned by value. 895 if (!getRecordArgABI(RetTy, getCXXABI())) { 896 // Ignore empty structs/unions. 897 if (isEmptyRecord(getContext(), RetTy, true)) 898 return ABIArgInfo::getIgnore(); 899 // Lower single-element structs to just return a regular value. TODO: We 900 // could do reasonable-size multiple-element structs too, using 901 // ABIArgInfo::getDirect(). 902 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 903 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 904 // For the experimental multivalue ABI, return all other aggregates 905 if (Kind == ABIKind::ExperimentalMV) 906 return ABIArgInfo::getDirect(); 907 } 908 } 909 910 // Otherwise just do the default thing. 911 return defaultInfo.classifyReturnType(RetTy); 912 } 913 914 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 915 QualType Ty) const { 916 bool IsIndirect = isAggregateTypeForABI(Ty) && 917 !isEmptyRecord(getContext(), Ty, true) && 918 !isSingleElementStruct(Ty, getContext()); 919 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 920 getContext().getTypeInfoInChars(Ty), 921 CharUnits::fromQuantity(4), 922 /*AllowHigherAlign=*/true); 923 } 924 925 //===----------------------------------------------------------------------===// 926 // le32/PNaCl bitcode ABI Implementation 927 // 928 // This is a simplified version of the x86_32 ABI. Arguments and return values 929 // are always passed on the stack. 930 //===----------------------------------------------------------------------===// 931 932 class PNaClABIInfo : public ABIInfo { 933 public: 934 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 935 936 ABIArgInfo classifyReturnType(QualType RetTy) const; 937 ABIArgInfo classifyArgumentType(QualType RetTy) const; 938 939 void computeInfo(CGFunctionInfo &FI) const override; 940 Address EmitVAArg(CodeGenFunction &CGF, 941 Address VAListAddr, QualType Ty) const override; 942 }; 943 944 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 945 public: 946 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 947 : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {} 948 }; 949 950 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 951 if (!getCXXABI().classifyReturnType(FI)) 952 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 953 954 for (auto &I : FI.arguments()) 955 I.info = classifyArgumentType(I.type); 956 } 957 958 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 959 QualType Ty) const { 960 // The PNaCL ABI is a bit odd, in that varargs don't use normal 961 // function classification. Structs get passed directly for varargs 962 // functions, through a rewriting transform in 963 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows 964 // this target to actually support a va_arg instructions with an 965 // aggregate type, unlike other targets. 966 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 967 } 968 969 /// Classify argument of given type \p Ty. 970 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 971 if (isAggregateTypeForABI(Ty)) { 972 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 973 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 974 return getNaturalAlignIndirect(Ty); 975 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 976 // Treat an enum type as its underlying type. 977 Ty = EnumTy->getDecl()->getIntegerType(); 978 } else if (Ty->isFloatingType()) { 979 // Floating-point types don't go inreg. 980 return ABIArgInfo::getDirect(); 981 } else if (const auto *EIT = Ty->getAs<ExtIntType>()) { 982 // Treat extended integers as integers if <=64, otherwise pass indirectly. 983 if (EIT->getNumBits() > 64) 984 return getNaturalAlignIndirect(Ty); 985 return ABIArgInfo::getDirect(); 986 } 987 988 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 989 : ABIArgInfo::getDirect()); 990 } 991 992 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 993 if (RetTy->isVoidType()) 994 return ABIArgInfo::getIgnore(); 995 996 // In the PNaCl ABI we always return records/structures on the stack. 997 if (isAggregateTypeForABI(RetTy)) 998 return getNaturalAlignIndirect(RetTy); 999 1000 // Treat extended integers as integers if <=64, otherwise pass indirectly. 1001 if (const auto *EIT = RetTy->getAs<ExtIntType>()) { 1002 if (EIT->getNumBits() > 64) 1003 return getNaturalAlignIndirect(RetTy); 1004 return ABIArgInfo::getDirect(); 1005 } 1006 1007 // Treat an enum type as its underlying type. 1008 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1009 RetTy = EnumTy->getDecl()->getIntegerType(); 1010 1011 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1012 : ABIArgInfo::getDirect()); 1013 } 1014 1015 /// IsX86_MMXType - Return true if this is an MMX type. 1016 bool IsX86_MMXType(llvm::Type *IRType) { 1017 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 1018 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 1019 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 1020 IRType->getScalarSizeInBits() != 64; 1021 } 1022 1023 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1024 StringRef Constraint, 1025 llvm::Type* Ty) { 1026 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) 1027 .Cases("y", "&y", "^Ym", true) 1028 .Default(false); 1029 if (IsMMXCons && Ty->isVectorTy()) { 1030 if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() != 1031 64) { 1032 // Invalid MMX constraint 1033 return nullptr; 1034 } 1035 1036 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 1037 } 1038 1039 // No operation needed 1040 return Ty; 1041 } 1042 1043 /// Returns true if this type can be passed in SSE registers with the 1044 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1045 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 1046 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1047 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 1048 if (BT->getKind() == BuiltinType::LongDouble) { 1049 if (&Context.getTargetInfo().getLongDoubleFormat() == 1050 &llvm::APFloat::x87DoubleExtended()) 1051 return false; 1052 } 1053 return true; 1054 } 1055 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 1056 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 1057 // registers specially. 1058 unsigned VecSize = Context.getTypeSize(VT); 1059 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 1060 return true; 1061 } 1062 return false; 1063 } 1064 1065 /// Returns true if this aggregate is small enough to be passed in SSE registers 1066 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1067 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 1068 return NumMembers <= 4; 1069 } 1070 1071 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 1072 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 1073 auto AI = ABIArgInfo::getDirect(T); 1074 AI.setInReg(true); 1075 AI.setCanBeFlattened(false); 1076 return AI; 1077 } 1078 1079 //===----------------------------------------------------------------------===// 1080 // X86-32 ABI Implementation 1081 //===----------------------------------------------------------------------===// 1082 1083 /// Similar to llvm::CCState, but for Clang. 1084 struct CCState { 1085 CCState(CGFunctionInfo &FI) 1086 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} 1087 1088 llvm::SmallBitVector IsPreassigned; 1089 unsigned CC = CallingConv::CC_C; 1090 unsigned FreeRegs = 0; 1091 unsigned FreeSSERegs = 0; 1092 }; 1093 1094 /// X86_32ABIInfo - The X86-32 ABI information. 1095 class X86_32ABIInfo : public SwiftABIInfo { 1096 enum Class { 1097 Integer, 1098 Float 1099 }; 1100 1101 static const unsigned MinABIStackAlignInBytes = 4; 1102 1103 bool IsDarwinVectorABI; 1104 bool IsRetSmallStructInRegABI; 1105 bool IsWin32StructABI; 1106 bool IsSoftFloatABI; 1107 bool IsMCUABI; 1108 bool IsLinuxABI; 1109 unsigned DefaultNumRegisterParameters; 1110 1111 static bool isRegisterSize(unsigned Size) { 1112 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1113 } 1114 1115 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1116 // FIXME: Assumes vectorcall is in use. 1117 return isX86VectorTypeForVectorCall(getContext(), Ty); 1118 } 1119 1120 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1121 uint64_t NumMembers) const override { 1122 // FIXME: Assumes vectorcall is in use. 1123 return isX86VectorCallAggregateSmallEnough(NumMembers); 1124 } 1125 1126 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1127 1128 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1129 /// such that the argument will be passed in memory. 1130 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1131 1132 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1133 1134 /// Return the alignment to use for the given type on the stack. 1135 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1136 1137 Class classify(QualType Ty) const; 1138 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1139 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1140 1141 /// Updates the number of available free registers, returns 1142 /// true if any registers were allocated. 1143 bool updateFreeRegs(QualType Ty, CCState &State) const; 1144 1145 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1146 bool &NeedsPadding) const; 1147 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1148 1149 bool canExpandIndirectArgument(QualType Ty) const; 1150 1151 /// Rewrite the function info so that all memory arguments use 1152 /// inalloca. 1153 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1154 1155 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1156 CharUnits &StackOffset, ABIArgInfo &Info, 1157 QualType Type) const; 1158 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; 1159 1160 public: 1161 1162 void computeInfo(CGFunctionInfo &FI) const override; 1163 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1164 QualType Ty) const override; 1165 1166 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1167 bool RetSmallStructInRegABI, bool Win32StructABI, 1168 unsigned NumRegisterParameters, bool SoftFloatABI) 1169 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1170 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1171 IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI), 1172 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1173 IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() || 1174 CGT.getTarget().getTriple().isOSCygMing()), 1175 DefaultNumRegisterParameters(NumRegisterParameters) {} 1176 1177 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1178 bool asReturnValue) const override { 1179 // LLVM's x86-32 lowering currently only assigns up to three 1180 // integer registers and three fp registers. Oddly, it'll use up to 1181 // four vector registers for vectors, but those can overlap with the 1182 // scalar registers. 1183 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1184 } 1185 1186 bool isSwiftErrorInRegister() const override { 1187 // x86-32 lowering does not support passing swifterror in a register. 1188 return false; 1189 } 1190 }; 1191 1192 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1193 public: 1194 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1195 bool RetSmallStructInRegABI, bool Win32StructABI, 1196 unsigned NumRegisterParameters, bool SoftFloatABI) 1197 : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>( 1198 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1199 NumRegisterParameters, SoftFloatABI)) {} 1200 1201 static bool isStructReturnInRegABI( 1202 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1203 1204 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1205 CodeGen::CodeGenModule &CGM) const override; 1206 1207 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1208 // Darwin uses different dwarf register numbers for EH. 1209 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1210 return 4; 1211 } 1212 1213 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1214 llvm::Value *Address) const override; 1215 1216 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1217 StringRef Constraint, 1218 llvm::Type* Ty) const override { 1219 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1220 } 1221 1222 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1223 std::string &Constraints, 1224 std::vector<llvm::Type *> &ResultRegTypes, 1225 std::vector<llvm::Type *> &ResultTruncRegTypes, 1226 std::vector<LValue> &ResultRegDests, 1227 std::string &AsmString, 1228 unsigned NumOutputs) const override; 1229 1230 llvm::Constant * 1231 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1232 unsigned Sig = (0xeb << 0) | // jmp rel8 1233 (0x06 << 8) | // .+0x08 1234 ('v' << 16) | 1235 ('2' << 24); 1236 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1237 } 1238 1239 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1240 return "movl\t%ebp, %ebp" 1241 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1242 } 1243 }; 1244 1245 } 1246 1247 /// Rewrite input constraint references after adding some output constraints. 1248 /// In the case where there is one output and one input and we add one output, 1249 /// we need to replace all operand references greater than or equal to 1: 1250 /// mov $0, $1 1251 /// mov eax, $1 1252 /// The result will be: 1253 /// mov $0, $2 1254 /// mov eax, $2 1255 static void rewriteInputConstraintReferences(unsigned FirstIn, 1256 unsigned NumNewOuts, 1257 std::string &AsmString) { 1258 std::string Buf; 1259 llvm::raw_string_ostream OS(Buf); 1260 size_t Pos = 0; 1261 while (Pos < AsmString.size()) { 1262 size_t DollarStart = AsmString.find('$', Pos); 1263 if (DollarStart == std::string::npos) 1264 DollarStart = AsmString.size(); 1265 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1266 if (DollarEnd == std::string::npos) 1267 DollarEnd = AsmString.size(); 1268 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1269 Pos = DollarEnd; 1270 size_t NumDollars = DollarEnd - DollarStart; 1271 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1272 // We have an operand reference. 1273 size_t DigitStart = Pos; 1274 if (AsmString[DigitStart] == '{') { 1275 OS << '{'; 1276 ++DigitStart; 1277 } 1278 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1279 if (DigitEnd == std::string::npos) 1280 DigitEnd = AsmString.size(); 1281 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1282 unsigned OperandIndex; 1283 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1284 if (OperandIndex >= FirstIn) 1285 OperandIndex += NumNewOuts; 1286 OS << OperandIndex; 1287 } else { 1288 OS << OperandStr; 1289 } 1290 Pos = DigitEnd; 1291 } 1292 } 1293 AsmString = std::move(OS.str()); 1294 } 1295 1296 /// Add output constraints for EAX:EDX because they are return registers. 1297 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1298 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1299 std::vector<llvm::Type *> &ResultRegTypes, 1300 std::vector<llvm::Type *> &ResultTruncRegTypes, 1301 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1302 unsigned NumOutputs) const { 1303 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1304 1305 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1306 // larger. 1307 if (!Constraints.empty()) 1308 Constraints += ','; 1309 if (RetWidth <= 32) { 1310 Constraints += "={eax}"; 1311 ResultRegTypes.push_back(CGF.Int32Ty); 1312 } else { 1313 // Use the 'A' constraint for EAX:EDX. 1314 Constraints += "=A"; 1315 ResultRegTypes.push_back(CGF.Int64Ty); 1316 } 1317 1318 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1319 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1320 ResultTruncRegTypes.push_back(CoerceTy); 1321 1322 // Coerce the integer by bitcasting the return slot pointer. 1323 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF), 1324 CoerceTy->getPointerTo())); 1325 ResultRegDests.push_back(ReturnSlot); 1326 1327 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1328 } 1329 1330 /// shouldReturnTypeInRegister - Determine if the given type should be 1331 /// returned in a register (for the Darwin and MCU ABI). 1332 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1333 ASTContext &Context) const { 1334 uint64_t Size = Context.getTypeSize(Ty); 1335 1336 // For i386, type must be register sized. 1337 // For the MCU ABI, it only needs to be <= 8-byte 1338 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1339 return false; 1340 1341 if (Ty->isVectorType()) { 1342 // 64- and 128- bit vectors inside structures are not returned in 1343 // registers. 1344 if (Size == 64 || Size == 128) 1345 return false; 1346 1347 return true; 1348 } 1349 1350 // If this is a builtin, pointer, enum, complex type, member pointer, or 1351 // member function pointer it is ok. 1352 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1353 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1354 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1355 return true; 1356 1357 // Arrays are treated like records. 1358 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1359 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1360 1361 // Otherwise, it must be a record type. 1362 const RecordType *RT = Ty->getAs<RecordType>(); 1363 if (!RT) return false; 1364 1365 // FIXME: Traverse bases here too. 1366 1367 // Structure types are passed in register if all fields would be 1368 // passed in a register. 1369 for (const auto *FD : RT->getDecl()->fields()) { 1370 // Empty fields are ignored. 1371 if (isEmptyField(Context, FD, true)) 1372 continue; 1373 1374 // Check fields recursively. 1375 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1376 return false; 1377 } 1378 return true; 1379 } 1380 1381 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1382 // Treat complex types as the element type. 1383 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1384 Ty = CTy->getElementType(); 1385 1386 // Check for a type which we know has a simple scalar argument-passing 1387 // convention without any padding. (We're specifically looking for 32 1388 // and 64-bit integer and integer-equivalents, float, and double.) 1389 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1390 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1391 return false; 1392 1393 uint64_t Size = Context.getTypeSize(Ty); 1394 return Size == 32 || Size == 64; 1395 } 1396 1397 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1398 uint64_t &Size) { 1399 for (const auto *FD : RD->fields()) { 1400 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1401 // argument is smaller than 32-bits, expanding the struct will create 1402 // alignment padding. 1403 if (!is32Or64BitBasicType(FD->getType(), Context)) 1404 return false; 1405 1406 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1407 // how to expand them yet, and the predicate for telling if a bitfield still 1408 // counts as "basic" is more complicated than what we were doing previously. 1409 if (FD->isBitField()) 1410 return false; 1411 1412 Size += Context.getTypeSize(FD->getType()); 1413 } 1414 return true; 1415 } 1416 1417 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1418 uint64_t &Size) { 1419 // Don't do this if there are any non-empty bases. 1420 for (const CXXBaseSpecifier &Base : RD->bases()) { 1421 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1422 Size)) 1423 return false; 1424 } 1425 if (!addFieldSizes(Context, RD, Size)) 1426 return false; 1427 return true; 1428 } 1429 1430 /// Test whether an argument type which is to be passed indirectly (on the 1431 /// stack) would have the equivalent layout if it was expanded into separate 1432 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1433 /// optimizations. 1434 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1435 // We can only expand structure types. 1436 const RecordType *RT = Ty->getAs<RecordType>(); 1437 if (!RT) 1438 return false; 1439 const RecordDecl *RD = RT->getDecl(); 1440 uint64_t Size = 0; 1441 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1442 if (!IsWin32StructABI) { 1443 // On non-Windows, we have to conservatively match our old bitcode 1444 // prototypes in order to be ABI-compatible at the bitcode level. 1445 if (!CXXRD->isCLike()) 1446 return false; 1447 } else { 1448 // Don't do this for dynamic classes. 1449 if (CXXRD->isDynamicClass()) 1450 return false; 1451 } 1452 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1453 return false; 1454 } else { 1455 if (!addFieldSizes(getContext(), RD, Size)) 1456 return false; 1457 } 1458 1459 // We can do this if there was no alignment padding. 1460 return Size == getContext().getTypeSize(Ty); 1461 } 1462 1463 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1464 // If the return value is indirect, then the hidden argument is consuming one 1465 // integer register. 1466 if (State.FreeRegs) { 1467 --State.FreeRegs; 1468 if (!IsMCUABI) 1469 return getNaturalAlignIndirectInReg(RetTy); 1470 } 1471 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1472 } 1473 1474 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1475 CCState &State) const { 1476 if (RetTy->isVoidType()) 1477 return ABIArgInfo::getIgnore(); 1478 1479 const Type *Base = nullptr; 1480 uint64_t NumElts = 0; 1481 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1482 State.CC == llvm::CallingConv::X86_RegCall) && 1483 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1484 // The LLVM struct type for such an aggregate should lower properly. 1485 return ABIArgInfo::getDirect(); 1486 } 1487 1488 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1489 // On Darwin, some vectors are returned in registers. 1490 if (IsDarwinVectorABI) { 1491 uint64_t Size = getContext().getTypeSize(RetTy); 1492 1493 // 128-bit vectors are a special case; they are returned in 1494 // registers and we need to make sure to pick a type the LLVM 1495 // backend will like. 1496 if (Size == 128) 1497 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1498 llvm::Type::getInt64Ty(getVMContext()), 2)); 1499 1500 // Always return in register if it fits in a general purpose 1501 // register, or if it is 64 bits and has a single element. 1502 if ((Size == 8 || Size == 16 || Size == 32) || 1503 (Size == 64 && VT->getNumElements() == 1)) 1504 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1505 Size)); 1506 1507 return getIndirectReturnResult(RetTy, State); 1508 } 1509 1510 return ABIArgInfo::getDirect(); 1511 } 1512 1513 if (isAggregateTypeForABI(RetTy)) { 1514 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1515 // Structures with flexible arrays are always indirect. 1516 if (RT->getDecl()->hasFlexibleArrayMember()) 1517 return getIndirectReturnResult(RetTy, State); 1518 } 1519 1520 // If specified, structs and unions are always indirect. 1521 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1522 return getIndirectReturnResult(RetTy, State); 1523 1524 // Ignore empty structs/unions. 1525 if (isEmptyRecord(getContext(), RetTy, true)) 1526 return ABIArgInfo::getIgnore(); 1527 1528 // Return complex of _Float16 as <2 x half> so the backend will use xmm0. 1529 if (const ComplexType *CT = RetTy->getAs<ComplexType>()) { 1530 QualType ET = getContext().getCanonicalType(CT->getElementType()); 1531 if (ET->isFloat16Type()) 1532 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1533 llvm::Type::getHalfTy(getVMContext()), 2)); 1534 } 1535 1536 // Small structures which are register sized are generally returned 1537 // in a register. 1538 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1539 uint64_t Size = getContext().getTypeSize(RetTy); 1540 1541 // As a special-case, if the struct is a "single-element" struct, and 1542 // the field is of type "float" or "double", return it in a 1543 // floating-point register. (MSVC does not apply this special case.) 1544 // We apply a similar transformation for pointer types to improve the 1545 // quality of the generated IR. 1546 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1547 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1548 || SeltTy->hasPointerRepresentation()) 1549 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1550 1551 // FIXME: We should be able to narrow this integer in cases with dead 1552 // padding. 1553 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1554 } 1555 1556 return getIndirectReturnResult(RetTy, State); 1557 } 1558 1559 // Treat an enum type as its underlying type. 1560 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1561 RetTy = EnumTy->getDecl()->getIntegerType(); 1562 1563 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 1564 if (EIT->getNumBits() > 64) 1565 return getIndirectReturnResult(RetTy, State); 1566 1567 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1568 : ABIArgInfo::getDirect()); 1569 } 1570 1571 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) { 1572 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1573 } 1574 1575 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) { 1576 const RecordType *RT = Ty->getAs<RecordType>(); 1577 if (!RT) 1578 return 0; 1579 const RecordDecl *RD = RT->getDecl(); 1580 1581 // If this is a C++ record, check the bases first. 1582 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1583 for (const auto &I : CXXRD->bases()) 1584 if (!isRecordWithSIMDVectorType(Context, I.getType())) 1585 return false; 1586 1587 for (const auto *i : RD->fields()) { 1588 QualType FT = i->getType(); 1589 1590 if (isSIMDVectorType(Context, FT)) 1591 return true; 1592 1593 if (isRecordWithSIMDVectorType(Context, FT)) 1594 return true; 1595 } 1596 1597 return false; 1598 } 1599 1600 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1601 unsigned Align) const { 1602 // Otherwise, if the alignment is less than or equal to the minimum ABI 1603 // alignment, just use the default; the backend will handle this. 1604 if (Align <= MinABIStackAlignInBytes) 1605 return 0; // Use default alignment. 1606 1607 if (IsLinuxABI) { 1608 // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't 1609 // want to spend any effort dealing with the ramifications of ABI breaks. 1610 // 1611 // If the vector type is __m128/__m256/__m512, return the default alignment. 1612 if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64)) 1613 return Align; 1614 } 1615 // On non-Darwin, the stack type alignment is always 4. 1616 if (!IsDarwinVectorABI) { 1617 // Set explicit alignment, since we may need to realign the top. 1618 return MinABIStackAlignInBytes; 1619 } 1620 1621 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1622 if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) || 1623 isRecordWithSIMDVectorType(getContext(), Ty))) 1624 return 16; 1625 1626 return MinABIStackAlignInBytes; 1627 } 1628 1629 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1630 CCState &State) const { 1631 if (!ByVal) { 1632 if (State.FreeRegs) { 1633 --State.FreeRegs; // Non-byval indirects just use one pointer. 1634 if (!IsMCUABI) 1635 return getNaturalAlignIndirectInReg(Ty); 1636 } 1637 return getNaturalAlignIndirect(Ty, false); 1638 } 1639 1640 // Compute the byval alignment. 1641 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1642 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1643 if (StackAlign == 0) 1644 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1645 1646 // If the stack alignment is less than the type alignment, realign the 1647 // argument. 1648 bool Realign = TypeAlign > StackAlign; 1649 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1650 /*ByVal=*/true, Realign); 1651 } 1652 1653 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1654 const Type *T = isSingleElementStruct(Ty, getContext()); 1655 if (!T) 1656 T = Ty.getTypePtr(); 1657 1658 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1659 BuiltinType::Kind K = BT->getKind(); 1660 if (K == BuiltinType::Float || K == BuiltinType::Double) 1661 return Float; 1662 } 1663 return Integer; 1664 } 1665 1666 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1667 if (!IsSoftFloatABI) { 1668 Class C = classify(Ty); 1669 if (C == Float) 1670 return false; 1671 } 1672 1673 unsigned Size = getContext().getTypeSize(Ty); 1674 unsigned SizeInRegs = (Size + 31) / 32; 1675 1676 if (SizeInRegs == 0) 1677 return false; 1678 1679 if (!IsMCUABI) { 1680 if (SizeInRegs > State.FreeRegs) { 1681 State.FreeRegs = 0; 1682 return false; 1683 } 1684 } else { 1685 // The MCU psABI allows passing parameters in-reg even if there are 1686 // earlier parameters that are passed on the stack. Also, 1687 // it does not allow passing >8-byte structs in-register, 1688 // even if there are 3 free registers available. 1689 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1690 return false; 1691 } 1692 1693 State.FreeRegs -= SizeInRegs; 1694 return true; 1695 } 1696 1697 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1698 bool &InReg, 1699 bool &NeedsPadding) const { 1700 // On Windows, aggregates other than HFAs are never passed in registers, and 1701 // they do not consume register slots. Homogenous floating-point aggregates 1702 // (HFAs) have already been dealt with at this point. 1703 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1704 return false; 1705 1706 NeedsPadding = false; 1707 InReg = !IsMCUABI; 1708 1709 if (!updateFreeRegs(Ty, State)) 1710 return false; 1711 1712 if (IsMCUABI) 1713 return true; 1714 1715 if (State.CC == llvm::CallingConv::X86_FastCall || 1716 State.CC == llvm::CallingConv::X86_VectorCall || 1717 State.CC == llvm::CallingConv::X86_RegCall) { 1718 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1719 NeedsPadding = true; 1720 1721 return false; 1722 } 1723 1724 return true; 1725 } 1726 1727 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1728 if (!updateFreeRegs(Ty, State)) 1729 return false; 1730 1731 if (IsMCUABI) 1732 return false; 1733 1734 if (State.CC == llvm::CallingConv::X86_FastCall || 1735 State.CC == llvm::CallingConv::X86_VectorCall || 1736 State.CC == llvm::CallingConv::X86_RegCall) { 1737 if (getContext().getTypeSize(Ty) > 32) 1738 return false; 1739 1740 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1741 Ty->isReferenceType()); 1742 } 1743 1744 return true; 1745 } 1746 1747 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { 1748 // Vectorcall x86 works subtly different than in x64, so the format is 1749 // a bit different than the x64 version. First, all vector types (not HVAs) 1750 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. 1751 // This differs from the x64 implementation, where the first 6 by INDEX get 1752 // registers. 1753 // In the second pass over the arguments, HVAs are passed in the remaining 1754 // vector registers if possible, or indirectly by address. The address will be 1755 // passed in ECX/EDX if available. Any other arguments are passed according to 1756 // the usual fastcall rules. 1757 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1758 for (int I = 0, E = Args.size(); I < E; ++I) { 1759 const Type *Base = nullptr; 1760 uint64_t NumElts = 0; 1761 const QualType &Ty = Args[I].type; 1762 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1763 isHomogeneousAggregate(Ty, Base, NumElts)) { 1764 if (State.FreeSSERegs >= NumElts) { 1765 State.FreeSSERegs -= NumElts; 1766 Args[I].info = ABIArgInfo::getDirectInReg(); 1767 State.IsPreassigned.set(I); 1768 } 1769 } 1770 } 1771 } 1772 1773 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1774 CCState &State) const { 1775 // FIXME: Set alignment on indirect arguments. 1776 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; 1777 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; 1778 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; 1779 1780 Ty = useFirstFieldIfTransparentUnion(Ty); 1781 TypeInfo TI = getContext().getTypeInfo(Ty); 1782 1783 // Check with the C++ ABI first. 1784 const RecordType *RT = Ty->getAs<RecordType>(); 1785 if (RT) { 1786 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1787 if (RAA == CGCXXABI::RAA_Indirect) { 1788 return getIndirectResult(Ty, false, State); 1789 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1790 // The field index doesn't matter, we'll fix it up later. 1791 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1792 } 1793 } 1794 1795 // Regcall uses the concept of a homogenous vector aggregate, similar 1796 // to other targets. 1797 const Type *Base = nullptr; 1798 uint64_t NumElts = 0; 1799 if ((IsRegCall || IsVectorCall) && 1800 isHomogeneousAggregate(Ty, Base, NumElts)) { 1801 if (State.FreeSSERegs >= NumElts) { 1802 State.FreeSSERegs -= NumElts; 1803 1804 // Vectorcall passes HVAs directly and does not flatten them, but regcall 1805 // does. 1806 if (IsVectorCall) 1807 return getDirectX86Hva(); 1808 1809 if (Ty->isBuiltinType() || Ty->isVectorType()) 1810 return ABIArgInfo::getDirect(); 1811 return ABIArgInfo::getExpand(); 1812 } 1813 return getIndirectResult(Ty, /*ByVal=*/false, State); 1814 } 1815 1816 if (isAggregateTypeForABI(Ty)) { 1817 // Structures with flexible arrays are always indirect. 1818 // FIXME: This should not be byval! 1819 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1820 return getIndirectResult(Ty, true, State); 1821 1822 // Ignore empty structs/unions on non-Windows. 1823 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1824 return ABIArgInfo::getIgnore(); 1825 1826 llvm::LLVMContext &LLVMContext = getVMContext(); 1827 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1828 bool NeedsPadding = false; 1829 bool InReg; 1830 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1831 unsigned SizeInRegs = (TI.Width + 31) / 32; 1832 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1833 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1834 if (InReg) 1835 return ABIArgInfo::getDirectInReg(Result); 1836 else 1837 return ABIArgInfo::getDirect(Result); 1838 } 1839 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1840 1841 // Pass over-aligned aggregates on Windows indirectly. This behavior was 1842 // added in MSVC 2015. 1843 if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32) 1844 return getIndirectResult(Ty, /*ByVal=*/false, State); 1845 1846 // Expand small (<= 128-bit) record types when we know that the stack layout 1847 // of those arguments will match the struct. This is important because the 1848 // LLVM backend isn't smart enough to remove byval, which inhibits many 1849 // optimizations. 1850 // Don't do this for the MCU if there are still free integer registers 1851 // (see X86_64 ABI for full explanation). 1852 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && 1853 canExpandIndirectArgument(Ty)) 1854 return ABIArgInfo::getExpandWithPadding( 1855 IsFastCall || IsVectorCall || IsRegCall, PaddingType); 1856 1857 return getIndirectResult(Ty, true, State); 1858 } 1859 1860 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1861 // On Windows, vectors are passed directly if registers are available, or 1862 // indirectly if not. This avoids the need to align argument memory. Pass 1863 // user-defined vector types larger than 512 bits indirectly for simplicity. 1864 if (IsWin32StructABI) { 1865 if (TI.Width <= 512 && State.FreeSSERegs > 0) { 1866 --State.FreeSSERegs; 1867 return ABIArgInfo::getDirectInReg(); 1868 } 1869 return getIndirectResult(Ty, /*ByVal=*/false, State); 1870 } 1871 1872 // On Darwin, some vectors are passed in memory, we handle this by passing 1873 // it as an i8/i16/i32/i64. 1874 if (IsDarwinVectorABI) { 1875 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) || 1876 (TI.Width == 64 && VT->getNumElements() == 1)) 1877 return ABIArgInfo::getDirect( 1878 llvm::IntegerType::get(getVMContext(), TI.Width)); 1879 } 1880 1881 if (IsX86_MMXType(CGT.ConvertType(Ty))) 1882 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 1883 1884 return ABIArgInfo::getDirect(); 1885 } 1886 1887 1888 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1889 Ty = EnumTy->getDecl()->getIntegerType(); 1890 1891 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1892 1893 if (isPromotableIntegerTypeForABI(Ty)) { 1894 if (InReg) 1895 return ABIArgInfo::getExtendInReg(Ty); 1896 return ABIArgInfo::getExtend(Ty); 1897 } 1898 1899 if (const auto * EIT = Ty->getAs<ExtIntType>()) { 1900 if (EIT->getNumBits() <= 64) { 1901 if (InReg) 1902 return ABIArgInfo::getDirectInReg(); 1903 return ABIArgInfo::getDirect(); 1904 } 1905 return getIndirectResult(Ty, /*ByVal=*/false, State); 1906 } 1907 1908 if (InReg) 1909 return ABIArgInfo::getDirectInReg(); 1910 return ABIArgInfo::getDirect(); 1911 } 1912 1913 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1914 CCState State(FI); 1915 if (IsMCUABI) 1916 State.FreeRegs = 3; 1917 else if (State.CC == llvm::CallingConv::X86_FastCall) { 1918 State.FreeRegs = 2; 1919 State.FreeSSERegs = 3; 1920 } else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1921 State.FreeRegs = 2; 1922 State.FreeSSERegs = 6; 1923 } else if (FI.getHasRegParm()) 1924 State.FreeRegs = FI.getRegParm(); 1925 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1926 State.FreeRegs = 5; 1927 State.FreeSSERegs = 8; 1928 } else if (IsWin32StructABI) { 1929 // Since MSVC 2015, the first three SSE vectors have been passed in 1930 // registers. The rest are passed indirectly. 1931 State.FreeRegs = DefaultNumRegisterParameters; 1932 State.FreeSSERegs = 3; 1933 } else 1934 State.FreeRegs = DefaultNumRegisterParameters; 1935 1936 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1937 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1938 } else if (FI.getReturnInfo().isIndirect()) { 1939 // The C++ ABI is not aware of register usage, so we have to check if the 1940 // return value was sret and put it in a register ourselves if appropriate. 1941 if (State.FreeRegs) { 1942 --State.FreeRegs; // The sret parameter consumes a register. 1943 if (!IsMCUABI) 1944 FI.getReturnInfo().setInReg(true); 1945 } 1946 } 1947 1948 // The chain argument effectively gives us another free register. 1949 if (FI.isChainCall()) 1950 ++State.FreeRegs; 1951 1952 // For vectorcall, do a first pass over the arguments, assigning FP and vector 1953 // arguments to XMM registers as available. 1954 if (State.CC == llvm::CallingConv::X86_VectorCall) 1955 runVectorCallFirstPass(FI, State); 1956 1957 bool UsedInAlloca = false; 1958 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1959 for (int I = 0, E = Args.size(); I < E; ++I) { 1960 // Skip arguments that have already been assigned. 1961 if (State.IsPreassigned.test(I)) 1962 continue; 1963 1964 Args[I].info = classifyArgumentType(Args[I].type, State); 1965 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); 1966 } 1967 1968 // If we needed to use inalloca for any argument, do a second pass and rewrite 1969 // all the memory arguments to use inalloca. 1970 if (UsedInAlloca) 1971 rewriteWithInAlloca(FI); 1972 } 1973 1974 void 1975 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1976 CharUnits &StackOffset, ABIArgInfo &Info, 1977 QualType Type) const { 1978 // Arguments are always 4-byte-aligned. 1979 CharUnits WordSize = CharUnits::fromQuantity(4); 1980 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct"); 1981 1982 // sret pointers and indirect things will require an extra pointer 1983 // indirection, unless they are byval. Most things are byval, and will not 1984 // require this indirection. 1985 bool IsIndirect = false; 1986 if (Info.isIndirect() && !Info.getIndirectByVal()) 1987 IsIndirect = true; 1988 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect); 1989 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type); 1990 if (IsIndirect) 1991 LLTy = LLTy->getPointerTo(0); 1992 FrameFields.push_back(LLTy); 1993 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type); 1994 1995 // Insert padding bytes to respect alignment. 1996 CharUnits FieldEnd = StackOffset; 1997 StackOffset = FieldEnd.alignTo(WordSize); 1998 if (StackOffset != FieldEnd) { 1999 CharUnits NumBytes = StackOffset - FieldEnd; 2000 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 2001 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 2002 FrameFields.push_back(Ty); 2003 } 2004 } 2005 2006 static bool isArgInAlloca(const ABIArgInfo &Info) { 2007 // Leave ignored and inreg arguments alone. 2008 switch (Info.getKind()) { 2009 case ABIArgInfo::InAlloca: 2010 return true; 2011 case ABIArgInfo::Ignore: 2012 case ABIArgInfo::IndirectAliased: 2013 return false; 2014 case ABIArgInfo::Indirect: 2015 case ABIArgInfo::Direct: 2016 case ABIArgInfo::Extend: 2017 return !Info.getInReg(); 2018 case ABIArgInfo::Expand: 2019 case ABIArgInfo::CoerceAndExpand: 2020 // These are aggregate types which are never passed in registers when 2021 // inalloca is involved. 2022 return true; 2023 } 2024 llvm_unreachable("invalid enum"); 2025 } 2026 2027 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 2028 assert(IsWin32StructABI && "inalloca only supported on win32"); 2029 2030 // Build a packed struct type for all of the arguments in memory. 2031 SmallVector<llvm::Type *, 6> FrameFields; 2032 2033 // The stack alignment is always 4. 2034 CharUnits StackAlign = CharUnits::fromQuantity(4); 2035 2036 CharUnits StackOffset; 2037 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 2038 2039 // Put 'this' into the struct before 'sret', if necessary. 2040 bool IsThisCall = 2041 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 2042 ABIArgInfo &Ret = FI.getReturnInfo(); 2043 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 2044 isArgInAlloca(I->info)) { 2045 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2046 ++I; 2047 } 2048 2049 // Put the sret parameter into the inalloca struct if it's in memory. 2050 if (Ret.isIndirect() && !Ret.getInReg()) { 2051 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType()); 2052 // On Windows, the hidden sret parameter is always returned in eax. 2053 Ret.setInAllocaSRet(IsWin32StructABI); 2054 } 2055 2056 // Skip the 'this' parameter in ecx. 2057 if (IsThisCall) 2058 ++I; 2059 2060 // Put arguments passed in memory into the struct. 2061 for (; I != E; ++I) { 2062 if (isArgInAlloca(I->info)) 2063 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2064 } 2065 2066 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 2067 /*isPacked=*/true), 2068 StackAlign); 2069 } 2070 2071 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 2072 Address VAListAddr, QualType Ty) const { 2073 2074 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 2075 2076 // x86-32 changes the alignment of certain arguments on the stack. 2077 // 2078 // Just messing with TypeInfo like this works because we never pass 2079 // anything indirectly. 2080 TypeInfo.Align = CharUnits::fromQuantity( 2081 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity())); 2082 2083 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 2084 TypeInfo, CharUnits::fromQuantity(4), 2085 /*AllowHigherAlign*/ true); 2086 } 2087 2088 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 2089 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 2090 assert(Triple.getArch() == llvm::Triple::x86); 2091 2092 switch (Opts.getStructReturnConvention()) { 2093 case CodeGenOptions::SRCK_Default: 2094 break; 2095 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 2096 return false; 2097 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 2098 return true; 2099 } 2100 2101 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 2102 return true; 2103 2104 switch (Triple.getOS()) { 2105 case llvm::Triple::DragonFly: 2106 case llvm::Triple::FreeBSD: 2107 case llvm::Triple::OpenBSD: 2108 case llvm::Triple::Win32: 2109 return true; 2110 default: 2111 return false; 2112 } 2113 } 2114 2115 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV, 2116 CodeGen::CodeGenModule &CGM) { 2117 if (!FD->hasAttr<AnyX86InterruptAttr>()) 2118 return; 2119 2120 llvm::Function *Fn = cast<llvm::Function>(GV); 2121 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2122 if (FD->getNumParams() == 0) 2123 return; 2124 2125 auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType()); 2126 llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType()); 2127 llvm::Attribute NewAttr = llvm::Attribute::getWithByValType( 2128 Fn->getContext(), ByValTy); 2129 Fn->addParamAttr(0, NewAttr); 2130 } 2131 2132 void X86_32TargetCodeGenInfo::setTargetAttributes( 2133 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2134 if (GV->isDeclaration()) 2135 return; 2136 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2137 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2138 llvm::Function *Fn = cast<llvm::Function>(GV); 2139 Fn->addFnAttr("stackrealign"); 2140 } 2141 2142 addX86InterruptAttrs(FD, GV, CGM); 2143 } 2144 } 2145 2146 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 2147 CodeGen::CodeGenFunction &CGF, 2148 llvm::Value *Address) const { 2149 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2150 2151 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2152 2153 // 0-7 are the eight integer registers; the order is different 2154 // on Darwin (for EH), but the range is the same. 2155 // 8 is %eip. 2156 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2157 2158 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2159 // 12-16 are st(0..4). Not sure why we stop at 4. 2160 // These have size 16, which is sizeof(long double) on 2161 // platforms with 8-byte alignment for that type. 2162 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2163 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2164 2165 } else { 2166 // 9 is %eflags, which doesn't get a size on Darwin for some 2167 // reason. 2168 Builder.CreateAlignedStore( 2169 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2170 CharUnits::One()); 2171 2172 // 11-16 are st(0..5). Not sure why we stop at 5. 2173 // These have size 12, which is sizeof(long double) on 2174 // platforms with 4-byte alignment for that type. 2175 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2176 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2177 } 2178 2179 return false; 2180 } 2181 2182 //===----------------------------------------------------------------------===// 2183 // X86-64 ABI Implementation 2184 //===----------------------------------------------------------------------===// 2185 2186 2187 namespace { 2188 /// The AVX ABI level for X86 targets. 2189 enum class X86AVXABILevel { 2190 None, 2191 AVX, 2192 AVX512 2193 }; 2194 2195 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2196 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2197 switch (AVXLevel) { 2198 case X86AVXABILevel::AVX512: 2199 return 512; 2200 case X86AVXABILevel::AVX: 2201 return 256; 2202 case X86AVXABILevel::None: 2203 return 128; 2204 } 2205 llvm_unreachable("Unknown AVXLevel"); 2206 } 2207 2208 /// X86_64ABIInfo - The X86_64 ABI information. 2209 class X86_64ABIInfo : public SwiftABIInfo { 2210 enum Class { 2211 Integer = 0, 2212 SSE, 2213 SSEUp, 2214 X87, 2215 X87Up, 2216 ComplexX87, 2217 NoClass, 2218 Memory 2219 }; 2220 2221 /// merge - Implement the X86_64 ABI merging algorithm. 2222 /// 2223 /// Merge an accumulating classification \arg Accum with a field 2224 /// classification \arg Field. 2225 /// 2226 /// \param Accum - The accumulating classification. This should 2227 /// always be either NoClass or the result of a previous merge 2228 /// call. In addition, this should never be Memory (the caller 2229 /// should just return Memory for the aggregate). 2230 static Class merge(Class Accum, Class Field); 2231 2232 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2233 /// 2234 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2235 /// final MEMORY or SSE classes when necessary. 2236 /// 2237 /// \param AggregateSize - The size of the current aggregate in 2238 /// the classification process. 2239 /// 2240 /// \param Lo - The classification for the parts of the type 2241 /// residing in the low word of the containing object. 2242 /// 2243 /// \param Hi - The classification for the parts of the type 2244 /// residing in the higher words of the containing object. 2245 /// 2246 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2247 2248 /// classify - Determine the x86_64 register classes in which the 2249 /// given type T should be passed. 2250 /// 2251 /// \param Lo - The classification for the parts of the type 2252 /// residing in the low word of the containing object. 2253 /// 2254 /// \param Hi - The classification for the parts of the type 2255 /// residing in the high word of the containing object. 2256 /// 2257 /// \param OffsetBase - The bit offset of this type in the 2258 /// containing object. Some parameters are classified different 2259 /// depending on whether they straddle an eightbyte boundary. 2260 /// 2261 /// \param isNamedArg - Whether the argument in question is a "named" 2262 /// argument, as used in AMD64-ABI 3.5.7. 2263 /// 2264 /// If a word is unused its result will be NoClass; if a type should 2265 /// be passed in Memory then at least the classification of \arg Lo 2266 /// will be Memory. 2267 /// 2268 /// The \arg Lo class will be NoClass iff the argument is ignored. 2269 /// 2270 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2271 /// also be ComplexX87. 2272 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2273 bool isNamedArg) const; 2274 2275 llvm::Type *GetByteVectorType(QualType Ty) const; 2276 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2277 unsigned IROffset, QualType SourceTy, 2278 unsigned SourceOffset) const; 2279 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2280 unsigned IROffset, QualType SourceTy, 2281 unsigned SourceOffset) const; 2282 2283 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2284 /// such that the argument will be returned in memory. 2285 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2286 2287 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2288 /// such that the argument will be passed in memory. 2289 /// 2290 /// \param freeIntRegs - The number of free integer registers remaining 2291 /// available. 2292 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2293 2294 ABIArgInfo classifyReturnType(QualType RetTy) const; 2295 2296 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2297 unsigned &neededInt, unsigned &neededSSE, 2298 bool isNamedArg) const; 2299 2300 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2301 unsigned &NeededSSE) const; 2302 2303 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2304 unsigned &NeededSSE) const; 2305 2306 bool IsIllegalVectorType(QualType Ty) const; 2307 2308 /// The 0.98 ABI revision clarified a lot of ambiguities, 2309 /// unfortunately in ways that were not always consistent with 2310 /// certain previous compilers. In particular, platforms which 2311 /// required strict binary compatibility with older versions of GCC 2312 /// may need to exempt themselves. 2313 bool honorsRevision0_98() const { 2314 return !getTarget().getTriple().isOSDarwin(); 2315 } 2316 2317 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2318 /// classify it as INTEGER (for compatibility with older clang compilers). 2319 bool classifyIntegerMMXAsSSE() const { 2320 // Clang <= 3.8 did not do this. 2321 if (getContext().getLangOpts().getClangABICompat() <= 2322 LangOptions::ClangABI::Ver3_8) 2323 return false; 2324 2325 const llvm::Triple &Triple = getTarget().getTriple(); 2326 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2327 return false; 2328 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2329 return false; 2330 return true; 2331 } 2332 2333 // GCC classifies vectors of __int128 as memory. 2334 bool passInt128VectorsInMem() const { 2335 // Clang <= 9.0 did not do this. 2336 if (getContext().getLangOpts().getClangABICompat() <= 2337 LangOptions::ClangABI::Ver9) 2338 return false; 2339 2340 const llvm::Triple &T = getTarget().getTriple(); 2341 return T.isOSLinux() || T.isOSNetBSD(); 2342 } 2343 2344 X86AVXABILevel AVXLevel; 2345 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2346 // 64-bit hardware. 2347 bool Has64BitPointers; 2348 2349 public: 2350 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2351 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2352 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2353 } 2354 2355 bool isPassedUsingAVXType(QualType type) const { 2356 unsigned neededInt, neededSSE; 2357 // The freeIntRegs argument doesn't matter here. 2358 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2359 /*isNamedArg*/true); 2360 if (info.isDirect()) { 2361 llvm::Type *ty = info.getCoerceToType(); 2362 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2363 return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128; 2364 } 2365 return false; 2366 } 2367 2368 void computeInfo(CGFunctionInfo &FI) const override; 2369 2370 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2371 QualType Ty) const override; 2372 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2373 QualType Ty) const override; 2374 2375 bool has64BitPointers() const { 2376 return Has64BitPointers; 2377 } 2378 2379 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2380 bool asReturnValue) const override { 2381 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2382 } 2383 bool isSwiftErrorInRegister() const override { 2384 return true; 2385 } 2386 }; 2387 2388 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2389 class WinX86_64ABIInfo : public SwiftABIInfo { 2390 public: 2391 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2392 : SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2393 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2394 2395 void computeInfo(CGFunctionInfo &FI) const override; 2396 2397 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2398 QualType Ty) const override; 2399 2400 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2401 // FIXME: Assumes vectorcall is in use. 2402 return isX86VectorTypeForVectorCall(getContext(), Ty); 2403 } 2404 2405 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2406 uint64_t NumMembers) const override { 2407 // FIXME: Assumes vectorcall is in use. 2408 return isX86VectorCallAggregateSmallEnough(NumMembers); 2409 } 2410 2411 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2412 bool asReturnValue) const override { 2413 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2414 } 2415 2416 bool isSwiftErrorInRegister() const override { 2417 return true; 2418 } 2419 2420 private: 2421 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2422 bool IsVectorCall, bool IsRegCall) const; 2423 ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs, 2424 const ABIArgInfo ¤t) const; 2425 2426 X86AVXABILevel AVXLevel; 2427 2428 bool IsMingw64; 2429 }; 2430 2431 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2432 public: 2433 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2434 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {} 2435 2436 const X86_64ABIInfo &getABIInfo() const { 2437 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2438 } 2439 2440 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2441 /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations. 2442 bool markARCOptimizedReturnCallsAsNoTail() const override { return true; } 2443 2444 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2445 return 7; 2446 } 2447 2448 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2449 llvm::Value *Address) const override { 2450 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2451 2452 // 0-15 are the 16 integer registers. 2453 // 16 is %rip. 2454 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2455 return false; 2456 } 2457 2458 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2459 StringRef Constraint, 2460 llvm::Type* Ty) const override { 2461 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2462 } 2463 2464 bool isNoProtoCallVariadic(const CallArgList &args, 2465 const FunctionNoProtoType *fnType) const override { 2466 // The default CC on x86-64 sets %al to the number of SSA 2467 // registers used, and GCC sets this when calling an unprototyped 2468 // function, so we override the default behavior. However, don't do 2469 // that when AVX types are involved: the ABI explicitly states it is 2470 // undefined, and it doesn't work in practice because of how the ABI 2471 // defines varargs anyway. 2472 if (fnType->getCallConv() == CC_C) { 2473 bool HasAVXType = false; 2474 for (CallArgList::const_iterator 2475 it = args.begin(), ie = args.end(); it != ie; ++it) { 2476 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2477 HasAVXType = true; 2478 break; 2479 } 2480 } 2481 2482 if (!HasAVXType) 2483 return true; 2484 } 2485 2486 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2487 } 2488 2489 llvm::Constant * 2490 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2491 unsigned Sig = (0xeb << 0) | // jmp rel8 2492 (0x06 << 8) | // .+0x08 2493 ('v' << 16) | 2494 ('2' << 24); 2495 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2496 } 2497 2498 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2499 CodeGen::CodeGenModule &CGM) const override { 2500 if (GV->isDeclaration()) 2501 return; 2502 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2503 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2504 llvm::Function *Fn = cast<llvm::Function>(GV); 2505 Fn->addFnAttr("stackrealign"); 2506 } 2507 2508 addX86InterruptAttrs(FD, GV, CGM); 2509 } 2510 } 2511 2512 void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, 2513 const FunctionDecl *Caller, 2514 const FunctionDecl *Callee, 2515 const CallArgList &Args) const override; 2516 }; 2517 2518 static void initFeatureMaps(const ASTContext &Ctx, 2519 llvm::StringMap<bool> &CallerMap, 2520 const FunctionDecl *Caller, 2521 llvm::StringMap<bool> &CalleeMap, 2522 const FunctionDecl *Callee) { 2523 if (CalleeMap.empty() && CallerMap.empty()) { 2524 // The caller is potentially nullptr in the case where the call isn't in a 2525 // function. In this case, the getFunctionFeatureMap ensures we just get 2526 // the TU level setting (since it cannot be modified by 'target'.. 2527 Ctx.getFunctionFeatureMap(CallerMap, Caller); 2528 Ctx.getFunctionFeatureMap(CalleeMap, Callee); 2529 } 2530 } 2531 2532 static bool checkAVXParamFeature(DiagnosticsEngine &Diag, 2533 SourceLocation CallLoc, 2534 const llvm::StringMap<bool> &CallerMap, 2535 const llvm::StringMap<bool> &CalleeMap, 2536 QualType Ty, StringRef Feature, 2537 bool IsArgument) { 2538 bool CallerHasFeat = CallerMap.lookup(Feature); 2539 bool CalleeHasFeat = CalleeMap.lookup(Feature); 2540 if (!CallerHasFeat && !CalleeHasFeat) 2541 return Diag.Report(CallLoc, diag::warn_avx_calling_convention) 2542 << IsArgument << Ty << Feature; 2543 2544 // Mixing calling conventions here is very clearly an error. 2545 if (!CallerHasFeat || !CalleeHasFeat) 2546 return Diag.Report(CallLoc, diag::err_avx_calling_convention) 2547 << IsArgument << Ty << Feature; 2548 2549 // Else, both caller and callee have the required feature, so there is no need 2550 // to diagnose. 2551 return false; 2552 } 2553 2554 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx, 2555 SourceLocation CallLoc, 2556 const llvm::StringMap<bool> &CallerMap, 2557 const llvm::StringMap<bool> &CalleeMap, QualType Ty, 2558 bool IsArgument) { 2559 uint64_t Size = Ctx.getTypeSize(Ty); 2560 if (Size > 256) 2561 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, 2562 "avx512f", IsArgument); 2563 2564 if (Size > 128) 2565 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx", 2566 IsArgument); 2567 2568 return false; 2569 } 2570 2571 void X86_64TargetCodeGenInfo::checkFunctionCallABI( 2572 CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, 2573 const FunctionDecl *Callee, const CallArgList &Args) const { 2574 llvm::StringMap<bool> CallerMap; 2575 llvm::StringMap<bool> CalleeMap; 2576 unsigned ArgIndex = 0; 2577 2578 // We need to loop through the actual call arguments rather than the the 2579 // function's parameters, in case this variadic. 2580 for (const CallArg &Arg : Args) { 2581 // The "avx" feature changes how vectors >128 in size are passed. "avx512f" 2582 // additionally changes how vectors >256 in size are passed. Like GCC, we 2583 // warn when a function is called with an argument where this will change. 2584 // Unlike GCC, we also error when it is an obvious ABI mismatch, that is, 2585 // the caller and callee features are mismatched. 2586 // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can 2587 // change its ABI with attribute-target after this call. 2588 if (Arg.getType()->isVectorType() && 2589 CGM.getContext().getTypeSize(Arg.getType()) > 128) { 2590 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2591 QualType Ty = Arg.getType(); 2592 // The CallArg seems to have desugared the type already, so for clearer 2593 // diagnostics, replace it with the type in the FunctionDecl if possible. 2594 if (ArgIndex < Callee->getNumParams()) 2595 Ty = Callee->getParamDecl(ArgIndex)->getType(); 2596 2597 if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2598 CalleeMap, Ty, /*IsArgument*/ true)) 2599 return; 2600 } 2601 ++ArgIndex; 2602 } 2603 2604 // Check return always, as we don't have a good way of knowing in codegen 2605 // whether this value is used, tail-called, etc. 2606 if (Callee->getReturnType()->isVectorType() && 2607 CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) { 2608 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2609 checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2610 CalleeMap, Callee->getReturnType(), 2611 /*IsArgument*/ false); 2612 } 2613 } 2614 2615 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2616 // If the argument does not end in .lib, automatically add the suffix. 2617 // If the argument contains a space, enclose it in quotes. 2618 // This matches the behavior of MSVC. 2619 bool Quote = (Lib.find(' ') != StringRef::npos); 2620 std::string ArgStr = Quote ? "\"" : ""; 2621 ArgStr += Lib; 2622 if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a")) 2623 ArgStr += ".lib"; 2624 ArgStr += Quote ? "\"" : ""; 2625 return ArgStr; 2626 } 2627 2628 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2629 public: 2630 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2631 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2632 unsigned NumRegisterParameters) 2633 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2634 Win32StructABI, NumRegisterParameters, false) {} 2635 2636 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2637 CodeGen::CodeGenModule &CGM) const override; 2638 2639 void getDependentLibraryOption(llvm::StringRef Lib, 2640 llvm::SmallString<24> &Opt) const override { 2641 Opt = "/DEFAULTLIB:"; 2642 Opt += qualifyWindowsLibrary(Lib); 2643 } 2644 2645 void getDetectMismatchOption(llvm::StringRef Name, 2646 llvm::StringRef Value, 2647 llvm::SmallString<32> &Opt) const override { 2648 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2649 } 2650 }; 2651 2652 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2653 CodeGen::CodeGenModule &CGM) { 2654 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2655 2656 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2657 Fn->addFnAttr("stack-probe-size", 2658 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2659 if (CGM.getCodeGenOpts().NoStackArgProbe) 2660 Fn->addFnAttr("no-stack-arg-probe"); 2661 } 2662 } 2663 2664 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2665 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2666 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2667 if (GV->isDeclaration()) 2668 return; 2669 addStackProbeTargetAttributes(D, GV, CGM); 2670 } 2671 2672 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2673 public: 2674 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2675 X86AVXABILevel AVXLevel) 2676 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {} 2677 2678 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2679 CodeGen::CodeGenModule &CGM) const override; 2680 2681 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2682 return 7; 2683 } 2684 2685 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2686 llvm::Value *Address) const override { 2687 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2688 2689 // 0-15 are the 16 integer registers. 2690 // 16 is %rip. 2691 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2692 return false; 2693 } 2694 2695 void getDependentLibraryOption(llvm::StringRef Lib, 2696 llvm::SmallString<24> &Opt) const override { 2697 Opt = "/DEFAULTLIB:"; 2698 Opt += qualifyWindowsLibrary(Lib); 2699 } 2700 2701 void getDetectMismatchOption(llvm::StringRef Name, 2702 llvm::StringRef Value, 2703 llvm::SmallString<32> &Opt) const override { 2704 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2705 } 2706 }; 2707 2708 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2709 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2710 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2711 if (GV->isDeclaration()) 2712 return; 2713 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2714 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2715 llvm::Function *Fn = cast<llvm::Function>(GV); 2716 Fn->addFnAttr("stackrealign"); 2717 } 2718 2719 addX86InterruptAttrs(FD, GV, CGM); 2720 } 2721 2722 addStackProbeTargetAttributes(D, GV, CGM); 2723 } 2724 } 2725 2726 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2727 Class &Hi) const { 2728 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2729 // 2730 // (a) If one of the classes is Memory, the whole argument is passed in 2731 // memory. 2732 // 2733 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2734 // memory. 2735 // 2736 // (c) If the size of the aggregate exceeds two eightbytes and the first 2737 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2738 // argument is passed in memory. NOTE: This is necessary to keep the 2739 // ABI working for processors that don't support the __m256 type. 2740 // 2741 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2742 // 2743 // Some of these are enforced by the merging logic. Others can arise 2744 // only with unions; for example: 2745 // union { _Complex double; unsigned; } 2746 // 2747 // Note that clauses (b) and (c) were added in 0.98. 2748 // 2749 if (Hi == Memory) 2750 Lo = Memory; 2751 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2752 Lo = Memory; 2753 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2754 Lo = Memory; 2755 if (Hi == SSEUp && Lo != SSE) 2756 Hi = SSE; 2757 } 2758 2759 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2760 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2761 // classified recursively so that always two fields are 2762 // considered. The resulting class is calculated according to 2763 // the classes of the fields in the eightbyte: 2764 // 2765 // (a) If both classes are equal, this is the resulting class. 2766 // 2767 // (b) If one of the classes is NO_CLASS, the resulting class is 2768 // the other class. 2769 // 2770 // (c) If one of the classes is MEMORY, the result is the MEMORY 2771 // class. 2772 // 2773 // (d) If one of the classes is INTEGER, the result is the 2774 // INTEGER. 2775 // 2776 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2777 // MEMORY is used as class. 2778 // 2779 // (f) Otherwise class SSE is used. 2780 2781 // Accum should never be memory (we should have returned) or 2782 // ComplexX87 (because this cannot be passed in a structure). 2783 assert((Accum != Memory && Accum != ComplexX87) && 2784 "Invalid accumulated classification during merge."); 2785 if (Accum == Field || Field == NoClass) 2786 return Accum; 2787 if (Field == Memory) 2788 return Memory; 2789 if (Accum == NoClass) 2790 return Field; 2791 if (Accum == Integer || Field == Integer) 2792 return Integer; 2793 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2794 Accum == X87 || Accum == X87Up) 2795 return Memory; 2796 return SSE; 2797 } 2798 2799 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 2800 Class &Lo, Class &Hi, bool isNamedArg) const { 2801 // FIXME: This code can be simplified by introducing a simple value class for 2802 // Class pairs with appropriate constructor methods for the various 2803 // situations. 2804 2805 // FIXME: Some of the split computations are wrong; unaligned vectors 2806 // shouldn't be passed in registers for example, so there is no chance they 2807 // can straddle an eightbyte. Verify & simplify. 2808 2809 Lo = Hi = NoClass; 2810 2811 Class &Current = OffsetBase < 64 ? Lo : Hi; 2812 Current = Memory; 2813 2814 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2815 BuiltinType::Kind k = BT->getKind(); 2816 2817 if (k == BuiltinType::Void) { 2818 Current = NoClass; 2819 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2820 Lo = Integer; 2821 Hi = Integer; 2822 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2823 Current = Integer; 2824 } else if (k == BuiltinType::Float || k == BuiltinType::Double || 2825 k == BuiltinType::Float16) { 2826 Current = SSE; 2827 } else if (k == BuiltinType::LongDouble) { 2828 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2829 if (LDF == &llvm::APFloat::IEEEquad()) { 2830 Lo = SSE; 2831 Hi = SSEUp; 2832 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2833 Lo = X87; 2834 Hi = X87Up; 2835 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2836 Current = SSE; 2837 } else 2838 llvm_unreachable("unexpected long double representation!"); 2839 } 2840 // FIXME: _Decimal32 and _Decimal64 are SSE. 2841 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2842 return; 2843 } 2844 2845 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2846 // Classify the underlying integer type. 2847 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2848 return; 2849 } 2850 2851 if (Ty->hasPointerRepresentation()) { 2852 Current = Integer; 2853 return; 2854 } 2855 2856 if (Ty->isMemberPointerType()) { 2857 if (Ty->isMemberFunctionPointerType()) { 2858 if (Has64BitPointers) { 2859 // If Has64BitPointers, this is an {i64, i64}, so classify both 2860 // Lo and Hi now. 2861 Lo = Hi = Integer; 2862 } else { 2863 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2864 // straddles an eightbyte boundary, Hi should be classified as well. 2865 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2866 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2867 if (EB_FuncPtr != EB_ThisAdj) { 2868 Lo = Hi = Integer; 2869 } else { 2870 Current = Integer; 2871 } 2872 } 2873 } else { 2874 Current = Integer; 2875 } 2876 return; 2877 } 2878 2879 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2880 uint64_t Size = getContext().getTypeSize(VT); 2881 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2882 // gcc passes the following as integer: 2883 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2884 // 2 bytes - <2 x char>, <1 x short> 2885 // 1 byte - <1 x char> 2886 Current = Integer; 2887 2888 // If this type crosses an eightbyte boundary, it should be 2889 // split. 2890 uint64_t EB_Lo = (OffsetBase) / 64; 2891 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2892 if (EB_Lo != EB_Hi) 2893 Hi = Lo; 2894 } else if (Size == 64) { 2895 QualType ElementType = VT->getElementType(); 2896 2897 // gcc passes <1 x double> in memory. :( 2898 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2899 return; 2900 2901 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2902 // pass them as integer. For platforms where clang is the de facto 2903 // platform compiler, we must continue to use integer. 2904 if (!classifyIntegerMMXAsSSE() && 2905 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2906 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2907 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2908 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2909 Current = Integer; 2910 else 2911 Current = SSE; 2912 2913 // If this type crosses an eightbyte boundary, it should be 2914 // split. 2915 if (OffsetBase && OffsetBase != 64) 2916 Hi = Lo; 2917 } else if (Size == 128 || 2918 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2919 QualType ElementType = VT->getElementType(); 2920 2921 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( 2922 if (passInt128VectorsInMem() && Size != 128 && 2923 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || 2924 ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) 2925 return; 2926 2927 // Arguments of 256-bits are split into four eightbyte chunks. The 2928 // least significant one belongs to class SSE and all the others to class 2929 // SSEUP. The original Lo and Hi design considers that types can't be 2930 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2931 // This design isn't correct for 256-bits, but since there're no cases 2932 // where the upper parts would need to be inspected, avoid adding 2933 // complexity and just consider Hi to match the 64-256 part. 2934 // 2935 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2936 // registers if they are "named", i.e. not part of the "..." of a 2937 // variadic function. 2938 // 2939 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2940 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2941 Lo = SSE; 2942 Hi = SSEUp; 2943 } 2944 return; 2945 } 2946 2947 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2948 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2949 2950 uint64_t Size = getContext().getTypeSize(Ty); 2951 if (ET->isIntegralOrEnumerationType()) { 2952 if (Size <= 64) 2953 Current = Integer; 2954 else if (Size <= 128) 2955 Lo = Hi = Integer; 2956 } else if (ET->isFloat16Type() || ET == getContext().FloatTy) { 2957 Current = SSE; 2958 } else if (ET == getContext().DoubleTy) { 2959 Lo = Hi = SSE; 2960 } else if (ET == getContext().LongDoubleTy) { 2961 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2962 if (LDF == &llvm::APFloat::IEEEquad()) 2963 Current = Memory; 2964 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 2965 Current = ComplexX87; 2966 else if (LDF == &llvm::APFloat::IEEEdouble()) 2967 Lo = Hi = SSE; 2968 else 2969 llvm_unreachable("unexpected long double representation!"); 2970 } 2971 2972 // If this complex type crosses an eightbyte boundary then it 2973 // should be split. 2974 uint64_t EB_Real = (OffsetBase) / 64; 2975 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 2976 if (Hi == NoClass && EB_Real != EB_Imag) 2977 Hi = Lo; 2978 2979 return; 2980 } 2981 2982 if (const auto *EITy = Ty->getAs<ExtIntType>()) { 2983 if (EITy->getNumBits() <= 64) 2984 Current = Integer; 2985 else if (EITy->getNumBits() <= 128) 2986 Lo = Hi = Integer; 2987 // Larger values need to get passed in memory. 2988 return; 2989 } 2990 2991 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 2992 // Arrays are treated like structures. 2993 2994 uint64_t Size = getContext().getTypeSize(Ty); 2995 2996 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2997 // than eight eightbytes, ..., it has class MEMORY. 2998 if (Size > 512) 2999 return; 3000 3001 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 3002 // fields, it has class MEMORY. 3003 // 3004 // Only need to check alignment of array base. 3005 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 3006 return; 3007 3008 // Otherwise implement simplified merge. We could be smarter about 3009 // this, but it isn't worth it and would be harder to verify. 3010 Current = NoClass; 3011 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 3012 uint64_t ArraySize = AT->getSize().getZExtValue(); 3013 3014 // The only case a 256-bit wide vector could be used is when the array 3015 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 3016 // to work for sizes wider than 128, early check and fallback to memory. 3017 // 3018 if (Size > 128 && 3019 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 3020 return; 3021 3022 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 3023 Class FieldLo, FieldHi; 3024 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 3025 Lo = merge(Lo, FieldLo); 3026 Hi = merge(Hi, FieldHi); 3027 if (Lo == Memory || Hi == Memory) 3028 break; 3029 } 3030 3031 postMerge(Size, Lo, Hi); 3032 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 3033 return; 3034 } 3035 3036 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3037 uint64_t Size = getContext().getTypeSize(Ty); 3038 3039 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 3040 // than eight eightbytes, ..., it has class MEMORY. 3041 if (Size > 512) 3042 return; 3043 3044 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 3045 // copy constructor or a non-trivial destructor, it is passed by invisible 3046 // reference. 3047 if (getRecordArgABI(RT, getCXXABI())) 3048 return; 3049 3050 const RecordDecl *RD = RT->getDecl(); 3051 3052 // Assume variable sized types are passed in memory. 3053 if (RD->hasFlexibleArrayMember()) 3054 return; 3055 3056 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 3057 3058 // Reset Lo class, this will be recomputed. 3059 Current = NoClass; 3060 3061 // If this is a C++ record, classify the bases first. 3062 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3063 for (const auto &I : CXXRD->bases()) { 3064 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3065 "Unexpected base class!"); 3066 const auto *Base = 3067 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3068 3069 // Classify this field. 3070 // 3071 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 3072 // single eightbyte, each is classified separately. Each eightbyte gets 3073 // initialized to class NO_CLASS. 3074 Class FieldLo, FieldHi; 3075 uint64_t Offset = 3076 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 3077 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 3078 Lo = merge(Lo, FieldLo); 3079 Hi = merge(Hi, FieldHi); 3080 if (Lo == Memory || Hi == Memory) { 3081 postMerge(Size, Lo, Hi); 3082 return; 3083 } 3084 } 3085 } 3086 3087 // Classify the fields one at a time, merging the results. 3088 unsigned idx = 0; 3089 bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <= 3090 LangOptions::ClangABI::Ver11 || 3091 getContext().getTargetInfo().getTriple().isPS4(); 3092 bool IsUnion = RT->isUnionType() && !UseClang11Compat; 3093 3094 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3095 i != e; ++i, ++idx) { 3096 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3097 bool BitField = i->isBitField(); 3098 3099 // Ignore padding bit-fields. 3100 if (BitField && i->isUnnamedBitfield()) 3101 continue; 3102 3103 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 3104 // eight eightbytes, or it contains unaligned fields, it has class MEMORY. 3105 // 3106 // The only case a 256-bit or a 512-bit wide vector could be used is when 3107 // the struct contains a single 256-bit or 512-bit element. Early check 3108 // and fallback to memory. 3109 // 3110 // FIXME: Extended the Lo and Hi logic properly to work for size wider 3111 // than 128. 3112 if (Size > 128 && 3113 ((!IsUnion && Size != getContext().getTypeSize(i->getType())) || 3114 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 3115 Lo = Memory; 3116 postMerge(Size, Lo, Hi); 3117 return; 3118 } 3119 // Note, skip this test for bit-fields, see below. 3120 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 3121 Lo = Memory; 3122 postMerge(Size, Lo, Hi); 3123 return; 3124 } 3125 3126 // Classify this field. 3127 // 3128 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 3129 // exceeds a single eightbyte, each is classified 3130 // separately. Each eightbyte gets initialized to class 3131 // NO_CLASS. 3132 Class FieldLo, FieldHi; 3133 3134 // Bit-fields require special handling, they do not force the 3135 // structure to be passed in memory even if unaligned, and 3136 // therefore they can straddle an eightbyte. 3137 if (BitField) { 3138 assert(!i->isUnnamedBitfield()); 3139 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3140 uint64_t Size = i->getBitWidthValue(getContext()); 3141 3142 uint64_t EB_Lo = Offset / 64; 3143 uint64_t EB_Hi = (Offset + Size - 1) / 64; 3144 3145 if (EB_Lo) { 3146 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 3147 FieldLo = NoClass; 3148 FieldHi = Integer; 3149 } else { 3150 FieldLo = Integer; 3151 FieldHi = EB_Hi ? Integer : NoClass; 3152 } 3153 } else 3154 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 3155 Lo = merge(Lo, FieldLo); 3156 Hi = merge(Hi, FieldHi); 3157 if (Lo == Memory || Hi == Memory) 3158 break; 3159 } 3160 3161 postMerge(Size, Lo, Hi); 3162 } 3163 } 3164 3165 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 3166 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3167 // place naturally. 3168 if (!isAggregateTypeForABI(Ty)) { 3169 // Treat an enum type as its underlying type. 3170 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3171 Ty = EnumTy->getDecl()->getIntegerType(); 3172 3173 if (Ty->isExtIntType()) 3174 return getNaturalAlignIndirect(Ty); 3175 3176 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3177 : ABIArgInfo::getDirect()); 3178 } 3179 3180 return getNaturalAlignIndirect(Ty); 3181 } 3182 3183 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 3184 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 3185 uint64_t Size = getContext().getTypeSize(VecTy); 3186 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 3187 if (Size <= 64 || Size > LargestVector) 3188 return true; 3189 QualType EltTy = VecTy->getElementType(); 3190 if (passInt128VectorsInMem() && 3191 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || 3192 EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) 3193 return true; 3194 } 3195 3196 return false; 3197 } 3198 3199 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 3200 unsigned freeIntRegs) const { 3201 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3202 // place naturally. 3203 // 3204 // This assumption is optimistic, as there could be free registers available 3205 // when we need to pass this argument in memory, and LLVM could try to pass 3206 // the argument in the free register. This does not seem to happen currently, 3207 // but this code would be much safer if we could mark the argument with 3208 // 'onstack'. See PR12193. 3209 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) && 3210 !Ty->isExtIntType()) { 3211 // Treat an enum type as its underlying type. 3212 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3213 Ty = EnumTy->getDecl()->getIntegerType(); 3214 3215 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3216 : ABIArgInfo::getDirect()); 3217 } 3218 3219 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3220 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3221 3222 // Compute the byval alignment. We specify the alignment of the byval in all 3223 // cases so that the mid-level optimizer knows the alignment of the byval. 3224 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 3225 3226 // Attempt to avoid passing indirect results using byval when possible. This 3227 // is important for good codegen. 3228 // 3229 // We do this by coercing the value into a scalar type which the backend can 3230 // handle naturally (i.e., without using byval). 3231 // 3232 // For simplicity, we currently only do this when we have exhausted all of the 3233 // free integer registers. Doing this when there are free integer registers 3234 // would require more care, as we would have to ensure that the coerced value 3235 // did not claim the unused register. That would require either reording the 3236 // arguments to the function (so that any subsequent inreg values came first), 3237 // or only doing this optimization when there were no following arguments that 3238 // might be inreg. 3239 // 3240 // We currently expect it to be rare (particularly in well written code) for 3241 // arguments to be passed on the stack when there are still free integer 3242 // registers available (this would typically imply large structs being passed 3243 // by value), so this seems like a fair tradeoff for now. 3244 // 3245 // We can revisit this if the backend grows support for 'onstack' parameter 3246 // attributes. See PR12193. 3247 if (freeIntRegs == 0) { 3248 uint64_t Size = getContext().getTypeSize(Ty); 3249 3250 // If this type fits in an eightbyte, coerce it into the matching integral 3251 // type, which will end up on the stack (with alignment 8). 3252 if (Align == 8 && Size <= 64) 3253 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3254 Size)); 3255 } 3256 3257 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 3258 } 3259 3260 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 3261 /// register. Pick an LLVM IR type that will be passed as a vector register. 3262 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 3263 // Wrapper structs/arrays that only contain vectors are passed just like 3264 // vectors; strip them off if present. 3265 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 3266 Ty = QualType(InnerTy, 0); 3267 3268 llvm::Type *IRType = CGT.ConvertType(Ty); 3269 if (isa<llvm::VectorType>(IRType)) { 3270 // Don't pass vXi128 vectors in their native type, the backend can't 3271 // legalize them. 3272 if (passInt128VectorsInMem() && 3273 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) { 3274 // Use a vXi64 vector. 3275 uint64_t Size = getContext().getTypeSize(Ty); 3276 return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()), 3277 Size / 64); 3278 } 3279 3280 return IRType; 3281 } 3282 3283 if (IRType->getTypeID() == llvm::Type::FP128TyID) 3284 return IRType; 3285 3286 // We couldn't find the preferred IR vector type for 'Ty'. 3287 uint64_t Size = getContext().getTypeSize(Ty); 3288 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 3289 3290 3291 // Return a LLVM IR vector type based on the size of 'Ty'. 3292 return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()), 3293 Size / 64); 3294 } 3295 3296 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3297 /// is known to either be off the end of the specified type or being in 3298 /// alignment padding. The user type specified is known to be at most 128 bits 3299 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3300 /// classification that put one of the two halves in the INTEGER class. 3301 /// 3302 /// It is conservatively correct to return false. 3303 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3304 unsigned EndBit, ASTContext &Context) { 3305 // If the bytes being queried are off the end of the type, there is no user 3306 // data hiding here. This handles analysis of builtins, vectors and other 3307 // types that don't contain interesting padding. 3308 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3309 if (TySize <= StartBit) 3310 return true; 3311 3312 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3313 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3314 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3315 3316 // Check each element to see if the element overlaps with the queried range. 3317 for (unsigned i = 0; i != NumElts; ++i) { 3318 // If the element is after the span we care about, then we're done.. 3319 unsigned EltOffset = i*EltSize; 3320 if (EltOffset >= EndBit) break; 3321 3322 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3323 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3324 EndBit-EltOffset, Context)) 3325 return false; 3326 } 3327 // If it overlaps no elements, then it is safe to process as padding. 3328 return true; 3329 } 3330 3331 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3332 const RecordDecl *RD = RT->getDecl(); 3333 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3334 3335 // If this is a C++ record, check the bases first. 3336 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3337 for (const auto &I : CXXRD->bases()) { 3338 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3339 "Unexpected base class!"); 3340 const auto *Base = 3341 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3342 3343 // If the base is after the span we care about, ignore it. 3344 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3345 if (BaseOffset >= EndBit) continue; 3346 3347 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3348 if (!BitsContainNoUserData(I.getType(), BaseStart, 3349 EndBit-BaseOffset, Context)) 3350 return false; 3351 } 3352 } 3353 3354 // Verify that no field has data that overlaps the region of interest. Yes 3355 // this could be sped up a lot by being smarter about queried fields, 3356 // however we're only looking at structs up to 16 bytes, so we don't care 3357 // much. 3358 unsigned idx = 0; 3359 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3360 i != e; ++i, ++idx) { 3361 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3362 3363 // If we found a field after the region we care about, then we're done. 3364 if (FieldOffset >= EndBit) break; 3365 3366 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3367 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3368 Context)) 3369 return false; 3370 } 3371 3372 // If nothing in this record overlapped the area of interest, then we're 3373 // clean. 3374 return true; 3375 } 3376 3377 return false; 3378 } 3379 3380 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 3381 /// float member at the specified offset. For example, {int,{float}} has a 3382 /// float at offset 4. It is conservatively correct for this routine to return 3383 /// false. 3384 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 3385 const llvm::DataLayout &TD) { 3386 // Base case if we find a float. 3387 if (IROffset == 0 && IRType->isFloatTy()) 3388 return true; 3389 3390 // If this is a struct, recurse into the field at the specified offset. 3391 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3392 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3393 unsigned Elt = SL->getElementContainingOffset(IROffset); 3394 IROffset -= SL->getElementOffset(Elt); 3395 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 3396 } 3397 3398 // If this is an array, recurse into the field at the specified offset. 3399 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3400 llvm::Type *EltTy = ATy->getElementType(); 3401 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3402 IROffset -= IROffset/EltSize*EltSize; 3403 return ContainsFloatAtOffset(EltTy, IROffset, TD); 3404 } 3405 3406 return false; 3407 } 3408 3409 /// ContainsHalfAtOffset - Return true if the specified LLVM IR type has a 3410 /// half member at the specified offset. For example, {int,{half}} has a 3411 /// half at offset 4. It is conservatively correct for this routine to return 3412 /// false. 3413 /// FIXME: Merge with ContainsFloatAtOffset 3414 static bool ContainsHalfAtOffset(llvm::Type *IRType, unsigned IROffset, 3415 const llvm::DataLayout &TD) { 3416 // Base case if we find a float. 3417 if (IROffset == 0 && IRType->isHalfTy()) 3418 return true; 3419 3420 // If this is a struct, recurse into the field at the specified offset. 3421 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3422 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3423 unsigned Elt = SL->getElementContainingOffset(IROffset); 3424 IROffset -= SL->getElementOffset(Elt); 3425 return ContainsHalfAtOffset(STy->getElementType(Elt), IROffset, TD); 3426 } 3427 3428 // If this is an array, recurse into the field at the specified offset. 3429 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3430 llvm::Type *EltTy = ATy->getElementType(); 3431 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3432 IROffset -= IROffset / EltSize * EltSize; 3433 return ContainsHalfAtOffset(EltTy, IROffset, TD); 3434 } 3435 3436 return false; 3437 } 3438 3439 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3440 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3441 llvm::Type *X86_64ABIInfo:: 3442 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3443 QualType SourceTy, unsigned SourceOffset) const { 3444 // If the high 32 bits are not used, we have three choices. Single half, 3445 // single float or two halfs. 3446 if (BitsContainNoUserData(SourceTy, SourceOffset * 8 + 32, 3447 SourceOffset * 8 + 64, getContext())) { 3448 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout())) 3449 return llvm::Type::getFloatTy(getVMContext()); 3450 if (ContainsHalfAtOffset(IRType, IROffset + 2, getDataLayout())) 3451 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 3452 2); 3453 3454 return llvm::Type::getHalfTy(getVMContext()); 3455 } 3456 3457 // We want to pass as <2 x float> if the LLVM IR type contains a float at 3458 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 3459 // case. 3460 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 3461 ContainsFloatAtOffset(IRType, IROffset + 4, getDataLayout())) 3462 return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()), 3463 2); 3464 3465 // We want to pass as <4 x half> if the LLVM IR type contains a half at 3466 // offset+0, +2, +4. Walk the LLVM IR type to find out if this is the case. 3467 if (ContainsHalfAtOffset(IRType, IROffset, getDataLayout()) && 3468 ContainsHalfAtOffset(IRType, IROffset + 2, getDataLayout()) && 3469 ContainsHalfAtOffset(IRType, IROffset + 4, getDataLayout())) 3470 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4); 3471 3472 // We want to pass as <4 x half> if the LLVM IR type contains a mix of float 3473 // and half. 3474 // FIXME: Do we have a better representation for the mixed type? 3475 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) || 3476 ContainsFloatAtOffset(IRType, IROffset + 4, getDataLayout())) 3477 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4); 3478 3479 return llvm::Type::getDoubleTy(getVMContext()); 3480 } 3481 3482 3483 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3484 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3485 /// about the high or low part of an up-to-16-byte struct. This routine picks 3486 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3487 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3488 /// etc). 3489 /// 3490 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3491 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3492 /// the 8-byte value references. PrefType may be null. 3493 /// 3494 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3495 /// an offset into this that we're processing (which is always either 0 or 8). 3496 /// 3497 llvm::Type *X86_64ABIInfo:: 3498 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3499 QualType SourceTy, unsigned SourceOffset) const { 3500 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3501 // returning an 8-byte unit starting with it. See if we can safely use it. 3502 if (IROffset == 0) { 3503 // Pointers and int64's always fill the 8-byte unit. 3504 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3505 IRType->isIntegerTy(64)) 3506 return IRType; 3507 3508 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3509 // goodness in the source type is just tail padding. This is allowed to 3510 // kick in for struct {double,int} on the int, but not on 3511 // struct{double,int,int} because we wouldn't return the second int. We 3512 // have to do this analysis on the source type because we can't depend on 3513 // unions being lowered a specific way etc. 3514 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3515 IRType->isIntegerTy(32) || 3516 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3517 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3518 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3519 3520 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3521 SourceOffset*8+64, getContext())) 3522 return IRType; 3523 } 3524 } 3525 3526 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3527 // If this is a struct, recurse into the field at the specified offset. 3528 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3529 if (IROffset < SL->getSizeInBytes()) { 3530 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3531 IROffset -= SL->getElementOffset(FieldIdx); 3532 3533 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3534 SourceTy, SourceOffset); 3535 } 3536 } 3537 3538 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3539 llvm::Type *EltTy = ATy->getElementType(); 3540 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3541 unsigned EltOffset = IROffset/EltSize*EltSize; 3542 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3543 SourceOffset); 3544 } 3545 3546 // Okay, we don't have any better idea of what to pass, so we pass this in an 3547 // integer register that isn't too big to fit the rest of the struct. 3548 unsigned TySizeInBytes = 3549 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3550 3551 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3552 3553 // It is always safe to classify this as an integer type up to i64 that 3554 // isn't larger than the structure. 3555 return llvm::IntegerType::get(getVMContext(), 3556 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3557 } 3558 3559 3560 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3561 /// be used as elements of a two register pair to pass or return, return a 3562 /// first class aggregate to represent them. For example, if the low part of 3563 /// a by-value argument should be passed as i32* and the high part as float, 3564 /// return {i32*, float}. 3565 static llvm::Type * 3566 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3567 const llvm::DataLayout &TD) { 3568 // In order to correctly satisfy the ABI, we need to the high part to start 3569 // at offset 8. If the high and low parts we inferred are both 4-byte types 3570 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3571 // the second element at offset 8. Check for this: 3572 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3573 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3574 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3575 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3576 3577 // To handle this, we have to increase the size of the low part so that the 3578 // second element will start at an 8 byte offset. We can't increase the size 3579 // of the second element because it might make us access off the end of the 3580 // struct. 3581 if (HiStart != 8) { 3582 // There are usually two sorts of types the ABI generation code can produce 3583 // for the low part of a pair that aren't 8 bytes in size: half, float or 3584 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3585 // NaCl). 3586 // Promote these to a larger type. 3587 if (Lo->isHalfTy() || Lo->isFloatTy()) 3588 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3589 else { 3590 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3591 && "Invalid/unknown lo type"); 3592 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3593 } 3594 } 3595 3596 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3597 3598 // Verify that the second element is at an 8-byte offset. 3599 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3600 "Invalid x86-64 argument pair!"); 3601 return Result; 3602 } 3603 3604 ABIArgInfo X86_64ABIInfo:: 3605 classifyReturnType(QualType RetTy) const { 3606 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3607 // classification algorithm. 3608 X86_64ABIInfo::Class Lo, Hi; 3609 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3610 3611 // Check some invariants. 3612 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3613 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3614 3615 llvm::Type *ResType = nullptr; 3616 switch (Lo) { 3617 case NoClass: 3618 if (Hi == NoClass) 3619 return ABIArgInfo::getIgnore(); 3620 // If the low part is just padding, it takes no register, leave ResType 3621 // null. 3622 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3623 "Unknown missing lo part"); 3624 break; 3625 3626 case SSEUp: 3627 case X87Up: 3628 llvm_unreachable("Invalid classification for lo word."); 3629 3630 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3631 // hidden argument. 3632 case Memory: 3633 return getIndirectReturnResult(RetTy); 3634 3635 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3636 // available register of the sequence %rax, %rdx is used. 3637 case Integer: 3638 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3639 3640 // If we have a sign or zero extended integer, make sure to return Extend 3641 // so that the parameter gets the right LLVM IR attributes. 3642 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3643 // Treat an enum type as its underlying type. 3644 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3645 RetTy = EnumTy->getDecl()->getIntegerType(); 3646 3647 if (RetTy->isIntegralOrEnumerationType() && 3648 isPromotableIntegerTypeForABI(RetTy)) 3649 return ABIArgInfo::getExtend(RetTy); 3650 } 3651 break; 3652 3653 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3654 // available SSE register of the sequence %xmm0, %xmm1 is used. 3655 case SSE: 3656 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3657 break; 3658 3659 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3660 // returned on the X87 stack in %st0 as 80-bit x87 number. 3661 case X87: 3662 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3663 break; 3664 3665 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3666 // part of the value is returned in %st0 and the imaginary part in 3667 // %st1. 3668 case ComplexX87: 3669 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3670 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3671 llvm::Type::getX86_FP80Ty(getVMContext())); 3672 break; 3673 } 3674 3675 llvm::Type *HighPart = nullptr; 3676 switch (Hi) { 3677 // Memory was handled previously and X87 should 3678 // never occur as a hi class. 3679 case Memory: 3680 case X87: 3681 llvm_unreachable("Invalid classification for hi word."); 3682 3683 case ComplexX87: // Previously handled. 3684 case NoClass: 3685 break; 3686 3687 case Integer: 3688 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3689 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3690 return ABIArgInfo::getDirect(HighPart, 8); 3691 break; 3692 case SSE: 3693 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3694 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3695 return ABIArgInfo::getDirect(HighPart, 8); 3696 break; 3697 3698 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3699 // is passed in the next available eightbyte chunk if the last used 3700 // vector register. 3701 // 3702 // SSEUP should always be preceded by SSE, just widen. 3703 case SSEUp: 3704 assert(Lo == SSE && "Unexpected SSEUp classification."); 3705 ResType = GetByteVectorType(RetTy); 3706 break; 3707 3708 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3709 // returned together with the previous X87 value in %st0. 3710 case X87Up: 3711 // If X87Up is preceded by X87, we don't need to do 3712 // anything. However, in some cases with unions it may not be 3713 // preceded by X87. In such situations we follow gcc and pass the 3714 // extra bits in an SSE reg. 3715 if (Lo != X87) { 3716 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3717 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3718 return ABIArgInfo::getDirect(HighPart, 8); 3719 } 3720 break; 3721 } 3722 3723 // If a high part was specified, merge it together with the low part. It is 3724 // known to pass in the high eightbyte of the result. We do this by forming a 3725 // first class struct aggregate with the high and low part: {low, high} 3726 if (HighPart) 3727 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3728 3729 return ABIArgInfo::getDirect(ResType); 3730 } 3731 3732 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 3733 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 3734 bool isNamedArg) 3735 const 3736 { 3737 Ty = useFirstFieldIfTransparentUnion(Ty); 3738 3739 X86_64ABIInfo::Class Lo, Hi; 3740 classify(Ty, 0, Lo, Hi, isNamedArg); 3741 3742 // Check some invariants. 3743 // FIXME: Enforce these by construction. 3744 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3745 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3746 3747 neededInt = 0; 3748 neededSSE = 0; 3749 llvm::Type *ResType = nullptr; 3750 switch (Lo) { 3751 case NoClass: 3752 if (Hi == NoClass) 3753 return ABIArgInfo::getIgnore(); 3754 // If the low part is just padding, it takes no register, leave ResType 3755 // null. 3756 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3757 "Unknown missing lo part"); 3758 break; 3759 3760 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3761 // on the stack. 3762 case Memory: 3763 3764 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3765 // COMPLEX_X87, it is passed in memory. 3766 case X87: 3767 case ComplexX87: 3768 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3769 ++neededInt; 3770 return getIndirectResult(Ty, freeIntRegs); 3771 3772 case SSEUp: 3773 case X87Up: 3774 llvm_unreachable("Invalid classification for lo word."); 3775 3776 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3777 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3778 // and %r9 is used. 3779 case Integer: 3780 ++neededInt; 3781 3782 // Pick an 8-byte type based on the preferred type. 3783 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3784 3785 // If we have a sign or zero extended integer, make sure to return Extend 3786 // so that the parameter gets the right LLVM IR attributes. 3787 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3788 // Treat an enum type as its underlying type. 3789 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3790 Ty = EnumTy->getDecl()->getIntegerType(); 3791 3792 if (Ty->isIntegralOrEnumerationType() && 3793 isPromotableIntegerTypeForABI(Ty)) 3794 return ABIArgInfo::getExtend(Ty); 3795 } 3796 3797 break; 3798 3799 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3800 // available SSE register is used, the registers are taken in the 3801 // order from %xmm0 to %xmm7. 3802 case SSE: { 3803 llvm::Type *IRType = CGT.ConvertType(Ty); 3804 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3805 ++neededSSE; 3806 break; 3807 } 3808 } 3809 3810 llvm::Type *HighPart = nullptr; 3811 switch (Hi) { 3812 // Memory was handled previously, ComplexX87 and X87 should 3813 // never occur as hi classes, and X87Up must be preceded by X87, 3814 // which is passed in memory. 3815 case Memory: 3816 case X87: 3817 case ComplexX87: 3818 llvm_unreachable("Invalid classification for hi word."); 3819 3820 case NoClass: break; 3821 3822 case Integer: 3823 ++neededInt; 3824 // Pick an 8-byte type based on the preferred type. 3825 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3826 3827 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3828 return ABIArgInfo::getDirect(HighPart, 8); 3829 break; 3830 3831 // X87Up generally doesn't occur here (long double is passed in 3832 // memory), except in situations involving unions. 3833 case X87Up: 3834 case SSE: 3835 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3836 3837 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3838 return ABIArgInfo::getDirect(HighPart, 8); 3839 3840 ++neededSSE; 3841 break; 3842 3843 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3844 // eightbyte is passed in the upper half of the last used SSE 3845 // register. This only happens when 128-bit vectors are passed. 3846 case SSEUp: 3847 assert(Lo == SSE && "Unexpected SSEUp classification"); 3848 ResType = GetByteVectorType(Ty); 3849 break; 3850 } 3851 3852 // If a high part was specified, merge it together with the low part. It is 3853 // known to pass in the high eightbyte of the result. We do this by forming a 3854 // first class struct aggregate with the high and low part: {low, high} 3855 if (HighPart) 3856 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3857 3858 return ABIArgInfo::getDirect(ResType); 3859 } 3860 3861 ABIArgInfo 3862 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3863 unsigned &NeededSSE) const { 3864 auto RT = Ty->getAs<RecordType>(); 3865 assert(RT && "classifyRegCallStructType only valid with struct types"); 3866 3867 if (RT->getDecl()->hasFlexibleArrayMember()) 3868 return getIndirectReturnResult(Ty); 3869 3870 // Sum up bases 3871 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3872 if (CXXRD->isDynamicClass()) { 3873 NeededInt = NeededSSE = 0; 3874 return getIndirectReturnResult(Ty); 3875 } 3876 3877 for (const auto &I : CXXRD->bases()) 3878 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) 3879 .isIndirect()) { 3880 NeededInt = NeededSSE = 0; 3881 return getIndirectReturnResult(Ty); 3882 } 3883 } 3884 3885 // Sum up members 3886 for (const auto *FD : RT->getDecl()->fields()) { 3887 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { 3888 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) 3889 .isIndirect()) { 3890 NeededInt = NeededSSE = 0; 3891 return getIndirectReturnResult(Ty); 3892 } 3893 } else { 3894 unsigned LocalNeededInt, LocalNeededSSE; 3895 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, 3896 LocalNeededSSE, true) 3897 .isIndirect()) { 3898 NeededInt = NeededSSE = 0; 3899 return getIndirectReturnResult(Ty); 3900 } 3901 NeededInt += LocalNeededInt; 3902 NeededSSE += LocalNeededSSE; 3903 } 3904 } 3905 3906 return ABIArgInfo::getDirect(); 3907 } 3908 3909 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, 3910 unsigned &NeededInt, 3911 unsigned &NeededSSE) const { 3912 3913 NeededInt = 0; 3914 NeededSSE = 0; 3915 3916 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); 3917 } 3918 3919 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3920 3921 const unsigned CallingConv = FI.getCallingConvention(); 3922 // It is possible to force Win64 calling convention on any x86_64 target by 3923 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3924 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3925 if (CallingConv == llvm::CallingConv::Win64) { 3926 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); 3927 Win64ABIInfo.computeInfo(FI); 3928 return; 3929 } 3930 3931 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3932 3933 // Keep track of the number of assigned registers. 3934 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3935 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3936 unsigned NeededInt, NeededSSE; 3937 3938 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3939 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3940 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3941 FI.getReturnInfo() = 3942 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); 3943 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3944 FreeIntRegs -= NeededInt; 3945 FreeSSERegs -= NeededSSE; 3946 } else { 3947 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3948 } 3949 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() && 3950 getContext().getCanonicalType(FI.getReturnType() 3951 ->getAs<ComplexType>() 3952 ->getElementType()) == 3953 getContext().LongDoubleTy) 3954 // Complex Long Double Type is passed in Memory when Regcall 3955 // calling convention is used. 3956 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3957 else 3958 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3959 } 3960 3961 // If the return value is indirect, then the hidden argument is consuming one 3962 // integer register. 3963 if (FI.getReturnInfo().isIndirect()) 3964 --FreeIntRegs; 3965 3966 // The chain argument effectively gives us another free register. 3967 if (FI.isChainCall()) 3968 ++FreeIntRegs; 3969 3970 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 3971 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 3972 // get assigned (in left-to-right order) for passing as follows... 3973 unsigned ArgNo = 0; 3974 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3975 it != ie; ++it, ++ArgNo) { 3976 bool IsNamedArg = ArgNo < NumRequiredArgs; 3977 3978 if (IsRegCall && it->type->isStructureOrClassType()) 3979 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); 3980 else 3981 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 3982 NeededSSE, IsNamedArg); 3983 3984 // AMD64-ABI 3.2.3p3: If there are no registers available for any 3985 // eightbyte of an argument, the whole argument is passed on the 3986 // stack. If registers have already been assigned for some 3987 // eightbytes of such an argument, the assignments get reverted. 3988 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3989 FreeIntRegs -= NeededInt; 3990 FreeSSERegs -= NeededSSE; 3991 } else { 3992 it->info = getIndirectResult(it->type, FreeIntRegs); 3993 } 3994 } 3995 } 3996 3997 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 3998 Address VAListAddr, QualType Ty) { 3999 Address overflow_arg_area_p = 4000 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 4001 llvm::Value *overflow_arg_area = 4002 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 4003 4004 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 4005 // byte boundary if alignment needed by type exceeds 8 byte boundary. 4006 // It isn't stated explicitly in the standard, but in practice we use 4007 // alignment greater than 16 where necessary. 4008 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4009 if (Align > CharUnits::fromQuantity(8)) { 4010 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 4011 Align); 4012 } 4013 4014 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 4015 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4016 llvm::Value *Res = 4017 CGF.Builder.CreateBitCast(overflow_arg_area, 4018 llvm::PointerType::getUnqual(LTy)); 4019 4020 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 4021 // l->overflow_arg_area + sizeof(type). 4022 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 4023 // an 8 byte boundary. 4024 4025 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 4026 llvm::Value *Offset = 4027 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 4028 overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area, 4029 Offset, "overflow_arg_area.next"); 4030 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 4031 4032 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 4033 return Address(Res, Align); 4034 } 4035 4036 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4037 QualType Ty) const { 4038 // Assume that va_list type is correct; should be pointer to LLVM type: 4039 // struct { 4040 // i32 gp_offset; 4041 // i32 fp_offset; 4042 // i8* overflow_arg_area; 4043 // i8* reg_save_area; 4044 // }; 4045 unsigned neededInt, neededSSE; 4046 4047 Ty = getContext().getCanonicalType(Ty); 4048 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 4049 /*isNamedArg*/false); 4050 4051 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 4052 // in the registers. If not go to step 7. 4053 if (!neededInt && !neededSSE) 4054 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4055 4056 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 4057 // general purpose registers needed to pass type and num_fp to hold 4058 // the number of floating point registers needed. 4059 4060 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 4061 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 4062 // l->fp_offset > 304 - num_fp * 16 go to step 7. 4063 // 4064 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 4065 // register save space). 4066 4067 llvm::Value *InRegs = nullptr; 4068 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 4069 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 4070 if (neededInt) { 4071 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 4072 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 4073 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 4074 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 4075 } 4076 4077 if (neededSSE) { 4078 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 4079 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 4080 llvm::Value *FitsInFP = 4081 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 4082 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 4083 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 4084 } 4085 4086 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4087 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 4088 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4089 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 4090 4091 // Emit code to load the value if it was passed in registers. 4092 4093 CGF.EmitBlock(InRegBlock); 4094 4095 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 4096 // an offset of l->gp_offset and/or l->fp_offset. This may require 4097 // copying to a temporary location in case the parameter is passed 4098 // in different register classes or requires an alignment greater 4099 // than 8 for general purpose registers and 16 for XMM registers. 4100 // 4101 // FIXME: This really results in shameful code when we end up needing to 4102 // collect arguments from different places; often what should result in a 4103 // simple assembling of a structure from scattered addresses has many more 4104 // loads than necessary. Can we clean this up? 4105 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4106 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 4107 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 4108 4109 Address RegAddr = Address::invalid(); 4110 if (neededInt && neededSSE) { 4111 // FIXME: Cleanup. 4112 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 4113 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 4114 Address Tmp = CGF.CreateMemTemp(Ty); 4115 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4116 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 4117 llvm::Type *TyLo = ST->getElementType(0); 4118 llvm::Type *TyHi = ST->getElementType(1); 4119 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 4120 "Unexpected ABI info for mixed regs"); 4121 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 4122 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 4123 llvm::Value *GPAddr = 4124 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset); 4125 llvm::Value *FPAddr = 4126 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset); 4127 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 4128 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 4129 4130 // Copy the first element. 4131 // FIXME: Our choice of alignment here and below is probably pessimistic. 4132 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 4133 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 4134 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 4135 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4136 4137 // Copy the second element. 4138 V = CGF.Builder.CreateAlignedLoad( 4139 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 4140 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 4141 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4142 4143 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4144 } else if (neededInt) { 4145 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset), 4146 CharUnits::fromQuantity(8)); 4147 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4148 4149 // Copy to a temporary if necessary to ensure the appropriate alignment. 4150 auto TInfo = getContext().getTypeInfoInChars(Ty); 4151 uint64_t TySize = TInfo.Width.getQuantity(); 4152 CharUnits TyAlign = TInfo.Align; 4153 4154 // Copy into a temporary if the type is more aligned than the 4155 // register save area. 4156 if (TyAlign.getQuantity() > 8) { 4157 Address Tmp = CGF.CreateMemTemp(Ty); 4158 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 4159 RegAddr = Tmp; 4160 } 4161 4162 } else if (neededSSE == 1) { 4163 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset), 4164 CharUnits::fromQuantity(16)); 4165 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4166 } else { 4167 assert(neededSSE == 2 && "Invalid number of needed registers!"); 4168 // SSE registers are spaced 16 bytes apart in the register save 4169 // area, we need to collect the two eightbytes together. 4170 // The ABI isn't explicit about this, but it seems reasonable 4171 // to assume that the slots are 16-byte aligned, since the stack is 4172 // naturally 16-byte aligned and the prologue is expected to store 4173 // all the SSE registers to the RSA. 4174 Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, 4175 fp_offset), 4176 CharUnits::fromQuantity(16)); 4177 Address RegAddrHi = 4178 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 4179 CharUnits::fromQuantity(16)); 4180 llvm::Type *ST = AI.canHaveCoerceToType() 4181 ? AI.getCoerceToType() 4182 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 4183 llvm::Value *V; 4184 Address Tmp = CGF.CreateMemTemp(Ty); 4185 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4186 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4187 RegAddrLo, ST->getStructElementType(0))); 4188 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4189 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4190 RegAddrHi, ST->getStructElementType(1))); 4191 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4192 4193 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4194 } 4195 4196 // AMD64-ABI 3.5.7p5: Step 5. Set: 4197 // l->gp_offset = l->gp_offset + num_gp * 8 4198 // l->fp_offset = l->fp_offset + num_fp * 16. 4199 if (neededInt) { 4200 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 4201 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 4202 gp_offset_p); 4203 } 4204 if (neededSSE) { 4205 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 4206 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 4207 fp_offset_p); 4208 } 4209 CGF.EmitBranch(ContBlock); 4210 4211 // Emit code to load the value if it was passed in memory. 4212 4213 CGF.EmitBlock(InMemBlock); 4214 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4215 4216 // Return the appropriate result. 4217 4218 CGF.EmitBlock(ContBlock); 4219 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 4220 "vaarg.addr"); 4221 return ResAddr; 4222 } 4223 4224 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 4225 QualType Ty) const { 4226 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4227 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4228 uint64_t Width = getContext().getTypeSize(Ty); 4229 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4230 4231 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4232 CGF.getContext().getTypeInfoInChars(Ty), 4233 CharUnits::fromQuantity(8), 4234 /*allowHigherAlign*/ false); 4235 } 4236 4237 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall( 4238 QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo ¤t) const { 4239 const Type *Base = nullptr; 4240 uint64_t NumElts = 0; 4241 4242 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 4243 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 4244 FreeSSERegs -= NumElts; 4245 return getDirectX86Hva(); 4246 } 4247 return current; 4248 } 4249 4250 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 4251 bool IsReturnType, bool IsVectorCall, 4252 bool IsRegCall) const { 4253 4254 if (Ty->isVoidType()) 4255 return ABIArgInfo::getIgnore(); 4256 4257 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4258 Ty = EnumTy->getDecl()->getIntegerType(); 4259 4260 TypeInfo Info = getContext().getTypeInfo(Ty); 4261 uint64_t Width = Info.Width; 4262 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 4263 4264 const RecordType *RT = Ty->getAs<RecordType>(); 4265 if (RT) { 4266 if (!IsReturnType) { 4267 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 4268 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4269 } 4270 4271 if (RT->getDecl()->hasFlexibleArrayMember()) 4272 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4273 4274 } 4275 4276 const Type *Base = nullptr; 4277 uint64_t NumElts = 0; 4278 // vectorcall adds the concept of a homogenous vector aggregate, similar to 4279 // other targets. 4280 if ((IsVectorCall || IsRegCall) && 4281 isHomogeneousAggregate(Ty, Base, NumElts)) { 4282 if (IsRegCall) { 4283 if (FreeSSERegs >= NumElts) { 4284 FreeSSERegs -= NumElts; 4285 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 4286 return ABIArgInfo::getDirect(); 4287 return ABIArgInfo::getExpand(); 4288 } 4289 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4290 } else if (IsVectorCall) { 4291 if (FreeSSERegs >= NumElts && 4292 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 4293 FreeSSERegs -= NumElts; 4294 return ABIArgInfo::getDirect(); 4295 } else if (IsReturnType) { 4296 return ABIArgInfo::getExpand(); 4297 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 4298 // HVAs are delayed and reclassified in the 2nd step. 4299 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4300 } 4301 } 4302 } 4303 4304 if (Ty->isMemberPointerType()) { 4305 // If the member pointer is represented by an LLVM int or ptr, pass it 4306 // directly. 4307 llvm::Type *LLTy = CGT.ConvertType(Ty); 4308 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 4309 return ABIArgInfo::getDirect(); 4310 } 4311 4312 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 4313 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4314 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4315 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 4316 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4317 4318 // Otherwise, coerce it to a small integer. 4319 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 4320 } 4321 4322 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4323 switch (BT->getKind()) { 4324 case BuiltinType::Bool: 4325 // Bool type is always extended to the ABI, other builtin types are not 4326 // extended. 4327 return ABIArgInfo::getExtend(Ty); 4328 4329 case BuiltinType::LongDouble: 4330 // Mingw64 GCC uses the old 80 bit extended precision floating point 4331 // unit. It passes them indirectly through memory. 4332 if (IsMingw64) { 4333 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 4334 if (LDF == &llvm::APFloat::x87DoubleExtended()) 4335 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4336 } 4337 break; 4338 4339 case BuiltinType::Int128: 4340 case BuiltinType::UInt128: 4341 // If it's a parameter type, the normal ABI rule is that arguments larger 4342 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 4343 // even though it isn't particularly efficient. 4344 if (!IsReturnType) 4345 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4346 4347 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 4348 // Clang matches them for compatibility. 4349 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 4350 llvm::Type::getInt64Ty(getVMContext()), 2)); 4351 4352 default: 4353 break; 4354 } 4355 } 4356 4357 if (Ty->isExtIntType()) { 4358 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4359 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4360 // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes 4361 // anyway as long is it fits in them, so we don't have to check the power of 4362 // 2. 4363 if (Width <= 64) 4364 return ABIArgInfo::getDirect(); 4365 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4366 } 4367 4368 return ABIArgInfo::getDirect(); 4369 } 4370 4371 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4372 const unsigned CC = FI.getCallingConvention(); 4373 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; 4374 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; 4375 4376 // If __attribute__((sysv_abi)) is in use, use the SysV argument 4377 // classification rules. 4378 if (CC == llvm::CallingConv::X86_64_SysV) { 4379 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); 4380 SysVABIInfo.computeInfo(FI); 4381 return; 4382 } 4383 4384 unsigned FreeSSERegs = 0; 4385 if (IsVectorCall) { 4386 // We can use up to 4 SSE return registers with vectorcall. 4387 FreeSSERegs = 4; 4388 } else if (IsRegCall) { 4389 // RegCall gives us 16 SSE registers. 4390 FreeSSERegs = 16; 4391 } 4392 4393 if (!getCXXABI().classifyReturnType(FI)) 4394 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, 4395 IsVectorCall, IsRegCall); 4396 4397 if (IsVectorCall) { 4398 // We can use up to 6 SSE register parameters with vectorcall. 4399 FreeSSERegs = 6; 4400 } else if (IsRegCall) { 4401 // RegCall gives us 16 SSE registers, we can reuse the return registers. 4402 FreeSSERegs = 16; 4403 } 4404 4405 unsigned ArgNum = 0; 4406 unsigned ZeroSSERegs = 0; 4407 for (auto &I : FI.arguments()) { 4408 // Vectorcall in x64 only permits the first 6 arguments to be passed as 4409 // XMM/YMM registers. After the sixth argument, pretend no vector 4410 // registers are left. 4411 unsigned *MaybeFreeSSERegs = 4412 (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs; 4413 I.info = 4414 classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall); 4415 ++ArgNum; 4416 } 4417 4418 if (IsVectorCall) { 4419 // For vectorcall, assign aggregate HVAs to any free vector registers in a 4420 // second pass. 4421 for (auto &I : FI.arguments()) 4422 I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info); 4423 } 4424 } 4425 4426 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4427 QualType Ty) const { 4428 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4429 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4430 uint64_t Width = getContext().getTypeSize(Ty); 4431 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4432 4433 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4434 CGF.getContext().getTypeInfoInChars(Ty), 4435 CharUnits::fromQuantity(8), 4436 /*allowHigherAlign*/ false); 4437 } 4438 4439 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4440 llvm::Value *Address, bool Is64Bit, 4441 bool IsAIX) { 4442 // This is calculated from the LLVM and GCC tables and verified 4443 // against gcc output. AFAIK all PPC ABIs use the same encoding. 4444 4445 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4446 4447 llvm::IntegerType *i8 = CGF.Int8Ty; 4448 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4449 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4450 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4451 4452 // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers 4453 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31); 4454 4455 // 32-63: fp0-31, the 8-byte floating-point registers 4456 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4457 4458 // 64-67 are various 4-byte or 8-byte special-purpose registers: 4459 // 64: mq 4460 // 65: lr 4461 // 66: ctr 4462 // 67: ap 4463 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67); 4464 4465 // 68-76 are various 4-byte special-purpose registers: 4466 // 68-75 cr0-7 4467 // 76: xer 4468 AssignToArrayRange(Builder, Address, Four8, 68, 76); 4469 4470 // 77-108: v0-31, the 16-byte vector registers 4471 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4472 4473 // 109: vrsave 4474 // 110: vscr 4475 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110); 4476 4477 // AIX does not utilize the rest of the registers. 4478 if (IsAIX) 4479 return false; 4480 4481 // 111: spe_acc 4482 // 112: spefscr 4483 // 113: sfp 4484 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113); 4485 4486 if (!Is64Bit) 4487 return false; 4488 4489 // TODO: Need to verify if these registers are used on 64 bit AIX with Power8 4490 // or above CPU. 4491 // 64-bit only registers: 4492 // 114: tfhar 4493 // 115: tfiar 4494 // 116: texasr 4495 AssignToArrayRange(Builder, Address, Eight8, 114, 116); 4496 4497 return false; 4498 } 4499 4500 // AIX 4501 namespace { 4502 /// AIXABIInfo - The AIX XCOFF ABI information. 4503 class AIXABIInfo : public ABIInfo { 4504 const bool Is64Bit; 4505 const unsigned PtrByteSize; 4506 CharUnits getParamTypeAlignment(QualType Ty) const; 4507 4508 public: 4509 AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4510 : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {} 4511 4512 bool isPromotableTypeForABI(QualType Ty) const; 4513 4514 ABIArgInfo classifyReturnType(QualType RetTy) const; 4515 ABIArgInfo classifyArgumentType(QualType Ty) const; 4516 4517 void computeInfo(CGFunctionInfo &FI) const override { 4518 if (!getCXXABI().classifyReturnType(FI)) 4519 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4520 4521 for (auto &I : FI.arguments()) 4522 I.info = classifyArgumentType(I.type); 4523 } 4524 4525 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4526 QualType Ty) const override; 4527 }; 4528 4529 class AIXTargetCodeGenInfo : public TargetCodeGenInfo { 4530 const bool Is64Bit; 4531 4532 public: 4533 AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4534 : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)), 4535 Is64Bit(Is64Bit) {} 4536 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4537 return 1; // r1 is the dedicated stack pointer 4538 } 4539 4540 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4541 llvm::Value *Address) const override; 4542 }; 4543 } // namespace 4544 4545 // Return true if the ABI requires Ty to be passed sign- or zero- 4546 // extended to 32/64 bits. 4547 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const { 4548 // Treat an enum type as its underlying type. 4549 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4550 Ty = EnumTy->getDecl()->getIntegerType(); 4551 4552 // Promotable integer types are required to be promoted by the ABI. 4553 if (Ty->isPromotableIntegerType()) 4554 return true; 4555 4556 if (!Is64Bit) 4557 return false; 4558 4559 // For 64 bit mode, in addition to the usual promotable integer types, we also 4560 // need to extend all 32-bit types, since the ABI requires promotion to 64 4561 // bits. 4562 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4563 switch (BT->getKind()) { 4564 case BuiltinType::Int: 4565 case BuiltinType::UInt: 4566 return true; 4567 default: 4568 break; 4569 } 4570 4571 return false; 4572 } 4573 4574 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const { 4575 if (RetTy->isAnyComplexType()) 4576 return ABIArgInfo::getDirect(); 4577 4578 if (RetTy->isVectorType()) 4579 return ABIArgInfo::getDirect(); 4580 4581 if (RetTy->isVoidType()) 4582 return ABIArgInfo::getIgnore(); 4583 4584 if (isAggregateTypeForABI(RetTy)) 4585 return getNaturalAlignIndirect(RetTy); 4586 4587 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 4588 : ABIArgInfo::getDirect()); 4589 } 4590 4591 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const { 4592 Ty = useFirstFieldIfTransparentUnion(Ty); 4593 4594 if (Ty->isAnyComplexType()) 4595 return ABIArgInfo::getDirect(); 4596 4597 if (Ty->isVectorType()) 4598 return ABIArgInfo::getDirect(); 4599 4600 if (isAggregateTypeForABI(Ty)) { 4601 // Records with non-trivial destructors/copy-constructors should not be 4602 // passed by value. 4603 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4604 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4605 4606 CharUnits CCAlign = getParamTypeAlignment(Ty); 4607 CharUnits TyAlign = getContext().getTypeAlignInChars(Ty); 4608 4609 return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true, 4610 /*Realign*/ TyAlign > CCAlign); 4611 } 4612 4613 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 4614 : ABIArgInfo::getDirect()); 4615 } 4616 4617 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const { 4618 // Complex types are passed just like their elements. 4619 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4620 Ty = CTy->getElementType(); 4621 4622 if (Ty->isVectorType()) 4623 return CharUnits::fromQuantity(16); 4624 4625 // If the structure contains a vector type, the alignment is 16. 4626 if (isRecordWithSIMDVectorType(getContext(), Ty)) 4627 return CharUnits::fromQuantity(16); 4628 4629 return CharUnits::fromQuantity(PtrByteSize); 4630 } 4631 4632 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4633 QualType Ty) const { 4634 if (Ty->isAnyComplexType()) 4635 llvm::report_fatal_error("complex type is not supported on AIX yet"); 4636 4637 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 4638 TypeInfo.Align = getParamTypeAlignment(Ty); 4639 4640 CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize); 4641 4642 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo, 4643 SlotSize, /*AllowHigher*/ true); 4644 } 4645 4646 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable( 4647 CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { 4648 return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true); 4649 } 4650 4651 // PowerPC-32 4652 namespace { 4653 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. 4654 class PPC32_SVR4_ABIInfo : public DefaultABIInfo { 4655 bool IsSoftFloatABI; 4656 bool IsRetSmallStructInRegABI; 4657 4658 CharUnits getParamTypeAlignment(QualType Ty) const; 4659 4660 public: 4661 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI, 4662 bool RetSmallStructInRegABI) 4663 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI), 4664 IsRetSmallStructInRegABI(RetSmallStructInRegABI) {} 4665 4666 ABIArgInfo classifyReturnType(QualType RetTy) const; 4667 4668 void computeInfo(CGFunctionInfo &FI) const override { 4669 if (!getCXXABI().classifyReturnType(FI)) 4670 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4671 for (auto &I : FI.arguments()) 4672 I.info = classifyArgumentType(I.type); 4673 } 4674 4675 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4676 QualType Ty) const override; 4677 }; 4678 4679 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { 4680 public: 4681 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI, 4682 bool RetSmallStructInRegABI) 4683 : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>( 4684 CGT, SoftFloatABI, RetSmallStructInRegABI)) {} 4685 4686 static bool isStructReturnInRegABI(const llvm::Triple &Triple, 4687 const CodeGenOptions &Opts); 4688 4689 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4690 // This is recovered from gcc output. 4691 return 1; // r1 is the dedicated stack pointer 4692 } 4693 4694 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4695 llvm::Value *Address) const override; 4696 }; 4697 } 4698 4699 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4700 // Complex types are passed just like their elements. 4701 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4702 Ty = CTy->getElementType(); 4703 4704 if (Ty->isVectorType()) 4705 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 4706 : 4); 4707 4708 // For single-element float/vector structs, we consider the whole type 4709 // to have the same alignment requirements as its single element. 4710 const Type *AlignTy = nullptr; 4711 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { 4712 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4713 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 4714 (BT && BT->isFloatingPoint())) 4715 AlignTy = EltType; 4716 } 4717 4718 if (AlignTy) 4719 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); 4720 return CharUnits::fromQuantity(4); 4721 } 4722 4723 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4724 uint64_t Size; 4725 4726 // -msvr4-struct-return puts small aggregates in GPR3 and GPR4. 4727 if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI && 4728 (Size = getContext().getTypeSize(RetTy)) <= 64) { 4729 // System V ABI (1995), page 3-22, specified: 4730 // > A structure or union whose size is less than or equal to 8 bytes 4731 // > shall be returned in r3 and r4, as if it were first stored in the 4732 // > 8-byte aligned memory area and then the low addressed word were 4733 // > loaded into r3 and the high-addressed word into r4. Bits beyond 4734 // > the last member of the structure or union are not defined. 4735 // 4736 // GCC for big-endian PPC32 inserts the pad before the first member, 4737 // not "beyond the last member" of the struct. To stay compatible 4738 // with GCC, we coerce the struct to an integer of the same size. 4739 // LLVM will extend it and return i32 in r3, or i64 in r3:r4. 4740 if (Size == 0) 4741 return ABIArgInfo::getIgnore(); 4742 else { 4743 llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size); 4744 return ABIArgInfo::getDirect(CoerceTy); 4745 } 4746 } 4747 4748 return DefaultABIInfo::classifyReturnType(RetTy); 4749 } 4750 4751 // TODO: this implementation is now likely redundant with 4752 // DefaultABIInfo::EmitVAArg. 4753 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, 4754 QualType Ty) const { 4755 if (getTarget().getTriple().isOSDarwin()) { 4756 auto TI = getContext().getTypeInfoInChars(Ty); 4757 TI.Align = getParamTypeAlignment(Ty); 4758 4759 CharUnits SlotSize = CharUnits::fromQuantity(4); 4760 return emitVoidPtrVAArg(CGF, VAList, Ty, 4761 classifyArgumentType(Ty).isIndirect(), TI, SlotSize, 4762 /*AllowHigherAlign=*/true); 4763 } 4764 4765 const unsigned OverflowLimit = 8; 4766 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4767 // TODO: Implement this. For now ignore. 4768 (void)CTy; 4769 return Address::invalid(); // FIXME? 4770 } 4771 4772 // struct __va_list_tag { 4773 // unsigned char gpr; 4774 // unsigned char fpr; 4775 // unsigned short reserved; 4776 // void *overflow_arg_area; 4777 // void *reg_save_area; 4778 // }; 4779 4780 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; 4781 bool isInt = !Ty->isFloatingType(); 4782 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; 4783 4784 // All aggregates are passed indirectly? That doesn't seem consistent 4785 // with the argument-lowering code. 4786 bool isIndirect = isAggregateTypeForABI(Ty); 4787 4788 CGBuilderTy &Builder = CGF.Builder; 4789 4790 // The calling convention either uses 1-2 GPRs or 1 FPR. 4791 Address NumRegsAddr = Address::invalid(); 4792 if (isInt || IsSoftFloatABI) { 4793 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); 4794 } else { 4795 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); 4796 } 4797 4798 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); 4799 4800 // "Align" the register count when TY is i64. 4801 if (isI64 || (isF64 && IsSoftFloatABI)) { 4802 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); 4803 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); 4804 } 4805 4806 llvm::Value *CC = 4807 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); 4808 4809 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); 4810 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); 4811 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 4812 4813 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); 4814 4815 llvm::Type *DirectTy = CGF.ConvertType(Ty); 4816 if (isIndirect) DirectTy = DirectTy->getPointerTo(0); 4817 4818 // Case 1: consume registers. 4819 Address RegAddr = Address::invalid(); 4820 { 4821 CGF.EmitBlock(UsingRegs); 4822 4823 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); 4824 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), 4825 CharUnits::fromQuantity(8)); 4826 assert(RegAddr.getElementType() == CGF.Int8Ty); 4827 4828 // Floating-point registers start after the general-purpose registers. 4829 if (!(isInt || IsSoftFloatABI)) { 4830 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, 4831 CharUnits::fromQuantity(32)); 4832 } 4833 4834 // Get the address of the saved value by scaling the number of 4835 // registers we've used by the number of 4836 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); 4837 llvm::Value *RegOffset = 4838 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); 4839 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, 4840 RegAddr.getPointer(), RegOffset), 4841 RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); 4842 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); 4843 4844 // Increase the used-register count. 4845 NumRegs = 4846 Builder.CreateAdd(NumRegs, 4847 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); 4848 Builder.CreateStore(NumRegs, NumRegsAddr); 4849 4850 CGF.EmitBranch(Cont); 4851 } 4852 4853 // Case 2: consume space in the overflow area. 4854 Address MemAddr = Address::invalid(); 4855 { 4856 CGF.EmitBlock(UsingOverflow); 4857 4858 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); 4859 4860 // Everything in the overflow area is rounded up to a size of at least 4. 4861 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); 4862 4863 CharUnits Size; 4864 if (!isIndirect) { 4865 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); 4866 Size = TypeInfo.Width.alignTo(OverflowAreaAlign); 4867 } else { 4868 Size = CGF.getPointerSize(); 4869 } 4870 4871 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); 4872 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), 4873 OverflowAreaAlign); 4874 // Round up address of argument to alignment 4875 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4876 if (Align > OverflowAreaAlign) { 4877 llvm::Value *Ptr = OverflowArea.getPointer(); 4878 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), 4879 Align); 4880 } 4881 4882 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); 4883 4884 // Increase the overflow area. 4885 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); 4886 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); 4887 CGF.EmitBranch(Cont); 4888 } 4889 4890 CGF.EmitBlock(Cont); 4891 4892 // Merge the cases with a phi. 4893 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, 4894 "vaarg.addr"); 4895 4896 // Load the pointer if the argument was passed indirectly. 4897 if (isIndirect) { 4898 Result = Address(Builder.CreateLoad(Result, "aggr"), 4899 getContext().getTypeAlignInChars(Ty)); 4900 } 4901 4902 return Result; 4903 } 4904 4905 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI( 4906 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4907 assert(Triple.isPPC32()); 4908 4909 switch (Opts.getStructReturnConvention()) { 4910 case CodeGenOptions::SRCK_Default: 4911 break; 4912 case CodeGenOptions::SRCK_OnStack: // -maix-struct-return 4913 return false; 4914 case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return 4915 return true; 4916 } 4917 4918 if (Triple.isOSBinFormatELF() && !Triple.isOSLinux()) 4919 return true; 4920 4921 return false; 4922 } 4923 4924 bool 4925 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4926 llvm::Value *Address) const { 4927 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false, 4928 /*IsAIX*/ false); 4929 } 4930 4931 // PowerPC-64 4932 4933 namespace { 4934 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 4935 class PPC64_SVR4_ABIInfo : public SwiftABIInfo { 4936 public: 4937 enum ABIKind { 4938 ELFv1 = 0, 4939 ELFv2 4940 }; 4941 4942 private: 4943 static const unsigned GPRBits = 64; 4944 ABIKind Kind; 4945 bool IsSoftFloatABI; 4946 4947 public: 4948 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, 4949 bool SoftFloatABI) 4950 : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {} 4951 4952 bool isPromotableTypeForABI(QualType Ty) const; 4953 CharUnits getParamTypeAlignment(QualType Ty) const; 4954 4955 ABIArgInfo classifyReturnType(QualType RetTy) const; 4956 ABIArgInfo classifyArgumentType(QualType Ty) const; 4957 4958 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 4959 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 4960 uint64_t Members) const override; 4961 4962 // TODO: We can add more logic to computeInfo to improve performance. 4963 // Example: For aggregate arguments that fit in a register, we could 4964 // use getDirectInReg (as is done below for structs containing a single 4965 // floating-point value) to avoid pushing them to memory on function 4966 // entry. This would require changing the logic in PPCISelLowering 4967 // when lowering the parameters in the caller and args in the callee. 4968 void computeInfo(CGFunctionInfo &FI) const override { 4969 if (!getCXXABI().classifyReturnType(FI)) 4970 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4971 for (auto &I : FI.arguments()) { 4972 // We rely on the default argument classification for the most part. 4973 // One exception: An aggregate containing a single floating-point 4974 // or vector item must be passed in a register if one is available. 4975 const Type *T = isSingleElementStruct(I.type, getContext()); 4976 if (T) { 4977 const BuiltinType *BT = T->getAs<BuiltinType>(); 4978 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) || 4979 (BT && BT->isFloatingPoint())) { 4980 QualType QT(T, 0); 4981 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 4982 continue; 4983 } 4984 } 4985 I.info = classifyArgumentType(I.type); 4986 } 4987 } 4988 4989 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4990 QualType Ty) const override; 4991 4992 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 4993 bool asReturnValue) const override { 4994 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 4995 } 4996 4997 bool isSwiftErrorInRegister() const override { 4998 return false; 4999 } 5000 }; 5001 5002 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 5003 5004 public: 5005 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, 5006 PPC64_SVR4_ABIInfo::ABIKind Kind, 5007 bool SoftFloatABI) 5008 : TargetCodeGenInfo( 5009 std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {} 5010 5011 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5012 // This is recovered from gcc output. 5013 return 1; // r1 is the dedicated stack pointer 5014 } 5015 5016 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5017 llvm::Value *Address) const override; 5018 }; 5019 5020 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 5021 public: 5022 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 5023 5024 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5025 // This is recovered from gcc output. 5026 return 1; // r1 is the dedicated stack pointer 5027 } 5028 5029 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5030 llvm::Value *Address) const override; 5031 }; 5032 5033 } 5034 5035 // Return true if the ABI requires Ty to be passed sign- or zero- 5036 // extended to 64 bits. 5037 bool 5038 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 5039 // Treat an enum type as its underlying type. 5040 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5041 Ty = EnumTy->getDecl()->getIntegerType(); 5042 5043 // Promotable integer types are required to be promoted by the ABI. 5044 if (isPromotableIntegerTypeForABI(Ty)) 5045 return true; 5046 5047 // In addition to the usual promotable integer types, we also need to 5048 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 5049 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 5050 switch (BT->getKind()) { 5051 case BuiltinType::Int: 5052 case BuiltinType::UInt: 5053 return true; 5054 default: 5055 break; 5056 } 5057 5058 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5059 if (EIT->getNumBits() < 64) 5060 return true; 5061 5062 return false; 5063 } 5064 5065 /// isAlignedParamType - Determine whether a type requires 16-byte or 5066 /// higher alignment in the parameter area. Always returns at least 8. 5067 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 5068 // Complex types are passed just like their elements. 5069 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 5070 Ty = CTy->getElementType(); 5071 5072 // Only vector types of size 16 bytes need alignment (larger types are 5073 // passed via reference, smaller types are not aligned). 5074 if (Ty->isVectorType()) { 5075 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); 5076 } else if (Ty->isRealFloatingType() && 5077 &getContext().getFloatTypeSemantics(Ty) == 5078 &llvm::APFloat::IEEEquad()) { 5079 // According to ABI document section 'Optional Save Areas': If extended 5080 // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION 5081 // format are supported, map them to a single quadword, quadword aligned. 5082 return CharUnits::fromQuantity(16); 5083 } 5084 5085 // For single-element float/vector structs, we consider the whole type 5086 // to have the same alignment requirements as its single element. 5087 const Type *AlignAsType = nullptr; 5088 const Type *EltType = isSingleElementStruct(Ty, getContext()); 5089 if (EltType) { 5090 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 5091 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 5092 (BT && BT->isFloatingPoint())) 5093 AlignAsType = EltType; 5094 } 5095 5096 // Likewise for ELFv2 homogeneous aggregates. 5097 const Type *Base = nullptr; 5098 uint64_t Members = 0; 5099 if (!AlignAsType && Kind == ELFv2 && 5100 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) 5101 AlignAsType = Base; 5102 5103 // With special case aggregates, only vector base types need alignment. 5104 if (AlignAsType) { 5105 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8); 5106 } 5107 5108 // Otherwise, we only need alignment for any aggregate type that 5109 // has an alignment requirement of >= 16 bytes. 5110 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { 5111 return CharUnits::fromQuantity(16); 5112 } 5113 5114 return CharUnits::fromQuantity(8); 5115 } 5116 5117 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous 5118 /// aggregate. Base is set to the base element type, and Members is set 5119 /// to the number of base elements. 5120 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, 5121 uint64_t &Members) const { 5122 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 5123 uint64_t NElements = AT->getSize().getZExtValue(); 5124 if (NElements == 0) 5125 return false; 5126 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) 5127 return false; 5128 Members *= NElements; 5129 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 5130 const RecordDecl *RD = RT->getDecl(); 5131 if (RD->hasFlexibleArrayMember()) 5132 return false; 5133 5134 Members = 0; 5135 5136 // If this is a C++ record, check the properties of the record such as 5137 // bases and ABI specific restrictions 5138 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 5139 if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD)) 5140 return false; 5141 5142 for (const auto &I : CXXRD->bases()) { 5143 // Ignore empty records. 5144 if (isEmptyRecord(getContext(), I.getType(), true)) 5145 continue; 5146 5147 uint64_t FldMembers; 5148 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) 5149 return false; 5150 5151 Members += FldMembers; 5152 } 5153 } 5154 5155 for (const auto *FD : RD->fields()) { 5156 // Ignore (non-zero arrays of) empty records. 5157 QualType FT = FD->getType(); 5158 while (const ConstantArrayType *AT = 5159 getContext().getAsConstantArrayType(FT)) { 5160 if (AT->getSize().getZExtValue() == 0) 5161 return false; 5162 FT = AT->getElementType(); 5163 } 5164 if (isEmptyRecord(getContext(), FT, true)) 5165 continue; 5166 5167 // For compatibility with GCC, ignore empty bitfields in C++ mode. 5168 if (getContext().getLangOpts().CPlusPlus && 5169 FD->isZeroLengthBitField(getContext())) 5170 continue; 5171 5172 uint64_t FldMembers; 5173 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) 5174 return false; 5175 5176 Members = (RD->isUnion() ? 5177 std::max(Members, FldMembers) : Members + FldMembers); 5178 } 5179 5180 if (!Base) 5181 return false; 5182 5183 // Ensure there is no padding. 5184 if (getContext().getTypeSize(Base) * Members != 5185 getContext().getTypeSize(Ty)) 5186 return false; 5187 } else { 5188 Members = 1; 5189 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 5190 Members = 2; 5191 Ty = CT->getElementType(); 5192 } 5193 5194 // Most ABIs only support float, double, and some vector type widths. 5195 if (!isHomogeneousAggregateBaseType(Ty)) 5196 return false; 5197 5198 // The base type must be the same for all members. Types that 5199 // agree in both total size and mode (float vs. vector) are 5200 // treated as being equivalent here. 5201 const Type *TyPtr = Ty.getTypePtr(); 5202 if (!Base) { 5203 Base = TyPtr; 5204 // If it's a non-power-of-2 vector, its size is already a power-of-2, 5205 // so make sure to widen it explicitly. 5206 if (const VectorType *VT = Base->getAs<VectorType>()) { 5207 QualType EltTy = VT->getElementType(); 5208 unsigned NumElements = 5209 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); 5210 Base = getContext() 5211 .getVectorType(EltTy, NumElements, VT->getVectorKind()) 5212 .getTypePtr(); 5213 } 5214 } 5215 5216 if (Base->isVectorType() != TyPtr->isVectorType() || 5217 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) 5218 return false; 5219 } 5220 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); 5221 } 5222 5223 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5224 // Homogeneous aggregates for ELFv2 must have base types of float, 5225 // double, long double, or 128-bit vectors. 5226 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5227 if (BT->getKind() == BuiltinType::Float || 5228 BT->getKind() == BuiltinType::Double || 5229 BT->getKind() == BuiltinType::LongDouble || 5230 BT->getKind() == BuiltinType::Ibm128 || 5231 (getContext().getTargetInfo().hasFloat128Type() && 5232 (BT->getKind() == BuiltinType::Float128))) { 5233 if (IsSoftFloatABI) 5234 return false; 5235 return true; 5236 } 5237 } 5238 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5239 if (getContext().getTypeSize(VT) == 128) 5240 return true; 5241 } 5242 return false; 5243 } 5244 5245 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( 5246 const Type *Base, uint64_t Members) const { 5247 // Vector and fp128 types require one register, other floating point types 5248 // require one or two registers depending on their size. 5249 uint32_t NumRegs = 5250 ((getContext().getTargetInfo().hasFloat128Type() && 5251 Base->isFloat128Type()) || 5252 Base->isVectorType()) ? 1 5253 : (getContext().getTypeSize(Base) + 63) / 64; 5254 5255 // Homogeneous Aggregates may occupy at most 8 registers. 5256 return Members * NumRegs <= 8; 5257 } 5258 5259 ABIArgInfo 5260 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 5261 Ty = useFirstFieldIfTransparentUnion(Ty); 5262 5263 if (Ty->isAnyComplexType()) 5264 return ABIArgInfo::getDirect(); 5265 5266 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) 5267 // or via reference (larger than 16 bytes). 5268 if (Ty->isVectorType()) { 5269 uint64_t Size = getContext().getTypeSize(Ty); 5270 if (Size > 128) 5271 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5272 else if (Size < 128) { 5273 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5274 return ABIArgInfo::getDirect(CoerceTy); 5275 } 5276 } 5277 5278 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5279 if (EIT->getNumBits() > 128) 5280 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 5281 5282 if (isAggregateTypeForABI(Ty)) { 5283 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5284 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 5285 5286 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); 5287 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 5288 5289 // ELFv2 homogeneous aggregates are passed as array types. 5290 const Type *Base = nullptr; 5291 uint64_t Members = 0; 5292 if (Kind == ELFv2 && 5293 isHomogeneousAggregate(Ty, Base, Members)) { 5294 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5295 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5296 return ABIArgInfo::getDirect(CoerceTy); 5297 } 5298 5299 // If an aggregate may end up fully in registers, we do not 5300 // use the ByVal method, but pass the aggregate as array. 5301 // This is usually beneficial since we avoid forcing the 5302 // back-end to store the argument to memory. 5303 uint64_t Bits = getContext().getTypeSize(Ty); 5304 if (Bits > 0 && Bits <= 8 * GPRBits) { 5305 llvm::Type *CoerceTy; 5306 5307 // Types up to 8 bytes are passed as integer type (which will be 5308 // properly aligned in the argument save area doubleword). 5309 if (Bits <= GPRBits) 5310 CoerceTy = 5311 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5312 // Larger types are passed as arrays, with the base type selected 5313 // according to the required alignment in the save area. 5314 else { 5315 uint64_t RegBits = ABIAlign * 8; 5316 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; 5317 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); 5318 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); 5319 } 5320 5321 return ABIArgInfo::getDirect(CoerceTy); 5322 } 5323 5324 // All other aggregates are passed ByVal. 5325 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 5326 /*ByVal=*/true, 5327 /*Realign=*/TyAlign > ABIAlign); 5328 } 5329 5330 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 5331 : ABIArgInfo::getDirect()); 5332 } 5333 5334 ABIArgInfo 5335 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 5336 if (RetTy->isVoidType()) 5337 return ABIArgInfo::getIgnore(); 5338 5339 if (RetTy->isAnyComplexType()) 5340 return ABIArgInfo::getDirect(); 5341 5342 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) 5343 // or via reference (larger than 16 bytes). 5344 if (RetTy->isVectorType()) { 5345 uint64_t Size = getContext().getTypeSize(RetTy); 5346 if (Size > 128) 5347 return getNaturalAlignIndirect(RetTy); 5348 else if (Size < 128) { 5349 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5350 return ABIArgInfo::getDirect(CoerceTy); 5351 } 5352 } 5353 5354 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 5355 if (EIT->getNumBits() > 128) 5356 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 5357 5358 if (isAggregateTypeForABI(RetTy)) { 5359 // ELFv2 homogeneous aggregates are returned as array types. 5360 const Type *Base = nullptr; 5361 uint64_t Members = 0; 5362 if (Kind == ELFv2 && 5363 isHomogeneousAggregate(RetTy, Base, Members)) { 5364 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5365 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5366 return ABIArgInfo::getDirect(CoerceTy); 5367 } 5368 5369 // ELFv2 small aggregates are returned in up to two registers. 5370 uint64_t Bits = getContext().getTypeSize(RetTy); 5371 if (Kind == ELFv2 && Bits <= 2 * GPRBits) { 5372 if (Bits == 0) 5373 return ABIArgInfo::getIgnore(); 5374 5375 llvm::Type *CoerceTy; 5376 if (Bits > GPRBits) { 5377 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); 5378 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); 5379 } else 5380 CoerceTy = 5381 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5382 return ABIArgInfo::getDirect(CoerceTy); 5383 } 5384 5385 // All other aggregates are returned indirectly. 5386 return getNaturalAlignIndirect(RetTy); 5387 } 5388 5389 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 5390 : ABIArgInfo::getDirect()); 5391 } 5392 5393 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 5394 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5395 QualType Ty) const { 5396 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 5397 TypeInfo.Align = getParamTypeAlignment(Ty); 5398 5399 CharUnits SlotSize = CharUnits::fromQuantity(8); 5400 5401 // If we have a complex type and the base type is smaller than 8 bytes, 5402 // the ABI calls for the real and imaginary parts to be right-adjusted 5403 // in separate doublewords. However, Clang expects us to produce a 5404 // pointer to a structure with the two parts packed tightly. So generate 5405 // loads of the real and imaginary parts relative to the va_list pointer, 5406 // and store them to a temporary structure. 5407 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 5408 CharUnits EltSize = TypeInfo.Width / 2; 5409 if (EltSize < SlotSize) { 5410 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, 5411 SlotSize * 2, SlotSize, 5412 SlotSize, /*AllowHigher*/ true); 5413 5414 Address RealAddr = Addr; 5415 Address ImagAddr = RealAddr; 5416 if (CGF.CGM.getDataLayout().isBigEndian()) { 5417 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, 5418 SlotSize - EltSize); 5419 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 5420 2 * SlotSize - EltSize); 5421 } else { 5422 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); 5423 } 5424 5425 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); 5426 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); 5427 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); 5428 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); 5429 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); 5430 5431 Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); 5432 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), 5433 /*init*/ true); 5434 return Temp; 5435 } 5436 } 5437 5438 // Otherwise, just use the general rule. 5439 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 5440 TypeInfo, SlotSize, /*AllowHigher*/ true); 5441 } 5442 5443 bool 5444 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 5445 CodeGen::CodeGenFunction &CGF, 5446 llvm::Value *Address) const { 5447 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5448 /*IsAIX*/ false); 5449 } 5450 5451 bool 5452 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5453 llvm::Value *Address) const { 5454 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5455 /*IsAIX*/ false); 5456 } 5457 5458 //===----------------------------------------------------------------------===// 5459 // AArch64 ABI Implementation 5460 //===----------------------------------------------------------------------===// 5461 5462 namespace { 5463 5464 class AArch64ABIInfo : public SwiftABIInfo { 5465 public: 5466 enum ABIKind { 5467 AAPCS = 0, 5468 DarwinPCS, 5469 Win64 5470 }; 5471 5472 private: 5473 ABIKind Kind; 5474 5475 public: 5476 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) 5477 : SwiftABIInfo(CGT), Kind(Kind) {} 5478 5479 private: 5480 ABIKind getABIKind() const { return Kind; } 5481 bool isDarwinPCS() const { return Kind == DarwinPCS; } 5482 5483 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; 5484 ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic, 5485 unsigned CallingConvention) const; 5486 ABIArgInfo coerceIllegalVector(QualType Ty) const; 5487 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5488 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5489 uint64_t Members) const override; 5490 5491 bool isIllegalVectorType(QualType Ty) const; 5492 5493 void computeInfo(CGFunctionInfo &FI) const override { 5494 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5495 FI.getReturnInfo() = 5496 classifyReturnType(FI.getReturnType(), FI.isVariadic()); 5497 5498 for (auto &it : FI.arguments()) 5499 it.info = classifyArgumentType(it.type, FI.isVariadic(), 5500 FI.getCallingConvention()); 5501 } 5502 5503 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5504 CodeGenFunction &CGF) const; 5505 5506 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5507 CodeGenFunction &CGF) const; 5508 5509 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5510 QualType Ty) const override { 5511 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5512 if (isa<llvm::ScalableVectorType>(BaseTy)) 5513 llvm::report_fatal_error("Passing SVE types to variadic functions is " 5514 "currently not supported"); 5515 5516 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) 5517 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) 5518 : EmitAAPCSVAArg(VAListAddr, Ty, CGF); 5519 } 5520 5521 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5522 QualType Ty) const override; 5523 5524 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5525 bool asReturnValue) const override { 5526 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5527 } 5528 bool isSwiftErrorInRegister() const override { 5529 return true; 5530 } 5531 5532 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5533 unsigned elts) const override; 5534 5535 bool allowBFloatArgsAndRet() const override { 5536 return getTarget().hasBFloat16Type(); 5537 } 5538 }; 5539 5540 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 5541 public: 5542 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) 5543 : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {} 5544 5545 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5546 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; 5547 } 5548 5549 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5550 return 31; 5551 } 5552 5553 bool doesReturnSlotInterfereWithArgs() const override { return false; } 5554 5555 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5556 CodeGen::CodeGenModule &CGM) const override { 5557 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5558 if (!FD) 5559 return; 5560 5561 const auto *TA = FD->getAttr<TargetAttr>(); 5562 if (TA == nullptr) 5563 return; 5564 5565 ParsedTargetAttr Attr = TA->parse(); 5566 if (Attr.BranchProtection.empty()) 5567 return; 5568 5569 TargetInfo::BranchProtectionInfo BPI; 5570 StringRef Error; 5571 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection, 5572 BPI, Error); 5573 assert(Error.empty()); 5574 5575 auto *Fn = cast<llvm::Function>(GV); 5576 static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"}; 5577 Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]); 5578 5579 if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) { 5580 Fn->addFnAttr("sign-return-address-key", 5581 BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey 5582 ? "a_key" 5583 : "b_key"); 5584 } 5585 5586 Fn->addFnAttr("branch-target-enforcement", 5587 BPI.BranchTargetEnforcement ? "true" : "false"); 5588 } 5589 5590 bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF, 5591 llvm::Type *Ty) const override { 5592 if (CGF.getTarget().hasFeature("ls64")) { 5593 auto *ST = dyn_cast<llvm::StructType>(Ty); 5594 if (ST && ST->getNumElements() == 1) { 5595 auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0)); 5596 if (AT && AT->getNumElements() == 8 && 5597 AT->getElementType()->isIntegerTy(64)) 5598 return true; 5599 } 5600 } 5601 return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty); 5602 } 5603 }; 5604 5605 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { 5606 public: 5607 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) 5608 : AArch64TargetCodeGenInfo(CGT, K) {} 5609 5610 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5611 CodeGen::CodeGenModule &CGM) const override; 5612 5613 void getDependentLibraryOption(llvm::StringRef Lib, 5614 llvm::SmallString<24> &Opt) const override { 5615 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5616 } 5617 5618 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5619 llvm::SmallString<32> &Opt) const override { 5620 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5621 } 5622 }; 5623 5624 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( 5625 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5626 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5627 if (GV->isDeclaration()) 5628 return; 5629 addStackProbeTargetAttributes(D, GV, CGM); 5630 } 5631 } 5632 5633 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const { 5634 assert(Ty->isVectorType() && "expected vector type!"); 5635 5636 const auto *VT = Ty->castAs<VectorType>(); 5637 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 5638 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5639 assert(VT->getElementType()->castAs<BuiltinType>()->getKind() == 5640 BuiltinType::UChar && 5641 "unexpected builtin type for SVE predicate!"); 5642 return ABIArgInfo::getDirect(llvm::ScalableVectorType::get( 5643 llvm::Type::getInt1Ty(getVMContext()), 16)); 5644 } 5645 5646 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) { 5647 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5648 5649 const auto *BT = VT->getElementType()->castAs<BuiltinType>(); 5650 llvm::ScalableVectorType *ResType = nullptr; 5651 switch (BT->getKind()) { 5652 default: 5653 llvm_unreachable("unexpected builtin type for SVE vector!"); 5654 case BuiltinType::SChar: 5655 case BuiltinType::UChar: 5656 ResType = llvm::ScalableVectorType::get( 5657 llvm::Type::getInt8Ty(getVMContext()), 16); 5658 break; 5659 case BuiltinType::Short: 5660 case BuiltinType::UShort: 5661 ResType = llvm::ScalableVectorType::get( 5662 llvm::Type::getInt16Ty(getVMContext()), 8); 5663 break; 5664 case BuiltinType::Int: 5665 case BuiltinType::UInt: 5666 ResType = llvm::ScalableVectorType::get( 5667 llvm::Type::getInt32Ty(getVMContext()), 4); 5668 break; 5669 case BuiltinType::Long: 5670 case BuiltinType::ULong: 5671 ResType = llvm::ScalableVectorType::get( 5672 llvm::Type::getInt64Ty(getVMContext()), 2); 5673 break; 5674 case BuiltinType::Half: 5675 ResType = llvm::ScalableVectorType::get( 5676 llvm::Type::getHalfTy(getVMContext()), 8); 5677 break; 5678 case BuiltinType::Float: 5679 ResType = llvm::ScalableVectorType::get( 5680 llvm::Type::getFloatTy(getVMContext()), 4); 5681 break; 5682 case BuiltinType::Double: 5683 ResType = llvm::ScalableVectorType::get( 5684 llvm::Type::getDoubleTy(getVMContext()), 2); 5685 break; 5686 case BuiltinType::BFloat16: 5687 ResType = llvm::ScalableVectorType::get( 5688 llvm::Type::getBFloatTy(getVMContext()), 8); 5689 break; 5690 } 5691 return ABIArgInfo::getDirect(ResType); 5692 } 5693 5694 uint64_t Size = getContext().getTypeSize(Ty); 5695 // Android promotes <2 x i8> to i16, not i32 5696 if (isAndroid() && (Size <= 16)) { 5697 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); 5698 return ABIArgInfo::getDirect(ResType); 5699 } 5700 if (Size <= 32) { 5701 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); 5702 return ABIArgInfo::getDirect(ResType); 5703 } 5704 if (Size == 64) { 5705 auto *ResType = 5706 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); 5707 return ABIArgInfo::getDirect(ResType); 5708 } 5709 if (Size == 128) { 5710 auto *ResType = 5711 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); 5712 return ABIArgInfo::getDirect(ResType); 5713 } 5714 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5715 } 5716 5717 ABIArgInfo 5718 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic, 5719 unsigned CallingConvention) const { 5720 Ty = useFirstFieldIfTransparentUnion(Ty); 5721 5722 // Handle illegal vector types here. 5723 if (isIllegalVectorType(Ty)) 5724 return coerceIllegalVector(Ty); 5725 5726 if (!isAggregateTypeForABI(Ty)) { 5727 // Treat an enum type as its underlying type. 5728 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5729 Ty = EnumTy->getDecl()->getIntegerType(); 5730 5731 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5732 if (EIT->getNumBits() > 128) 5733 return getNaturalAlignIndirect(Ty); 5734 5735 return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS() 5736 ? ABIArgInfo::getExtend(Ty) 5737 : ABIArgInfo::getDirect()); 5738 } 5739 5740 // Structures with either a non-trivial destructor or a non-trivial 5741 // copy constructor are always indirect. 5742 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5743 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 5744 CGCXXABI::RAA_DirectInMemory); 5745 } 5746 5747 // Empty records are always ignored on Darwin, but actually passed in C++ mode 5748 // elsewhere for GNU compatibility. 5749 uint64_t Size = getContext().getTypeSize(Ty); 5750 bool IsEmpty = isEmptyRecord(getContext(), Ty, true); 5751 if (IsEmpty || Size == 0) { 5752 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) 5753 return ABIArgInfo::getIgnore(); 5754 5755 // GNU C mode. The only argument that gets ignored is an empty one with size 5756 // 0. 5757 if (IsEmpty && Size == 0) 5758 return ABIArgInfo::getIgnore(); 5759 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5760 } 5761 5762 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. 5763 const Type *Base = nullptr; 5764 uint64_t Members = 0; 5765 bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64; 5766 bool IsWinVariadic = IsWin64 && IsVariadic; 5767 // In variadic functions on Windows, all composite types are treated alike, 5768 // no special handling of HFAs/HVAs. 5769 if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) { 5770 if (Kind != AArch64ABIInfo::AAPCS) 5771 return ABIArgInfo::getDirect( 5772 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); 5773 5774 // For alignment adjusted HFAs, cap the argument alignment to 16, leave it 5775 // default otherwise. 5776 unsigned Align = 5777 getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 5778 unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity(); 5779 Align = (Align > BaseAlign && Align >= 16) ? 16 : 0; 5780 return ABIArgInfo::getDirect( 5781 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0, 5782 nullptr, true, Align); 5783 } 5784 5785 // Aggregates <= 16 bytes are passed directly in registers or on the stack. 5786 if (Size <= 128) { 5787 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5788 // same size and alignment. 5789 if (getTarget().isRenderScriptTarget()) { 5790 return coerceToIntArray(Ty, getContext(), getVMContext()); 5791 } 5792 unsigned Alignment; 5793 if (Kind == AArch64ABIInfo::AAPCS) { 5794 Alignment = getContext().getTypeUnadjustedAlign(Ty); 5795 Alignment = Alignment < 128 ? 64 : 128; 5796 } else { 5797 Alignment = std::max(getContext().getTypeAlign(Ty), 5798 (unsigned)getTarget().getPointerWidth(0)); 5799 } 5800 Size = llvm::alignTo(Size, Alignment); 5801 5802 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5803 // For aggregates with 16-byte alignment, we use i128. 5804 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); 5805 return ABIArgInfo::getDirect( 5806 Size == Alignment ? BaseTy 5807 : llvm::ArrayType::get(BaseTy, Size / Alignment)); 5808 } 5809 5810 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5811 } 5812 5813 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, 5814 bool IsVariadic) const { 5815 if (RetTy->isVoidType()) 5816 return ABIArgInfo::getIgnore(); 5817 5818 if (const auto *VT = RetTy->getAs<VectorType>()) { 5819 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5820 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5821 return coerceIllegalVector(RetTy); 5822 } 5823 5824 // Large vector types should be returned via memory. 5825 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 5826 return getNaturalAlignIndirect(RetTy); 5827 5828 if (!isAggregateTypeForABI(RetTy)) { 5829 // Treat an enum type as its underlying type. 5830 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5831 RetTy = EnumTy->getDecl()->getIntegerType(); 5832 5833 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 5834 if (EIT->getNumBits() > 128) 5835 return getNaturalAlignIndirect(RetTy); 5836 5837 return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS() 5838 ? ABIArgInfo::getExtend(RetTy) 5839 : ABIArgInfo::getDirect()); 5840 } 5841 5842 uint64_t Size = getContext().getTypeSize(RetTy); 5843 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) 5844 return ABIArgInfo::getIgnore(); 5845 5846 const Type *Base = nullptr; 5847 uint64_t Members = 0; 5848 if (isHomogeneousAggregate(RetTy, Base, Members) && 5849 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && 5850 IsVariadic)) 5851 // Homogeneous Floating-point Aggregates (HFAs) are returned directly. 5852 return ABIArgInfo::getDirect(); 5853 5854 // Aggregates <= 16 bytes are returned directly in registers or on the stack. 5855 if (Size <= 128) { 5856 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5857 // same size and alignment. 5858 if (getTarget().isRenderScriptTarget()) { 5859 return coerceToIntArray(RetTy, getContext(), getVMContext()); 5860 } 5861 5862 if (Size <= 64 && getDataLayout().isLittleEndian()) { 5863 // Composite types are returned in lower bits of a 64-bit register for LE, 5864 // and in higher bits for BE. However, integer types are always returned 5865 // in lower bits for both LE and BE, and they are not rounded up to 5866 // 64-bits. We can skip rounding up of composite types for LE, but not for 5867 // BE, otherwise composite types will be indistinguishable from integer 5868 // types. 5869 return ABIArgInfo::getDirect( 5870 llvm::IntegerType::get(getVMContext(), Size)); 5871 } 5872 5873 unsigned Alignment = getContext().getTypeAlign(RetTy); 5874 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes 5875 5876 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5877 // For aggregates with 16-byte alignment, we use i128. 5878 if (Alignment < 128 && Size == 128) { 5879 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); 5880 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); 5881 } 5882 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); 5883 } 5884 5885 return getNaturalAlignIndirect(RetTy); 5886 } 5887 5888 /// isIllegalVectorType - check whether the vector type is legal for AArch64. 5889 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { 5890 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5891 // Check whether VT is a fixed-length SVE vector. These types are 5892 // represented as scalable vectors in function args/return and must be 5893 // coerced from fixed vectors. 5894 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5895 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5896 return true; 5897 5898 // Check whether VT is legal. 5899 unsigned NumElements = VT->getNumElements(); 5900 uint64_t Size = getContext().getTypeSize(VT); 5901 // NumElements should be power of 2. 5902 if (!llvm::isPowerOf2_32(NumElements)) 5903 return true; 5904 5905 // arm64_32 has to be compatible with the ARM logic here, which allows huge 5906 // vectors for some reason. 5907 llvm::Triple Triple = getTarget().getTriple(); 5908 if (Triple.getArch() == llvm::Triple::aarch64_32 && 5909 Triple.isOSBinFormatMachO()) 5910 return Size <= 32; 5911 5912 return Size != 64 && (Size != 128 || NumElements == 1); 5913 } 5914 return false; 5915 } 5916 5917 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, 5918 llvm::Type *eltTy, 5919 unsigned elts) const { 5920 if (!llvm::isPowerOf2_32(elts)) 5921 return false; 5922 if (totalSize.getQuantity() != 8 && 5923 (totalSize.getQuantity() != 16 || elts == 1)) 5924 return false; 5925 return true; 5926 } 5927 5928 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5929 // Homogeneous aggregates for AAPCS64 must have base types of a floating 5930 // point type or a short-vector type. This is the same as the 32-bit ABI, 5931 // but with the difference that any floating-point type is allowed, 5932 // including __fp16. 5933 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5934 if (BT->isFloatingPoint()) 5935 return true; 5936 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 5937 unsigned VecSize = getContext().getTypeSize(VT); 5938 if (VecSize == 64 || VecSize == 128) 5939 return true; 5940 } 5941 return false; 5942 } 5943 5944 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 5945 uint64_t Members) const { 5946 return Members <= 4; 5947 } 5948 5949 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5950 CodeGenFunction &CGF) const { 5951 ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true, 5952 CGF.CurFnInfo->getCallingConvention()); 5953 bool IsIndirect = AI.isIndirect(); 5954 5955 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5956 if (IsIndirect) 5957 BaseTy = llvm::PointerType::getUnqual(BaseTy); 5958 else if (AI.getCoerceToType()) 5959 BaseTy = AI.getCoerceToType(); 5960 5961 unsigned NumRegs = 1; 5962 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { 5963 BaseTy = ArrTy->getElementType(); 5964 NumRegs = ArrTy->getNumElements(); 5965 } 5966 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); 5967 5968 // The AArch64 va_list type and handling is specified in the Procedure Call 5969 // Standard, section B.4: 5970 // 5971 // struct { 5972 // void *__stack; 5973 // void *__gr_top; 5974 // void *__vr_top; 5975 // int __gr_offs; 5976 // int __vr_offs; 5977 // }; 5978 5979 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 5980 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 5981 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 5982 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 5983 5984 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 5985 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); 5986 5987 Address reg_offs_p = Address::invalid(); 5988 llvm::Value *reg_offs = nullptr; 5989 int reg_top_index; 5990 int RegSize = IsIndirect ? 8 : TySize.getQuantity(); 5991 if (!IsFPR) { 5992 // 3 is the field number of __gr_offs 5993 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 5994 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 5995 reg_top_index = 1; // field number for __gr_top 5996 RegSize = llvm::alignTo(RegSize, 8); 5997 } else { 5998 // 4 is the field number of __vr_offs. 5999 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 6000 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 6001 reg_top_index = 2; // field number for __vr_top 6002 RegSize = 16 * NumRegs; 6003 } 6004 6005 //======================================= 6006 // Find out where argument was passed 6007 //======================================= 6008 6009 // If reg_offs >= 0 we're already using the stack for this type of 6010 // argument. We don't want to keep updating reg_offs (in case it overflows, 6011 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 6012 // whatever they get). 6013 llvm::Value *UsingStack = nullptr; 6014 UsingStack = CGF.Builder.CreateICmpSGE( 6015 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 6016 6017 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 6018 6019 // Otherwise, at least some kind of argument could go in these registers, the 6020 // question is whether this particular type is too big. 6021 CGF.EmitBlock(MaybeRegBlock); 6022 6023 // Integer arguments may need to correct register alignment (for example a 6024 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 6025 // align __gr_offs to calculate the potential address. 6026 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { 6027 int Align = TyAlign.getQuantity(); 6028 6029 reg_offs = CGF.Builder.CreateAdd( 6030 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 6031 "align_regoffs"); 6032 reg_offs = CGF.Builder.CreateAnd( 6033 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), 6034 "aligned_regoffs"); 6035 } 6036 6037 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 6038 // The fact that this is done unconditionally reflects the fact that 6039 // allocating an argument to the stack also uses up all the remaining 6040 // registers of the appropriate kind. 6041 llvm::Value *NewOffset = nullptr; 6042 NewOffset = CGF.Builder.CreateAdd( 6043 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); 6044 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 6045 6046 // Now we're in a position to decide whether this argument really was in 6047 // registers or not. 6048 llvm::Value *InRegs = nullptr; 6049 InRegs = CGF.Builder.CreateICmpSLE( 6050 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); 6051 6052 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 6053 6054 //======================================= 6055 // Argument was in registers 6056 //======================================= 6057 6058 // Now we emit the code for if the argument was originally passed in 6059 // registers. First start the appropriate block: 6060 CGF.EmitBlock(InRegBlock); 6061 6062 llvm::Value *reg_top = nullptr; 6063 Address reg_top_p = 6064 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 6065 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 6066 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs), 6067 CharUnits::fromQuantity(IsFPR ? 16 : 8)); 6068 Address RegAddr = Address::invalid(); 6069 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); 6070 6071 if (IsIndirect) { 6072 // If it's been passed indirectly (actually a struct), whatever we find from 6073 // stored registers or on the stack will actually be a struct **. 6074 MemTy = llvm::PointerType::getUnqual(MemTy); 6075 } 6076 6077 const Type *Base = nullptr; 6078 uint64_t NumMembers = 0; 6079 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); 6080 if (IsHFA && NumMembers > 1) { 6081 // Homogeneous aggregates passed in registers will have their elements split 6082 // and stored 16-bytes apart regardless of size (they're notionally in qN, 6083 // qN+1, ...). We reload and store into a temporary local variable 6084 // contiguously. 6085 assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); 6086 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); 6087 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 6088 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 6089 Address Tmp = CGF.CreateTempAlloca(HFATy, 6090 std::max(TyAlign, BaseTyInfo.Align)); 6091 6092 // On big-endian platforms, the value will be right-aligned in its slot. 6093 int Offset = 0; 6094 if (CGF.CGM.getDataLayout().isBigEndian() && 6095 BaseTyInfo.Width.getQuantity() < 16) 6096 Offset = 16 - BaseTyInfo.Width.getQuantity(); 6097 6098 for (unsigned i = 0; i < NumMembers; ++i) { 6099 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); 6100 Address LoadAddr = 6101 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); 6102 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); 6103 6104 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i); 6105 6106 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 6107 CGF.Builder.CreateStore(Elem, StoreAddr); 6108 } 6109 6110 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); 6111 } else { 6112 // Otherwise the object is contiguous in memory. 6113 6114 // It might be right-aligned in its slot. 6115 CharUnits SlotSize = BaseAddr.getAlignment(); 6116 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && 6117 (IsHFA || !isAggregateTypeForABI(Ty)) && 6118 TySize < SlotSize) { 6119 CharUnits Offset = SlotSize - TySize; 6120 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); 6121 } 6122 6123 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); 6124 } 6125 6126 CGF.EmitBranch(ContBlock); 6127 6128 //======================================= 6129 // Argument was on the stack 6130 //======================================= 6131 CGF.EmitBlock(OnStackBlock); 6132 6133 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 6134 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); 6135 6136 // Again, stack arguments may need realignment. In this case both integer and 6137 // floating-point ones might be affected. 6138 if (!IsIndirect && TyAlign.getQuantity() > 8) { 6139 int Align = TyAlign.getQuantity(); 6140 6141 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); 6142 6143 OnStackPtr = CGF.Builder.CreateAdd( 6144 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 6145 "align_stack"); 6146 OnStackPtr = CGF.Builder.CreateAnd( 6147 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), 6148 "align_stack"); 6149 6150 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); 6151 } 6152 Address OnStackAddr(OnStackPtr, 6153 std::max(CharUnits::fromQuantity(8), TyAlign)); 6154 6155 // All stack slots are multiples of 8 bytes. 6156 CharUnits StackSlotSize = CharUnits::fromQuantity(8); 6157 CharUnits StackSize; 6158 if (IsIndirect) 6159 StackSize = StackSlotSize; 6160 else 6161 StackSize = TySize.alignTo(StackSlotSize); 6162 6163 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); 6164 llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP( 6165 CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack"); 6166 6167 // Write the new value of __stack for the next call to va_arg 6168 CGF.Builder.CreateStore(NewStack, stack_p); 6169 6170 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 6171 TySize < StackSlotSize) { 6172 CharUnits Offset = StackSlotSize - TySize; 6173 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); 6174 } 6175 6176 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); 6177 6178 CGF.EmitBranch(ContBlock); 6179 6180 //======================================= 6181 // Tidy up 6182 //======================================= 6183 CGF.EmitBlock(ContBlock); 6184 6185 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 6186 OnStackAddr, OnStackBlock, "vaargs.addr"); 6187 6188 if (IsIndirect) 6189 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), 6190 TyAlign); 6191 6192 return ResAddr; 6193 } 6194 6195 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, 6196 CodeGenFunction &CGF) const { 6197 // The backend's lowering doesn't support va_arg for aggregates or 6198 // illegal vector types. Lower VAArg here for these cases and use 6199 // the LLVM va_arg instruction for everything else. 6200 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) 6201 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 6202 6203 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8; 6204 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize); 6205 6206 // Empty records are ignored for parameter passing purposes. 6207 if (isEmptyRecord(getContext(), Ty, true)) { 6208 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 6209 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6210 return Addr; 6211 } 6212 6213 // The size of the actual thing passed, which might end up just 6214 // being a pointer for indirect types. 6215 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6216 6217 // Arguments bigger than 16 bytes which aren't homogeneous 6218 // aggregates should be passed indirectly. 6219 bool IsIndirect = false; 6220 if (TyInfo.Width.getQuantity() > 16) { 6221 const Type *Base = nullptr; 6222 uint64_t Members = 0; 6223 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); 6224 } 6225 6226 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6227 TyInfo, SlotSize, /*AllowHigherAlign*/ true); 6228 } 6229 6230 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 6231 QualType Ty) const { 6232 bool IsIndirect = false; 6233 6234 // Composites larger than 16 bytes are passed by reference. 6235 if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128) 6236 IsIndirect = true; 6237 6238 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6239 CGF.getContext().getTypeInfoInChars(Ty), 6240 CharUnits::fromQuantity(8), 6241 /*allowHigherAlign*/ false); 6242 } 6243 6244 //===----------------------------------------------------------------------===// 6245 // ARM ABI Implementation 6246 //===----------------------------------------------------------------------===// 6247 6248 namespace { 6249 6250 class ARMABIInfo : public SwiftABIInfo { 6251 public: 6252 enum ABIKind { 6253 APCS = 0, 6254 AAPCS = 1, 6255 AAPCS_VFP = 2, 6256 AAPCS16_VFP = 3, 6257 }; 6258 6259 private: 6260 ABIKind Kind; 6261 bool IsFloatABISoftFP; 6262 6263 public: 6264 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) 6265 : SwiftABIInfo(CGT), Kind(_Kind) { 6266 setCCs(); 6267 IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" || 6268 CGT.getCodeGenOpts().FloatABI == ""; // default 6269 } 6270 6271 bool isEABI() const { 6272 switch (getTarget().getTriple().getEnvironment()) { 6273 case llvm::Triple::Android: 6274 case llvm::Triple::EABI: 6275 case llvm::Triple::EABIHF: 6276 case llvm::Triple::GNUEABI: 6277 case llvm::Triple::GNUEABIHF: 6278 case llvm::Triple::MuslEABI: 6279 case llvm::Triple::MuslEABIHF: 6280 return true; 6281 default: 6282 return false; 6283 } 6284 } 6285 6286 bool isEABIHF() const { 6287 switch (getTarget().getTriple().getEnvironment()) { 6288 case llvm::Triple::EABIHF: 6289 case llvm::Triple::GNUEABIHF: 6290 case llvm::Triple::MuslEABIHF: 6291 return true; 6292 default: 6293 return false; 6294 } 6295 } 6296 6297 ABIKind getABIKind() const { return Kind; } 6298 6299 bool allowBFloatArgsAndRet() const override { 6300 return !IsFloatABISoftFP && getTarget().hasBFloat16Type(); 6301 } 6302 6303 private: 6304 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic, 6305 unsigned functionCallConv) const; 6306 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic, 6307 unsigned functionCallConv) const; 6308 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, 6309 uint64_t Members) const; 6310 ABIArgInfo coerceIllegalVector(QualType Ty) const; 6311 bool isIllegalVectorType(QualType Ty) const; 6312 bool containsAnyFP16Vectors(QualType Ty) const; 6313 6314 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 6315 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 6316 uint64_t Members) const override; 6317 6318 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const; 6319 6320 void computeInfo(CGFunctionInfo &FI) const override; 6321 6322 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6323 QualType Ty) const override; 6324 6325 llvm::CallingConv::ID getLLVMDefaultCC() const; 6326 llvm::CallingConv::ID getABIDefaultCC() const; 6327 void setCCs(); 6328 6329 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6330 bool asReturnValue) const override { 6331 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6332 } 6333 bool isSwiftErrorInRegister() const override { 6334 return true; 6335 } 6336 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 6337 unsigned elts) const override; 6338 }; 6339 6340 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 6341 public: 6342 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6343 : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {} 6344 6345 const ARMABIInfo &getABIInfo() const { 6346 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 6347 } 6348 6349 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 6350 return 13; 6351 } 6352 6353 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 6354 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; 6355 } 6356 6357 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 6358 llvm::Value *Address) const override { 6359 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 6360 6361 // 0-15 are the 16 integer registers. 6362 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 6363 return false; 6364 } 6365 6366 unsigned getSizeOfUnwindException() const override { 6367 if (getABIInfo().isEABI()) return 88; 6368 return TargetCodeGenInfo::getSizeOfUnwindException(); 6369 } 6370 6371 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6372 CodeGen::CodeGenModule &CGM) const override { 6373 if (GV->isDeclaration()) 6374 return; 6375 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6376 if (!FD) 6377 return; 6378 6379 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 6380 if (!Attr) 6381 return; 6382 6383 const char *Kind; 6384 switch (Attr->getInterrupt()) { 6385 case ARMInterruptAttr::Generic: Kind = ""; break; 6386 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 6387 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 6388 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 6389 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 6390 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 6391 } 6392 6393 llvm::Function *Fn = cast<llvm::Function>(GV); 6394 6395 Fn->addFnAttr("interrupt", Kind); 6396 6397 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind(); 6398 if (ABI == ARMABIInfo::APCS) 6399 return; 6400 6401 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 6402 // however this is not necessarily true on taking any interrupt. Instruct 6403 // the backend to perform a realignment as part of the function prologue. 6404 llvm::AttrBuilder B; 6405 B.addStackAlignmentAttr(8); 6406 Fn->addFnAttrs(B); 6407 } 6408 }; 6409 6410 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { 6411 public: 6412 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6413 : ARMTargetCodeGenInfo(CGT, K) {} 6414 6415 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6416 CodeGen::CodeGenModule &CGM) const override; 6417 6418 void getDependentLibraryOption(llvm::StringRef Lib, 6419 llvm::SmallString<24> &Opt) const override { 6420 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 6421 } 6422 6423 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 6424 llvm::SmallString<32> &Opt) const override { 6425 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 6426 } 6427 }; 6428 6429 void WindowsARMTargetCodeGenInfo::setTargetAttributes( 6430 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 6431 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 6432 if (GV->isDeclaration()) 6433 return; 6434 addStackProbeTargetAttributes(D, GV, CGM); 6435 } 6436 } 6437 6438 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 6439 if (!::classifyReturnType(getCXXABI(), FI, *this)) 6440 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(), 6441 FI.getCallingConvention()); 6442 6443 for (auto &I : FI.arguments()) 6444 I.info = classifyArgumentType(I.type, FI.isVariadic(), 6445 FI.getCallingConvention()); 6446 6447 6448 // Always honor user-specified calling convention. 6449 if (FI.getCallingConvention() != llvm::CallingConv::C) 6450 return; 6451 6452 llvm::CallingConv::ID cc = getRuntimeCC(); 6453 if (cc != llvm::CallingConv::C) 6454 FI.setEffectiveCallingConvention(cc); 6455 } 6456 6457 /// Return the default calling convention that LLVM will use. 6458 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 6459 // The default calling convention that LLVM will infer. 6460 if (isEABIHF() || getTarget().getTriple().isWatchABI()) 6461 return llvm::CallingConv::ARM_AAPCS_VFP; 6462 else if (isEABI()) 6463 return llvm::CallingConv::ARM_AAPCS; 6464 else 6465 return llvm::CallingConv::ARM_APCS; 6466 } 6467 6468 /// Return the calling convention that our ABI would like us to use 6469 /// as the C calling convention. 6470 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 6471 switch (getABIKind()) { 6472 case APCS: return llvm::CallingConv::ARM_APCS; 6473 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 6474 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6475 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6476 } 6477 llvm_unreachable("bad ABI kind"); 6478 } 6479 6480 void ARMABIInfo::setCCs() { 6481 assert(getRuntimeCC() == llvm::CallingConv::C); 6482 6483 // Don't muddy up the IR with a ton of explicit annotations if 6484 // they'd just match what LLVM will infer from the triple. 6485 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 6486 if (abiCC != getLLVMDefaultCC()) 6487 RuntimeCC = abiCC; 6488 } 6489 6490 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { 6491 uint64_t Size = getContext().getTypeSize(Ty); 6492 if (Size <= 32) { 6493 llvm::Type *ResType = 6494 llvm::Type::getInt32Ty(getVMContext()); 6495 return ABIArgInfo::getDirect(ResType); 6496 } 6497 if (Size == 64 || Size == 128) { 6498 auto *ResType = llvm::FixedVectorType::get( 6499 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6500 return ABIArgInfo::getDirect(ResType); 6501 } 6502 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6503 } 6504 6505 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, 6506 const Type *Base, 6507 uint64_t Members) const { 6508 assert(Base && "Base class should be set for homogeneous aggregate"); 6509 // Base can be a floating-point or a vector. 6510 if (const VectorType *VT = Base->getAs<VectorType>()) { 6511 // FP16 vectors should be converted to integer vectors 6512 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) { 6513 uint64_t Size = getContext().getTypeSize(VT); 6514 auto *NewVecTy = llvm::FixedVectorType::get( 6515 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6516 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); 6517 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6518 } 6519 } 6520 unsigned Align = 0; 6521 if (getABIKind() == ARMABIInfo::AAPCS || 6522 getABIKind() == ARMABIInfo::AAPCS_VFP) { 6523 // For alignment adjusted HFAs, cap the argument alignment to 8, leave it 6524 // default otherwise. 6525 Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6526 unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity(); 6527 Align = (Align > BaseAlign && Align >= 8) ? 8 : 0; 6528 } 6529 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align); 6530 } 6531 6532 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic, 6533 unsigned functionCallConv) const { 6534 // 6.1.2.1 The following argument types are VFP CPRCs: 6535 // A single-precision floating-point type (including promoted 6536 // half-precision types); A double-precision floating-point type; 6537 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 6538 // with a Base Type of a single- or double-precision floating-point type, 6539 // 64-bit containerized vectors or 128-bit containerized vectors with one 6540 // to four Elements. 6541 // Variadic functions should always marshal to the base standard. 6542 bool IsAAPCS_VFP = 6543 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false); 6544 6545 Ty = useFirstFieldIfTransparentUnion(Ty); 6546 6547 // Handle illegal vector types here. 6548 if (isIllegalVectorType(Ty)) 6549 return coerceIllegalVector(Ty); 6550 6551 if (!isAggregateTypeForABI(Ty)) { 6552 // Treat an enum type as its underlying type. 6553 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 6554 Ty = EnumTy->getDecl()->getIntegerType(); 6555 } 6556 6557 if (const auto *EIT = Ty->getAs<ExtIntType>()) 6558 if (EIT->getNumBits() > 64) 6559 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 6560 6561 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 6562 : ABIArgInfo::getDirect()); 6563 } 6564 6565 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 6566 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 6567 } 6568 6569 // Ignore empty records. 6570 if (isEmptyRecord(getContext(), Ty, true)) 6571 return ABIArgInfo::getIgnore(); 6572 6573 if (IsAAPCS_VFP) { 6574 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 6575 // into VFP registers. 6576 const Type *Base = nullptr; 6577 uint64_t Members = 0; 6578 if (isHomogeneousAggregate(Ty, Base, Members)) 6579 return classifyHomogeneousAggregate(Ty, Base, Members); 6580 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6581 // WatchOS does have homogeneous aggregates. Note that we intentionally use 6582 // this convention even for a variadic function: the backend will use GPRs 6583 // if needed. 6584 const Type *Base = nullptr; 6585 uint64_t Members = 0; 6586 if (isHomogeneousAggregate(Ty, Base, Members)) { 6587 assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); 6588 llvm::Type *Ty = 6589 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); 6590 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6591 } 6592 } 6593 6594 if (getABIKind() == ARMABIInfo::AAPCS16_VFP && 6595 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { 6596 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're 6597 // bigger than 128-bits, they get placed in space allocated by the caller, 6598 // and a pointer is passed. 6599 return ABIArgInfo::getIndirect( 6600 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); 6601 } 6602 6603 // Support byval for ARM. 6604 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 6605 // most 8-byte. We realign the indirect argument if type alignment is bigger 6606 // than ABI alignment. 6607 uint64_t ABIAlign = 4; 6608 uint64_t TyAlign; 6609 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6610 getABIKind() == ARMABIInfo::AAPCS) { 6611 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6612 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 6613 } else { 6614 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 6615 } 6616 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 6617 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); 6618 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 6619 /*ByVal=*/true, 6620 /*Realign=*/TyAlign > ABIAlign); 6621 } 6622 6623 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of 6624 // same size and alignment. 6625 if (getTarget().isRenderScriptTarget()) { 6626 return coerceToIntArray(Ty, getContext(), getVMContext()); 6627 } 6628 6629 // Otherwise, pass by coercing to a structure of the appropriate size. 6630 llvm::Type* ElemTy; 6631 unsigned SizeRegs; 6632 // FIXME: Try to match the types of the arguments more accurately where 6633 // we can. 6634 if (TyAlign <= 4) { 6635 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 6636 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 6637 } else { 6638 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 6639 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 6640 } 6641 6642 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); 6643 } 6644 6645 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 6646 llvm::LLVMContext &VMContext) { 6647 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 6648 // is called integer-like if its size is less than or equal to one word, and 6649 // the offset of each of its addressable sub-fields is zero. 6650 6651 uint64_t Size = Context.getTypeSize(Ty); 6652 6653 // Check that the type fits in a word. 6654 if (Size > 32) 6655 return false; 6656 6657 // FIXME: Handle vector types! 6658 if (Ty->isVectorType()) 6659 return false; 6660 6661 // Float types are never treated as "integer like". 6662 if (Ty->isRealFloatingType()) 6663 return false; 6664 6665 // If this is a builtin or pointer type then it is ok. 6666 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 6667 return true; 6668 6669 // Small complex integer types are "integer like". 6670 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 6671 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 6672 6673 // Single element and zero sized arrays should be allowed, by the definition 6674 // above, but they are not. 6675 6676 // Otherwise, it must be a record type. 6677 const RecordType *RT = Ty->getAs<RecordType>(); 6678 if (!RT) return false; 6679 6680 // Ignore records with flexible arrays. 6681 const RecordDecl *RD = RT->getDecl(); 6682 if (RD->hasFlexibleArrayMember()) 6683 return false; 6684 6685 // Check that all sub-fields are at offset 0, and are themselves "integer 6686 // like". 6687 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 6688 6689 bool HadField = false; 6690 unsigned idx = 0; 6691 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 6692 i != e; ++i, ++idx) { 6693 const FieldDecl *FD = *i; 6694 6695 // Bit-fields are not addressable, we only need to verify they are "integer 6696 // like". We still have to disallow a subsequent non-bitfield, for example: 6697 // struct { int : 0; int x } 6698 // is non-integer like according to gcc. 6699 if (FD->isBitField()) { 6700 if (!RD->isUnion()) 6701 HadField = true; 6702 6703 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6704 return false; 6705 6706 continue; 6707 } 6708 6709 // Check if this field is at offset 0. 6710 if (Layout.getFieldOffset(idx) != 0) 6711 return false; 6712 6713 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6714 return false; 6715 6716 // Only allow at most one field in a structure. This doesn't match the 6717 // wording above, but follows gcc in situations with a field following an 6718 // empty structure. 6719 if (!RD->isUnion()) { 6720 if (HadField) 6721 return false; 6722 6723 HadField = true; 6724 } 6725 } 6726 6727 return true; 6728 } 6729 6730 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic, 6731 unsigned functionCallConv) const { 6732 6733 // Variadic functions should always marshal to the base standard. 6734 bool IsAAPCS_VFP = 6735 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true); 6736 6737 if (RetTy->isVoidType()) 6738 return ABIArgInfo::getIgnore(); 6739 6740 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 6741 // Large vector types should be returned via memory. 6742 if (getContext().getTypeSize(RetTy) > 128) 6743 return getNaturalAlignIndirect(RetTy); 6744 // TODO: FP16/BF16 vectors should be converted to integer vectors 6745 // This check is similar to isIllegalVectorType - refactor? 6746 if ((!getTarget().hasLegalHalfType() && 6747 (VT->getElementType()->isFloat16Type() || 6748 VT->getElementType()->isHalfType())) || 6749 (IsFloatABISoftFP && 6750 VT->getElementType()->isBFloat16Type())) 6751 return coerceIllegalVector(RetTy); 6752 } 6753 6754 if (!isAggregateTypeForABI(RetTy)) { 6755 // Treat an enum type as its underlying type. 6756 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6757 RetTy = EnumTy->getDecl()->getIntegerType(); 6758 6759 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 6760 if (EIT->getNumBits() > 64) 6761 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 6762 6763 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 6764 : ABIArgInfo::getDirect(); 6765 } 6766 6767 // Are we following APCS? 6768 if (getABIKind() == APCS) { 6769 if (isEmptyRecord(getContext(), RetTy, false)) 6770 return ABIArgInfo::getIgnore(); 6771 6772 // Complex types are all returned as packed integers. 6773 // 6774 // FIXME: Consider using 2 x vector types if the back end handles them 6775 // correctly. 6776 if (RetTy->isAnyComplexType()) 6777 return ABIArgInfo::getDirect(llvm::IntegerType::get( 6778 getVMContext(), getContext().getTypeSize(RetTy))); 6779 6780 // Integer like structures are returned in r0. 6781 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 6782 // Return in the smallest viable integer type. 6783 uint64_t Size = getContext().getTypeSize(RetTy); 6784 if (Size <= 8) 6785 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6786 if (Size <= 16) 6787 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6788 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6789 } 6790 6791 // Otherwise return in memory. 6792 return getNaturalAlignIndirect(RetTy); 6793 } 6794 6795 // Otherwise this is an AAPCS variant. 6796 6797 if (isEmptyRecord(getContext(), RetTy, true)) 6798 return ABIArgInfo::getIgnore(); 6799 6800 // Check for homogeneous aggregates with AAPCS-VFP. 6801 if (IsAAPCS_VFP) { 6802 const Type *Base = nullptr; 6803 uint64_t Members = 0; 6804 if (isHomogeneousAggregate(RetTy, Base, Members)) 6805 return classifyHomogeneousAggregate(RetTy, Base, Members); 6806 } 6807 6808 // Aggregates <= 4 bytes are returned in r0; other aggregates 6809 // are returned indirectly. 6810 uint64_t Size = getContext().getTypeSize(RetTy); 6811 if (Size <= 32) { 6812 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of 6813 // same size and alignment. 6814 if (getTarget().isRenderScriptTarget()) { 6815 return coerceToIntArray(RetTy, getContext(), getVMContext()); 6816 } 6817 if (getDataLayout().isBigEndian()) 6818 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) 6819 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6820 6821 // Return in the smallest viable integer type. 6822 if (Size <= 8) 6823 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6824 if (Size <= 16) 6825 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6826 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6827 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { 6828 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); 6829 llvm::Type *CoerceTy = 6830 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); 6831 return ABIArgInfo::getDirect(CoerceTy); 6832 } 6833 6834 return getNaturalAlignIndirect(RetTy); 6835 } 6836 6837 /// isIllegalVector - check whether Ty is an illegal vector type. 6838 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 6839 if (const VectorType *VT = Ty->getAs<VectorType> ()) { 6840 // On targets that don't support half, fp16 or bfloat, they are expanded 6841 // into float, and we don't want the ABI to depend on whether or not they 6842 // are supported in hardware. Thus return false to coerce vectors of these 6843 // types into integer vectors. 6844 // We do not depend on hasLegalHalfType for bfloat as it is a 6845 // separate IR type. 6846 if ((!getTarget().hasLegalHalfType() && 6847 (VT->getElementType()->isFloat16Type() || 6848 VT->getElementType()->isHalfType())) || 6849 (IsFloatABISoftFP && 6850 VT->getElementType()->isBFloat16Type())) 6851 return true; 6852 if (isAndroid()) { 6853 // Android shipped using Clang 3.1, which supported a slightly different 6854 // vector ABI. The primary differences were that 3-element vector types 6855 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path 6856 // accepts that legacy behavior for Android only. 6857 // Check whether VT is legal. 6858 unsigned NumElements = VT->getNumElements(); 6859 // NumElements should be power of 2 or equal to 3. 6860 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) 6861 return true; 6862 } else { 6863 // Check whether VT is legal. 6864 unsigned NumElements = VT->getNumElements(); 6865 uint64_t Size = getContext().getTypeSize(VT); 6866 // NumElements should be power of 2. 6867 if (!llvm::isPowerOf2_32(NumElements)) 6868 return true; 6869 // Size should be greater than 32 bits. 6870 return Size <= 32; 6871 } 6872 } 6873 return false; 6874 } 6875 6876 /// Return true if a type contains any 16-bit floating point vectors 6877 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const { 6878 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 6879 uint64_t NElements = AT->getSize().getZExtValue(); 6880 if (NElements == 0) 6881 return false; 6882 return containsAnyFP16Vectors(AT->getElementType()); 6883 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 6884 const RecordDecl *RD = RT->getDecl(); 6885 6886 // If this is a C++ record, check the bases first. 6887 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6888 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) { 6889 return containsAnyFP16Vectors(B.getType()); 6890 })) 6891 return true; 6892 6893 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) { 6894 return FD && containsAnyFP16Vectors(FD->getType()); 6895 })) 6896 return true; 6897 6898 return false; 6899 } else { 6900 if (const VectorType *VT = Ty->getAs<VectorType>()) 6901 return (VT->getElementType()->isFloat16Type() || 6902 VT->getElementType()->isBFloat16Type() || 6903 VT->getElementType()->isHalfType()); 6904 return false; 6905 } 6906 } 6907 6908 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 6909 llvm::Type *eltTy, 6910 unsigned numElts) const { 6911 if (!llvm::isPowerOf2_32(numElts)) 6912 return false; 6913 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); 6914 if (size > 64) 6915 return false; 6916 if (vectorSize.getQuantity() != 8 && 6917 (vectorSize.getQuantity() != 16 || numElts == 1)) 6918 return false; 6919 return true; 6920 } 6921 6922 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 6923 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 6924 // double, or 64-bit or 128-bit vectors. 6925 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 6926 if (BT->getKind() == BuiltinType::Float || 6927 BT->getKind() == BuiltinType::Double || 6928 BT->getKind() == BuiltinType::LongDouble) 6929 return true; 6930 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 6931 unsigned VecSize = getContext().getTypeSize(VT); 6932 if (VecSize == 64 || VecSize == 128) 6933 return true; 6934 } 6935 return false; 6936 } 6937 6938 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 6939 uint64_t Members) const { 6940 return Members <= 4; 6941 } 6942 6943 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention, 6944 bool acceptHalf) const { 6945 // Give precedence to user-specified calling conventions. 6946 if (callConvention != llvm::CallingConv::C) 6947 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP); 6948 else 6949 return (getABIKind() == AAPCS_VFP) || 6950 (acceptHalf && (getABIKind() == AAPCS16_VFP)); 6951 } 6952 6953 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6954 QualType Ty) const { 6955 CharUnits SlotSize = CharUnits::fromQuantity(4); 6956 6957 // Empty records are ignored for parameter passing purposes. 6958 if (isEmptyRecord(getContext(), Ty, true)) { 6959 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 6960 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6961 return Addr; 6962 } 6963 6964 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6965 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty); 6966 6967 // Use indirect if size of the illegal vector is bigger than 16 bytes. 6968 bool IsIndirect = false; 6969 const Type *Base = nullptr; 6970 uint64_t Members = 0; 6971 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { 6972 IsIndirect = true; 6973 6974 // ARMv7k passes structs bigger than 16 bytes indirectly, in space 6975 // allocated by the caller. 6976 } else if (TySize > CharUnits::fromQuantity(16) && 6977 getABIKind() == ARMABIInfo::AAPCS16_VFP && 6978 !isHomogeneousAggregate(Ty, Base, Members)) { 6979 IsIndirect = true; 6980 6981 // Otherwise, bound the type's ABI alignment. 6982 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 6983 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 6984 // Our callers should be prepared to handle an under-aligned address. 6985 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6986 getABIKind() == ARMABIInfo::AAPCS) { 6987 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6988 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); 6989 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6990 // ARMv7k allows type alignment up to 16 bytes. 6991 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6992 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); 6993 } else { 6994 TyAlignForABI = CharUnits::fromQuantity(4); 6995 } 6996 6997 TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None); 6998 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, 6999 SlotSize, /*AllowHigherAlign*/ true); 7000 } 7001 7002 //===----------------------------------------------------------------------===// 7003 // NVPTX ABI Implementation 7004 //===----------------------------------------------------------------------===// 7005 7006 namespace { 7007 7008 class NVPTXTargetCodeGenInfo; 7009 7010 class NVPTXABIInfo : public ABIInfo { 7011 NVPTXTargetCodeGenInfo &CGInfo; 7012 7013 public: 7014 NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info) 7015 : ABIInfo(CGT), CGInfo(Info) {} 7016 7017 ABIArgInfo classifyReturnType(QualType RetTy) const; 7018 ABIArgInfo classifyArgumentType(QualType Ty) const; 7019 7020 void computeInfo(CGFunctionInfo &FI) const override; 7021 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7022 QualType Ty) const override; 7023 bool isUnsupportedType(QualType T) const; 7024 ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const; 7025 }; 7026 7027 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 7028 public: 7029 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 7030 : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {} 7031 7032 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7033 CodeGen::CodeGenModule &M) const override; 7034 bool shouldEmitStaticExternCAliases() const override; 7035 7036 llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override { 7037 // On the device side, surface reference is represented as an object handle 7038 // in 64-bit integer. 7039 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 7040 } 7041 7042 llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override { 7043 // On the device side, texture reference is represented as an object handle 7044 // in 64-bit integer. 7045 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 7046 } 7047 7048 bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7049 LValue Src) const override { 7050 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 7051 return true; 7052 } 7053 7054 bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7055 LValue Src) const override { 7056 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 7057 return true; 7058 } 7059 7060 private: 7061 // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the 7062 // resulting MDNode to the nvvm.annotations MDNode. 7063 static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name, 7064 int Operand); 7065 7066 static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7067 LValue Src) { 7068 llvm::Value *Handle = nullptr; 7069 llvm::Constant *C = 7070 llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer()); 7071 // Lookup `addrspacecast` through the constant pointer if any. 7072 if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C)) 7073 C = llvm::cast<llvm::Constant>(ASC->getPointerOperand()); 7074 if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) { 7075 // Load the handle from the specific global variable using 7076 // `nvvm.texsurf.handle.internal` intrinsic. 7077 Handle = CGF.EmitRuntimeCall( 7078 CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal, 7079 {GV->getType()}), 7080 {GV}, "texsurf_handle"); 7081 } else 7082 Handle = CGF.EmitLoadOfScalar(Src, SourceLocation()); 7083 CGF.EmitStoreOfScalar(Handle, Dst); 7084 } 7085 }; 7086 7087 /// Checks if the type is unsupported directly by the current target. 7088 bool NVPTXABIInfo::isUnsupportedType(QualType T) const { 7089 ASTContext &Context = getContext(); 7090 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type()) 7091 return true; 7092 if (!Context.getTargetInfo().hasFloat128Type() && 7093 (T->isFloat128Type() || 7094 (T->isRealFloatingType() && Context.getTypeSize(T) == 128))) 7095 return true; 7096 if (const auto *EIT = T->getAs<ExtIntType>()) 7097 return EIT->getNumBits() > 7098 (Context.getTargetInfo().hasInt128Type() ? 128U : 64U); 7099 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 7100 Context.getTypeSize(T) > 64U) 7101 return true; 7102 if (const auto *AT = T->getAsArrayTypeUnsafe()) 7103 return isUnsupportedType(AT->getElementType()); 7104 const auto *RT = T->getAs<RecordType>(); 7105 if (!RT) 7106 return false; 7107 const RecordDecl *RD = RT->getDecl(); 7108 7109 // If this is a C++ record, check the bases first. 7110 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7111 for (const CXXBaseSpecifier &I : CXXRD->bases()) 7112 if (isUnsupportedType(I.getType())) 7113 return true; 7114 7115 for (const FieldDecl *I : RD->fields()) 7116 if (isUnsupportedType(I->getType())) 7117 return true; 7118 return false; 7119 } 7120 7121 /// Coerce the given type into an array with maximum allowed size of elements. 7122 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty, 7123 unsigned MaxSize) const { 7124 // Alignment and Size are measured in bits. 7125 const uint64_t Size = getContext().getTypeSize(Ty); 7126 const uint64_t Alignment = getContext().getTypeAlign(Ty); 7127 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 7128 llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div); 7129 const uint64_t NumElements = (Size + Div - 1) / Div; 7130 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 7131 } 7132 7133 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 7134 if (RetTy->isVoidType()) 7135 return ABIArgInfo::getIgnore(); 7136 7137 if (getContext().getLangOpts().OpenMP && 7138 getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy)) 7139 return coerceToIntArrayWithLimit(RetTy, 64); 7140 7141 // note: this is different from default ABI 7142 if (!RetTy->isScalarType()) 7143 return ABIArgInfo::getDirect(); 7144 7145 // Treat an enum type as its underlying type. 7146 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7147 RetTy = EnumTy->getDecl()->getIntegerType(); 7148 7149 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7150 : ABIArgInfo::getDirect()); 7151 } 7152 7153 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 7154 // Treat an enum type as its underlying type. 7155 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7156 Ty = EnumTy->getDecl()->getIntegerType(); 7157 7158 // Return aggregates type as indirect by value 7159 if (isAggregateTypeForABI(Ty)) { 7160 // Under CUDA device compilation, tex/surf builtin types are replaced with 7161 // object types and passed directly. 7162 if (getContext().getLangOpts().CUDAIsDevice) { 7163 if (Ty->isCUDADeviceBuiltinSurfaceType()) 7164 return ABIArgInfo::getDirect( 7165 CGInfo.getCUDADeviceBuiltinSurfaceDeviceType()); 7166 if (Ty->isCUDADeviceBuiltinTextureType()) 7167 return ABIArgInfo::getDirect( 7168 CGInfo.getCUDADeviceBuiltinTextureDeviceType()); 7169 } 7170 return getNaturalAlignIndirect(Ty, /* byval */ true); 7171 } 7172 7173 if (const auto *EIT = Ty->getAs<ExtIntType>()) { 7174 if ((EIT->getNumBits() > 128) || 7175 (!getContext().getTargetInfo().hasInt128Type() && 7176 EIT->getNumBits() > 64)) 7177 return getNaturalAlignIndirect(Ty, /* byval */ true); 7178 } 7179 7180 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 7181 : ABIArgInfo::getDirect()); 7182 } 7183 7184 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 7185 if (!getCXXABI().classifyReturnType(FI)) 7186 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7187 for (auto &I : FI.arguments()) 7188 I.info = classifyArgumentType(I.type); 7189 7190 // Always honor user-specified calling convention. 7191 if (FI.getCallingConvention() != llvm::CallingConv::C) 7192 return; 7193 7194 FI.setEffectiveCallingConvention(getRuntimeCC()); 7195 } 7196 7197 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7198 QualType Ty) const { 7199 llvm_unreachable("NVPTX does not support varargs"); 7200 } 7201 7202 void NVPTXTargetCodeGenInfo::setTargetAttributes( 7203 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7204 if (GV->isDeclaration()) 7205 return; 7206 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 7207 if (VD) { 7208 if (M.getLangOpts().CUDA) { 7209 if (VD->getType()->isCUDADeviceBuiltinSurfaceType()) 7210 addNVVMMetadata(GV, "surface", 1); 7211 else if (VD->getType()->isCUDADeviceBuiltinTextureType()) 7212 addNVVMMetadata(GV, "texture", 1); 7213 return; 7214 } 7215 } 7216 7217 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7218 if (!FD) return; 7219 7220 llvm::Function *F = cast<llvm::Function>(GV); 7221 7222 // Perform special handling in OpenCL mode 7223 if (M.getLangOpts().OpenCL) { 7224 // Use OpenCL function attributes to check for kernel functions 7225 // By default, all functions are device functions 7226 if (FD->hasAttr<OpenCLKernelAttr>()) { 7227 // OpenCL __kernel functions get kernel metadata 7228 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7229 addNVVMMetadata(F, "kernel", 1); 7230 // And kernel functions are not subject to inlining 7231 F->addFnAttr(llvm::Attribute::NoInline); 7232 } 7233 } 7234 7235 // Perform special handling in CUDA mode. 7236 if (M.getLangOpts().CUDA) { 7237 // CUDA __global__ functions get a kernel metadata entry. Since 7238 // __global__ functions cannot be called from the device, we do not 7239 // need to set the noinline attribute. 7240 if (FD->hasAttr<CUDAGlobalAttr>()) { 7241 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7242 addNVVMMetadata(F, "kernel", 1); 7243 } 7244 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 7245 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 7246 llvm::APSInt MaxThreads(32); 7247 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 7248 if (MaxThreads > 0) 7249 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 7250 7251 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 7252 // not specified in __launch_bounds__ or if the user specified a 0 value, 7253 // we don't have to add a PTX directive. 7254 if (Attr->getMinBlocks()) { 7255 llvm::APSInt MinBlocks(32); 7256 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 7257 if (MinBlocks > 0) 7258 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 7259 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 7260 } 7261 } 7262 } 7263 } 7264 7265 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV, 7266 StringRef Name, int Operand) { 7267 llvm::Module *M = GV->getParent(); 7268 llvm::LLVMContext &Ctx = M->getContext(); 7269 7270 // Get "nvvm.annotations" metadata node 7271 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 7272 7273 llvm::Metadata *MDVals[] = { 7274 llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name), 7275 llvm::ConstantAsMetadata::get( 7276 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 7277 // Append metadata to nvvm.annotations 7278 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 7279 } 7280 7281 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 7282 return false; 7283 } 7284 } 7285 7286 //===----------------------------------------------------------------------===// 7287 // SystemZ ABI Implementation 7288 //===----------------------------------------------------------------------===// 7289 7290 namespace { 7291 7292 class SystemZABIInfo : public SwiftABIInfo { 7293 bool HasVector; 7294 bool IsSoftFloatABI; 7295 7296 public: 7297 SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF) 7298 : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {} 7299 7300 bool isPromotableIntegerTypeForABI(QualType Ty) const; 7301 bool isCompoundType(QualType Ty) const; 7302 bool isVectorArgumentType(QualType Ty) const; 7303 bool isFPArgumentType(QualType Ty) const; 7304 QualType GetSingleElementType(QualType Ty) const; 7305 7306 ABIArgInfo classifyReturnType(QualType RetTy) const; 7307 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 7308 7309 void computeInfo(CGFunctionInfo &FI) const override { 7310 if (!getCXXABI().classifyReturnType(FI)) 7311 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7312 for (auto &I : FI.arguments()) 7313 I.info = classifyArgumentType(I.type); 7314 } 7315 7316 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7317 QualType Ty) const override; 7318 7319 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 7320 bool asReturnValue) const override { 7321 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 7322 } 7323 bool isSwiftErrorInRegister() const override { 7324 return false; 7325 } 7326 }; 7327 7328 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 7329 public: 7330 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI) 7331 : TargetCodeGenInfo( 7332 std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {} 7333 7334 llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID, 7335 CGBuilderTy &Builder, 7336 CodeGenModule &CGM) const override { 7337 assert(V->getType()->isFloatingPointTy() && "V should have an FP type."); 7338 // Only use TDC in constrained FP mode. 7339 if (!Builder.getIsFPConstrained()) 7340 return nullptr; 7341 7342 llvm::Type *Ty = V->getType(); 7343 if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) { 7344 llvm::Module &M = CGM.getModule(); 7345 auto &Ctx = M.getContext(); 7346 llvm::Function *TDCFunc = 7347 llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty); 7348 unsigned TDCBits = 0; 7349 switch (BuiltinID) { 7350 case Builtin::BI__builtin_isnan: 7351 TDCBits = 0xf; 7352 break; 7353 case Builtin::BIfinite: 7354 case Builtin::BI__finite: 7355 case Builtin::BIfinitef: 7356 case Builtin::BI__finitef: 7357 case Builtin::BIfinitel: 7358 case Builtin::BI__finitel: 7359 case Builtin::BI__builtin_isfinite: 7360 TDCBits = 0xfc0; 7361 break; 7362 case Builtin::BI__builtin_isinf: 7363 TDCBits = 0x30; 7364 break; 7365 default: 7366 break; 7367 } 7368 if (TDCBits) 7369 return Builder.CreateCall( 7370 TDCFunc, 7371 {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)}); 7372 } 7373 return nullptr; 7374 } 7375 }; 7376 } 7377 7378 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 7379 // Treat an enum type as its underlying type. 7380 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7381 Ty = EnumTy->getDecl()->getIntegerType(); 7382 7383 // Promotable integer types are required to be promoted by the ABI. 7384 if (ABIInfo::isPromotableIntegerTypeForABI(Ty)) 7385 return true; 7386 7387 if (const auto *EIT = Ty->getAs<ExtIntType>()) 7388 if (EIT->getNumBits() < 64) 7389 return true; 7390 7391 // 32-bit values must also be promoted. 7392 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7393 switch (BT->getKind()) { 7394 case BuiltinType::Int: 7395 case BuiltinType::UInt: 7396 return true; 7397 default: 7398 return false; 7399 } 7400 return false; 7401 } 7402 7403 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 7404 return (Ty->isAnyComplexType() || 7405 Ty->isVectorType() || 7406 isAggregateTypeForABI(Ty)); 7407 } 7408 7409 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 7410 return (HasVector && 7411 Ty->isVectorType() && 7412 getContext().getTypeSize(Ty) <= 128); 7413 } 7414 7415 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 7416 if (IsSoftFloatABI) 7417 return false; 7418 7419 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7420 switch (BT->getKind()) { 7421 case BuiltinType::Float: 7422 case BuiltinType::Double: 7423 return true; 7424 default: 7425 return false; 7426 } 7427 7428 return false; 7429 } 7430 7431 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 7432 const RecordType *RT = Ty->getAs<RecordType>(); 7433 7434 if (RT && RT->isStructureOrClassType()) { 7435 const RecordDecl *RD = RT->getDecl(); 7436 QualType Found; 7437 7438 // If this is a C++ record, check the bases first. 7439 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7440 for (const auto &I : CXXRD->bases()) { 7441 QualType Base = I.getType(); 7442 7443 // Empty bases don't affect things either way. 7444 if (isEmptyRecord(getContext(), Base, true)) 7445 continue; 7446 7447 if (!Found.isNull()) 7448 return Ty; 7449 Found = GetSingleElementType(Base); 7450 } 7451 7452 // Check the fields. 7453 for (const auto *FD : RD->fields()) { 7454 // For compatibility with GCC, ignore empty bitfields in C++ mode. 7455 // Unlike isSingleElementStruct(), empty structure and array fields 7456 // do count. So do anonymous bitfields that aren't zero-sized. 7457 if (getContext().getLangOpts().CPlusPlus && 7458 FD->isZeroLengthBitField(getContext())) 7459 continue; 7460 // Like isSingleElementStruct(), ignore C++20 empty data members. 7461 if (FD->hasAttr<NoUniqueAddressAttr>() && 7462 isEmptyRecord(getContext(), FD->getType(), true)) 7463 continue; 7464 7465 // Unlike isSingleElementStruct(), arrays do not count. 7466 // Nested structures still do though. 7467 if (!Found.isNull()) 7468 return Ty; 7469 Found = GetSingleElementType(FD->getType()); 7470 } 7471 7472 // Unlike isSingleElementStruct(), trailing padding is allowed. 7473 // An 8-byte aligned struct s { float f; } is passed as a double. 7474 if (!Found.isNull()) 7475 return Found; 7476 } 7477 7478 return Ty; 7479 } 7480 7481 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7482 QualType Ty) const { 7483 // Assume that va_list type is correct; should be pointer to LLVM type: 7484 // struct { 7485 // i64 __gpr; 7486 // i64 __fpr; 7487 // i8 *__overflow_arg_area; 7488 // i8 *__reg_save_area; 7489 // }; 7490 7491 // Every non-vector argument occupies 8 bytes and is passed by preference 7492 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 7493 // always passed on the stack. 7494 Ty = getContext().getCanonicalType(Ty); 7495 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7496 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 7497 llvm::Type *DirectTy = ArgTy; 7498 ABIArgInfo AI = classifyArgumentType(Ty); 7499 bool IsIndirect = AI.isIndirect(); 7500 bool InFPRs = false; 7501 bool IsVector = false; 7502 CharUnits UnpaddedSize; 7503 CharUnits DirectAlign; 7504 if (IsIndirect) { 7505 DirectTy = llvm::PointerType::getUnqual(DirectTy); 7506 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 7507 } else { 7508 if (AI.getCoerceToType()) 7509 ArgTy = AI.getCoerceToType(); 7510 InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy())); 7511 IsVector = ArgTy->isVectorTy(); 7512 UnpaddedSize = TyInfo.Width; 7513 DirectAlign = TyInfo.Align; 7514 } 7515 CharUnits PaddedSize = CharUnits::fromQuantity(8); 7516 if (IsVector && UnpaddedSize > PaddedSize) 7517 PaddedSize = CharUnits::fromQuantity(16); 7518 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 7519 7520 CharUnits Padding = (PaddedSize - UnpaddedSize); 7521 7522 llvm::Type *IndexTy = CGF.Int64Ty; 7523 llvm::Value *PaddedSizeV = 7524 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 7525 7526 if (IsVector) { 7527 // Work out the address of a vector argument on the stack. 7528 // Vector arguments are always passed in the high bits of a 7529 // single (8 byte) or double (16 byte) stack slot. 7530 Address OverflowArgAreaPtr = 7531 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7532 Address OverflowArgArea = 7533 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7534 TyInfo.Align); 7535 Address MemAddr = 7536 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 7537 7538 // Update overflow_arg_area_ptr pointer 7539 llvm::Value *NewOverflowArgArea = 7540 CGF.Builder.CreateGEP(OverflowArgArea.getElementType(), 7541 OverflowArgArea.getPointer(), PaddedSizeV, 7542 "overflow_arg_area"); 7543 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7544 7545 return MemAddr; 7546 } 7547 7548 assert(PaddedSize.getQuantity() == 8); 7549 7550 unsigned MaxRegs, RegCountField, RegSaveIndex; 7551 CharUnits RegPadding; 7552 if (InFPRs) { 7553 MaxRegs = 4; // Maximum of 4 FPR arguments 7554 RegCountField = 1; // __fpr 7555 RegSaveIndex = 16; // save offset for f0 7556 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 7557 } else { 7558 MaxRegs = 5; // Maximum of 5 GPR arguments 7559 RegCountField = 0; // __gpr 7560 RegSaveIndex = 2; // save offset for r2 7561 RegPadding = Padding; // values are passed in the low bits of a GPR 7562 } 7563 7564 Address RegCountPtr = 7565 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 7566 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 7567 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 7568 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 7569 "fits_in_regs"); 7570 7571 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 7572 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 7573 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 7574 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 7575 7576 // Emit code to load the value if it was passed in registers. 7577 CGF.EmitBlock(InRegBlock); 7578 7579 // Work out the address of an argument register. 7580 llvm::Value *ScaledRegCount = 7581 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 7582 llvm::Value *RegBase = 7583 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 7584 + RegPadding.getQuantity()); 7585 llvm::Value *RegOffset = 7586 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 7587 Address RegSaveAreaPtr = 7588 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 7589 llvm::Value *RegSaveArea = 7590 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 7591 Address RawRegAddr(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset, 7592 "raw_reg_addr"), 7593 PaddedSize); 7594 Address RegAddr = 7595 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 7596 7597 // Update the register count 7598 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 7599 llvm::Value *NewRegCount = 7600 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 7601 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 7602 CGF.EmitBranch(ContBlock); 7603 7604 // Emit code to load the value if it was passed in memory. 7605 CGF.EmitBlock(InMemBlock); 7606 7607 // Work out the address of a stack argument. 7608 Address OverflowArgAreaPtr = 7609 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7610 Address OverflowArgArea = 7611 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7612 PaddedSize); 7613 Address RawMemAddr = 7614 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 7615 Address MemAddr = 7616 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 7617 7618 // Update overflow_arg_area_ptr pointer 7619 llvm::Value *NewOverflowArgArea = 7620 CGF.Builder.CreateGEP(OverflowArgArea.getElementType(), 7621 OverflowArgArea.getPointer(), PaddedSizeV, 7622 "overflow_arg_area"); 7623 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7624 CGF.EmitBranch(ContBlock); 7625 7626 // Return the appropriate result. 7627 CGF.EmitBlock(ContBlock); 7628 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 7629 MemAddr, InMemBlock, "va_arg.addr"); 7630 7631 if (IsIndirect) 7632 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), 7633 TyInfo.Align); 7634 7635 return ResAddr; 7636 } 7637 7638 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 7639 if (RetTy->isVoidType()) 7640 return ABIArgInfo::getIgnore(); 7641 if (isVectorArgumentType(RetTy)) 7642 return ABIArgInfo::getDirect(); 7643 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 7644 return getNaturalAlignIndirect(RetTy); 7645 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7646 : ABIArgInfo::getDirect()); 7647 } 7648 7649 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 7650 // Handle the generic C++ ABI. 7651 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7652 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7653 7654 // Integers and enums are extended to full register width. 7655 if (isPromotableIntegerTypeForABI(Ty)) 7656 return ABIArgInfo::getExtend(Ty); 7657 7658 // Handle vector types and vector-like structure types. Note that 7659 // as opposed to float-like structure types, we do not allow any 7660 // padding for vector-like structures, so verify the sizes match. 7661 uint64_t Size = getContext().getTypeSize(Ty); 7662 QualType SingleElementTy = GetSingleElementType(Ty); 7663 if (isVectorArgumentType(SingleElementTy) && 7664 getContext().getTypeSize(SingleElementTy) == Size) 7665 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 7666 7667 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 7668 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 7669 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7670 7671 // Handle small structures. 7672 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7673 // Structures with flexible arrays have variable length, so really 7674 // fail the size test above. 7675 const RecordDecl *RD = RT->getDecl(); 7676 if (RD->hasFlexibleArrayMember()) 7677 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7678 7679 // The structure is passed as an unextended integer, a float, or a double. 7680 llvm::Type *PassTy; 7681 if (isFPArgumentType(SingleElementTy)) { 7682 assert(Size == 32 || Size == 64); 7683 if (Size == 32) 7684 PassTy = llvm::Type::getFloatTy(getVMContext()); 7685 else 7686 PassTy = llvm::Type::getDoubleTy(getVMContext()); 7687 } else 7688 PassTy = llvm::IntegerType::get(getVMContext(), Size); 7689 return ABIArgInfo::getDirect(PassTy); 7690 } 7691 7692 // Non-structure compounds are passed indirectly. 7693 if (isCompoundType(Ty)) 7694 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7695 7696 return ABIArgInfo::getDirect(nullptr); 7697 } 7698 7699 //===----------------------------------------------------------------------===// 7700 // MSP430 ABI Implementation 7701 //===----------------------------------------------------------------------===// 7702 7703 namespace { 7704 7705 class MSP430ABIInfo : public DefaultABIInfo { 7706 static ABIArgInfo complexArgInfo() { 7707 ABIArgInfo Info = ABIArgInfo::getDirect(); 7708 Info.setCanBeFlattened(false); 7709 return Info; 7710 } 7711 7712 public: 7713 MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7714 7715 ABIArgInfo classifyReturnType(QualType RetTy) const { 7716 if (RetTy->isAnyComplexType()) 7717 return complexArgInfo(); 7718 7719 return DefaultABIInfo::classifyReturnType(RetTy); 7720 } 7721 7722 ABIArgInfo classifyArgumentType(QualType RetTy) const { 7723 if (RetTy->isAnyComplexType()) 7724 return complexArgInfo(); 7725 7726 return DefaultABIInfo::classifyArgumentType(RetTy); 7727 } 7728 7729 // Just copy the original implementations because 7730 // DefaultABIInfo::classify{Return,Argument}Type() are not virtual 7731 void computeInfo(CGFunctionInfo &FI) const override { 7732 if (!getCXXABI().classifyReturnType(FI)) 7733 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7734 for (auto &I : FI.arguments()) 7735 I.info = classifyArgumentType(I.type); 7736 } 7737 7738 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7739 QualType Ty) const override { 7740 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 7741 } 7742 }; 7743 7744 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 7745 public: 7746 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 7747 : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {} 7748 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7749 CodeGen::CodeGenModule &M) const override; 7750 }; 7751 7752 } 7753 7754 void MSP430TargetCodeGenInfo::setTargetAttributes( 7755 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7756 if (GV->isDeclaration()) 7757 return; 7758 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 7759 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 7760 if (!InterruptAttr) 7761 return; 7762 7763 // Handle 'interrupt' attribute: 7764 llvm::Function *F = cast<llvm::Function>(GV); 7765 7766 // Step 1: Set ISR calling convention. 7767 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 7768 7769 // Step 2: Add attributes goodness. 7770 F->addFnAttr(llvm::Attribute::NoInline); 7771 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 7772 } 7773 } 7774 7775 //===----------------------------------------------------------------------===// 7776 // MIPS ABI Implementation. This works for both little-endian and 7777 // big-endian variants. 7778 //===----------------------------------------------------------------------===// 7779 7780 namespace { 7781 class MipsABIInfo : public ABIInfo { 7782 bool IsO32; 7783 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 7784 void CoerceToIntArgs(uint64_t TySize, 7785 SmallVectorImpl<llvm::Type *> &ArgList) const; 7786 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 7787 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 7788 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 7789 public: 7790 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 7791 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 7792 StackAlignInBytes(IsO32 ? 8 : 16) {} 7793 7794 ABIArgInfo classifyReturnType(QualType RetTy) const; 7795 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 7796 void computeInfo(CGFunctionInfo &FI) const override; 7797 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7798 QualType Ty) const override; 7799 ABIArgInfo extendType(QualType Ty) const; 7800 }; 7801 7802 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 7803 unsigned SizeOfUnwindException; 7804 public: 7805 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 7806 : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)), 7807 SizeOfUnwindException(IsO32 ? 24 : 32) {} 7808 7809 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 7810 return 29; 7811 } 7812 7813 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7814 CodeGen::CodeGenModule &CGM) const override { 7815 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7816 if (!FD) return; 7817 llvm::Function *Fn = cast<llvm::Function>(GV); 7818 7819 if (FD->hasAttr<MipsLongCallAttr>()) 7820 Fn->addFnAttr("long-call"); 7821 else if (FD->hasAttr<MipsShortCallAttr>()) 7822 Fn->addFnAttr("short-call"); 7823 7824 // Other attributes do not have a meaning for declarations. 7825 if (GV->isDeclaration()) 7826 return; 7827 7828 if (FD->hasAttr<Mips16Attr>()) { 7829 Fn->addFnAttr("mips16"); 7830 } 7831 else if (FD->hasAttr<NoMips16Attr>()) { 7832 Fn->addFnAttr("nomips16"); 7833 } 7834 7835 if (FD->hasAttr<MicroMipsAttr>()) 7836 Fn->addFnAttr("micromips"); 7837 else if (FD->hasAttr<NoMicroMipsAttr>()) 7838 Fn->addFnAttr("nomicromips"); 7839 7840 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 7841 if (!Attr) 7842 return; 7843 7844 const char *Kind; 7845 switch (Attr->getInterrupt()) { 7846 case MipsInterruptAttr::eic: Kind = "eic"; break; 7847 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 7848 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 7849 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 7850 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 7851 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 7852 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 7853 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 7854 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 7855 } 7856 7857 Fn->addFnAttr("interrupt", Kind); 7858 7859 } 7860 7861 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7862 llvm::Value *Address) const override; 7863 7864 unsigned getSizeOfUnwindException() const override { 7865 return SizeOfUnwindException; 7866 } 7867 }; 7868 } 7869 7870 void MipsABIInfo::CoerceToIntArgs( 7871 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 7872 llvm::IntegerType *IntTy = 7873 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 7874 7875 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 7876 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 7877 ArgList.push_back(IntTy); 7878 7879 // If necessary, add one more integer type to ArgList. 7880 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 7881 7882 if (R) 7883 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 7884 } 7885 7886 // In N32/64, an aligned double precision floating point field is passed in 7887 // a register. 7888 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7889 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7890 7891 if (IsO32) { 7892 CoerceToIntArgs(TySize, ArgList); 7893 return llvm::StructType::get(getVMContext(), ArgList); 7894 } 7895 7896 if (Ty->isComplexType()) 7897 return CGT.ConvertType(Ty); 7898 7899 const RecordType *RT = Ty->getAs<RecordType>(); 7900 7901 // Unions/vectors are passed in integer registers. 7902 if (!RT || !RT->isStructureOrClassType()) { 7903 CoerceToIntArgs(TySize, ArgList); 7904 return llvm::StructType::get(getVMContext(), ArgList); 7905 } 7906 7907 const RecordDecl *RD = RT->getDecl(); 7908 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7909 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7910 7911 uint64_t LastOffset = 0; 7912 unsigned idx = 0; 7913 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7914 7915 // Iterate over fields in the struct/class and check if there are any aligned 7916 // double fields. 7917 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7918 i != e; ++i, ++idx) { 7919 const QualType Ty = i->getType(); 7920 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7921 7922 if (!BT || BT->getKind() != BuiltinType::Double) 7923 continue; 7924 7925 uint64_t Offset = Layout.getFieldOffset(idx); 7926 if (Offset % 64) // Ignore doubles that are not aligned. 7927 continue; 7928 7929 // Add ((Offset - LastOffset) / 64) args of type i64. 7930 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7931 ArgList.push_back(I64); 7932 7933 // Add double type. 7934 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7935 LastOffset = Offset + 64; 7936 } 7937 7938 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7939 ArgList.append(IntArgList.begin(), IntArgList.end()); 7940 7941 return llvm::StructType::get(getVMContext(), ArgList); 7942 } 7943 7944 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 7945 uint64_t Offset) const { 7946 if (OrigOffset + MinABIStackAlignInBytes > Offset) 7947 return nullptr; 7948 7949 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 7950 } 7951 7952 ABIArgInfo 7953 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 7954 Ty = useFirstFieldIfTransparentUnion(Ty); 7955 7956 uint64_t OrigOffset = Offset; 7957 uint64_t TySize = getContext().getTypeSize(Ty); 7958 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 7959 7960 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 7961 (uint64_t)StackAlignInBytes); 7962 unsigned CurrOffset = llvm::alignTo(Offset, Align); 7963 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 7964 7965 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 7966 // Ignore empty aggregates. 7967 if (TySize == 0) 7968 return ABIArgInfo::getIgnore(); 7969 7970 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 7971 Offset = OrigOffset + MinABIStackAlignInBytes; 7972 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7973 } 7974 7975 // If we have reached here, aggregates are passed directly by coercing to 7976 // another structure type. Padding is inserted if the offset of the 7977 // aggregate is unaligned. 7978 ABIArgInfo ArgInfo = 7979 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 7980 getPaddingType(OrigOffset, CurrOffset)); 7981 ArgInfo.setInReg(true); 7982 return ArgInfo; 7983 } 7984 7985 // Treat an enum type as its underlying type. 7986 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7987 Ty = EnumTy->getDecl()->getIntegerType(); 7988 7989 // Make sure we pass indirectly things that are too large. 7990 if (const auto *EIT = Ty->getAs<ExtIntType>()) 7991 if (EIT->getNumBits() > 128 || 7992 (EIT->getNumBits() > 64 && 7993 !getContext().getTargetInfo().hasInt128Type())) 7994 return getNaturalAlignIndirect(Ty); 7995 7996 // All integral types are promoted to the GPR width. 7997 if (Ty->isIntegralOrEnumerationType()) 7998 return extendType(Ty); 7999 8000 return ABIArgInfo::getDirect( 8001 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 8002 } 8003 8004 llvm::Type* 8005 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 8006 const RecordType *RT = RetTy->getAs<RecordType>(); 8007 SmallVector<llvm::Type*, 8> RTList; 8008 8009 if (RT && RT->isStructureOrClassType()) { 8010 const RecordDecl *RD = RT->getDecl(); 8011 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 8012 unsigned FieldCnt = Layout.getFieldCount(); 8013 8014 // N32/64 returns struct/classes in floating point registers if the 8015 // following conditions are met: 8016 // 1. The size of the struct/class is no larger than 128-bit. 8017 // 2. The struct/class has one or two fields all of which are floating 8018 // point types. 8019 // 3. The offset of the first field is zero (this follows what gcc does). 8020 // 8021 // Any other composite results are returned in integer registers. 8022 // 8023 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 8024 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 8025 for (; b != e; ++b) { 8026 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 8027 8028 if (!BT || !BT->isFloatingPoint()) 8029 break; 8030 8031 RTList.push_back(CGT.ConvertType(b->getType())); 8032 } 8033 8034 if (b == e) 8035 return llvm::StructType::get(getVMContext(), RTList, 8036 RD->hasAttr<PackedAttr>()); 8037 8038 RTList.clear(); 8039 } 8040 } 8041 8042 CoerceToIntArgs(Size, RTList); 8043 return llvm::StructType::get(getVMContext(), RTList); 8044 } 8045 8046 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 8047 uint64_t Size = getContext().getTypeSize(RetTy); 8048 8049 if (RetTy->isVoidType()) 8050 return ABIArgInfo::getIgnore(); 8051 8052 // O32 doesn't treat zero-sized structs differently from other structs. 8053 // However, N32/N64 ignores zero sized return values. 8054 if (!IsO32 && Size == 0) 8055 return ABIArgInfo::getIgnore(); 8056 8057 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 8058 if (Size <= 128) { 8059 if (RetTy->isAnyComplexType()) 8060 return ABIArgInfo::getDirect(); 8061 8062 // O32 returns integer vectors in registers and N32/N64 returns all small 8063 // aggregates in registers. 8064 if (!IsO32 || 8065 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 8066 ABIArgInfo ArgInfo = 8067 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 8068 ArgInfo.setInReg(true); 8069 return ArgInfo; 8070 } 8071 } 8072 8073 return getNaturalAlignIndirect(RetTy); 8074 } 8075 8076 // Treat an enum type as its underlying type. 8077 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8078 RetTy = EnumTy->getDecl()->getIntegerType(); 8079 8080 // Make sure we pass indirectly things that are too large. 8081 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 8082 if (EIT->getNumBits() > 128 || 8083 (EIT->getNumBits() > 64 && 8084 !getContext().getTargetInfo().hasInt128Type())) 8085 return getNaturalAlignIndirect(RetTy); 8086 8087 if (isPromotableIntegerTypeForABI(RetTy)) 8088 return ABIArgInfo::getExtend(RetTy); 8089 8090 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 8091 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 8092 return ABIArgInfo::getSignExtend(RetTy); 8093 8094 return ABIArgInfo::getDirect(); 8095 } 8096 8097 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 8098 ABIArgInfo &RetInfo = FI.getReturnInfo(); 8099 if (!getCXXABI().classifyReturnType(FI)) 8100 RetInfo = classifyReturnType(FI.getReturnType()); 8101 8102 // Check if a pointer to an aggregate is passed as a hidden argument. 8103 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 8104 8105 for (auto &I : FI.arguments()) 8106 I.info = classifyArgumentType(I.type, Offset); 8107 } 8108 8109 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8110 QualType OrigTy) const { 8111 QualType Ty = OrigTy; 8112 8113 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 8114 // Pointers are also promoted in the same way but this only matters for N32. 8115 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 8116 unsigned PtrWidth = getTarget().getPointerWidth(0); 8117 bool DidPromote = false; 8118 if ((Ty->isIntegerType() && 8119 getContext().getIntWidth(Ty) < SlotSizeInBits) || 8120 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 8121 DidPromote = true; 8122 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 8123 Ty->isSignedIntegerType()); 8124 } 8125 8126 auto TyInfo = getContext().getTypeInfoInChars(Ty); 8127 8128 // The alignment of things in the argument area is never larger than 8129 // StackAlignInBytes. 8130 TyInfo.Align = 8131 std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes)); 8132 8133 // MinABIStackAlignInBytes is the size of argument slots on the stack. 8134 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 8135 8136 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 8137 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 8138 8139 8140 // If there was a promotion, "unpromote" into a temporary. 8141 // TODO: can we just use a pointer into a subset of the original slot? 8142 if (DidPromote) { 8143 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 8144 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 8145 8146 // Truncate down to the right width. 8147 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 8148 : CGF.IntPtrTy); 8149 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 8150 if (OrigTy->isPointerType()) 8151 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 8152 8153 CGF.Builder.CreateStore(V, Temp); 8154 Addr = Temp; 8155 } 8156 8157 return Addr; 8158 } 8159 8160 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 8161 int TySize = getContext().getTypeSize(Ty); 8162 8163 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 8164 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 8165 return ABIArgInfo::getSignExtend(Ty); 8166 8167 return ABIArgInfo::getExtend(Ty); 8168 } 8169 8170 bool 8171 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8172 llvm::Value *Address) const { 8173 // This information comes from gcc's implementation, which seems to 8174 // as canonical as it gets. 8175 8176 // Everything on MIPS is 4 bytes. Double-precision FP registers 8177 // are aliased to pairs of single-precision FP registers. 8178 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 8179 8180 // 0-31 are the general purpose registers, $0 - $31. 8181 // 32-63 are the floating-point registers, $f0 - $f31. 8182 // 64 and 65 are the multiply/divide registers, $hi and $lo. 8183 // 66 is the (notional, I think) register for signal-handler return. 8184 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 8185 8186 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 8187 // They are one bit wide and ignored here. 8188 8189 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 8190 // (coprocessor 1 is the FP unit) 8191 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 8192 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 8193 // 176-181 are the DSP accumulator registers. 8194 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 8195 return false; 8196 } 8197 8198 //===----------------------------------------------------------------------===// 8199 // M68k ABI Implementation 8200 //===----------------------------------------------------------------------===// 8201 8202 namespace { 8203 8204 class M68kTargetCodeGenInfo : public TargetCodeGenInfo { 8205 public: 8206 M68kTargetCodeGenInfo(CodeGenTypes &CGT) 8207 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 8208 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8209 CodeGen::CodeGenModule &M) const override; 8210 }; 8211 8212 } // namespace 8213 8214 void M68kTargetCodeGenInfo::setTargetAttributes( 8215 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8216 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 8217 if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) { 8218 // Handle 'interrupt' attribute: 8219 llvm::Function *F = cast<llvm::Function>(GV); 8220 8221 // Step 1: Set ISR calling convention. 8222 F->setCallingConv(llvm::CallingConv::M68k_INTR); 8223 8224 // Step 2: Add attributes goodness. 8225 F->addFnAttr(llvm::Attribute::NoInline); 8226 8227 // Step 3: Emit ISR vector alias. 8228 unsigned Num = attr->getNumber() / 2; 8229 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage, 8230 "__isr_" + Twine(Num), F); 8231 } 8232 } 8233 } 8234 8235 //===----------------------------------------------------------------------===// 8236 // AVR ABI Implementation. Documented at 8237 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention 8238 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny 8239 //===----------------------------------------------------------------------===// 8240 8241 namespace { 8242 class AVRABIInfo : public DefaultABIInfo { 8243 public: 8244 AVRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8245 8246 ABIArgInfo classifyReturnType(QualType Ty) const { 8247 // A return struct with size less than or equal to 8 bytes is returned 8248 // directly via registers R18-R25. 8249 if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) <= 64) 8250 return ABIArgInfo::getDirect(); 8251 else 8252 return DefaultABIInfo::classifyReturnType(Ty); 8253 } 8254 8255 // Just copy the original implementation of DefaultABIInfo::computeInfo(), 8256 // since DefaultABIInfo::classify{Return,Argument}Type() are not virtual. 8257 void computeInfo(CGFunctionInfo &FI) const override { 8258 if (!getCXXABI().classifyReturnType(FI)) 8259 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8260 for (auto &I : FI.arguments()) 8261 I.info = classifyArgumentType(I.type); 8262 } 8263 }; 8264 8265 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 8266 public: 8267 AVRTargetCodeGenInfo(CodeGenTypes &CGT) 8268 : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT)) {} 8269 8270 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 8271 const VarDecl *D) const override { 8272 // Check if a global/static variable is defined within address space 1 8273 // but not constant. 8274 LangAS AS = D->getType().getAddressSpace(); 8275 if (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 1 && 8276 !D->getType().isConstQualified()) 8277 CGM.getDiags().Report(D->getLocation(), 8278 diag::err_verify_nonconst_addrspace) 8279 << "__flash"; 8280 return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D); 8281 } 8282 8283 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8284 CodeGen::CodeGenModule &CGM) const override { 8285 if (GV->isDeclaration()) 8286 return; 8287 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 8288 if (!FD) return; 8289 auto *Fn = cast<llvm::Function>(GV); 8290 8291 if (FD->getAttr<AVRInterruptAttr>()) 8292 Fn->addFnAttr("interrupt"); 8293 8294 if (FD->getAttr<AVRSignalAttr>()) 8295 Fn->addFnAttr("signal"); 8296 } 8297 }; 8298 } 8299 8300 //===----------------------------------------------------------------------===// 8301 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 8302 // Currently subclassed only to implement custom OpenCL C function attribute 8303 // handling. 8304 //===----------------------------------------------------------------------===// 8305 8306 namespace { 8307 8308 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 8309 public: 8310 TCETargetCodeGenInfo(CodeGenTypes &CGT) 8311 : DefaultTargetCodeGenInfo(CGT) {} 8312 8313 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8314 CodeGen::CodeGenModule &M) const override; 8315 }; 8316 8317 void TCETargetCodeGenInfo::setTargetAttributes( 8318 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8319 if (GV->isDeclaration()) 8320 return; 8321 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8322 if (!FD) return; 8323 8324 llvm::Function *F = cast<llvm::Function>(GV); 8325 8326 if (M.getLangOpts().OpenCL) { 8327 if (FD->hasAttr<OpenCLKernelAttr>()) { 8328 // OpenCL C Kernel functions are not subject to inlining 8329 F->addFnAttr(llvm::Attribute::NoInline); 8330 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 8331 if (Attr) { 8332 // Convert the reqd_work_group_size() attributes to metadata. 8333 llvm::LLVMContext &Context = F->getContext(); 8334 llvm::NamedMDNode *OpenCLMetadata = 8335 M.getModule().getOrInsertNamedMetadata( 8336 "opencl.kernel_wg_size_info"); 8337 8338 SmallVector<llvm::Metadata *, 5> Operands; 8339 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 8340 8341 Operands.push_back( 8342 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8343 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 8344 Operands.push_back( 8345 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8346 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 8347 Operands.push_back( 8348 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8349 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 8350 8351 // Add a boolean constant operand for "required" (true) or "hint" 8352 // (false) for implementing the work_group_size_hint attr later. 8353 // Currently always true as the hint is not yet implemented. 8354 Operands.push_back( 8355 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 8356 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 8357 } 8358 } 8359 } 8360 } 8361 8362 } 8363 8364 //===----------------------------------------------------------------------===// 8365 // Hexagon ABI Implementation 8366 //===----------------------------------------------------------------------===// 8367 8368 namespace { 8369 8370 class HexagonABIInfo : public DefaultABIInfo { 8371 public: 8372 HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8373 8374 private: 8375 ABIArgInfo classifyReturnType(QualType RetTy) const; 8376 ABIArgInfo classifyArgumentType(QualType RetTy) const; 8377 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const; 8378 8379 void computeInfo(CGFunctionInfo &FI) const override; 8380 8381 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8382 QualType Ty) const override; 8383 Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr, 8384 QualType Ty) const; 8385 Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr, 8386 QualType Ty) const; 8387 Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr, 8388 QualType Ty) const; 8389 }; 8390 8391 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 8392 public: 8393 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 8394 : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {} 8395 8396 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8397 return 29; 8398 } 8399 8400 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8401 CodeGen::CodeGenModule &GCM) const override { 8402 if (GV->isDeclaration()) 8403 return; 8404 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8405 if (!FD) 8406 return; 8407 } 8408 }; 8409 8410 } // namespace 8411 8412 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 8413 unsigned RegsLeft = 6; 8414 if (!getCXXABI().classifyReturnType(FI)) 8415 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8416 for (auto &I : FI.arguments()) 8417 I.info = classifyArgumentType(I.type, &RegsLeft); 8418 } 8419 8420 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) { 8421 assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits" 8422 " through registers"); 8423 8424 if (*RegsLeft == 0) 8425 return false; 8426 8427 if (Size <= 32) { 8428 (*RegsLeft)--; 8429 return true; 8430 } 8431 8432 if (2 <= (*RegsLeft & (~1U))) { 8433 *RegsLeft = (*RegsLeft & (~1U)) - 2; 8434 return true; 8435 } 8436 8437 // Next available register was r5 but candidate was greater than 32-bits so it 8438 // has to go on the stack. However we still consume r5 8439 if (*RegsLeft == 1) 8440 *RegsLeft = 0; 8441 8442 return false; 8443 } 8444 8445 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty, 8446 unsigned *RegsLeft) const { 8447 if (!isAggregateTypeForABI(Ty)) { 8448 // Treat an enum type as its underlying type. 8449 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8450 Ty = EnumTy->getDecl()->getIntegerType(); 8451 8452 uint64_t Size = getContext().getTypeSize(Ty); 8453 if (Size <= 64) 8454 HexagonAdjustRegsLeft(Size, RegsLeft); 8455 8456 if (Size > 64 && Ty->isExtIntType()) 8457 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8458 8459 return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 8460 : ABIArgInfo::getDirect(); 8461 } 8462 8463 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8464 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8465 8466 // Ignore empty records. 8467 if (isEmptyRecord(getContext(), Ty, true)) 8468 return ABIArgInfo::getIgnore(); 8469 8470 uint64_t Size = getContext().getTypeSize(Ty); 8471 unsigned Align = getContext().getTypeAlign(Ty); 8472 8473 if (Size > 64) 8474 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8475 8476 if (HexagonAdjustRegsLeft(Size, RegsLeft)) 8477 Align = Size <= 32 ? 32 : 64; 8478 if (Size <= Align) { 8479 // Pass in the smallest viable integer type. 8480 if (!llvm::isPowerOf2_64(Size)) 8481 Size = llvm::NextPowerOf2(Size); 8482 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8483 } 8484 return DefaultABIInfo::classifyArgumentType(Ty); 8485 } 8486 8487 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 8488 if (RetTy->isVoidType()) 8489 return ABIArgInfo::getIgnore(); 8490 8491 const TargetInfo &T = CGT.getTarget(); 8492 uint64_t Size = getContext().getTypeSize(RetTy); 8493 8494 if (RetTy->getAs<VectorType>()) { 8495 // HVX vectors are returned in vector registers or register pairs. 8496 if (T.hasFeature("hvx")) { 8497 assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b")); 8498 uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8; 8499 if (Size == VecSize || Size == 2*VecSize) 8500 return ABIArgInfo::getDirectInReg(); 8501 } 8502 // Large vector types should be returned via memory. 8503 if (Size > 64) 8504 return getNaturalAlignIndirect(RetTy); 8505 } 8506 8507 if (!isAggregateTypeForABI(RetTy)) { 8508 // Treat an enum type as its underlying type. 8509 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8510 RetTy = EnumTy->getDecl()->getIntegerType(); 8511 8512 if (Size > 64 && RetTy->isExtIntType()) 8513 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 8514 8515 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 8516 : ABIArgInfo::getDirect(); 8517 } 8518 8519 if (isEmptyRecord(getContext(), RetTy, true)) 8520 return ABIArgInfo::getIgnore(); 8521 8522 // Aggregates <= 8 bytes are returned in registers, other aggregates 8523 // are returned indirectly. 8524 if (Size <= 64) { 8525 // Return in the smallest viable integer type. 8526 if (!llvm::isPowerOf2_64(Size)) 8527 Size = llvm::NextPowerOf2(Size); 8528 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8529 } 8530 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 8531 } 8532 8533 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF, 8534 Address VAListAddr, 8535 QualType Ty) const { 8536 // Load the overflow area pointer. 8537 Address __overflow_area_pointer_p = 8538 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8539 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8540 __overflow_area_pointer_p, "__overflow_area_pointer"); 8541 8542 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 8543 if (Align > 4) { 8544 // Alignment should be a power of 2. 8545 assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!"); 8546 8547 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 8548 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 8549 8550 // Add offset to the current pointer to access the argument. 8551 __overflow_area_pointer = 8552 CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset); 8553 llvm::Value *AsInt = 8554 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8555 8556 // Create a mask which should be "AND"ed 8557 // with (overflow_arg_area + align - 1) 8558 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align); 8559 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8560 CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(), 8561 "__overflow_area_pointer.align"); 8562 } 8563 8564 // Get the type of the argument from memory and bitcast 8565 // overflow area pointer to the argument type. 8566 llvm::Type *PTy = CGF.ConvertTypeForMem(Ty); 8567 Address AddrTyped = CGF.Builder.CreateBitCast( 8568 Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)), 8569 llvm::PointerType::getUnqual(PTy)); 8570 8571 // Round up to the minimum stack alignment for varargs which is 4 bytes. 8572 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8573 8574 __overflow_area_pointer = CGF.Builder.CreateGEP( 8575 CGF.Int8Ty, __overflow_area_pointer, 8576 llvm::ConstantInt::get(CGF.Int32Ty, Offset), 8577 "__overflow_area_pointer.next"); 8578 CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p); 8579 8580 return AddrTyped; 8581 } 8582 8583 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF, 8584 Address VAListAddr, 8585 QualType Ty) const { 8586 // FIXME: Need to handle alignment 8587 llvm::Type *BP = CGF.Int8PtrTy; 8588 llvm::Type *BPP = CGF.Int8PtrPtrTy; 8589 CGBuilderTy &Builder = CGF.Builder; 8590 Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 8591 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 8592 // Handle address alignment for type alignment > 32 bits 8593 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 8594 if (TyAlign > 4) { 8595 assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!"); 8596 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 8597 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 8598 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 8599 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 8600 } 8601 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 8602 Address AddrTyped = Builder.CreateBitCast( 8603 Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy); 8604 8605 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8606 llvm::Value *NextAddr = Builder.CreateGEP( 8607 CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next"); 8608 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 8609 8610 return AddrTyped; 8611 } 8612 8613 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF, 8614 Address VAListAddr, 8615 QualType Ty) const { 8616 int ArgSize = CGF.getContext().getTypeSize(Ty) / 8; 8617 8618 if (ArgSize > 8) 8619 return EmitVAArgFromMemory(CGF, VAListAddr, Ty); 8620 8621 // Here we have check if the argument is in register area or 8622 // in overflow area. 8623 // If the saved register area pointer + argsize rounded up to alignment > 8624 // saved register area end pointer, argument is in overflow area. 8625 unsigned RegsLeft = 6; 8626 Ty = CGF.getContext().getCanonicalType(Ty); 8627 (void)classifyArgumentType(Ty, &RegsLeft); 8628 8629 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 8630 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 8631 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 8632 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 8633 8634 // Get rounded size of the argument.GCC does not allow vararg of 8635 // size < 4 bytes. We follow the same logic here. 8636 ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8637 int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8638 8639 // Argument may be in saved register area 8640 CGF.EmitBlock(MaybeRegBlock); 8641 8642 // Load the current saved register area pointer. 8643 Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP( 8644 VAListAddr, 0, "__current_saved_reg_area_pointer_p"); 8645 llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad( 8646 __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer"); 8647 8648 // Load the saved register area end pointer. 8649 Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP( 8650 VAListAddr, 1, "__saved_reg_area_end_pointer_p"); 8651 llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad( 8652 __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer"); 8653 8654 // If the size of argument is > 4 bytes, check if the stack 8655 // location is aligned to 8 bytes 8656 if (ArgAlign > 4) { 8657 8658 llvm::Value *__current_saved_reg_area_pointer_int = 8659 CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer, 8660 CGF.Int32Ty); 8661 8662 __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd( 8663 __current_saved_reg_area_pointer_int, 8664 llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)), 8665 "align_current_saved_reg_area_pointer"); 8666 8667 __current_saved_reg_area_pointer_int = 8668 CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int, 8669 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8670 "align_current_saved_reg_area_pointer"); 8671 8672 __current_saved_reg_area_pointer = 8673 CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int, 8674 __current_saved_reg_area_pointer->getType(), 8675 "align_current_saved_reg_area_pointer"); 8676 } 8677 8678 llvm::Value *__new_saved_reg_area_pointer = 8679 CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer, 8680 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8681 "__new_saved_reg_area_pointer"); 8682 8683 llvm::Value *UsingStack = 0; 8684 UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer, 8685 __saved_reg_area_end_pointer); 8686 8687 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock); 8688 8689 // Argument in saved register area 8690 // Implement the block where argument is in register saved area 8691 CGF.EmitBlock(InRegBlock); 8692 8693 llvm::Type *PTy = CGF.ConvertType(Ty); 8694 llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast( 8695 __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy)); 8696 8697 CGF.Builder.CreateStore(__new_saved_reg_area_pointer, 8698 __current_saved_reg_area_pointer_p); 8699 8700 CGF.EmitBranch(ContBlock); 8701 8702 // Argument in overflow area 8703 // Implement the block where the argument is in overflow area. 8704 CGF.EmitBlock(OnStackBlock); 8705 8706 // Load the overflow area pointer 8707 Address __overflow_area_pointer_p = 8708 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8709 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8710 __overflow_area_pointer_p, "__overflow_area_pointer"); 8711 8712 // Align the overflow area pointer according to the alignment of the argument 8713 if (ArgAlign > 4) { 8714 llvm::Value *__overflow_area_pointer_int = 8715 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8716 8717 __overflow_area_pointer_int = 8718 CGF.Builder.CreateAdd(__overflow_area_pointer_int, 8719 llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1), 8720 "align_overflow_area_pointer"); 8721 8722 __overflow_area_pointer_int = 8723 CGF.Builder.CreateAnd(__overflow_area_pointer_int, 8724 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8725 "align_overflow_area_pointer"); 8726 8727 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8728 __overflow_area_pointer_int, __overflow_area_pointer->getType(), 8729 "align_overflow_area_pointer"); 8730 } 8731 8732 // Get the pointer for next argument in overflow area and store it 8733 // to overflow area pointer. 8734 llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP( 8735 CGF.Int8Ty, __overflow_area_pointer, 8736 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8737 "__overflow_area_pointer.next"); 8738 8739 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8740 __overflow_area_pointer_p); 8741 8742 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8743 __current_saved_reg_area_pointer_p); 8744 8745 // Bitcast the overflow area pointer to the type of argument. 8746 llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty); 8747 llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast( 8748 __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy)); 8749 8750 CGF.EmitBranch(ContBlock); 8751 8752 // Get the correct pointer to load the variable argument 8753 // Implement the ContBlock 8754 CGF.EmitBlock(ContBlock); 8755 8756 llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 8757 llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr"); 8758 ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock); 8759 ArgAddr->addIncoming(__overflow_area_p, OnStackBlock); 8760 8761 return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign)); 8762 } 8763 8764 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8765 QualType Ty) const { 8766 8767 if (getTarget().getTriple().isMusl()) 8768 return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty); 8769 8770 return EmitVAArgForHexagon(CGF, VAListAddr, Ty); 8771 } 8772 8773 //===----------------------------------------------------------------------===// 8774 // Lanai ABI Implementation 8775 //===----------------------------------------------------------------------===// 8776 8777 namespace { 8778 class LanaiABIInfo : public DefaultABIInfo { 8779 public: 8780 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8781 8782 bool shouldUseInReg(QualType Ty, CCState &State) const; 8783 8784 void computeInfo(CGFunctionInfo &FI) const override { 8785 CCState State(FI); 8786 // Lanai uses 4 registers to pass arguments unless the function has the 8787 // regparm attribute set. 8788 if (FI.getHasRegParm()) { 8789 State.FreeRegs = FI.getRegParm(); 8790 } else { 8791 State.FreeRegs = 4; 8792 } 8793 8794 if (!getCXXABI().classifyReturnType(FI)) 8795 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8796 for (auto &I : FI.arguments()) 8797 I.info = classifyArgumentType(I.type, State); 8798 } 8799 8800 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 8801 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 8802 }; 8803 } // end anonymous namespace 8804 8805 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 8806 unsigned Size = getContext().getTypeSize(Ty); 8807 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 8808 8809 if (SizeInRegs == 0) 8810 return false; 8811 8812 if (SizeInRegs > State.FreeRegs) { 8813 State.FreeRegs = 0; 8814 return false; 8815 } 8816 8817 State.FreeRegs -= SizeInRegs; 8818 8819 return true; 8820 } 8821 8822 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 8823 CCState &State) const { 8824 if (!ByVal) { 8825 if (State.FreeRegs) { 8826 --State.FreeRegs; // Non-byval indirects just use one pointer. 8827 return getNaturalAlignIndirectInReg(Ty); 8828 } 8829 return getNaturalAlignIndirect(Ty, false); 8830 } 8831 8832 // Compute the byval alignment. 8833 const unsigned MinABIStackAlignInBytes = 4; 8834 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8835 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8836 /*Realign=*/TypeAlign > 8837 MinABIStackAlignInBytes); 8838 } 8839 8840 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 8841 CCState &State) const { 8842 // Check with the C++ ABI first. 8843 const RecordType *RT = Ty->getAs<RecordType>(); 8844 if (RT) { 8845 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8846 if (RAA == CGCXXABI::RAA_Indirect) { 8847 return getIndirectResult(Ty, /*ByVal=*/false, State); 8848 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 8849 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8850 } 8851 } 8852 8853 if (isAggregateTypeForABI(Ty)) { 8854 // Structures with flexible arrays are always indirect. 8855 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8856 return getIndirectResult(Ty, /*ByVal=*/true, State); 8857 8858 // Ignore empty structs/unions. 8859 if (isEmptyRecord(getContext(), Ty, true)) 8860 return ABIArgInfo::getIgnore(); 8861 8862 llvm::LLVMContext &LLVMContext = getVMContext(); 8863 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 8864 if (SizeInRegs <= State.FreeRegs) { 8865 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 8866 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 8867 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 8868 State.FreeRegs -= SizeInRegs; 8869 return ABIArgInfo::getDirectInReg(Result); 8870 } else { 8871 State.FreeRegs = 0; 8872 } 8873 return getIndirectResult(Ty, true, State); 8874 } 8875 8876 // Treat an enum type as its underlying type. 8877 if (const auto *EnumTy = Ty->getAs<EnumType>()) 8878 Ty = EnumTy->getDecl()->getIntegerType(); 8879 8880 bool InReg = shouldUseInReg(Ty, State); 8881 8882 // Don't pass >64 bit integers in registers. 8883 if (const auto *EIT = Ty->getAs<ExtIntType>()) 8884 if (EIT->getNumBits() > 64) 8885 return getIndirectResult(Ty, /*ByVal=*/true, State); 8886 8887 if (isPromotableIntegerTypeForABI(Ty)) { 8888 if (InReg) 8889 return ABIArgInfo::getDirectInReg(); 8890 return ABIArgInfo::getExtend(Ty); 8891 } 8892 if (InReg) 8893 return ABIArgInfo::getDirectInReg(); 8894 return ABIArgInfo::getDirect(); 8895 } 8896 8897 namespace { 8898 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 8899 public: 8900 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 8901 : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {} 8902 }; 8903 } 8904 8905 //===----------------------------------------------------------------------===// 8906 // AMDGPU ABI Implementation 8907 //===----------------------------------------------------------------------===// 8908 8909 namespace { 8910 8911 class AMDGPUABIInfo final : public DefaultABIInfo { 8912 private: 8913 static const unsigned MaxNumRegsForArgsRet = 16; 8914 8915 unsigned numRegsForType(QualType Ty) const; 8916 8917 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 8918 bool isHomogeneousAggregateSmallEnough(const Type *Base, 8919 uint64_t Members) const override; 8920 8921 // Coerce HIP scalar pointer arguments from generic pointers to global ones. 8922 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS, 8923 unsigned ToAS) const { 8924 // Single value types. 8925 if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS) 8926 return llvm::PointerType::get( 8927 cast<llvm::PointerType>(Ty)->getElementType(), ToAS); 8928 return Ty; 8929 } 8930 8931 public: 8932 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 8933 DefaultABIInfo(CGT) {} 8934 8935 ABIArgInfo classifyReturnType(QualType RetTy) const; 8936 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 8937 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 8938 8939 void computeInfo(CGFunctionInfo &FI) const override; 8940 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8941 QualType Ty) const override; 8942 }; 8943 8944 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 8945 return true; 8946 } 8947 8948 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 8949 const Type *Base, uint64_t Members) const { 8950 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 8951 8952 // Homogeneous Aggregates may occupy at most 16 registers. 8953 return Members * NumRegs <= MaxNumRegsForArgsRet; 8954 } 8955 8956 /// Estimate number of registers the type will use when passed in registers. 8957 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 8958 unsigned NumRegs = 0; 8959 8960 if (const VectorType *VT = Ty->getAs<VectorType>()) { 8961 // Compute from the number of elements. The reported size is based on the 8962 // in-memory size, which includes the padding 4th element for 3-vectors. 8963 QualType EltTy = VT->getElementType(); 8964 unsigned EltSize = getContext().getTypeSize(EltTy); 8965 8966 // 16-bit element vectors should be passed as packed. 8967 if (EltSize == 16) 8968 return (VT->getNumElements() + 1) / 2; 8969 8970 unsigned EltNumRegs = (EltSize + 31) / 32; 8971 return EltNumRegs * VT->getNumElements(); 8972 } 8973 8974 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8975 const RecordDecl *RD = RT->getDecl(); 8976 assert(!RD->hasFlexibleArrayMember()); 8977 8978 for (const FieldDecl *Field : RD->fields()) { 8979 QualType FieldTy = Field->getType(); 8980 NumRegs += numRegsForType(FieldTy); 8981 } 8982 8983 return NumRegs; 8984 } 8985 8986 return (getContext().getTypeSize(Ty) + 31) / 32; 8987 } 8988 8989 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 8990 llvm::CallingConv::ID CC = FI.getCallingConvention(); 8991 8992 if (!getCXXABI().classifyReturnType(FI)) 8993 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8994 8995 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 8996 for (auto &Arg : FI.arguments()) { 8997 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 8998 Arg.info = classifyKernelArgumentType(Arg.type); 8999 } else { 9000 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 9001 } 9002 } 9003 } 9004 9005 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9006 QualType Ty) const { 9007 llvm_unreachable("AMDGPU does not support varargs"); 9008 } 9009 9010 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 9011 if (isAggregateTypeForABI(RetTy)) { 9012 // Records with non-trivial destructors/copy-constructors should not be 9013 // returned by value. 9014 if (!getRecordArgABI(RetTy, getCXXABI())) { 9015 // Ignore empty structs/unions. 9016 if (isEmptyRecord(getContext(), RetTy, true)) 9017 return ABIArgInfo::getIgnore(); 9018 9019 // Lower single-element structs to just return a regular value. 9020 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 9021 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 9022 9023 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 9024 const RecordDecl *RD = RT->getDecl(); 9025 if (RD->hasFlexibleArrayMember()) 9026 return DefaultABIInfo::classifyReturnType(RetTy); 9027 } 9028 9029 // Pack aggregates <= 4 bytes into single VGPR or pair. 9030 uint64_t Size = getContext().getTypeSize(RetTy); 9031 if (Size <= 16) 9032 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 9033 9034 if (Size <= 32) 9035 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 9036 9037 if (Size <= 64) { 9038 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 9039 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 9040 } 9041 9042 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 9043 return ABIArgInfo::getDirect(); 9044 } 9045 } 9046 9047 // Otherwise just do the default thing. 9048 return DefaultABIInfo::classifyReturnType(RetTy); 9049 } 9050 9051 /// For kernels all parameters are really passed in a special buffer. It doesn't 9052 /// make sense to pass anything byval, so everything must be direct. 9053 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 9054 Ty = useFirstFieldIfTransparentUnion(Ty); 9055 9056 // TODO: Can we omit empty structs? 9057 9058 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 9059 Ty = QualType(SeltTy, 0); 9060 9061 llvm::Type *OrigLTy = CGT.ConvertType(Ty); 9062 llvm::Type *LTy = OrigLTy; 9063 if (getContext().getLangOpts().HIP) { 9064 LTy = coerceKernelArgumentType( 9065 OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default), 9066 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device)); 9067 } 9068 9069 // FIXME: Should also use this for OpenCL, but it requires addressing the 9070 // problem of kernels being called. 9071 // 9072 // FIXME: This doesn't apply the optimization of coercing pointers in structs 9073 // to global address space when using byref. This would require implementing a 9074 // new kind of coercion of the in-memory type when for indirect arguments. 9075 if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy && 9076 isAggregateTypeForABI(Ty)) { 9077 return ABIArgInfo::getIndirectAliased( 9078 getContext().getTypeAlignInChars(Ty), 9079 getContext().getTargetAddressSpace(LangAS::opencl_constant), 9080 false /*Realign*/, nullptr /*Padding*/); 9081 } 9082 9083 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 9084 // individual elements, which confuses the Clover OpenCL backend; therefore we 9085 // have to set it to false here. Other args of getDirect() are just defaults. 9086 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 9087 } 9088 9089 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 9090 unsigned &NumRegsLeft) const { 9091 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 9092 9093 Ty = useFirstFieldIfTransparentUnion(Ty); 9094 9095 if (isAggregateTypeForABI(Ty)) { 9096 // Records with non-trivial destructors/copy-constructors should not be 9097 // passed by value. 9098 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 9099 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9100 9101 // Ignore empty structs/unions. 9102 if (isEmptyRecord(getContext(), Ty, true)) 9103 return ABIArgInfo::getIgnore(); 9104 9105 // Lower single-element structs to just pass a regular value. TODO: We 9106 // could do reasonable-size multiple-element structs too, using getExpand(), 9107 // though watch out for things like bitfields. 9108 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 9109 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 9110 9111 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9112 const RecordDecl *RD = RT->getDecl(); 9113 if (RD->hasFlexibleArrayMember()) 9114 return DefaultABIInfo::classifyArgumentType(Ty); 9115 } 9116 9117 // Pack aggregates <= 8 bytes into single VGPR or pair. 9118 uint64_t Size = getContext().getTypeSize(Ty); 9119 if (Size <= 64) { 9120 unsigned NumRegs = (Size + 31) / 32; 9121 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 9122 9123 if (Size <= 16) 9124 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 9125 9126 if (Size <= 32) 9127 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 9128 9129 // XXX: Should this be i64 instead, and should the limit increase? 9130 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 9131 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 9132 } 9133 9134 if (NumRegsLeft > 0) { 9135 unsigned NumRegs = numRegsForType(Ty); 9136 if (NumRegsLeft >= NumRegs) { 9137 NumRegsLeft -= NumRegs; 9138 return ABIArgInfo::getDirect(); 9139 } 9140 } 9141 } 9142 9143 // Otherwise just do the default thing. 9144 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 9145 if (!ArgInfo.isIndirect()) { 9146 unsigned NumRegs = numRegsForType(Ty); 9147 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 9148 } 9149 9150 return ArgInfo; 9151 } 9152 9153 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 9154 public: 9155 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 9156 : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {} 9157 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 9158 CodeGen::CodeGenModule &M) const override; 9159 unsigned getOpenCLKernelCallingConv() const override; 9160 9161 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 9162 llvm::PointerType *T, QualType QT) const override; 9163 9164 LangAS getASTAllocaAddressSpace() const override { 9165 return getLangASFromTargetAS( 9166 getABIInfo().getDataLayout().getAllocaAddrSpace()); 9167 } 9168 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 9169 const VarDecl *D) const override; 9170 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 9171 SyncScope Scope, 9172 llvm::AtomicOrdering Ordering, 9173 llvm::LLVMContext &Ctx) const override; 9174 llvm::Function * 9175 createEnqueuedBlockKernel(CodeGenFunction &CGF, 9176 llvm::Function *BlockInvokeFunc, 9177 llvm::Value *BlockLiteral) const override; 9178 bool shouldEmitStaticExternCAliases() const override; 9179 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 9180 }; 9181 } 9182 9183 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 9184 llvm::GlobalValue *GV) { 9185 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 9186 return false; 9187 9188 return D->hasAttr<OpenCLKernelAttr>() || 9189 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 9190 (isa<VarDecl>(D) && 9191 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 9192 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() || 9193 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType())); 9194 } 9195 9196 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 9197 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 9198 if (requiresAMDGPUProtectedVisibility(D, GV)) { 9199 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 9200 GV->setDSOLocal(true); 9201 } 9202 9203 if (GV->isDeclaration()) 9204 return; 9205 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 9206 if (!FD) 9207 return; 9208 9209 llvm::Function *F = cast<llvm::Function>(GV); 9210 9211 const auto *ReqdWGS = M.getLangOpts().OpenCL ? 9212 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 9213 9214 9215 const bool IsOpenCLKernel = M.getLangOpts().OpenCL && 9216 FD->hasAttr<OpenCLKernelAttr>(); 9217 const bool IsHIPKernel = M.getLangOpts().HIP && 9218 FD->hasAttr<CUDAGlobalAttr>(); 9219 if ((IsOpenCLKernel || IsHIPKernel) && 9220 (M.getTriple().getOS() == llvm::Triple::AMDHSA)) 9221 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56"); 9222 9223 if (IsHIPKernel) 9224 F->addFnAttr("uniform-work-group-size", "true"); 9225 9226 9227 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 9228 if (ReqdWGS || FlatWGS) { 9229 unsigned Min = 0; 9230 unsigned Max = 0; 9231 if (FlatWGS) { 9232 Min = FlatWGS->getMin() 9233 ->EvaluateKnownConstInt(M.getContext()) 9234 .getExtValue(); 9235 Max = FlatWGS->getMax() 9236 ->EvaluateKnownConstInt(M.getContext()) 9237 .getExtValue(); 9238 } 9239 if (ReqdWGS && Min == 0 && Max == 0) 9240 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 9241 9242 if (Min != 0) { 9243 assert(Min <= Max && "Min must be less than or equal Max"); 9244 9245 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 9246 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9247 } else 9248 assert(Max == 0 && "Max must be zero"); 9249 } else if (IsOpenCLKernel || IsHIPKernel) { 9250 // By default, restrict the maximum size to a value specified by 9251 // --gpu-max-threads-per-block=n or its default value for HIP. 9252 const unsigned OpenCLDefaultMaxWorkGroupSize = 256; 9253 const unsigned DefaultMaxWorkGroupSize = 9254 IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize 9255 : M.getLangOpts().GPUMaxThreadsPerBlock; 9256 std::string AttrVal = 9257 std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize); 9258 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9259 } 9260 9261 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 9262 unsigned Min = 9263 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 9264 unsigned Max = Attr->getMax() ? Attr->getMax() 9265 ->EvaluateKnownConstInt(M.getContext()) 9266 .getExtValue() 9267 : 0; 9268 9269 if (Min != 0) { 9270 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 9271 9272 std::string AttrVal = llvm::utostr(Min); 9273 if (Max != 0) 9274 AttrVal = AttrVal + "," + llvm::utostr(Max); 9275 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 9276 } else 9277 assert(Max == 0 && "Max must be zero"); 9278 } 9279 9280 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 9281 unsigned NumSGPR = Attr->getNumSGPR(); 9282 9283 if (NumSGPR != 0) 9284 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 9285 } 9286 9287 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 9288 uint32_t NumVGPR = Attr->getNumVGPR(); 9289 9290 if (NumVGPR != 0) 9291 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 9292 } 9293 9294 if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics()) 9295 F->addFnAttr("amdgpu-unsafe-fp-atomics", "true"); 9296 9297 if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts) 9298 F->addFnAttr("amdgpu-ieee", "false"); 9299 } 9300 9301 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9302 return llvm::CallingConv::AMDGPU_KERNEL; 9303 } 9304 9305 // Currently LLVM assumes null pointers always have value 0, 9306 // which results in incorrectly transformed IR. Therefore, instead of 9307 // emitting null pointers in private and local address spaces, a null 9308 // pointer in generic address space is emitted which is casted to a 9309 // pointer in local or private address space. 9310 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 9311 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 9312 QualType QT) const { 9313 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 9314 return llvm::ConstantPointerNull::get(PT); 9315 9316 auto &Ctx = CGM.getContext(); 9317 auto NPT = llvm::PointerType::get(PT->getElementType(), 9318 Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 9319 return llvm::ConstantExpr::getAddrSpaceCast( 9320 llvm::ConstantPointerNull::get(NPT), PT); 9321 } 9322 9323 LangAS 9324 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 9325 const VarDecl *D) const { 9326 assert(!CGM.getLangOpts().OpenCL && 9327 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 9328 "Address space agnostic languages only"); 9329 LangAS DefaultGlobalAS = getLangASFromTargetAS( 9330 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 9331 if (!D) 9332 return DefaultGlobalAS; 9333 9334 LangAS AddrSpace = D->getType().getAddressSpace(); 9335 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 9336 if (AddrSpace != LangAS::Default) 9337 return AddrSpace; 9338 9339 if (CGM.isTypeConstant(D->getType(), false)) { 9340 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 9341 return ConstAS.getValue(); 9342 } 9343 return DefaultGlobalAS; 9344 } 9345 9346 llvm::SyncScope::ID 9347 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 9348 SyncScope Scope, 9349 llvm::AtomicOrdering Ordering, 9350 llvm::LLVMContext &Ctx) const { 9351 std::string Name; 9352 switch (Scope) { 9353 case SyncScope::OpenCLWorkGroup: 9354 Name = "workgroup"; 9355 break; 9356 case SyncScope::OpenCLDevice: 9357 Name = "agent"; 9358 break; 9359 case SyncScope::OpenCLAllSVMDevices: 9360 Name = ""; 9361 break; 9362 case SyncScope::OpenCLSubGroup: 9363 Name = "wavefront"; 9364 } 9365 9366 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 9367 if (!Name.empty()) 9368 Name = Twine(Twine(Name) + Twine("-")).str(); 9369 9370 Name = Twine(Twine(Name) + Twine("one-as")).str(); 9371 } 9372 9373 return Ctx.getOrInsertSyncScopeID(Name); 9374 } 9375 9376 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 9377 return false; 9378 } 9379 9380 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 9381 const FunctionType *&FT) const { 9382 FT = getABIInfo().getContext().adjustFunctionType( 9383 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 9384 } 9385 9386 //===----------------------------------------------------------------------===// 9387 // SPARC v8 ABI Implementation. 9388 // Based on the SPARC Compliance Definition version 2.4.1. 9389 // 9390 // Ensures that complex values are passed in registers. 9391 // 9392 namespace { 9393 class SparcV8ABIInfo : public DefaultABIInfo { 9394 public: 9395 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9396 9397 private: 9398 ABIArgInfo classifyReturnType(QualType RetTy) const; 9399 void computeInfo(CGFunctionInfo &FI) const override; 9400 }; 9401 } // end anonymous namespace 9402 9403 9404 ABIArgInfo 9405 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 9406 if (Ty->isAnyComplexType()) { 9407 return ABIArgInfo::getDirect(); 9408 } 9409 else { 9410 return DefaultABIInfo::classifyReturnType(Ty); 9411 } 9412 } 9413 9414 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9415 9416 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9417 for (auto &Arg : FI.arguments()) 9418 Arg.info = classifyArgumentType(Arg.type); 9419 } 9420 9421 namespace { 9422 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 9423 public: 9424 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 9425 : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {} 9426 }; 9427 } // end anonymous namespace 9428 9429 //===----------------------------------------------------------------------===// 9430 // SPARC v9 ABI Implementation. 9431 // Based on the SPARC Compliance Definition version 2.4.1. 9432 // 9433 // Function arguments a mapped to a nominal "parameter array" and promoted to 9434 // registers depending on their type. Each argument occupies 8 or 16 bytes in 9435 // the array, structs larger than 16 bytes are passed indirectly. 9436 // 9437 // One case requires special care: 9438 // 9439 // struct mixed { 9440 // int i; 9441 // float f; 9442 // }; 9443 // 9444 // When a struct mixed is passed by value, it only occupies 8 bytes in the 9445 // parameter array, but the int is passed in an integer register, and the float 9446 // is passed in a floating point register. This is represented as two arguments 9447 // with the LLVM IR inreg attribute: 9448 // 9449 // declare void f(i32 inreg %i, float inreg %f) 9450 // 9451 // The code generator will only allocate 4 bytes from the parameter array for 9452 // the inreg arguments. All other arguments are allocated a multiple of 8 9453 // bytes. 9454 // 9455 namespace { 9456 class SparcV9ABIInfo : public ABIInfo { 9457 public: 9458 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 9459 9460 private: 9461 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 9462 void computeInfo(CGFunctionInfo &FI) const override; 9463 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9464 QualType Ty) const override; 9465 9466 // Coercion type builder for structs passed in registers. The coercion type 9467 // serves two purposes: 9468 // 9469 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 9470 // in registers. 9471 // 2. Expose aligned floating point elements as first-level elements, so the 9472 // code generator knows to pass them in floating point registers. 9473 // 9474 // We also compute the InReg flag which indicates that the struct contains 9475 // aligned 32-bit floats. 9476 // 9477 struct CoerceBuilder { 9478 llvm::LLVMContext &Context; 9479 const llvm::DataLayout &DL; 9480 SmallVector<llvm::Type*, 8> Elems; 9481 uint64_t Size; 9482 bool InReg; 9483 9484 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 9485 : Context(c), DL(dl), Size(0), InReg(false) {} 9486 9487 // Pad Elems with integers until Size is ToSize. 9488 void pad(uint64_t ToSize) { 9489 assert(ToSize >= Size && "Cannot remove elements"); 9490 if (ToSize == Size) 9491 return; 9492 9493 // Finish the current 64-bit word. 9494 uint64_t Aligned = llvm::alignTo(Size, 64); 9495 if (Aligned > Size && Aligned <= ToSize) { 9496 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 9497 Size = Aligned; 9498 } 9499 9500 // Add whole 64-bit words. 9501 while (Size + 64 <= ToSize) { 9502 Elems.push_back(llvm::Type::getInt64Ty(Context)); 9503 Size += 64; 9504 } 9505 9506 // Final in-word padding. 9507 if (Size < ToSize) { 9508 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 9509 Size = ToSize; 9510 } 9511 } 9512 9513 // Add a floating point element at Offset. 9514 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 9515 // Unaligned floats are treated as integers. 9516 if (Offset % Bits) 9517 return; 9518 // The InReg flag is only required if there are any floats < 64 bits. 9519 if (Bits < 64) 9520 InReg = true; 9521 pad(Offset); 9522 Elems.push_back(Ty); 9523 Size = Offset + Bits; 9524 } 9525 9526 // Add a struct type to the coercion type, starting at Offset (in bits). 9527 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 9528 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 9529 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 9530 llvm::Type *ElemTy = StrTy->getElementType(i); 9531 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 9532 switch (ElemTy->getTypeID()) { 9533 case llvm::Type::StructTyID: 9534 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 9535 break; 9536 case llvm::Type::FloatTyID: 9537 addFloat(ElemOffset, ElemTy, 32); 9538 break; 9539 case llvm::Type::DoubleTyID: 9540 addFloat(ElemOffset, ElemTy, 64); 9541 break; 9542 case llvm::Type::FP128TyID: 9543 addFloat(ElemOffset, ElemTy, 128); 9544 break; 9545 case llvm::Type::PointerTyID: 9546 if (ElemOffset % 64 == 0) { 9547 pad(ElemOffset); 9548 Elems.push_back(ElemTy); 9549 Size += 64; 9550 } 9551 break; 9552 default: 9553 break; 9554 } 9555 } 9556 } 9557 9558 // Check if Ty is a usable substitute for the coercion type. 9559 bool isUsableType(llvm::StructType *Ty) const { 9560 return llvm::makeArrayRef(Elems) == Ty->elements(); 9561 } 9562 9563 // Get the coercion type as a literal struct type. 9564 llvm::Type *getType() const { 9565 if (Elems.size() == 1) 9566 return Elems.front(); 9567 else 9568 return llvm::StructType::get(Context, Elems); 9569 } 9570 }; 9571 }; 9572 } // end anonymous namespace 9573 9574 ABIArgInfo 9575 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 9576 if (Ty->isVoidType()) 9577 return ABIArgInfo::getIgnore(); 9578 9579 uint64_t Size = getContext().getTypeSize(Ty); 9580 9581 // Anything too big to fit in registers is passed with an explicit indirect 9582 // pointer / sret pointer. 9583 if (Size > SizeLimit) 9584 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 9585 9586 // Treat an enum type as its underlying type. 9587 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9588 Ty = EnumTy->getDecl()->getIntegerType(); 9589 9590 // Integer types smaller than a register are extended. 9591 if (Size < 64 && Ty->isIntegerType()) 9592 return ABIArgInfo::getExtend(Ty); 9593 9594 if (const auto *EIT = Ty->getAs<ExtIntType>()) 9595 if (EIT->getNumBits() < 64) 9596 return ABIArgInfo::getExtend(Ty); 9597 9598 // Other non-aggregates go in registers. 9599 if (!isAggregateTypeForABI(Ty)) 9600 return ABIArgInfo::getDirect(); 9601 9602 // If a C++ object has either a non-trivial copy constructor or a non-trivial 9603 // destructor, it is passed with an explicit indirect pointer / sret pointer. 9604 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 9605 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9606 9607 // This is a small aggregate type that should be passed in registers. 9608 // Build a coercion type from the LLVM struct type. 9609 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 9610 if (!StrTy) 9611 return ABIArgInfo::getDirect(); 9612 9613 CoerceBuilder CB(getVMContext(), getDataLayout()); 9614 CB.addStruct(0, StrTy); 9615 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 9616 9617 // Try to use the original type for coercion. 9618 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 9619 9620 if (CB.InReg) 9621 return ABIArgInfo::getDirectInReg(CoerceTy); 9622 else 9623 return ABIArgInfo::getDirect(CoerceTy); 9624 } 9625 9626 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9627 QualType Ty) const { 9628 ABIArgInfo AI = classifyType(Ty, 16 * 8); 9629 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9630 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9631 AI.setCoerceToType(ArgTy); 9632 9633 CharUnits SlotSize = CharUnits::fromQuantity(8); 9634 9635 CGBuilderTy &Builder = CGF.Builder; 9636 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 9637 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9638 9639 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 9640 9641 Address ArgAddr = Address::invalid(); 9642 CharUnits Stride; 9643 switch (AI.getKind()) { 9644 case ABIArgInfo::Expand: 9645 case ABIArgInfo::CoerceAndExpand: 9646 case ABIArgInfo::InAlloca: 9647 llvm_unreachable("Unsupported ABI kind for va_arg"); 9648 9649 case ABIArgInfo::Extend: { 9650 Stride = SlotSize; 9651 CharUnits Offset = SlotSize - TypeInfo.Width; 9652 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 9653 break; 9654 } 9655 9656 case ABIArgInfo::Direct: { 9657 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 9658 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 9659 ArgAddr = Addr; 9660 break; 9661 } 9662 9663 case ABIArgInfo::Indirect: 9664 case ABIArgInfo::IndirectAliased: 9665 Stride = SlotSize; 9666 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 9667 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), 9668 TypeInfo.Align); 9669 break; 9670 9671 case ABIArgInfo::Ignore: 9672 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align); 9673 } 9674 9675 // Update VAList. 9676 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 9677 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 9678 9679 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); 9680 } 9681 9682 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9683 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 9684 for (auto &I : FI.arguments()) 9685 I.info = classifyType(I.type, 16 * 8); 9686 } 9687 9688 namespace { 9689 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 9690 public: 9691 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 9692 : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {} 9693 9694 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 9695 return 14; 9696 } 9697 9698 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9699 llvm::Value *Address) const override; 9700 }; 9701 } // end anonymous namespace 9702 9703 bool 9704 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9705 llvm::Value *Address) const { 9706 // This is calculated from the LLVM and GCC tables and verified 9707 // against gcc output. AFAIK all ABIs use the same encoding. 9708 9709 CodeGen::CGBuilderTy &Builder = CGF.Builder; 9710 9711 llvm::IntegerType *i8 = CGF.Int8Ty; 9712 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 9713 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 9714 9715 // 0-31: the 8-byte general-purpose registers 9716 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 9717 9718 // 32-63: f0-31, the 4-byte floating-point registers 9719 AssignToArrayRange(Builder, Address, Four8, 32, 63); 9720 9721 // Y = 64 9722 // PSR = 65 9723 // WIM = 66 9724 // TBR = 67 9725 // PC = 68 9726 // NPC = 69 9727 // FSR = 70 9728 // CSR = 71 9729 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 9730 9731 // 72-87: d0-15, the 8-byte floating-point registers 9732 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 9733 9734 return false; 9735 } 9736 9737 // ARC ABI implementation. 9738 namespace { 9739 9740 class ARCABIInfo : public DefaultABIInfo { 9741 public: 9742 using DefaultABIInfo::DefaultABIInfo; 9743 9744 private: 9745 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9746 QualType Ty) const override; 9747 9748 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 9749 if (!State.FreeRegs) 9750 return; 9751 if (Info.isIndirect() && Info.getInReg()) 9752 State.FreeRegs--; 9753 else if (Info.isDirect() && Info.getInReg()) { 9754 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 9755 if (sz < State.FreeRegs) 9756 State.FreeRegs -= sz; 9757 else 9758 State.FreeRegs = 0; 9759 } 9760 } 9761 9762 void computeInfo(CGFunctionInfo &FI) const override { 9763 CCState State(FI); 9764 // ARC uses 8 registers to pass arguments. 9765 State.FreeRegs = 8; 9766 9767 if (!getCXXABI().classifyReturnType(FI)) 9768 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9769 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 9770 for (auto &I : FI.arguments()) { 9771 I.info = classifyArgumentType(I.type, State.FreeRegs); 9772 updateState(I.info, I.type, State); 9773 } 9774 } 9775 9776 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 9777 ABIArgInfo getIndirectByValue(QualType Ty) const; 9778 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 9779 ABIArgInfo classifyReturnType(QualType RetTy) const; 9780 }; 9781 9782 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 9783 public: 9784 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 9785 : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {} 9786 }; 9787 9788 9789 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 9790 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 9791 getNaturalAlignIndirect(Ty, false); 9792 } 9793 9794 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 9795 // Compute the byval alignment. 9796 const unsigned MinABIStackAlignInBytes = 4; 9797 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 9798 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 9799 TypeAlign > MinABIStackAlignInBytes); 9800 } 9801 9802 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9803 QualType Ty) const { 9804 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 9805 getContext().getTypeInfoInChars(Ty), 9806 CharUnits::fromQuantity(4), true); 9807 } 9808 9809 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 9810 uint8_t FreeRegs) const { 9811 // Handle the generic C++ ABI. 9812 const RecordType *RT = Ty->getAs<RecordType>(); 9813 if (RT) { 9814 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 9815 if (RAA == CGCXXABI::RAA_Indirect) 9816 return getIndirectByRef(Ty, FreeRegs > 0); 9817 9818 if (RAA == CGCXXABI::RAA_DirectInMemory) 9819 return getIndirectByValue(Ty); 9820 } 9821 9822 // Treat an enum type as its underlying type. 9823 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9824 Ty = EnumTy->getDecl()->getIntegerType(); 9825 9826 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 9827 9828 if (isAggregateTypeForABI(Ty)) { 9829 // Structures with flexible arrays are always indirect. 9830 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 9831 return getIndirectByValue(Ty); 9832 9833 // Ignore empty structs/unions. 9834 if (isEmptyRecord(getContext(), Ty, true)) 9835 return ABIArgInfo::getIgnore(); 9836 9837 llvm::LLVMContext &LLVMContext = getVMContext(); 9838 9839 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 9840 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 9841 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 9842 9843 return FreeRegs >= SizeInRegs ? 9844 ABIArgInfo::getDirectInReg(Result) : 9845 ABIArgInfo::getDirect(Result, 0, nullptr, false); 9846 } 9847 9848 if (const auto *EIT = Ty->getAs<ExtIntType>()) 9849 if (EIT->getNumBits() > 64) 9850 return getIndirectByValue(Ty); 9851 9852 return isPromotableIntegerTypeForABI(Ty) 9853 ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) 9854 : ABIArgInfo::getExtend(Ty)) 9855 : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() 9856 : ABIArgInfo::getDirect()); 9857 } 9858 9859 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 9860 if (RetTy->isAnyComplexType()) 9861 return ABIArgInfo::getDirectInReg(); 9862 9863 // Arguments of size > 4 registers are indirect. 9864 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 9865 if (RetSize > 4) 9866 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 9867 9868 return DefaultABIInfo::classifyReturnType(RetTy); 9869 } 9870 9871 } // End anonymous namespace. 9872 9873 //===----------------------------------------------------------------------===// 9874 // XCore ABI Implementation 9875 //===----------------------------------------------------------------------===// 9876 9877 namespace { 9878 9879 /// A SmallStringEnc instance is used to build up the TypeString by passing 9880 /// it by reference between functions that append to it. 9881 typedef llvm::SmallString<128> SmallStringEnc; 9882 9883 /// TypeStringCache caches the meta encodings of Types. 9884 /// 9885 /// The reason for caching TypeStrings is two fold: 9886 /// 1. To cache a type's encoding for later uses; 9887 /// 2. As a means to break recursive member type inclusion. 9888 /// 9889 /// A cache Entry can have a Status of: 9890 /// NonRecursive: The type encoding is not recursive; 9891 /// Recursive: The type encoding is recursive; 9892 /// Incomplete: An incomplete TypeString; 9893 /// IncompleteUsed: An incomplete TypeString that has been used in a 9894 /// Recursive type encoding. 9895 /// 9896 /// A NonRecursive entry will have all of its sub-members expanded as fully 9897 /// as possible. Whilst it may contain types which are recursive, the type 9898 /// itself is not recursive and thus its encoding may be safely used whenever 9899 /// the type is encountered. 9900 /// 9901 /// A Recursive entry will have all of its sub-members expanded as fully as 9902 /// possible. The type itself is recursive and it may contain other types which 9903 /// are recursive. The Recursive encoding must not be used during the expansion 9904 /// of a recursive type's recursive branch. For simplicity the code uses 9905 /// IncompleteCount to reject all usage of Recursive encodings for member types. 9906 /// 9907 /// An Incomplete entry is always a RecordType and only encodes its 9908 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 9909 /// are placed into the cache during type expansion as a means to identify and 9910 /// handle recursive inclusion of types as sub-members. If there is recursion 9911 /// the entry becomes IncompleteUsed. 9912 /// 9913 /// During the expansion of a RecordType's members: 9914 /// 9915 /// If the cache contains a NonRecursive encoding for the member type, the 9916 /// cached encoding is used; 9917 /// 9918 /// If the cache contains a Recursive encoding for the member type, the 9919 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 9920 /// 9921 /// If the member is a RecordType, an Incomplete encoding is placed into the 9922 /// cache to break potential recursive inclusion of itself as a sub-member; 9923 /// 9924 /// Once a member RecordType has been expanded, its temporary incomplete 9925 /// entry is removed from the cache. If a Recursive encoding was swapped out 9926 /// it is swapped back in; 9927 /// 9928 /// If an incomplete entry is used to expand a sub-member, the incomplete 9929 /// entry is marked as IncompleteUsed. The cache keeps count of how many 9930 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 9931 /// 9932 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 9933 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 9934 /// Else the member is part of a recursive type and thus the recursion has 9935 /// been exited too soon for the encoding to be correct for the member. 9936 /// 9937 class TypeStringCache { 9938 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 9939 struct Entry { 9940 std::string Str; // The encoded TypeString for the type. 9941 enum Status State; // Information about the encoding in 'Str'. 9942 std::string Swapped; // A temporary place holder for a Recursive encoding 9943 // during the expansion of RecordType's members. 9944 }; 9945 std::map<const IdentifierInfo *, struct Entry> Map; 9946 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 9947 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 9948 public: 9949 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 9950 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 9951 bool removeIncomplete(const IdentifierInfo *ID); 9952 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 9953 bool IsRecursive); 9954 StringRef lookupStr(const IdentifierInfo *ID); 9955 }; 9956 9957 /// TypeString encodings for enum & union fields must be order. 9958 /// FieldEncoding is a helper for this ordering process. 9959 class FieldEncoding { 9960 bool HasName; 9961 std::string Enc; 9962 public: 9963 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 9964 StringRef str() { return Enc; } 9965 bool operator<(const FieldEncoding &rhs) const { 9966 if (HasName != rhs.HasName) return HasName; 9967 return Enc < rhs.Enc; 9968 } 9969 }; 9970 9971 class XCoreABIInfo : public DefaultABIInfo { 9972 public: 9973 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9974 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9975 QualType Ty) const override; 9976 }; 9977 9978 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 9979 mutable TypeStringCache TSC; 9980 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9981 const CodeGen::CodeGenModule &M) const; 9982 9983 public: 9984 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 9985 : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {} 9986 void emitTargetMetadata(CodeGen::CodeGenModule &CGM, 9987 const llvm::MapVector<GlobalDecl, StringRef> 9988 &MangledDeclNames) const override; 9989 }; 9990 9991 } // End anonymous namespace. 9992 9993 // TODO: this implementation is likely now redundant with the default 9994 // EmitVAArg. 9995 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9996 QualType Ty) const { 9997 CGBuilderTy &Builder = CGF.Builder; 9998 9999 // Get the VAList. 10000 CharUnits SlotSize = CharUnits::fromQuantity(4); 10001 Address AP(Builder.CreateLoad(VAListAddr), SlotSize); 10002 10003 // Handle the argument. 10004 ABIArgInfo AI = classifyArgumentType(Ty); 10005 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 10006 llvm::Type *ArgTy = CGT.ConvertType(Ty); 10007 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 10008 AI.setCoerceToType(ArgTy); 10009 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 10010 10011 Address Val = Address::invalid(); 10012 CharUnits ArgSize = CharUnits::Zero(); 10013 switch (AI.getKind()) { 10014 case ABIArgInfo::Expand: 10015 case ABIArgInfo::CoerceAndExpand: 10016 case ABIArgInfo::InAlloca: 10017 llvm_unreachable("Unsupported ABI kind for va_arg"); 10018 case ABIArgInfo::Ignore: 10019 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); 10020 ArgSize = CharUnits::Zero(); 10021 break; 10022 case ABIArgInfo::Extend: 10023 case ABIArgInfo::Direct: 10024 Val = Builder.CreateBitCast(AP, ArgPtrTy); 10025 ArgSize = CharUnits::fromQuantity( 10026 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 10027 ArgSize = ArgSize.alignTo(SlotSize); 10028 break; 10029 case ABIArgInfo::Indirect: 10030 case ABIArgInfo::IndirectAliased: 10031 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 10032 Val = Address(Builder.CreateLoad(Val), TypeAlign); 10033 ArgSize = SlotSize; 10034 break; 10035 } 10036 10037 // Increment the VAList. 10038 if (!ArgSize.isZero()) { 10039 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 10040 Builder.CreateStore(APN.getPointer(), VAListAddr); 10041 } 10042 10043 return Val; 10044 } 10045 10046 /// During the expansion of a RecordType, an incomplete TypeString is placed 10047 /// into the cache as a means to identify and break recursion. 10048 /// If there is a Recursive encoding in the cache, it is swapped out and will 10049 /// be reinserted by removeIncomplete(). 10050 /// All other types of encoding should have been used rather than arriving here. 10051 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 10052 std::string StubEnc) { 10053 if (!ID) 10054 return; 10055 Entry &E = Map[ID]; 10056 assert( (E.Str.empty() || E.State == Recursive) && 10057 "Incorrectly use of addIncomplete"); 10058 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 10059 E.Swapped.swap(E.Str); // swap out the Recursive 10060 E.Str.swap(StubEnc); 10061 E.State = Incomplete; 10062 ++IncompleteCount; 10063 } 10064 10065 /// Once the RecordType has been expanded, the temporary incomplete TypeString 10066 /// must be removed from the cache. 10067 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 10068 /// Returns true if the RecordType was defined recursively. 10069 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 10070 if (!ID) 10071 return false; 10072 auto I = Map.find(ID); 10073 assert(I != Map.end() && "Entry not present"); 10074 Entry &E = I->second; 10075 assert( (E.State == Incomplete || 10076 E.State == IncompleteUsed) && 10077 "Entry must be an incomplete type"); 10078 bool IsRecursive = false; 10079 if (E.State == IncompleteUsed) { 10080 // We made use of our Incomplete encoding, thus we are recursive. 10081 IsRecursive = true; 10082 --IncompleteUsedCount; 10083 } 10084 if (E.Swapped.empty()) 10085 Map.erase(I); 10086 else { 10087 // Swap the Recursive back. 10088 E.Swapped.swap(E.Str); 10089 E.Swapped.clear(); 10090 E.State = Recursive; 10091 } 10092 --IncompleteCount; 10093 return IsRecursive; 10094 } 10095 10096 /// Add the encoded TypeString to the cache only if it is NonRecursive or 10097 /// Recursive (viz: all sub-members were expanded as fully as possible). 10098 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 10099 bool IsRecursive) { 10100 if (!ID || IncompleteUsedCount) 10101 return; // No key or it is is an incomplete sub-type so don't add. 10102 Entry &E = Map[ID]; 10103 if (IsRecursive && !E.Str.empty()) { 10104 assert(E.State==Recursive && E.Str.size() == Str.size() && 10105 "This is not the same Recursive entry"); 10106 // The parent container was not recursive after all, so we could have used 10107 // this Recursive sub-member entry after all, but we assumed the worse when 10108 // we started viz: IncompleteCount!=0. 10109 return; 10110 } 10111 assert(E.Str.empty() && "Entry already present"); 10112 E.Str = Str.str(); 10113 E.State = IsRecursive? Recursive : NonRecursive; 10114 } 10115 10116 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 10117 /// are recursively expanding a type (IncompleteCount != 0) and the cached 10118 /// encoding is Recursive, return an empty StringRef. 10119 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 10120 if (!ID) 10121 return StringRef(); // We have no key. 10122 auto I = Map.find(ID); 10123 if (I == Map.end()) 10124 return StringRef(); // We have no encoding. 10125 Entry &E = I->second; 10126 if (E.State == Recursive && IncompleteCount) 10127 return StringRef(); // We don't use Recursive encodings for member types. 10128 10129 if (E.State == Incomplete) { 10130 // The incomplete type is being used to break out of recursion. 10131 E.State = IncompleteUsed; 10132 ++IncompleteUsedCount; 10133 } 10134 return E.Str; 10135 } 10136 10137 /// The XCore ABI includes a type information section that communicates symbol 10138 /// type information to the linker. The linker uses this information to verify 10139 /// safety/correctness of things such as array bound and pointers et al. 10140 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 10141 /// This type information (TypeString) is emitted into meta data for all global 10142 /// symbols: definitions, declarations, functions & variables. 10143 /// 10144 /// The TypeString carries type, qualifier, name, size & value details. 10145 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 10146 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 10147 /// The output is tested by test/CodeGen/xcore-stringtype.c. 10148 /// 10149 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10150 const CodeGen::CodeGenModule &CGM, 10151 TypeStringCache &TSC); 10152 10153 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 10154 void XCoreTargetCodeGenInfo::emitTargetMD( 10155 const Decl *D, llvm::GlobalValue *GV, 10156 const CodeGen::CodeGenModule &CGM) const { 10157 SmallStringEnc Enc; 10158 if (getTypeString(Enc, D, CGM, TSC)) { 10159 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 10160 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 10161 llvm::MDString::get(Ctx, Enc.str())}; 10162 llvm::NamedMDNode *MD = 10163 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 10164 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 10165 } 10166 } 10167 10168 void XCoreTargetCodeGenInfo::emitTargetMetadata( 10169 CodeGen::CodeGenModule &CGM, 10170 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const { 10171 // Warning, new MangledDeclNames may be appended within this loop. 10172 // We rely on MapVector insertions adding new elements to the end 10173 // of the container. 10174 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 10175 auto Val = *(MangledDeclNames.begin() + I); 10176 llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second); 10177 if (GV) { 10178 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 10179 emitTargetMD(D, GV, CGM); 10180 } 10181 } 10182 } 10183 //===----------------------------------------------------------------------===// 10184 // SPIR ABI Implementation 10185 //===----------------------------------------------------------------------===// 10186 10187 namespace { 10188 class SPIRABIInfo : public DefaultABIInfo { 10189 public: 10190 SPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); } 10191 10192 private: 10193 void setCCs(); 10194 }; 10195 } // end anonymous namespace 10196 namespace { 10197 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo { 10198 public: 10199 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 10200 : TargetCodeGenInfo(std::make_unique<SPIRABIInfo>(CGT)) {} 10201 10202 LangAS getASTAllocaAddressSpace() const override { 10203 return getLangASFromTargetAS( 10204 getABIInfo().getDataLayout().getAllocaAddrSpace()); 10205 } 10206 10207 unsigned getOpenCLKernelCallingConv() const override; 10208 }; 10209 10210 } // End anonymous namespace. 10211 void SPIRABIInfo::setCCs() { 10212 assert(getRuntimeCC() == llvm::CallingConv::C); 10213 RuntimeCC = llvm::CallingConv::SPIR_FUNC; 10214 } 10215 10216 namespace clang { 10217 namespace CodeGen { 10218 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 10219 DefaultABIInfo SPIRABI(CGM.getTypes()); 10220 SPIRABI.computeInfo(FI); 10221 } 10222 } 10223 } 10224 10225 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 10226 return llvm::CallingConv::SPIR_KERNEL; 10227 } 10228 10229 static bool appendType(SmallStringEnc &Enc, QualType QType, 10230 const CodeGen::CodeGenModule &CGM, 10231 TypeStringCache &TSC); 10232 10233 /// Helper function for appendRecordType(). 10234 /// Builds a SmallVector containing the encoded field types in declaration 10235 /// order. 10236 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 10237 const RecordDecl *RD, 10238 const CodeGen::CodeGenModule &CGM, 10239 TypeStringCache &TSC) { 10240 for (const auto *Field : RD->fields()) { 10241 SmallStringEnc Enc; 10242 Enc += "m("; 10243 Enc += Field->getName(); 10244 Enc += "){"; 10245 if (Field->isBitField()) { 10246 Enc += "b("; 10247 llvm::raw_svector_ostream OS(Enc); 10248 OS << Field->getBitWidthValue(CGM.getContext()); 10249 Enc += ':'; 10250 } 10251 if (!appendType(Enc, Field->getType(), CGM, TSC)) 10252 return false; 10253 if (Field->isBitField()) 10254 Enc += ')'; 10255 Enc += '}'; 10256 FE.emplace_back(!Field->getName().empty(), Enc); 10257 } 10258 return true; 10259 } 10260 10261 /// Appends structure and union types to Enc and adds encoding to cache. 10262 /// Recursively calls appendType (via extractFieldType) for each field. 10263 /// Union types have their fields ordered according to the ABI. 10264 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 10265 const CodeGen::CodeGenModule &CGM, 10266 TypeStringCache &TSC, const IdentifierInfo *ID) { 10267 // Append the cached TypeString if we have one. 10268 StringRef TypeString = TSC.lookupStr(ID); 10269 if (!TypeString.empty()) { 10270 Enc += TypeString; 10271 return true; 10272 } 10273 10274 // Start to emit an incomplete TypeString. 10275 size_t Start = Enc.size(); 10276 Enc += (RT->isUnionType()? 'u' : 's'); 10277 Enc += '('; 10278 if (ID) 10279 Enc += ID->getName(); 10280 Enc += "){"; 10281 10282 // We collect all encoded fields and order as necessary. 10283 bool IsRecursive = false; 10284 const RecordDecl *RD = RT->getDecl()->getDefinition(); 10285 if (RD && !RD->field_empty()) { 10286 // An incomplete TypeString stub is placed in the cache for this RecordType 10287 // so that recursive calls to this RecordType will use it whilst building a 10288 // complete TypeString for this RecordType. 10289 SmallVector<FieldEncoding, 16> FE; 10290 std::string StubEnc(Enc.substr(Start).str()); 10291 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 10292 TSC.addIncomplete(ID, std::move(StubEnc)); 10293 if (!extractFieldType(FE, RD, CGM, TSC)) { 10294 (void) TSC.removeIncomplete(ID); 10295 return false; 10296 } 10297 IsRecursive = TSC.removeIncomplete(ID); 10298 // The ABI requires unions to be sorted but not structures. 10299 // See FieldEncoding::operator< for sort algorithm. 10300 if (RT->isUnionType()) 10301 llvm::sort(FE); 10302 // We can now complete the TypeString. 10303 unsigned E = FE.size(); 10304 for (unsigned I = 0; I != E; ++I) { 10305 if (I) 10306 Enc += ','; 10307 Enc += FE[I].str(); 10308 } 10309 } 10310 Enc += '}'; 10311 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 10312 return true; 10313 } 10314 10315 /// Appends enum types to Enc and adds the encoding to the cache. 10316 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 10317 TypeStringCache &TSC, 10318 const IdentifierInfo *ID) { 10319 // Append the cached TypeString if we have one. 10320 StringRef TypeString = TSC.lookupStr(ID); 10321 if (!TypeString.empty()) { 10322 Enc += TypeString; 10323 return true; 10324 } 10325 10326 size_t Start = Enc.size(); 10327 Enc += "e("; 10328 if (ID) 10329 Enc += ID->getName(); 10330 Enc += "){"; 10331 10332 // We collect all encoded enumerations and order them alphanumerically. 10333 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 10334 SmallVector<FieldEncoding, 16> FE; 10335 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 10336 ++I) { 10337 SmallStringEnc EnumEnc; 10338 EnumEnc += "m("; 10339 EnumEnc += I->getName(); 10340 EnumEnc += "){"; 10341 I->getInitVal().toString(EnumEnc); 10342 EnumEnc += '}'; 10343 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 10344 } 10345 llvm::sort(FE); 10346 unsigned E = FE.size(); 10347 for (unsigned I = 0; I != E; ++I) { 10348 if (I) 10349 Enc += ','; 10350 Enc += FE[I].str(); 10351 } 10352 } 10353 Enc += '}'; 10354 TSC.addIfComplete(ID, Enc.substr(Start), false); 10355 return true; 10356 } 10357 10358 /// Appends type's qualifier to Enc. 10359 /// This is done prior to appending the type's encoding. 10360 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 10361 // Qualifiers are emitted in alphabetical order. 10362 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 10363 int Lookup = 0; 10364 if (QT.isConstQualified()) 10365 Lookup += 1<<0; 10366 if (QT.isRestrictQualified()) 10367 Lookup += 1<<1; 10368 if (QT.isVolatileQualified()) 10369 Lookup += 1<<2; 10370 Enc += Table[Lookup]; 10371 } 10372 10373 /// Appends built-in types to Enc. 10374 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 10375 const char *EncType; 10376 switch (BT->getKind()) { 10377 case BuiltinType::Void: 10378 EncType = "0"; 10379 break; 10380 case BuiltinType::Bool: 10381 EncType = "b"; 10382 break; 10383 case BuiltinType::Char_U: 10384 EncType = "uc"; 10385 break; 10386 case BuiltinType::UChar: 10387 EncType = "uc"; 10388 break; 10389 case BuiltinType::SChar: 10390 EncType = "sc"; 10391 break; 10392 case BuiltinType::UShort: 10393 EncType = "us"; 10394 break; 10395 case BuiltinType::Short: 10396 EncType = "ss"; 10397 break; 10398 case BuiltinType::UInt: 10399 EncType = "ui"; 10400 break; 10401 case BuiltinType::Int: 10402 EncType = "si"; 10403 break; 10404 case BuiltinType::ULong: 10405 EncType = "ul"; 10406 break; 10407 case BuiltinType::Long: 10408 EncType = "sl"; 10409 break; 10410 case BuiltinType::ULongLong: 10411 EncType = "ull"; 10412 break; 10413 case BuiltinType::LongLong: 10414 EncType = "sll"; 10415 break; 10416 case BuiltinType::Float: 10417 EncType = "ft"; 10418 break; 10419 case BuiltinType::Double: 10420 EncType = "d"; 10421 break; 10422 case BuiltinType::LongDouble: 10423 EncType = "ld"; 10424 break; 10425 default: 10426 return false; 10427 } 10428 Enc += EncType; 10429 return true; 10430 } 10431 10432 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 10433 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 10434 const CodeGen::CodeGenModule &CGM, 10435 TypeStringCache &TSC) { 10436 Enc += "p("; 10437 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 10438 return false; 10439 Enc += ')'; 10440 return true; 10441 } 10442 10443 /// Appends array encoding to Enc before calling appendType for the element. 10444 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 10445 const ArrayType *AT, 10446 const CodeGen::CodeGenModule &CGM, 10447 TypeStringCache &TSC, StringRef NoSizeEnc) { 10448 if (AT->getSizeModifier() != ArrayType::Normal) 10449 return false; 10450 Enc += "a("; 10451 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 10452 CAT->getSize().toStringUnsigned(Enc); 10453 else 10454 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 10455 Enc += ':'; 10456 // The Qualifiers should be attached to the type rather than the array. 10457 appendQualifier(Enc, QT); 10458 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 10459 return false; 10460 Enc += ')'; 10461 return true; 10462 } 10463 10464 /// Appends a function encoding to Enc, calling appendType for the return type 10465 /// and the arguments. 10466 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 10467 const CodeGen::CodeGenModule &CGM, 10468 TypeStringCache &TSC) { 10469 Enc += "f{"; 10470 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 10471 return false; 10472 Enc += "}("; 10473 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 10474 // N.B. we are only interested in the adjusted param types. 10475 auto I = FPT->param_type_begin(); 10476 auto E = FPT->param_type_end(); 10477 if (I != E) { 10478 do { 10479 if (!appendType(Enc, *I, CGM, TSC)) 10480 return false; 10481 ++I; 10482 if (I != E) 10483 Enc += ','; 10484 } while (I != E); 10485 if (FPT->isVariadic()) 10486 Enc += ",va"; 10487 } else { 10488 if (FPT->isVariadic()) 10489 Enc += "va"; 10490 else 10491 Enc += '0'; 10492 } 10493 } 10494 Enc += ')'; 10495 return true; 10496 } 10497 10498 /// Handles the type's qualifier before dispatching a call to handle specific 10499 /// type encodings. 10500 static bool appendType(SmallStringEnc &Enc, QualType QType, 10501 const CodeGen::CodeGenModule &CGM, 10502 TypeStringCache &TSC) { 10503 10504 QualType QT = QType.getCanonicalType(); 10505 10506 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 10507 // The Qualifiers should be attached to the type rather than the array. 10508 // Thus we don't call appendQualifier() here. 10509 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 10510 10511 appendQualifier(Enc, QT); 10512 10513 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 10514 return appendBuiltinType(Enc, BT); 10515 10516 if (const PointerType *PT = QT->getAs<PointerType>()) 10517 return appendPointerType(Enc, PT, CGM, TSC); 10518 10519 if (const EnumType *ET = QT->getAs<EnumType>()) 10520 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 10521 10522 if (const RecordType *RT = QT->getAsStructureType()) 10523 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10524 10525 if (const RecordType *RT = QT->getAsUnionType()) 10526 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10527 10528 if (const FunctionType *FT = QT->getAs<FunctionType>()) 10529 return appendFunctionType(Enc, FT, CGM, TSC); 10530 10531 return false; 10532 } 10533 10534 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10535 const CodeGen::CodeGenModule &CGM, 10536 TypeStringCache &TSC) { 10537 if (!D) 10538 return false; 10539 10540 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10541 if (FD->getLanguageLinkage() != CLanguageLinkage) 10542 return false; 10543 return appendType(Enc, FD->getType(), CGM, TSC); 10544 } 10545 10546 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 10547 if (VD->getLanguageLinkage() != CLanguageLinkage) 10548 return false; 10549 QualType QT = VD->getType().getCanonicalType(); 10550 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 10551 // Global ArrayTypes are given a size of '*' if the size is unknown. 10552 // The Qualifiers should be attached to the type rather than the array. 10553 // Thus we don't call appendQualifier() here. 10554 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 10555 } 10556 return appendType(Enc, QT, CGM, TSC); 10557 } 10558 return false; 10559 } 10560 10561 //===----------------------------------------------------------------------===// 10562 // RISCV ABI Implementation 10563 //===----------------------------------------------------------------------===// 10564 10565 namespace { 10566 class RISCVABIInfo : public DefaultABIInfo { 10567 private: 10568 // Size of the integer ('x') registers in bits. 10569 unsigned XLen; 10570 // Size of the floating point ('f') registers in bits. Note that the target 10571 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target 10572 // with soft float ABI has FLen==0). 10573 unsigned FLen; 10574 static const int NumArgGPRs = 8; 10575 static const int NumArgFPRs = 8; 10576 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10577 llvm::Type *&Field1Ty, 10578 CharUnits &Field1Off, 10579 llvm::Type *&Field2Ty, 10580 CharUnits &Field2Off) const; 10581 10582 public: 10583 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen) 10584 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {} 10585 10586 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 10587 // non-virtual, but computeInfo is virtual, so we overload it. 10588 void computeInfo(CGFunctionInfo &FI) const override; 10589 10590 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft, 10591 int &ArgFPRsLeft) const; 10592 ABIArgInfo classifyReturnType(QualType RetTy) const; 10593 10594 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10595 QualType Ty) const override; 10596 10597 ABIArgInfo extendType(QualType Ty) const; 10598 10599 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10600 CharUnits &Field1Off, llvm::Type *&Field2Ty, 10601 CharUnits &Field2Off, int &NeededArgGPRs, 10602 int &NeededArgFPRs) const; 10603 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty, 10604 CharUnits Field1Off, 10605 llvm::Type *Field2Ty, 10606 CharUnits Field2Off) const; 10607 }; 10608 } // end anonymous namespace 10609 10610 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 10611 QualType RetTy = FI.getReturnType(); 10612 if (!getCXXABI().classifyReturnType(FI)) 10613 FI.getReturnInfo() = classifyReturnType(RetTy); 10614 10615 // IsRetIndirect is true if classifyArgumentType indicated the value should 10616 // be passed indirect, or if the type size is a scalar greater than 2*XLen 10617 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct 10618 // in LLVM IR, relying on the backend lowering code to rewrite the argument 10619 // list and pass indirectly on RV32. 10620 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 10621 if (!IsRetIndirect && RetTy->isScalarType() && 10622 getContext().getTypeSize(RetTy) > (2 * XLen)) { 10623 if (RetTy->isComplexType() && FLen) { 10624 QualType EltTy = RetTy->castAs<ComplexType>()->getElementType(); 10625 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen; 10626 } else { 10627 // This is a normal scalar > 2*XLen, such as fp128 on RV32. 10628 IsRetIndirect = true; 10629 } 10630 } 10631 10632 // We must track the number of GPRs used in order to conform to the RISC-V 10633 // ABI, as integer scalars passed in registers should have signext/zeroext 10634 // when promoted, but are anyext if passed on the stack. As GPR usage is 10635 // different for variadic arguments, we must also track whether we are 10636 // examining a vararg or not. 10637 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 10638 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 10639 int NumFixedArgs = FI.getNumRequiredArgs(); 10640 10641 int ArgNum = 0; 10642 for (auto &ArgInfo : FI.arguments()) { 10643 bool IsFixed = ArgNum < NumFixedArgs; 10644 ArgInfo.info = 10645 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft); 10646 ArgNum++; 10647 } 10648 } 10649 10650 // Returns true if the struct is a potential candidate for the floating point 10651 // calling convention. If this function returns true, the caller is 10652 // responsible for checking that if there is only a single field then that 10653 // field is a float. 10654 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10655 llvm::Type *&Field1Ty, 10656 CharUnits &Field1Off, 10657 llvm::Type *&Field2Ty, 10658 CharUnits &Field2Off) const { 10659 bool IsInt = Ty->isIntegralOrEnumerationType(); 10660 bool IsFloat = Ty->isRealFloatingType(); 10661 10662 if (IsInt || IsFloat) { 10663 uint64_t Size = getContext().getTypeSize(Ty); 10664 if (IsInt && Size > XLen) 10665 return false; 10666 // Can't be eligible if larger than the FP registers. Half precision isn't 10667 // currently supported on RISC-V and the ABI hasn't been confirmed, so 10668 // default to the integer ABI in that case. 10669 if (IsFloat && (Size > FLen || Size < 32)) 10670 return false; 10671 // Can't be eligible if an integer type was already found (int+int pairs 10672 // are not eligible). 10673 if (IsInt && Field1Ty && Field1Ty->isIntegerTy()) 10674 return false; 10675 if (!Field1Ty) { 10676 Field1Ty = CGT.ConvertType(Ty); 10677 Field1Off = CurOff; 10678 return true; 10679 } 10680 if (!Field2Ty) { 10681 Field2Ty = CGT.ConvertType(Ty); 10682 Field2Off = CurOff; 10683 return true; 10684 } 10685 return false; 10686 } 10687 10688 if (auto CTy = Ty->getAs<ComplexType>()) { 10689 if (Field1Ty) 10690 return false; 10691 QualType EltTy = CTy->getElementType(); 10692 if (getContext().getTypeSize(EltTy) > FLen) 10693 return false; 10694 Field1Ty = CGT.ConvertType(EltTy); 10695 Field1Off = CurOff; 10696 Field2Ty = Field1Ty; 10697 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy); 10698 return true; 10699 } 10700 10701 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) { 10702 uint64_t ArraySize = ATy->getSize().getZExtValue(); 10703 QualType EltTy = ATy->getElementType(); 10704 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy); 10705 for (uint64_t i = 0; i < ArraySize; ++i) { 10706 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty, 10707 Field1Off, Field2Ty, Field2Off); 10708 if (!Ret) 10709 return false; 10710 CurOff += EltSize; 10711 } 10712 return true; 10713 } 10714 10715 if (const auto *RTy = Ty->getAs<RecordType>()) { 10716 // Structures with either a non-trivial destructor or a non-trivial 10717 // copy constructor are not eligible for the FP calling convention. 10718 if (getRecordArgABI(Ty, CGT.getCXXABI())) 10719 return false; 10720 if (isEmptyRecord(getContext(), Ty, true)) 10721 return true; 10722 const RecordDecl *RD = RTy->getDecl(); 10723 // Unions aren't eligible unless they're empty (which is caught above). 10724 if (RD->isUnion()) 10725 return false; 10726 int ZeroWidthBitFieldCount = 0; 10727 for (const FieldDecl *FD : RD->fields()) { 10728 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 10729 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex()); 10730 QualType QTy = FD->getType(); 10731 if (FD->isBitField()) { 10732 unsigned BitWidth = FD->getBitWidthValue(getContext()); 10733 // Allow a bitfield with a type greater than XLen as long as the 10734 // bitwidth is XLen or less. 10735 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen) 10736 QTy = getContext().getIntTypeForBitwidth(XLen, false); 10737 if (BitWidth == 0) { 10738 ZeroWidthBitFieldCount++; 10739 continue; 10740 } 10741 } 10742 10743 bool Ret = detectFPCCEligibleStructHelper( 10744 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits), 10745 Field1Ty, Field1Off, Field2Ty, Field2Off); 10746 if (!Ret) 10747 return false; 10748 10749 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp 10750 // or int+fp structs, but are ignored for a struct with an fp field and 10751 // any number of zero-width bitfields. 10752 if (Field2Ty && ZeroWidthBitFieldCount > 0) 10753 return false; 10754 } 10755 return Field1Ty != nullptr; 10756 } 10757 10758 return false; 10759 } 10760 10761 // Determine if a struct is eligible for passing according to the floating 10762 // point calling convention (i.e., when flattened it contains a single fp 10763 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and 10764 // NeededArgGPRs are incremented appropriately. 10765 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10766 CharUnits &Field1Off, 10767 llvm::Type *&Field2Ty, 10768 CharUnits &Field2Off, 10769 int &NeededArgGPRs, 10770 int &NeededArgFPRs) const { 10771 Field1Ty = nullptr; 10772 Field2Ty = nullptr; 10773 NeededArgGPRs = 0; 10774 NeededArgFPRs = 0; 10775 bool IsCandidate = detectFPCCEligibleStructHelper( 10776 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off); 10777 // Not really a candidate if we have a single int but no float. 10778 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy()) 10779 return false; 10780 if (!IsCandidate) 10781 return false; 10782 if (Field1Ty && Field1Ty->isFloatingPointTy()) 10783 NeededArgFPRs++; 10784 else if (Field1Ty) 10785 NeededArgGPRs++; 10786 if (Field2Ty && Field2Ty->isFloatingPointTy()) 10787 NeededArgFPRs++; 10788 else if (Field2Ty) 10789 NeededArgGPRs++; 10790 return true; 10791 } 10792 10793 // Call getCoerceAndExpand for the two-element flattened struct described by 10794 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an 10795 // appropriate coerceToType and unpaddedCoerceToType. 10796 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct( 10797 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty, 10798 CharUnits Field2Off) const { 10799 SmallVector<llvm::Type *, 3> CoerceElts; 10800 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts; 10801 if (!Field1Off.isZero()) 10802 CoerceElts.push_back(llvm::ArrayType::get( 10803 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity())); 10804 10805 CoerceElts.push_back(Field1Ty); 10806 UnpaddedCoerceElts.push_back(Field1Ty); 10807 10808 if (!Field2Ty) { 10809 return ABIArgInfo::getCoerceAndExpand( 10810 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()), 10811 UnpaddedCoerceElts[0]); 10812 } 10813 10814 CharUnits Field2Align = 10815 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty)); 10816 CharUnits Field1End = Field1Off + 10817 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty)); 10818 CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align); 10819 10820 CharUnits Padding = CharUnits::Zero(); 10821 if (Field2Off > Field2OffNoPadNoPack) 10822 Padding = Field2Off - Field2OffNoPadNoPack; 10823 else if (Field2Off != Field2Align && Field2Off > Field1End) 10824 Padding = Field2Off - Field1End; 10825 10826 bool IsPacked = !Field2Off.isMultipleOf(Field2Align); 10827 10828 if (!Padding.isZero()) 10829 CoerceElts.push_back(llvm::ArrayType::get( 10830 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity())); 10831 10832 CoerceElts.push_back(Field2Ty); 10833 UnpaddedCoerceElts.push_back(Field2Ty); 10834 10835 auto CoerceToType = 10836 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked); 10837 auto UnpaddedCoerceToType = 10838 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked); 10839 10840 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType); 10841 } 10842 10843 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 10844 int &ArgGPRsLeft, 10845 int &ArgFPRsLeft) const { 10846 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 10847 Ty = useFirstFieldIfTransparentUnion(Ty); 10848 10849 // Structures with either a non-trivial destructor or a non-trivial 10850 // copy constructor are always passed indirectly. 10851 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 10852 if (ArgGPRsLeft) 10853 ArgGPRsLeft -= 1; 10854 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 10855 CGCXXABI::RAA_DirectInMemory); 10856 } 10857 10858 // Ignore empty structs/unions. 10859 if (isEmptyRecord(getContext(), Ty, true)) 10860 return ABIArgInfo::getIgnore(); 10861 10862 uint64_t Size = getContext().getTypeSize(Ty); 10863 10864 // Pass floating point values via FPRs if possible. 10865 if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() && 10866 FLen >= Size && ArgFPRsLeft) { 10867 ArgFPRsLeft--; 10868 return ABIArgInfo::getDirect(); 10869 } 10870 10871 // Complex types for the hard float ABI must be passed direct rather than 10872 // using CoerceAndExpand. 10873 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) { 10874 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 10875 if (getContext().getTypeSize(EltTy) <= FLen) { 10876 ArgFPRsLeft -= 2; 10877 return ABIArgInfo::getDirect(); 10878 } 10879 } 10880 10881 if (IsFixed && FLen && Ty->isStructureOrClassType()) { 10882 llvm::Type *Field1Ty = nullptr; 10883 llvm::Type *Field2Ty = nullptr; 10884 CharUnits Field1Off = CharUnits::Zero(); 10885 CharUnits Field2Off = CharUnits::Zero(); 10886 int NeededArgGPRs = 0; 10887 int NeededArgFPRs = 0; 10888 bool IsCandidate = 10889 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off, 10890 NeededArgGPRs, NeededArgFPRs); 10891 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft && 10892 NeededArgFPRs <= ArgFPRsLeft) { 10893 ArgGPRsLeft -= NeededArgGPRs; 10894 ArgFPRsLeft -= NeededArgFPRs; 10895 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty, 10896 Field2Off); 10897 } 10898 } 10899 10900 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 10901 bool MustUseStack = false; 10902 // Determine the number of GPRs needed to pass the current argument 10903 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 10904 // register pairs, so may consume 3 registers. 10905 int NeededArgGPRs = 1; 10906 if (!IsFixed && NeededAlign == 2 * XLen) 10907 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 10908 else if (Size > XLen && Size <= 2 * XLen) 10909 NeededArgGPRs = 2; 10910 10911 if (NeededArgGPRs > ArgGPRsLeft) { 10912 MustUseStack = true; 10913 NeededArgGPRs = ArgGPRsLeft; 10914 } 10915 10916 ArgGPRsLeft -= NeededArgGPRs; 10917 10918 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 10919 // Treat an enum type as its underlying type. 10920 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 10921 Ty = EnumTy->getDecl()->getIntegerType(); 10922 10923 // All integral types are promoted to XLen width, unless passed on the 10924 // stack. 10925 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 10926 return extendType(Ty); 10927 } 10928 10929 if (const auto *EIT = Ty->getAs<ExtIntType>()) { 10930 if (EIT->getNumBits() < XLen && !MustUseStack) 10931 return extendType(Ty); 10932 if (EIT->getNumBits() > 128 || 10933 (!getContext().getTargetInfo().hasInt128Type() && 10934 EIT->getNumBits() > 64)) 10935 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10936 } 10937 10938 return ABIArgInfo::getDirect(); 10939 } 10940 10941 // Aggregates which are <= 2*XLen will be passed in registers if possible, 10942 // so coerce to integers. 10943 if (Size <= 2 * XLen) { 10944 unsigned Alignment = getContext().getTypeAlign(Ty); 10945 10946 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 10947 // required, and a 2-element XLen array if only XLen alignment is required. 10948 if (Size <= XLen) { 10949 return ABIArgInfo::getDirect( 10950 llvm::IntegerType::get(getVMContext(), XLen)); 10951 } else if (Alignment == 2 * XLen) { 10952 return ABIArgInfo::getDirect( 10953 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 10954 } else { 10955 return ABIArgInfo::getDirect(llvm::ArrayType::get( 10956 llvm::IntegerType::get(getVMContext(), XLen), 2)); 10957 } 10958 } 10959 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10960 } 10961 10962 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 10963 if (RetTy->isVoidType()) 10964 return ABIArgInfo::getIgnore(); 10965 10966 int ArgGPRsLeft = 2; 10967 int ArgFPRsLeft = FLen ? 2 : 0; 10968 10969 // The rules for return and argument types are the same, so defer to 10970 // classifyArgumentType. 10971 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft, 10972 ArgFPRsLeft); 10973 } 10974 10975 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10976 QualType Ty) const { 10977 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 10978 10979 // Empty records are ignored for parameter passing purposes. 10980 if (isEmptyRecord(getContext(), Ty, true)) { 10981 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 10982 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 10983 return Addr; 10984 } 10985 10986 auto TInfo = getContext().getTypeInfoInChars(Ty); 10987 10988 // Arguments bigger than 2*Xlen bytes are passed indirectly. 10989 bool IsIndirect = TInfo.Width > 2 * SlotSize; 10990 10991 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo, 10992 SlotSize, /*AllowHigherAlign=*/true); 10993 } 10994 10995 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 10996 int TySize = getContext().getTypeSize(Ty); 10997 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 10998 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 10999 return ABIArgInfo::getSignExtend(Ty); 11000 return ABIArgInfo::getExtend(Ty); 11001 } 11002 11003 namespace { 11004 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 11005 public: 11006 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, 11007 unsigned FLen) 11008 : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {} 11009 11010 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 11011 CodeGen::CodeGenModule &CGM) const override { 11012 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 11013 if (!FD) return; 11014 11015 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 11016 if (!Attr) 11017 return; 11018 11019 const char *Kind; 11020 switch (Attr->getInterrupt()) { 11021 case RISCVInterruptAttr::user: Kind = "user"; break; 11022 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 11023 case RISCVInterruptAttr::machine: Kind = "machine"; break; 11024 } 11025 11026 auto *Fn = cast<llvm::Function>(GV); 11027 11028 Fn->addFnAttr("interrupt", Kind); 11029 } 11030 }; 11031 } // namespace 11032 11033 //===----------------------------------------------------------------------===// 11034 // VE ABI Implementation. 11035 // 11036 namespace { 11037 class VEABIInfo : public DefaultABIInfo { 11038 public: 11039 VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 11040 11041 private: 11042 ABIArgInfo classifyReturnType(QualType RetTy) const; 11043 ABIArgInfo classifyArgumentType(QualType RetTy) const; 11044 void computeInfo(CGFunctionInfo &FI) const override; 11045 }; 11046 } // end anonymous namespace 11047 11048 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const { 11049 if (Ty->isAnyComplexType()) 11050 return ABIArgInfo::getDirect(); 11051 uint64_t Size = getContext().getTypeSize(Ty); 11052 if (Size < 64 && Ty->isIntegerType()) 11053 return ABIArgInfo::getExtend(Ty); 11054 return DefaultABIInfo::classifyReturnType(Ty); 11055 } 11056 11057 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const { 11058 if (Ty->isAnyComplexType()) 11059 return ABIArgInfo::getDirect(); 11060 uint64_t Size = getContext().getTypeSize(Ty); 11061 if (Size < 64 && Ty->isIntegerType()) 11062 return ABIArgInfo::getExtend(Ty); 11063 return DefaultABIInfo::classifyArgumentType(Ty); 11064 } 11065 11066 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const { 11067 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 11068 for (auto &Arg : FI.arguments()) 11069 Arg.info = classifyArgumentType(Arg.type); 11070 } 11071 11072 namespace { 11073 class VETargetCodeGenInfo : public TargetCodeGenInfo { 11074 public: 11075 VETargetCodeGenInfo(CodeGenTypes &CGT) 11076 : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {} 11077 // VE ABI requires the arguments of variadic and prototype-less functions 11078 // are passed in both registers and memory. 11079 bool isNoProtoCallVariadic(const CallArgList &args, 11080 const FunctionNoProtoType *fnType) const override { 11081 return true; 11082 } 11083 }; 11084 } // end anonymous namespace 11085 11086 //===----------------------------------------------------------------------===// 11087 // Driver code 11088 //===----------------------------------------------------------------------===// 11089 11090 bool CodeGenModule::supportsCOMDAT() const { 11091 return getTriple().supportsCOMDAT(); 11092 } 11093 11094 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 11095 if (TheTargetCodeGenInfo) 11096 return *TheTargetCodeGenInfo; 11097 11098 // Helper to set the unique_ptr while still keeping the return value. 11099 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 11100 this->TheTargetCodeGenInfo.reset(P); 11101 return *P; 11102 }; 11103 11104 const llvm::Triple &Triple = getTarget().getTriple(); 11105 switch (Triple.getArch()) { 11106 default: 11107 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 11108 11109 case llvm::Triple::le32: 11110 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 11111 case llvm::Triple::m68k: 11112 return SetCGInfo(new M68kTargetCodeGenInfo(Types)); 11113 case llvm::Triple::mips: 11114 case llvm::Triple::mipsel: 11115 if (Triple.getOS() == llvm::Triple::NaCl) 11116 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 11117 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 11118 11119 case llvm::Triple::mips64: 11120 case llvm::Triple::mips64el: 11121 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 11122 11123 case llvm::Triple::avr: 11124 return SetCGInfo(new AVRTargetCodeGenInfo(Types)); 11125 11126 case llvm::Triple::aarch64: 11127 case llvm::Triple::aarch64_32: 11128 case llvm::Triple::aarch64_be: { 11129 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 11130 if (getTarget().getABI() == "darwinpcs") 11131 Kind = AArch64ABIInfo::DarwinPCS; 11132 else if (Triple.isOSWindows()) 11133 return SetCGInfo( 11134 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 11135 11136 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 11137 } 11138 11139 case llvm::Triple::wasm32: 11140 case llvm::Triple::wasm64: { 11141 WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP; 11142 if (getTarget().getABI() == "experimental-mv") 11143 Kind = WebAssemblyABIInfo::ExperimentalMV; 11144 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind)); 11145 } 11146 11147 case llvm::Triple::arm: 11148 case llvm::Triple::armeb: 11149 case llvm::Triple::thumb: 11150 case llvm::Triple::thumbeb: { 11151 if (Triple.getOS() == llvm::Triple::Win32) { 11152 return SetCGInfo( 11153 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 11154 } 11155 11156 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 11157 StringRef ABIStr = getTarget().getABI(); 11158 if (ABIStr == "apcs-gnu") 11159 Kind = ARMABIInfo::APCS; 11160 else if (ABIStr == "aapcs16") 11161 Kind = ARMABIInfo::AAPCS16_VFP; 11162 else if (CodeGenOpts.FloatABI == "hard" || 11163 (CodeGenOpts.FloatABI != "soft" && 11164 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 11165 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 11166 Triple.getEnvironment() == llvm::Triple::EABIHF))) 11167 Kind = ARMABIInfo::AAPCS_VFP; 11168 11169 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 11170 } 11171 11172 case llvm::Triple::ppc: { 11173 if (Triple.isOSAIX()) 11174 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false)); 11175 11176 bool IsSoftFloat = 11177 CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe"); 11178 bool RetSmallStructInRegABI = 11179 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11180 return SetCGInfo( 11181 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 11182 } 11183 case llvm::Triple::ppcle: { 11184 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11185 bool RetSmallStructInRegABI = 11186 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11187 return SetCGInfo( 11188 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 11189 } 11190 case llvm::Triple::ppc64: 11191 if (Triple.isOSAIX()) 11192 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true)); 11193 11194 if (Triple.isOSBinFormatELF()) { 11195 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 11196 if (getTarget().getABI() == "elfv2") 11197 Kind = PPC64_SVR4_ABIInfo::ELFv2; 11198 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11199 11200 return SetCGInfo( 11201 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat)); 11202 } 11203 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 11204 case llvm::Triple::ppc64le: { 11205 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 11206 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 11207 if (getTarget().getABI() == "elfv1") 11208 Kind = PPC64_SVR4_ABIInfo::ELFv1; 11209 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11210 11211 return SetCGInfo( 11212 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat)); 11213 } 11214 11215 case llvm::Triple::nvptx: 11216 case llvm::Triple::nvptx64: 11217 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 11218 11219 case llvm::Triple::msp430: 11220 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 11221 11222 case llvm::Triple::riscv32: 11223 case llvm::Triple::riscv64: { 11224 StringRef ABIStr = getTarget().getABI(); 11225 unsigned XLen = getTarget().getPointerWidth(0); 11226 unsigned ABIFLen = 0; 11227 if (ABIStr.endswith("f")) 11228 ABIFLen = 32; 11229 else if (ABIStr.endswith("d")) 11230 ABIFLen = 64; 11231 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen)); 11232 } 11233 11234 case llvm::Triple::systemz: { 11235 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 11236 bool HasVector = !SoftFloat && getTarget().getABI() == "vector"; 11237 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat)); 11238 } 11239 11240 case llvm::Triple::tce: 11241 case llvm::Triple::tcele: 11242 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 11243 11244 case llvm::Triple::x86: { 11245 bool IsDarwinVectorABI = Triple.isOSDarwin(); 11246 bool RetSmallStructInRegABI = 11247 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11248 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 11249 11250 if (Triple.getOS() == llvm::Triple::Win32) { 11251 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 11252 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11253 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 11254 } else { 11255 return SetCGInfo(new X86_32TargetCodeGenInfo( 11256 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11257 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 11258 CodeGenOpts.FloatABI == "soft")); 11259 } 11260 } 11261 11262 case llvm::Triple::x86_64: { 11263 StringRef ABI = getTarget().getABI(); 11264 X86AVXABILevel AVXLevel = 11265 (ABI == "avx512" 11266 ? X86AVXABILevel::AVX512 11267 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 11268 11269 switch (Triple.getOS()) { 11270 case llvm::Triple::Win32: 11271 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 11272 default: 11273 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 11274 } 11275 } 11276 case llvm::Triple::hexagon: 11277 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 11278 case llvm::Triple::lanai: 11279 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 11280 case llvm::Triple::r600: 11281 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11282 case llvm::Triple::amdgcn: 11283 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11284 case llvm::Triple::sparc: 11285 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 11286 case llvm::Triple::sparcv9: 11287 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 11288 case llvm::Triple::xcore: 11289 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 11290 case llvm::Triple::arc: 11291 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 11292 case llvm::Triple::spir: 11293 case llvm::Triple::spir64: 11294 return SetCGInfo(new SPIRTargetCodeGenInfo(Types)); 11295 case llvm::Triple::ve: 11296 return SetCGInfo(new VETargetCodeGenInfo(Types)); 11297 } 11298 } 11299 11300 /// Create an OpenCL kernel for an enqueued block. 11301 /// 11302 /// The kernel has the same function type as the block invoke function. Its 11303 /// name is the name of the block invoke function postfixed with "_kernel". 11304 /// It simply calls the block invoke function then returns. 11305 llvm::Function * 11306 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 11307 llvm::Function *Invoke, 11308 llvm::Value *BlockLiteral) const { 11309 auto *InvokeFT = Invoke->getFunctionType(); 11310 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11311 for (auto &P : InvokeFT->params()) 11312 ArgTys.push_back(P); 11313 auto &C = CGF.getLLVMContext(); 11314 std::string Name = Invoke->getName().str() + "_kernel"; 11315 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11316 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11317 &CGF.CGM.getModule()); 11318 auto IP = CGF.Builder.saveIP(); 11319 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11320 auto &Builder = CGF.Builder; 11321 Builder.SetInsertPoint(BB); 11322 llvm::SmallVector<llvm::Value *, 2> Args; 11323 for (auto &A : F->args()) 11324 Args.push_back(&A); 11325 llvm::CallInst *call = Builder.CreateCall(Invoke, Args); 11326 call->setCallingConv(Invoke->getCallingConv()); 11327 Builder.CreateRetVoid(); 11328 Builder.restoreIP(IP); 11329 return F; 11330 } 11331 11332 /// Create an OpenCL kernel for an enqueued block. 11333 /// 11334 /// The type of the first argument (the block literal) is the struct type 11335 /// of the block literal instead of a pointer type. The first argument 11336 /// (block literal) is passed directly by value to the kernel. The kernel 11337 /// allocates the same type of struct on stack and stores the block literal 11338 /// to it and passes its pointer to the block invoke function. The kernel 11339 /// has "enqueued-block" function attribute and kernel argument metadata. 11340 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 11341 CodeGenFunction &CGF, llvm::Function *Invoke, 11342 llvm::Value *BlockLiteral) const { 11343 auto &Builder = CGF.Builder; 11344 auto &C = CGF.getLLVMContext(); 11345 11346 auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); 11347 auto *InvokeFT = Invoke->getFunctionType(); 11348 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11349 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 11350 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 11351 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 11352 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 11353 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 11354 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 11355 11356 ArgTys.push_back(BlockTy); 11357 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11358 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 11359 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11360 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11361 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11362 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 11363 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 11364 ArgTys.push_back(InvokeFT->getParamType(I)); 11365 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 11366 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 11367 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11368 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 11369 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11370 ArgNames.push_back( 11371 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 11372 } 11373 std::string Name = Invoke->getName().str() + "_kernel"; 11374 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11375 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11376 &CGF.CGM.getModule()); 11377 F->addFnAttr("enqueued-block"); 11378 auto IP = CGF.Builder.saveIP(); 11379 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11380 Builder.SetInsertPoint(BB); 11381 const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy); 11382 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 11383 BlockPtr->setAlignment(BlockAlign); 11384 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 11385 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 11386 llvm::SmallVector<llvm::Value *, 2> Args; 11387 Args.push_back(Cast); 11388 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 11389 Args.push_back(I); 11390 llvm::CallInst *call = Builder.CreateCall(Invoke, Args); 11391 call->setCallingConv(Invoke->getCallingConv()); 11392 Builder.CreateRetVoid(); 11393 Builder.restoreIP(IP); 11394 11395 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 11396 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 11397 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 11398 F->setMetadata("kernel_arg_base_type", 11399 llvm::MDNode::get(C, ArgBaseTypeNames)); 11400 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 11401 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 11402 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 11403 11404 return F; 11405 } 11406